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