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; 661 662 from_host = ".na."; 663 664 /* Need real hostname for temporary filenames */ 665 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0, 666 NI_NAMEREQD); 667 if (error) { 668 errsav = error; 669 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), 670 NULL, 0, NI_NUMERICHOST); 671 if (error) { 672 asprintf(&syserr, 673 "can not determine hostname for remote host (%d,%d)", 674 errsav, error); 675 asprintf(&usererr, 676 "Host name for your address is not known"); 677 fhosterr(ch_opts, syserr, usererr); 678 /* NOTREACHED */ 679 } 680 asprintf(&syserr, 681 "Host name for remote host (%s) not known (%d)", 682 hostbuf, errsav); 683 asprintf(&usererr, 684 "Host name for your address (%s) is not known", 685 hostbuf); 686 fhosterr(ch_opts, syserr, usererr); 687 /* NOTREACHED */ 688 } 689 690 strlcpy(frombuf, hostbuf, sizeof(frombuf)); 691 from_host = frombuf; 692 ch_opts |= LPD_ADDFROMLINE; 693 694 /* Need address in stringform for comparison (no DNS lookup here) */ 695 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0, 696 NI_NUMERICHOST); 697 if (error) { 698 asprintf(&syserr, "Cannot print IP address (error %d)", 699 error); 700 asprintf(&usererr, "Cannot print IP address for your host"); 701 fhosterr(ch_opts, syserr, usererr); 702 /* NOTREACHED */ 703 } 704 from_ip = strdup(hostbuf); 705 706 /* Reject numeric addresses */ 707 memset(&hints, 0, sizeof(hints)); 708 hints.ai_family = family; 709 hints.ai_socktype = SOCK_DGRAM; /*dummy*/ 710 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST; 711 if (getaddrinfo(from_host, NULL, &hints, &res) == 0) { 712 freeaddrinfo(res); 713 /* This syslog message already includes from_host */ 714 ch_opts &= ~LPD_ADDFROMLINE; 715 asprintf(&syserr, "reverse lookup results in non-FQDN %s", 716 from_host); 717 /* same message to both syslog and remote user */ 718 fhosterr(ch_opts, syserr, syserr); 719 /* NOTREACHED */ 720 } 721 722 /* Check for spoof, ala rlogind */ 723 memset(&hints, 0, sizeof(hints)); 724 hints.ai_family = family; 725 hints.ai_socktype = SOCK_DGRAM; /*dummy*/ 726 error = getaddrinfo(from_host, NULL, &hints, &res); 727 if (error) { 728 asprintf(&syserr, "dns lookup for address %s failed: %s", 729 from_ip, gai_strerror(error)); 730 asprintf(&usererr, "hostname for your address (%s) unknown: %s", 731 from_ip, gai_strerror(error)); 732 fhosterr(ch_opts, syserr, usererr); 733 /* NOTREACHED */ 734 } 735 good = 0; 736 for (r = res; good == 0 && r; r = r->ai_next) { 737 error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip), 738 NULL, 0, NI_NUMERICHOST); 739 if (!error && !strcmp(from_ip, ip)) 740 good = 1; 741 } 742 if (res) 743 freeaddrinfo(res); 744 if (good == 0) { 745 asprintf(&syserr, "address for remote host (%s) not matched", 746 from_ip); 747 asprintf(&usererr, 748 "address for your hostname (%s) not matched", from_ip); 749 fhosterr(ch_opts, syserr, usererr); 750 /* NOTREACHED */ 751 } 752 753 fpass = 1; 754 hostf = fopen(_PATH_HOSTSEQUIV, "r"); 755 again: 756 if (hostf) { 757 if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) { 758 (void) fclose(hostf); 759 goto foundhost; 760 } 761 (void) fclose(hostf); 762 } 763 if (fpass == 1) { 764 fpass = 2; 765 hostf = fopen(_PATH_HOSTSLPD, "r"); 766 goto again; 767 } 768 /* This syslog message already includes from_host */ 769 ch_opts &= ~LPD_ADDFROMLINE; 770 asprintf(&syserr, "refused connection from %s, sip=%s", from_host, 771 from_ip); 772 asprintf(&usererr, 773 "Print-services are not available to your host (%s).", from_host); 774 fhosterr(ch_opts, syserr, usererr); 775 /* NOTREACHED */ 776 777 foundhost: 778 if (ch_opts & LPD_NOPORTCHK) 779 return; /* skip the reserved-port check */ 780 781 error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv), 782 NI_NUMERICSERV); 783 if (error) { 784 /* same message to both syslog and remote user */ 785 asprintf(&syserr, "malformed from-address (%d)", error); 786 fhosterr(ch_opts, syserr, syserr); 787 /* NOTREACHED */ 788 } 789 790 if (atoi(serv) >= IPPORT_RESERVED) { 791 /* same message to both syslog and remote user */ 792 asprintf(&syserr, "connected from invalid port (%s)", serv); 793 fhosterr(ch_opts, syserr, syserr); 794 /* NOTREACHED */ 795 } 796 } 797 798 /* 799 * Handle fatal errors in chkhost. The first message will optionally be 800 * sent to syslog, the second one is sent to the connecting host. 801 * 802 * The idea is that the syslog message is meant for an administrator of a 803 * print server (the host receiving connections), while the usermsg is meant 804 * for a remote user who may or may not be clueful, and may or may not be 805 * doing something nefarious. Some remote users (eg, MS-Windows...) may not 806 * even see whatever message is sent, which is why there's the option to 807 * start 'lpd' with the connection-errors also sent to syslog. 808 * 809 * Given that hostnames can theoretically be fairly long (well, over 250 810 * bytes), it would probably be helpful to have the 'from_host' field at 811 * the end of any error messages which include that info. 812 * 813 * These are Fatal host-connection errors, so this routine does not return. 814 */ 815 static void 816 fhosterr(int ch_opts, char *sysmsg, char *usermsg) 817 { 818 819 /* 820 * If lpd was started up to print connection errors, then write 821 * the syslog message before the user message. 822 * And for many of the syslog messages, it is helpful to first 823 * write the from_host (if it is known) as a separate syslog 824 * message, since the hostname may be so long. 825 */ 826 if (ch_opts & LPD_LOGCONNERR) { 827 if (ch_opts & LPD_ADDFROMLINE) { 828 syslog(LOG_WARNING, "for connection from %s:", from_host); 829 } 830 syslog(LOG_WARNING, "%s", sysmsg); 831 } 832 833 /* 834 * Now send the error message to the remote host which is trying 835 * to make the connection. 836 */ 837 printf("%s [@%s]: %s\n", progname, local_host, usermsg); 838 fflush(stdout); 839 840 /* 841 * Add a minimal delay before exiting (and disconnecting from the 842 * sending-host). This is just in case that machine responds by 843 * INSTANTLY retrying (and instantly re-failing...). This may also 844 * give the other side more time to read the error message. 845 */ 846 sleep(2); /* a paranoid throttling measure */ 847 exit(1); 848 } 849 850 /* setup server socket for specified address family */ 851 /* if af is PF_UNSPEC more than one socket may be returned */ 852 /* the returned list is dynamically allocated, so caller needs to free it */ 853 static int * 854 socksetup(int af, int debuglvl) 855 { 856 struct addrinfo hints, *res, *r; 857 int error, maxs, *s, *socks; 858 const int on = 1; 859 860 memset(&hints, 0, sizeof(hints)); 861 hints.ai_flags = AI_PASSIVE; 862 hints.ai_family = af; 863 hints.ai_socktype = SOCK_STREAM; 864 error = getaddrinfo(NULL, "printer", &hints, &res); 865 if (error) { 866 syslog(LOG_ERR, "%s", gai_strerror(error)); 867 mcleanup(0); 868 } 869 870 /* Count max number of sockets we may open */ 871 for (maxs = 0, r = res; r; r = r->ai_next, maxs++) 872 ; 873 socks = malloc((maxs + 1) * sizeof(int)); 874 if (!socks) { 875 syslog(LOG_ERR, "couldn't allocate memory for sockets"); 876 mcleanup(0); 877 } 878 879 *socks = 0; /* num of sockets counter at start of array */ 880 s = socks + 1; 881 for (r = res; r; r = r->ai_next) { 882 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol); 883 if (*s < 0) { 884 syslog(LOG_DEBUG, "socket(): %m"); 885 continue; 886 } 887 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) 888 < 0) { 889 syslog(LOG_ERR, "setsockopt(SO_REUSEADDR): %m"); 890 close(*s); 891 continue; 892 } 893 if (debuglvl) 894 if (setsockopt(*s, SOL_SOCKET, SO_DEBUG, &debuglvl, 895 sizeof(debuglvl)) < 0) { 896 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m"); 897 close(*s); 898 continue; 899 } 900 if (r->ai_family == AF_INET6) { 901 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY, 902 &on, sizeof(on)) < 0) { 903 syslog(LOG_ERR, 904 "setsockopt (IPV6_V6ONLY): %m"); 905 close(*s); 906 continue; 907 } 908 } 909 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) { 910 syslog(LOG_DEBUG, "bind(): %m"); 911 close(*s); 912 continue; 913 } 914 (*socks)++; 915 s++; 916 } 917 918 if (res) 919 freeaddrinfo(res); 920 921 if (*socks == 0) { 922 syslog(LOG_ERR, "Couldn't bind to any socket"); 923 free(socks); 924 mcleanup(0); 925 } 926 return(socks); 927 } 928 929 static void 930 usage(void) 931 { 932 #ifdef INET6 933 fprintf(stderr, "usage: lpd [-cdlsW46] [port#]\n"); 934 #else 935 fprintf(stderr, "usage: lpd [-cdlsW] [port#]\n"); 936 #endif 937 exit(EX_USAGE); 938 } 939