lpd.c revision 1.21 1 /* $NetBSD: lpd.c,v 1.21 2000/02/24 06:33:48 itojun Exp $ */
2
3 /*
4 * Copyright (c) 1983, 1993, 1994
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. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37 #include <sys/cdefs.h>
38
39 #ifndef lint
40 __COPYRIGHT("@(#) Copyright (c) 1983, 1993, 1994\n\
41 The Regents of the University of California. All rights reserved.\n");
42 #endif /* not lint */
43
44 #ifndef lint
45 #if 0
46 static char sccsid[] = "@(#)lpd.c 8.7 (Berkeley) 5/10/95";
47 #else
48 __RCSID("$NetBSD: lpd.c,v 1.21 2000/02/24 06:33:48 itojun Exp $");
49 #endif
50 #endif /* not lint */
51
52 /*
53 * lpd -- line printer daemon.
54 *
55 * Listen for a connection and perform the requested operation.
56 * Operations are:
57 * \1printer\n
58 * check the queue for jobs and print any found.
59 * \2printer\n
60 * receive a job from another machine and queue it.
61 * \3printer [users ...] [jobs ...]\n
62 * return the current state of the queue (short form).
63 * \4printer [users ...] [jobs ...]\n
64 * return the current state of the queue (long form).
65 * \5printer person [users ...] [jobs ...]\n
66 * remove jobs from the queue.
67 *
68 * Strategy to maintain protected spooling area:
69 * 1. Spooling area is writable only by daemon and spooling group
70 * 2. lpr runs setuid root and setgrp spooling group; it uses
71 * root to access any file it wants (verifying things before
72 * with an access call) and group id to know how it should
73 * set up ownership of files in the spooling area.
74 * 3. Files in spooling area are owned by root, group spooling
75 * group, with mode 660.
76 * 4. lpd, lpq and lprm run setuid daemon and setgrp spooling group to
77 * access files and printer. Users can't get to anything
78 * w/o help of lpq and lprm programs.
79 */
80
81 #include <sys/param.h>
82 #include <sys/wait.h>
83 #include <sys/types.h>
84 #include <sys/socket.h>
85 #include <sys/un.h>
86 #include <sys/stat.h>
87 #include <sys/file.h>
88 #include <netinet/in.h>
89
90 #include <err.h>
91 #include <netdb.h>
92 #include <unistd.h>
93 #include <syslog.h>
94 #include <signal.h>
95 #include <errno.h>
96 #include <fcntl.h>
97 #include <dirent.h>
98 #include <stdio.h>
99 #include <stdlib.h>
100 #include <string.h>
101 #include <ctype.h>
102 #include <arpa/inet.h>
103
104 #include "lp.h"
105 #include "lp.local.h"
106 #include "pathnames.h"
107 #include "extern.h"
108
109 /* XXX from libc/net/rcmd.c */
110 extern int __ivaliduser_sa __P((FILE *, struct sockaddr *, socklen_t,
111 const char *, const char *));
112
113 int lflag; /* log requests flag */
114 int rflag; /* allow of for remote printers */
115 int sflag; /* secure (no inet) flag */
116 int from_remote; /* from remote socket */
117
118 int main __P((int, char **));
119 static void reapchild __P((int));
120 static void mcleanup __P((int));
121 static void doit __P((void));
122 static void startup __P((void));
123 static void chkhost __P((struct sockaddr *));
124 static int ckqueue __P((char *));
125 static void usage __P((void));
126 static int *socksetup __P((int, int));
127
128 uid_t uid, euid;
129 int child_count;
130
131 int
132 main(argc, argv)
133 int argc;
134 char **argv;
135 {
136 int f, funix, *finet, options, fromlen;
137 fd_set defreadfds;
138 struct sockaddr_un un, fromunix;
139 struct sockaddr_storage frominet;
140 int omask, lfd, errs, i;
141 int child_max = 32; /* more then enough to hose the system */
142
143 euid = geteuid(); /* these shouldn't be different */
144 uid = getuid();
145 options = 0;
146 gethostname(host, sizeof(host));
147 host[sizeof(host) - 1] = '\0';
148 name = argv[0];
149
150 errs = 0;
151 while ((i = getopt(argc, argv, "dln:srw:")) != -1)
152 switch (i) {
153 case 'd':
154 options |= SO_DEBUG;
155 break;
156 case 'l':
157 lflag++;
158 break;
159 case 'n':
160 child_max = atoi(optarg);
161 if (child_max < 0 || child_max > 1024)
162 errx(1, "invalid number of children: %s",
163 optarg);
164 break;
165 case 'r':
166 rflag++;
167 break;
168 case 's':
169 sflag++;
170 break;
171 case 'w':
172 wait_time = atoi(optarg);
173 if (wait_time < 0)
174 errx(1, "wait time must be postive: %s",
175 optarg);
176 if (wait_time < 30)
177 warnx("warning: wait time less than 30 seconds");
178 break;
179 default:
180 errs++;
181 }
182 argc -= optind;
183 argv += optind;
184 if (errs || argc != 0)
185 usage();
186
187 #ifndef DEBUG
188 /*
189 * Set up standard environment by detaching from the parent.
190 */
191 daemon(0, 0);
192 #endif
193
194 openlog("lpd", LOG_PID, LOG_LPR);
195 syslog(LOG_INFO, "restarted");
196 (void)umask(0);
197 lfd = open(_PATH_MASTERLOCK, O_WRONLY|O_CREAT, 0644);
198 if (lfd < 0) {
199 syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
200 exit(1);
201 }
202 if (flock(lfd, LOCK_EX|LOCK_NB) < 0) {
203 if (errno == EWOULDBLOCK) /* active deamon present */
204 exit(0);
205 syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
206 exit(1);
207 }
208 ftruncate(lfd, 0);
209 /*
210 * write process id for others to know
211 */
212 (void)snprintf(line, sizeof(line), "%u\n", getpid());
213 f = strlen(line);
214 if (write(lfd, line, f) != f) {
215 syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
216 exit(1);
217 }
218 signal(SIGCHLD, reapchild);
219 /*
220 * Restart all the printers.
221 */
222 startup();
223 (void)unlink(_PATH_SOCKETNAME);
224 funix = socket(AF_LOCAL, SOCK_STREAM, 0);
225 if (funix < 0) {
226 syslog(LOG_ERR, "socket: %m");
227 exit(1);
228 }
229 #define mask(s) (1 << ((s) - 1))
230 omask = sigblock(mask(SIGHUP)|mask(SIGINT)|mask(SIGQUIT)|mask(SIGTERM));
231 signal(SIGHUP, mcleanup);
232 signal(SIGINT, mcleanup);
233 signal(SIGQUIT, mcleanup);
234 signal(SIGTERM, mcleanup);
235 memset(&un, 0, sizeof(un));
236 un.sun_family = AF_LOCAL;
237 strncpy(un.sun_path, _PATH_SOCKETNAME, sizeof(un.sun_path) - 1);
238 #ifndef SUN_LEN
239 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
240 #endif
241 if (bind(funix, (struct sockaddr *)&un, SUN_LEN(&un)) < 0) {
242 syslog(LOG_ERR, "ubind: %m");
243 exit(1);
244 }
245 sigsetmask(omask);
246 FD_ZERO(&defreadfds);
247 FD_SET(funix, &defreadfds);
248 listen(funix, 5);
249 if (!sflag)
250 finet = socksetup(PF_UNSPEC, options);
251 else
252 finet = NULL; /* pretend we couldn't open TCP socket. */
253
254 if (finet) {
255 for (i = 1; i <= *finet; i++) {
256 FD_SET(finet[i], &defreadfds);
257 listen(finet[i], 5);
258 }
259 }
260 /*
261 * Main loop: accept, do a request, continue.
262 */
263 memset(&frominet, 0, sizeof(frominet));
264 memset(&fromunix, 0, sizeof(fromunix));
265 for (;;) {
266 int domain, nfds, s;
267 fd_set readfds;
268 /* "short" so it overflows in about 2 hours */
269 short sleeptime = 10;
270
271 while (child_max < child_count) {
272 syslog(LOG_WARNING,
273 "too many children, sleeping for %d seconds",
274 sleeptime);
275 sleep(sleeptime);
276 sleeptime <<= 1;
277 if (sleeptime < 0) {
278 syslog(LOG_CRIT, "sleeptime overflowed! help!");
279 sleeptime = 10;
280 }
281 }
282
283 FD_COPY(&defreadfds, &readfds);
284 nfds = select(20, &readfds, 0, 0, 0);
285 if (nfds <= 0) {
286 if (nfds < 0 && errno != EINTR)
287 syslog(LOG_WARNING, "select: %m");
288 continue;
289 }
290 if (FD_ISSET(funix, &readfds)) {
291 domain = AF_LOCAL, fromlen = sizeof(fromunix);
292 s = accept(funix,
293 (struct sockaddr *)&fromunix, &fromlen);
294 } else {
295 for (i = 1; i <= *finet; i++)
296 if (FD_ISSET(finet[i], &readfds)) {
297 domain = AF_INET, fromlen = sizeof(frominet);
298 s = accept(finet[i], (struct sockaddr *)&frominet, &fromlen);
299 }
300 }
301 if (s < 0) {
302 if (errno != EINTR)
303 syslog(LOG_WARNING, "accept: %m");
304 continue;
305 }
306
307 switch (fork()) {
308 case 0:
309 signal(SIGCHLD, SIG_IGN);
310 signal(SIGHUP, SIG_IGN);
311 signal(SIGINT, SIG_IGN);
312 signal(SIGQUIT, SIG_IGN);
313 signal(SIGTERM, SIG_IGN);
314 (void)close(funix);
315 if (!sflag && finet)
316 for (i = 1; i <= *finet; i++)
317 (void)close(finet[i]);
318 dup2(s, 1);
319 (void)close(s);
320 if (domain == AF_INET) {
321 /* for both AF_INET and AF_INET6 */
322 from_remote = 1;
323 chkhost((struct sockaddr *)&frominet);
324 } else
325 from_remote = 0;
326 doit();
327 exit(0);
328 case -1:
329 syslog(LOG_WARNING, "fork: %m, sleeping for 10 seconds...");
330 sleep(10);
331 continue;
332 default:
333 child_count++;
334 }
335 (void)close(s);
336 }
337 }
338
339 static void
340 reapchild(signo)
341 int signo;
342 {
343 union wait status;
344
345 while (wait3((int *)&status, WNOHANG, 0) > 0)
346 child_count--;
347 }
348
349 static void
350 mcleanup(signo)
351 int signo;
352 {
353 if (lflag)
354 syslog(LOG_INFO, "exiting");
355 unlink(_PATH_SOCKETNAME);
356 exit(0);
357 }
358
359 /*
360 * Stuff for handling job specifications
361 */
362 char *user[MAXUSERS]; /* users to process */
363 int users; /* # of users in user array */
364 int requ[MAXREQUESTS]; /* job number of spool entries */
365 int requests; /* # of spool requests */
366 char *person; /* name of person doing lprm */
367
368 char fromb[NI_MAXHOST]; /* buffer for client's machine name */
369 char cbuf[BUFSIZ]; /* command line buffer */
370 char *cmdnames[] = {
371 "null",
372 "printjob",
373 "recvjob",
374 "displayq short",
375 "displayq long",
376 "rmjob"
377 };
378
379 static void
380 doit()
381 {
382 char *cp;
383 int n;
384
385 for (;;) {
386 cp = cbuf;
387 do {
388 if (cp >= &cbuf[sizeof(cbuf) - 1])
389 fatal("Command line too long");
390 if ((n = read(1, cp, 1)) != 1) {
391 if (n < 0)
392 fatal("Lost connection");
393 return;
394 }
395 } while (*cp++ != '\n');
396 *--cp = '\0';
397 cp = cbuf;
398 if (lflag) {
399 if (*cp >= '\1' && *cp <= '\5') {
400 syslog(LOG_INFO, "%s requests %s %s",
401 from, cmdnames[(int)*cp], cp+1);
402 setproctitle("serving %s: %s %s", from,
403 cmdnames[(int)*cp], cp+1);
404 }
405 else
406 syslog(LOG_INFO, "bad request (%d) from %s",
407 *cp, from);
408 }
409 switch (*cp++) {
410 case '\1': /* check the queue and print any jobs there */
411 printer = cp;
412 printjob();
413 break;
414 case '\2': /* receive files to be queued */
415 if (!from_remote) {
416 syslog(LOG_INFO, "illegal request (%d)", *cp);
417 exit(1);
418 }
419 printer = cp;
420 recvjob();
421 break;
422 case '\3': /* display the queue (short form) */
423 case '\4': /* display the queue (long form) */
424 printer = cp;
425 while (*cp) {
426 if (*cp != ' ') {
427 cp++;
428 continue;
429 }
430 *cp++ = '\0';
431 while (isspace(*cp))
432 cp++;
433 if (*cp == '\0')
434 break;
435 if (isdigit(*cp)) {
436 if (requests >= MAXREQUESTS)
437 fatal("Too many requests");
438 requ[requests++] = atoi(cp);
439 } else {
440 if (users >= MAXUSERS)
441 fatal("Too many users");
442 user[users++] = cp;
443 }
444 }
445 displayq(cbuf[0] - '\3');
446 exit(0);
447 case '\5': /* remove a job from the queue */
448 if (!from_remote) {
449 syslog(LOG_INFO, "illegal request (%d)", *cp);
450 exit(1);
451 }
452 printer = cp;
453 while (*cp && *cp != ' ')
454 cp++;
455 if (!*cp)
456 break;
457 *cp++ = '\0';
458 person = cp;
459 while (*cp) {
460 if (*cp != ' ') {
461 cp++;
462 continue;
463 }
464 *cp++ = '\0';
465 while (isspace(*cp))
466 cp++;
467 if (*cp == '\0')
468 break;
469 if (isdigit(*cp)) {
470 if (requests >= MAXREQUESTS)
471 fatal("Too many requests");
472 requ[requests++] = atoi(cp);
473 } else {
474 if (users >= MAXUSERS)
475 fatal("Too many users");
476 user[users++] = cp;
477 }
478 }
479 rmjob();
480 break;
481 }
482 fatal("Illegal service request");
483 }
484 }
485
486 /*
487 * Make a pass through the printcap database and start printing any
488 * files left from the last time the machine went down.
489 */
490 static void
491 startup()
492 {
493 char *buf;
494 char *cp;
495
496 /*
497 * Restart the daemons.
498 */
499 while (cgetnext(&buf, printcapdb) > 0) {
500 if (ckqueue(buf) <= 0) {
501 free(buf);
502 continue; /* no work to do for this printer */
503 }
504 for (cp = buf; *cp; cp++)
505 if (*cp == '|' || *cp == ':') {
506 *cp = '\0';
507 break;
508 }
509 if (lflag)
510 syslog(LOG_INFO, "work for %s", buf);
511 switch (fork()) {
512 case -1:
513 syslog(LOG_WARNING, "startup: cannot fork");
514 mcleanup(0);
515 case 0:
516 printer = buf;
517 setproctitle("working on printer %s", printer);
518 cgetclose();
519 printjob();
520 /* NOTREACHED */
521 default:
522 child_count++;
523 free(buf);
524 }
525 }
526 }
527
528 /*
529 * Make sure there's some work to do before forking off a child
530 */
531 static int
532 ckqueue(cap)
533 char *cap;
534 {
535 struct dirent *d;
536 DIR *dirp;
537 char *spooldir;
538
539 if (cgetstr(cap, "sd", &spooldir) == -1)
540 spooldir = _PATH_DEFSPOOL;
541 if ((dirp = opendir(spooldir)) == NULL)
542 return (-1);
543 while ((d = readdir(dirp)) != NULL) {
544 if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
545 continue; /* daemon control files only */
546 closedir(dirp);
547 return (1); /* found something */
548 }
549 closedir(dirp);
550 return (0);
551 }
552
553 #define DUMMY ":nobody::"
554
555 /*
556 * Check to see if the from host has access to the line printer.
557 */
558 static void
559 chkhost(f)
560 struct sockaddr *f;
561 {
562 struct addrinfo hints, *res, *r;
563 FILE *hostf;
564 int first = 1, good = 0;
565 char host[NI_MAXHOST], ip[NI_MAXHOST];
566 char serv[NI_MAXSERV];
567 int error;
568
569 error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
570 NI_NUMERICSERV);
571 if (error || atoi(serv) >= IPPORT_RESERVED)
572 fatal("Malformed from address");
573
574 /* Need real hostname for temporary filenames */
575 error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
576 NI_NAMEREQD);
577 if (error) {
578 error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
579 NI_NUMERICHOST);
580 if (error)
581 fatal("Host name for your address unknown");
582 else
583 fatal("Host name for your address (%s) unknown", host);
584 }
585
586 (void)strncpy(fromb, host, sizeof(fromb) - 1);
587 fromb[sizeof(fromb) - 1] = '\0';
588 from = fromb;
589
590 /* need address in stringform for comparison (no DNS lookup here) */
591 error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
592 NI_NUMERICHOST);
593 if (error)
594 fatal("Cannot print address");
595
596 /* Check for spoof, ala rlogind */
597 memset(&hints, 0, sizeof(hints));
598 hints.ai_family = PF_UNSPEC;
599 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
600 error = getaddrinfo(fromb, NULL, &hints, &res);
601 if (error) {
602 fatal("hostname for your address (%s) unknown: %s", host,
603 gai_strerror(error));
604 }
605 good = 0;
606 for (r = res; good == 0 && r; r = r->ai_next) {
607 error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
608 NULL, 0, NI_NUMERICHOST);
609 if (!error && !strcmp(host, ip))
610 good = 1;
611 }
612 if (res)
613 freeaddrinfo(res);
614 if (good == 0)
615 fatal("address for your hostname (%s) not matched", host);
616 setproctitle("serving %s", from);
617 hostf = fopen(_PATH_HOSTSEQUIV, "r");
618 again:
619 if (hostf) {
620 if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
621 (void)fclose(hostf);
622 return;
623 }
624 (void)fclose(hostf);
625 }
626 if (first == 1) {
627 first = 0;
628 hostf = fopen(_PATH_HOSTSLPD, "r");
629 goto again;
630 }
631 fatal("Your host does not have line printer access");
632 /*NOTREACHED*/
633 }
634
635 static void
636 usage()
637 {
638 extern char *__progname; /* XXX */
639
640 fprintf(stderr, "usage: %s [-d] [-l]\n", __progname);
641 exit(1);
642 }
643
644 /* setup server socket for specified address family */
645 /* if af is PF_UNSPEC more than one socket may be returned */
646 /* the returned list is dynamically allocated, so caller needs to free it */
647 int *
648 socksetup(af, options)
649 int af, options;
650 {
651 struct addrinfo hints, *res, *r;
652 int error, maxs, *s, *socks;
653 const int on = 1;
654
655 memset(&hints, 0, sizeof(hints));
656 hints.ai_flags = AI_PASSIVE;
657 hints.ai_family = af;
658 hints.ai_socktype = SOCK_STREAM;
659 error = getaddrinfo(NULL, "printer", &hints, &res);
660 if (error) {
661 syslog(LOG_ERR, (gai_strerror(error)));
662 mcleanup(0);
663 }
664
665 /* Count max number of sockets we may open */
666 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
667 ;
668 socks = malloc((maxs + 1) * sizeof(int));
669 if (!socks) {
670 syslog(LOG_ERR, "couldn't allocate memory for sockets");
671 mcleanup(0);
672 }
673
674 *socks = 0; /* num of sockets counter at start of array */
675 s = socks + 1;
676 for (r = res; r; r = r->ai_next) {
677 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
678 if (*s < 0) {
679 syslog(LOG_DEBUG, "socket(): %m");
680 continue;
681 }
682 if (options & SO_DEBUG)
683 if (setsockopt(*s, SOL_SOCKET, SO_DEBUG,
684 &on, sizeof(on)) < 0) {
685 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
686 close (*s);
687 continue;
688 }
689 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
690 syslog(LOG_DEBUG, "bind(): %m");
691 close (*s);
692 continue;
693 }
694 *socks = *socks + 1;
695 s++;
696 }
697
698 if (res)
699 freeaddrinfo(res);
700
701 if (*socks == 0) {
702 syslog(LOG_ERR, "Couldn't bind to any socket");
703 free(socks);
704 mcleanup(0);
705 }
706 return(socks);
707 }
708