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.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
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 $
42 #include <sys/param.h>
45 #include <sys/types.h>
57 #include "pathnames.h"
60 * Routines and data common to all the line printer functions.
63 const char *progname; /* program name */
65 extern uid_t uid, euid;
67 static int compar(const void *_p1, const void *_p2);
70 * Getline reads a line from the control file cfp, removes tabs, converts
71 * new-line to null and leaves it in line.
72 * Returns 0 at EOF or the number of characters read.
81 while ((c = getc(cfp)) != '\n' && (size_t)(linel+1) < sizeof(line)) {
88 } while ((linel & 07) != 0 && (size_t)(linel+1) <
100 * Scan the current directory and make a list of daemon files sorted by
102 * Return the number of entries and a pointer to the list.
105 getq(const struct printer *pp, struct jobqueue *(*namelist[]))
108 struct jobqueue *q, **queue;
109 size_t arraysz, entrysz, nitems;
115 if ((dirp = opendir(pp->spool_dir)) == NULL) {
119 if (fstat(dirfd(dirp), &stbuf) < 0)
124 * Estimate the array size by taking the size of the directory file
125 * and dividing it by a multiple of the minimum size entry.
127 * However some file systems do report a directory size == 0 (HAMMER
128 * for instance). Use a sensible minimum size for the array.
130 arraysz = MAX(20, (stbuf.st_size / 24));
131 queue = (struct jobqueue **)malloc(arraysz * sizeof(struct jobqueue *));
136 while ((d = readdir(dirp)) != NULL) {
137 if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
138 continue; /* daemon control files only */
140 statres = stat(d->d_name, &stbuf);
143 continue; /* Doesn't exist */
144 entrysz = sizeof(struct jobqueue) - sizeof(q->job_cfname) +
145 strlen(d->d_name) + 1;
146 q = (struct jobqueue *)malloc(entrysz);
150 q->job_processed = 0;
151 q->job_time = stbuf.st_mtime;
152 strcpy(q->job_cfname, d->d_name);
154 * Check to make sure the array has space left and
155 * realloc the maximum size.
157 if (++nitems > arraysz) {
159 queue = (struct jobqueue **)realloc((char *)queue,
160 arraysz * sizeof(struct jobqueue *));
168 qsort(queue, nitems, sizeof(struct jobqueue *), compar);
179 * Compare modification times.
182 compar(const void *p1, const void *p2)
184 const struct jobqueue *qe1, *qe2;
186 qe1 = *(const struct jobqueue * const *)p1;
187 qe2 = *(const struct jobqueue * const *)p2;
189 if (qe1->job_time < qe2->job_time)
191 if (qe1->job_time > qe2->job_time)
194 * At this point, the two files have the same last-modification time.
195 * return a result based on filenames, so that 'cfA001some.host' will
196 * come before 'cfA002some.host'. Since the jobid ('001') will wrap
197 * around when it gets to '999', we also assume that '9xx' jobs are
198 * older than '0xx' jobs.
200 if ((qe1->job_cfname[3] == '9') && (qe2->job_cfname[3] == '0'))
202 if ((qe1->job_cfname[3] == '0') && (qe2->job_cfname[3] == '9'))
204 return (strcmp(qe1->job_cfname, qe2->job_cfname));
207 /* sleep n milliseconds */
211 struct timeval tdelay;
213 if (millisec <= 0 || millisec > 10000)
214 fatal(NULL, /* fatal() knows how to deal */
215 "unreasonable delay period (%d)", millisec);
216 tdelay.tv_sec = millisec / 1000;
217 tdelay.tv_usec = millisec * 1000 % 1000000;
218 select(0, NULL, NULL, NULL, &tdelay);
222 lock_file_name(const struct printer *pp, char *buf, size_t len)
224 static char staticbuf[MAXPATHLEN];
231 if (pp->lock_file[0] == '/')
232 strlcpy(buf, pp->lock_file, len);
234 snprintf(buf, len, "%s/%s", pp->spool_dir, pp->lock_file);
240 status_file_name(const struct printer *pp, char *buf, size_t len)
242 static char staticbuf[MAXPATHLEN];
249 if (pp->status_file[0] == '/')
250 strlcpy(buf, pp->status_file, len);
252 snprintf(buf, len, "%s/%s", pp->spool_dir, pp->status_file);
258 * Routine to change operational state of a print queue. The operational
259 * state is indicated by the access bits on the lock file for the queue.
260 * At present, this is only called from various routines in lpc/cmds.c.
262 * XXX - Note that this works by changing access-bits on the
263 * file, and you can only do that if you are the owner of
264 * the file, or root. Thus, this won't really work for
265 * userids in the "LPR_OPER" group, unless lpc is running
266 * setuid to root (or maybe setuid to daemon).
267 * Generally lpc is installed setgid to daemon, but does
271 set_qstate(int action, const char *lfname)
274 mode_t chgbits, newbits, oldmask;
275 const char *failmsg, *okmsg;
276 static const char *nomsg = "no state msg";
277 int chres, errsav, fd, res, statres;
280 * Find what the current access-bits are.
282 memset(&stbuf, 0, sizeof(stbuf));
284 statres = stat(lfname, &stbuf);
287 if ((statres < 0) && (errsav != ENOENT)) {
288 printf("\tcannot stat() lock file\n");
289 return (SQS_STATFAIL);
294 * Determine which bit(s) should change for the requested action.
296 chgbits = stbuf.st_mode;
297 newbits = LOCK_FILE_MODE;
300 if (action & SQS_QCHANGED) {
301 chgbits |= LFM_RESET_QUE;
302 newbits |= LFM_RESET_QUE;
303 /* The okmsg is not actually printed for this case. */
305 failmsg = "set queue-changed";
307 if (action & SQS_DISABLEQ) {
308 chgbits |= LFM_QUEUE_DIS;
309 newbits |= LFM_QUEUE_DIS;
310 okmsg = "queuing disabled";
311 failmsg = "disable queuing";
313 if (action & SQS_STOPP) {
314 chgbits |= LFM_PRINT_DIS;
315 newbits |= LFM_PRINT_DIS;
316 okmsg = "printing disabled";
317 failmsg = "disable printing";
318 if (action & SQS_DISABLEQ) {
319 okmsg = "printer and queuing disabled";
320 failmsg = "disable queuing and printing";
323 if (action & SQS_ENABLEQ) {
324 chgbits &= ~LFM_QUEUE_DIS;
325 newbits &= ~LFM_QUEUE_DIS;
326 okmsg = "queuing enabled";
327 failmsg = "enable queuing";
329 if (action & SQS_STARTP) {
330 chgbits &= ~LFM_PRINT_DIS;
331 newbits &= ~LFM_PRINT_DIS;
332 okmsg = "printing enabled";
333 failmsg = "enable printing";
336 /* This routine was called with an invalid action. */
337 printf("\t<error in set_qstate!>\n");
338 return (SQS_PARMERR);
344 /* The file already exists, so change the access. */
346 chres = chmod(lfname, chgbits);
352 } else if (newbits == LOCK_FILE_MODE) {
354 * The file does not exist, but the state requested is
355 * the same as the default state when no file exists.
356 * Thus, there is no need to create the file.
361 * The file did not exist, so create it with the
362 * appropriate access bits for the requested action.
363 * Push a new umask around that create, to make sure
364 * all the read/write bits are set as desired.
366 oldmask = umask(S_IWOTH);
368 fd = open(lfname, O_WRONLY|O_CREAT, newbits);
384 printf("\t%s\n", okmsg);
387 printf("\tcannot create lock file: %s\n",
391 printf("\tcannot %s: %s\n", failmsg, strerror(errsav));
398 /* routine to get a current timestamp, optionally in a standard-fmt string */
400 lpd_gettime(struct timespec *tsp, char *strp, size_t strsize)
402 struct timespec local_ts;
403 struct timeval btime;
404 char tempstr[TIMESTR_SIZE];
405 #ifdef STRFTIME_WRONG_z
412 /* some platforms have a routine called clock_gettime, but the
413 * routine does nothing but return "not implemented". */
414 memset(tsp, 0, sizeof(struct timespec));
415 if (clock_gettime(CLOCK_REALTIME, tsp)) {
416 /* nanosec-aware rtn failed, fall back to microsec-aware rtn */
417 memset(tsp, 0, sizeof(struct timespec));
418 gettimeofday(&btime, NULL);
419 tsp->tv_sec = btime.tv_sec;
420 tsp->tv_nsec = btime.tv_usec * 1000;
423 /* caller may not need a character-ized version */
424 if ((strp == NULL) || (strsize < 1))
427 strftime(tempstr, TIMESTR_SIZE, LPD_TIMESTAMP_PATTERN,
428 localtime(&tsp->tv_sec));
431 * This check is for implementations of strftime which treat %z
432 * (timezone as [+-]hhmm ) like %Z (timezone as characters), or
433 * completely ignore %z. This section is not needed on freebsd.
434 * I'm not sure this is completely right, but it should work OK
437 #ifdef STRFTIME_WRONG_z
438 destp = strrchr(tempstr, ':');
441 if ((*destp != '+') && (*destp != '-')) {
443 int tzmin = timezone / 60;
444 int tzhr = tzmin / 60;
447 strcpy(savday, destp + strlen(destp) - 4);
448 snprintf(destp, (destp - tempstr), "%+03d%02d",
449 (-1*tzhr), tzmin % 60);
450 strcat(destp, savday);
455 if (strsize > TIMESTR_SIZE) {
456 strsize = TIMESTR_SIZE;
457 strp[TIMESTR_SIZE+1] = '\0';
459 strlcpy(strp, tempstr, strsize);
462 /* routines for writing transfer-statistic records */
464 trstat_init(struct printer *pp, const char *fname, int filenum)
470 * Figure out the job id of this file. The filename should be
471 * 'cf', 'df', or maybe 'tf', followed by a letter (or sometimes
472 * two), followed by the jobnum, followed by a hostname.
473 * The jobnum is usually 3 digits, but might be as many as 5.
474 * Note that some care has to be taken parsing this, as the
475 * filename could be coming from a remote-host, and thus might
476 * not look anything like what is expected...
478 memset(pp->jobnum, 0, sizeof(pp->jobnum));
480 srcp = strchr(fname, '/');
483 destp = &(pp->jobnum[0]);
485 while (*srcp != '\0' && (*srcp < '0' || *srcp > '9'))
487 while (*srcp >= '0' && *srcp <= '9' && destp < endp)
488 *(destp++) = *(srcp++);
490 /* get the starting time in both numeric and string formats, and
491 * save those away along with the file-number */
492 pp->jobdfnum = filenum;
493 lpd_gettime(&pp->tr_start, pp->tr_timestr, (size_t)TIMESTR_SIZE);
499 trstat_write(struct printer *pp, tr_sendrecv sendrecv, size_t bytecnt,
500 const char *userid, const char *otherhost, const char *orighost)
502 #define STATLINE_SIZE 1024
506 char thishost[MAXHOSTNAMELEN], statline[STATLINE_SIZE];
508 const char *lprhost, *recvdev, *recvhost, *rectype;
509 const char *sendhost, *statfname;
510 #define UPD_EOSTAT(xStr) do { \
511 eostat = strchr(xStr, '\0'); \
512 remspace = eostat - xStr; \
515 lpd_gettime(&pp->tr_done, NULL, (size_t)0);
516 trtime = DIFFTIME_TS(pp->tr_done, pp->tr_start);
518 gethostname(thishost, sizeof(thishost));
519 lprhost = sendhost = recvhost = recvdev = NULL;
523 statfname = pp->stat_send;
525 recvhost = otherhost;
529 statfname = pp->stat_recv;
530 sendhost = otherhost;
535 * This case is for copying to a device (presumably local,
536 * though filters using things like 'net/CAP' can confuse
537 * this assumption...).
540 statfname = pp->stat_send;
542 recvdev = _PATH_DEFDEVLP;
543 if (pp->lp) recvdev = pp->lp;
546 /* internal error... should we syslog/printf an error? */
549 if (statfname == NULL)
553 * the original-host and userid are found out by reading thru the
554 * cf (control-file) for the job. Unfortunately, on incoming jobs
555 * the df's (data-files) are sent before the matching cf, so the
556 * orighost & userid are generally not-available for incoming jobs.
558 * (it would be nice to create a work-around for that..)
560 if (orighost && (*orighost != '\0'))
568 * Format of statline.
569 * Some of the keywords listed here are not implemented here, but
570 * they are listed to reserve the meaning for a given keyword.
571 * Fields are separated by a blank. The fields in statline are:
572 * <tstamp> - time the transfer started
573 * <ptrqueue> - name of the printer queue (the short-name...)
574 * <hname> - hostname the file originally came from (the
575 * 'lpr host'), if known, or "_na_" if not known.
576 * <xxx> - id of job from that host (generally three digits)
577 * <n> - file count (# of file within job)
578 * <rectype> - 4-byte field indicating the type of transfer
579 * statistics record. "send" means it's from the
580 * host sending a datafile, "recv" means it's from
581 * a host as it receives a datafile.
582 * user=<userid> - user who sent the job (if known)
583 * secs=<n> - seconds it took to transfer the file
584 * bytes=<n> - number of bytes transfered (ie, "bytecount")
585 * bps=<n.n>e<n> - Bytes/sec (if the transfer was "big enough"
586 * for this to be useful)
587 * ! top=<str> - type of printer (if the type is defined in
588 * printcap, and if this statline is for sending
589 * a file to that ptr)
590 * ! qls=<n> - queue-length at start of send/print-ing a job
591 * ! qle=<n> - queue-length at end of send/print-ing a job
592 * sip=<addr> - IP address of sending host, only included when
594 * shost=<hname> - sending host (if that does != the original host)
595 * rhost=<hname> - hostname receiving the file (ie, "destination")
596 * rdev=<dev> - device receiving the file, when the file is being
597 * send to a device instead of a remote host.
599 * Note: A single print job may be transferred multiple times. The
600 * original 'lpr' occurs on one host, and that original host might
601 * send to some interim host (or print server). That interim host
602 * might turn around and send the job to yet another host (most likely
603 * the real printer). The 'shost=' parameter is only included if the
604 * sending host for this particular transfer is NOT the same as the
605 * host which did the original 'lpr'.
607 * Many values have 'something=' tags before them, because they are
608 * in some sense "optional", or their order may vary. "Optional" may
609 * mean in the sense that different SITES might choose to have other
610 * fields in the record, or that some fields are only included under
611 * some circumstances. Programs processing these records should not
612 * assume the order or existence of any of these keyword fields.
614 snprintf(statline, STATLINE_SIZE, "%s %s %s %s %03ld %s",
615 pp->tr_timestr, pp->printer, lprhost, pp->jobnum,
616 pp->jobdfnum, rectype);
617 UPD_EOSTAT(statline);
619 if (userid != NULL) {
620 snprintf(eostat, remspace, " user=%s", userid);
621 UPD_EOSTAT(statline);
623 snprintf(eostat, remspace, " secs=%#.2f bytes=%lu", trtime,
624 (unsigned long)bytecnt);
625 UPD_EOSTAT(statline);
628 * The bps field duplicates info from bytes and secs, so do
629 * not bother to include it for very small files.
631 if ((bytecnt > 25000) && (trtime > 1.1)) {
632 snprintf(eostat, remspace, " bps=%#.2e",
633 ((double)bytecnt/trtime));
634 UPD_EOSTAT(statline);
637 if (sendrecv == TR_RECVING) {
638 if (remspace > 5+strlen(from_ip) ) {
639 snprintf(eostat, remspace, " sip=%s", from_ip);
640 UPD_EOSTAT(statline);
643 if (0 != strcmp(lprhost, sendhost)) {
644 if (remspace > 7+strlen(sendhost) ) {
645 snprintf(eostat, remspace, " shost=%s", sendhost);
646 UPD_EOSTAT(statline);
650 if (remspace > 7+strlen(recvhost) ) {
651 snprintf(eostat, remspace, " rhost=%s", recvhost);
652 UPD_EOSTAT(statline);
656 if (remspace > 6+strlen(recvdev) ) {
657 snprintf(eostat, remspace, " rdev=%s", recvdev);
658 UPD_EOSTAT(statline);
662 strcpy(eostat, "\n");
664 /* probably should back up to just before the final " x=".. */
665 strcpy(statline+STATLINE_SIZE-2, "\n");
667 statfile = open(statfname, O_WRONLY|O_APPEND, 0664);
669 /* statfile was given, but we can't open it. should we
670 * syslog/printf this as an error? */
673 write(statfile, statline, strlen(statline));
683 fatal(const struct printer *pp, const char *msg, ...)
687 /* this error message is being sent to the 'from_host' */
688 if (from_host != local_host)
689 printf("%s: ", local_host);
690 printf("%s: ", progname);
691 if (pp && pp->printer)
692 printf("%s: ", pp->printer);
700 * Close all file descriptors from START on up.
701 * This is a horrific kluge, since getdtablesize() might return
702 * ``infinity'', in which case we will be spending a long time
703 * closing ``files'' which were never open. Perhaps it would
704 * be better to close the first N fds, for some small value of N.
707 closeallfds(int start)
709 int stop = getdtablesize();
710 for (; start < stop; start++)