common.c revision 68401
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/* 41static char sccsid[] = "@(#)common.c 8.5 (Berkeley) 4/28/95"; 42*/ 43static const char rcsid[] = 44 "$FreeBSD: head/usr.sbin/lpr/common_source/common.c 68401 2000-11-06 19:36:38Z gad $"; 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 */ 66char line[BUFSIZ]; 67char *name; /* program name */ 68 69extern uid_t uid, euid; 70 71static int compar __P((const void *, const void *)); 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 */ 78int 79getline(cfp) 80 FILE *cfp; 81{ 82 register int linel = 0; 83 register char *lp = line; 84 register int c; 85 86 while ((c = getc(cfp)) != '\n' && linel+1 < sizeof(line)) { 87 if (c == EOF) 88 return(0); 89 if (c == '\t') { 90 do { 91 *lp++ = ' '; 92 linel++; 93 } while ((linel & 07) != 0 && linel+1 < 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 */ 108int 109getq(pp, namelist) 110 const struct printer *pp; 111 struct jobqueue *(*namelist[]); 112{ 113 register struct dirent *d; 114 register struct jobqueue *q, **queue; 115 register int nitems; 116 struct stat stbuf; 117 DIR *dirp; 118 int arraysz; 119 120 seteuid(euid); 121 if ((dirp = opendir(pp->spool_dir)) == NULL) 122 return(-1); 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 if (stat(d->d_name, &stbuf) < 0) 142 continue; /* Doesn't exist */ 143 seteuid(uid); 144 q = (struct jobqueue *)malloc(sizeof(time_t)+strlen(d->d_name)+1); 145 if (q == NULL) 146 goto errdone; 147 q->job_time = stbuf.st_mtime; 148 strcpy(q->job_cfname, d->d_name); 149 /* 150 * Check to make sure the array has space left and 151 * realloc the maximum size. 152 */ 153 if (++nitems > arraysz) { 154 arraysz *= 2; 155 queue = (struct jobqueue **)realloc((char *)queue, 156 arraysz * sizeof(struct jobqueue *)); 157 if (queue == NULL) 158 goto errdone; 159 } 160 queue[nitems-1] = q; 161 } 162 closedir(dirp); 163 if (nitems) 164 qsort(queue, nitems, sizeof(struct jobqueue *), compar); 165 *namelist = queue; 166 return(nitems); 167 168errdone: 169 closedir(dirp); 170 return(-1); 171} 172 173/* 174 * Compare modification times. 175 */ 176static int 177compar(p1, p2) 178 const void *p1, *p2; 179{ 180 const struct jobqueue *qe1, *qe2; 181 qe1 = *(const struct jobqueue **)p1; 182 qe2 = *(const struct jobqueue **)p2; 183 184 if (qe1->job_time < qe2->job_time) 185 return (-1); 186 if (qe1->job_time > qe2->job_time) 187 return (1); 188 /* 189 * At this point, the two files have the same last-modification time. 190 * return a result based on filenames, so that 'cfA001some.host' will 191 * come before 'cfA002some.host'. Since the jobid ('001') will wrap 192 * around when it gets to '999', we also assume that '9xx' jobs are 193 * older than '0xx' jobs. 194 */ 195 if ((qe1->job_cfname[3] == '9') && (qe2->job_cfname[3] == '0')) 196 return (-1); 197 if ((qe1->job_cfname[3] == '0') && (qe2->job_cfname[3] == '9')) 198 return (1); 199 return (strcmp(qe1->job_cfname, qe2->job_cfname)); 200} 201 202/* sleep n milliseconds */ 203void 204delay(n) 205 int n; 206{ 207 struct timeval tdelay; 208 209 if (n <= 0 || n > 10000) 210 fatal((struct printer *)0, /* fatal() knows how to deal */ 211 "unreasonable delay period (%d)", n); 212 tdelay.tv_sec = n / 1000; 213 tdelay.tv_usec = n * 1000 % 1000000; 214 (void) select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tdelay); 215} 216 217char * 218lock_file_name(pp, buf, len) 219 const struct printer *pp; 220 char *buf; 221 size_t len; 222{ 223 static char staticbuf[MAXPATHLEN]; 224 225 if (buf == 0) 226 buf = staticbuf; 227 if (len == 0) 228 len = MAXPATHLEN; 229 230 if (pp->lock_file[0] == '/') { 231 buf[0] = '\0'; 232 strncpy(buf, pp->lock_file, len); 233 } else { 234 snprintf(buf, len, "%s/%s", pp->spool_dir, pp->lock_file); 235 } 236 return buf; 237} 238 239char * 240status_file_name(pp, buf, len) 241 const struct printer *pp; 242 char *buf; 243 size_t len; 244{ 245 static char staticbuf[MAXPATHLEN]; 246 247 if (buf == 0) 248 buf = staticbuf; 249 if (len == 0) 250 len = MAXPATHLEN; 251 252 if (pp->status_file[0] == '/') { 253 buf[0] = '\0'; 254 strncpy(buf, pp->status_file, len); 255 } else { 256 snprintf(buf, len, "%s/%s", pp->spool_dir, pp->status_file); 257 } 258 return buf; 259} 260 261/* routine to get a current timestamp, optionally in a standard-fmt string */ 262void 263lpd_gettime(tsp, strp, strsize) 264 struct timespec *tsp; 265 char *strp; 266 int strsize; 267{ 268 struct timespec local_ts; 269 struct timeval btime; 270 char *destp; 271 char tempstr[TIMESTR_SIZE]; 272 273 if (tsp == NULL) 274 tsp = &local_ts; 275 276 /* some platforms have a routine called clock_gettime, but the 277 * routine does nothing but return "not implemented". */ 278 memset(tsp, 0, sizeof(struct timespec)); 279 if (clock_gettime(CLOCK_REALTIME, tsp)) { 280 /* nanosec-aware rtn failed, fall back to microsec-aware rtn */ 281 memset(tsp, 0, sizeof(struct timespec)); 282 gettimeofday(&btime, NULL); 283 tsp->tv_sec = btime.tv_sec; 284 tsp->tv_nsec = btime.tv_usec * 1000; 285 } 286 287 /* caller may not need a character-ized version */ 288 if ((strp == NULL) || (strsize < 1)) 289 return; 290 291 strftime(tempstr, TIMESTR_SIZE, LPD_TIMESTAMP_PATTERN, 292 localtime(&tsp->tv_sec)); 293 294 /* 295 * This check is for implementations of strftime which treat %z 296 * (timezone as [+-]hhmm ) like %Z (timezone as characters), or 297 * completely ignore %z. This section is not needed on freebsd. 298 * I'm not sure this is completely right, but it should work OK 299 * for EST and EDT... 300 */ 301#ifdef STRFTIME_WRONG_z 302 destp = strrchr(tempstr, ':'); 303 if (destp != NULL) { 304 destp += 3; 305 if ((*destp != '+') && (*destp != '-')) { 306 char savday[6]; 307 int tzmin = timezone / 60; 308 int tzhr = tzmin / 60; 309 if (daylight) 310 tzhr--; 311 strcpy(savday, destp + strlen(destp) - 4); 312 snprintf(destp, (destp - tempstr), "%+03d%02d", 313 (-1*tzhr), tzmin % 60); 314 strcat(destp, savday); 315 } 316 } 317#endif 318 319 if (strsize > TIMESTR_SIZE) { 320 strsize = TIMESTR_SIZE; 321 strp[TIMESTR_SIZE+1] = '\0'; 322 } 323 strncpy(strp, tempstr, strsize); 324} 325 326/* routines for writing transfer-statistic records */ 327void 328trstat_init(pp, fname, filenum) 329 struct printer *pp; 330 const char *fname; 331 int filenum; 332{ 333 register const char *srcp; 334 register char *destp, *endp; 335 336 /* 337 * Figure out the job id of this file. The filename should be 338 * 'cf', 'df', or maybe 'tf', followed by a letter (or sometimes 339 * two), followed by the jobnum, followed by a hostname. 340 * The jobnum is usually 3 digits, but might be as many as 5. 341 * Note that some care has to be taken parsing this, as the 342 * filename could be coming from a remote-host, and thus might 343 * not look anything like what is expected... 344 */ 345 memset(pp->jobnum, 0, sizeof(pp->jobnum)); 346 pp->jobnum[0] = '0'; 347 srcp = strchr(fname, '/'); 348 if (srcp == NULL) 349 srcp = fname; 350 destp = &(pp->jobnum[0]); 351 endp = destp + 5; 352 while (*srcp != '\0' && (*srcp < '0' || *srcp > '9')) 353 srcp++; 354 while (*srcp >= '0' && *srcp <= '9' && destp < endp) 355 *(destp++) = *(srcp++); 356 357 /* get the starting time in both numeric and string formats, and 358 * save those away along with the file-number */ 359 pp->jobdfnum = filenum; 360 lpd_gettime(&pp->tr_start, pp->tr_timestr, TIMESTR_SIZE); 361 362 return; 363} 364 365void 366trstat_write(pp, sendrecv, bytecnt, userid, otherhost, orighost) 367 struct printer *pp; 368 tr_sendrecv sendrecv; 369 size_t bytecnt; 370 const char *userid; 371 const char *otherhost; 372 const char *orighost; 373{ 374#define STATLINE_SIZE 1024 375 double trtime; 376 int remspace; 377 int statfile; 378 char thishost[MAXHOSTNAMELEN+1], statline[STATLINE_SIZE]; 379 const char *rectype, *statfname; 380 const char *lprhost, *sendhost, *recvhost, *recvdev; 381 char *eostat; 382#define UPD_EOSTAT(xStr) do { \ 383 eostat = strchr(xStr, '\0'); \ 384 remspace = eostat - xStr; \ 385} while(0) 386 387 lpd_gettime(&pp->tr_done, NULL, 0); 388 trtime = DIFFTIME_TS(pp->tr_done, pp->tr_start); 389 390 gethostname(thishost, sizeof(thishost)); 391 lprhost = sendhost = recvhost = recvdev = NULL; 392 switch (sendrecv) { 393 case TR_SENDING: 394 rectype = "send"; 395 statfname = pp->stat_send; 396 sendhost = thishost; 397 recvhost = otherhost; 398 break; 399 case TR_RECVING: 400 rectype = "recv"; 401 statfname = pp->stat_recv; 402 sendhost = otherhost; 403 recvhost = thishost; 404 break; 405 case TR_PRINTING: 406 /* copying to a device (presumably local, though things 407 * like 'net/CAP' can confuse this assumption...) */ 408 rectype = "prnt"; 409 statfname = pp->stat_send; 410 sendhost = thishost; 411 recvdev = _PATH_DEFDEVLP; 412 if (pp->lp) recvdev = pp->lp; 413 break; 414 default: 415 /* internal error... should we syslog/printf an error? */ 416 return; 417 } 418 if (statfname == NULL) return; 419 420 /* 421 * the original-host and userid are found out by reading thru the 422 * cf (control-file) for the job. Unfortunately, on incoming jobs 423 * the df's (data-files) are sent before the matching cf, so the 424 * orighost & userid are generally not-available for incoming jobs. 425 * 426 * (it would be nice to create a work-around for that..) 427 */ 428 if (orighost && (*orighost != '\0')) 429 lprhost = orighost; 430 else 431 lprhost = ".na."; 432 if (*userid == '\0') userid = NULL; 433 434 /* 435 * Format of statline. 436 * Some of the keywords listed here are not implemented here, but 437 * they are listed to reserve the meaning for a given keyword. 438 * Fields are separated by a blank. The fields in statline are: 439 * <tstamp> - time the transfer started 440 * <ptrqueue> - name of the printer queue (the short-name...) 441 * <hname> - hostname the file originally came from (the 442 * 'lpr host'), if known, or "_na_" if not known. 443 * <xxx> - id of job from that host (generally three digits) 444 * <n> - file count (# of file within job) 445 * <rectype> - 4-byte field indicating the type of transfer 446 * statistics record. "send" means it's from the 447 * host sending a datafile, "recv" means it's from 448 * a host as it receives a datafile. 449 * user=<userid> - user who sent the job (if known) 450 * secs=<n> - seconds it took to transfer the file 451 * bytes=<n> - number of bytes transfered (ie, "bytecount") 452 * bps=<n.n>e<n> - Bytes/sec (if the transfer was "big enough" 453 * for this to be useful) 454 * ! top=<str> - type of printer (if the type is defined in 455 * printcap, and if this statline is for sending 456 * a file to that ptr) 457 * ! qls=<n> - queue-length at start of send/print-ing a job 458 * ! qle=<n> - queue-length at end of send/print-ing a job 459 * sip=<addr> - IP address of sending host, only included when 460 * receiving a job. 461 * shost=<hname> - sending host (if that does != the original host) 462 * rhost=<hname> - hostname receiving the file (ie, "destination") 463 * rdev=<dev> - device receiving the file, when the file is being 464 * send to a device instead of a remote host. 465 * 466 * Note: A single print job may be transferred multiple times. The 467 * original 'lpr' occurs on one host, and that original host might 468 * send to some interim host (or print server). That interim host 469 * might turn around and send the job to yet another host (most likely 470 * the real printer). The 'shost=' parameter is only included if the 471 * sending host for this particular transfer is NOT the same as the 472 * host which did the original 'lpr'. 473 * 474 * Many values have 'something=' tags before them, because they are 475 * in some sense "optional", or their order may vary. "Optional" may 476 * mean in the sense that different SITES might choose to have other 477 * fields in the record, or that some fields are only included under 478 * some circumstances. Programs processing these records should not 479 * assume the order or existence of any of these keyword fields. 480 */ 481 snprintf(statline, STATLINE_SIZE, "%s %s %s %s %03ld %s", 482 pp->tr_timestr, pp->printer, lprhost, 483 pp->jobnum, pp->jobdfnum, rectype); 484 UPD_EOSTAT(statline); 485 486 if (userid != NULL) { 487 snprintf(eostat, remspace, " user=%s", userid); 488 UPD_EOSTAT(statline); 489 } 490 snprintf(eostat, remspace, " secs=%#.2f bytes=%u", trtime, bytecnt); 491 UPD_EOSTAT(statline); 492 493 /* the bps field duplicates info from bytes and secs, so do not 494 * bother to include it for very small files */ 495 if ((bytecnt > 25000) && (trtime > 1.1)) { 496 snprintf(eostat, remspace, " bps=%#.2e", 497 ((double)bytecnt/trtime)); 498 UPD_EOSTAT(statline); 499 } 500 501 if (sendrecv == TR_RECVING) { 502 if (remspace > 5+strlen(from_ip) ) { 503 snprintf(eostat, remspace, " sip=%s", from_ip); 504 UPD_EOSTAT(statline); 505 } 506 } 507 if (0 != strcmp(lprhost, sendhost)) { 508 if (remspace > 7+strlen(sendhost) ) { 509 snprintf(eostat, remspace, " shost=%s", sendhost); 510 UPD_EOSTAT(statline); 511 } 512 } 513 if (recvhost) { 514 if (remspace > 7+strlen(recvhost) ) { 515 snprintf(eostat, remspace, " rhost=%s", recvhost); 516 UPD_EOSTAT(statline); 517 } 518 } 519 if (recvdev) { 520 if (remspace > 6+strlen(recvdev) ) { 521 snprintf(eostat, remspace, " rdev=%s", recvdev); 522 UPD_EOSTAT(statline); 523 } 524 } 525 if (remspace > 1) { 526 strcpy(eostat, "\n"); 527 } else { 528 /* probably should back up to just before the final " x=".. */ 529 strcpy(statline+STATLINE_SIZE-2, "\n"); 530 } 531 statfile = open(statfname, O_WRONLY|O_APPEND, 0664); 532 if (statfile < 0) { 533 /* statfile was given, but we can't open it. should we 534 * syslog/printf this as an error? */ 535 return; 536 } 537 write(statfile, statline, strlen(statline)); 538 close(statfile); 539 540 return; 541#undef UPD_EOSTAT 542} 543 544#ifdef __STDC__ 545#include <stdarg.h> 546#else 547#include <varargs.h> 548#endif 549 550void 551#ifdef __STDC__ 552fatal(const struct printer *pp, const char *msg, ...) 553#else 554fatal(pp, msg, va_alist) 555 const struct printer *pp; 556 char *msg; 557 va_dcl 558#endif 559{ 560 va_list ap; 561#ifdef __STDC__ 562 va_start(ap, msg); 563#else 564 va_start(ap); 565#endif 566 if (from != host) 567 (void)printf("%s: ", host); 568 (void)printf("%s: ", name); 569 if (pp && pp->printer) 570 (void)printf("%s: ", pp->printer); 571 (void)vprintf(msg, ap); 572 va_end(ap); 573 (void)putchar('\n'); 574 exit(1); 575} 576 577/* 578 * Close all file descriptors from START on up. 579 * This is a horrific kluge, since getdtablesize() might return 580 * ``infinity'', in which case we will be spending a long time 581 * closing ``files'' which were never open. Perhaps it would 582 * be better to close the first N fds, for some small value of N. 583 */ 584void 585closeallfds(start) 586 int start; 587{ 588 int stop = getdtablesize(); 589 for (; start < stop; start++) 590 close(start); 591} 592 593