1 /*
2 * Port 9100+n daemon
3 * Accepts a connection from port 9100+n and copy stream to
4 * /dev/lpn, where n = 0,1,2.
5 *
6 * GPLv2 license, read COPYING
7 *
8 * Run standalone as: p910nd [0|1|2]
9 *
10 * Run under inetd as:
11 * p910n stream tcp nowait root /usr/sbin/tcpd p910nd [0|1|2]
12 * where p910n is an /etc/services entry for
13 * port 9100, 9101 or 9102 as the case may be.
14 * root can be replaced by any uid with rw permission on /dev/lpn
15 *
16 * Port 9100+n will then be passively opened
17 * n defaults to 0
18 *
19 * Version 0.97
20 * Patches by Stefan Sichler.
21 * Stream to printer is only closed after EOF from network if
22 * it is no more busy, otherwise printer driver may discard data of last
23 * write() at close().
24 *
25 * Version 0.96
26 * Patches by Stefan Sichler.
27 * Fixed bi-directional mode to stay alive until connection is closed.
28 * Fixed timeout value in select() (controlling in/out balancing).
29 * Fixed network-to-printer buffer reporting EOF although there was data
30 * left in the buffer.
31 * Added log-to-stdout option (-d).
32 *
33 * Version 0.95
34 * Patch by Mario Izquierdo
35 * Fix incomplete conversion to manipulate new ip_addr structure
36 * when LIBWRAP is selected
37 *
38 * Version 0.94
39 * Patch by Guenther Niess:
40 * Support IPv6
41 * Patch by Philip Prindeville:
42 * Increase socket buffer size
43 * Use %hu for printing port
44 * Makefile fixes for LIBWRAP
45 *
46 * Version 0.93
47 * Fix open call to include mode, required for O_CREAT
48 *
49 * Version 0.92
50 * Patches by Dave Brown. Use raw I/O syscalls instead of
51 * stdio buffering. Buffer system to handle talkative bidi
52 * devices better on low-powered hosts.
53 *
54 * Version 0.91
55 * Patch by Hans Harder. Close printer device after each use to
56 * avoid crashing when hotpluggable devices going away.
57 * Don't wait 10 seconds after successful open.
58 *
59 * Version 0.9
60 * Patch by Kostas Liakakis to keep retrying every 10 seconds
61 * if EBUSY is returned by open_printer, apparently NetBSD
62 * does this if the printer is not on.
63 * Patch by Albert Bartoszko (al_bin@vp_pl), August 2006
64 * Work with hotpluggable devices
65 * Improve Makefile
66 *
67 * (The last two patches conflict somewhat, Liakakis's patch
68 * retries opening the device every 10 seconds until successful,
69 * whereas Bartoszko's patch exits if the printer device cannot be opened.
70 * The problem is with a hotpluggable device, that device node may
71 * not appear again.
72 *
73 * I have opted for Liakakis's behaviour. Let me know if this can
74 * be improved. Perhaps we need another option that chooses the
75 * behaviour. - Ken)
76 *
77 * Version 0.8
78 * Allow specifying address to bind to
79 *
80 * Version 0.7
81 * Bidirectional data transfer
82 *
83 * Version 0.6
84 * Arne Bernin fixed some cast warnings, corrected the version number
85 * and added a -v option to print the version.
86 *
87 * Version 0.5
88 * -DUSE_LIBWRAP and -lwrap enables hosts_access (tcpwrappers) checking.
89 *
90 * Version 0.4
91 * Ken Yap (greenpossum@users.sourceforge.net), April 2001
92 * Placed under GPL.
93 *
94 * Added -f switch to specify device which overrides /dev/lpn.
95 * But number is still required get distinct ports and locks.
96 *
97 * Added locking so that two invocations of the daemon under inetd
98 * don't try to open the printer at the same time. This can happen
99 * even if there is one host running clients because the previous
100 * client can exit after it has sent all data but the printer has not
101 * finished printing and inetd starts up a new daemon when the next
102 * request comes in too soon.
103 *
104 * Various things could be Linux specific. I don't
105 * think there is much demand for this program outside of PCs,
106 * but if you port it to other distributions or platforms,
107 * I'd be happy to receive your patches.
108 */
109
110 #include <unistd.h>
111 #include <stdlib.h>
112 #include <stdio.h>
113 #include <getopt.h>
114 #include <ctype.h>
115 #include <string.h>
116 #include <fcntl.h>
117 #include <netdb.h>
118 #include <syslog.h>
119 #include <errno.h>
120 #include <stdarg.h>
121 #include <sys/types.h>
122 #include <sys/time.h>
123 #include <sys/resource.h>
124 #include <sys/stat.h>
125 #include <sys/socket.h>
126 #include <netinet/in.h>
127 #include <arpa/inet.h>
128
129 #ifdef USE_LIBWRAP
130 #include "tcpd.h"
131 int allow_severity, deny_severity;
132 extern int hosts_ctl(char *daemon, char *client_name, char *client_addr, char *client_user);
133 #endif
134
135 #define BASEPORT 9100
136 #define PIDFILE "/var/run/p910%cd.pid"
137 #ifdef LOCKFILE_DIR
138 #define LOCKFILE LOCKFILE_DIR "/p910%cd"
139 #else
140 #define LOCKFILE "/var/lock/subsys/p910%cd"
141 #endif
142 #ifndef PRINTERFILE
143 #define PRINTERFILE "/dev/lp%c"
144 #endif
145 #define LOGOPTS LOG_ERR
146
147 #define BUFFER_SIZE 8192
148
149 /* Circular buffer used for each direction. */
150 typedef struct {
151 int detectEof; /* If nonzero, EOF is marked when read returns 0 bytes. */
152 int infd; /* Input file descriptor. */
153 int outfd; /* Output file descriptor. */
154 int startidx; /* Index of the start of valid data. */
155 int endidx; /* Index of the end of valid data. */
156 int bytes; /* The number of bytes currently buffered. */
157 int totalin; /* Total bytes that have been read. */
158 int totalout; /* Total bytes that have been written. */
159 int eof_read; /* Nonzero indicates the input file has reached EOF. */
160 int eof_sent; /* Nonzero indicates the output file has fully received all data. */
161 int err; /* Nonzero indicates an error detected on the output file. */
162 char buffer[BUFFER_SIZE]; /* Buffered data goes here. */
163 } Buffer_t;
164
165 static char *progname;
166 static char version[] = "Version 0.97";
167 static char copyright[] = "Copyright (c) 2008-2014 Ken Yap and others, GPLv2";
168 static int lockfd = -1;
169 static char *device = 0;
170 static int bidir = 0;
171 static char *bindaddr = 0;
172 static int log_to_stdout = 0;
173
174
175 /* Helper function: convert a struct sockaddr address (IPv4 and IPv6) to a string */
get_ip_str(const struct sockaddr * sa,char * s,size_t maxlen)176 char *get_ip_str(const struct sockaddr *sa, char *s, size_t maxlen)
177 {
178 switch(sa->sa_family) {
179 case AF_INET:
180 inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr), s, maxlen);
181 break;
182 case AF_INET6:
183 inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr), s, maxlen);
184 break;
185 default:
186 strncpy(s, "Unknown AF", maxlen);
187 return NULL;
188 }
189 return s;
190 }
191
get_port(const struct sockaddr * sa)192 uint16_t get_port(const struct sockaddr *sa)
193 {
194 uint16_t port;
195 switch(sa->sa_family) {
196 case AF_INET:
197 port = ntohs(((struct sockaddr_in *)sa)->sin_port);
198 break;
199 case AF_INET6:
200 port = ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
201 break;
202 default:
203 return 0;
204 }
205 return port;
206 }
207
usage(void)208 void usage(void)
209 {
210 fprintf(stderr, "%s %s %s\n", progname, version, copyright);
211 fprintf(stderr, "Usage: %s [-f device] [-i bindaddr] [-bvd] [0|1|2]\n", progname);
212 exit(1);
213 }
214
show_version(void)215 void show_version(void)
216 {
217 fprintf(stdout, "%s %s\n", progname, version);
218 }
219
dolog(int level,char * msg,...)220 void dolog(int level, char* msg, ...)
221 {
222 va_list argp;
223 va_start(argp, msg);
224 if (log_to_stdout)
225 vfprintf(stdout, msg, argp);
226 else if (level != LOG_DEBUG)
227 vsyslog(level, msg, argp);
228 va_end(argp);
229 }
230
open_printer(int lpnumber)231 int open_printer(int lpnumber)
232 {
233 int lp;
234 char lpname[sizeof(PRINTERFILE)];
235
236 #ifdef TESTING
237 (void)snprintf(lpname, sizeof(lpname), "/dev/tty");
238 #else
239 (void)snprintf(lpname, sizeof(lpname), PRINTERFILE, lpnumber);
240 #endif
241 if (device == 0)
242 device = lpname;
243 if ((lp = open(device, bidir ? (O_RDWR|O_NONBLOCK) : O_WRONLY)) == -1) {
244 if (errno != EBUSY)
245 dolog(LOGOPTS, "%s: %m\n", device);
246 dolog(LOGOPTS, "%s: %m, will try opening later\n", device);
247 }
248 return (lp);
249 }
250
get_lock(int lpnumber)251 int get_lock(int lpnumber)
252 {
253 char lockname[sizeof(LOCKFILE)];
254 struct flock lplock;
255
256 (void)snprintf(lockname, sizeof(lockname), LOCKFILE, lpnumber);
257 if ((lockfd = open(lockname, O_CREAT | O_RDWR, 0666)) < 0) {
258 dolog(LOGOPTS, "%s: %m\n", lockname);
259 return (0);
260 }
261 memset(&lplock, 0, sizeof(lplock));
262 lplock.l_type = F_WRLCK;
263 lplock.l_pid = getpid();
264 if (fcntl(lockfd, F_SETLKW, &lplock) < 0) {
265 dolog(LOGOPTS, "%s: %m\n", lockname);
266 return (0);
267 }
268 return (1);
269 }
270
free_lock(void)271 void free_lock(void)
272 {
273 if (lockfd >= 0)
274 (void)close(lockfd);
275 }
276
277 /* Initializes the buffer, at the start. */
initBuffer(Buffer_t * b,int infd,int outfd,int detectEof)278 void initBuffer(Buffer_t * b, int infd, int outfd, int detectEof)
279 {
280 b->detectEof = detectEof;
281 b->infd = infd;
282 b->outfd = outfd;
283 b->startidx = 0;
284 b->endidx = 0;
285 b->bytes = 0;
286 b->totalin = 0;
287 b->totalout = 0;
288 b->eof_read = 0;
289 b->eof_sent = 0;
290 b->err = 0;
291 }
292
293 /* Sets the readfds and writefds (used by select) based on current buffer state. */
prepBuffer(Buffer_t * b,fd_set * readfds,fd_set * writefds)294 void prepBuffer(Buffer_t * b, fd_set * readfds, fd_set * writefds)
295 {
296 if (b->outfd>=0 && !b->err && (b->bytes != 0 || b->eof_read)) {
297 FD_SET(b->outfd, writefds);
298 }
299 if (b->infd>=0 && !b->eof_read && b->bytes < sizeof(b->buffer)) {
300 FD_SET(b->infd, readfds);
301 }
302 }
303
304 /* Reads data into a buffer from its input file. */
readBuffer(Buffer_t * b)305 ssize_t readBuffer(Buffer_t * b)
306 {
307 int avail;
308 ssize_t result = 0;
309 /* If err, the data will not be written, so no need to store it. */
310 if (b->bytes == 0 || b->err) {
311 /* The buffer is empty. */
312 b->startidx = b->endidx = 0;
313 avail = sizeof(b->buffer);
314 } else if (b->bytes == sizeof(b->buffer)) {
315 /* The buffer is full. */
316 avail = 0;
317 } else if (b->endidx > b->startidx) {
318 /* The buffer is not wrapped: from endidx to end of buffer is free. */
319 avail = sizeof(b->buffer) - b->endidx;
320 } else {
321 /* The buffer is wrapped: gap between endidx and startidx is free. */
322 avail = b->startidx - b->endidx;
323 }
324 if (avail) {
325 result = read(b->infd, b->buffer + b->endidx, avail);
326 if (result > 0) {
327 /* Some data was read. Update accordingly. */
328 b->endidx += result;
329 b->totalin += result;
330 b->bytes += result;
331 if (b->endidx == sizeof(b->buffer)) {
332 /* Time to wrap the buffer. */
333 b->endidx = 0;
334 }
335 } else if (result < 0) {
336 dolog(LOGOPTS, "read: %m\n");
337 b->err = 1;
338 }
339 else if (b->detectEof) {
340 dolog(LOG_DEBUG, "read: eof\n");
341 b->eof_read = 1;
342 } else
343 result = 0; // in case there is still data in the buffer, ignore the error by now
344 }
345 /* Return the value returned by read(), which is -1 (error), or #bytes read. */
346 return result;
347 }
348
349 /* Writes data from a buffer to the output file or discard if no output file is set. */
writeBuffer(Buffer_t * b)350 ssize_t writeBuffer(Buffer_t * b)
351 {
352 int avail;
353 ssize_t result = 0;
354 if (b->bytes == 0 || b->err) {
355 /* Buffer is empty. */
356 avail = 0;
357 } else if (b->endidx > b->startidx) {
358 /* Buffer is not wrapped. Can write all the data. */
359 avail = b->endidx - b->startidx;
360 } else {
361 /* Buffer is wrapped. Can only write the top (first) part. */
362 avail = sizeof(b->buffer) - b->startidx;
363 }
364 if (avail) {
365 if (b->outfd>=0)
366 result = write(b->outfd, b->buffer + b->startidx, avail);
367 else
368 result = avail;
369 if (result < 0) {
370 /* Mark the output file in an error condition. */
371 dolog(LOGOPTS, "write: %m\n");
372 b->err = 1;
373 } else {
374 /* Zero or more bytes were written. */
375 b->startidx += result;
376 if (b->outfd>=0)
377 b->totalout += result;
378 b->bytes -= result;
379 if (b->startidx == sizeof(b->buffer)) {
380 /* Unwrap the buffer. */
381 b->startidx = 0;
382 }
383 }
384 }
385 else if (b->eof_read)
386 b->eof_sent = 1;
387
388 /* Return the write() result, -1 (error) or #bytes written. */
389 return result;
390 }
391
392 /* Copy network data from file descriptor fd (network) to lp (printer) until EOS */
393 /* If bidir, also copy data from printer (lp) to network (fd). */
copy_stream(int fd,int lp)394 int copy_stream(int fd, int lp)
395 {
396 int result;
397 Buffer_t networkToPrinterBuffer;
398 initBuffer(&networkToPrinterBuffer, fd, lp, 1);
399
400 if (bidir) {
401 struct timeval now;
402 struct timeval then;
403 struct timeval timeout;
404 int timer = 0;
405 Buffer_t printerToNetworkBuffer;
406 initBuffer(&printerToNetworkBuffer, lp, fd, 0);
407 fd_set readfds;
408 fd_set writefds;
409 /* Finish when network sent EOF. */
410 /* Although the printer to network stream may not be finished (does this matter?) */
411 while (!networkToPrinterBuffer.eof_sent && !networkToPrinterBuffer.err) {
412 FD_ZERO(&readfds);
413 FD_ZERO(&writefds);
414 prepBuffer(&networkToPrinterBuffer, &readfds, &writefds);
415 prepBuffer(&printerToNetworkBuffer, &readfds, &writefds);
416
417 int maxfd = lp > fd ? lp : fd;
418 if (timer) {
419 /* Delay after reading from the printer, so the */
420 /* return stream cannot dominate. */
421 /* Don't read from the printer until the timer expires. */
422 gettimeofday(&now, 0);
423 if ((now.tv_sec > then.tv_sec) || (now.tv_sec == then.tv_sec && now.tv_usec > then.tv_usec))
424 timer = 0;
425 else
426 FD_CLR(lp, &readfds);
427 }
428 timeout.tv_sec = 0;
429 timeout.tv_usec = 100000;
430 result = select(maxfd + 1, &readfds, &writefds, 0, &timeout);
431 if (result < 0)
432 return (result);
433 if (FD_ISSET(fd, &readfds)) {
434 /* Read network data. */
435 result = readBuffer(&networkToPrinterBuffer);
436 if (result > 0)
437 dolog(LOG_DEBUG,"read %d bytes from network\n",result);
438 }
439 if (FD_ISSET(lp, &readfds)) {
440 /* Read printer data, but pace it more slowly. */
441 result = readBuffer(&printerToNetworkBuffer);
442 if (result > 0) {
443 dolog(LOG_DEBUG,"read %d bytes from printer\n",result);
444 gettimeofday(&then, 0);
445 // wait 100 msec before reading again.
446 then.tv_usec += 100000;
447 if (then.tv_usec > 1000000) {
448 then.tv_usec -= 1000000;
449 then.tv_sec++;
450 }
451 timer = 1;
452 }
453 }
454 if (FD_ISSET(lp, &writefds)) {
455 /* Write data to printer. */
456 result = writeBuffer(&networkToPrinterBuffer);
457 if (result > 0)
458 dolog(LOG_DEBUG,"wrote %d bytes to printer\n",result);
459 }
460 if (FD_ISSET(fd, &writefds) || printerToNetworkBuffer.outfd == -1) {
461 /* Write data to network. */
462 result = writeBuffer(&printerToNetworkBuffer);
463 /* If socket write error, discard further data from printer */
464 if (result < 0) {
465 printerToNetworkBuffer.outfd = -1;
466 printerToNetworkBuffer.err = 0;
467 result = 0;
468 dolog(LOG_DEBUG,"network write error, discarding further printer data\n",result);
469 }
470 else if (result > 0) {
471 if (printerToNetworkBuffer.outfd == -1)
472 dolog(LOG_DEBUG,"discarded %d bytes from printer\n",result);
473 else
474 dolog(LOG_DEBUG,"wrote %d bytes to network\n",result);
475 }
476 }
477 }
478 dolog(LOG_NOTICE,
479 "Finished job: %d/%d bytes sent to printer, %d/%d bytes sent to network\n",
480 networkToPrinterBuffer.totalout,networkToPrinterBuffer.totalin, printerToNetworkBuffer.totalout, printerToNetworkBuffer.totalin);
481 } else {
482 /* Unidirectional: simply read from network, and write to printer. */
483 while (!networkToPrinterBuffer.eof_sent && !networkToPrinterBuffer.err) {
484 result = readBuffer(&networkToPrinterBuffer);
485 if (result > 0)
486 dolog(LOG_DEBUG,"read %d bytes from network\n",result);
487 result = writeBuffer(&networkToPrinterBuffer);
488 if (result > 0)
489 dolog(LOG_DEBUG,"wrote %d bytes to printer\n",result);
490 }
491 dolog(LOG_NOTICE, "Finished job: %d/%d bytes sent to printer\n", networkToPrinterBuffer.totalout, networkToPrinterBuffer.totalin);
492 }
493 return (networkToPrinterBuffer.err?-1:0);
494 }
495
one_job(int lpnumber)496 void one_job(int lpnumber)
497 {
498 int lp;
499 struct sockaddr_storage client;
500 socklen_t clientlen = sizeof(client);
501
502 if (getpeername(0, (struct sockaddr *)&client, &clientlen) >= 0) {
503 char host[INET6_ADDRSTRLEN];
504 dolog(LOG_NOTICE, "Connection from %s port %hu\n", get_ip_str((struct sockaddr *)&client, host, sizeof(host)), get_port((struct sockaddr *)&client));
505 }
506 if (get_lock(lpnumber) == 0)
507 return;
508 /* Make sure lp device is open... */
509 while ((lp = open_printer(lpnumber)) == -1)
510 sleep(10);
511 if (copy_stream(0, lp) < 0)
512 dolog(LOGOPTS, "copy_stream: %m\n");
513 close(lp);
514 free_lock();
515 }
516
server(int lpnumber)517 void server(int lpnumber)
518 {
519 struct rlimit resourcelimit;
520 #ifdef USE_GETPROTOBYNAME
521 struct protoent *proto;
522 #endif
523 int netfd = -1, fd, lp, one = 1;
524 socklen_t clientlen;
525 struct sockaddr_storage client;
526 struct addrinfo hints, *res, *ressave;
527 char pidfilename[sizeof(PIDFILE)];
528 char service[sizeof(BASEPORT+lpnumber-'0')+1];
529 FILE *f;
530 const int bufsiz = 65536;
531
532 #ifndef TESTING
533 if (!log_to_stdout)
534 {
535 switch (fork()) {
536 case -1:
537 dolog(LOGOPTS, "fork: %m\n");
538 exit(1);
539 case 0: /* child */
540 break;
541 default: /* parent */
542 exit(0);
543 }
544 /* Now in child process */
545 resourcelimit.rlim_max = 0;
546 if (getrlimit(RLIMIT_NOFILE, &resourcelimit) < 0) {
547 dolog(LOGOPTS, "getrlimit: %m\n");
548 exit(1);
549 }
550 for (fd = 0; fd < resourcelimit.rlim_max; ++fd)
551 (void)close(fd);
552 if (setsid() < 0) {
553 dolog(LOGOPTS, "setsid: %m\n");
554 exit(1);
555 }
556 (void)chdir("/");
557 (void)umask(022);
558 fd = open("/dev/null", O_RDWR); /* stdin */
559 (void)dup(fd); /* stdout */
560 (void)dup(fd); /* stderr */
561 (void)snprintf(pidfilename, sizeof(pidfilename), PIDFILE, lpnumber);
562 if ((f = fopen(pidfilename, "w")) == NULL) {
563 dolog(LOGOPTS, "%s: %m\n", pidfilename);
564 exit(1);
565 }
566 (void)fprintf(f, "%d\n", getpid());
567 (void)fclose(f);
568 }
569 if (get_lock(lpnumber) == 0)
570 exit(1);
571 #endif
572 memset(&hints, 0, sizeof(hints));
573 hints.ai_family = PF_UNSPEC;
574 hints.ai_flags = AI_PASSIVE;
575 hints.ai_socktype = SOCK_STREAM;
576 (void)snprintf(service, sizeof(service), "%hu", (BASEPORT + lpnumber - '0'));
577 if (getaddrinfo(bindaddr, service, &hints, &res) != 0) {
578 dolog(LOGOPTS, "getaddr: %m\n");
579 exit(1);
580 }
581 ressave = res;
582 while (res) {
583 #ifdef USE_GETPROTOBYNAME
584 if ((proto = getprotobyname("tcp6")) == NULL) {
585 if ((proto = getprotobyname("tcp")) == NULL) {
586 dolog(LOGOPTS, "Cannot find protocol for TCP!\n");
587 exit(1);
588 }
589 }
590 if ((netfd = socket(res->ai_family, res->ai_socktype, proto->p_proto)) < 0)
591 #else
592 if ((netfd = socket(res->ai_family, res->ai_socktype, IPPROTO_IP)) < 0)
593 #endif
594 {
595 dolog(LOGOPTS, "socket: %m\n");
596 close(netfd);
597 res = res->ai_next;
598 continue;
599 }
600 if (setsockopt(netfd, SOL_SOCKET, SO_RCVBUF, &bufsiz, sizeof(bufsiz)) < 0) {
601 dolog(LOGOPTS, "setsocketopt: SO_RCVBUF: %m\n");
602 /* not fatal if it fails */
603 }
604 if (setsockopt(netfd, SOL_SOCKET, SO_SNDBUF, &bufsiz, sizeof(bufsiz)) < 0) {
605 dolog(LOGOPTS, "setsocketopt: SO_SNDBUF: %m\n");
606 /* not fatal if it fails */
607 }
608 if (setsockopt(netfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0) {
609 dolog(LOGOPTS, "setsocketopt: SO_REUSEADDR: %m\n");
610 close(netfd);
611 res = res->ai_next;
612 continue;
613 }
614 if (bind(netfd, res->ai_addr, res->ai_addrlen) < 0) {
615 dolog(LOGOPTS, "bind: %m\n");
616 close(netfd);
617 res = res->ai_next;
618 continue;
619 }
620 if (listen(netfd, 5) < 0) {
621 dolog(LOGOPTS, "listen: %m\n");
622 close(netfd);
623 res = res->ai_next;
624 continue;
625 }
626 break;
627 }
628 freeaddrinfo(ressave);
629 clientlen = sizeof(client);
630 memset(&client, 0, sizeof(client));
631 while ((fd = accept(netfd, (struct sockaddr *)&client, &clientlen)) >= 0) {
632 char host[INET6_ADDRSTRLEN];
633 #ifdef USE_LIBWRAP
634 if (hosts_ctl("p910nd", STRING_UNKNOWN, get_ip_str((struct sockaddr *)&client, host, sizeof(host)), STRING_UNKNOWN) == 0) {
635 dolog(LOGOPTS,
636 "Connection from %s port %hu rejected\n", get_ip_str((struct sockaddr *)&client, host, sizeof(host)), get_port((struct sockaddr *)&client));
637 close(fd);
638 continue;
639 }
640 #endif
641 dolog(LOG_NOTICE, "Connection from %s port %hu accepted\n", get_ip_str((struct sockaddr *)&client, host, sizeof(host)), get_port((struct sockaddr *)&client));
642 /*write(fd, "Printing", 8); */
643
644 /* Make sure lp device is open... */
645 while ((lp = open_printer(lpnumber)) == -1)
646 sleep(10);
647
648 if (copy_stream(fd, lp) < 0)
649 dolog(LOGOPTS, "copy_stream: %m\n");
650 (void)close(fd);
651 (void)close(lp);
652 }
653 dolog(LOGOPTS, "accept: %m\n");
654 free_lock();
655 exit(1);
656 }
657
is_standalone(void)658 int is_standalone(void)
659 {
660 struct sockaddr_storage bind_addr;
661 socklen_t ba_len;
662
663 /*
664 * Check to see if a socket was passed to us from (x)inetd.
665 *
666 * Use getsockname() to determine if descriptor 0 is indeed a socket
667 * (and thus we are probably a child of (x)inetd) or if it is instead
668 * something else and we are running standalone.
669 */
670 ba_len = sizeof(bind_addr);
671 if (getsockname(0, (struct sockaddr *)&bind_addr, &ba_len) == 0)
672 return (0); /* under (x)inetd */
673 if (errno != ENOTSOCK) /* strange... */
674 dolog(LOGOPTS, "getsockname: %m\n");
675 return (1);
676 }
677
main(int argc,char * argv[])678 int main(int argc, char *argv[])
679 {
680 int c, lpnumber;
681 char *p;
682
683 if (argc <= 0) /* in case not provided in (x)inetd config */
684 progname = "p910nd";
685 else {
686 progname = argv[0];
687 if ((p = strrchr(progname, '/')) != 0)
688 progname = p + 1;
689 }
690 lpnumber = '0';
691 while ((c = getopt(argc, argv, "bdi:f:v")) != EOF) {
692 switch (c) {
693 case 'b':
694 bidir = 1;
695 break;
696 case 'd':
697 log_to_stdout = 1;
698 break;
699 case 'f':
700 device = optarg;
701 break;
702 case 'i':
703 bindaddr = optarg;
704 break;
705 case 'v':
706 show_version();
707 break;
708 default:
709 usage();
710 break;
711 }
712 }
713 argc -= optind;
714 argv += optind;
715 if (argc > 0) {
716 if (isdigit(argv[0][0]))
717 lpnumber = argv[0][0];
718 }
719 /* change the n in argv[0] to match the port so ps will show that */
720 if ((p = strstr(progname, "p910n")) != NULL)
721 p[4] = lpnumber;
722
723 /* We used to pass (LOG_PERROR|LOG_PID|LOG_LPR|LOG_ERR) to syslog, but
724 * syslog ignored the LOG_PID and LOG_PERROR option. I.e. the intention
725 * was to add both options but the effect was to have neither.
726 * I disagree with the intention to add PERROR. --Stef */
727 if (!log_to_stdout)
728 openlog(p, LOG_PID, LOG_LPR);
729
730 if (log_to_stdout || is_standalone())
731 server(lpnumber);
732 else
733 one_job(lpnumber);
734 return (0);
735 }
736