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
41 static char sccsid[] = "@(#)common.c 8.5 (Berkeley) 4/28/95";
45 #include "lp.cdefs.h" /* A cross-platform version of <sys/cdefs.h> */
46 __FBSDID("$FreeBSD$");
48 #include <sys/param.h>
51 #include <sys/types.h>
65 #include "pathnames.h"
68 * Routines and data common to all the line printer functions.
71 const char *progname; /* program name */
73 static int compar(const void *_p1, const void *_p2);
76 * isdigit() takes a parameter of 'int', but expect values in the range
77 * of unsigned char. Define a wrapper which takes a value of type 'char',
78 * whether signed or unsigned, and ensure it ends up in the right range.
80 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
83 * get_line reads a line from the control file cfp, removes tabs, converts
84 * new-line to null and leaves it in line.
85 * Returns 0 at EOF or the number of characters read.
90 register int linel = 0;
91 register char *lp = line;
94 while ((c = getc(cfp)) != '\n' && (size_t)(linel+1) < sizeof(line)) {
101 } while ((linel & 07) != 0 && (size_t)(linel+1) <
113 * Scan the current directory and make a list of daemon files sorted by
115 * Return the number of entries and a pointer to the list.
118 getq(const struct printer *pp, struct jobqueue *(*namelist[]))
120 register struct dirent *d;
121 register struct jobqueue *q, **queue;
122 size_t arraysz, entrysz, nitems;
128 if ((dirp = opendir(pp->spool_dir)) == NULL) {
132 if (fstat(dirfd(dirp), &stbuf) < 0)
137 * Estimate the array size by taking the size of the directory file
138 * and dividing it by a multiple of the minimum size entry.
140 arraysz = (stbuf.st_size / 24);
143 queue = (struct jobqueue **)malloc(arraysz * sizeof(struct jobqueue *));
148 while ((d = readdir(dirp)) != NULL) {
149 if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
150 continue; /* daemon control files only */
152 statres = stat(d->d_name, &stbuf);
155 continue; /* Doesn't exist */
156 entrysz = sizeof(struct jobqueue) - sizeof(q->job_cfname) +
157 strlen(d->d_name) + 1;
158 q = (struct jobqueue *)malloc(entrysz);
162 q->job_processed = 0;
163 q->job_time = stbuf.st_mtime;
164 strcpy(q->job_cfname, d->d_name);
166 * Check to make sure the array has space left and
167 * realloc the maximum size.
169 if (++nitems > arraysz) {
170 queue = (struct jobqueue **)reallocarray((char *)queue,
171 arraysz, 2 * sizeof(struct jobqueue *));
182 qsort(queue, nitems, sizeof(struct jobqueue *), compar);
193 * Compare modification times.
196 compar(const void *p1, const void *p2)
198 const struct jobqueue *qe1, *qe2;
200 qe1 = *(const struct jobqueue * const *)p1;
201 qe2 = *(const struct jobqueue * const *)p2;
203 if (qe1->job_time < qe2->job_time)
205 if (qe1->job_time > qe2->job_time)
208 * At this point, the two files have the same last-modification time.
209 * return a result based on filenames, so that 'cfA001some.host' will
210 * come before 'cfA002some.host'. Since the jobid ('001') will wrap
211 * around when it gets to '999', we also assume that '9xx' jobs are
212 * older than '0xx' jobs.
214 if ((qe1->job_cfname[3] == '9') && (qe2->job_cfname[3] == '0'))
216 if ((qe1->job_cfname[3] == '0') && (qe2->job_cfname[3] == '9'))
218 return (strcmp(qe1->job_cfname, qe2->job_cfname));
222 * A simple routine to determine the job number for a print job based on
223 * the name of its control file. The algorithm used here may look odd, but
224 * the main issue is that all parts of `lpd', `lpc', `lpq' & `lprm' must be
225 * using the same algorithm, whatever that algorithm may be. If the caller
226 * provides a non-null value for ''hostpp', then this returns a pointer to
227 * the start of the hostname (or IP address?) as found in the filename.
229 * Algorithm: The standard `cf' file has the job number start in position 4,
230 * but some implementations have that as an extra file-sequence letter, and
231 * start the job number in position 5. The job number is usually three bytes,
232 * but may be as many as five. Confusing matters still more, some Windows
233 * print servers will append an IP address to the job number, instead of
234 * the expected hostname. So, if the job number ends with a '.', then
235 * assume the correct jobnum value is the first three digits.
238 calc_jobnum(const char *cfname, const char **hostpp)
241 const char *cp, *numstr, *hoststr;
244 if (!isdigitch(*numstr))
247 for (cp = numstr; (cp < numstr + 5) && isdigitch(*cp); cp++)
248 jnum = jnum * 10 + (*cp - '0');
252 * If the filename was built with an IP number instead of a hostname,
253 * then recalculate using only the first three digits found.
255 while(isdigitch(*cp))
259 for (cp = numstr; (cp < numstr + 3) && isdigitch(*cp); cp++)
260 jnum = jnum * 10 + (*cp - '0');
268 /* sleep n milliseconds */
272 struct timeval tdelay;
274 if (millisec <= 0 || millisec > 10000)
275 fatal((struct printer *)0, /* fatal() knows how to deal */
276 "unreasonable delay period (%d)", millisec);
277 tdelay.tv_sec = millisec / 1000;
278 tdelay.tv_usec = millisec * 1000 % 1000000;
279 (void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay);
283 lock_file_name(const struct printer *pp, char *buf, size_t len)
285 static char staticbuf[MAXPATHLEN];
292 if (pp->lock_file[0] == '/')
293 strlcpy(buf, pp->lock_file, len);
295 snprintf(buf, len, "%s/%s", pp->spool_dir, pp->lock_file);
301 status_file_name(const struct printer *pp, char *buf, size_t len)
303 static char staticbuf[MAXPATHLEN];
310 if (pp->status_file[0] == '/')
311 strlcpy(buf, pp->status_file, len);
313 snprintf(buf, len, "%s/%s", pp->spool_dir, pp->status_file);
319 * Routine to change operational state of a print queue. The operational
320 * state is indicated by the access bits on the lock file for the queue.
321 * At present, this is only called from various routines in lpc/cmds.c.
323 * XXX - Note that this works by changing access-bits on the
324 * file, and you can only do that if you are the owner of
325 * the file, or root. Thus, this won't really work for
326 * userids in the "LPR_OPER" group, unless lpc is running
327 * setuid to root (or maybe setuid to daemon).
328 * Generally lpc is installed setgid to daemon, but does
332 set_qstate(int action, const char *lfname)
335 mode_t chgbits, newbits, oldmask;
336 const char *failmsg, *okmsg;
337 static const char *nomsg = "no state msg";
338 int chres, errsav, fd, res, statres;
341 * Find what the current access-bits are.
343 memset(&stbuf, 0, sizeof(stbuf));
345 statres = stat(lfname, &stbuf);
348 if ((statres < 0) && (errsav != ENOENT)) {
349 printf("\tcannot stat() lock file\n");
350 return (SQS_STATFAIL);
355 * Determine which bit(s) should change for the requested action.
357 chgbits = stbuf.st_mode;
358 newbits = LOCK_FILE_MODE;
361 if (action & SQS_QCHANGED) {
362 chgbits |= LFM_RESET_QUE;
363 newbits |= LFM_RESET_QUE;
364 /* The okmsg is not actually printed for this case. */
366 failmsg = "set queue-changed";
368 if (action & SQS_DISABLEQ) {
369 chgbits |= LFM_QUEUE_DIS;
370 newbits |= LFM_QUEUE_DIS;
371 okmsg = "queuing disabled";
372 failmsg = "disable queuing";
374 if (action & SQS_STOPP) {
375 chgbits |= LFM_PRINT_DIS;
376 newbits |= LFM_PRINT_DIS;
377 okmsg = "printing disabled";
378 failmsg = "disable printing";
379 if (action & SQS_DISABLEQ) {
380 okmsg = "printer and queuing disabled";
381 failmsg = "disable queuing and printing";
384 if (action & SQS_ENABLEQ) {
385 chgbits &= ~LFM_QUEUE_DIS;
386 newbits &= ~LFM_QUEUE_DIS;
387 okmsg = "queuing enabled";
388 failmsg = "enable queuing";
390 if (action & SQS_STARTP) {
391 chgbits &= ~LFM_PRINT_DIS;
392 newbits &= ~LFM_PRINT_DIS;
393 okmsg = "printing enabled";
394 failmsg = "enable printing";
397 /* This routine was called with an invalid action. */
398 printf("\t<error in set_qstate!>\n");
399 return (SQS_PARMERR);
405 /* The file already exists, so change the access. */
407 chres = chmod(lfname, chgbits);
413 } else if (newbits == LOCK_FILE_MODE) {
415 * The file does not exist, but the state requested is
416 * the same as the default state when no file exists.
417 * Thus, there is no need to create the file.
422 * The file did not exist, so create it with the
423 * appropriate access bits for the requested action.
424 * Push a new umask around that create, to make sure
425 * all the read/write bits are set as desired.
427 oldmask = umask(S_IWOTH);
429 fd = open(lfname, O_WRONLY|O_CREAT, newbits);
445 printf("\t%s\n", okmsg);
448 printf("\tcannot create lock file: %s\n",
452 printf("\tcannot %s: %s\n", failmsg, strerror(errsav));
459 /* routine to get a current timestamp, optionally in a standard-fmt string */
461 lpd_gettime(struct timespec *tsp, char *strp, size_t strsize)
463 struct timespec local_ts;
464 struct timeval btime;
465 char tempstr[TIMESTR_SIZE];
466 #ifdef STRFTIME_WRONG_z
473 /* some platforms have a routine called clock_gettime, but the
474 * routine does nothing but return "not implemented". */
475 memset(tsp, 0, sizeof(struct timespec));
476 if (clock_gettime(CLOCK_REALTIME, tsp)) {
477 /* nanosec-aware rtn failed, fall back to microsec-aware rtn */
478 memset(tsp, 0, sizeof(struct timespec));
479 gettimeofday(&btime, NULL);
480 tsp->tv_sec = btime.tv_sec;
481 tsp->tv_nsec = btime.tv_usec * 1000;
484 /* caller may not need a character-ized version */
485 if ((strp == NULL) || (strsize < 1))
488 strftime(tempstr, TIMESTR_SIZE, LPD_TIMESTAMP_PATTERN,
489 localtime(&tsp->tv_sec));
492 * This check is for implementations of strftime which treat %z
493 * (timezone as [+-]hhmm ) like %Z (timezone as characters), or
494 * completely ignore %z. This section is not needed on freebsd.
495 * I'm not sure this is completely right, but it should work OK
498 #ifdef STRFTIME_WRONG_z
499 destp = strrchr(tempstr, ':');
502 if ((*destp != '+') && (*destp != '-')) {
504 int tzmin = timezone / 60;
505 int tzhr = tzmin / 60;
508 strcpy(savday, destp + strlen(destp) - 4);
509 snprintf(destp, (destp - tempstr), "%+03d%02d",
510 (-1*tzhr), tzmin % 60);
511 strcat(destp, savday);
516 if (strsize > TIMESTR_SIZE) {
517 strsize = TIMESTR_SIZE;
518 strp[TIMESTR_SIZE+1] = '\0';
520 strlcpy(strp, tempstr, strsize);
523 /* routines for writing transfer-statistic records */
525 trstat_init(struct printer *pp, const char *fname, int filenum)
527 register const char *srcp;
528 register char *destp, *endp;
531 * Figure out the job id of this file. The filename should be
532 * 'cf', 'df', or maybe 'tf', followed by a letter (or sometimes
533 * two), followed by the jobnum, followed by a hostname.
534 * The jobnum is usually 3 digits, but might be as many as 5.
535 * Note that some care has to be taken parsing this, as the
536 * filename could be coming from a remote-host, and thus might
537 * not look anything like what is expected...
539 memset(pp->jobnum, 0, sizeof(pp->jobnum));
541 srcp = strchr(fname, '/');
544 destp = &(pp->jobnum[0]);
546 while (*srcp != '\0' && (*srcp < '0' || *srcp > '9'))
548 while (*srcp >= '0' && *srcp <= '9' && destp < endp)
549 *(destp++) = *(srcp++);
551 /* get the starting time in both numeric and string formats, and
552 * save those away along with the file-number */
553 pp->jobdfnum = filenum;
554 lpd_gettime(&pp->tr_start, pp->tr_timestr, (size_t)TIMESTR_SIZE);
560 trstat_write(struct printer *pp, tr_sendrecv sendrecv, size_t bytecnt,
561 const char *userid, const char *otherhost, const char *orighost)
563 #define STATLINE_SIZE 1024
567 char thishost[MAXHOSTNAMELEN], statline[STATLINE_SIZE];
569 const char *lprhost, *recvdev, *recvhost, *rectype;
570 const char *sendhost, *statfname;
571 #define UPD_EOSTAT(xStr) do { \
572 eostat = strchr(xStr, '\0'); \
573 remspace = eostat - xStr; \
576 lpd_gettime(&pp->tr_done, NULL, (size_t)0);
577 trtime = DIFFTIME_TS(pp->tr_done, pp->tr_start);
579 gethostname(thishost, sizeof(thishost));
580 lprhost = sendhost = recvhost = recvdev = NULL;
584 statfname = pp->stat_send;
586 recvhost = otherhost;
590 statfname = pp->stat_recv;
591 sendhost = otherhost;
596 * This case is for copying to a device (presumably local,
597 * though filters using things like 'net/CAP' can confuse
598 * this assumption...).
601 statfname = pp->stat_send;
603 recvdev = _PATH_DEFDEVLP;
604 if (pp->lp) recvdev = pp->lp;
607 /* internal error... should we syslog/printf an error? */
610 if (statfname == NULL)
614 * the original-host and userid are found out by reading thru the
615 * cf (control-file) for the job. Unfortunately, on incoming jobs
616 * the df's (data-files) are sent before the matching cf, so the
617 * orighost & userid are generally not-available for incoming jobs.
619 * (it would be nice to create a work-around for that..)
621 if (orighost && (*orighost != '\0'))
629 * Format of statline.
630 * Some of the keywords listed here are not implemented here, but
631 * they are listed to reserve the meaning for a given keyword.
632 * Fields are separated by a blank. The fields in statline are:
633 * <tstamp> - time the transfer started
634 * <ptrqueue> - name of the printer queue (the short-name...)
635 * <hname> - hostname the file originally came from (the
636 * 'lpr host'), if known, or "_na_" if not known.
637 * <xxx> - id of job from that host (generally three digits)
638 * <n> - file count (# of file within job)
639 * <rectype> - 4-byte field indicating the type of transfer
640 * statistics record. "send" means it's from the
641 * host sending a datafile, "recv" means it's from
642 * a host as it receives a datafile.
643 * user=<userid> - user who sent the job (if known)
644 * secs=<n> - seconds it took to transfer the file
645 * bytes=<n> - number of bytes transferred (ie, "bytecount")
646 * bps=<n.n>e<n> - Bytes/sec (if the transfer was "big enough"
647 * for this to be useful)
648 * ! top=<str> - type of printer (if the type is defined in
649 * printcap, and if this statline is for sending
650 * a file to that ptr)
651 * ! qls=<n> - queue-length at start of send/print-ing a job
652 * ! qle=<n> - queue-length at end of send/print-ing a job
653 * sip=<addr> - IP address of sending host, only included when
655 * shost=<hname> - sending host (if that does != the original host)
656 * rhost=<hname> - hostname receiving the file (ie, "destination")
657 * rdev=<dev> - device receiving the file, when the file is being
658 * send to a device instead of a remote host.
660 * Note: A single print job may be transferred multiple times. The
661 * original 'lpr' occurs on one host, and that original host might
662 * send to some interim host (or print server). That interim host
663 * might turn around and send the job to yet another host (most likely
664 * the real printer). The 'shost=' parameter is only included if the
665 * sending host for this particular transfer is NOT the same as the
666 * host which did the original 'lpr'.
668 * Many values have 'something=' tags before them, because they are
669 * in some sense "optional", or their order may vary. "Optional" may
670 * mean in the sense that different SITES might choose to have other
671 * fields in the record, or that some fields are only included under
672 * some circumstances. Programs processing these records should not
673 * assume the order or existence of any of these keyword fields.
675 snprintf(statline, STATLINE_SIZE, "%s %s %s %s %03ld %s",
676 pp->tr_timestr, pp->printer, lprhost, pp->jobnum,
677 pp->jobdfnum, rectype);
678 UPD_EOSTAT(statline);
680 if (userid != NULL) {
681 snprintf(eostat, remspace, " user=%s", userid);
682 UPD_EOSTAT(statline);
684 snprintf(eostat, remspace, " secs=%#.2f bytes=%lu", trtime,
685 (unsigned long)bytecnt);
686 UPD_EOSTAT(statline);
689 * The bps field duplicates info from bytes and secs, so do
690 * not bother to include it for very small files.
692 if ((bytecnt > 25000) && (trtime > 1.1)) {
693 snprintf(eostat, remspace, " bps=%#.2e",
694 ((double)bytecnt/trtime));
695 UPD_EOSTAT(statline);
698 if (sendrecv == TR_RECVING) {
699 if (remspace > 5+strlen(from_ip) ) {
700 snprintf(eostat, remspace, " sip=%s", from_ip);
701 UPD_EOSTAT(statline);
704 if (0 != strcmp(lprhost, sendhost)) {
705 if (remspace > 7+strlen(sendhost) ) {
706 snprintf(eostat, remspace, " shost=%s", sendhost);
707 UPD_EOSTAT(statline);
711 if (remspace > 7+strlen(recvhost) ) {
712 snprintf(eostat, remspace, " rhost=%s", recvhost);
713 UPD_EOSTAT(statline);
717 if (remspace > 6+strlen(recvdev) ) {
718 snprintf(eostat, remspace, " rdev=%s", recvdev);
719 UPD_EOSTAT(statline);
723 strcpy(eostat, "\n");
725 /* probably should back up to just before the final " x=".. */
726 strcpy(statline+STATLINE_SIZE-2, "\n");
728 statfile = open(statfname, O_WRONLY|O_APPEND, 0664);
730 /* statfile was given, but we can't open it. should we
731 * syslog/printf this as an error? */
734 write(statfile, statline, strlen(statline));
744 fatal(const struct printer *pp, const char *msg, ...)
748 /* this error message is being sent to the 'from_host' */
749 if (from_host != local_host)
750 (void)printf("%s: ", local_host);
751 (void)printf("%s: ", progname);
752 if (pp && pp->printer)
753 (void)printf("%s: ", pp->printer);
754 (void)vprintf(msg, ap);
761 * Close all file descriptors from START on up.
764 closeallfds(int start)
768 if (USE_CLOSEFROM) /* The faster, modern solution */
771 /* This older logic can be pretty awful on some OS's. The
772 * getdtablesize() might return ``infinity'', and then this
773 * will waste a lot of time closing file descriptors which
774 * had never been open()-ed. */
775 stop = getdtablesize();
776 for (; start < stop; start++)