]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/lpr/common_source/common.c
Fix a few more minor compile-time warnings, mainly by using size_t where
[FreeBSD/FreeBSD.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
39 #ifndef lint
40 /*
41 static char sccsid[] = "@(#)common.c    8.5 (Berkeley) 4/28/95";
42 */
43 static const char rcsid[] =
44   "$FreeBSD$";
45 #endif /* not lint */
46
47 #include <sys/param.h>
48 #include <sys/stat.h>
49 #include <sys/time.h>
50 #include <sys/types.h>
51
52 #include <dirent.h>
53 #include <fcntl.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58
59 #include "lp.h"
60 #include "lp.local.h"
61 #include "pathnames.h"
62
63 /*
64  * Routines and data common to all the line printer functions.
65  */
66 char    line[BUFSIZ];
67 const char      *progname;              /* program name */
68
69 extern uid_t    uid, euid;
70
71 static int compar(const void *_p1, const void *_p2);
72
73 /*
74  * Getline reads a line from the control file cfp, removes tabs, converts
75  *  new-line to null and leaves it in line.
76  * Returns 0 at EOF or the number of characters read.
77  */
78 int
79 getline(FILE *cfp)
80 {
81         register int linel = 0;
82         register char *lp = line;
83         register int c;
84
85         while ((c = getc(cfp)) != '\n' && (size_t)(linel+1) < sizeof(line)) {
86                 if (c == EOF)
87                         return(0);
88                 if (c == '\t') {
89                         do {
90                                 *lp++ = ' ';
91                                 linel++;
92                         } while ((linel & 07) != 0 && (size_t)(linel+1) <
93                             sizeof(line));
94                         continue;
95                 }
96                 *lp++ = c;
97                 linel++;
98         }
99         *lp++ = '\0';
100         return(linel);
101 }
102
103 /*
104  * Scan the current directory and make a list of daemon files sorted by
105  * creation time.
106  * Return the number of entries and a pointer to the list.
107  */
108 int
109 getq(const struct printer *pp, struct jobqueue *(*namelist[]))
110 {
111         register struct dirent *d;
112         register struct jobqueue *q, **queue;
113         size_t arraysz, nitems;
114         struct stat stbuf;
115         DIR *dirp;
116         int statres;
117
118         seteuid(euid);
119         if ((dirp = opendir(pp->spool_dir)) == NULL) {
120                 seteuid(uid);
121                 return (-1);
122         }
123         if (fstat(dirp->dd_fd, &stbuf) < 0)
124                 goto errdone;
125         seteuid(uid);
126
127         /*
128          * Estimate the array size by taking the size of the directory file
129          * and dividing it by a multiple of the minimum size entry. 
130          */
131         arraysz = (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                 q = (struct jobqueue *)malloc(sizeof(time_t) + strlen(d->d_name)
146                     + 1);
147                 if (q == NULL)
148                         goto errdone;
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 **)p1;
185         qe2 = *(const struct jobqueue **)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 /* routine to get a current timestamp, optionally in a standard-fmt string */
256 void
257 lpd_gettime(struct timespec *tsp, char *strp, size_t strsize)
258 {
259         struct timespec local_ts;
260         struct timeval btime;
261         char tempstr[TIMESTR_SIZE];
262 #ifdef STRFTIME_WRONG_z
263         char *destp;
264 #endif
265
266         if (tsp == NULL)
267                 tsp = &local_ts;
268
269         /* some platforms have a routine called clock_gettime, but the
270          * routine does nothing but return "not implemented". */
271         memset(tsp, 0, sizeof(struct timespec));
272         if (clock_gettime(CLOCK_REALTIME, tsp)) {
273                 /* nanosec-aware rtn failed, fall back to microsec-aware rtn */
274                 memset(tsp, 0, sizeof(struct timespec));
275                 gettimeofday(&btime, NULL);
276                 tsp->tv_sec = btime.tv_sec;
277                 tsp->tv_nsec = btime.tv_usec * 1000;
278         }
279
280         /* caller may not need a character-ized version */
281         if ((strp == NULL) || (strsize < 1))
282                 return;
283
284         strftime(tempstr, TIMESTR_SIZE, LPD_TIMESTAMP_PATTERN,
285                  localtime(&tsp->tv_sec));
286
287         /*
288          * This check is for implementations of strftime which treat %z
289          * (timezone as [+-]hhmm ) like %Z (timezone as characters), or
290          * completely ignore %z.  This section is not needed on freebsd.
291          * I'm not sure this is completely right, but it should work OK
292          * for EST and EDT...
293          */
294 #ifdef STRFTIME_WRONG_z
295         destp = strrchr(tempstr, ':');
296         if (destp != NULL) {
297                 destp += 3;
298                 if ((*destp != '+') && (*destp != '-')) {
299                         char savday[6];
300                         int tzmin = timezone / 60;
301                         int tzhr = tzmin / 60;
302                         if (daylight)
303                                 tzhr--;
304                         strcpy(savday, destp + strlen(destp) - 4);
305                         snprintf(destp, (destp - tempstr), "%+03d%02d",
306                             (-1*tzhr), tzmin % 60);
307                         strcat(destp, savday);
308                 }
309         }
310 #endif
311
312         if (strsize > TIMESTR_SIZE) {
313                 strsize = TIMESTR_SIZE;
314                 strp[TIMESTR_SIZE+1] = '\0';
315         }
316         strlcpy(strp, tempstr, strsize);
317 }
318
319 /* routines for writing transfer-statistic records */
320 void
321 trstat_init(struct printer *pp, const char *fname, int filenum)
322 {
323         register const char *srcp;
324         register char *destp, *endp;
325
326         /*
327          * Figure out the job id of this file.  The filename should be
328          * 'cf', 'df', or maybe 'tf', followed by a letter (or sometimes
329          * two), followed by the jobnum, followed by a hostname.
330          * The jobnum is usually 3 digits, but might be as many as 5.
331          * Note that some care has to be taken parsing this, as the
332          * filename could be coming from a remote-host, and thus might
333          * not look anything like what is expected...
334          */
335         memset(pp->jobnum, 0, sizeof(pp->jobnum));
336         pp->jobnum[0] = '0';
337         srcp = strchr(fname, '/');
338         if (srcp == NULL)
339                 srcp = fname;
340         destp = &(pp->jobnum[0]);
341         endp = destp + 5;
342         while (*srcp != '\0' && (*srcp < '0' || *srcp > '9'))
343                 srcp++;
344         while (*srcp >= '0' && *srcp <= '9' && destp < endp)
345                 *(destp++) = *(srcp++);
346
347         /* get the starting time in both numeric and string formats, and
348          * save those away along with the file-number */
349         pp->jobdfnum = filenum;
350         lpd_gettime(&pp->tr_start, pp->tr_timestr, (size_t)TIMESTR_SIZE);
351
352         return;
353 }
354
355 void
356 trstat_write(struct printer *pp, tr_sendrecv sendrecv, size_t bytecnt,
357     const char *userid, const char *otherhost, const char *orighost)
358 {
359 #define STATLINE_SIZE 1024
360         double trtime;
361         size_t remspace;
362         int statfile;
363         char thishost[MAXHOSTNAMELEN], statline[STATLINE_SIZE];
364         char *eostat;
365         const char *lprhost, *recvdev, *recvhost, *rectype;
366         const char *sendhost, *statfname;
367 #define UPD_EOSTAT(xStr) do {         \
368         eostat = strchr(xStr, '\0');  \
369         remspace = eostat - xStr;     \
370 } while(0)
371
372         lpd_gettime(&pp->tr_done, NULL, (size_t)0);
373         trtime = DIFFTIME_TS(pp->tr_done, pp->tr_start);
374
375         gethostname(thishost, sizeof(thishost));
376         lprhost = sendhost = recvhost = recvdev = NULL;
377         switch (sendrecv) {
378             case TR_SENDING:
379                 rectype = "send";
380                 statfname = pp->stat_send;
381                 sendhost = thishost;
382                 recvhost = otherhost;
383                 break;
384             case TR_RECVING:
385                 rectype = "recv";
386                 statfname = pp->stat_recv;
387                 sendhost = otherhost;
388                 recvhost = thishost;
389                 break;
390             case TR_PRINTING:
391                 /*
392                  * This case is for copying to a device (presumably local,
393                  * though filters using things like 'net/CAP' can confuse
394                  * this assumption...).
395                  */
396                 rectype = "prnt";
397                 statfname = pp->stat_send;
398                 sendhost = thishost;
399                 recvdev = _PATH_DEFDEVLP;
400                 if (pp->lp) recvdev = pp->lp;
401                 break;
402             default:
403                 /* internal error...  should we syslog/printf an error? */
404                 return;
405         }
406         if (statfname == NULL)
407                 return;
408
409         /*
410          * the original-host and userid are found out by reading thru the
411          * cf (control-file) for the job.  Unfortunately, on incoming jobs
412          * the df's (data-files) are sent before the matching cf, so the
413          * orighost & userid are generally not-available for incoming jobs.
414          *
415          * (it would be nice to create a work-around for that..)
416          */
417         if (orighost && (*orighost != '\0'))
418                 lprhost = orighost;
419         else
420                 lprhost = ".na.";
421         if (*userid == '\0')
422                 userid = NULL;
423
424         /*
425          * Format of statline.
426          * Some of the keywords listed here are not implemented here, but
427          * they are listed to reserve the meaning for a given keyword.
428          * Fields are separated by a blank.  The fields in statline are:
429          *   <tstamp>      - time the transfer started
430          *   <ptrqueue>    - name of the printer queue (the short-name...)
431          *   <hname>       - hostname the file originally came from (the
432          *                   'lpr host'), if known, or  "_na_" if not known.
433          *   <xxx>         - id of job from that host (generally three digits)
434          *   <n>           - file count (# of file within job)
435          *   <rectype>     - 4-byte field indicating the type of transfer
436          *                   statistics record.  "send" means it's from the
437          *                   host sending a datafile, "recv" means it's from
438          *                   a host as it receives a datafile.
439          *   user=<userid> - user who sent the job (if known)
440          *   secs=<n>      - seconds it took to transfer the file
441          *   bytes=<n>     - number of bytes transfered (ie, "bytecount")
442          *   bps=<n.n>e<n> - Bytes/sec (if the transfer was "big enough"
443          *                   for this to be useful) 
444          * ! top=<str>     - type of printer (if the type is defined in
445          *                   printcap, and if this statline is for sending
446          *                   a file to that ptr)
447          * ! qls=<n>       - queue-length at start of send/print-ing a job
448          * ! qle=<n>       - queue-length at end of send/print-ing a job
449          *   sip=<addr>    - IP address of sending host, only included when
450          *                   receiving a job.
451          *   shost=<hname> - sending host (if that does != the original host)
452          *   rhost=<hname> - hostname receiving the file (ie, "destination")
453          *   rdev=<dev>    - device receiving the file, when the file is being
454          *                   send to a device instead of a remote host.
455          *
456          * Note: A single print job may be transferred multiple times.  The
457          * original 'lpr' occurs on one host, and that original host might
458          * send to some interim host (or print server).  That interim host
459          * might turn around and send the job to yet another host (most likely
460          * the real printer).  The 'shost=' parameter is only included if the
461          * sending host for this particular transfer is NOT the same as the
462          * host which did the original 'lpr'.
463          *
464          * Many values have 'something=' tags before them, because they are
465          * in some sense "optional", or their order may vary.  "Optional" may
466          * mean in the sense that different SITES might choose to have other
467          * fields in the record, or that some fields are only included under
468          * some circumstances.  Programs processing these records should not
469          * assume the order or existence of any of these keyword fields.
470          */
471         snprintf(statline, STATLINE_SIZE, "%s %s %s %s %03ld %s",
472             pp->tr_timestr, pp->printer, lprhost, pp->jobnum,
473             pp->jobdfnum, rectype);
474         UPD_EOSTAT(statline);
475
476         if (userid != NULL) {
477                 snprintf(eostat, remspace, " user=%s", userid);
478                 UPD_EOSTAT(statline);
479         }
480         snprintf(eostat, remspace, " secs=%#.2f bytes=%lu", trtime,
481             (unsigned long)bytecnt);
482         UPD_EOSTAT(statline);
483
484         /*
485          * The bps field duplicates info from bytes and secs, so do
486          * not bother to include it for very small files.
487          */
488         if ((bytecnt > 25000) && (trtime > 1.1)) {
489                 snprintf(eostat, remspace, " bps=%#.2e",
490                     ((double)bytecnt/trtime));
491                 UPD_EOSTAT(statline);
492         }
493
494         if (sendrecv == TR_RECVING) {
495                 if (remspace > 5+strlen(from_ip) ) {
496                         snprintf(eostat, remspace, " sip=%s", from_ip);
497                         UPD_EOSTAT(statline);
498                 }
499         }
500         if (0 != strcmp(lprhost, sendhost)) {
501                 if (remspace > 7+strlen(sendhost) ) {
502                         snprintf(eostat, remspace, " shost=%s", sendhost);
503                         UPD_EOSTAT(statline);
504                 }
505         }
506         if (recvhost) {
507                 if (remspace > 7+strlen(recvhost) ) {
508                         snprintf(eostat, remspace, " rhost=%s", recvhost);
509                         UPD_EOSTAT(statline);
510                 }
511         }
512         if (recvdev) {
513                 if (remspace > 6+strlen(recvdev) ) {
514                         snprintf(eostat, remspace, " rdev=%s", recvdev);
515                         UPD_EOSTAT(statline);
516                 }
517         }
518         if (remspace > 1) {
519                 strcpy(eostat, "\n");
520         } else {
521                 /* probably should back up to just before the final " x=".. */  
522                 strcpy(statline+STATLINE_SIZE-2, "\n");
523         }
524         statfile = open(statfname, O_WRONLY|O_APPEND, 0664);
525         if (statfile < 0) {
526                 /* statfile was given, but we can't open it.  should we
527                  * syslog/printf this as an error? */
528                 return;
529         }
530         write(statfile, statline, strlen(statline));
531         close(statfile);
532
533         return;
534 #undef UPD_EOSTAT       
535 }
536
537 #ifdef __STDC__
538 #include <stdarg.h>
539 #else
540 #include <varargs.h>
541 #endif
542
543 void
544 #ifdef __STDC__
545 fatal(const struct printer *pp, const char *msg, ...)
546 #else
547 fatal(pp, msg, va_alist)
548         const struct printer *pp;
549         char *msg;
550         va_dcl
551 #endif
552 {
553         va_list ap;
554 #ifdef __STDC__
555         va_start(ap, msg);
556 #else
557         va_start(ap);
558 #endif
559         /* this error message is being sent to the 'from_host' */
560         if (from_host != local_host)
561                 (void)printf("%s: ", local_host);
562         (void)printf("%s: ", progname);
563         if (pp && pp->printer)
564                 (void)printf("%s: ", pp->printer);
565         (void)vprintf(msg, ap);
566         va_end(ap);
567         (void)putchar('\n');
568         exit(1);
569 }
570
571 /*
572  * Close all file descriptors from START on up.
573  * This is a horrific kluge, since getdtablesize() might return
574  * ``infinity'', in which case we will be spending a long time
575  * closing ``files'' which were never open.  Perhaps it would
576  * be better to close the first N fds, for some small value of N.
577  */
578 void
579 closeallfds(int start)
580 {
581         int stop = getdtablesize();
582         for (; start < stop; start++)
583                 close(start);
584 }
585