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