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