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