1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
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. 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 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1983, 1993, 1994\n\
36 The Regents of the University of California. All rights reserved.\n";
37 #endif /* not lint */
38
39 #if 0
40 #ifndef lint
41 static char sccsid[] = "@(#)lpd.c 8.7 (Berkeley) 5/10/95";
42 #endif /* not lint */
43 #endif
44
45 #include "lp.cdefs.h" /* A cross-platform version of <sys/cdefs.h> */
46 /*
47 * lpd -- line printer daemon.
48 *
49 * Listen for a connection and perform the requested operation.
50 * Operations are:
51 * \1printer\n
52 * check the queue for jobs and print any found.
53 * \2printer\n
54 * receive a job from another machine and queue it.
55 * \3printer [users ...] [jobs ...]\n
56 * return the current state of the queue (short form).
57 * \4printer [users ...] [jobs ...]\n
58 * return the current state of the queue (long form).
59 * \5printer person [users ...] [jobs ...]\n
60 * remove jobs from the queue.
61 *
62 * Strategy to maintain protected spooling area:
63 * 1. Spooling area is writable only by daemon and spooling group
64 * 2. lpr runs setuid root and setgrp spooling group; it uses
65 * root to access any file it wants (verifying things before
66 * with an access call) and group id to know how it should
67 * set up ownership of files in the spooling area.
68 * 3. Files in spooling area are owned by root, group spooling
69 * group, with mode 660.
70 * 4. lpd, lpq and lprm run setuid daemon and setgrp spooling group to
71 * access files and printer. Users can't get to anything
72 * w/o help of lpq and lprm programs.
73 */
74
75 #include <sys/param.h>
76 #include <sys/wait.h>
77 #include <sys/types.h>
78 #include <sys/socket.h>
79 #include <sys/un.h>
80 #include <sys/stat.h>
81 #include <sys/file.h>
82 #include <netinet/in.h>
83 #include <arpa/inet.h>
84
85 #include <netdb.h>
86 #include <unistd.h>
87 #include <syslog.h>
88 #include <signal.h>
89 #include <err.h>
90 #include <errno.h>
91 #include <fcntl.h>
92 #include <dirent.h>
93 #include <stdio.h>
94 #include <stdlib.h>
95 #include <string.h>
96 #include <sysexits.h>
97 #include <ctype.h>
98 #include "lp.h"
99 #include "lp.local.h"
100 #include "pathnames.h"
101 #include "extern.h"
102
103 int lflag; /* log requests flag */
104 int sflag; /* no incoming port flag */
105 int Fflag; /* run in foreground flag */
106 int from_remote; /* from remote socket */
107
108 int main(int argc, char **_argv);
109 static void reapchild(int _signo);
110 static void mcleanup(int _signo);
111 static void doit(void);
112 static void startup(void);
113 static void chkhost(struct sockaddr *_f, int _ch_opts);
114 static int ckqueue(struct printer *_pp);
115 static void fhosterr(int _ch_opts, char *_sysmsg, char *_usermsg);
116 static int *socksetup(int _af, int _debuglvl);
117 static void usage(void);
118
119 /* XXX from libc/net/rcmd.c */
120 extern int __ivaliduser_sa(FILE *, struct sockaddr *, socklen_t,
121 const char *, const char *);
122
123 uid_t uid, euid;
124
125 #define LPD_NOPORTCHK 0001 /* skip reserved-port check */
126 #define LPD_LOGCONNERR 0002 /* (sys)log connection errors */
127 #define LPD_ADDFROMLINE 0004 /* just used for fhosterr() */
128
129 int
main(int argc,char ** argv)130 main(int argc, char **argv)
131 {
132 int ch_options, errs, f, funix, *finet, i, lfd, socket_debug;
133 fd_set defreadfds;
134 struct sockaddr_un un, fromunix;
135 struct sockaddr_storage frominet;
136 socklen_t fromlen;
137 sigset_t omask, nmask;
138 struct servent *sp, serv;
139 int inet_flag = 0, inet6_flag = 0;
140
141 euid = geteuid(); /* these shouldn't be different */
142 uid = getuid();
143
144 ch_options = 0;
145 socket_debug = 0;
146 gethostname(local_host, sizeof(local_host));
147
148 progname = "lpd";
149
150 if (euid != 0)
151 errx(EX_NOPERM,"must run as root");
152
153 errs = 0;
154 while ((i = getopt(argc, argv, "cdlpswFW46")) != -1)
155 switch (i) {
156 case 'c':
157 /* log all kinds of connection-errors to syslog */
158 ch_options |= LPD_LOGCONNERR;
159 break;
160 case 'd':
161 socket_debug++;
162 break;
163 case 'l':
164 lflag++;
165 break;
166 case 'p': /* letter initially used for -s */
167 /*
168 * This will probably be removed with 5.0-release.
169 */
170 /* FALLTHROUGH */
171 case 's': /* secure (no inet) */
172 sflag++;
173 break;
174 case 'w': /* netbsd uses -w for maxwait */
175 /*
176 * This will be removed after the release of 4.4, as
177 * it conflicts with -w in netbsd's lpd. For now it
178 * is just a warning, so we won't suddenly break lpd
179 * for anyone who is currently using the option.
180 */
181 syslog(LOG_WARNING,
182 "NOTE: the -w option has been renamed -W");
183 syslog(LOG_WARNING,
184 "NOTE: please change your lpd config to use -W");
185 /* FALLTHROUGH */
186 case 'F':
187 Fflag++;
188 break;
189 case 'W':
190 /* allow connections coming from a non-reserved port */
191 /* (done by some lpr-implementations for MS-Windows) */
192 ch_options |= LPD_NOPORTCHK;
193 break;
194 case '4':
195 family = PF_INET;
196 inet_flag++;
197 break;
198 case '6':
199 #ifdef INET6
200 family = PF_INET6;
201 inet6_flag++;
202 #else
203 errx(EX_USAGE, "lpd compiled sans INET6 (IPv6 support)");
204 #endif
205 break;
206 /*
207 * The following options are not in FreeBSD (yet?), but are
208 * listed here to "reserve" them, because the option-letters
209 * are used by either NetBSD or OpenBSD (as of July 2001).
210 */
211 case 'b': /* set bind-addr */
212 case 'n': /* set max num of children */
213 case 'r': /* allow 'of' for remote ptrs */
214 /* ...[not needed in freebsd] */
215 /* FALLTHROUGH */
216 default:
217 errs++;
218 }
219 if (inet_flag && inet6_flag)
220 family = PF_UNSPEC;
221 argc -= optind;
222 argv += optind;
223 if (errs)
224 usage();
225
226 if (argc == 1) {
227 if ((i = atoi(argv[0])) == 0)
228 usage();
229 if (i < 0 || i > USHRT_MAX)
230 errx(EX_USAGE, "port # %d is invalid", i);
231
232 serv.s_port = htons(i);
233 sp = &serv;
234 argc--;
235 } else {
236 sp = getservbyname("printer", "tcp");
237 if (sp == NULL)
238 errx(EX_OSFILE, "printer/tcp: unknown service");
239 }
240
241 if (argc != 0)
242 usage();
243
244 /*
245 * We run chkprintcap right away to catch any errors and blat them
246 * to stderr while we still have it open, rather than sending them
247 * to syslog and leaving the user wondering why lpd started and
248 * then stopped. There should probably be a command-line flag to
249 * ignore errors from chkprintcap.
250 */
251 {
252 pid_t pid;
253 int status;
254 pid = fork();
255 if (pid < 0) {
256 err(EX_OSERR, "cannot fork");
257 } else if (pid == 0) { /* child */
258 execl(_PATH_CHKPRINTCAP, _PATH_CHKPRINTCAP, (char *)0);
259 err(EX_OSERR, "cannot execute %s", _PATH_CHKPRINTCAP);
260 }
261 if (waitpid(pid, &status, 0) < 0) {
262 err(EX_OSERR, "cannot wait");
263 }
264 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
265 errx(EX_OSFILE, "%d errors in printcap file, exiting",
266 WEXITSTATUS(status));
267 }
268
269 #ifdef DEBUG
270 Fflag++;
271 #endif
272 /*
273 * Set up standard environment by detaching from the parent
274 * if -F not specified
275 */
276 if (Fflag == 0) {
277 daemon(0, 0);
278 }
279
280 openlog("lpd", LOG_PID, LOG_LPR);
281 syslog(LOG_INFO, "lpd startup: logging=%d%s%s", lflag,
282 socket_debug ? " dbg" : "", sflag ? " net-secure" : "");
283 (void) umask(0);
284 /*
285 * NB: This depends on O_NONBLOCK semantics doing the right thing;
286 * i.e., applying only to the O_EXLOCK and not to the rest of the
287 * open/creation. As of 1997-12-02, this is the case for commonly-
288 * used filesystems. There are other places in this code which
289 * make the same assumption.
290 */
291 lfd = open(_PATH_MASTERLOCK, O_WRONLY|O_CREAT|O_EXLOCK|O_NONBLOCK,
292 LOCK_FILE_MODE);
293 if (lfd < 0) {
294 if (errno == EWOULDBLOCK) /* active daemon present */
295 exit(0);
296 syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
297 exit(1);
298 }
299 fcntl(lfd, F_SETFL, 0); /* turn off non-blocking mode */
300 ftruncate(lfd, 0);
301 /*
302 * write process id for others to know
303 */
304 sprintf(line, "%u\n", getpid());
305 f = strlen(line);
306 if (write(lfd, line, f) != f) {
307 syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
308 exit(1);
309 }
310 signal(SIGCHLD, reapchild);
311 /*
312 * Restart all the printers.
313 */
314 startup();
315 (void) unlink(_PATH_SOCKETNAME);
316 funix = socket(AF_UNIX, SOCK_STREAM, 0);
317 if (funix < 0) {
318 syslog(LOG_ERR, "socket: %m");
319 exit(1);
320 }
321
322 sigemptyset(&nmask);
323 sigaddset(&nmask, SIGHUP);
324 sigaddset(&nmask, SIGINT);
325 sigaddset(&nmask, SIGQUIT);
326 sigaddset(&nmask, SIGTERM);
327 sigprocmask(SIG_BLOCK, &nmask, &omask);
328
329 (void) umask(077);
330 signal(SIGHUP, mcleanup);
331 signal(SIGINT, mcleanup);
332 signal(SIGQUIT, mcleanup);
333 signal(SIGTERM, mcleanup);
334 memset(&un, 0, sizeof(un));
335 un.sun_family = AF_UNIX;
336 strcpy(un.sun_path, _PATH_SOCKETNAME);
337 #ifndef SUN_LEN
338 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
339 #endif
340 if (bind(funix, (struct sockaddr *)&un, SUN_LEN(&un)) < 0) {
341 syslog(LOG_ERR, "ubind: %m");
342 exit(1);
343 }
344 (void) umask(0);
345 sigprocmask(SIG_SETMASK, &omask, (sigset_t *)0);
346 FD_ZERO(&defreadfds);
347 FD_SET(funix, &defreadfds);
348 listen(funix, 5);
349 if (sflag == 0) {
350 finet = socksetup(family, socket_debug);
351 } else
352 finet = NULL; /* pretend we couldn't open TCP socket. */
353 if (finet) {
354 for (i = 1; i <= *finet; i++) {
355 FD_SET(finet[i], &defreadfds);
356 listen(finet[i], 5);
357 }
358 }
359 /*
360 * Main loop: accept, do a request, continue.
361 */
362 memset(&frominet, 0, sizeof(frominet));
363 memset(&fromunix, 0, sizeof(fromunix));
364 if (lflag)
365 syslog(LOG_INFO, "lpd startup: ready to accept requests");
366 /*
367 * XXX - should be redone for multi-protocol
368 */
369 for (;;) {
370 int domain, nfds, s;
371 fd_set readfds;
372
373 FD_COPY(&defreadfds, &readfds);
374 nfds = select(20, &readfds, 0, 0, 0);
375 if (nfds <= 0) {
376 if (nfds < 0 && errno != EINTR)
377 syslog(LOG_WARNING, "select: %m");
378 continue;
379 }
380 domain = -1; /* avoid compile-time warning */
381 s = -1; /* avoid compile-time warning */
382 if (FD_ISSET(funix, &readfds)) {
383 domain = AF_UNIX, fromlen = sizeof(fromunix);
384 s = accept(funix,
385 (struct sockaddr *)&fromunix, &fromlen);
386 } else {
387 for (i = 1; i <= *finet; i++)
388 if (FD_ISSET(finet[i], &readfds)) {
389 domain = AF_INET;
390 fromlen = sizeof(frominet);
391 s = accept(finet[i],
392 (struct sockaddr *)&frominet,
393 &fromlen);
394 }
395 }
396 if (s < 0) {
397 if (errno != EINTR)
398 syslog(LOG_WARNING, "accept: %m");
399 continue;
400 }
401 if (fork() == 0) {
402 /*
403 * Note that printjob() also plays around with
404 * signal-handling routines, and may need to be
405 * changed when making changes to signal-handling.
406 */
407 signal(SIGCHLD, SIG_DFL);
408 signal(SIGHUP, SIG_IGN);
409 signal(SIGINT, SIG_IGN);
410 signal(SIGQUIT, SIG_IGN);
411 signal(SIGTERM, SIG_IGN);
412 (void) close(funix);
413 if (sflag == 0 && finet) {
414 for (i = 1; i <= *finet; i++)
415 (void)close(finet[i]);
416 }
417 dup2(s, STDOUT_FILENO);
418 (void) close(s);
419 if (domain == AF_INET) {
420 /* for both AF_INET and AF_INET6 */
421 from_remote = 1;
422 chkhost((struct sockaddr *)&frominet,
423 ch_options);
424 } else
425 from_remote = 0;
426 doit();
427 exit(0);
428 }
429 (void) close(s);
430 }
431 }
432
433 static void
reapchild(int signo __unused)434 reapchild(int signo __unused)
435 {
436 int status;
437
438 while (wait3(&status, WNOHANG, 0) > 0)
439 ;
440 }
441
442 static void
mcleanup(int signo)443 mcleanup(int signo)
444 {
445 /*
446 * XXX syslog(3) is not signal-safe.
447 */
448 if (lflag) {
449 if (signo)
450 syslog(LOG_INFO, "exiting on signal %d", signo);
451 else
452 syslog(LOG_INFO, "exiting");
453 }
454 unlink(_PATH_SOCKETNAME);
455 exit(0);
456 }
457
458 /*
459 * Stuff for handling job specifications
460 */
461 char *user[MAXUSERS]; /* users to process */
462 int users; /* # of users in user array */
463 int requ[MAXREQUESTS]; /* job number of spool entries */
464 int requests; /* # of spool requests */
465 char *person; /* name of person doing lprm */
466
467 /* buffer to hold the client's machine-name */
468 static char frombuf[MAXHOSTNAMELEN];
469 char cbuf[BUFSIZ]; /* command line buffer */
470 const char *cmdnames[] = {
471 "null",
472 "printjob",
473 "recvjob",
474 "displayq short",
475 "displayq long",
476 "rmjob"
477 };
478
479 static void
doit(void)480 doit(void)
481 {
482 char *cp, *printer;
483 int n;
484 int status;
485 struct printer myprinter, *pp = &myprinter;
486
487 init_printer(&myprinter);
488
489 for (;;) {
490 cp = cbuf;
491 do {
492 if (cp >= &cbuf[sizeof(cbuf) - 1])
493 fatal(0, "Command line too long");
494 if ((n = read(STDOUT_FILENO, cp, 1)) != 1) {
495 if (n < 0)
496 fatal(0, "Lost connection");
497 return;
498 }
499 } while (*cp++ != '\n');
500 *--cp = '\0';
501 cp = cbuf;
502 if (lflag) {
503 if (*cp >= '\1' && *cp <= '\5')
504 syslog(LOG_INFO, "%s requests %s %s",
505 from_host, cmdnames[(u_char)*cp], cp+1);
506 else
507 syslog(LOG_INFO, "bad request (%d) from %s",
508 *cp, from_host);
509 }
510 switch (*cp++) {
511 case CMD_CHECK_QUE: /* check the queue, print any jobs there */
512 startprinting(cp);
513 break;
514 case CMD_TAKE_THIS: /* receive files to be queued */
515 if (!from_remote) {
516 syslog(LOG_INFO, "illegal request (%d)", *cp);
517 exit(1);
518 }
519 recvjob(cp);
520 break;
521 case CMD_SHOWQ_SHORT: /* display the queue (short form) */
522 case CMD_SHOWQ_LONG: /* display the queue (long form) */
523 /* XXX - this all needs to be redone. */
524 printer = cp;
525 while (*cp) {
526 if (*cp != ' ') {
527 cp++;
528 continue;
529 }
530 *cp++ = '\0';
531 while (isspace(*cp))
532 cp++;
533 if (*cp == '\0')
534 break;
535 if (isdigit(*cp)) {
536 if (requests >= MAXREQUESTS)
537 fatal(0, "Too many requests");
538 requ[requests++] = atoi(cp);
539 } else {
540 if (users >= MAXUSERS)
541 fatal(0, "Too many users");
542 user[users++] = cp;
543 }
544 }
545 status = getprintcap(printer, pp);
546 if (status < 0)
547 fatal(pp, "%s", pcaperr(status));
548 displayq(pp, cbuf[0] == CMD_SHOWQ_LONG);
549 exit(0);
550 case CMD_RMJOB: /* remove a job from the queue */
551 if (!from_remote) {
552 syslog(LOG_INFO, "illegal request (%d)", *cp);
553 exit(1);
554 }
555 printer = cp;
556 while (*cp && *cp != ' ')
557 cp++;
558 if (!*cp)
559 break;
560 *cp++ = '\0';
561 person = cp;
562 while (*cp) {
563 if (*cp != ' ') {
564 cp++;
565 continue;
566 }
567 *cp++ = '\0';
568 while (isspace(*cp))
569 cp++;
570 if (*cp == '\0')
571 break;
572 if (isdigit(*cp)) {
573 if (requests >= MAXREQUESTS)
574 fatal(0, "Too many requests");
575 requ[requests++] = atoi(cp);
576 } else {
577 if (users >= MAXUSERS)
578 fatal(0, "Too many users");
579 user[users++] = cp;
580 }
581 }
582 rmjob(printer);
583 break;
584 }
585 fatal(0, "Illegal service request");
586 }
587 }
588
589 /*
590 * Make a pass through the printcap database and start printing any
591 * files left from the last time the machine went down.
592 */
593 static void
startup(void)594 startup(void)
595 {
596 int pid, status, more;
597 struct printer myprinter, *pp = &myprinter;
598
599 more = firstprinter(pp, &status);
600 if (status)
601 goto errloop;
602 while (more) {
603 if (ckqueue(pp) <= 0) {
604 goto next;
605 }
606 if (lflag)
607 syslog(LOG_INFO, "lpd startup: work for %s",
608 pp->printer);
609 if ((pid = fork()) < 0) {
610 syslog(LOG_WARNING, "lpd startup: cannot fork for %s",
611 pp->printer);
612 mcleanup(0);
613 }
614 if (pid == 0) {
615 lastprinter();
616 printjob(pp);
617 /* NOTREACHED */
618 }
619 do {
620 next:
621 more = nextprinter(pp, &status);
622 errloop:
623 if (status)
624 syslog(LOG_WARNING,
625 "lpd startup: printcap entry for %s has errors, skipping",
626 pp->printer ? pp->printer : "<noname?>");
627 } while (more && status);
628 }
629 }
630
631 /*
632 * Make sure there's some work to do before forking off a child
633 */
634 static int
ckqueue(struct printer * pp)635 ckqueue(struct printer *pp)
636 {
637 register struct dirent *d;
638 DIR *dirp;
639 char *spooldir;
640
641 spooldir = pp->spool_dir;
642 if ((dirp = opendir(spooldir)) == NULL)
643 return (-1);
644 while ((d = readdir(dirp)) != NULL) {
645 if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
646 continue; /* daemon control files only */
647 closedir(dirp);
648 return (1); /* found something */
649 }
650 closedir(dirp);
651 return (0);
652 }
653
654 #define DUMMY ":nobody::"
655
656 /*
657 * Check to see if the host connecting to this host has access to any
658 * lpd services on this host.
659 */
660 static void
chkhost(struct sockaddr * f,int ch_opts)661 chkhost(struct sockaddr *f, int ch_opts)
662 {
663 struct addrinfo hints, *res, *r;
664 register FILE *hostf;
665 char hostbuf[NI_MAXHOST], ip[NI_MAXHOST];
666 char serv[NI_MAXSERV];
667 char *syserr, *usererr;
668 int error, errsav, fpass, good;
669
670 from_host = ".na.";
671
672 /* Need real hostname for temporary filenames */
673 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
674 NI_NAMEREQD);
675 if (error) {
676 errsav = error;
677 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf),
678 NULL, 0, NI_NUMERICHOST);
679 if (error) {
680 asprintf(&syserr,
681 "can not determine hostname for remote host (%d,%d)",
682 errsav, error);
683 asprintf(&usererr,
684 "Host name for your address is not known");
685 fhosterr(ch_opts, syserr, usererr);
686 /* NOTREACHED */
687 }
688 asprintf(&syserr,
689 "Host name for remote host (%s) not known (%d)",
690 hostbuf, errsav);
691 asprintf(&usererr,
692 "Host name for your address (%s) is not known",
693 hostbuf);
694 fhosterr(ch_opts, syserr, usererr);
695 /* NOTREACHED */
696 }
697
698 strlcpy(frombuf, hostbuf, sizeof(frombuf));
699 from_host = frombuf;
700 ch_opts |= LPD_ADDFROMLINE;
701
702 /* Need address in stringform for comparison (no DNS lookup here) */
703 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
704 NI_NUMERICHOST);
705 if (error) {
706 asprintf(&syserr, "Cannot print IP address (error %d)",
707 error);
708 asprintf(&usererr, "Cannot print IP address for your host");
709 fhosterr(ch_opts, syserr, usererr);
710 /* NOTREACHED */
711 }
712 from_ip = strdup(hostbuf);
713
714 /* Reject numeric addresses */
715 memset(&hints, 0, sizeof(hints));
716 hints.ai_family = family;
717 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
718 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
719 if (getaddrinfo(from_host, NULL, &hints, &res) == 0) {
720 freeaddrinfo(res);
721 /* This syslog message already includes from_host */
722 ch_opts &= ~LPD_ADDFROMLINE;
723 asprintf(&syserr, "reverse lookup results in non-FQDN %s",
724 from_host);
725 /* same message to both syslog and remote user */
726 fhosterr(ch_opts, syserr, syserr);
727 /* NOTREACHED */
728 }
729
730 /* Check for spoof, ala rlogind */
731 memset(&hints, 0, sizeof(hints));
732 hints.ai_family = family;
733 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
734 error = getaddrinfo(from_host, NULL, &hints, &res);
735 if (error) {
736 asprintf(&syserr, "dns lookup for address %s failed: %s",
737 from_ip, gai_strerror(error));
738 asprintf(&usererr, "hostname for your address (%s) unknown: %s",
739 from_ip, gai_strerror(error));
740 fhosterr(ch_opts, syserr, usererr);
741 /* NOTREACHED */
742 }
743 good = 0;
744 for (r = res; good == 0 && r; r = r->ai_next) {
745 error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
746 NULL, 0, NI_NUMERICHOST);
747 if (!error && !strcmp(from_ip, ip))
748 good = 1;
749 }
750 if (res)
751 freeaddrinfo(res);
752 if (good == 0) {
753 asprintf(&syserr, "address for remote host (%s) not matched",
754 from_ip);
755 asprintf(&usererr,
756 "address for your hostname (%s) not matched", from_ip);
757 fhosterr(ch_opts, syserr, usererr);
758 /* NOTREACHED */
759 }
760
761 fpass = 1;
762 hostf = fopen(_PATH_HOSTSEQUIV, "r");
763 again:
764 if (hostf) {
765 if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
766 (void) fclose(hostf);
767 goto foundhost;
768 }
769 (void) fclose(hostf);
770 }
771 if (fpass == 1) {
772 fpass = 2;
773 hostf = fopen(_PATH_HOSTSLPD, "r");
774 goto again;
775 }
776 /* This syslog message already includes from_host */
777 ch_opts &= ~LPD_ADDFROMLINE;
778 asprintf(&syserr, "refused connection from %s, sip=%s", from_host,
779 from_ip);
780 asprintf(&usererr,
781 "Print-services are not available to your host (%s).", from_host);
782 fhosterr(ch_opts, syserr, usererr);
783 /* NOTREACHED */
784
785 foundhost:
786 if (ch_opts & LPD_NOPORTCHK)
787 return; /* skip the reserved-port check */
788
789 error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
790 NI_NUMERICSERV);
791 if (error) {
792 /* same message to both syslog and remote user */
793 asprintf(&syserr, "malformed from-address (%d)", error);
794 fhosterr(ch_opts, syserr, syserr);
795 /* NOTREACHED */
796 }
797
798 if (atoi(serv) >= IPPORT_RESERVED) {
799 /* same message to both syslog and remote user */
800 asprintf(&syserr, "connected from invalid port (%s)", serv);
801 fhosterr(ch_opts, syserr, syserr);
802 /* NOTREACHED */
803 }
804 }
805
806 /*
807 * Handle fatal errors in chkhost. The first message will optionally be
808 * sent to syslog, the second one is sent to the connecting host.
809 *
810 * The idea is that the syslog message is meant for an administrator of a
811 * print server (the host receiving connections), while the usermsg is meant
812 * for a remote user who may or may not be clueful, and may or may not be
813 * doing something nefarious. Some remote users (eg, MS-Windows...) may not
814 * even see whatever message is sent, which is why there's the option to
815 * start 'lpd' with the connection-errors also sent to syslog.
816 *
817 * Given that hostnames can theoretically be fairly long (well, over 250
818 * bytes), it would probably be helpful to have the 'from_host' field at
819 * the end of any error messages which include that info.
820 *
821 * These are Fatal host-connection errors, so this routine does not return.
822 */
823 static void
fhosterr(int ch_opts,char * sysmsg,char * usermsg)824 fhosterr(int ch_opts, char *sysmsg, char *usermsg)
825 {
826
827 /*
828 * If lpd was started up to print connection errors, then write
829 * the syslog message before the user message.
830 * And for many of the syslog messages, it is helpful to first
831 * write the from_host (if it is known) as a separate syslog
832 * message, since the hostname may be so long.
833 */
834 if (ch_opts & LPD_LOGCONNERR) {
835 if (ch_opts & LPD_ADDFROMLINE) {
836 syslog(LOG_WARNING, "for connection from %s:", from_host);
837 }
838 syslog(LOG_WARNING, "%s", sysmsg);
839 }
840
841 /*
842 * Now send the error message to the remote host which is trying
843 * to make the connection.
844 */
845 printf("%s [@%s]: %s\n", progname, local_host, usermsg);
846 fflush(stdout);
847
848 /*
849 * Add a minimal delay before exiting (and disconnecting from the
850 * sending-host). This is just in case that machine responds by
851 * INSTANTLY retrying (and instantly re-failing...). This may also
852 * give the other side more time to read the error message.
853 */
854 sleep(2); /* a paranoid throttling measure */
855 exit(1);
856 }
857
858 /* setup server socket for specified address family */
859 /* if af is PF_UNSPEC more than one socket may be returned */
860 /* the returned list is dynamically allocated, so caller needs to free it */
861 static int *
socksetup(int af,int debuglvl)862 socksetup(int af, int debuglvl)
863 {
864 struct addrinfo hints, *res, *r;
865 int error, maxs, *s, *socks;
866 const int on = 1;
867
868 memset(&hints, 0, sizeof(hints));
869 hints.ai_flags = AI_PASSIVE;
870 hints.ai_family = af;
871 hints.ai_socktype = SOCK_STREAM;
872 error = getaddrinfo(NULL, "printer", &hints, &res);
873 if (error) {
874 syslog(LOG_ERR, "%s", gai_strerror(error));
875 mcleanup(0);
876 }
877
878 /* Count max number of sockets we may open */
879 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
880 ;
881 socks = malloc((maxs + 1) * sizeof(int));
882 if (!socks) {
883 syslog(LOG_ERR, "couldn't allocate memory for sockets");
884 mcleanup(0);
885 }
886
887 *socks = 0; /* num of sockets counter at start of array */
888 s = socks + 1;
889 for (r = res; r; r = r->ai_next) {
890 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
891 if (*s < 0) {
892 syslog(LOG_DEBUG, "socket(): %m");
893 continue;
894 }
895 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))
896 < 0) {
897 syslog(LOG_ERR, "setsockopt(SO_REUSEADDR): %m");
898 close(*s);
899 continue;
900 }
901 if (debuglvl)
902 if (setsockopt(*s, SOL_SOCKET, SO_DEBUG, &debuglvl,
903 sizeof(debuglvl)) < 0) {
904 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
905 close(*s);
906 continue;
907 }
908 if (r->ai_family == AF_INET6) {
909 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
910 &on, sizeof(on)) < 0) {
911 syslog(LOG_ERR,
912 "setsockopt (IPV6_V6ONLY): %m");
913 close(*s);
914 continue;
915 }
916 }
917 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
918 syslog(LOG_DEBUG, "bind(): %m");
919 close(*s);
920 continue;
921 }
922 (*socks)++;
923 s++;
924 }
925
926 if (res)
927 freeaddrinfo(res);
928
929 if (*socks == 0) {
930 syslog(LOG_ERR, "Couldn't bind to any socket");
931 free(socks);
932 mcleanup(0);
933 }
934 return(socks);
935 }
936
937 static void
usage(void)938 usage(void)
939 {
940 #ifdef INET6
941 fprintf(stderr, "usage: lpd [-cdlsFW46] [port#]\n");
942 #else
943 fprintf(stderr, "usage: lpd [-cdlsFW] [port#]\n");
944 #endif
945 exit(EX_USAGE);
946 }
947