xref: /dragonfly/usr.sbin/lpr/common_source/common.c (revision cae2835b6b4ebad97f7a0b45157102f433a3c656)
1 /*
2  * Copyright (c) 1983, 1993
3  *        The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * @(#)common.c     8.5 (Berkeley) 4/28/95
35  * $FreeBSD: src/usr.sbin/lpr/common_source/common.c,v 1.12.2.17 2002/07/14 23:58:52 gad Exp $
36  */
37 
38 #include <sys/param.h>
39 #include <sys/stat.h>
40 #include <sys/time.h>
41 #include <sys/types.h>
42 
43 #include <dirent.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 
51 #include "lp.h"
52 #include "lp.local.h"
53 #include "pathnames.h"
54 
55 /*
56  * Routines and data common to all the line printer functions.
57  */
58 char      line[BUFSIZ];
59 const char          *progname;                    /* program name */
60 
61 extern uid_t        uid, euid;
62 
63 static int compar(const void *_p1, const void *_p2);
64 
65 /*
66  * get_line reads a line from the control file cfp, removes tabs, converts
67  *  new-line to null and leaves it in line.
68  * Returns 0 at EOF or the number of characters read.
69  */
70 int
get_line(FILE * cfp)71 get_line(FILE *cfp)
72 {
73           int linel = 0;
74           char *lp = line;
75           int c;
76 
77           while ((c = getc(cfp)) != '\n' && (size_t)(linel+1) < sizeof(line)) {
78                     if (c == EOF)
79                               return(0);
80                     if (c == '\t') {
81                               do {
82                                         *lp++ = ' ';
83                                         linel++;
84                               } while ((linel & 07) != 0 && (size_t)(linel+1) <
85                                   sizeof(line));
86                               continue;
87                     }
88                     *lp++ = c;
89                     linel++;
90           }
91           *lp++ = '\0';
92           return(linel);
93 }
94 
95 /*
96  * Scan the current directory and make a list of daemon files sorted by
97  * creation time.
98  * Return the number of entries and a pointer to the list.
99  */
100 int
getq(const struct printer * pp,struct jobqueue * (* namelist[]))101 getq(const struct printer *pp, struct jobqueue *(*namelist[]))
102 {
103           struct dirent *d;
104           struct jobqueue *q, **queue;
105           size_t arraysz, entrysz, nitems;
106           struct stat stbuf;
107           DIR *dirp;
108           int statres;
109 
110           seteuid(euid);
111           if ((dirp = opendir(pp->spool_dir)) == NULL) {
112                     seteuid(uid);
113                     return (-1);
114           }
115           if (fstat(dirfd(dirp), &stbuf) < 0)
116                     goto errdone;
117           seteuid(uid);
118 
119           /*
120            * Estimate the array size by taking the size of the directory file
121            * and dividing it by a multiple of the minimum size entry.
122            *
123            * However some file systems do report a directory size == 0 (HAMMER
124            * for instance).  Use a sensible minimum size for the array.
125            */
126           arraysz = MAX(20, (stbuf.st_size / 24));
127           queue = (struct jobqueue **)malloc(arraysz * sizeof(struct jobqueue *));
128           if (queue == NULL)
129                     goto errdone;
130 
131           nitems = 0;
132           while ((d = readdir(dirp)) != NULL) {
133                     if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
134                               continue; /* daemon control files only */
135                     seteuid(euid);
136                     statres = stat(d->d_name, &stbuf);
137                     seteuid(uid);
138                     if (statres < 0)
139                               continue; /* Doesn't exist */
140                     entrysz = sizeof(struct jobqueue) - sizeof(q->job_cfname) +
141                         strlen(d->d_name) + 1;
142                     q = (struct jobqueue *)malloc(entrysz);
143                     if (q == NULL)
144                               goto errdone;
145                     q->job_matched = 0;
146                     q->job_processed = 0;
147                     q->job_time = stbuf.st_mtime;
148                     strcpy(q->job_cfname, d->d_name);
149                     /*
150                      * Check to make sure the array has space left and
151                      * realloc the maximum size.
152                      */
153                     if (++nitems > arraysz) {
154                               arraysz *= 2;
155                               queue = (struct jobqueue **)realloc((char *)queue,
156                                   arraysz * sizeof(struct jobqueue *));
157                               if (queue == NULL)
158                                         goto errdone;
159                     }
160                     queue[nitems-1] = q;
161           }
162           closedir(dirp);
163           if (nitems)
164                     qsort(queue, nitems, sizeof(struct jobqueue *), compar);
165           *namelist = queue;
166           return(nitems);
167 
168 errdone:
169           closedir(dirp);
170           seteuid(uid);
171           return (-1);
172 }
173 
174 /*
175  * Compare modification times.
176  */
177 static int
compar(const void * p1,const void * p2)178 compar(const void *p1, const void *p2)
179 {
180           const struct jobqueue *qe1, *qe2;
181 
182           qe1 = *(const struct jobqueue * const *)p1;
183           qe2 = *(const struct jobqueue * const *)p2;
184 
185           if (qe1->job_time < qe2->job_time)
186                     return (-1);
187           if (qe1->job_time > qe2->job_time)
188                     return (1);
189           /*
190            * At this point, the two files have the same last-modification time.
191            * return a result based on filenames, so that 'cfA001some.host' will
192            * come before 'cfA002some.host'.  Since the jobid ('001') will wrap
193            * around when it gets to '999', we also assume that '9xx' jobs are
194            * older than '0xx' jobs.
195           */
196           if ((qe1->job_cfname[3] == '9') && (qe2->job_cfname[3] == '0'))
197                     return (-1);
198           if ((qe1->job_cfname[3] == '0') && (qe2->job_cfname[3] == '9'))
199                     return (1);
200           return (strcmp(qe1->job_cfname, qe2->job_cfname));
201 }
202 
203 /* sleep n milliseconds */
204 void
delay(int millisec)205 delay(int millisec)
206 {
207           struct timeval tdelay;
208 
209           if (millisec <= 0 || millisec > 10000)
210                     fatal(NULL, /* fatal() knows how to deal */
211                         "unreasonable delay period (%d)", millisec);
212           tdelay.tv_sec = millisec / 1000;
213           tdelay.tv_usec = millisec * 1000 % 1000000;
214           select(0, NULL, NULL, NULL, &tdelay);
215 }
216 
217 char *
lock_file_name(const struct printer * pp,char * buf,size_t len)218 lock_file_name(const struct printer *pp, char *buf, size_t len)
219 {
220           static char staticbuf[MAXPATHLEN];
221 
222           if (buf == NULL)
223                     buf = staticbuf;
224           if (len == 0)
225                     len = MAXPATHLEN;
226 
227           if (pp->lock_file[0] == '/')
228                     strlcpy(buf, pp->lock_file, len);
229           else
230                     snprintf(buf, len, "%s/%s", pp->spool_dir, pp->lock_file);
231 
232           return buf;
233 }
234 
235 char *
status_file_name(const struct printer * pp,char * buf,size_t len)236 status_file_name(const struct printer *pp, char *buf, size_t len)
237 {
238           static char staticbuf[MAXPATHLEN];
239 
240           if (buf == NULL)
241                     buf = staticbuf;
242           if (len == 0)
243                     len = MAXPATHLEN;
244 
245           if (pp->status_file[0] == '/')
246                     strlcpy(buf, pp->status_file, len);
247           else
248                     snprintf(buf, len, "%s/%s", pp->spool_dir, pp->status_file);
249 
250           return buf;
251 }
252 
253 /*
254  * Routine to change operational state of a print queue.  The operational
255  * state is indicated by the access bits on the lock file for the queue.
256  * At present, this is only called from various routines in lpc/cmds.c.
257  *
258  *  XXX - Note that this works by changing access-bits on the
259  *        file, and you can only do that if you are the owner of
260  *        the file, or root.  Thus, this won't really work for
261  *        userids in the "LPR_OPER" group, unless lpc is running
262  *        setuid to root (or maybe setuid to daemon).
263  *        Generally lpc is installed setgid to daemon, but does
264  *        not run setuid.
265  */
266 int
set_qstate(int action,const char * lfname)267 set_qstate(int action, const char *lfname)
268 {
269           struct stat stbuf;
270           mode_t chgbits, newbits, oldmask;
271           const char *failmsg, *okmsg;
272           static const char *nomsg = "no state msg";
273           int chres, errsav, fd, res, statres;
274 
275           /*
276            * Find what the current access-bits are.
277            */
278           memset(&stbuf, 0, sizeof(stbuf));
279           seteuid(euid);
280           statres = stat(lfname, &stbuf);
281           errsav = errno;
282           seteuid(uid);
283           if ((statres < 0) && (errsav != ENOENT)) {
284                     printf("\tcannot stat() lock file\n");
285                     return (SQS_STATFAIL);
286                     /* NOTREACHED */
287           }
288 
289           /*
290            * Determine which bit(s) should change for the requested action.
291            */
292           chgbits = stbuf.st_mode;
293           newbits = LOCK_FILE_MODE;
294           okmsg = NULL;
295           failmsg = NULL;
296           if (action & SQS_QCHANGED) {
297                     chgbits |= LFM_RESET_QUE;
298                     newbits |= LFM_RESET_QUE;
299                     /* The okmsg is not actually printed for this case. */
300                     okmsg = nomsg;
301                     failmsg = "set queue-changed";
302           }
303           if (action & SQS_DISABLEQ) {
304                     chgbits |= LFM_QUEUE_DIS;
305                     newbits |= LFM_QUEUE_DIS;
306                     okmsg = "queuing disabled";
307                     failmsg = "disable queuing";
308           }
309           if (action & SQS_STOPP) {
310                     chgbits |= LFM_PRINT_DIS;
311                     newbits |= LFM_PRINT_DIS;
312                     okmsg = "printing disabled";
313                     failmsg = "disable printing";
314                     if (action & SQS_DISABLEQ) {
315                               okmsg = "printer and queuing disabled";
316                               failmsg = "disable queuing and printing";
317                     }
318           }
319           if (action & SQS_ENABLEQ) {
320                     chgbits &= ~LFM_QUEUE_DIS;
321                     newbits &= ~LFM_QUEUE_DIS;
322                     okmsg = "queuing enabled";
323                     failmsg = "enable queuing";
324           }
325           if (action & SQS_STARTP) {
326                     chgbits &= ~LFM_PRINT_DIS;
327                     newbits &= ~LFM_PRINT_DIS;
328                     okmsg = "printing enabled";
329                     failmsg = "enable printing";
330           }
331           if (okmsg == NULL) {
332                     /* This routine was called with an invalid action. */
333                     printf("\t<error in set_qstate!>\n");
334                     return (SQS_PARMERR);
335                     /* NOTREACHED */
336           }
337 
338           res = 0;
339           if (statres >= 0) {
340                     /* The file already exists, so change the access. */
341                     seteuid(euid);
342                     chres = chmod(lfname, chgbits);
343                     errsav = errno;
344                     seteuid(uid);
345                     res = SQS_CHGOK;
346                     if (chres < 0)
347                               res = SQS_CHGFAIL;
348           } else if (newbits == LOCK_FILE_MODE) {
349                     /*
350                      * The file does not exist, but the state requested is
351                      * the same as the default state when no file exists.
352                      * Thus, there is no need to create the file.
353                      */
354                     res = SQS_SKIPCREOK;
355           } else {
356                     /*
357                      * The file did not exist, so create it with the
358                      * appropriate access bits for the requested action.
359                      * Push a new umask around that create, to make sure
360                      * all the read/write bits are set as desired.
361                      */
362                     oldmask = umask(S_IWOTH);
363                     seteuid(euid);
364                     fd = open(lfname, O_WRONLY|O_CREAT, newbits);
365                     errsav = errno;
366                     seteuid(uid);
367                     umask(oldmask);
368                     res = SQS_CREFAIL;
369                     if (fd >= 0) {
370                               res = SQS_CREOK;
371                               close(fd);
372                     }
373           }
374 
375           switch (res) {
376           case SQS_CHGOK:
377           case SQS_CREOK:
378           case SQS_SKIPCREOK:
379                     if (okmsg != nomsg)
380                               printf("\t%s\n", okmsg);
381                     break;
382           case SQS_CREFAIL:
383                     printf("\tcannot create lock file: %s\n",
384                         strerror(errsav));
385                     break;
386           default:
387                     printf("\tcannot %s: %s\n", failmsg, strerror(errsav));
388                     break;
389           }
390 
391           return (res);
392 }
393 
394 /* routine to get a current timestamp, optionally in a standard-fmt string */
395 void
lpd_gettime(struct timespec * tsp,char * strp,size_t strsize)396 lpd_gettime(struct timespec *tsp, char *strp, size_t strsize)
397 {
398           struct timespec local_ts;
399           struct timeval btime;
400           char tempstr[TIMESTR_SIZE];
401 #ifdef STRFTIME_WRONG_z
402           char *destp;
403 #endif
404 
405           if (tsp == NULL)
406                     tsp = &local_ts;
407 
408           /* some platforms have a routine called clock_gettime, but the
409            * routine does nothing but return "not implemented". */
410           memset(tsp, 0, sizeof(struct timespec));
411           if (clock_gettime(CLOCK_REALTIME, tsp)) {
412                     /* nanosec-aware rtn failed, fall back to microsec-aware rtn */
413                     memset(tsp, 0, sizeof(struct timespec));
414                     gettimeofday(&btime, NULL);
415                     tsp->tv_sec = btime.tv_sec;
416                     tsp->tv_nsec = btime.tv_usec * 1000;
417           }
418 
419           /* caller may not need a character-ized version */
420           if ((strp == NULL) || (strsize < 1))
421                     return;
422 
423           strftime(tempstr, TIMESTR_SIZE, LPD_TIMESTAMP_PATTERN,
424                      localtime(&tsp->tv_sec));
425 
426           /*
427            * This check is for implementations of strftime which treat %z
428            * (timezone as [+-]hhmm ) like %Z (timezone as characters), or
429            * completely ignore %z.  This section is not needed on freebsd.
430            * I'm not sure this is completely right, but it should work OK
431            * for EST and EDT...
432            */
433 #ifdef STRFTIME_WRONG_z
434           destp = strrchr(tempstr, ':');
435           if (destp != NULL) {
436                     destp += 3;
437                     if ((*destp != '+') && (*destp != '-')) {
438                               char savday[6];
439                               int tzmin = timezone / 60;
440                               int tzhr = tzmin / 60;
441                               if (daylight)
442                                         tzhr--;
443                               strcpy(savday, destp + strlen(destp) - 4);
444                               snprintf(destp, (destp - tempstr), "%+03d%02d",
445                                   (-1*tzhr), tzmin % 60);
446                               strcat(destp, savday);
447                     }
448           }
449 #endif
450 
451           if (strsize > TIMESTR_SIZE) {
452                     strsize = TIMESTR_SIZE;
453                     strp[TIMESTR_SIZE+1] = '\0';
454           }
455           strlcpy(strp, tempstr, strsize);
456 }
457 
458 /* routines for writing transfer-statistic records */
459 void
trstat_init(struct printer * pp,const char * fname,int filenum)460 trstat_init(struct printer *pp, const char *fname, int filenum)
461 {
462           const char *srcp;
463           char *destp, *endp;
464 
465           /*
466            * Figure out the job id of this file.  The filename should be
467            * 'cf', 'df', or maybe 'tf', followed by a letter (or sometimes
468            * two), followed by the jobnum, followed by a hostname.
469            * The jobnum is usually 3 digits, but might be as many as 5.
470            * Note that some care has to be taken parsing this, as the
471            * filename could be coming from a remote-host, and thus might
472            * not look anything like what is expected...
473            */
474           memset(pp->jobnum, 0, sizeof(pp->jobnum));
475           pp->jobnum[0] = '0';
476           srcp = strchr(fname, '/');
477           if (srcp == NULL)
478                     srcp = fname;
479           destp = &(pp->jobnum[0]);
480           endp = destp + 5;
481           while (*srcp != '\0' && (*srcp < '0' || *srcp > '9'))
482                     srcp++;
483           while (*srcp >= '0' && *srcp <= '9' && destp < endp)
484                     *(destp++) = *(srcp++);
485 
486           /* get the starting time in both numeric and string formats, and
487            * save those away along with the file-number */
488           pp->jobdfnum = filenum;
489           lpd_gettime(&pp->tr_start, pp->tr_timestr, (size_t)TIMESTR_SIZE);
490 
491           return;
492 }
493 
494 void
trstat_write(struct printer * pp,tr_sendrecv sendrecv,size_t bytecnt,const char * userid,const char * otherhost,const char * orighost)495 trstat_write(struct printer *pp, tr_sendrecv sendrecv, size_t bytecnt,
496     const char *userid, const char *otherhost, const char *orighost)
497 {
498 #define STATLINE_SIZE 1024
499           double trtime;
500           size_t remspace;
501           int statfile;
502           char thishost[MAXHOSTNAMELEN], statline[STATLINE_SIZE];
503           char *eostat;
504           const char *lprhost, *recvdev, *recvhost, *rectype;
505           const char *sendhost, *statfname;
506 #define UPD_EOSTAT(xStr) do {         \
507           eostat = strchr(xStr, '\0');  \
508           remspace = eostat - xStr;     \
509 } while(0)
510 
511           lpd_gettime(&pp->tr_done, NULL, (size_t)0);
512           trtime = DIFFTIME_TS(pp->tr_done, pp->tr_start);
513 
514           gethostname(thishost, sizeof(thishost));
515           lprhost = sendhost = recvhost = recvdev = NULL;
516           switch (sendrecv) {
517               case TR_SENDING:
518                     rectype = "send";
519                     statfname = pp->stat_send;
520                     sendhost = thishost;
521                     recvhost = otherhost;
522                     break;
523               case TR_RECVING:
524                     rectype = "recv";
525                     statfname = pp->stat_recv;
526                     sendhost = otherhost;
527                     recvhost = thishost;
528                     break;
529               case TR_PRINTING:
530                     /*
531                      * This case is for copying to a device (presumably local,
532                      * though filters using things like 'net/CAP' can confuse
533                      * this assumption...).
534                      */
535                     rectype = "prnt";
536                     statfname = pp->stat_send;
537                     sendhost = thishost;
538                     recvdev = _PATH_DEFDEVLP;
539                     if (pp->lp) recvdev = pp->lp;
540                     break;
541               default:
542                     /* internal error...  should we syslog/printf an error? */
543                     return;
544           }
545           if (statfname == NULL)
546                     return;
547 
548           /*
549            * the original-host and userid are found out by reading thru the
550            * cf (control-file) for the job.  Unfortunately, on incoming jobs
551            * the df's (data-files) are sent before the matching cf, so the
552            * orighost & userid are generally not-available for incoming jobs.
553            *
554            * (it would be nice to create a work-around for that..)
555            */
556           if (orighost && (*orighost != '\0'))
557                     lprhost = orighost;
558           else
559                     lprhost = ".na.";
560           if (*userid == '\0')
561                     userid = NULL;
562 
563           /*
564            * Format of statline.
565            * Some of the keywords listed here are not implemented here, but
566            * they are listed to reserve the meaning for a given keyword.
567            * Fields are separated by a blank.  The fields in statline are:
568            *   <tstamp>      - time the transfer started
569            *   <ptrqueue>    - name of the printer queue (the short-name...)
570            *   <hname>       - hostname the file originally came from (the
571            *                       'lpr host'), if known, or  "_na_" if not known.
572            *   <xxx>         - id of job from that host (generally three digits)
573            *   <n>           - file count (# of file within job)
574            *   <rectype>     - 4-byte field indicating the type of transfer
575            *                       statistics record.  "send" means it's from the
576            *                       host sending a datafile, "recv" means it's from
577            *                       a host as it receives a datafile.
578            *   user=<userid> - user who sent the job (if known)
579            *   secs=<n>      - seconds it took to transfer the file
580            *   bytes=<n>     - number of bytes transfered (ie, "bytecount")
581            *   bps=<n.n>e<n> - Bytes/sec (if the transfer was "big enough"
582            *                       for this to be useful)
583            * ! top=<str>     - type of printer (if the type is defined in
584            *                       printcap, and if this statline is for sending
585            *                       a file to that ptr)
586            * ! qls=<n>       - queue-length at start of send/print-ing a job
587            * ! qle=<n>       - queue-length at end of send/print-ing a job
588            *   sip=<addr>    - IP address of sending host, only included when
589            *                       receiving a job.
590            *   shost=<hname> - sending host (if that does != the original host)
591            *   rhost=<hname> - hostname receiving the file (ie, "destination")
592            *   rdev=<dev>    - device receiving the file, when the file is being
593            *                       send to a device instead of a remote host.
594            *
595            * Note: A single print job may be transferred multiple times.  The
596            * original 'lpr' occurs on one host, and that original host might
597            * send to some interim host (or print server).  That interim host
598            * might turn around and send the job to yet another host (most likely
599            * the real printer).  The 'shost=' parameter is only included if the
600            * sending host for this particular transfer is NOT the same as the
601            * host which did the original 'lpr'.
602            *
603            * Many values have 'something=' tags before them, because they are
604            * in some sense "optional", or their order may vary.  "Optional" may
605            * mean in the sense that different SITES might choose to have other
606            * fields in the record, or that some fields are only included under
607            * some circumstances.  Programs processing these records should not
608            * assume the order or existence of any of these keyword fields.
609            */
610           snprintf(statline, STATLINE_SIZE, "%s %s %s %s %03ld %s",
611               pp->tr_timestr, pp->printer, lprhost, pp->jobnum,
612               pp->jobdfnum, rectype);
613           UPD_EOSTAT(statline);
614 
615           if (userid != NULL) {
616                     snprintf(eostat, remspace, " user=%s", userid);
617                     UPD_EOSTAT(statline);
618           }
619           snprintf(eostat, remspace, " secs=%#.2f bytes=%lu", trtime,
620               (unsigned long)bytecnt);
621           UPD_EOSTAT(statline);
622 
623           /*
624            * The bps field duplicates info from bytes and secs, so do
625            * not bother to include it for very small files.
626            */
627           if ((bytecnt > 25000) && (trtime > 1.1)) {
628                     snprintf(eostat, remspace, " bps=%#.2e",
629                         ((double)bytecnt/trtime));
630                     UPD_EOSTAT(statline);
631           }
632 
633           if (sendrecv == TR_RECVING) {
634                     if (remspace > 5+strlen(from_ip) ) {
635                               snprintf(eostat, remspace, " sip=%s", from_ip);
636                               UPD_EOSTAT(statline);
637                     }
638           }
639           if (0 != strcmp(lprhost, sendhost)) {
640                     if (remspace > 7+strlen(sendhost) ) {
641                               snprintf(eostat, remspace, " shost=%s", sendhost);
642                               UPD_EOSTAT(statline);
643                     }
644           }
645           if (recvhost) {
646                     if (remspace > 7+strlen(recvhost) ) {
647                               snprintf(eostat, remspace, " rhost=%s", recvhost);
648                               UPD_EOSTAT(statline);
649                     }
650           }
651           if (recvdev) {
652                     if (remspace > 6+strlen(recvdev) ) {
653                               snprintf(eostat, remspace, " rdev=%s", recvdev);
654                               UPD_EOSTAT(statline);
655                     }
656           }
657           if (remspace > 1) {
658                     strcpy(eostat, "\n");
659           } else {
660                     /* probably should back up to just before the final " x=".. */
661                     strcpy(statline+STATLINE_SIZE-2, "\n");
662           }
663           statfile = open(statfname, O_WRONLY|O_APPEND, 0664);
664           if (statfile < 0) {
665                     /* statfile was given, but we can't open it.  should we
666                      * syslog/printf this as an error? */
667                     return;
668           }
669           write(statfile, statline, strlen(statline));
670           close(statfile);
671 
672           return;
673 #undef UPD_EOSTAT
674 }
675 
676 #include <stdarg.h>
677 
678 void
fatal(const struct printer * pp,const char * msg,...)679 fatal(const struct printer *pp, const char *msg, ...)
680 {
681           va_list ap;
682           va_start(ap, msg);
683           /* this error message is being sent to the 'from_host' */
684           if (from_host != local_host)
685                     printf("%s: ", local_host);
686           printf("%s: ", progname);
687           if (pp && pp->printer)
688                     printf("%s: ", pp->printer);
689           vprintf(msg, ap);
690           va_end(ap);
691           putchar('\n');
692           exit(1);
693 }
694 
695 /*
696  * Close all file descriptors from START on up.
697  * This is a horrific kluge, since getdtablesize() might return
698  * ``infinity'', in which case we will be spending a long time
699  * closing ``files'' which were never open.  Perhaps it would
700  * be better to close the first N fds, for some small value of N.
701  */
702 void
closeallfds(int start)703 closeallfds(int start)
704 {
705           int stop = getdtablesize();
706           for (; start < stop; start++)
707                     close(start);
708 }
709 
710