1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1983, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33 #include "lp.cdefs.h" /* A cross-platform version of <sys/cdefs.h> */
34 /*
35 * Receive printer jobs from the network, queue them and
36 * start the printer daemon.
37 */
38 #include <sys/param.h>
39 #include <sys/mount.h>
40 #include <sys/stat.h>
41
42 #include <dirent.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <stdint.h>
46 #include <signal.h>
47 #include <stdarg.h>
48 #include <stdckdint.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <syslog.h>
53 #include <unistd.h>
54 #include "lp.h"
55 #include "lp.local.h"
56 #include "ctlinfo.h"
57 #include "extern.h"
58 #include "pathnames.h"
59
60 #define digit(ch) ((ch) >= '0' && (ch) <= '9')
61
62 /*
63 * The buffer size to use when reading/writing spool files.
64 */
65 #define SPL_BUFSIZ BUFSIZ
66
67 static char dfname[NAME_MAX]; /* data files */
68 static size_t minfree; /* keep at least minfree blocks available */
69 static char tfname[NAME_MAX]; /* tmp copy of cf before linking */
70
71 static void ack(struct printer *_pp);
72 static void nak(struct printer *_pp);
73 static int chksize(size_t _size);
74 static void frecverr(const char *_msg, ...) __printf0like(1, 2);
75 static int noresponse(void);
76 static void rcleanup(int _signo);
77 static void read_minfree(void);
78 static int readfile(struct printer *_pp, char *_file, size_t _size);
79 static int readjob(struct printer *_pp);
80
81
82 void
recvjob(const char * printer)83 recvjob(const char *printer)
84 {
85 struct stat stb;
86 int status;
87 struct printer myprinter, *pp = &myprinter;
88
89 /*
90 * Perform lookup for printer name or abbreviation
91 */
92 init_printer(pp);
93 status = getprintcap(printer, pp);
94 switch (status) {
95 case PCAPERR_OSERR:
96 frecverr("cannot open printer description file");
97 break;
98 case PCAPERR_NOTFOUND:
99 frecverr("unknown printer %s", printer);
100 break;
101 case PCAPERR_TCLOOP:
102 fatal(pp, "potential reference loop detected in printcap file");
103 default:
104 break;
105 }
106
107 (void) close(STDERR_FILENO); /* set up log file */
108 if (open(pp->log_file, O_WRONLY|O_APPEND, 0664) < 0) {
109 syslog(LOG_ERR, "%s: %m", pp->log_file);
110 (void) open(_PATH_DEVNULL, O_WRONLY);
111 }
112
113 if (chdir(pp->spool_dir) < 0)
114 frecverr("%s: chdir(%s): %s", pp->printer, pp->spool_dir,
115 strerror(errno));
116 if (stat(pp->lock_file, &stb) == 0) {
117 if (stb.st_mode & 010) {
118 /* queue is disabled */
119 putchar('\1'); /* return error code */
120 exit(1);
121 }
122 } else if (stat(pp->spool_dir, &stb) < 0)
123 frecverr("%s: stat(%s): %s", pp->printer, pp->spool_dir,
124 strerror(errno));
125 read_minfree();
126 signal(SIGTERM, rcleanup);
127 signal(SIGPIPE, rcleanup);
128
129 if (readjob(pp))
130 printjob(pp);
131 }
132
133 /*
134 * Read printer jobs sent by lpd and copy them to the spooling directory.
135 * Return the number of jobs successfully transferred.
136 *
137 * In theory, the protocol allows any number of jobs to be transferred in
138 * a single connection, with control and data files in any order. This
139 * would be very difficult to police effectively, so enforce a single job
140 * per connection. The control file can be sent at any time (first, last,
141 * or between data files). All files must bear the same job number, and
142 * the data files must be sent sequentially. If any of these requirements
143 * is violated, we close the connection and delete everything.
144 *
145 * Note that RFC 1179 strongly implies only one data file per job; I
146 * assume this is a mistake in the RFC since it is supposed to describe
147 * this code, which predates it, but was written by a third party.
148 */
149 static int
readjob(struct printer * pp)150 readjob(struct printer *pp)
151 {
152 ssize_t rlen;
153 size_t len, size;
154 int cfcnt, dfcnt, curd0, curd2, curn, n;
155 char *cp, *clastp, *errmsg, *sep;
156 char givenid[32], givenhost[MAXHOSTNAMELEN];
157
158 tfname[0] = dfname[0] = '\0';
159 ack(pp);
160 cfcnt = 0;
161 dfcnt = 0;
162 curd0 = 'd';
163 curd2 = 'A';
164 curn = -1;
165 for (;;) {
166 /*
167 * Read a command to tell us what to do
168 */
169 cp = line;
170 clastp = line + sizeof(line) - 1;
171 do {
172 rlen = read(STDOUT_FILENO, cp, 1);
173 if (rlen != 1) {
174 if (rlen < 0) {
175 frecverr("%s: lost connection",
176 pp->printer);
177 /*NOTREACHED*/
178 }
179 return (cfcnt);
180 }
181 } while (*cp++ != '\n' && cp <= clastp);
182 if (cp > clastp) {
183 frecverr("%s: readjob overflow", pp->printer);
184 /*NOTREACHED*/
185 }
186 *--cp = '\0';
187 cp = line;
188 switch (*cp++) {
189 case '\1': /* abort print job */
190 rcleanup(0);
191 continue;
192
193 case '\2': /* read control file */
194 if (tfname[0] != '\0') {
195 /* multiple control files */
196 break;
197 }
198 for (size = 0; digit(*cp); cp++) {
199 if (ckd_mul(&size, size, 10) ||
200 ckd_add(&size, size, *cp - '0'))
201 break;
202 }
203 if (*cp++ != ' ')
204 break;
205 /*
206 * The next six bytes must be "cfA" followed by a
207 * three-digit job number. The rest of the line
208 * is the client host name, but we substitute the
209 * host name we've already authenticated.
210 */
211 if (cp[0] != 'c' || cp[1] != 'f' || cp[2] != 'A' ||
212 !digit(cp[3]) || !digit(cp[4]) || !digit(cp[5]))
213 break;
214 n = (cp[3] - '0') * 100 + (cp[4] - '0') * 10 +
215 cp[5] - '0';
216 if (curn == -1)
217 curn = n;
218 else if (curn != n)
219 break;
220 len = snprintf(tfname, sizeof(tfname), "%.6s%s", cp,
221 from_host);
222 if (len >= sizeof(tfname))
223 break;
224 tfname[0] = 't';
225 if (!chksize(size)) {
226 nak(pp);
227 continue;
228 }
229 if (!readfile(pp, tfname, size)) {
230 rcleanup(0);
231 continue;
232 }
233 errmsg = ctl_renametf(pp->printer, tfname);
234 tfname[0] = '\0';
235 if (errmsg != NULL) {
236 frecverr("%s: %s", pp->printer, errmsg);
237 /*NOTREACHED*/
238 }
239 cfcnt++;
240 continue;
241
242 case '\3': /* read data file */
243 if (curd0 > 'z') {
244 /* too many data files */
245 break;
246 }
247 *givenid = '\0';
248 *givenhost = '\0';
249 for (size = 0; digit(*cp); cp++) {
250 if (ckd_mul(&size, size, 10) ||
251 ckd_add(&size, size, *cp - '0'))
252 break;
253 }
254 if (*cp++ != ' ')
255 break;
256 /*
257 * The next six bytes must be curd0, 'f', curd2
258 * followed by a three-digit job number, where
259 * curd2 cycles through [A-Za-z] while curd0
260 * starts at 'd' and increments when curd2 rolls
261 * around. The rest of the line is the client
262 * host name, but we substitute the host name
263 * we've already authenticated.
264 */
265 if (cp[0] != curd0 || cp[1] != 'f' || cp[2] != curd2 ||
266 !digit(cp[3]) || !digit(cp[4]) || !digit(cp[5]))
267 break;
268 n = (cp[3] - '0') * 100 + (cp[4] - '0') * 10 +
269 cp[5] - '0';
270 if (curn == -1)
271 curn = n;
272 else if (curn != n)
273 break;
274 len = snprintf(dfname, sizeof(dfname), "%.6s%s", cp,
275 from_host);
276 if (len >= sizeof(dfname))
277 break;
278 if (!chksize(size)) {
279 nak(pp);
280 continue;
281 }
282 switch (curd2++) {
283 case 'Z':
284 curd2 = 'a';
285 break;
286 case 'z':
287 curd0++;
288 curd2 = 'A';
289 break;
290 }
291 dfcnt++;
292 trstat_init(pp, dfname, dfcnt);
293 if (!readfile(pp, dfname, size)) {
294 rcleanup(0);
295 continue;
296 }
297 trstat_write(pp, TR_RECVING, size, givenid,
298 from_host, givenhost);
299 continue;
300 }
301 frecverr("protocol screwup: %s", line);
302 /*NOTREACHED*/
303 }
304 }
305
306 /*
307 * Read files send by lpd and copy them to the spooling directory.
308 */
309 static int
readfile(struct printer * pp,char * file,size_t size)310 readfile(struct printer *pp, char *file, size_t size)
311 {
312 char buf[SPL_BUFSIZ];
313 ssize_t rlen, wlen;
314 int err, f0, fd, j;
315
316 fd = open(file, O_CREAT|O_EXCL|O_WRONLY, FILMOD);
317 if (fd < 0) {
318 /*
319 * We need to pass the file name to frecverr() so it can
320 * log an error, but frecverr() will then call rcleanup()
321 * which will delete the file if we don't zero out the
322 * first character.
323 */
324 f0 = file[0];
325 file[0] = '\0';
326 frecverr("%s: readfile: error on open(%c%s): %s",
327 pp->printer, f0, file + 1, strerror(errno));
328 /*NOTREACHED*/
329 }
330 ack(pp);
331 while (size > 0) {
332 rlen = read(STDOUT_FILENO, buf, MIN(SPL_BUFSIZ, size));
333 if (rlen < 0 && errno == EINTR)
334 continue;
335 if (rlen <= 0) {
336 frecverr("%s: lost connection", pp->printer);
337 /*NOTREACHED*/
338 }
339 size -= rlen;
340 while (rlen > 0) {
341 wlen = write(fd, buf, rlen);
342 if (wlen < 0 && errno == EINTR)
343 continue;
344 if (wlen <= 0) {
345 frecverr("%s: write error on write(%s)",
346 pp->printer, file);
347 /*NOTREACHED*/
348 }
349 rlen -= wlen;
350 }
351 }
352 if (close(fd) != 0) {
353 frecverr("%s: write error on close(%s)", pp->printer, file);
354 /*NOTREACHED*/
355 }
356 if (noresponse()) { /* file sent had bad data in it */
357 (void) unlink(file);
358 return (0);
359 }
360 ack(pp);
361 return (1);
362 }
363
364 static int
noresponse(void)365 noresponse(void)
366 {
367 char resp;
368
369 if (read(STDOUT_FILENO, &resp, 1) != 1) {
370 frecverr("lost connection in noresponse()");
371 /*NOTREACHED*/
372 }
373 if (resp == '\0')
374 return (0);
375 return (1);
376 }
377
378 /*
379 * Check to see if there is enough space on the disk for size bytes.
380 * 1 == OK, 0 == Not OK.
381 */
382 static int
chksize(size_t size)383 chksize(size_t size)
384 {
385 struct statfs sfb;
386 size_t avail;
387
388 if (statfs(".", &sfb) < 0) {
389 syslog(LOG_ERR, "%s: %m", "statfs(\".\")");
390 return (1);
391 }
392 /* more free space than we can count; possible on 32-bit */
393 if (ckd_mul(&avail, sfb.f_bavail, (sfb.f_bsize / 512)))
394 return (1);
395 /* already at or below minfree */
396 if (avail <= minfree)
397 return (0);
398 /* not enough space */
399 if (avail - minfree <= size / 512)
400 return (0);
401 return (1);
402 }
403
404 static void
read_minfree(void)405 read_minfree(void)
406 {
407 FILE *fp;
408
409 minfree = 0;
410 /* read from disk */
411 if ((fp = fopen("minfree", "r")) != NULL) {
412 if (fscanf(fp, "%zu", &minfree) != 1)
413 minfree = 0;
414 fclose(fp);
415 }
416 /* scale kB to 512-byte blocks */
417 if (ckd_mul(&minfree, minfree, 2))
418 minfree = SIZE_MAX;
419 }
420
421 /*
422 * Remove all the files associated with the current job being transferred.
423 */
424 static void
rcleanup(int signo __unused)425 rcleanup(int signo __unused)
426 {
427 if (tfname[0] && strchr(tfname, '/') == NULL)
428 (void) unlink(tfname);
429 if (dfname[0] && strchr(dfname, '/') == NULL) {
430 do {
431 do
432 (void) unlink(dfname);
433 while (dfname[2]-- != 'A');
434 dfname[2] = 'z';
435 } while (dfname[0]-- != 'd');
436 }
437 dfname[0] = '\0';
438 }
439
440 static void
frecverr(const char * msg,...)441 frecverr(const char *msg, ...)
442 {
443 va_list ap;
444 va_start(ap, msg);
445 syslog(LOG_ERR, "Error receiving job from %s:", from_host);
446 vsyslog(LOG_ERR, msg, ap);
447 va_end(ap);
448 /*
449 * rcleanup is not called until AFTER logging the error message,
450 * because rcleanup will zap some variables which may have been
451 * supplied as parameters for that msg...
452 */
453 rcleanup(0);
454 /*
455 * Add a minimal delay before returning the final error code to
456 * the sending host. This just in case that machine responds
457 * this error by INSTANTLY retrying (and instantly re-failing...).
458 * It would be stupid of the sending host to do that, but if there
459 * was a broken implementation which did it, the result might be
460 * obscure performance problems and a flood of syslog messages on
461 * the receiving host.
462 */
463 sleep(2); /* a paranoid throttling measure */
464 putchar('\1'); /* return error code */
465 exit(1);
466 }
467
468 static void
ack(struct printer * pp)469 ack(struct printer *pp)
470 {
471 if (write(STDOUT_FILENO, "\0", 1) != 1)
472 frecverr("%s: write error on ack", pp->printer);
473 }
474
475 static void
nak(struct printer * pp)476 nak(struct printer *pp)
477 {
478 if (write(STDOUT_FILENO, "\2", 1) != 1)
479 frecverr("%s: write error on nak", pp->printer);
480 }
481