1 /* 2 * Copyright (c) 1998-2005 Sendmail, Inc. and its suppliers. 3 * All rights reserved. 4 * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. 5 * Copyright (c) 1988, 1993 6 * The Regents of the University of California. All rights reserved. 7 * 8 * By using this file, you agree to the terms and conditions set 9 * forth in the LICENSE file which can be found at the top level of 10 * the sendmail distribution. 11 * 12 */ 13 14 #pragma ident "%Z%%M% %I% %E% SMI" 15 16 #include <sendmail.h> 17 #include <sm/sem.h> 18 19 SM_RCSID("@(#)$Id: queue.c,v 8.949 2005/07/21 00:58:33 ca Exp $") 20 21 #include <dirent.h> 22 23 # define RELEASE_QUEUE (void) 0 24 # define ST_INODE(st) (st).st_ino 25 26 # define sm_file_exists(errno) ((errno) == EEXIST) 27 28 # if HASFLOCK && defined(O_EXLOCK) 29 # define SM_OPEN_EXLOCK 1 30 # define TF_OPEN_FLAGS (O_CREAT|O_WRONLY|O_EXCL|O_EXLOCK) 31 # else /* HASFLOCK && defined(O_EXLOCK) */ 32 # define TF_OPEN_FLAGS (O_CREAT|O_WRONLY|O_EXCL) 33 # endif /* HASFLOCK && defined(O_EXLOCK) */ 34 35 #ifndef SM_OPEN_EXLOCK 36 # define SM_OPEN_EXLOCK 0 37 #endif /* ! SM_OPEN_EXLOCK */ 38 39 /* 40 ** Historical notes: 41 ** QF_VERSION == 4 was sendmail 8.10/8.11 without _FFR_QUEUEDELAY 42 ** QF_VERSION == 5 was sendmail 8.10/8.11 with _FFR_QUEUEDELAY 43 ** QF_VERSION == 6 was sendmail 8.12 without _FFR_QUEUEDELAY 44 ** QF_VERSION == 7 was sendmail 8.12 with _FFR_QUEUEDELAY 45 ** QF_VERSION == 8 is sendmail 8.13 46 */ 47 48 #define QF_VERSION 8 /* version number of this queue format */ 49 50 static char queue_letter __P((ENVELOPE *, int)); 51 static bool quarantine_queue_item __P((int, int, ENVELOPE *, char *)); 52 53 /* Naming convention: qgrp: index of queue group, qg: QUEUEGROUP */ 54 55 /* 56 ** Work queue. 57 */ 58 59 struct work 60 { 61 char *w_name; /* name of control file */ 62 char *w_host; /* name of recipient host */ 63 bool w_lock; /* is message locked? */ 64 bool w_tooyoung; /* is it too young to run? */ 65 long w_pri; /* priority of message, see below */ 66 time_t w_ctime; /* creation time */ 67 time_t w_mtime; /* modification time */ 68 int w_qgrp; /* queue group located in */ 69 int w_qdir; /* queue directory located in */ 70 struct work *w_next; /* next in queue */ 71 }; 72 73 typedef struct work WORK; 74 75 static WORK *WorkQ; /* queue of things to be done */ 76 static int NumWorkGroups; /* number of work groups */ 77 static time_t Current_LA_time = 0; 78 79 /* Get new load average every 30 seconds. */ 80 #define GET_NEW_LA_TIME 30 81 82 #define SM_GET_LA(now) \ 83 do \ 84 { \ 85 now = curtime(); \ 86 if (Current_LA_time < now - GET_NEW_LA_TIME) \ 87 { \ 88 sm_getla(); \ 89 Current_LA_time = now; \ 90 } \ 91 } while (0) 92 93 /* 94 ** DoQueueRun indicates that a queue run is needed. 95 ** Notice: DoQueueRun is modified in a signal handler! 96 */ 97 98 static bool volatile DoQueueRun; /* non-interrupt time queue run needed */ 99 100 /* 101 ** Work group definition structure. 102 ** Each work group contains one or more queue groups. This is done 103 ** to manage the number of queue group runners active at the same time 104 ** to be within the constraints of MaxQueueChildren (if it is set). 105 ** The number of queue groups that can be run on the next work run 106 ** is kept track of. The queue groups are run in a round robin. 107 */ 108 109 struct workgrp 110 { 111 int wg_numqgrp; /* number of queue groups in work grp */ 112 int wg_runners; /* total runners */ 113 int wg_curqgrp; /* current queue group */ 114 QUEUEGRP **wg_qgs; /* array of queue groups */ 115 int wg_maxact; /* max # of active runners */ 116 time_t wg_lowqintvl; /* lowest queue interval */ 117 int wg_restart; /* needs restarting? */ 118 int wg_restartcnt; /* count of times restarted */ 119 }; 120 121 typedef struct workgrp WORKGRP; 122 123 static WORKGRP volatile WorkGrp[MAXWORKGROUPS + 1]; /* work groups */ 124 125 #if SM_HEAP_CHECK 126 static SM_DEBUG_T DebugLeakQ = SM_DEBUG_INITIALIZER("leak_q", 127 "@(#)$Debug: leak_q - trace memory leaks during queue processing $"); 128 #endif /* SM_HEAP_CHECK */ 129 130 /* 131 ** We use EmptyString instead of "" to avoid 132 ** 'zero-length format string' warnings from gcc 133 */ 134 135 static const char EmptyString[] = ""; 136 137 static void grow_wlist __P((int, int)); 138 static int multiqueue_cache __P((char *, int, QUEUEGRP *, int, unsigned int *)); 139 static int gatherq __P((int, int, bool, bool *, bool *)); 140 static int sortq __P((int)); 141 static void printctladdr __P((ADDRESS *, SM_FILE_T *)); 142 static bool readqf __P((ENVELOPE *, bool)); 143 static void restart_work_group __P((int)); 144 static void runner_work __P((ENVELOPE *, int, bool, int, int)); 145 static void schedule_queue_runs __P((bool, int, bool)); 146 static char *strrev __P((char *)); 147 static ADDRESS *setctluser __P((char *, int, ENVELOPE *)); 148 #if _FFR_RHS 149 static int sm_strshufflecmp __P((char *, char *)); 150 static void init_shuffle_alphabet __P(()); 151 #endif /* _FFR_RHS */ 152 static int workcmpf0(); 153 static int workcmpf1(); 154 static int workcmpf2(); 155 static int workcmpf3(); 156 static int workcmpf4(); 157 static int randi = 3; /* index for workcmpf5() */ 158 static int workcmpf5(); 159 static int workcmpf6(); 160 #if _FFR_RHS 161 static int workcmpf7(); 162 #endif /* _FFR_RHS */ 163 164 #if RANDOMSHIFT 165 # define get_rand_mod(m) ((get_random() >> RANDOMSHIFT) % (m)) 166 #else /* RANDOMSHIFT */ 167 # define get_rand_mod(m) (get_random() % (m)) 168 #endif /* RANDOMSHIFT */ 169 170 /* 171 ** File system definition. 172 ** Used to keep track of how much free space is available 173 ** on a file system in which one or more queue directories reside. 174 */ 175 176 typedef struct filesys_shared FILESYS; 177 178 struct filesys_shared 179 { 180 dev_t fs_dev; /* unique device id */ 181 long fs_avail; /* number of free blocks available */ 182 long fs_blksize; /* block size, in bytes */ 183 }; 184 185 /* probably kept in shared memory */ 186 static FILESYS FileSys[MAXFILESYS]; /* queue file systems */ 187 static char *FSPath[MAXFILESYS]; /* pathnames for file systems */ 188 189 #if SM_CONF_SHM 190 191 /* 192 ** Shared memory data 193 ** 194 ** Current layout: 195 ** size -- size of shared memory segment 196 ** pid -- pid of owner, should be a unique id to avoid misinterpretations 197 ** by other processes. 198 ** tag -- should be a unique id to avoid misinterpretations by others. 199 ** idea: hash over configuration data that will be stored here. 200 ** NumFileSys -- number of file systems. 201 ** FileSys -- (arrary of) structure for used file systems. 202 ** RSATmpCnt -- counter for number of uses of ephemeral RSA key. 203 ** QShm -- (array of) structure for information about queue directories. 204 */ 205 206 /* 207 ** Queue data in shared memory 208 */ 209 210 typedef struct queue_shared QUEUE_SHM_T; 211 212 struct queue_shared 213 { 214 int qs_entries; /* number of entries */ 215 /* XXX more to follow? */ 216 }; 217 218 static void *Pshm; /* pointer to shared memory */ 219 static FILESYS *PtrFileSys; /* pointer to queue file system array */ 220 int ShmId = SM_SHM_NO_ID; /* shared memory id */ 221 static QUEUE_SHM_T *QShm; /* pointer to shared queue data */ 222 static size_t shms; 223 224 # define SHM_OFF_PID(p) (((char *) (p)) + sizeof(int)) 225 # define SHM_OFF_TAG(p) (((char *) (p)) + sizeof(pid_t) + sizeof(int)) 226 # define SHM_OFF_HEAD (sizeof(pid_t) + sizeof(int) * 2) 227 228 /* how to access FileSys */ 229 # define FILE_SYS(i) (PtrFileSys[i]) 230 231 /* first entry is a tag, for now just the size */ 232 # define OFF_FILE_SYS(p) (((char *) (p)) + SHM_OFF_HEAD) 233 234 /* offset for PNumFileSys */ 235 # define OFF_NUM_FILE_SYS(p) (((char *) (p)) + SHM_OFF_HEAD + sizeof(FileSys)) 236 237 /* offset for PRSATmpCnt */ 238 # define OFF_RSA_TMP_CNT(p) (((char *) (p)) + SHM_OFF_HEAD + sizeof(FileSys) + sizeof(int)) 239 int *PRSATmpCnt; 240 241 /* offset for queue_shm */ 242 # define OFF_QUEUE_SHM(p) (((char *) (p)) + SHM_OFF_HEAD + sizeof(FileSys) + sizeof(int) * 2) 243 244 # define QSHM_ENTRIES(i) QShm[i].qs_entries 245 246 /* basic size of shared memory segment */ 247 # define SM_T_SIZE (SHM_OFF_HEAD + sizeof(FileSys) + sizeof(int) * 2) 248 249 static unsigned int hash_q __P((char *, unsigned int)); 250 251 /* 252 ** HASH_Q -- simple hash function 253 ** 254 ** Parameters: 255 ** p -- string to hash. 256 ** h -- hash start value (from previous run). 257 ** 258 ** Returns: 259 ** hash value. 260 */ 261 262 static unsigned int 263 hash_q(p, h) 264 char *p; 265 unsigned int h; 266 { 267 int c, d; 268 269 while (*p != '\0') 270 { 271 d = *p++; 272 c = d; 273 c ^= c<<6; 274 h += (c<<11) ^ (c>>1); 275 h ^= (d<<14) + (d<<7) + (d<<4) + d; 276 } 277 return h; 278 } 279 280 281 #else /* SM_CONF_SHM */ 282 # define FILE_SYS(i) FileSys[i] 283 #endif /* SM_CONF_SHM */ 284 285 /* access to the various components of file system data */ 286 #define FILE_SYS_NAME(i) FSPath[i] 287 #define FILE_SYS_AVAIL(i) FILE_SYS(i).fs_avail 288 #define FILE_SYS_BLKSIZE(i) FILE_SYS(i).fs_blksize 289 #define FILE_SYS_DEV(i) FILE_SYS(i).fs_dev 290 291 292 /* 293 ** Current qf file field assignments: 294 ** 295 ** A AUTH= parameter 296 ** B body type 297 ** C controlling user 298 ** D data file name 299 ** d data file directory name (added in 8.12) 300 ** E error recipient 301 ** F flag bits 302 ** G free (was: queue delay algorithm if _FFR_QUEUEDELAY) 303 ** H header 304 ** I data file's inode number 305 ** K time of last delivery attempt 306 ** L Solaris Content-Length: header (obsolete) 307 ** M message 308 ** N number of delivery attempts 309 ** P message priority 310 ** q quarantine reason 311 ** Q original recipient (ORCPT=) 312 ** r final recipient (Final-Recipient: DSN field) 313 ** R recipient 314 ** S sender 315 ** T init time 316 ** V queue file version 317 ** X free (was: character set if _FFR_SAVE_CHARSET) 318 ** Y free (was: current delay if _FFR_QUEUEDELAY) 319 ** Z original envelope id from ESMTP 320 ** ! deliver by (added in 8.12) 321 ** $ define macro 322 ** . terminate file 323 */ 324 325 /* 326 ** QUEUEUP -- queue a message up for future transmission. 327 ** 328 ** Parameters: 329 ** e -- the envelope to queue up. 330 ** announce -- if true, tell when you are queueing up. 331 ** msync -- if true, then fsync() if SuperSafe interactive mode. 332 ** 333 ** Returns: 334 ** none. 335 ** 336 ** Side Effects: 337 ** The current request is saved in a control file. 338 ** The queue file is left locked. 339 */ 340 341 void 342 queueup(e, announce, msync) 343 register ENVELOPE *e; 344 bool announce; 345 bool msync; 346 { 347 register SM_FILE_T *tfp; 348 register HDR *h; 349 register ADDRESS *q; 350 int tfd = -1; 351 int i; 352 bool newid; 353 register char *p; 354 MAILER nullmailer; 355 MCI mcibuf; 356 char qf[MAXPATHLEN]; 357 char tf[MAXPATHLEN]; 358 char df[MAXPATHLEN]; 359 char buf[MAXLINE]; 360 361 /* 362 ** Create control file. 363 */ 364 365 #define OPEN_TF do \ 366 { \ 367 MODE_T oldumask = 0; \ 368 \ 369 if (bitset(S_IWGRP, QueueFileMode)) \ 370 oldumask = umask(002); \ 371 tfd = open(tf, TF_OPEN_FLAGS, QueueFileMode); \ 372 if (bitset(S_IWGRP, QueueFileMode)) \ 373 (void) umask(oldumask); \ 374 } while (0) 375 376 377 newid = (e->e_id == NULL) || !bitset(EF_INQUEUE, e->e_flags); 378 (void) sm_strlcpy(tf, queuename(e, NEWQFL_LETTER), sizeof tf); 379 tfp = e->e_lockfp; 380 if (tfp == NULL && newid) 381 { 382 /* 383 ** open qf file directly: this will give an error if the file 384 ** already exists and hence prevent problems if a queue-id 385 ** is reused (e.g., because the clock is set back). 386 */ 387 388 (void) sm_strlcpy(tf, queuename(e, ANYQFL_LETTER), sizeof tf); 389 OPEN_TF; 390 if (tfd < 0 || 391 #if !SM_OPEN_EXLOCK 392 !lockfile(tfd, tf, NULL, LOCK_EX|LOCK_NB) || 393 #endif /* !SM_OPEN_EXLOCK */ 394 (tfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, 395 (void *) &tfd, SM_IO_WRONLY, 396 NULL)) == NULL) 397 { 398 int save_errno = errno; 399 400 printopenfds(true); 401 errno = save_errno; 402 syserr("!queueup: cannot create queue file %s, euid=%d, fd=%d, fp=%p", 403 tf, (int) geteuid(), tfd, tfp); 404 /* NOTREACHED */ 405 } 406 e->e_lockfp = tfp; 407 upd_qs(e, 1, 0, "queueup"); 408 } 409 410 /* if newid, write the queue file directly (instead of temp file) */ 411 if (!newid) 412 { 413 /* get a locked tf file */ 414 for (i = 0; i < 128; i++) 415 { 416 if (tfd < 0) 417 { 418 OPEN_TF; 419 if (tfd < 0) 420 { 421 if (errno != EEXIST) 422 break; 423 if (LogLevel > 0 && (i % 32) == 0) 424 sm_syslog(LOG_ALERT, e->e_id, 425 "queueup: cannot create %s, uid=%d: %s", 426 tf, (int) geteuid(), 427 sm_errstring(errno)); 428 } 429 #if SM_OPEN_EXLOCK 430 else 431 break; 432 #endif /* SM_OPEN_EXLOCK */ 433 } 434 if (tfd >= 0) 435 { 436 #if SM_OPEN_EXLOCK 437 /* file is locked by open() */ 438 break; 439 #else /* SM_OPEN_EXLOCK */ 440 if (lockfile(tfd, tf, NULL, LOCK_EX|LOCK_NB)) 441 break; 442 else 443 #endif /* SM_OPEN_EXLOCK */ 444 if (LogLevel > 0 && (i % 32) == 0) 445 sm_syslog(LOG_ALERT, e->e_id, 446 "queueup: cannot lock %s: %s", 447 tf, sm_errstring(errno)); 448 if ((i % 32) == 31) 449 { 450 (void) close(tfd); 451 tfd = -1; 452 } 453 } 454 455 if ((i % 32) == 31) 456 { 457 /* save the old temp file away */ 458 (void) rename(tf, queuename(e, TEMPQF_LETTER)); 459 } 460 else 461 (void) sleep(i % 32); 462 } 463 if (tfd < 0 || (tfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, 464 (void *) &tfd, SM_IO_WRONLY_B, 465 NULL)) == NULL) 466 { 467 int save_errno = errno; 468 469 printopenfds(true); 470 errno = save_errno; 471 syserr("!queueup: cannot create queue temp file %s, uid=%d", 472 tf, (int) geteuid()); 473 } 474 } 475 476 if (tTd(40, 1)) 477 sm_dprintf("\n>>>>> queueing %s/%s%s >>>>>\n", 478 qid_printqueue(e->e_qgrp, e->e_qdir), 479 queuename(e, ANYQFL_LETTER), 480 newid ? " (new id)" : ""); 481 if (tTd(40, 3)) 482 { 483 sm_dprintf(" e_flags="); 484 printenvflags(e); 485 } 486 if (tTd(40, 32)) 487 { 488 sm_dprintf(" sendq="); 489 printaddr(sm_debug_file(), e->e_sendqueue, true); 490 } 491 if (tTd(40, 9)) 492 { 493 sm_dprintf(" tfp="); 494 dumpfd(sm_io_getinfo(tfp, SM_IO_WHAT_FD, NULL), true, false); 495 sm_dprintf(" lockfp="); 496 if (e->e_lockfp == NULL) 497 sm_dprintf("NULL\n"); 498 else 499 dumpfd(sm_io_getinfo(e->e_lockfp, SM_IO_WHAT_FD, NULL), 500 true, false); 501 } 502 503 /* 504 ** If there is no data file yet, create one. 505 */ 506 507 (void) sm_strlcpy(df, queuename(e, DATAFL_LETTER), sizeof df); 508 if (bitset(EF_HAS_DF, e->e_flags)) 509 { 510 if (e->e_dfp != NULL && 511 SuperSafe != SAFE_REALLY && 512 SuperSafe != SAFE_REALLY_POSTMILTER && 513 sm_io_setinfo(e->e_dfp, SM_BF_COMMIT, NULL) < 0 && 514 errno != EINVAL) 515 { 516 syserr("!queueup: cannot commit data file %s, uid=%d", 517 queuename(e, DATAFL_LETTER), (int) geteuid()); 518 } 519 if (e->e_dfp != NULL && 520 SuperSafe == SAFE_INTERACTIVE && msync) 521 { 522 if (tTd(40,32)) 523 sm_syslog(LOG_INFO, e->e_id, 524 "queueup: fsync(e->e_dfp)"); 525 526 if (fsync(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, 527 NULL)) < 0) 528 { 529 if (newid) 530 syserr("!552 Error writing data file %s", 531 df); 532 else 533 syserr("!452 Error writing data file %s", 534 df); 535 } 536 } 537 } 538 else 539 { 540 int dfd; 541 MODE_T oldumask = 0; 542 register SM_FILE_T *dfp = NULL; 543 struct stat stbuf; 544 545 if (e->e_dfp != NULL && 546 sm_io_getinfo(e->e_dfp, SM_IO_WHAT_ISTYPE, BF_FILE_TYPE)) 547 syserr("committing over bf file"); 548 549 if (bitset(S_IWGRP, QueueFileMode)) 550 oldumask = umask(002); 551 dfd = open(df, O_WRONLY|O_CREAT|O_TRUNC|QF_O_EXTRA, 552 QueueFileMode); 553 if (bitset(S_IWGRP, QueueFileMode)) 554 (void) umask(oldumask); 555 if (dfd < 0 || (dfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, 556 (void *) &dfd, SM_IO_WRONLY_B, 557 NULL)) == NULL) 558 syserr("!queueup: cannot create data temp file %s, uid=%d", 559 df, (int) geteuid()); 560 if (fstat(dfd, &stbuf) < 0) 561 e->e_dfino = -1; 562 else 563 { 564 e->e_dfdev = stbuf.st_dev; 565 e->e_dfino = ST_INODE(stbuf); 566 } 567 e->e_flags |= EF_HAS_DF; 568 memset(&mcibuf, '\0', sizeof mcibuf); 569 mcibuf.mci_out = dfp; 570 mcibuf.mci_mailer = FileMailer; 571 (*e->e_putbody)(&mcibuf, e, NULL); 572 573 if (SuperSafe == SAFE_REALLY || 574 SuperSafe == SAFE_REALLY_POSTMILTER || 575 (SuperSafe == SAFE_INTERACTIVE && msync)) 576 { 577 if (tTd(40,32)) 578 sm_syslog(LOG_INFO, e->e_id, 579 "queueup: fsync(dfp)"); 580 581 if (fsync(sm_io_getinfo(dfp, SM_IO_WHAT_FD, NULL)) < 0) 582 { 583 if (newid) 584 syserr("!552 Error writing data file %s", 585 df); 586 else 587 syserr("!452 Error writing data file %s", 588 df); 589 } 590 } 591 592 if (sm_io_close(dfp, SM_TIME_DEFAULT) < 0) 593 syserr("!queueup: cannot save data temp file %s, uid=%d", 594 df, (int) geteuid()); 595 e->e_putbody = putbody; 596 } 597 598 /* 599 ** Output future work requests. 600 ** Priority and creation time should be first, since 601 ** they are required by gatherq. 602 */ 603 604 /* output queue version number (must be first!) */ 605 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "V%d\n", QF_VERSION); 606 607 /* output creation time */ 608 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "T%ld\n", (long) e->e_ctime); 609 610 /* output last delivery time */ 611 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "K%ld\n", (long) e->e_dtime); 612 613 /* output number of delivery attempts */ 614 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "N%d\n", e->e_ntries); 615 616 /* output message priority */ 617 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "P%ld\n", e->e_msgpriority); 618 619 /* 620 ** If data file is in a different directory than the queue file, 621 ** output a "d" record naming the directory of the data file. 622 */ 623 624 if (e->e_dfqgrp != e->e_qgrp) 625 { 626 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "d%s\n", 627 Queue[e->e_dfqgrp]->qg_qpaths[e->e_dfqdir].qp_name); 628 } 629 630 /* output inode number of data file */ 631 /* XXX should probably include device major/minor too */ 632 if (e->e_dfino != -1) 633 { 634 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "I%ld/%ld/%llu\n", 635 (long) major(e->e_dfdev), 636 (long) minor(e->e_dfdev), 637 (ULONGLONG_T) e->e_dfino); 638 } 639 640 /* output body type */ 641 if (e->e_bodytype != NULL) 642 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "B%s\n", 643 denlstring(e->e_bodytype, true, false)); 644 645 /* quarantine reason */ 646 if (e->e_quarmsg != NULL) 647 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "q%s\n", 648 denlstring(e->e_quarmsg, true, false)); 649 650 /* message from envelope, if it exists */ 651 if (e->e_message != NULL) 652 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "M%s\n", 653 denlstring(e->e_message, true, false)); 654 655 /* send various flag bits through */ 656 p = buf; 657 if (bitset(EF_WARNING, e->e_flags)) 658 *p++ = 'w'; 659 if (bitset(EF_RESPONSE, e->e_flags)) 660 *p++ = 'r'; 661 if (bitset(EF_HAS8BIT, e->e_flags)) 662 *p++ = '8'; 663 if (bitset(EF_DELETE_BCC, e->e_flags)) 664 *p++ = 'b'; 665 if (bitset(EF_RET_PARAM, e->e_flags)) 666 *p++ = 'd'; 667 if (bitset(EF_NO_BODY_RETN, e->e_flags)) 668 *p++ = 'n'; 669 if (bitset(EF_SPLIT, e->e_flags)) 670 *p++ = 's'; 671 *p++ = '\0'; 672 if (buf[0] != '\0') 673 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "F%s\n", buf); 674 675 /* save $={persistentMacros} macro values */ 676 queueup_macros(macid("{persistentMacros}"), tfp, e); 677 678 /* output name of sender */ 679 if (bitnset(M_UDBENVELOPE, e->e_from.q_mailer->m_flags)) 680 p = e->e_sender; 681 else 682 p = e->e_from.q_paddr; 683 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "S%s\n", 684 denlstring(p, true, false)); 685 686 /* output ESMTP-supplied "original" information */ 687 if (e->e_envid != NULL) 688 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "Z%s\n", 689 denlstring(e->e_envid, true, false)); 690 691 /* output AUTH= parameter */ 692 if (e->e_auth_param != NULL) 693 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "A%s\n", 694 denlstring(e->e_auth_param, true, false)); 695 if (e->e_dlvr_flag != 0) 696 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "!%c %ld\n", 697 (char) e->e_dlvr_flag, e->e_deliver_by); 698 699 /* output list of recipient addresses */ 700 printctladdr(NULL, NULL); 701 for (q = e->e_sendqueue; q != NULL; q = q->q_next) 702 { 703 if (!QS_IS_UNDELIVERED(q->q_state)) 704 continue; 705 706 /* message for this recipient, if it exists */ 707 if (q->q_message != NULL) 708 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "M%s\n", 709 denlstring(q->q_message, true, 710 false)); 711 712 printctladdr(q, tfp); 713 if (q->q_orcpt != NULL) 714 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "Q%s\n", 715 denlstring(q->q_orcpt, true, 716 false)); 717 if (q->q_finalrcpt != NULL) 718 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "r%s\n", 719 denlstring(q->q_finalrcpt, true, 720 false)); 721 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'R'); 722 if (bitset(QPRIMARY, q->q_flags)) 723 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'P'); 724 if (bitset(QHASNOTIFY, q->q_flags)) 725 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'N'); 726 if (bitset(QPINGONSUCCESS, q->q_flags)) 727 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'S'); 728 if (bitset(QPINGONFAILURE, q->q_flags)) 729 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'F'); 730 if (bitset(QPINGONDELAY, q->q_flags)) 731 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'D'); 732 if (q->q_alias != NULL && 733 bitset(QALIAS, q->q_alias->q_flags)) 734 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 'A'); 735 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, ':'); 736 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "%s\n", 737 denlstring(q->q_paddr, true, false)); 738 if (announce) 739 { 740 char *tag = "queued"; 741 742 if (e->e_quarmsg != NULL) 743 tag = "quarantined"; 744 745 e->e_to = q->q_paddr; 746 message(tag); 747 if (LogLevel > 8) 748 logdelivery(q->q_mailer, NULL, q->q_status, 749 tag, NULL, (time_t) 0, e); 750 e->e_to = NULL; 751 } 752 if (tTd(40, 1)) 753 { 754 sm_dprintf("queueing "); 755 printaddr(sm_debug_file(), q, false); 756 } 757 } 758 759 /* 760 ** Output headers for this message. 761 ** Expand macros completely here. Queue run will deal with 762 ** everything as absolute headers. 763 ** All headers that must be relative to the recipient 764 ** can be cracked later. 765 ** We set up a "null mailer" -- i.e., a mailer that will have 766 ** no effect on the addresses as they are output. 767 */ 768 769 memset((char *) &nullmailer, '\0', sizeof nullmailer); 770 nullmailer.m_re_rwset = nullmailer.m_rh_rwset = 771 nullmailer.m_se_rwset = nullmailer.m_sh_rwset = -1; 772 nullmailer.m_eol = "\n"; 773 memset(&mcibuf, '\0', sizeof mcibuf); 774 mcibuf.mci_mailer = &nullmailer; 775 mcibuf.mci_out = tfp; 776 777 macdefine(&e->e_macro, A_PERM, 'g', "\201f"); 778 for (h = e->e_header; h != NULL; h = h->h_link) 779 { 780 if (h->h_value == NULL) 781 continue; 782 783 /* don't output resent headers on non-resent messages */ 784 if (bitset(H_RESENT, h->h_flags) && 785 !bitset(EF_RESENT, e->e_flags)) 786 continue; 787 788 /* expand macros; if null, don't output header at all */ 789 if (bitset(H_DEFAULT, h->h_flags)) 790 { 791 (void) expand(h->h_value, buf, sizeof buf, e); 792 if (buf[0] == '\0') 793 continue; 794 } 795 796 /* output this header */ 797 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "H?"); 798 799 /* output conditional macro if present */ 800 if (h->h_macro != '\0') 801 { 802 if (bitset(0200, h->h_macro)) 803 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, 804 "${%s}", 805 macname(bitidx(h->h_macro))); 806 else 807 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, 808 "$%c", h->h_macro); 809 } 810 else if (!bitzerop(h->h_mflags) && 811 bitset(H_CHECK|H_ACHECK, h->h_flags)) 812 { 813 int j; 814 815 /* if conditional, output the set of conditions */ 816 for (j = '\0'; j <= '\177'; j++) 817 if (bitnset(j, h->h_mflags)) 818 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, 819 j); 820 } 821 (void) sm_io_putc(tfp, SM_TIME_DEFAULT, '?'); 822 823 /* output the header: expand macros, convert addresses */ 824 if (bitset(H_DEFAULT, h->h_flags) && 825 !bitset(H_BINDLATE, h->h_flags)) 826 { 827 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "%s: %s\n", 828 h->h_field, 829 denlstring(buf, false, true)); 830 } 831 else if (bitset(H_FROM|H_RCPT, h->h_flags) && 832 !bitset(H_BINDLATE, h->h_flags)) 833 { 834 bool oldstyle = bitset(EF_OLDSTYLE, e->e_flags); 835 SM_FILE_T *savetrace = TrafficLogFile; 836 837 TrafficLogFile = NULL; 838 839 if (bitset(H_FROM, h->h_flags)) 840 oldstyle = false; 841 842 commaize(h, h->h_value, oldstyle, &mcibuf, e); 843 844 TrafficLogFile = savetrace; 845 } 846 else 847 { 848 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "%s: %s\n", 849 h->h_field, 850 denlstring(h->h_value, false, 851 true)); 852 } 853 } 854 855 /* 856 ** Clean up. 857 ** 858 ** Write a terminator record -- this is to prevent 859 ** scurrilous crackers from appending any data. 860 */ 861 862 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, ".\n"); 863 864 if (sm_io_flush(tfp, SM_TIME_DEFAULT) != 0 || 865 ((SuperSafe == SAFE_REALLY || 866 SuperSafe == SAFE_REALLY_POSTMILTER || 867 (SuperSafe == SAFE_INTERACTIVE && msync)) && 868 fsync(sm_io_getinfo(tfp, SM_IO_WHAT_FD, NULL)) < 0) || 869 sm_io_error(tfp)) 870 { 871 if (newid) 872 syserr("!552 Error writing control file %s", tf); 873 else 874 syserr("!452 Error writing control file %s", tf); 875 } 876 877 if (!newid) 878 { 879 char new = queue_letter(e, ANYQFL_LETTER); 880 881 /* rename (locked) tf to be (locked) [qh]f */ 882 (void) sm_strlcpy(qf, queuename(e, ANYQFL_LETTER), 883 sizeof qf); 884 if (rename(tf, qf) < 0) 885 syserr("cannot rename(%s, %s), uid=%d", 886 tf, qf, (int) geteuid()); 887 else 888 { 889 /* 890 ** Check if type has changed and only 891 ** remove the old item if the rename above 892 ** succeeded. 893 */ 894 895 if (e->e_qfletter != '\0' && 896 e->e_qfletter != new) 897 { 898 if (tTd(40, 5)) 899 { 900 sm_dprintf("type changed from %c to %c\n", 901 e->e_qfletter, new); 902 } 903 904 if (unlink(queuename(e, e->e_qfletter)) < 0) 905 { 906 /* XXX: something more drastic? */ 907 if (LogLevel > 0) 908 sm_syslog(LOG_ERR, e->e_id, 909 "queueup: unlink(%s) failed: %s", 910 queuename(e, e->e_qfletter), 911 sm_errstring(errno)); 912 } 913 } 914 } 915 e->e_qfletter = new; 916 917 /* 918 ** fsync() after renaming to make sure metadata is 919 ** written to disk on filesystems in which renames are 920 ** not guaranteed. 921 */ 922 923 if (SuperSafe != SAFE_NO) 924 { 925 /* for softupdates */ 926 if (tfd >= 0 && fsync(tfd) < 0) 927 { 928 syserr("!queueup: cannot fsync queue temp file %s", 929 tf); 930 } 931 SYNC_DIR(qf, true); 932 } 933 934 /* close and unlock old (locked) queue file */ 935 if (e->e_lockfp != NULL) 936 (void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT); 937 e->e_lockfp = tfp; 938 939 /* save log info */ 940 if (LogLevel > 79) 941 sm_syslog(LOG_DEBUG, e->e_id, "queueup %s", qf); 942 } 943 else 944 { 945 /* save log info */ 946 if (LogLevel > 79) 947 sm_syslog(LOG_DEBUG, e->e_id, "queueup %s", tf); 948 949 e->e_qfletter = queue_letter(e, ANYQFL_LETTER); 950 } 951 952 errno = 0; 953 e->e_flags |= EF_INQUEUE; 954 955 if (tTd(40, 1)) 956 sm_dprintf("<<<<< done queueing %s <<<<<\n\n", e->e_id); 957 return; 958 } 959 960 /* 961 ** PRINTCTLADDR -- print control address to file. 962 ** 963 ** Parameters: 964 ** a -- address. 965 ** tfp -- file pointer. 966 ** 967 ** Returns: 968 ** none. 969 ** 970 ** Side Effects: 971 ** The control address (if changed) is printed to the file. 972 ** The last control address and uid are saved. 973 */ 974 975 static void 976 printctladdr(a, tfp) 977 register ADDRESS *a; 978 SM_FILE_T *tfp; 979 { 980 char *user; 981 register ADDRESS *q; 982 uid_t uid; 983 gid_t gid; 984 static ADDRESS *lastctladdr = NULL; 985 static uid_t lastuid; 986 987 /* initialization */ 988 if (a == NULL || a->q_alias == NULL || tfp == NULL) 989 { 990 if (lastctladdr != NULL && tfp != NULL) 991 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "C\n"); 992 lastctladdr = NULL; 993 lastuid = 0; 994 return; 995 } 996 997 /* find the active uid */ 998 q = getctladdr(a); 999 if (q == NULL) 1000 { 1001 user = NULL; 1002 uid = 0; 1003 gid = 0; 1004 } 1005 else 1006 { 1007 user = q->q_ruser != NULL ? q->q_ruser : q->q_user; 1008 uid = q->q_uid; 1009 gid = q->q_gid; 1010 } 1011 a = a->q_alias; 1012 1013 /* check to see if this is the same as last time */ 1014 if (lastctladdr != NULL && uid == lastuid && 1015 strcmp(lastctladdr->q_paddr, a->q_paddr) == 0) 1016 return; 1017 lastuid = uid; 1018 lastctladdr = a; 1019 1020 if (uid == 0 || user == NULL || user[0] == '\0') 1021 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "C"); 1022 else 1023 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, "C%s:%ld:%ld", 1024 denlstring(user, true, false), (long) uid, 1025 (long) gid); 1026 (void) sm_io_fprintf(tfp, SM_TIME_DEFAULT, ":%s\n", 1027 denlstring(a->q_paddr, true, false)); 1028 } 1029 1030 /* 1031 ** RUNNERS_SIGTERM -- propagate a SIGTERM to queue runner process 1032 ** 1033 ** This propagates the signal to the child processes that are queue 1034 ** runners. This is for a queue runner "cleanup". After all of the 1035 ** child queue runner processes are signaled (it should be SIGTERM 1036 ** being the sig) then the old signal handler (Oldsh) is called 1037 ** to handle any cleanup set for this process (provided it is not 1038 ** SIG_DFL or SIG_IGN). The signal may not be handled immediately 1039 ** if the BlockOldsh flag is set. If the current process doesn't 1040 ** have a parent then handle the signal immediately, regardless of 1041 ** BlockOldsh. 1042 ** 1043 ** Parameters: 1044 ** sig -- the signal number being sent 1045 ** 1046 ** Returns: 1047 ** none. 1048 ** 1049 ** Side Effects: 1050 ** Sets the NoMoreRunners boolean to true to stop more runners 1051 ** from being started in runqueue(). 1052 ** 1053 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD 1054 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE 1055 ** DOING. 1056 */ 1057 1058 static bool volatile NoMoreRunners = false; 1059 static sigfunc_t Oldsh_term = SIG_DFL; 1060 static sigfunc_t Oldsh_hup = SIG_DFL; 1061 static sigfunc_t volatile Oldsh = SIG_DFL; 1062 static bool BlockOldsh = false; 1063 static int volatile Oldsig = 0; 1064 static SIGFUNC_DECL runners_sigterm __P((int)); 1065 static SIGFUNC_DECL runners_sighup __P((int)); 1066 1067 static SIGFUNC_DECL 1068 runners_sigterm(sig) 1069 int sig; 1070 { 1071 int save_errno = errno; 1072 1073 FIX_SYSV_SIGNAL(sig, runners_sigterm); 1074 errno = save_errno; 1075 CHECK_CRITICAL(sig); 1076 NoMoreRunners = true; 1077 Oldsh = Oldsh_term; 1078 Oldsig = sig; 1079 proc_list_signal(PROC_QUEUE, sig); 1080 1081 if (!BlockOldsh || getppid() <= 1) 1082 { 1083 /* Check that a valid 'old signal handler' is callable */ 1084 if (Oldsh_term != SIG_DFL && Oldsh_term != SIG_IGN && 1085 Oldsh_term != runners_sigterm) 1086 (*Oldsh_term)(sig); 1087 } 1088 errno = save_errno; 1089 return SIGFUNC_RETURN; 1090 } 1091 /* 1092 ** RUNNERS_SIGHUP -- propagate a SIGHUP to queue runner process 1093 ** 1094 ** This propagates the signal to the child processes that are queue 1095 ** runners. This is for a queue runner "cleanup". After all of the 1096 ** child queue runner processes are signaled (it should be SIGHUP 1097 ** being the sig) then the old signal handler (Oldsh) is called to 1098 ** handle any cleanup set for this process (provided it is not SIG_DFL 1099 ** or SIG_IGN). The signal may not be handled immediately if the 1100 ** BlockOldsh flag is set. If the current process doesn't have 1101 ** a parent then handle the signal immediately, regardless of 1102 ** BlockOldsh. 1103 ** 1104 ** Parameters: 1105 ** sig -- the signal number being sent 1106 ** 1107 ** Returns: 1108 ** none. 1109 ** 1110 ** Side Effects: 1111 ** Sets the NoMoreRunners boolean to true to stop more runners 1112 ** from being started in runqueue(). 1113 ** 1114 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD 1115 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE 1116 ** DOING. 1117 */ 1118 1119 static SIGFUNC_DECL 1120 runners_sighup(sig) 1121 int sig; 1122 { 1123 int save_errno = errno; 1124 1125 FIX_SYSV_SIGNAL(sig, runners_sighup); 1126 errno = save_errno; 1127 CHECK_CRITICAL(sig); 1128 NoMoreRunners = true; 1129 Oldsh = Oldsh_hup; 1130 Oldsig = sig; 1131 proc_list_signal(PROC_QUEUE, sig); 1132 1133 if (!BlockOldsh || getppid() <= 1) 1134 { 1135 /* Check that a valid 'old signal handler' is callable */ 1136 if (Oldsh_hup != SIG_DFL && Oldsh_hup != SIG_IGN && 1137 Oldsh_hup != runners_sighup) 1138 (*Oldsh_hup)(sig); 1139 } 1140 errno = save_errno; 1141 return SIGFUNC_RETURN; 1142 } 1143 /* 1144 ** MARK_WORK_GROUP_RESTART -- mark a work group as needing a restart 1145 ** 1146 ** Sets a workgroup for restarting. 1147 ** 1148 ** Parameters: 1149 ** wgrp -- the work group id to restart. 1150 ** reason -- why (signal?), -1 to turn off restart 1151 ** 1152 ** Returns: 1153 ** none. 1154 ** 1155 ** Side effects: 1156 ** May set global RestartWorkGroup to true. 1157 ** 1158 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD 1159 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE 1160 ** DOING. 1161 */ 1162 1163 void 1164 mark_work_group_restart(wgrp, reason) 1165 int wgrp; 1166 int reason; 1167 { 1168 if (wgrp < 0 || wgrp > NumWorkGroups) 1169 return; 1170 1171 WorkGrp[wgrp].wg_restart = reason; 1172 if (reason >= 0) 1173 RestartWorkGroup = true; 1174 } 1175 /* 1176 ** RESTART_MARKED_WORK_GROUPS -- restart work groups marked as needing restart 1177 ** 1178 ** Restart any workgroup marked as needing a restart provided more 1179 ** runners are allowed. 1180 ** 1181 ** Parameters: 1182 ** none. 1183 ** 1184 ** Returns: 1185 ** none. 1186 ** 1187 ** Side effects: 1188 ** Sets global RestartWorkGroup to false. 1189 */ 1190 1191 void 1192 restart_marked_work_groups() 1193 { 1194 int i; 1195 int wasblocked; 1196 1197 if (NoMoreRunners) 1198 return; 1199 1200 /* Block SIGCHLD so reapchild() doesn't mess with us */ 1201 wasblocked = sm_blocksignal(SIGCHLD); 1202 1203 for (i = 0; i < NumWorkGroups; i++) 1204 { 1205 if (WorkGrp[i].wg_restart >= 0) 1206 { 1207 if (LogLevel > 8) 1208 sm_syslog(LOG_ERR, NOQID, 1209 "restart queue runner=%d due to signal 0x%x", 1210 i, WorkGrp[i].wg_restart); 1211 restart_work_group(i); 1212 } 1213 } 1214 RestartWorkGroup = false; 1215 1216 if (wasblocked == 0) 1217 (void) sm_releasesignal(SIGCHLD); 1218 } 1219 /* 1220 ** RESTART_WORK_GROUP -- restart a specific work group 1221 ** 1222 ** Restart a specific workgroup provided more runners are allowed. 1223 ** If the requested work group has been restarted too many times log 1224 ** this and refuse to restart. 1225 ** 1226 ** Parameters: 1227 ** wgrp -- the work group id to restart 1228 ** 1229 ** Returns: 1230 ** none. 1231 ** 1232 ** Side Effects: 1233 ** starts another process doing the work of wgrp 1234 */ 1235 1236 #define MAX_PERSIST_RESTART 10 /* max allowed number of restarts */ 1237 1238 static void 1239 restart_work_group(wgrp) 1240 int wgrp; 1241 { 1242 if (NoMoreRunners || 1243 wgrp < 0 || wgrp > NumWorkGroups) 1244 return; 1245 1246 WorkGrp[wgrp].wg_restart = -1; 1247 if (WorkGrp[wgrp].wg_restartcnt < MAX_PERSIST_RESTART) 1248 { 1249 /* avoid overflow; increment here */ 1250 WorkGrp[wgrp].wg_restartcnt++; 1251 (void) run_work_group(wgrp, RWG_FORK|RWG_PERSISTENT|RWG_RUNALL); 1252 } 1253 else 1254 { 1255 sm_syslog(LOG_ERR, NOQID, 1256 "ERROR: persistent queue runner=%d restarted too many times, queue runner lost", 1257 wgrp); 1258 } 1259 } 1260 /* 1261 ** SCHEDULE_QUEUE_RUNS -- schedule the next queue run for a work group. 1262 ** 1263 ** Parameters: 1264 ** runall -- schedule even if individual bit is not set. 1265 ** wgrp -- the work group id to schedule. 1266 ** didit -- the queue run was performed for this work group. 1267 ** 1268 ** Returns: 1269 ** nothing 1270 */ 1271 1272 #define INCR_MOD(v, m) if (++v >= m) \ 1273 v = 0; \ 1274 else 1275 1276 static void 1277 schedule_queue_runs(runall, wgrp, didit) 1278 bool runall; 1279 int wgrp; 1280 bool didit; 1281 { 1282 int qgrp, cgrp, endgrp; 1283 #if _FFR_QUEUE_SCHED_DBG 1284 time_t lastsched; 1285 bool sched; 1286 #endif /* _FFR_QUEUE_SCHED_DBG */ 1287 time_t now; 1288 time_t minqintvl; 1289 1290 /* 1291 ** This is a bit ugly since we have to duplicate the 1292 ** code that "walks" through a work queue group. 1293 */ 1294 1295 now = curtime(); 1296 minqintvl = 0; 1297 cgrp = endgrp = WorkGrp[wgrp].wg_curqgrp; 1298 do 1299 { 1300 time_t qintvl; 1301 1302 #if _FFR_QUEUE_SCHED_DBG 1303 lastsched = 0; 1304 sched = false; 1305 #endif /* _FFR_QUEUE_SCHED_DBG */ 1306 qgrp = WorkGrp[wgrp].wg_qgs[cgrp]->qg_index; 1307 if (Queue[qgrp]->qg_queueintvl > 0) 1308 qintvl = Queue[qgrp]->qg_queueintvl; 1309 else if (QueueIntvl > 0) 1310 qintvl = QueueIntvl; 1311 else 1312 qintvl = (time_t) 0; 1313 #if _FFR_QUEUE_SCHED_DBG 1314 lastsched = Queue[qgrp]->qg_nextrun; 1315 #endif /* _FFR_QUEUE_SCHED_DBG */ 1316 if ((runall || Queue[qgrp]->qg_nextrun <= now) && qintvl > 0) 1317 { 1318 #if _FFR_QUEUE_SCHED_DBG 1319 sched = true; 1320 #endif /* _FFR_QUEUE_SCHED_DBG */ 1321 if (minqintvl == 0 || qintvl < minqintvl) 1322 minqintvl = qintvl; 1323 1324 /* 1325 ** Only set a new time if a queue run was performed 1326 ** for this queue group. If the queue was not run, 1327 ** we could starve it by setting a new time on each 1328 ** call. 1329 */ 1330 1331 if (didit) 1332 Queue[qgrp]->qg_nextrun += qintvl; 1333 } 1334 #if _FFR_QUEUE_SCHED_DBG 1335 if (tTd(69, 10)) 1336 sm_syslog(LOG_INFO, NOQID, 1337 "sqr: wgrp=%d, cgrp=%d, qgrp=%d, intvl=%ld, QI=%ld, runall=%d, lastrun=%ld, nextrun=%ld, sched=%d", 1338 wgrp, cgrp, qgrp, Queue[qgrp]->qg_queueintvl, 1339 QueueIntvl, runall, lastsched, 1340 Queue[qgrp]->qg_nextrun, sched); 1341 #endif /* _FFR_QUEUE_SCHED_DBG */ 1342 INCR_MOD(cgrp, WorkGrp[wgrp].wg_numqgrp); 1343 } while (endgrp != cgrp); 1344 if (minqintvl > 0) 1345 (void) sm_setevent(minqintvl, runqueueevent, 0); 1346 } 1347 1348 #if _FFR_QUEUE_RUN_PARANOIA 1349 /* 1350 ** CHECKQUEUERUNNER -- check whether a queue group hasn't been run. 1351 ** 1352 ** Use this if events may get lost and hence queue runners may not 1353 ** be started and mail will pile up in a queue. 1354 ** 1355 ** Parameters: 1356 ** none. 1357 ** 1358 ** Returns: 1359 ** true if a queue run is necessary. 1360 ** 1361 ** Side Effects: 1362 ** may schedule a queue run. 1363 */ 1364 1365 bool 1366 checkqueuerunner() 1367 { 1368 int qgrp; 1369 time_t now, minqintvl; 1370 1371 now = curtime(); 1372 minqintvl = 0; 1373 for (qgrp = 0; qgrp < NumQueue && Queue[qgrp] != NULL; qgrp++) 1374 { 1375 time_t qintvl; 1376 1377 if (Queue[qgrp]->qg_queueintvl > 0) 1378 qintvl = Queue[qgrp]->qg_queueintvl; 1379 else if (QueueIntvl > 0) 1380 qintvl = QueueIntvl; 1381 else 1382 qintvl = (time_t) 0; 1383 if (Queue[qgrp]->qg_nextrun <= now - qintvl) 1384 { 1385 if (minqintvl == 0 || qintvl < minqintvl) 1386 minqintvl = qintvl; 1387 if (LogLevel > 1) 1388 sm_syslog(LOG_WARNING, NOQID, 1389 "checkqueuerunner: queue %d should have been run at %s, queue interval %ld", 1390 qgrp, 1391 arpadate(ctime(&Queue[qgrp]->qg_nextrun)), 1392 qintvl); 1393 } 1394 } 1395 if (minqintvl > 0) 1396 { 1397 (void) sm_setevent(minqintvl, runqueueevent, 0); 1398 return true; 1399 } 1400 return false; 1401 } 1402 #endif /* _FFR_QUEUE_RUN_PARANOIA */ 1403 1404 /* 1405 ** RUNQUEUE -- run the jobs in the queue. 1406 ** 1407 ** Gets the stuff out of the queue in some presumably logical 1408 ** order and processes them. 1409 ** 1410 ** Parameters: 1411 ** forkflag -- true if the queue scanning should be done in 1412 ** a child process. We double-fork so it is not our 1413 ** child and we don't have to clean up after it. 1414 ** false can be ignored if we have multiple queues. 1415 ** verbose -- if true, print out status information. 1416 ** persistent -- persistent queue runner? 1417 ** runall -- run all groups or only a subset (DoQueueRun)? 1418 ** 1419 ** Returns: 1420 ** true if the queue run successfully began. 1421 ** 1422 ** Side Effects: 1423 ** runs things in the mail queue using run_work_group(). 1424 ** maybe schedules next queue run. 1425 */ 1426 1427 static ENVELOPE QueueEnvelope; /* the queue run envelope */ 1428 static time_t LastQueueTime = 0; /* last time a queue ID assigned */ 1429 static pid_t LastQueuePid = -1; /* last PID which had a queue ID */ 1430 1431 /* values for qp_supdirs */ 1432 #define QP_NOSUB 0x0000 /* No subdirectories */ 1433 #define QP_SUBDF 0x0001 /* "df" subdirectory */ 1434 #define QP_SUBQF 0x0002 /* "qf" subdirectory */ 1435 #define QP_SUBXF 0x0004 /* "xf" subdirectory */ 1436 1437 bool 1438 runqueue(forkflag, verbose, persistent, runall) 1439 bool forkflag; 1440 bool verbose; 1441 bool persistent; 1442 bool runall; 1443 { 1444 int i; 1445 bool ret = true; 1446 static int curnum = 0; 1447 sigfunc_t cursh; 1448 #if SM_HEAP_CHECK 1449 SM_NONVOLATILE int oldgroup = 0; 1450 1451 if (sm_debug_active(&DebugLeakQ, 1)) 1452 { 1453 oldgroup = sm_heap_group(); 1454 sm_heap_newgroup(); 1455 sm_dprintf("runqueue() heap group #%d\n", sm_heap_group()); 1456 } 1457 #endif /* SM_HEAP_CHECK */ 1458 1459 /* queue run has been started, don't do any more this time */ 1460 DoQueueRun = false; 1461 1462 /* more than one queue or more than one directory per queue */ 1463 if (!forkflag && !verbose && 1464 (WorkGrp[0].wg_qgs[0]->qg_numqueues > 1 || NumWorkGroups > 1 || 1465 WorkGrp[0].wg_numqgrp > 1)) 1466 forkflag = true; 1467 1468 /* 1469 ** For controlling queue runners via signals sent to this process. 1470 ** Oldsh* will get called too by runners_sig* (if it is not SIG_IGN 1471 ** or SIG_DFL) to preserve cleanup behavior. Now that this process 1472 ** will have children (and perhaps grandchildren) this handler will 1473 ** be left in place. This is because this process, once it has 1474 ** finished spinning off queue runners, may go back to doing something 1475 ** else (like being a daemon). And we still want on a SIG{TERM,HUP} to 1476 ** clean up the child queue runners. Only install 'runners_sig*' once 1477 ** else we'll get stuck looping forever. 1478 */ 1479 1480 cursh = sm_signal(SIGTERM, runners_sigterm); 1481 if (cursh != runners_sigterm) 1482 Oldsh_term = cursh; 1483 cursh = sm_signal(SIGHUP, runners_sighup); 1484 if (cursh != runners_sighup) 1485 Oldsh_hup = cursh; 1486 1487 for (i = 0; i < NumWorkGroups && !NoMoreRunners; i++) 1488 { 1489 int rwgflags = RWG_NONE; 1490 1491 /* 1492 ** If MaxQueueChildren active then test whether the start 1493 ** of the next queue group's additional queue runners (maximum) 1494 ** will result in MaxQueueChildren being exceeded. 1495 ** 1496 ** Note: do not use continue; even though another workgroup 1497 ** may have fewer queue runners, this would be "unfair", 1498 ** i.e., this work group might "starve" then. 1499 */ 1500 1501 #if _FFR_QUEUE_SCHED_DBG 1502 if (tTd(69, 10)) 1503 sm_syslog(LOG_INFO, NOQID, 1504 "rq: curnum=%d, MaxQueueChildren=%d, CurRunners=%d, WorkGrp[curnum].wg_maxact=%d", 1505 curnum, MaxQueueChildren, CurRunners, 1506 WorkGrp[curnum].wg_maxact); 1507 #endif /* _FFR_QUEUE_SCHED_DBG */ 1508 if (MaxQueueChildren > 0 && 1509 CurRunners + WorkGrp[curnum].wg_maxact > MaxQueueChildren) 1510 break; 1511 1512 /* 1513 ** Pick up where we left off (curnum), in case we 1514 ** used up all the children last time without finishing. 1515 ** This give a round-robin fairness to queue runs. 1516 ** 1517 ** Increment CurRunners before calling run_work_group() 1518 ** to avoid a "race condition" with proc_list_drop() which 1519 ** decrements CurRunners if the queue runners terminate. 1520 ** Notice: CurRunners is an upper limit, in some cases 1521 ** (too few jobs in the queue) this value is larger than 1522 ** the actual number of queue runners. The discrepancy can 1523 ** increase if some queue runners "hang" for a long time. 1524 */ 1525 1526 CurRunners += WorkGrp[curnum].wg_maxact; 1527 if (forkflag) 1528 rwgflags |= RWG_FORK; 1529 if (verbose) 1530 rwgflags |= RWG_VERBOSE; 1531 if (persistent) 1532 rwgflags |= RWG_PERSISTENT; 1533 if (runall) 1534 rwgflags |= RWG_RUNALL; 1535 ret = run_work_group(curnum, rwgflags); 1536 1537 /* 1538 ** Failure means a message was printed for ETRN 1539 ** and subsequent queues are likely to fail as well. 1540 ** Decrement CurRunners in that case because 1541 ** none have been started. 1542 */ 1543 1544 if (!ret) 1545 { 1546 CurRunners -= WorkGrp[curnum].wg_maxact; 1547 break; 1548 } 1549 1550 if (!persistent) 1551 schedule_queue_runs(runall, curnum, true); 1552 INCR_MOD(curnum, NumWorkGroups); 1553 } 1554 1555 /* schedule left over queue runs */ 1556 if (i < NumWorkGroups && !NoMoreRunners && !persistent) 1557 { 1558 int h; 1559 1560 for (h = curnum; i < NumWorkGroups; i++) 1561 { 1562 schedule_queue_runs(runall, h, false); 1563 INCR_MOD(h, NumWorkGroups); 1564 } 1565 } 1566 1567 1568 #if SM_HEAP_CHECK 1569 if (sm_debug_active(&DebugLeakQ, 1)) 1570 sm_heap_setgroup(oldgroup); 1571 #endif /* SM_HEAP_CHECK */ 1572 return ret; 1573 } 1574 1575 #if _FFR_SKIP_DOMAINS 1576 /* 1577 ** SKIP_DOMAINS -- Skip 'skip' number of domains in the WorkQ. 1578 ** 1579 ** Added by Stephen Frost <sfrost@snowman.net> to support 1580 ** having each runner process every N'th domain instead of 1581 ** every N'th message. 1582 ** 1583 ** Parameters: 1584 ** skip -- number of domains in WorkQ to skip. 1585 ** 1586 ** Returns: 1587 ** total number of messages skipped. 1588 ** 1589 ** Side Effects: 1590 ** may change WorkQ 1591 */ 1592 1593 static int 1594 skip_domains(skip) 1595 int skip; 1596 { 1597 int n, seqjump; 1598 1599 for (n = 0, seqjump = 0; n < skip && WorkQ != NULL; seqjump++) 1600 { 1601 if (WorkQ->w_next != NULL) 1602 { 1603 if (WorkQ->w_host != NULL && 1604 WorkQ->w_next->w_host != NULL) 1605 { 1606 if (sm_strcasecmp(WorkQ->w_host, 1607 WorkQ->w_next->w_host) != 0) 1608 n++; 1609 } 1610 else 1611 { 1612 if ((WorkQ->w_host != NULL && 1613 WorkQ->w_next->w_host == NULL) || 1614 (WorkQ->w_host == NULL && 1615 WorkQ->w_next->w_host != NULL)) 1616 n++; 1617 } 1618 } 1619 WorkQ = WorkQ->w_next; 1620 } 1621 return seqjump; 1622 } 1623 #endif /* _FFR_SKIP_DOMAINS */ 1624 1625 /* 1626 ** RUNNER_WORK -- have a queue runner do its work 1627 ** 1628 ** Have a queue runner do its work a list of entries. 1629 ** When work isn't directly being done then this process can take a signal 1630 ** and terminate immediately (in a clean fashion of course). 1631 ** When work is directly being done, it's not to be interrupted 1632 ** immediately: the work should be allowed to finish at a clean point 1633 ** before termination (in a clean fashion of course). 1634 ** 1635 ** Parameters: 1636 ** e -- envelope. 1637 ** sequenceno -- 'th process to run WorkQ. 1638 ** didfork -- did the calling process fork()? 1639 ** skip -- process only each skip'th item. 1640 ** njobs -- number of jobs in WorkQ. 1641 ** 1642 ** Returns: 1643 ** none. 1644 ** 1645 ** Side Effects: 1646 ** runs things in the mail queue. 1647 */ 1648 1649 static void 1650 runner_work(e, sequenceno, didfork, skip, njobs) 1651 register ENVELOPE *e; 1652 int sequenceno; 1653 bool didfork; 1654 int skip; 1655 int njobs; 1656 { 1657 int n, seqjump; 1658 WORK *w; 1659 time_t now; 1660 1661 SM_GET_LA(now); 1662 1663 /* 1664 ** Here we temporarily block the second calling of the handlers. 1665 ** This allows us to handle the signal without terminating in the 1666 ** middle of direct work. If a signal does come, the test for 1667 ** NoMoreRunners will find it. 1668 */ 1669 1670 BlockOldsh = true; 1671 seqjump = skip; 1672 1673 /* process them once at a time */ 1674 while (WorkQ != NULL) 1675 { 1676 #if SM_HEAP_CHECK 1677 SM_NONVOLATILE int oldgroup = 0; 1678 1679 if (sm_debug_active(&DebugLeakQ, 1)) 1680 { 1681 oldgroup = sm_heap_group(); 1682 sm_heap_newgroup(); 1683 sm_dprintf("run_queue_group() heap group #%d\n", 1684 sm_heap_group()); 1685 } 1686 #endif /* SM_HEAP_CHECK */ 1687 1688 /* do no more work */ 1689 if (NoMoreRunners) 1690 { 1691 /* Check that a valid signal handler is callable */ 1692 if (Oldsh != SIG_DFL && Oldsh != SIG_IGN && 1693 Oldsh != runners_sighup && 1694 Oldsh != runners_sigterm) 1695 (*Oldsh)(Oldsig); 1696 break; 1697 } 1698 1699 w = WorkQ; /* assign current work item */ 1700 1701 /* 1702 ** Set the head of the WorkQ to the next work item. 1703 ** It is set 'skip' ahead (the number of parallel queue 1704 ** runners working on WorkQ together) since each runner 1705 ** works on every 'skip'th (N-th) item. 1706 #if _FFR_SKIP_DOMAINS 1707 ** In the case of the BYHOST Queue Sort Order, the 'item' 1708 ** is a domain, so we work on every 'skip'th (N-th) domain. 1709 #endif * _FFR_SKIP_DOMAINS * 1710 */ 1711 1712 #if _FFR_SKIP_DOMAINS 1713 if (QueueSortOrder == QSO_BYHOST) 1714 { 1715 seqjump = 1; 1716 if (WorkQ->w_next != NULL) 1717 { 1718 if (WorkQ->w_host != NULL && 1719 WorkQ->w_next->w_host != NULL) 1720 { 1721 if (sm_strcasecmp(WorkQ->w_host, 1722 WorkQ->w_next->w_host) 1723 != 0) 1724 seqjump = skip_domains(skip); 1725 else 1726 WorkQ = WorkQ->w_next; 1727 } 1728 else 1729 { 1730 if ((WorkQ->w_host != NULL && 1731 WorkQ->w_next->w_host == NULL) || 1732 (WorkQ->w_host == NULL && 1733 WorkQ->w_next->w_host != NULL)) 1734 seqjump = skip_domains(skip); 1735 else 1736 WorkQ = WorkQ->w_next; 1737 } 1738 } 1739 else 1740 WorkQ = WorkQ->w_next; 1741 } 1742 else 1743 #endif /* _FFR_SKIP_DOMAINS */ 1744 { 1745 for (n = 0; n < skip && WorkQ != NULL; n++) 1746 WorkQ = WorkQ->w_next; 1747 } 1748 1749 e->e_to = NULL; 1750 1751 /* 1752 ** Ignore jobs that are too expensive for the moment. 1753 ** 1754 ** Get new load average every GET_NEW_LA_TIME seconds. 1755 */ 1756 1757 SM_GET_LA(now); 1758 if (shouldqueue(WkRecipFact, Current_LA_time)) 1759 { 1760 char *msg = "Aborting queue run: load average too high"; 1761 1762 if (Verbose) 1763 message("%s", msg); 1764 if (LogLevel > 8) 1765 sm_syslog(LOG_INFO, NOQID, "runqueue: %s", msg); 1766 break; 1767 } 1768 if (shouldqueue(w->w_pri, w->w_ctime)) 1769 { 1770 if (Verbose) 1771 message(EmptyString); 1772 if (QueueSortOrder == QSO_BYPRIORITY) 1773 { 1774 if (Verbose) 1775 message("Skipping %s/%s (sequence %d of %d) and flushing rest of queue", 1776 qid_printqueue(w->w_qgrp, 1777 w->w_qdir), 1778 w->w_name + 2, sequenceno, 1779 njobs); 1780 if (LogLevel > 8) 1781 sm_syslog(LOG_INFO, NOQID, 1782 "runqueue: Flushing queue from %s/%s (pri %ld, LA %d, %d of %d)", 1783 qid_printqueue(w->w_qgrp, 1784 w->w_qdir), 1785 w->w_name + 2, w->w_pri, 1786 CurrentLA, sequenceno, 1787 njobs); 1788 break; 1789 } 1790 else if (Verbose) 1791 message("Skipping %s/%s (sequence %d of %d)", 1792 qid_printqueue(w->w_qgrp, w->w_qdir), 1793 w->w_name + 2, sequenceno, njobs); 1794 } 1795 else 1796 { 1797 if (Verbose) 1798 { 1799 message(EmptyString); 1800 message("Running %s/%s (sequence %d of %d)", 1801 qid_printqueue(w->w_qgrp, w->w_qdir), 1802 w->w_name + 2, sequenceno, njobs); 1803 } 1804 if (didfork && MaxQueueChildren > 0) 1805 { 1806 sm_blocksignal(SIGCHLD); 1807 (void) sm_signal(SIGCHLD, reapchild); 1808 } 1809 if (tTd(63, 100)) 1810 sm_syslog(LOG_DEBUG, NOQID, 1811 "runqueue %s dowork(%s)", 1812 qid_printqueue(w->w_qgrp, w->w_qdir), 1813 w->w_name + 2); 1814 1815 (void) dowork(w->w_qgrp, w->w_qdir, w->w_name + 2, 1816 ForkQueueRuns, false, e); 1817 errno = 0; 1818 } 1819 sm_free(w->w_name); /* XXX */ 1820 if (w->w_host != NULL) 1821 sm_free(w->w_host); /* XXX */ 1822 sm_free((char *) w); /* XXX */ 1823 sequenceno += seqjump; /* next sequence number */ 1824 #if SM_HEAP_CHECK 1825 if (sm_debug_active(&DebugLeakQ, 1)) 1826 sm_heap_setgroup(oldgroup); 1827 #endif /* SM_HEAP_CHECK */ 1828 } 1829 1830 BlockOldsh = false; 1831 1832 /* check the signals didn't happen during the revert */ 1833 if (NoMoreRunners) 1834 { 1835 /* Check that a valid signal handler is callable */ 1836 if (Oldsh != SIG_DFL && Oldsh != SIG_IGN && 1837 Oldsh != runners_sighup && Oldsh != runners_sigterm) 1838 (*Oldsh)(Oldsig); 1839 } 1840 1841 Oldsh = SIG_DFL; /* after the NoMoreRunners check */ 1842 } 1843 /* 1844 ** RUN_WORK_GROUP -- run the jobs in a queue group from a work group. 1845 ** 1846 ** Gets the stuff out of the queue in some presumably logical 1847 ** order and processes them. 1848 ** 1849 ** Parameters: 1850 ** wgrp -- work group to process. 1851 ** flags -- RWG_* flags 1852 ** 1853 ** Returns: 1854 ** true if the queue run successfully began. 1855 ** 1856 ** Side Effects: 1857 ** runs things in the mail queue. 1858 */ 1859 1860 /* Minimum sleep time for persistent queue runners */ 1861 #define MIN_SLEEP_TIME 5 1862 1863 bool 1864 run_work_group(wgrp, flags) 1865 int wgrp; 1866 int flags; 1867 { 1868 register ENVELOPE *e; 1869 int njobs, qdir; 1870 int sequenceno = 1; 1871 int qgrp, endgrp, h, i; 1872 time_t now; 1873 bool full, more; 1874 SM_RPOOL_T *rpool; 1875 extern void rmexpstab __P((void)); 1876 extern ENVELOPE BlankEnvelope; 1877 extern SIGFUNC_DECL reapchild __P((int)); 1878 1879 if (wgrp < 0) 1880 return false; 1881 1882 /* 1883 ** If no work will ever be selected, don't even bother reading 1884 ** the queue. 1885 */ 1886 1887 SM_GET_LA(now); 1888 1889 if (!bitset(RWG_PERSISTENT, flags) && 1890 shouldqueue(WkRecipFact, Current_LA_time)) 1891 { 1892 char *msg = "Skipping queue run -- load average too high"; 1893 1894 if (bitset(RWG_VERBOSE, flags)) 1895 message("458 %s\n", msg); 1896 if (LogLevel > 8) 1897 sm_syslog(LOG_INFO, NOQID, "runqueue: %s", msg); 1898 return false; 1899 } 1900 1901 /* 1902 ** See if we already have too many children. 1903 */ 1904 1905 if (bitset(RWG_FORK, flags) && 1906 WorkGrp[wgrp].wg_lowqintvl > 0 && 1907 !bitset(RWG_PERSISTENT, flags) && 1908 MaxChildren > 0 && CurChildren >= MaxChildren) 1909 { 1910 char *msg = "Skipping queue run -- too many children"; 1911 1912 if (bitset(RWG_VERBOSE, flags)) 1913 message("458 %s (%d)\n", msg, CurChildren); 1914 if (LogLevel > 8) 1915 sm_syslog(LOG_INFO, NOQID, "runqueue: %s (%d)", 1916 msg, CurChildren); 1917 return false; 1918 } 1919 1920 /* 1921 ** See if we want to go off and do other useful work. 1922 */ 1923 1924 if (bitset(RWG_FORK, flags)) 1925 { 1926 pid_t pid; 1927 1928 (void) sm_blocksignal(SIGCHLD); 1929 (void) sm_signal(SIGCHLD, reapchild); 1930 1931 pid = dofork(); 1932 if (pid == -1) 1933 { 1934 const char *msg = "Skipping queue run -- fork() failed"; 1935 const char *err = sm_errstring(errno); 1936 1937 if (bitset(RWG_VERBOSE, flags)) 1938 message("458 %s: %s\n", msg, err); 1939 if (LogLevel > 8) 1940 sm_syslog(LOG_INFO, NOQID, "runqueue: %s: %s", 1941 msg, err); 1942 (void) sm_releasesignal(SIGCHLD); 1943 return false; 1944 } 1945 if (pid != 0) 1946 { 1947 /* parent -- pick up intermediate zombie */ 1948 (void) sm_blocksignal(SIGALRM); 1949 1950 /* wgrp only used when queue runners are persistent */ 1951 proc_list_add(pid, "Queue runner", PROC_QUEUE, 1952 WorkGrp[wgrp].wg_maxact, 1953 bitset(RWG_PERSISTENT, flags) ? wgrp : -1, 1954 NULL); 1955 (void) sm_releasesignal(SIGALRM); 1956 (void) sm_releasesignal(SIGCHLD); 1957 return true; 1958 } 1959 1960 /* child -- clean up signals */ 1961 1962 /* Reset global flags */ 1963 RestartRequest = NULL; 1964 RestartWorkGroup = false; 1965 ShutdownRequest = NULL; 1966 PendingSignal = 0; 1967 CurrentPid = getpid(); 1968 close_sendmail_pid(); 1969 1970 /* 1971 ** Initialize exception stack and default exception 1972 ** handler for child process. 1973 */ 1974 1975 sm_exc_newthread(fatal_error); 1976 clrcontrol(); 1977 proc_list_clear(); 1978 1979 /* Add parent process as first child item */ 1980 proc_list_add(CurrentPid, "Queue runner child process", 1981 PROC_QUEUE_CHILD, 0, -1, NULL); 1982 (void) sm_releasesignal(SIGCHLD); 1983 (void) sm_signal(SIGCHLD, SIG_DFL); 1984 (void) sm_signal(SIGHUP, SIG_DFL); 1985 (void) sm_signal(SIGTERM, intsig); 1986 } 1987 1988 /* 1989 ** Release any resources used by the daemon code. 1990 */ 1991 1992 clrdaemon(); 1993 1994 /* force it to run expensive jobs */ 1995 NoConnect = false; 1996 1997 /* drop privileges */ 1998 if (geteuid() == (uid_t) 0) 1999 (void) drop_privileges(false); 2000 2001 /* 2002 ** Create ourselves an envelope 2003 */ 2004 2005 CurEnv = &QueueEnvelope; 2006 rpool = sm_rpool_new_x(NULL); 2007 e = newenvelope(&QueueEnvelope, CurEnv, rpool); 2008 e->e_flags = BlankEnvelope.e_flags; 2009 e->e_parent = NULL; 2010 2011 /* make sure we have disconnected from parent */ 2012 if (bitset(RWG_FORK, flags)) 2013 { 2014 disconnect(1, e); 2015 QuickAbort = false; 2016 } 2017 2018 /* 2019 ** If we are running part of the queue, always ignore stored 2020 ** host status. 2021 */ 2022 2023 if (QueueLimitId != NULL || QueueLimitSender != NULL || 2024 QueueLimitQuarantine != NULL || 2025 QueueLimitRecipient != NULL) 2026 { 2027 IgnoreHostStatus = true; 2028 MinQueueAge = 0; 2029 } 2030 2031 /* 2032 ** Here is where we choose the queue group from the work group. 2033 ** The caller of the "domorework" label must setup a new envelope. 2034 */ 2035 2036 endgrp = WorkGrp[wgrp].wg_curqgrp; /* to not spin endlessly */ 2037 2038 domorework: 2039 2040 /* 2041 ** Run a queue group if: 2042 ** RWG_RUNALL bit is set or the bit for this group is set. 2043 */ 2044 2045 now = curtime(); 2046 for (;;) 2047 { 2048 /* 2049 ** Find the next queue group within the work group that 2050 ** has been marked as needing a run. 2051 */ 2052 2053 qgrp = WorkGrp[wgrp].wg_qgs[WorkGrp[wgrp].wg_curqgrp]->qg_index; 2054 WorkGrp[wgrp].wg_curqgrp++; /* advance */ 2055 WorkGrp[wgrp].wg_curqgrp %= WorkGrp[wgrp].wg_numqgrp; /* wrap */ 2056 if (bitset(RWG_RUNALL, flags) || 2057 (Queue[qgrp]->qg_nextrun <= now && 2058 Queue[qgrp]->qg_nextrun != (time_t) -1)) 2059 break; 2060 if (endgrp == WorkGrp[wgrp].wg_curqgrp) 2061 { 2062 e->e_id = NULL; 2063 if (bitset(RWG_FORK, flags)) 2064 finis(true, true, ExitStat); 2065 return true; /* we're done */ 2066 } 2067 } 2068 2069 qdir = Queue[qgrp]->qg_curnum; /* round-robin init of queue position */ 2070 #if _FFR_QUEUE_SCHED_DBG 2071 if (tTd(69, 12)) 2072 sm_syslog(LOG_INFO, NOQID, 2073 "rwg: wgrp=%d, qgrp=%d, qdir=%d, name=%s, curqgrp=%d, numgrps=%d", 2074 wgrp, qgrp, qdir, qid_printqueue(qgrp, qdir), 2075 WorkGrp[wgrp].wg_curqgrp, WorkGrp[wgrp].wg_numqgrp); 2076 #endif /* _FFR_QUEUE_SCHED_DBG */ 2077 2078 #if HASNICE 2079 /* tweak niceness of queue runs */ 2080 if (Queue[qgrp]->qg_nice > 0) 2081 (void) nice(Queue[qgrp]->qg_nice); 2082 #endif /* HASNICE */ 2083 2084 /* XXX running queue group... */ 2085 sm_setproctitle(true, CurEnv, "running queue: %s", 2086 qid_printqueue(qgrp, qdir)); 2087 2088 if (LogLevel > 69 || tTd(63, 99)) 2089 sm_syslog(LOG_DEBUG, NOQID, 2090 "runqueue %s, pid=%d, forkflag=%d", 2091 qid_printqueue(qgrp, qdir), (int) CurrentPid, 2092 bitset(RWG_FORK, flags)); 2093 2094 /* 2095 ** Start making passes through the queue. 2096 ** First, read and sort the entire queue. 2097 ** Then, process the work in that order. 2098 ** But if you take too long, start over. 2099 */ 2100 2101 for (i = 0; i < Queue[qgrp]->qg_numqueues; i++) 2102 { 2103 h = gatherq(qgrp, qdir, false, &full, &more); 2104 #if SM_CONF_SHM 2105 if (ShmId != SM_SHM_NO_ID) 2106 QSHM_ENTRIES(Queue[qgrp]->qg_qpaths[qdir].qp_idx) = h; 2107 #endif /* SM_CONF_SHM */ 2108 /* If there are no more items in this queue advance */ 2109 if (!more) 2110 { 2111 /* A round-robin advance */ 2112 qdir++; 2113 qdir %= Queue[qgrp]->qg_numqueues; 2114 } 2115 2116 /* Has the WorkList reached the limit? */ 2117 if (full) 2118 break; /* don't try to gather more */ 2119 } 2120 2121 /* order the existing work requests */ 2122 njobs = sortq(Queue[qgrp]->qg_maxlist); 2123 Queue[qgrp]->qg_curnum = qdir; /* update */ 2124 2125 2126 if (!Verbose && bitnset(QD_FORK, Queue[qgrp]->qg_flags)) 2127 { 2128 int loop, maxrunners; 2129 pid_t pid; 2130 2131 /* 2132 ** For this WorkQ we want to fork off N children (maxrunners) 2133 ** at this point. Each child has a copy of WorkQ. Each child 2134 ** will process every N-th item. The parent will wait for all 2135 ** of the children to finish before moving on to the next 2136 ** queue group within the work group. This saves us forking 2137 ** a new runner-child for each work item. 2138 ** It's valid for qg_maxqrun == 0 since this may be an 2139 ** explicit "don't run this queue" setting. 2140 */ 2141 2142 maxrunners = Queue[qgrp]->qg_maxqrun; 2143 2144 /* No need to have more runners then there are jobs */ 2145 if (maxrunners > njobs) 2146 maxrunners = njobs; 2147 for (loop = 0; loop < maxrunners; loop++) 2148 { 2149 /* 2150 ** Since the delivery may happen in a child and the 2151 ** parent does not wait, the parent may close the 2152 ** maps thereby removing any shared memory used by 2153 ** the map. Therefore, close the maps now so the 2154 ** child will dynamically open them if necessary. 2155 */ 2156 2157 closemaps(false); 2158 2159 pid = fork(); 2160 if (pid < 0) 2161 { 2162 syserr("run_work_group: cannot fork"); 2163 return false; 2164 } 2165 else if (pid > 0) 2166 { 2167 /* parent -- clean out connection cache */ 2168 mci_flush(false, NULL); 2169 #if _FFR_SKIP_DOMAINS 2170 if (QueueSortOrder == QSO_BYHOST) 2171 { 2172 sequenceno += skip_domains(1); 2173 } 2174 else 2175 #endif /* _FFR_SKIP_DOMAINS */ 2176 { 2177 /* for the skip */ 2178 WorkQ = WorkQ->w_next; 2179 sequenceno++; 2180 } 2181 proc_list_add(pid, "Queue child runner process", 2182 PROC_QUEUE_CHILD, 0, -1, NULL); 2183 2184 /* No additional work, no additional runners */ 2185 if (WorkQ == NULL) 2186 break; 2187 } 2188 else 2189 { 2190 /* child -- Reset global flags */ 2191 RestartRequest = NULL; 2192 RestartWorkGroup = false; 2193 ShutdownRequest = NULL; 2194 PendingSignal = 0; 2195 CurrentPid = getpid(); 2196 close_sendmail_pid(); 2197 2198 /* 2199 ** Initialize exception stack and default 2200 ** exception handler for child process. 2201 ** When fork()'d the child now has a private 2202 ** copy of WorkQ at its current position. 2203 */ 2204 2205 sm_exc_newthread(fatal_error); 2206 2207 /* 2208 ** SMTP processes (whether -bd or -bs) set 2209 ** SIGCHLD to reapchild to collect 2210 ** children status. However, at delivery 2211 ** time, that status must be collected 2212 ** by sm_wait() to be dealt with properly 2213 ** (check success of delivery based 2214 ** on status code, etc). Therefore, if we 2215 ** are an SMTP process, reset SIGCHLD 2216 ** back to the default so reapchild 2217 ** doesn't collect status before 2218 ** sm_wait(). 2219 */ 2220 2221 if (OpMode == MD_SMTP || 2222 OpMode == MD_DAEMON || 2223 MaxQueueChildren > 0) 2224 { 2225 proc_list_clear(); 2226 sm_releasesignal(SIGCHLD); 2227 (void) sm_signal(SIGCHLD, SIG_DFL); 2228 } 2229 2230 /* child -- error messages to the transcript */ 2231 QuickAbort = OnlyOneError = false; 2232 runner_work(e, sequenceno, true, 2233 maxrunners, njobs); 2234 2235 /* This child is done */ 2236 finis(true, true, ExitStat); 2237 /* NOTREACHED */ 2238 } 2239 } 2240 2241 sm_releasesignal(SIGCHLD); 2242 2243 /* 2244 ** Wait until all of the runners have completed before 2245 ** seeing if there is another queue group in the 2246 ** work group to process. 2247 ** XXX Future enhancement: don't wait() for all children 2248 ** here, just go ahead and make sure that overall the number 2249 ** of children is not exceeded. 2250 */ 2251 2252 while (CurChildren > 0) 2253 { 2254 int status; 2255 pid_t ret; 2256 2257 while ((ret = sm_wait(&status)) <= 0) 2258 continue; 2259 proc_list_drop(ret, status, NULL); 2260 } 2261 } 2262 else if (Queue[qgrp]->qg_maxqrun > 0 || bitset(RWG_FORCE, flags)) 2263 { 2264 /* 2265 ** When current process will not fork children to do the work, 2266 ** it will do the work itself. The 'skip' will be 1 since 2267 ** there are no child runners to divide the work across. 2268 */ 2269 2270 runner_work(e, sequenceno, false, 1, njobs); 2271 } 2272 2273 /* free memory allocated by newenvelope() above */ 2274 sm_rpool_free(rpool); 2275 QueueEnvelope.e_rpool = NULL; 2276 2277 /* Are there still more queues in the work group to process? */ 2278 if (endgrp != WorkGrp[wgrp].wg_curqgrp) 2279 { 2280 rpool = sm_rpool_new_x(NULL); 2281 e = newenvelope(&QueueEnvelope, CurEnv, rpool); 2282 e->e_flags = BlankEnvelope.e_flags; 2283 goto domorework; 2284 } 2285 2286 /* No more queues in work group to process. Now check persistent. */ 2287 if (bitset(RWG_PERSISTENT, flags)) 2288 { 2289 sequenceno = 1; 2290 sm_setproctitle(true, CurEnv, "running queue: %s", 2291 qid_printqueue(qgrp, qdir)); 2292 2293 /* 2294 ** close bogus maps, i.e., maps which caused a tempfail, 2295 ** so we get fresh map connections on the next lookup. 2296 ** closemaps() is also called when children are started. 2297 */ 2298 2299 closemaps(true); 2300 2301 /* Close any cached connections. */ 2302 mci_flush(true, NULL); 2303 2304 /* Clean out expired related entries. */ 2305 rmexpstab(); 2306 2307 #if NAMED_BIND 2308 /* Update MX records for FallbackMX. */ 2309 if (FallbackMX != NULL) 2310 (void) getfallbackmxrr(FallbackMX); 2311 #endif /* NAMED_BIND */ 2312 2313 #if USERDB 2314 /* close UserDatabase */ 2315 _udbx_close(); 2316 #endif /* USERDB */ 2317 2318 #if SM_HEAP_CHECK 2319 if (sm_debug_active(&SmHeapCheck, 2) 2320 && access("memdump", F_OK) == 0 2321 ) 2322 { 2323 SM_FILE_T *out; 2324 2325 remove("memdump"); 2326 out = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, 2327 "memdump.out", SM_IO_APPEND, NULL); 2328 if (out != NULL) 2329 { 2330 (void) sm_io_fprintf(out, SM_TIME_DEFAULT, "----------------------\n"); 2331 sm_heap_report(out, 2332 sm_debug_level(&SmHeapCheck) - 1); 2333 (void) sm_io_close(out, SM_TIME_DEFAULT); 2334 } 2335 } 2336 #endif /* SM_HEAP_CHECK */ 2337 2338 /* let me rest for a second to catch my breath */ 2339 if (njobs == 0 && WorkGrp[wgrp].wg_lowqintvl < MIN_SLEEP_TIME) 2340 sleep(MIN_SLEEP_TIME); 2341 else if (WorkGrp[wgrp].wg_lowqintvl <= 0) 2342 sleep(QueueIntvl > 0 ? QueueIntvl : MIN_SLEEP_TIME); 2343 else 2344 sleep(WorkGrp[wgrp].wg_lowqintvl); 2345 2346 /* 2347 ** Get the LA outside the WorkQ loop if necessary. 2348 ** In a persistent queue runner the code is repeated over 2349 ** and over but gatherq() may ignore entries due to 2350 ** shouldqueue() (do we really have to do this twice?). 2351 ** Hence the queue runners would just idle around when once 2352 ** CurrentLA caused all entries in a queue to be ignored. 2353 */ 2354 2355 if (njobs == 0) 2356 SM_GET_LA(now); 2357 rpool = sm_rpool_new_x(NULL); 2358 e = newenvelope(&QueueEnvelope, CurEnv, rpool); 2359 e->e_flags = BlankEnvelope.e_flags; 2360 goto domorework; 2361 } 2362 2363 /* exit without the usual cleanup */ 2364 e->e_id = NULL; 2365 if (bitset(RWG_FORK, flags)) 2366 finis(true, true, ExitStat); 2367 /* NOTREACHED */ 2368 return true; 2369 } 2370 2371 /* 2372 ** DOQUEUERUN -- do a queue run? 2373 */ 2374 2375 bool 2376 doqueuerun() 2377 { 2378 return DoQueueRun; 2379 } 2380 2381 /* 2382 ** RUNQUEUEEVENT -- Sets a flag to indicate that a queue run should be done. 2383 ** 2384 ** Parameters: 2385 ** none. 2386 ** 2387 ** Returns: 2388 ** none. 2389 ** 2390 ** Side Effects: 2391 ** The invocation of this function via an alarm may interrupt 2392 ** a set of actions. Thus errno may be set in that context. 2393 ** We need to restore errno at the end of this function to ensure 2394 ** that any work done here that sets errno doesn't return a 2395 ** misleading/false errno value. Errno may be EINTR upon entry to 2396 ** this function because of non-restartable/continuable system 2397 ** API was active. Iff this is true we will override errno as 2398 ** a timeout (as a more accurate error message). 2399 ** 2400 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD 2401 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE 2402 ** DOING. 2403 */ 2404 2405 void 2406 runqueueevent(ignore) 2407 int ignore; 2408 { 2409 int save_errno = errno; 2410 2411 /* 2412 ** Set the general bit that we want a queue run, 2413 ** tested in doqueuerun() 2414 */ 2415 2416 DoQueueRun = true; 2417 #if _FFR_QUEUE_SCHED_DBG 2418 if (tTd(69, 10)) 2419 sm_syslog(LOG_INFO, NOQID, "rqe: done"); 2420 #endif /* _FFR_QUEUE_SCHED_DBG */ 2421 2422 errno = save_errno; 2423 if (errno == EINTR) 2424 errno = ETIMEDOUT; 2425 } 2426 /* 2427 ** GATHERQ -- gather messages from the message queue(s) the work queue. 2428 ** 2429 ** Parameters: 2430 ** qgrp -- the index of the queue group. 2431 ** qdir -- the index of the queue directory. 2432 ** doall -- if set, include everything in the queue (even 2433 ** the jobs that cannot be run because the load 2434 ** average is too high, or MaxQueueRun is reached). 2435 ** Otherwise, exclude those jobs. 2436 ** full -- (optional) to be set 'true' if WorkList is full 2437 ** more -- (optional) to be set 'true' if there are still more 2438 ** messages in this queue not added to WorkList 2439 ** 2440 ** Returns: 2441 ** The number of request in the queue (not necessarily 2442 ** the number of requests in WorkList however). 2443 ** 2444 ** Side Effects: 2445 ** prepares available work into WorkList 2446 */ 2447 2448 #define NEED_P 0001 /* 'P': priority */ 2449 #define NEED_T 0002 /* 'T': time */ 2450 #define NEED_R 0004 /* 'R': recipient */ 2451 #define NEED_S 0010 /* 'S': sender */ 2452 #define NEED_H 0020 /* host */ 2453 #define HAS_QUARANTINE 0040 /* has an unexpected 'q' line */ 2454 #define NEED_QUARANTINE 0100 /* 'q': reason */ 2455 2456 static WORK *WorkList = NULL; /* list of unsort work */ 2457 static int WorkListSize = 0; /* current max size of WorkList */ 2458 static int WorkListCount = 0; /* # of work items in WorkList */ 2459 2460 static int 2461 gatherq(qgrp, qdir, doall, full, more) 2462 int qgrp; 2463 int qdir; 2464 bool doall; 2465 bool *full; 2466 bool *more; 2467 { 2468 register struct dirent *d; 2469 register WORK *w; 2470 register char *p; 2471 DIR *f; 2472 int i, num_ent; 2473 int wn; 2474 QUEUE_CHAR *check; 2475 char qd[MAXPATHLEN]; 2476 char qf[MAXPATHLEN]; 2477 2478 wn = WorkListCount - 1; 2479 num_ent = 0; 2480 if (qdir == NOQDIR) 2481 (void) sm_strlcpy(qd, ".", sizeof qd); 2482 else 2483 (void) sm_strlcpyn(qd, sizeof qd, 2, 2484 Queue[qgrp]->qg_qpaths[qdir].qp_name, 2485 (bitset(QP_SUBQF, 2486 Queue[qgrp]->qg_qpaths[qdir].qp_subdirs) 2487 ? "/qf" : "")); 2488 2489 if (tTd(41, 1)) 2490 { 2491 sm_dprintf("gatherq:\n"); 2492 2493 check = QueueLimitId; 2494 while (check != NULL) 2495 { 2496 sm_dprintf("\tQueueLimitId = %s%s\n", 2497 check->queue_negate ? "!" : "", 2498 check->queue_match); 2499 check = check->queue_next; 2500 } 2501 2502 check = QueueLimitSender; 2503 while (check != NULL) 2504 { 2505 sm_dprintf("\tQueueLimitSender = %s%s\n", 2506 check->queue_negate ? "!" : "", 2507 check->queue_match); 2508 check = check->queue_next; 2509 } 2510 2511 check = QueueLimitRecipient; 2512 while (check != NULL) 2513 { 2514 sm_dprintf("\tQueueLimitRecipient = %s%s\n", 2515 check->queue_negate ? "!" : "", 2516 check->queue_match); 2517 check = check->queue_next; 2518 } 2519 2520 if (QueueMode == QM_QUARANTINE) 2521 { 2522 check = QueueLimitQuarantine; 2523 while (check != NULL) 2524 { 2525 sm_dprintf("\tQueueLimitQuarantine = %s%s\n", 2526 check->queue_negate ? "!" : "", 2527 check->queue_match); 2528 check = check->queue_next; 2529 } 2530 } 2531 } 2532 2533 /* open the queue directory */ 2534 f = opendir(qd); 2535 if (f == NULL) 2536 { 2537 syserr("gatherq: cannot open \"%s\"", 2538 qid_printqueue(qgrp, qdir)); 2539 if (full != NULL) 2540 *full = WorkListCount >= MaxQueueRun && MaxQueueRun > 0; 2541 if (more != NULL) 2542 *more = false; 2543 return 0; 2544 } 2545 2546 /* 2547 ** Read the work directory. 2548 */ 2549 2550 while ((d = readdir(f)) != NULL) 2551 { 2552 SM_FILE_T *cf; 2553 int qfver = 0; 2554 char lbuf[MAXNAME + 1]; 2555 struct stat sbuf; 2556 2557 if (tTd(41, 50)) 2558 sm_dprintf("gatherq: checking %s..", d->d_name); 2559 2560 /* is this an interesting entry? */ 2561 if (!(((QueueMode == QM_NORMAL && 2562 d->d_name[0] == NORMQF_LETTER) || 2563 (QueueMode == QM_QUARANTINE && 2564 d->d_name[0] == QUARQF_LETTER) || 2565 (QueueMode == QM_LOST && 2566 d->d_name[0] == LOSEQF_LETTER)) && 2567 d->d_name[1] == 'f')) 2568 { 2569 if (tTd(41, 50)) 2570 sm_dprintf(" skipping\n"); 2571 continue; 2572 } 2573 if (tTd(41, 50)) 2574 sm_dprintf("\n"); 2575 2576 if (strlen(d->d_name) >= MAXQFNAME) 2577 { 2578 if (Verbose) 2579 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 2580 "gatherq: %s too long, %d max characters\n", 2581 d->d_name, MAXQFNAME); 2582 if (LogLevel > 0) 2583 sm_syslog(LOG_ALERT, NOQID, 2584 "gatherq: %s too long, %d max characters", 2585 d->d_name, MAXQFNAME); 2586 continue; 2587 } 2588 2589 check = QueueLimitId; 2590 while (check != NULL) 2591 { 2592 if (strcontainedin(false, check->queue_match, 2593 d->d_name) != check->queue_negate) 2594 break; 2595 else 2596 check = check->queue_next; 2597 } 2598 if (QueueLimitId != NULL && check == NULL) 2599 continue; 2600 2601 /* grow work list if necessary */ 2602 if (++wn >= MaxQueueRun && MaxQueueRun > 0) 2603 { 2604 if (wn == MaxQueueRun && LogLevel > 0) 2605 sm_syslog(LOG_WARNING, NOQID, 2606 "WorkList for %s maxed out at %d", 2607 qid_printqueue(qgrp, qdir), 2608 MaxQueueRun); 2609 if (doall) 2610 continue; /* just count entries */ 2611 break; 2612 } 2613 if (wn >= WorkListSize) 2614 { 2615 grow_wlist(qgrp, qdir); 2616 if (wn >= WorkListSize) 2617 continue; 2618 } 2619 SM_ASSERT(wn >= 0); 2620 w = &WorkList[wn]; 2621 2622 (void) sm_strlcpyn(qf, sizeof qf, 3, qd, "/", d->d_name); 2623 if (stat(qf, &sbuf) < 0) 2624 { 2625 if (errno != ENOENT) 2626 sm_syslog(LOG_INFO, NOQID, 2627 "gatherq: can't stat %s/%s", 2628 qid_printqueue(qgrp, qdir), 2629 d->d_name); 2630 wn--; 2631 continue; 2632 } 2633 if (!bitset(S_IFREG, sbuf.st_mode)) 2634 { 2635 /* Yikes! Skip it or we will hang on open! */ 2636 if (!((d->d_name[0] == DATAFL_LETTER || 2637 d->d_name[0] == NORMQF_LETTER || 2638 d->d_name[0] == QUARQF_LETTER || 2639 d->d_name[0] == LOSEQF_LETTER || 2640 d->d_name[0] == XSCRPT_LETTER) && 2641 d->d_name[1] == 'f' && d->d_name[2] == '\0')) 2642 syserr("gatherq: %s/%s is not a regular file", 2643 qid_printqueue(qgrp, qdir), d->d_name); 2644 wn--; 2645 continue; 2646 } 2647 2648 /* avoid work if possible */ 2649 if ((QueueSortOrder == QSO_BYFILENAME || 2650 QueueSortOrder == QSO_BYMODTIME || 2651 QueueSortOrder == QSO_RANDOM) && 2652 QueueLimitQuarantine == NULL && 2653 QueueLimitSender == NULL && 2654 QueueLimitRecipient == NULL) 2655 { 2656 w->w_qgrp = qgrp; 2657 w->w_qdir = qdir; 2658 w->w_name = newstr(d->d_name); 2659 w->w_host = NULL; 2660 w->w_lock = w->w_tooyoung = false; 2661 w->w_pri = 0; 2662 w->w_ctime = 0; 2663 w->w_mtime = sbuf.st_mtime; 2664 ++num_ent; 2665 continue; 2666 } 2667 2668 /* open control file */ 2669 cf = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, qf, SM_IO_RDONLY_B, 2670 NULL); 2671 if (cf == NULL && OpMode != MD_PRINT) 2672 { 2673 /* this may be some random person sending hir msgs */ 2674 if (tTd(41, 2)) 2675 sm_dprintf("gatherq: cannot open %s: %s\n", 2676 d->d_name, sm_errstring(errno)); 2677 errno = 0; 2678 wn--; 2679 continue; 2680 } 2681 w->w_qgrp = qgrp; 2682 w->w_qdir = qdir; 2683 w->w_name = newstr(d->d_name); 2684 w->w_host = NULL; 2685 if (cf != NULL) 2686 { 2687 w->w_lock = !lockfile(sm_io_getinfo(cf, SM_IO_WHAT_FD, 2688 NULL), 2689 w->w_name, NULL, 2690 LOCK_SH|LOCK_NB); 2691 } 2692 w->w_tooyoung = false; 2693 2694 /* make sure jobs in creation don't clog queue */ 2695 w->w_pri = 0x7fffffff; 2696 w->w_ctime = 0; 2697 w->w_mtime = sbuf.st_mtime; 2698 2699 /* extract useful information */ 2700 i = NEED_P|NEED_T; 2701 if (QueueSortOrder == QSO_BYHOST 2702 #if _FFR_RHS 2703 || QueueSortOrder == QSO_BYSHUFFLE 2704 #endif /* _FFR_RHS */ 2705 ) 2706 { 2707 /* need w_host set for host sort order */ 2708 i |= NEED_H; 2709 } 2710 if (QueueLimitSender != NULL) 2711 i |= NEED_S; 2712 if (QueueLimitRecipient != NULL) 2713 i |= NEED_R; 2714 if (QueueLimitQuarantine != NULL) 2715 i |= NEED_QUARANTINE; 2716 while (cf != NULL && i != 0 && 2717 sm_io_fgets(cf, SM_TIME_DEFAULT, lbuf, 2718 sizeof lbuf) != NULL) 2719 { 2720 int c; 2721 time_t age; 2722 2723 p = strchr(lbuf, '\n'); 2724 if (p != NULL) 2725 *p = '\0'; 2726 else 2727 { 2728 /* flush rest of overly long line */ 2729 while ((c = sm_io_getc(cf, SM_TIME_DEFAULT)) 2730 != SM_IO_EOF && c != '\n') 2731 continue; 2732 } 2733 2734 switch (lbuf[0]) 2735 { 2736 case 'V': 2737 qfver = atoi(&lbuf[1]); 2738 break; 2739 2740 case 'P': 2741 w->w_pri = atol(&lbuf[1]); 2742 i &= ~NEED_P; 2743 break; 2744 2745 case 'T': 2746 w->w_ctime = atol(&lbuf[1]); 2747 i &= ~NEED_T; 2748 break; 2749 2750 case 'q': 2751 if (QueueMode != QM_QUARANTINE && 2752 QueueMode != QM_LOST) 2753 { 2754 if (tTd(41, 49)) 2755 sm_dprintf("%s not marked as quarantined but has a 'q' line\n", 2756 w->w_name); 2757 i |= HAS_QUARANTINE; 2758 } 2759 else if (QueueMode == QM_QUARANTINE) 2760 { 2761 if (QueueLimitQuarantine == NULL) 2762 { 2763 i &= ~NEED_QUARANTINE; 2764 break; 2765 } 2766 p = &lbuf[1]; 2767 check = QueueLimitQuarantine; 2768 while (check != NULL) 2769 { 2770 if (strcontainedin(false, 2771 check->queue_match, 2772 p) != 2773 check->queue_negate) 2774 break; 2775 else 2776 check = check->queue_next; 2777 } 2778 if (check != NULL) 2779 i &= ~NEED_QUARANTINE; 2780 } 2781 break; 2782 2783 case 'R': 2784 if (w->w_host == NULL && 2785 (p = strrchr(&lbuf[1], '@')) != NULL) 2786 { 2787 #if _FFR_RHS 2788 if (QueueSortOrder == QSO_BYSHUFFLE) 2789 w->w_host = newstr(&p[1]); 2790 else 2791 #endif /* _FFR_RHS */ 2792 w->w_host = strrev(&p[1]); 2793 makelower(w->w_host); 2794 i &= ~NEED_H; 2795 } 2796 if (QueueLimitRecipient == NULL) 2797 { 2798 i &= ~NEED_R; 2799 break; 2800 } 2801 if (qfver > 0) 2802 { 2803 p = strchr(&lbuf[1], ':'); 2804 if (p == NULL) 2805 p = &lbuf[1]; 2806 else 2807 ++p; /* skip over ':' */ 2808 } 2809 else 2810 p = &lbuf[1]; 2811 check = QueueLimitRecipient; 2812 while (check != NULL) 2813 { 2814 if (strcontainedin(true, 2815 check->queue_match, 2816 p) != 2817 check->queue_negate) 2818 break; 2819 else 2820 check = check->queue_next; 2821 } 2822 if (check != NULL) 2823 i &= ~NEED_R; 2824 break; 2825 2826 case 'S': 2827 check = QueueLimitSender; 2828 while (check != NULL) 2829 { 2830 if (strcontainedin(true, 2831 check->queue_match, 2832 &lbuf[1]) != 2833 check->queue_negate) 2834 break; 2835 else 2836 check = check->queue_next; 2837 } 2838 if (check != NULL) 2839 i &= ~NEED_S; 2840 break; 2841 2842 case 'K': 2843 age = curtime() - (time_t) atol(&lbuf[1]); 2844 if (age >= 0 && MinQueueAge > 0 && 2845 age < MinQueueAge) 2846 w->w_tooyoung = true; 2847 break; 2848 2849 case 'N': 2850 if (atol(&lbuf[1]) == 0) 2851 w->w_tooyoung = false; 2852 break; 2853 } 2854 } 2855 if (cf != NULL) 2856 (void) sm_io_close(cf, SM_TIME_DEFAULT); 2857 2858 if ((!doall && shouldqueue(w->w_pri, w->w_ctime)) || 2859 bitset(HAS_QUARANTINE, i) || 2860 bitset(NEED_QUARANTINE, i) || 2861 bitset(NEED_R|NEED_S, i)) 2862 { 2863 /* don't even bother sorting this job in */ 2864 if (tTd(41, 49)) 2865 sm_dprintf("skipping %s (%x)\n", w->w_name, i); 2866 sm_free(w->w_name); /* XXX */ 2867 if (w->w_host != NULL) 2868 sm_free(w->w_host); /* XXX */ 2869 wn--; 2870 } 2871 else 2872 ++num_ent; 2873 } 2874 (void) closedir(f); 2875 wn++; 2876 2877 i = wn - WorkListCount; 2878 WorkListCount += SM_MIN(num_ent, WorkListSize); 2879 2880 if (more != NULL) 2881 *more = WorkListCount < wn; 2882 2883 if (full != NULL) 2884 *full = (wn >= MaxQueueRun && MaxQueueRun > 0) || 2885 (WorkList == NULL && wn > 0); 2886 2887 return i; 2888 } 2889 /* 2890 ** SORTQ -- sort the work list 2891 ** 2892 ** First the old WorkQ is cleared away. Then the WorkList is sorted 2893 ** for all items so that important (higher sorting value) items are not 2894 ** trunctated off. Then the most important items are moved from 2895 ** WorkList to WorkQ. The lower count of 'max' or MaxListCount items 2896 ** are moved. 2897 ** 2898 ** Parameters: 2899 ** max -- maximum number of items to be placed in WorkQ 2900 ** 2901 ** Returns: 2902 ** the number of items in WorkQ 2903 ** 2904 ** Side Effects: 2905 ** WorkQ gets released and filled with new work. WorkList 2906 ** gets released. Work items get sorted in order. 2907 */ 2908 2909 static int 2910 sortq(max) 2911 int max; 2912 { 2913 register int i; /* local counter */ 2914 register WORK *w; /* tmp item pointer */ 2915 int wc = WorkListCount; /* trim size for WorkQ */ 2916 2917 if (WorkQ != NULL) 2918 { 2919 WORK *nw; 2920 2921 /* Clear out old WorkQ. */ 2922 for (w = WorkQ; w != NULL; w = nw) 2923 { 2924 nw = w->w_next; 2925 sm_free(w->w_name); /* XXX */ 2926 if (w->w_host != NULL) 2927 sm_free(w->w_host); /* XXX */ 2928 sm_free((char *) w); /* XXX */ 2929 } 2930 WorkQ = NULL; 2931 } 2932 2933 if (WorkList == NULL || wc <= 0) 2934 return 0; 2935 2936 /* 2937 ** The sort now takes place using all of the items in WorkList. 2938 ** The list gets trimmed to the most important items after the sort. 2939 ** If the trim were to happen before the sort then one or more 2940 ** important items might get truncated off -- not what we want. 2941 */ 2942 2943 if (QueueSortOrder == QSO_BYHOST) 2944 { 2945 /* 2946 ** Sort the work directory for the first time, 2947 ** based on host name, lock status, and priority. 2948 */ 2949 2950 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf1); 2951 2952 /* 2953 ** If one message to host is locked, "lock" all messages 2954 ** to that host. 2955 */ 2956 2957 i = 0; 2958 while (i < wc) 2959 { 2960 if (!WorkList[i].w_lock) 2961 { 2962 i++; 2963 continue; 2964 } 2965 w = &WorkList[i]; 2966 while (++i < wc) 2967 { 2968 if (WorkList[i].w_host == NULL && 2969 w->w_host == NULL) 2970 WorkList[i].w_lock = true; 2971 else if (WorkList[i].w_host != NULL && 2972 w->w_host != NULL && 2973 sm_strcasecmp(WorkList[i].w_host, 2974 w->w_host) == 0) 2975 WorkList[i].w_lock = true; 2976 else 2977 break; 2978 } 2979 } 2980 2981 /* 2982 ** Sort the work directory for the second time, 2983 ** based on lock status, host name, and priority. 2984 */ 2985 2986 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf2); 2987 } 2988 else if (QueueSortOrder == QSO_BYTIME) 2989 { 2990 /* 2991 ** Simple sort based on submission time only. 2992 */ 2993 2994 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf3); 2995 } 2996 else if (QueueSortOrder == QSO_BYFILENAME) 2997 { 2998 /* 2999 ** Sort based on queue filename. 3000 */ 3001 3002 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf4); 3003 } 3004 else if (QueueSortOrder == QSO_RANDOM) 3005 { 3006 /* 3007 ** Sort randomly. To avoid problems with an instable sort, 3008 ** use a random index into the queue file name to start 3009 ** comparison. 3010 */ 3011 3012 randi = get_rand_mod(MAXQFNAME); 3013 if (randi < 2) 3014 randi = 3; 3015 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf5); 3016 } 3017 else if (QueueSortOrder == QSO_BYMODTIME) 3018 { 3019 /* 3020 ** Simple sort based on modification time of queue file. 3021 ** This puts the oldest items first. 3022 */ 3023 3024 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf6); 3025 } 3026 #if _FFR_RHS 3027 else if (QueueSortOrder == QSO_BYSHUFFLE) 3028 { 3029 /* 3030 ** Simple sort based on shuffled host name. 3031 */ 3032 3033 init_shuffle_alphabet(); 3034 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf7); 3035 } 3036 #endif /* _FFR_RHS */ 3037 else if (QueueSortOrder == QSO_BYPRIORITY) 3038 { 3039 /* 3040 ** Simple sort based on queue priority only. 3041 */ 3042 3043 qsort((char *) WorkList, wc, sizeof *WorkList, workcmpf0); 3044 } 3045 /* else don't sort at all */ 3046 3047 /* Check if the per queue group item limit will be exceeded */ 3048 if (wc > max && max > 0) 3049 wc = max; 3050 3051 /* 3052 ** Convert the work list into canonical form. 3053 ** Should be turning it into a list of envelopes here perhaps. 3054 ** Only take the most important items up to the per queue group 3055 ** maximum. 3056 */ 3057 3058 for (i = wc; --i >= 0; ) 3059 { 3060 w = (WORK *) xalloc(sizeof *w); 3061 w->w_qgrp = WorkList[i].w_qgrp; 3062 w->w_qdir = WorkList[i].w_qdir; 3063 w->w_name = WorkList[i].w_name; 3064 w->w_host = WorkList[i].w_host; 3065 w->w_lock = WorkList[i].w_lock; 3066 w->w_tooyoung = WorkList[i].w_tooyoung; 3067 w->w_pri = WorkList[i].w_pri; 3068 w->w_ctime = WorkList[i].w_ctime; 3069 w->w_mtime = WorkList[i].w_mtime; 3070 w->w_next = WorkQ; 3071 WorkQ = w; 3072 } 3073 3074 /* free the rest of the list */ 3075 for (i = WorkListCount; --i >= wc; ) 3076 { 3077 sm_free(WorkList[i].w_name); 3078 if (WorkList[i].w_host != NULL) 3079 sm_free(WorkList[i].w_host); 3080 } 3081 3082 if (WorkList != NULL) 3083 sm_free(WorkList); /* XXX */ 3084 WorkList = NULL; 3085 WorkListSize = 0; 3086 WorkListCount = 0; 3087 3088 if (tTd(40, 1)) 3089 { 3090 for (w = WorkQ; w != NULL; w = w->w_next) 3091 { 3092 if (w->w_host != NULL) 3093 sm_dprintf("%22s: pri=%ld %s\n", 3094 w->w_name, w->w_pri, w->w_host); 3095 else 3096 sm_dprintf("%32s: pri=%ld\n", 3097 w->w_name, w->w_pri); 3098 } 3099 } 3100 3101 return wc; /* return number of WorkQ items */ 3102 } 3103 /* 3104 ** GROW_WLIST -- make the work list larger 3105 ** 3106 ** Parameters: 3107 ** qgrp -- the index for the queue group. 3108 ** qdir -- the index for the queue directory. 3109 ** 3110 ** Returns: 3111 ** none. 3112 ** 3113 ** Side Effects: 3114 ** Adds another QUEUESEGSIZE entries to WorkList if possible. 3115 ** It can fail if there isn't enough memory, so WorkListSize 3116 ** should be checked again upon return. 3117 */ 3118 3119 static void 3120 grow_wlist(qgrp, qdir) 3121 int qgrp; 3122 int qdir; 3123 { 3124 if (tTd(41, 1)) 3125 sm_dprintf("grow_wlist: WorkListSize=%d\n", WorkListSize); 3126 if (WorkList == NULL) 3127 { 3128 WorkList = (WORK *) xalloc((sizeof *WorkList) * 3129 (QUEUESEGSIZE + 1)); 3130 WorkListSize = QUEUESEGSIZE; 3131 } 3132 else 3133 { 3134 int newsize = WorkListSize + QUEUESEGSIZE; 3135 WORK *newlist = (WORK *) sm_realloc((char *) WorkList, 3136 (unsigned) sizeof(WORK) * (newsize + 1)); 3137 3138 if (newlist != NULL) 3139 { 3140 WorkListSize = newsize; 3141 WorkList = newlist; 3142 if (LogLevel > 1) 3143 { 3144 sm_syslog(LOG_INFO, NOQID, 3145 "grew WorkList for %s to %d", 3146 qid_printqueue(qgrp, qdir), 3147 WorkListSize); 3148 } 3149 } 3150 else if (LogLevel > 0) 3151 { 3152 sm_syslog(LOG_ALERT, NOQID, 3153 "FAILED to grow WorkList for %s to %d", 3154 qid_printqueue(qgrp, qdir), newsize); 3155 } 3156 } 3157 if (tTd(41, 1)) 3158 sm_dprintf("grow_wlist: WorkListSize now %d\n", WorkListSize); 3159 } 3160 /* 3161 ** WORKCMPF0 -- simple priority-only compare function. 3162 ** 3163 ** Parameters: 3164 ** a -- the first argument. 3165 ** b -- the second argument. 3166 ** 3167 ** Returns: 3168 ** -1 if a < b 3169 ** 0 if a == b 3170 ** +1 if a > b 3171 ** 3172 */ 3173 3174 static int 3175 workcmpf0(a, b) 3176 register WORK *a; 3177 register WORK *b; 3178 { 3179 long pa = a->w_pri; 3180 long pb = b->w_pri; 3181 3182 if (pa == pb) 3183 return 0; 3184 else if (pa > pb) 3185 return 1; 3186 else 3187 return -1; 3188 } 3189 /* 3190 ** WORKCMPF1 -- first compare function for ordering work based on host name. 3191 ** 3192 ** Sorts on host name, lock status, and priority in that order. 3193 ** 3194 ** Parameters: 3195 ** a -- the first argument. 3196 ** b -- the second argument. 3197 ** 3198 ** Returns: 3199 ** <0 if a < b 3200 ** 0 if a == b 3201 ** >0 if a > b 3202 ** 3203 */ 3204 3205 static int 3206 workcmpf1(a, b) 3207 register WORK *a; 3208 register WORK *b; 3209 { 3210 int i; 3211 3212 /* host name */ 3213 if (a->w_host != NULL && b->w_host == NULL) 3214 return 1; 3215 else if (a->w_host == NULL && b->w_host != NULL) 3216 return -1; 3217 if (a->w_host != NULL && b->w_host != NULL && 3218 (i = sm_strcasecmp(a->w_host, b->w_host)) != 0) 3219 return i; 3220 3221 /* lock status */ 3222 if (a->w_lock != b->w_lock) 3223 return b->w_lock - a->w_lock; 3224 3225 /* job priority */ 3226 return workcmpf0(a, b); 3227 } 3228 /* 3229 ** WORKCMPF2 -- second compare function for ordering work based on host name. 3230 ** 3231 ** Sorts on lock status, host name, and priority in that order. 3232 ** 3233 ** Parameters: 3234 ** a -- the first argument. 3235 ** b -- the second argument. 3236 ** 3237 ** Returns: 3238 ** <0 if a < b 3239 ** 0 if a == b 3240 ** >0 if a > b 3241 ** 3242 */ 3243 3244 static int 3245 workcmpf2(a, b) 3246 register WORK *a; 3247 register WORK *b; 3248 { 3249 int i; 3250 3251 /* lock status */ 3252 if (a->w_lock != b->w_lock) 3253 return a->w_lock - b->w_lock; 3254 3255 /* host name */ 3256 if (a->w_host != NULL && b->w_host == NULL) 3257 return 1; 3258 else if (a->w_host == NULL && b->w_host != NULL) 3259 return -1; 3260 if (a->w_host != NULL && b->w_host != NULL && 3261 (i = sm_strcasecmp(a->w_host, b->w_host)) != 0) 3262 return i; 3263 3264 /* job priority */ 3265 return workcmpf0(a, b); 3266 } 3267 /* 3268 ** WORKCMPF3 -- simple submission-time-only compare function. 3269 ** 3270 ** Parameters: 3271 ** a -- the first argument. 3272 ** b -- the second argument. 3273 ** 3274 ** Returns: 3275 ** -1 if a < b 3276 ** 0 if a == b 3277 ** +1 if a > b 3278 ** 3279 */ 3280 3281 static int 3282 workcmpf3(a, b) 3283 register WORK *a; 3284 register WORK *b; 3285 { 3286 if (a->w_ctime > b->w_ctime) 3287 return 1; 3288 else if (a->w_ctime < b->w_ctime) 3289 return -1; 3290 else 3291 return 0; 3292 } 3293 /* 3294 ** WORKCMPF4 -- compare based on file name 3295 ** 3296 ** Parameters: 3297 ** a -- the first argument. 3298 ** b -- the second argument. 3299 ** 3300 ** Returns: 3301 ** -1 if a < b 3302 ** 0 if a == b 3303 ** +1 if a > b 3304 ** 3305 */ 3306 3307 static int 3308 workcmpf4(a, b) 3309 register WORK *a; 3310 register WORK *b; 3311 { 3312 return strcmp(a->w_name, b->w_name); 3313 } 3314 /* 3315 ** WORKCMPF5 -- compare based on assigned random number 3316 ** 3317 ** Parameters: 3318 ** a -- the first argument (ignored). 3319 ** b -- the second argument (ignored). 3320 ** 3321 ** Returns: 3322 ** randomly 1/-1 3323 */ 3324 3325 /* ARGSUSED0 */ 3326 static int 3327 workcmpf5(a, b) 3328 register WORK *a; 3329 register WORK *b; 3330 { 3331 if (strlen(a->w_name) < randi || strlen(b->w_name) < randi) 3332 return -1; 3333 return a->w_name[randi] - b->w_name[randi]; 3334 } 3335 /* 3336 ** WORKCMPF6 -- simple modification-time-only compare function. 3337 ** 3338 ** Parameters: 3339 ** a -- the first argument. 3340 ** b -- the second argument. 3341 ** 3342 ** Returns: 3343 ** -1 if a < b 3344 ** 0 if a == b 3345 ** +1 if a > b 3346 ** 3347 */ 3348 3349 static int 3350 workcmpf6(a, b) 3351 register WORK *a; 3352 register WORK *b; 3353 { 3354 if (a->w_mtime > b->w_mtime) 3355 return 1; 3356 else if (a->w_mtime < b->w_mtime) 3357 return -1; 3358 else 3359 return 0; 3360 } 3361 #if _FFR_RHS 3362 /* 3363 ** WORKCMPF7 -- compare function for ordering work based on shuffled host name. 3364 ** 3365 ** Sorts on lock status, host name, and priority in that order. 3366 ** 3367 ** Parameters: 3368 ** a -- the first argument. 3369 ** b -- the second argument. 3370 ** 3371 ** Returns: 3372 ** <0 if a < b 3373 ** 0 if a == b 3374 ** >0 if a > b 3375 ** 3376 */ 3377 3378 static int 3379 workcmpf7(a, b) 3380 register WORK *a; 3381 register WORK *b; 3382 { 3383 int i; 3384 3385 /* lock status */ 3386 if (a->w_lock != b->w_lock) 3387 return a->w_lock - b->w_lock; 3388 3389 /* host name */ 3390 if (a->w_host != NULL && b->w_host == NULL) 3391 return 1; 3392 else if (a->w_host == NULL && b->w_host != NULL) 3393 return -1; 3394 if (a->w_host != NULL && b->w_host != NULL && 3395 (i = sm_strshufflecmp(a->w_host, b->w_host)) != 0) 3396 return i; 3397 3398 /* job priority */ 3399 return workcmpf0(a, b); 3400 } 3401 #endif /* _FFR_RHS */ 3402 /* 3403 ** STRREV -- reverse string 3404 ** 3405 ** Returns a pointer to a new string that is the reverse of 3406 ** the string pointed to by fwd. The space for the new 3407 ** string is obtained using xalloc(). 3408 ** 3409 ** Parameters: 3410 ** fwd -- the string to reverse. 3411 ** 3412 ** Returns: 3413 ** the reversed string. 3414 */ 3415 3416 static char * 3417 strrev(fwd) 3418 char *fwd; 3419 { 3420 char *rev = NULL; 3421 int len, cnt; 3422 3423 len = strlen(fwd); 3424 rev = xalloc(len + 1); 3425 for (cnt = 0; cnt < len; ++cnt) 3426 rev[cnt] = fwd[len - cnt - 1]; 3427 rev[len] = '\0'; 3428 return rev; 3429 } 3430 3431 #if _FFR_RHS 3432 3433 # define NASCII 128 3434 # define NCHAR 256 3435 3436 static unsigned char ShuffledAlphabet[NCHAR]; 3437 3438 void 3439 init_shuffle_alphabet() 3440 { 3441 static bool init = false; 3442 int i; 3443 3444 if (init) 3445 return; 3446 3447 /* fill the ShuffledAlphabet */ 3448 for (i = 0; i < NASCII; i++) 3449 ShuffledAlphabet[i] = i; 3450 3451 /* mix it */ 3452 for (i = 1; i < NASCII; i++) 3453 { 3454 register int j = get_random() % NASCII; 3455 register int tmp; 3456 3457 tmp = ShuffledAlphabet[j]; 3458 ShuffledAlphabet[j] = ShuffledAlphabet[i]; 3459 ShuffledAlphabet[i] = tmp; 3460 } 3461 3462 /* make it case insensitive */ 3463 for (i = 'A'; i <= 'Z'; i++) 3464 ShuffledAlphabet[i] = ShuffledAlphabet[i + 'a' - 'A']; 3465 3466 /* fill the upper part */ 3467 for (i = 0; i < NASCII; i++) 3468 ShuffledAlphabet[i + NASCII] = ShuffledAlphabet[i]; 3469 init = true; 3470 } 3471 3472 static int 3473 sm_strshufflecmp(a, b) 3474 char *a; 3475 char *b; 3476 { 3477 const unsigned char *us1 = (const unsigned char *) a; 3478 const unsigned char *us2 = (const unsigned char *) b; 3479 3480 while (ShuffledAlphabet[*us1] == ShuffledAlphabet[*us2++]) 3481 { 3482 if (*us1++ == '\0') 3483 return 0; 3484 } 3485 return (ShuffledAlphabet[*us1] - ShuffledAlphabet[*--us2]); 3486 } 3487 #endif /* _FFR_RHS */ 3488 3489 /* 3490 ** DOWORK -- do a work request. 3491 ** 3492 ** Parameters: 3493 ** qgrp -- the index of the queue group for the job. 3494 ** qdir -- the index of the queue directory for the job. 3495 ** id -- the ID of the job to run. 3496 ** forkflag -- if set, run this in background. 3497 ** requeueflag -- if set, reinstantiate the queue quickly. 3498 ** This is used when expanding aliases in the queue. 3499 ** If forkflag is also set, it doesn't wait for the 3500 ** child. 3501 ** e - the envelope in which to run it. 3502 ** 3503 ** Returns: 3504 ** process id of process that is running the queue job. 3505 ** 3506 ** Side Effects: 3507 ** The work request is satisfied if possible. 3508 */ 3509 3510 pid_t 3511 dowork(qgrp, qdir, id, forkflag, requeueflag, e) 3512 int qgrp; 3513 int qdir; 3514 char *id; 3515 bool forkflag; 3516 bool requeueflag; 3517 register ENVELOPE *e; 3518 { 3519 register pid_t pid; 3520 SM_RPOOL_T *rpool; 3521 3522 if (tTd(40, 1)) 3523 sm_dprintf("dowork(%s/%s)\n", qid_printqueue(qgrp, qdir), id); 3524 3525 /* 3526 ** Fork for work. 3527 */ 3528 3529 if (forkflag) 3530 { 3531 /* 3532 ** Since the delivery may happen in a child and the 3533 ** parent does not wait, the parent may close the 3534 ** maps thereby removing any shared memory used by 3535 ** the map. Therefore, close the maps now so the 3536 ** child will dynamically open them if necessary. 3537 */ 3538 3539 closemaps(false); 3540 3541 pid = fork(); 3542 if (pid < 0) 3543 { 3544 syserr("dowork: cannot fork"); 3545 return 0; 3546 } 3547 else if (pid > 0) 3548 { 3549 /* parent -- clean out connection cache */ 3550 mci_flush(false, NULL); 3551 } 3552 else 3553 { 3554 /* 3555 ** Initialize exception stack and default exception 3556 ** handler for child process. 3557 */ 3558 3559 /* Reset global flags */ 3560 RestartRequest = NULL; 3561 RestartWorkGroup = false; 3562 ShutdownRequest = NULL; 3563 PendingSignal = 0; 3564 CurrentPid = getpid(); 3565 sm_exc_newthread(fatal_error); 3566 3567 /* 3568 ** See note above about SMTP processes and SIGCHLD. 3569 */ 3570 3571 if (OpMode == MD_SMTP || 3572 OpMode == MD_DAEMON || 3573 MaxQueueChildren > 0) 3574 { 3575 proc_list_clear(); 3576 sm_releasesignal(SIGCHLD); 3577 (void) sm_signal(SIGCHLD, SIG_DFL); 3578 } 3579 3580 /* child -- error messages to the transcript */ 3581 QuickAbort = OnlyOneError = false; 3582 } 3583 } 3584 else 3585 { 3586 pid = 0; 3587 } 3588 3589 if (pid == 0) 3590 { 3591 /* 3592 ** CHILD 3593 ** Lock the control file to avoid duplicate deliveries. 3594 ** Then run the file as though we had just read it. 3595 ** We save an idea of the temporary name so we 3596 ** can recover on interrupt. 3597 */ 3598 3599 if (forkflag) 3600 { 3601 /* Reset global flags */ 3602 RestartRequest = NULL; 3603 RestartWorkGroup = false; 3604 ShutdownRequest = NULL; 3605 PendingSignal = 0; 3606 } 3607 3608 /* set basic modes, etc. */ 3609 sm_clear_events(); 3610 clearstats(); 3611 rpool = sm_rpool_new_x(NULL); 3612 clearenvelope(e, false, rpool); 3613 e->e_flags |= EF_QUEUERUN|EF_GLOBALERRS; 3614 set_delivery_mode(SM_DELIVER, e); 3615 e->e_errormode = EM_MAIL; 3616 e->e_id = id; 3617 e->e_qgrp = qgrp; 3618 e->e_qdir = qdir; 3619 GrabTo = UseErrorsTo = false; 3620 ExitStat = EX_OK; 3621 if (forkflag) 3622 { 3623 disconnect(1, e); 3624 set_op_mode(MD_QUEUERUN); 3625 } 3626 sm_setproctitle(true, e, "%s from queue", qid_printname(e)); 3627 if (LogLevel > 76) 3628 sm_syslog(LOG_DEBUG, e->e_id, "dowork, pid=%d", 3629 (int) CurrentPid); 3630 3631 /* don't use the headers from sendmail.cf... */ 3632 e->e_header = NULL; 3633 3634 /* read the queue control file -- return if locked */ 3635 if (!readqf(e, false)) 3636 { 3637 if (tTd(40, 4) && e->e_id != NULL) 3638 sm_dprintf("readqf(%s) failed\n", 3639 qid_printname(e)); 3640 e->e_id = NULL; 3641 if (forkflag) 3642 finis(false, true, EX_OK); 3643 else 3644 { 3645 /* adding this frees 8 bytes */ 3646 clearenvelope(e, false, rpool); 3647 3648 /* adding this frees 12 bytes */ 3649 sm_rpool_free(rpool); 3650 e->e_rpool = NULL; 3651 return 0; 3652 } 3653 } 3654 3655 e->e_flags |= EF_INQUEUE; 3656 eatheader(e, requeueflag, true); 3657 3658 if (requeueflag) 3659 queueup(e, false, false); 3660 3661 /* do the delivery */ 3662 sendall(e, SM_DELIVER); 3663 3664 /* finish up and exit */ 3665 if (forkflag) 3666 finis(true, true, ExitStat); 3667 else 3668 { 3669 dropenvelope(e, true, false); 3670 sm_rpool_free(rpool); 3671 e->e_rpool = NULL; 3672 } 3673 } 3674 e->e_id = NULL; 3675 return pid; 3676 } 3677 3678 /* 3679 ** DOWORKLIST -- process a list of envelopes as work requests 3680 ** 3681 ** Similar to dowork(), except that after forking, it processes an 3682 ** envelope and its siblings, treating each envelope as a work request. 3683 ** 3684 ** Parameters: 3685 ** el -- envelope to be processed including its siblings. 3686 ** forkflag -- if set, run this in background. 3687 ** requeueflag -- if set, reinstantiate the queue quickly. 3688 ** This is used when expanding aliases in the queue. 3689 ** If forkflag is also set, it doesn't wait for the 3690 ** child. 3691 ** 3692 ** Returns: 3693 ** process id of process that is running the queue job. 3694 ** 3695 ** Side Effects: 3696 ** The work request is satisfied if possible. 3697 */ 3698 3699 pid_t 3700 doworklist(el, forkflag, requeueflag) 3701 ENVELOPE *el; 3702 bool forkflag; 3703 bool requeueflag; 3704 { 3705 register pid_t pid; 3706 ENVELOPE *ei; 3707 3708 if (tTd(40, 1)) 3709 sm_dprintf("doworklist()\n"); 3710 3711 /* 3712 ** Fork for work. 3713 */ 3714 3715 if (forkflag) 3716 { 3717 /* 3718 ** Since the delivery may happen in a child and the 3719 ** parent does not wait, the parent may close the 3720 ** maps thereby removing any shared memory used by 3721 ** the map. Therefore, close the maps now so the 3722 ** child will dynamically open them if necessary. 3723 */ 3724 3725 closemaps(false); 3726 3727 pid = fork(); 3728 if (pid < 0) 3729 { 3730 syserr("doworklist: cannot fork"); 3731 return 0; 3732 } 3733 else if (pid > 0) 3734 { 3735 /* parent -- clean out connection cache */ 3736 mci_flush(false, NULL); 3737 } 3738 else 3739 { 3740 /* 3741 ** Initialize exception stack and default exception 3742 ** handler for child process. 3743 */ 3744 3745 /* Reset global flags */ 3746 RestartRequest = NULL; 3747 RestartWorkGroup = false; 3748 ShutdownRequest = NULL; 3749 PendingSignal = 0; 3750 CurrentPid = getpid(); 3751 sm_exc_newthread(fatal_error); 3752 3753 /* 3754 ** See note above about SMTP processes and SIGCHLD. 3755 */ 3756 3757 if (OpMode == MD_SMTP || 3758 OpMode == MD_DAEMON || 3759 MaxQueueChildren > 0) 3760 { 3761 proc_list_clear(); 3762 sm_releasesignal(SIGCHLD); 3763 (void) sm_signal(SIGCHLD, SIG_DFL); 3764 } 3765 3766 /* child -- error messages to the transcript */ 3767 QuickAbort = OnlyOneError = false; 3768 } 3769 } 3770 else 3771 { 3772 pid = 0; 3773 } 3774 3775 if (pid != 0) 3776 return pid; 3777 3778 /* 3779 ** IN CHILD 3780 ** Lock the control file to avoid duplicate deliveries. 3781 ** Then run the file as though we had just read it. 3782 ** We save an idea of the temporary name so we 3783 ** can recover on interrupt. 3784 */ 3785 3786 if (forkflag) 3787 { 3788 /* Reset global flags */ 3789 RestartRequest = NULL; 3790 RestartWorkGroup = false; 3791 ShutdownRequest = NULL; 3792 PendingSignal = 0; 3793 } 3794 3795 /* set basic modes, etc. */ 3796 sm_clear_events(); 3797 clearstats(); 3798 GrabTo = UseErrorsTo = false; 3799 ExitStat = EX_OK; 3800 if (forkflag) 3801 { 3802 disconnect(1, el); 3803 set_op_mode(MD_QUEUERUN); 3804 } 3805 if (LogLevel > 76) 3806 sm_syslog(LOG_DEBUG, el->e_id, "doworklist, pid=%d", 3807 (int) CurrentPid); 3808 3809 for (ei = el; ei != NULL; ei = ei->e_sibling) 3810 { 3811 ENVELOPE e; 3812 SM_RPOOL_T *rpool; 3813 3814 if (WILL_BE_QUEUED(ei->e_sendmode)) 3815 continue; 3816 else if (QueueMode != QM_QUARANTINE && 3817 ei->e_quarmsg != NULL) 3818 continue; 3819 3820 rpool = sm_rpool_new_x(NULL); 3821 clearenvelope(&e, true, rpool); 3822 e.e_flags |= EF_QUEUERUN|EF_GLOBALERRS; 3823 set_delivery_mode(SM_DELIVER, &e); 3824 e.e_errormode = EM_MAIL; 3825 e.e_id = ei->e_id; 3826 e.e_qgrp = ei->e_qgrp; 3827 e.e_qdir = ei->e_qdir; 3828 openxscript(&e); 3829 sm_setproctitle(true, &e, "%s from queue", qid_printname(&e)); 3830 3831 /* don't use the headers from sendmail.cf... */ 3832 e.e_header = NULL; 3833 CurEnv = &e; 3834 3835 /* read the queue control file -- return if locked */ 3836 if (readqf(&e, false)) 3837 { 3838 e.e_flags |= EF_INQUEUE; 3839 eatheader(&e, requeueflag, true); 3840 3841 if (requeueflag) 3842 queueup(&e, false, false); 3843 3844 /* do the delivery */ 3845 sendall(&e, SM_DELIVER); 3846 dropenvelope(&e, true, false); 3847 } 3848 else 3849 { 3850 if (tTd(40, 4) && e.e_id != NULL) 3851 sm_dprintf("readqf(%s) failed\n", 3852 qid_printname(&e)); 3853 } 3854 sm_rpool_free(rpool); 3855 ei->e_id = NULL; 3856 } 3857 3858 /* restore CurEnv */ 3859 CurEnv = el; 3860 3861 /* finish up and exit */ 3862 if (forkflag) 3863 finis(true, true, ExitStat); 3864 return 0; 3865 } 3866 /* 3867 ** READQF -- read queue file and set up environment. 3868 ** 3869 ** Parameters: 3870 ** e -- the envelope of the job to run. 3871 ** openonly -- only open the qf (returned as e_lockfp) 3872 ** 3873 ** Returns: 3874 ** true if it successfully read the queue file. 3875 ** false otherwise. 3876 ** 3877 ** Side Effects: 3878 ** The queue file is returned locked. 3879 */ 3880 3881 static bool 3882 readqf(e, openonly) 3883 register ENVELOPE *e; 3884 bool openonly; 3885 { 3886 register SM_FILE_T *qfp; 3887 ADDRESS *ctladdr; 3888 struct stat st, stf; 3889 char *bp; 3890 int qfver = 0; 3891 long hdrsize = 0; 3892 register char *p; 3893 char *frcpt = NULL; 3894 char *orcpt = NULL; 3895 bool nomore = false; 3896 bool bogus = false; 3897 MODE_T qsafe; 3898 char *err; 3899 char qf[MAXPATHLEN]; 3900 char buf[MAXLINE]; 3901 3902 /* 3903 ** Read and process the file. 3904 */ 3905 3906 (void) sm_strlcpy(qf, queuename(e, ANYQFL_LETTER), sizeof qf); 3907 qfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, qf, SM_IO_RDWR_B, NULL); 3908 if (qfp == NULL) 3909 { 3910 int save_errno = errno; 3911 3912 if (tTd(40, 8)) 3913 sm_dprintf("readqf(%s): sm_io_open failure (%s)\n", 3914 qf, sm_errstring(errno)); 3915 errno = save_errno; 3916 if (errno != ENOENT 3917 ) 3918 syserr("readqf: no control file %s", qf); 3919 RELEASE_QUEUE; 3920 return false; 3921 } 3922 3923 if (!lockfile(sm_io_getinfo(qfp, SM_IO_WHAT_FD, NULL), qf, NULL, 3924 LOCK_EX|LOCK_NB)) 3925 { 3926 /* being processed by another queuer */ 3927 if (Verbose) 3928 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 3929 "%s: locked\n", e->e_id); 3930 if (tTd(40, 8)) 3931 sm_dprintf("%s: locked\n", e->e_id); 3932 if (LogLevel > 19) 3933 sm_syslog(LOG_DEBUG, e->e_id, "locked"); 3934 (void) sm_io_close(qfp, SM_TIME_DEFAULT); 3935 RELEASE_QUEUE; 3936 return false; 3937 } 3938 3939 RELEASE_QUEUE; 3940 3941 /* 3942 ** Prevent locking race condition. 3943 ** 3944 ** Process A: readqf(): qfp = fopen(qffile) 3945 ** Process B: queueup(): rename(tf, qf) 3946 ** Process B: unlocks(tf) 3947 ** Process A: lockfile(qf); 3948 ** 3949 ** Process A (us) has the old qf file (before the rename deleted 3950 ** the directory entry) and will be delivering based on old data. 3951 ** This can lead to multiple deliveries of the same recipients. 3952 ** 3953 ** Catch this by checking if the underlying qf file has changed 3954 ** *after* acquiring our lock and if so, act as though the file 3955 ** was still locked (i.e., just return like the lockfile() case 3956 ** above. 3957 */ 3958 3959 if (stat(qf, &stf) < 0 || 3960 fstat(sm_io_getinfo(qfp, SM_IO_WHAT_FD, NULL), &st) < 0) 3961 { 3962 /* must have been being processed by someone else */ 3963 if (tTd(40, 8)) 3964 sm_dprintf("readqf(%s): [f]stat failure (%s)\n", 3965 qf, sm_errstring(errno)); 3966 (void) sm_io_close(qfp, SM_TIME_DEFAULT); 3967 return false; 3968 } 3969 3970 if (st.st_nlink != stf.st_nlink || 3971 st.st_dev != stf.st_dev || 3972 ST_INODE(st) != ST_INODE(stf) || 3973 #if HAS_ST_GEN && 0 /* AFS returns garbage in st_gen */ 3974 st.st_gen != stf.st_gen || 3975 #endif /* HAS_ST_GEN && 0 */ 3976 st.st_uid != stf.st_uid || 3977 st.st_gid != stf.st_gid || 3978 st.st_size != stf.st_size) 3979 { 3980 /* changed after opened */ 3981 if (Verbose) 3982 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 3983 "%s: changed\n", e->e_id); 3984 if (tTd(40, 8)) 3985 sm_dprintf("%s: changed\n", e->e_id); 3986 if (LogLevel > 19) 3987 sm_syslog(LOG_DEBUG, e->e_id, "changed"); 3988 (void) sm_io_close(qfp, SM_TIME_DEFAULT); 3989 return false; 3990 } 3991 3992 /* 3993 ** Check the queue file for plausibility to avoid attacks. 3994 */ 3995 3996 qsafe = S_IWOTH|S_IWGRP; 3997 if (bitset(S_IWGRP, QueueFileMode)) 3998 qsafe &= ~S_IWGRP; 3999 4000 bogus = st.st_uid != geteuid() && 4001 st.st_uid != TrustedUid && 4002 geteuid() != RealUid; 4003 4004 /* 4005 ** If this qf file results from a set-group-ID binary, then 4006 ** we check whether the directory is group-writable, 4007 ** the queue file mode contains the group-writable bit, and 4008 ** the groups are the same. 4009 ** Notice: this requires that the set-group-ID binary is used to 4010 ** run the queue! 4011 */ 4012 4013 if (bogus && st.st_gid == getegid() && UseMSP) 4014 { 4015 char delim; 4016 struct stat dst; 4017 4018 bp = SM_LAST_DIR_DELIM(qf); 4019 if (bp == NULL) 4020 delim = '\0'; 4021 else 4022 { 4023 delim = *bp; 4024 *bp = '\0'; 4025 } 4026 if (stat(delim == '\0' ? "." : qf, &dst) < 0) 4027 syserr("readqf: cannot stat directory %s", 4028 delim == '\0' ? "." : qf); 4029 else 4030 { 4031 bogus = !(bitset(S_IWGRP, QueueFileMode) && 4032 bitset(S_IWGRP, dst.st_mode) && 4033 dst.st_gid == st.st_gid); 4034 } 4035 if (delim != '\0') 4036 *bp = delim; 4037 } 4038 if (!bogus) 4039 bogus = bitset(qsafe, st.st_mode); 4040 if (bogus) 4041 { 4042 if (LogLevel > 0) 4043 { 4044 sm_syslog(LOG_ALERT, e->e_id, 4045 "bogus queue file, uid=%d, gid=%d, mode=%o", 4046 st.st_uid, st.st_gid, st.st_mode); 4047 } 4048 if (tTd(40, 8)) 4049 sm_dprintf("readqf(%s): bogus file\n", qf); 4050 e->e_flags |= EF_INQUEUE; 4051 if (!openonly) 4052 loseqfile(e, "bogus file uid/gid in mqueue"); 4053 (void) sm_io_close(qfp, SM_TIME_DEFAULT); 4054 return false; 4055 } 4056 4057 if (st.st_size == 0) 4058 { 4059 /* must be a bogus file -- if also old, just remove it */ 4060 if (!openonly && st.st_ctime + 10 * 60 < curtime()) 4061 { 4062 (void) xunlink(queuename(e, DATAFL_LETTER)); 4063 (void) xunlink(queuename(e, ANYQFL_LETTER)); 4064 } 4065 (void) sm_io_close(qfp, SM_TIME_DEFAULT); 4066 return false; 4067 } 4068 4069 if (st.st_nlink == 0) 4070 { 4071 /* 4072 ** Race condition -- we got a file just as it was being 4073 ** unlinked. Just assume it is zero length. 4074 */ 4075 4076 (void) sm_io_close(qfp, SM_TIME_DEFAULT); 4077 return false; 4078 } 4079 4080 #if _FFR_TRUSTED_QF 4081 /* 4082 ** If we don't own the file mark it as unsafe. 4083 ** However, allow TrustedUser to own it as well 4084 ** in case TrustedUser manipulates the queue. 4085 */ 4086 4087 if (st.st_uid != geteuid() && st.st_uid != TrustedUid) 4088 e->e_flags |= EF_UNSAFE; 4089 #else /* _FFR_TRUSTED_QF */ 4090 /* If we don't own the file mark it as unsafe */ 4091 if (st.st_uid != geteuid()) 4092 e->e_flags |= EF_UNSAFE; 4093 #endif /* _FFR_TRUSTED_QF */ 4094 4095 /* good file -- save this lock */ 4096 e->e_lockfp = qfp; 4097 4098 /* Just wanted the open file */ 4099 if (openonly) 4100 return true; 4101 4102 /* do basic system initialization */ 4103 initsys(e); 4104 macdefine(&e->e_macro, A_PERM, 'i', e->e_id); 4105 4106 LineNumber = 0; 4107 e->e_flags |= EF_GLOBALERRS; 4108 set_op_mode(MD_QUEUERUN); 4109 ctladdr = NULL; 4110 e->e_qfletter = queue_letter(e, ANYQFL_LETTER); 4111 e->e_dfqgrp = e->e_qgrp; 4112 e->e_dfqdir = e->e_qdir; 4113 #if _FFR_QUEUE_MACRO 4114 macdefine(&e->e_macro, A_TEMP, macid("{queue}"), 4115 qid_printqueue(e->e_qgrp, e->e_qdir)); 4116 #endif /* _FFR_QUEUE_MACRO */ 4117 e->e_dfino = -1; 4118 e->e_msgsize = -1; 4119 while ((bp = fgetfolded(buf, sizeof buf, qfp)) != NULL) 4120 { 4121 unsigned long qflags; 4122 ADDRESS *q; 4123 int r; 4124 time_t now; 4125 auto char *ep; 4126 4127 if (tTd(40, 4)) 4128 sm_dprintf("+++++ %s\n", bp); 4129 if (nomore) 4130 { 4131 /* hack attack */ 4132 hackattack: 4133 syserr("SECURITY ALERT: extra or bogus data in queue file: %s", 4134 bp); 4135 err = "bogus queue line"; 4136 goto fail; 4137 } 4138 switch (bp[0]) 4139 { 4140 case 'A': /* AUTH= parameter */ 4141 if (!xtextok(&bp[1])) 4142 goto hackattack; 4143 e->e_auth_param = sm_rpool_strdup_x(e->e_rpool, &bp[1]); 4144 break; 4145 4146 case 'B': /* body type */ 4147 r = check_bodytype(&bp[1]); 4148 if (!BODYTYPE_VALID(r)) 4149 goto hackattack; 4150 e->e_bodytype = sm_rpool_strdup_x(e->e_rpool, &bp[1]); 4151 break; 4152 4153 case 'C': /* specify controlling user */ 4154 ctladdr = setctluser(&bp[1], qfver, e); 4155 break; 4156 4157 case 'D': /* data file name */ 4158 /* obsolete -- ignore */ 4159 break; 4160 4161 case 'd': /* data file directory name */ 4162 { 4163 int qgrp, qdir; 4164 4165 #if _FFR_MSP_PARANOIA 4166 /* forbid queue groups in MSP? */ 4167 if (UseMSP) 4168 goto hackattack; 4169 #endif /* _FFR_MSP_PARANOIA */ 4170 for (qgrp = 0; 4171 qgrp < NumQueue && Queue[qgrp] != NULL; 4172 ++qgrp) 4173 { 4174 for (qdir = 0; 4175 qdir < Queue[qgrp]->qg_numqueues; 4176 ++qdir) 4177 { 4178 if (strcmp(&bp[1], 4179 Queue[qgrp]->qg_qpaths[qdir].qp_name) 4180 == 0) 4181 { 4182 e->e_dfqgrp = qgrp; 4183 e->e_dfqdir = qdir; 4184 goto done; 4185 } 4186 } 4187 } 4188 err = "bogus queue file directory"; 4189 goto fail; 4190 done: 4191 break; 4192 } 4193 4194 case 'E': /* specify error recipient */ 4195 /* no longer used */ 4196 break; 4197 4198 case 'F': /* flag bits */ 4199 if (strncmp(bp, "From ", 5) == 0) 4200 { 4201 /* we are being spoofed! */ 4202 syserr("SECURITY ALERT: bogus qf line %s", bp); 4203 err = "bogus queue line"; 4204 goto fail; 4205 } 4206 for (p = &bp[1]; *p != '\0'; p++) 4207 { 4208 switch (*p) 4209 { 4210 case '8': /* has 8 bit data */ 4211 e->e_flags |= EF_HAS8BIT; 4212 break; 4213 4214 case 'b': /* delete Bcc: header */ 4215 e->e_flags |= EF_DELETE_BCC; 4216 break; 4217 4218 case 'd': /* envelope has DSN RET= */ 4219 e->e_flags |= EF_RET_PARAM; 4220 break; 4221 4222 case 'n': /* don't return body */ 4223 e->e_flags |= EF_NO_BODY_RETN; 4224 break; 4225 4226 case 'r': /* response */ 4227 e->e_flags |= EF_RESPONSE; 4228 break; 4229 4230 case 's': /* split */ 4231 e->e_flags |= EF_SPLIT; 4232 break; 4233 4234 case 'w': /* warning sent */ 4235 e->e_flags |= EF_WARNING; 4236 break; 4237 } 4238 } 4239 break; 4240 4241 case 'q': /* quarantine reason */ 4242 e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, &bp[1]); 4243 macdefine(&e->e_macro, A_PERM, 4244 macid("{quarantine}"), e->e_quarmsg); 4245 break; 4246 4247 case 'H': /* header */ 4248 4249 /* 4250 ** count size before chompheader() destroys the line. 4251 ** this isn't accurate due to macro expansion, but 4252 ** better than before. "-3" to skip H?? at least. 4253 */ 4254 4255 hdrsize += strlen(bp) - 3; 4256 (void) chompheader(&bp[1], CHHDR_QUEUE, NULL, e); 4257 break; 4258 4259 case 'I': /* data file's inode number */ 4260 /* regenerated below */ 4261 break; 4262 4263 case 'K': /* time of last delivery attempt */ 4264 e->e_dtime = atol(&buf[1]); 4265 break; 4266 4267 case 'L': /* Solaris Content-Length: */ 4268 case 'M': /* message */ 4269 /* ignore this; we want a new message next time */ 4270 break; 4271 4272 case 'N': /* number of delivery attempts */ 4273 e->e_ntries = atoi(&buf[1]); 4274 4275 /* if this has been tried recently, let it be */ 4276 now = curtime(); 4277 if (e->e_ntries > 0 && e->e_dtime <= now && 4278 now < e->e_dtime + MinQueueAge) 4279 { 4280 char *howlong; 4281 4282 howlong = pintvl(now - e->e_dtime, true); 4283 if (Verbose) 4284 (void) sm_io_fprintf(smioout, 4285 SM_TIME_DEFAULT, 4286 "%s: too young (%s)\n", 4287 e->e_id, howlong); 4288 if (tTd(40, 8)) 4289 sm_dprintf("%s: too young (%s)\n", 4290 e->e_id, howlong); 4291 if (LogLevel > 19) 4292 sm_syslog(LOG_DEBUG, e->e_id, 4293 "too young (%s)", 4294 howlong); 4295 e->e_id = NULL; 4296 unlockqueue(e); 4297 return false; 4298 } 4299 macdefine(&e->e_macro, A_TEMP, 4300 macid("{ntries}"), &buf[1]); 4301 4302 #if NAMED_BIND 4303 /* adjust BIND parameters immediately */ 4304 if (e->e_ntries == 0) 4305 { 4306 _res.retry = TimeOuts.res_retry[RES_TO_FIRST]; 4307 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST]; 4308 } 4309 else 4310 { 4311 _res.retry = TimeOuts.res_retry[RES_TO_NORMAL]; 4312 _res.retrans = TimeOuts.res_retrans[RES_TO_NORMAL]; 4313 } 4314 #endif /* NAMED_BIND */ 4315 break; 4316 4317 case 'P': /* message priority */ 4318 e->e_msgpriority = atol(&bp[1]) + WkTimeFact; 4319 break; 4320 4321 case 'Q': /* original recipient */ 4322 orcpt = sm_rpool_strdup_x(e->e_rpool, &bp[1]); 4323 break; 4324 4325 case 'r': /* final recipient */ 4326 frcpt = sm_rpool_strdup_x(e->e_rpool, &bp[1]); 4327 break; 4328 4329 case 'R': /* specify recipient */ 4330 p = bp; 4331 qflags = 0; 4332 if (qfver >= 1) 4333 { 4334 /* get flag bits */ 4335 while (*++p != '\0' && *p != ':') 4336 { 4337 switch (*p) 4338 { 4339 case 'N': 4340 qflags |= QHASNOTIFY; 4341 break; 4342 4343 case 'S': 4344 qflags |= QPINGONSUCCESS; 4345 break; 4346 4347 case 'F': 4348 qflags |= QPINGONFAILURE; 4349 break; 4350 4351 case 'D': 4352 qflags |= QPINGONDELAY; 4353 break; 4354 4355 case 'P': 4356 qflags |= QPRIMARY; 4357 break; 4358 4359 case 'A': 4360 if (ctladdr != NULL) 4361 ctladdr->q_flags |= QALIAS; 4362 break; 4363 4364 default: /* ignore or complain? */ 4365 break; 4366 } 4367 } 4368 } 4369 else 4370 qflags |= QPRIMARY; 4371 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), 4372 "e r"); 4373 if (*p != '\0') 4374 q = parseaddr(++p, NULLADDR, RF_COPYALL, '\0', 4375 NULL, e, true); 4376 else 4377 q = NULL; 4378 if (q != NULL) 4379 { 4380 /* make sure we keep the current qgrp */ 4381 if (ISVALIDQGRP(e->e_qgrp)) 4382 q->q_qgrp = e->e_qgrp; 4383 q->q_alias = ctladdr; 4384 if (qfver >= 1) 4385 q->q_flags &= ~Q_PINGFLAGS; 4386 q->q_flags |= qflags; 4387 q->q_finalrcpt = frcpt; 4388 q->q_orcpt = orcpt; 4389 (void) recipient(q, &e->e_sendqueue, 0, e); 4390 } 4391 frcpt = NULL; 4392 orcpt = NULL; 4393 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), 4394 NULL); 4395 break; 4396 4397 case 'S': /* sender */ 4398 setsender(sm_rpool_strdup_x(e->e_rpool, &bp[1]), 4399 e, NULL, '\0', true); 4400 break; 4401 4402 case 'T': /* init time */ 4403 e->e_ctime = atol(&bp[1]); 4404 break; 4405 4406 case 'V': /* queue file version number */ 4407 qfver = atoi(&bp[1]); 4408 if (qfver <= QF_VERSION) 4409 break; 4410 syserr("Version number in queue file (%d) greater than max (%d)", 4411 qfver, QF_VERSION); 4412 err = "unsupported queue file version"; 4413 goto fail; 4414 /* NOTREACHED */ 4415 break; 4416 4417 case 'Z': /* original envelope id from ESMTP */ 4418 e->e_envid = sm_rpool_strdup_x(e->e_rpool, &bp[1]); 4419 macdefine(&e->e_macro, A_PERM, 4420 macid("{dsn_envid}"), e->e_envid); 4421 break; 4422 4423 case '!': /* deliver by */ 4424 4425 /* format: flag (1 char) space long-integer */ 4426 e->e_dlvr_flag = buf[1]; 4427 e->e_deliver_by = strtol(&buf[3], NULL, 10); 4428 4429 case '$': /* define macro */ 4430 { 4431 char *p; 4432 4433 /* XXX elimate p? */ 4434 r = macid_parse(&bp[1], &ep); 4435 if (r == 0) 4436 break; 4437 p = sm_rpool_strdup_x(e->e_rpool, ep); 4438 macdefine(&e->e_macro, A_PERM, r, p); 4439 } 4440 break; 4441 4442 case '.': /* terminate file */ 4443 nomore = true; 4444 break; 4445 4446 #if _FFR_QUEUEDELAY 4447 case 'G': 4448 case 'Y': 4449 4450 /* 4451 ** Maintain backward compatibility for 4452 ** users who defined _FFR_QUEUEDELAY in 4453 ** previous releases. Remove this 4454 ** code in 8.14 or 8.15. 4455 */ 4456 4457 if (qfver == 5 || qfver == 7) 4458 break; 4459 4460 /* If not qfver 5 or 7, then 'G' or 'Y' is invalid */ 4461 /* FALLTHROUGH */ 4462 #endif /* _FFR_QUEUEDELAY */ 4463 4464 default: 4465 syserr("readqf: %s: line %d: bad line \"%s\"", 4466 qf, LineNumber, shortenstring(bp, MAXSHORTSTR)); 4467 err = "unrecognized line"; 4468 goto fail; 4469 } 4470 4471 if (bp != buf) 4472 sm_free(bp); /* XXX */ 4473 } 4474 4475 /* 4476 ** If we haven't read any lines, this queue file is empty. 4477 ** Arrange to remove it without referencing any null pointers. 4478 */ 4479 4480 if (LineNumber == 0) 4481 { 4482 errno = 0; 4483 e->e_flags |= EF_CLRQUEUE|EF_FATALERRS|EF_RESPONSE; 4484 return true; 4485 } 4486 4487 /* Check to make sure we have a complete queue file read */ 4488 if (!nomore) 4489 { 4490 syserr("readqf: %s: incomplete queue file read", qf); 4491 (void) sm_io_close(qfp, SM_TIME_DEFAULT); 4492 return false; 4493 } 4494 4495 /* possibly set ${dsn_ret} macro */ 4496 if (bitset(EF_RET_PARAM, e->e_flags)) 4497 { 4498 if (bitset(EF_NO_BODY_RETN, e->e_flags)) 4499 macdefine(&e->e_macro, A_PERM, 4500 macid("{dsn_ret}"), "hdrs"); 4501 else 4502 macdefine(&e->e_macro, A_PERM, 4503 macid("{dsn_ret}"), "full"); 4504 } 4505 4506 /* 4507 ** Arrange to read the data file. 4508 */ 4509 4510 p = queuename(e, DATAFL_LETTER); 4511 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, p, SM_IO_RDONLY_B, 4512 NULL); 4513 if (e->e_dfp == NULL) 4514 { 4515 syserr("readqf: cannot open %s", p); 4516 } 4517 else 4518 { 4519 e->e_flags |= EF_HAS_DF; 4520 if (fstat(sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL), &st) 4521 >= 0) 4522 { 4523 e->e_msgsize = st.st_size + hdrsize; 4524 e->e_dfdev = st.st_dev; 4525 e->e_dfino = ST_INODE(st); 4526 (void) sm_snprintf(buf, sizeof buf, "%ld", 4527 e->e_msgsize); 4528 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), 4529 buf); 4530 } 4531 } 4532 4533 return true; 4534 4535 fail: 4536 /* 4537 ** There was some error reading the qf file (reason is in err var.) 4538 ** Cleanup: 4539 ** close file; clear e_lockfp since it is the same as qfp, 4540 ** hence it is invalid (as file) after qfp is closed; 4541 ** the qf file is on disk, so set the flag to avoid calling 4542 ** queueup() with bogus data. 4543 */ 4544 4545 if (qfp != NULL) 4546 (void) sm_io_close(qfp, SM_TIME_DEFAULT); 4547 e->e_lockfp = NULL; 4548 e->e_flags |= EF_INQUEUE; 4549 loseqfile(e, err); 4550 return false; 4551 } 4552 /* 4553 ** PRTSTR -- print a string, "unprintable" characters are shown as \oct 4554 ** 4555 ** Parameters: 4556 ** s -- string to print 4557 ** ml -- maximum length of output 4558 ** 4559 ** Returns: 4560 ** number of entries 4561 ** 4562 ** Side Effects: 4563 ** Prints a string on stdout. 4564 */ 4565 4566 static void 4567 prtstr(s, ml) 4568 char *s; 4569 int ml; 4570 { 4571 int c; 4572 4573 if (s == NULL) 4574 return; 4575 while (ml-- > 0 && ((c = *s++) != '\0')) 4576 { 4577 if (c == '\\') 4578 { 4579 if (ml-- > 0) 4580 { 4581 (void) sm_io_putc(smioout, SM_TIME_DEFAULT, c); 4582 (void) sm_io_putc(smioout, SM_TIME_DEFAULT, c); 4583 } 4584 } 4585 else if (isascii(c) && isprint(c)) 4586 (void) sm_io_putc(smioout, SM_TIME_DEFAULT, c); 4587 else 4588 { 4589 if ((ml -= 3) > 0) 4590 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 4591 "\\%03o", c & 0xFF); 4592 } 4593 } 4594 } 4595 /* 4596 ** PRINTNQE -- print out number of entries in the mail queue 4597 ** 4598 ** Parameters: 4599 ** out -- output file pointer. 4600 ** prefix -- string to output in front of each line. 4601 ** 4602 ** Returns: 4603 ** none. 4604 */ 4605 4606 void 4607 printnqe(out, prefix) 4608 SM_FILE_T *out; 4609 char *prefix; 4610 { 4611 #if SM_CONF_SHM 4612 int i, k = 0, nrequests = 0; 4613 bool unknown = false; 4614 4615 if (ShmId == SM_SHM_NO_ID) 4616 { 4617 if (prefix == NULL) 4618 (void) sm_io_fprintf(out, SM_TIME_DEFAULT, 4619 "Data unavailable: shared memory not updated\n"); 4620 else 4621 (void) sm_io_fprintf(out, SM_TIME_DEFAULT, 4622 "%sNOTCONFIGURED:-1\r\n", prefix); 4623 return; 4624 } 4625 for (i = 0; i < NumQueue && Queue[i] != NULL; i++) 4626 { 4627 int j; 4628 4629 k++; 4630 for (j = 0; j < Queue[i]->qg_numqueues; j++) 4631 { 4632 int n; 4633 4634 if (StopRequest) 4635 stop_sendmail(); 4636 4637 n = QSHM_ENTRIES(Queue[i]->qg_qpaths[j].qp_idx); 4638 if (prefix != NULL) 4639 (void) sm_io_fprintf(out, SM_TIME_DEFAULT, 4640 "%s%s:%d\r\n", 4641 prefix, qid_printqueue(i, j), n); 4642 else if (n < 0) 4643 { 4644 (void) sm_io_fprintf(out, SM_TIME_DEFAULT, 4645 "%s: unknown number of entries\n", 4646 qid_printqueue(i, j)); 4647 unknown = true; 4648 } 4649 else if (n == 0) 4650 { 4651 (void) sm_io_fprintf(out, SM_TIME_DEFAULT, 4652 "%s is empty\n", 4653 qid_printqueue(i, j)); 4654 } 4655 else if (n > 0) 4656 { 4657 (void) sm_io_fprintf(out, SM_TIME_DEFAULT, 4658 "%s: entries=%d\n", 4659 qid_printqueue(i, j), n); 4660 nrequests += n; 4661 k++; 4662 } 4663 } 4664 } 4665 if (prefix == NULL && k > 1) 4666 (void) sm_io_fprintf(out, SM_TIME_DEFAULT, 4667 "\t\tTotal requests: %d%s\n", 4668 nrequests, unknown ? " (about)" : ""); 4669 #else /* SM_CONF_SHM */ 4670 if (prefix == NULL) 4671 (void) sm_io_fprintf(out, SM_TIME_DEFAULT, 4672 "Data unavailable without shared memory support\n"); 4673 else 4674 (void) sm_io_fprintf(out, SM_TIME_DEFAULT, 4675 "%sNOTAVAILABLE:-1\r\n", prefix); 4676 #endif /* SM_CONF_SHM */ 4677 } 4678 /* 4679 ** PRINTQUEUE -- print out a representation of the mail queue 4680 ** 4681 ** Parameters: 4682 ** none. 4683 ** 4684 ** Returns: 4685 ** none. 4686 ** 4687 ** Side Effects: 4688 ** Prints a listing of the mail queue on the standard output. 4689 */ 4690 4691 void 4692 printqueue() 4693 { 4694 int i, k = 0, nrequests = 0; 4695 4696 for (i = 0; i < NumQueue && Queue[i] != NULL; i++) 4697 { 4698 int j; 4699 4700 k++; 4701 for (j = 0; j < Queue[i]->qg_numqueues; j++) 4702 { 4703 if (StopRequest) 4704 stop_sendmail(); 4705 nrequests += print_single_queue(i, j); 4706 k++; 4707 } 4708 } 4709 if (k > 1) 4710 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 4711 "\t\tTotal requests: %d\n", 4712 nrequests); 4713 } 4714 /* 4715 ** PRINT_SINGLE_QUEUE -- print out a representation of a single mail queue 4716 ** 4717 ** Parameters: 4718 ** qgrp -- the index of the queue group. 4719 ** qdir -- the queue directory. 4720 ** 4721 ** Returns: 4722 ** number of requests in mail queue. 4723 ** 4724 ** Side Effects: 4725 ** Prints a listing of the mail queue on the standard output. 4726 */ 4727 4728 int 4729 print_single_queue(qgrp, qdir) 4730 int qgrp; 4731 int qdir; 4732 { 4733 register WORK *w; 4734 SM_FILE_T *f; 4735 int nrequests; 4736 char qd[MAXPATHLEN]; 4737 char qddf[MAXPATHLEN]; 4738 char buf[MAXLINE]; 4739 4740 if (qdir == NOQDIR) 4741 { 4742 (void) sm_strlcpy(qd, ".", sizeof qd); 4743 (void) sm_strlcpy(qddf, ".", sizeof qddf); 4744 } 4745 else 4746 { 4747 (void) sm_strlcpyn(qd, sizeof qd, 2, 4748 Queue[qgrp]->qg_qpaths[qdir].qp_name, 4749 (bitset(QP_SUBQF, 4750 Queue[qgrp]->qg_qpaths[qdir].qp_subdirs) 4751 ? "/qf" : "")); 4752 (void) sm_strlcpyn(qddf, sizeof qddf, 2, 4753 Queue[qgrp]->qg_qpaths[qdir].qp_name, 4754 (bitset(QP_SUBDF, 4755 Queue[qgrp]->qg_qpaths[qdir].qp_subdirs) 4756 ? "/df" : "")); 4757 } 4758 4759 /* 4760 ** Check for permission to print the queue 4761 */ 4762 4763 if (bitset(PRIV_RESTRICTMAILQ, PrivacyFlags) && RealUid != 0) 4764 { 4765 struct stat st; 4766 #ifdef NGROUPS_MAX 4767 int n; 4768 extern GIDSET_T InitialGidSet[NGROUPS_MAX]; 4769 #endif /* NGROUPS_MAX */ 4770 4771 if (stat(qd, &st) < 0) 4772 { 4773 syserr("Cannot stat %s", 4774 qid_printqueue(qgrp, qdir)); 4775 return 0; 4776 } 4777 #ifdef NGROUPS_MAX 4778 n = NGROUPS_MAX; 4779 while (--n >= 0) 4780 { 4781 if (InitialGidSet[n] == st.st_gid) 4782 break; 4783 } 4784 if (n < 0 && RealGid != st.st_gid) 4785 #else /* NGROUPS_MAX */ 4786 if (RealGid != st.st_gid) 4787 #endif /* NGROUPS_MAX */ 4788 { 4789 usrerr("510 You are not permitted to see the queue"); 4790 setstat(EX_NOPERM); 4791 return 0; 4792 } 4793 } 4794 4795 /* 4796 ** Read and order the queue. 4797 */ 4798 4799 nrequests = gatherq(qgrp, qdir, true, NULL, NULL); 4800 (void) sortq(Queue[qgrp]->qg_maxlist); 4801 4802 /* 4803 ** Print the work list that we have read. 4804 */ 4805 4806 /* first see if there is anything */ 4807 if (nrequests <= 0) 4808 { 4809 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%s is empty\n", 4810 qid_printqueue(qgrp, qdir)); 4811 return 0; 4812 } 4813 4814 sm_getla(); /* get load average */ 4815 4816 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\t\t%s (%d request%s", 4817 qid_printqueue(qgrp, qdir), 4818 nrequests, nrequests == 1 ? "" : "s"); 4819 if (MaxQueueRun > 0 && nrequests > MaxQueueRun) 4820 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 4821 ", only %d printed", MaxQueueRun); 4822 if (Verbose) 4823 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 4824 ")\n-----Q-ID----- --Size-- -Priority- ---Q-Time--- --------Sender/Recipient--------\n"); 4825 else 4826 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 4827 ")\n-----Q-ID----- --Size-- -----Q-Time----- ------------Sender/Recipient-----------\n"); 4828 for (w = WorkQ; w != NULL; w = w->w_next) 4829 { 4830 struct stat st; 4831 auto time_t submittime = 0; 4832 long dfsize; 4833 int flags = 0; 4834 int qfver; 4835 char quarmsg[MAXLINE]; 4836 char statmsg[MAXLINE]; 4837 char bodytype[MAXNAME + 1]; 4838 char qf[MAXPATHLEN]; 4839 4840 if (StopRequest) 4841 stop_sendmail(); 4842 4843 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "%13s", 4844 w->w_name + 2); 4845 (void) sm_strlcpyn(qf, sizeof qf, 3, qd, "/", w->w_name); 4846 f = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, qf, SM_IO_RDONLY_B, 4847 NULL); 4848 if (f == NULL) 4849 { 4850 if (errno == EPERM) 4851 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 4852 " (permission denied)\n"); 4853 else if (errno == ENOENT) 4854 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 4855 " (job completed)\n"); 4856 else 4857 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 4858 " (%s)\n", 4859 sm_errstring(errno)); 4860 errno = 0; 4861 continue; 4862 } 4863 w->w_name[0] = DATAFL_LETTER; 4864 (void) sm_strlcpyn(qf, sizeof qf, 3, qddf, "/", w->w_name); 4865 if (stat(qf, &st) >= 0) 4866 dfsize = st.st_size; 4867 else 4868 { 4869 ENVELOPE e; 4870 4871 /* 4872 ** Maybe the df file can't be statted because 4873 ** it is in a different directory than the qf file. 4874 ** In order to find out, we must read the qf file. 4875 */ 4876 4877 newenvelope(&e, &BlankEnvelope, sm_rpool_new_x(NULL)); 4878 e.e_id = w->w_name + 2; 4879 e.e_qgrp = qgrp; 4880 e.e_qdir = qdir; 4881 dfsize = -1; 4882 if (readqf(&e, false)) 4883 { 4884 char *df = queuename(&e, DATAFL_LETTER); 4885 if (stat(df, &st) >= 0) 4886 dfsize = st.st_size; 4887 } 4888 if (e.e_lockfp != NULL) 4889 { 4890 (void) sm_io_close(e.e_lockfp, SM_TIME_DEFAULT); 4891 e.e_lockfp = NULL; 4892 } 4893 clearenvelope(&e, false, e.e_rpool); 4894 sm_rpool_free(e.e_rpool); 4895 } 4896 if (w->w_lock) 4897 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "*"); 4898 else if (QueueMode == QM_LOST) 4899 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "?"); 4900 else if (w->w_tooyoung) 4901 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "-"); 4902 else if (shouldqueue(w->w_pri, w->w_ctime)) 4903 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "X"); 4904 else 4905 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, " "); 4906 4907 errno = 0; 4908 4909 quarmsg[0] = '\0'; 4910 statmsg[0] = bodytype[0] = '\0'; 4911 qfver = 0; 4912 while (sm_io_fgets(f, SM_TIME_DEFAULT, buf, sizeof buf) != NULL) 4913 { 4914 register int i; 4915 register char *p; 4916 4917 if (StopRequest) 4918 stop_sendmail(); 4919 4920 fixcrlf(buf, true); 4921 switch (buf[0]) 4922 { 4923 case 'V': /* queue file version */ 4924 qfver = atoi(&buf[1]); 4925 break; 4926 4927 case 'M': /* error message */ 4928 if ((i = strlen(&buf[1])) >= sizeof statmsg) 4929 i = sizeof statmsg - 1; 4930 memmove(statmsg, &buf[1], i); 4931 statmsg[i] = '\0'; 4932 break; 4933 4934 case 'q': /* quarantine reason */ 4935 if ((i = strlen(&buf[1])) >= sizeof quarmsg) 4936 i = sizeof quarmsg - 1; 4937 memmove(quarmsg, &buf[1], i); 4938 quarmsg[i] = '\0'; 4939 break; 4940 4941 case 'B': /* body type */ 4942 if ((i = strlen(&buf[1])) >= sizeof bodytype) 4943 i = sizeof bodytype - 1; 4944 memmove(bodytype, &buf[1], i); 4945 bodytype[i] = '\0'; 4946 break; 4947 4948 case 'S': /* sender name */ 4949 if (Verbose) 4950 { 4951 (void) sm_io_fprintf(smioout, 4952 SM_TIME_DEFAULT, 4953 "%8ld %10ld%c%.12s ", 4954 dfsize, 4955 w->w_pri, 4956 bitset(EF_WARNING, flags) 4957 ? '+' : ' ', 4958 ctime(&submittime) + 4); 4959 prtstr(&buf[1], 78); 4960 } 4961 else 4962 { 4963 (void) sm_io_fprintf(smioout, 4964 SM_TIME_DEFAULT, 4965 "%8ld %.16s ", 4966 dfsize, 4967 ctime(&submittime)); 4968 prtstr(&buf[1], 39); 4969 } 4970 4971 if (quarmsg[0] != '\0') 4972 { 4973 (void) sm_io_fprintf(smioout, 4974 SM_TIME_DEFAULT, 4975 "\n QUARANTINE: %.*s", 4976 Verbose ? 100 : 60, 4977 quarmsg); 4978 quarmsg[0] = '\0'; 4979 } 4980 4981 if (statmsg[0] != '\0' || bodytype[0] != '\0') 4982 { 4983 (void) sm_io_fprintf(smioout, 4984 SM_TIME_DEFAULT, 4985 "\n %10.10s", 4986 bodytype); 4987 if (statmsg[0] != '\0') 4988 (void) sm_io_fprintf(smioout, 4989 SM_TIME_DEFAULT, 4990 " (%.*s)", 4991 Verbose ? 100 : 60, 4992 statmsg); 4993 statmsg[0] = '\0'; 4994 } 4995 break; 4996 4997 case 'C': /* controlling user */ 4998 if (Verbose) 4999 (void) sm_io_fprintf(smioout, 5000 SM_TIME_DEFAULT, 5001 "\n\t\t\t\t\t\t(---%.64s---)", 5002 &buf[1]); 5003 break; 5004 5005 case 'R': /* recipient name */ 5006 p = &buf[1]; 5007 if (qfver >= 1) 5008 { 5009 p = strchr(p, ':'); 5010 if (p == NULL) 5011 break; 5012 p++; 5013 } 5014 if (Verbose) 5015 { 5016 (void) sm_io_fprintf(smioout, 5017 SM_TIME_DEFAULT, 5018 "\n\t\t\t\t\t\t"); 5019 prtstr(p, 71); 5020 } 5021 else 5022 { 5023 (void) sm_io_fprintf(smioout, 5024 SM_TIME_DEFAULT, 5025 "\n\t\t\t\t\t "); 5026 prtstr(p, 38); 5027 } 5028 if (Verbose && statmsg[0] != '\0') 5029 { 5030 (void) sm_io_fprintf(smioout, 5031 SM_TIME_DEFAULT, 5032 "\n\t\t (%.100s)", 5033 statmsg); 5034 statmsg[0] = '\0'; 5035 } 5036 break; 5037 5038 case 'T': /* creation time */ 5039 submittime = atol(&buf[1]); 5040 break; 5041 5042 case 'F': /* flag bits */ 5043 for (p = &buf[1]; *p != '\0'; p++) 5044 { 5045 switch (*p) 5046 { 5047 case 'w': 5048 flags |= EF_WARNING; 5049 break; 5050 } 5051 } 5052 } 5053 } 5054 if (submittime == (time_t) 0) 5055 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 5056 " (no control file)"); 5057 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "\n"); 5058 (void) sm_io_close(f, SM_TIME_DEFAULT); 5059 } 5060 return nrequests; 5061 } 5062 5063 /* 5064 ** QUEUE_LETTER -- get the proper queue letter for the current QueueMode. 5065 ** 5066 ** Parameters: 5067 ** e -- envelope to build it in/from. 5068 ** type -- the file type, used as the first character 5069 ** of the file name. 5070 ** 5071 ** Returns: 5072 ** the letter to use 5073 */ 5074 5075 static char 5076 queue_letter(e, type) 5077 ENVELOPE *e; 5078 int type; 5079 { 5080 /* Change type according to QueueMode */ 5081 if (type == ANYQFL_LETTER) 5082 { 5083 if (e->e_quarmsg != NULL) 5084 type = QUARQF_LETTER; 5085 else 5086 { 5087 switch (QueueMode) 5088 { 5089 case QM_NORMAL: 5090 type = NORMQF_LETTER; 5091 break; 5092 5093 case QM_QUARANTINE: 5094 type = QUARQF_LETTER; 5095 break; 5096 5097 case QM_LOST: 5098 type = LOSEQF_LETTER; 5099 break; 5100 5101 default: 5102 /* should never happen */ 5103 abort(); 5104 /* NOTREACHED */ 5105 } 5106 } 5107 } 5108 return type; 5109 } 5110 5111 /* 5112 ** QUEUENAME -- build a file name in the queue directory for this envelope. 5113 ** 5114 ** Parameters: 5115 ** e -- envelope to build it in/from. 5116 ** type -- the file type, used as the first character 5117 ** of the file name. 5118 ** 5119 ** Returns: 5120 ** a pointer to the queue name (in a static buffer). 5121 ** 5122 ** Side Effects: 5123 ** If no id code is already assigned, queuename() will 5124 ** assign an id code with assign_queueid(). If no queue 5125 ** directory is assigned, one will be set with setnewqueue(). 5126 */ 5127 5128 char * 5129 queuename(e, type) 5130 register ENVELOPE *e; 5131 int type; 5132 { 5133 int qd, qg; 5134 char *sub = "/"; 5135 char pref[3]; 5136 static char buf[MAXPATHLEN]; 5137 5138 /* Assign an ID if needed */ 5139 if (e->e_id == NULL) 5140 assign_queueid(e); 5141 type = queue_letter(e, type); 5142 5143 /* begin of filename */ 5144 pref[0] = (char) type; 5145 pref[1] = 'f'; 5146 pref[2] = '\0'; 5147 5148 /* Assign a queue group/directory if needed */ 5149 if (type == XSCRPT_LETTER) 5150 { 5151 /* 5152 ** We don't want to call setnewqueue() if we are fetching 5153 ** the pathname of the transcript file, because setnewqueue 5154 ** chooses a queue, and sometimes we need to write to the 5155 ** transcript file before we have gathered enough information 5156 ** to choose a queue. 5157 */ 5158 5159 if (e->e_xfqgrp == NOQGRP || e->e_xfqdir == NOQDIR) 5160 { 5161 if (e->e_qgrp != NOQGRP && e->e_qdir != NOQDIR) 5162 { 5163 e->e_xfqgrp = e->e_qgrp; 5164 e->e_xfqdir = e->e_qdir; 5165 } 5166 else 5167 { 5168 e->e_xfqgrp = 0; 5169 if (Queue[e->e_xfqgrp]->qg_numqueues <= 1) 5170 e->e_xfqdir = 0; 5171 else 5172 { 5173 e->e_xfqdir = get_rand_mod( 5174 Queue[e->e_xfqgrp]->qg_numqueues); 5175 } 5176 } 5177 } 5178 qd = e->e_xfqdir; 5179 qg = e->e_xfqgrp; 5180 } 5181 else 5182 { 5183 if (e->e_qgrp == NOQGRP || e->e_qdir == NOQDIR) 5184 setnewqueue(e); 5185 if (type == DATAFL_LETTER) 5186 { 5187 qd = e->e_dfqdir; 5188 qg = e->e_dfqgrp; 5189 } 5190 else 5191 { 5192 qd = e->e_qdir; 5193 qg = e->e_qgrp; 5194 } 5195 } 5196 5197 /* xf files always have a valid qd and qg picked above */ 5198 if (e->e_qdir == NOQDIR && type != XSCRPT_LETTER) 5199 (void) sm_strlcpyn(buf, sizeof buf, 2, pref, e->e_id); 5200 else 5201 { 5202 switch (type) 5203 { 5204 case DATAFL_LETTER: 5205 if (bitset(QP_SUBDF, Queue[qg]->qg_qpaths[qd].qp_subdirs)) 5206 sub = "/df/"; 5207 break; 5208 5209 case QUARQF_LETTER: 5210 case TEMPQF_LETTER: 5211 case NEWQFL_LETTER: 5212 case LOSEQF_LETTER: 5213 case NORMQF_LETTER: 5214 if (bitset(QP_SUBQF, Queue[qg]->qg_qpaths[qd].qp_subdirs)) 5215 sub = "/qf/"; 5216 break; 5217 5218 case XSCRPT_LETTER: 5219 if (bitset(QP_SUBXF, Queue[qg]->qg_qpaths[qd].qp_subdirs)) 5220 sub = "/xf/"; 5221 break; 5222 5223 default: 5224 sm_abort("queuename: bad queue file type %d", type); 5225 } 5226 5227 (void) sm_strlcpyn(buf, sizeof buf, 4, 5228 Queue[qg]->qg_qpaths[qd].qp_name, 5229 sub, pref, e->e_id); 5230 } 5231 5232 if (tTd(7, 2)) 5233 sm_dprintf("queuename: %s\n", buf); 5234 return buf; 5235 } 5236 5237 /* 5238 ** INIT_QID_ALG -- Initialize the (static) parameters that are used to 5239 ** generate a queue ID. 5240 ** 5241 ** This function is called by the daemon to reset 5242 ** LastQueueTime and LastQueuePid which are used by assign_queueid(). 5243 ** Otherwise the algorithm may cause problems because 5244 ** LastQueueTime and LastQueuePid are set indirectly by main() 5245 ** before the daemon process is started, hence LastQueuePid is not 5246 ** the pid of the daemon and therefore a child of the daemon can 5247 ** actually have the same pid as LastQueuePid which means the section 5248 ** in assign_queueid(): 5249 ** * see if we need to get a new base time/pid * 5250 ** is NOT triggered which will cause the same queue id to be generated. 5251 ** 5252 ** Parameters: 5253 ** none 5254 ** 5255 ** Returns: 5256 ** none. 5257 */ 5258 5259 void 5260 init_qid_alg() 5261 { 5262 LastQueueTime = 0; 5263 LastQueuePid = -1; 5264 } 5265 5266 /* 5267 ** ASSIGN_QUEUEID -- assign a queue ID for this envelope. 5268 ** 5269 ** Assigns an id code if one does not already exist. 5270 ** This code assumes that nothing will remain in the queue for 5271 ** longer than 60 years. It is critical that files with the given 5272 ** name do not already exist in the queue. 5273 ** [No longer initializes e_qdir to NOQDIR.] 5274 ** 5275 ** Parameters: 5276 ** e -- envelope to set it in. 5277 ** 5278 ** Returns: 5279 ** none. 5280 */ 5281 5282 static const char QueueIdChars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; 5283 # define QIC_LEN 60 5284 # define QIC_LEN_R 62 5285 5286 /* 5287 ** Note: the length is "officially" 60 because minutes and seconds are 5288 ** usually only 0-59. However (Linux): 5289 ** tm_sec The number of seconds after the minute, normally in 5290 ** the range 0 to 59, but can be up to 61 to allow for 5291 ** leap seconds. 5292 ** Hence the real length of the string is 62 to take this into account. 5293 ** Alternatively % QIC_LEN can (should) be used for access everywhere. 5294 */ 5295 5296 # define queuenextid() CurrentPid 5297 5298 5299 void 5300 assign_queueid(e) 5301 register ENVELOPE *e; 5302 { 5303 pid_t pid = queuenextid(); 5304 static int cX = 0; 5305 static long random_offset; 5306 struct tm *tm; 5307 char idbuf[MAXQFNAME - 2]; 5308 int seq; 5309 5310 if (e->e_id != NULL) 5311 return; 5312 5313 /* see if we need to get a new base time/pid */ 5314 if (cX >= QIC_LEN * QIC_LEN || LastQueueTime == 0 || 5315 LastQueuePid != pid) 5316 { 5317 time_t then = LastQueueTime; 5318 5319 /* if the first time through, pick a random offset */ 5320 if (LastQueueTime == 0) 5321 random_offset = get_random(); 5322 5323 while ((LastQueueTime = curtime()) == then && 5324 LastQueuePid == pid) 5325 { 5326 (void) sleep(1); 5327 } 5328 LastQueuePid = queuenextid(); 5329 cX = 0; 5330 } 5331 5332 /* 5333 ** Generate a new sequence number between 0 and QIC_LEN*QIC_LEN-1. 5334 ** This lets us generate up to QIC_LEN*QIC_LEN unique queue ids 5335 ** per second, per process. With envelope splitting, 5336 ** a single message can consume many queue ids. 5337 */ 5338 5339 seq = (int)((cX + random_offset) % (QIC_LEN * QIC_LEN)); 5340 ++cX; 5341 if (tTd(7, 50)) 5342 sm_dprintf("assign_queueid: random_offset = %ld (%d)\n", 5343 random_offset, seq); 5344 5345 tm = gmtime(&LastQueueTime); 5346 idbuf[0] = QueueIdChars[tm->tm_year % QIC_LEN]; 5347 idbuf[1] = QueueIdChars[tm->tm_mon]; 5348 idbuf[2] = QueueIdChars[tm->tm_mday]; 5349 idbuf[3] = QueueIdChars[tm->tm_hour]; 5350 idbuf[4] = QueueIdChars[tm->tm_min % QIC_LEN_R]; 5351 idbuf[5] = QueueIdChars[tm->tm_sec % QIC_LEN_R]; 5352 idbuf[6] = QueueIdChars[seq / QIC_LEN]; 5353 idbuf[7] = QueueIdChars[seq % QIC_LEN]; 5354 (void) sm_snprintf(&idbuf[8], sizeof idbuf - 8, "%06d", 5355 (int) LastQueuePid); 5356 e->e_id = sm_rpool_strdup_x(e->e_rpool, idbuf); 5357 macdefine(&e->e_macro, A_PERM, 'i', e->e_id); 5358 #if 0 5359 /* XXX: inherited from MainEnvelope */ 5360 e->e_qgrp = NOQGRP; /* too early to do anything else */ 5361 e->e_qdir = NOQDIR; 5362 e->e_xfqgrp = NOQGRP; 5363 #endif /* 0 */ 5364 5365 /* New ID means it's not on disk yet */ 5366 e->e_qfletter = '\0'; 5367 5368 if (tTd(7, 1)) 5369 sm_dprintf("assign_queueid: assigned id %s, e=%p\n", 5370 e->e_id, e); 5371 if (LogLevel > 93) 5372 sm_syslog(LOG_DEBUG, e->e_id, "assigned id"); 5373 } 5374 /* 5375 ** SYNC_QUEUE_TIME -- Assure exclusive PID in any given second 5376 ** 5377 ** Make sure one PID can't be used by two processes in any one second. 5378 ** 5379 ** If the system rotates PIDs fast enough, may get the 5380 ** same pid in the same second for two distinct processes. 5381 ** This will interfere with the queue file naming system. 5382 ** 5383 ** Parameters: 5384 ** none 5385 ** 5386 ** Returns: 5387 ** none 5388 */ 5389 5390 void 5391 sync_queue_time() 5392 { 5393 #if FAST_PID_RECYCLE 5394 if (OpMode != MD_TEST && 5395 OpMode != MD_VERIFY && 5396 LastQueueTime > 0 && 5397 LastQueuePid == CurrentPid && 5398 curtime() == LastQueueTime) 5399 (void) sleep(1); 5400 #endif /* FAST_PID_RECYCLE */ 5401 } 5402 /* 5403 ** UNLOCKQUEUE -- unlock the queue entry for a specified envelope 5404 ** 5405 ** Parameters: 5406 ** e -- the envelope to unlock. 5407 ** 5408 ** Returns: 5409 ** none 5410 ** 5411 ** Side Effects: 5412 ** unlocks the queue for `e'. 5413 */ 5414 5415 void 5416 unlockqueue(e) 5417 ENVELOPE *e; 5418 { 5419 if (tTd(51, 4)) 5420 sm_dprintf("unlockqueue(%s)\n", 5421 e->e_id == NULL ? "NOQUEUE" : e->e_id); 5422 5423 5424 /* if there is a lock file in the envelope, close it */ 5425 if (e->e_lockfp != NULL) 5426 (void) sm_io_close(e->e_lockfp, SM_TIME_DEFAULT); 5427 e->e_lockfp = NULL; 5428 5429 /* don't create a queue id if we don't already have one */ 5430 if (e->e_id == NULL) 5431 return; 5432 5433 /* remove the transcript */ 5434 if (LogLevel > 87) 5435 sm_syslog(LOG_DEBUG, e->e_id, "unlock"); 5436 if (!tTd(51, 104)) 5437 (void) xunlink(queuename(e, XSCRPT_LETTER)); 5438 } 5439 /* 5440 ** SETCTLUSER -- create a controlling address 5441 ** 5442 ** Create a fake "address" given only a local login name; this is 5443 ** used as a "controlling user" for future recipient addresses. 5444 ** 5445 ** Parameters: 5446 ** user -- the user name of the controlling user. 5447 ** qfver -- the version stamp of this queue file. 5448 ** e -- envelope 5449 ** 5450 ** Returns: 5451 ** An address descriptor for the controlling user, 5452 ** using storage allocated from e->e_rpool. 5453 ** 5454 */ 5455 5456 static ADDRESS * 5457 setctluser(user, qfver, e) 5458 char *user; 5459 int qfver; 5460 ENVELOPE *e; 5461 { 5462 register ADDRESS *a; 5463 struct passwd *pw; 5464 char *p; 5465 5466 /* 5467 ** See if this clears our concept of controlling user. 5468 */ 5469 5470 if (user == NULL || *user == '\0') 5471 return NULL; 5472 5473 /* 5474 ** Set up addr fields for controlling user. 5475 */ 5476 5477 a = (ADDRESS *) sm_rpool_malloc_x(e->e_rpool, sizeof *a); 5478 memset((char *) a, '\0', sizeof *a); 5479 5480 if (*user == ':') 5481 { 5482 p = &user[1]; 5483 a->q_user = sm_rpool_strdup_x(e->e_rpool, p); 5484 } 5485 else 5486 { 5487 p = strtok(user, ":"); 5488 a->q_user = sm_rpool_strdup_x(e->e_rpool, user); 5489 if (qfver >= 2) 5490 { 5491 if ((p = strtok(NULL, ":")) != NULL) 5492 a->q_uid = atoi(p); 5493 if ((p = strtok(NULL, ":")) != NULL) 5494 a->q_gid = atoi(p); 5495 if ((p = strtok(NULL, ":")) != NULL) 5496 { 5497 char *o; 5498 5499 a->q_flags |= QGOODUID; 5500 5501 /* if there is another ':': restore it */ 5502 if ((o = strtok(NULL, ":")) != NULL && o > p) 5503 o[-1] = ':'; 5504 } 5505 } 5506 else if ((pw = sm_getpwnam(user)) != NULL) 5507 { 5508 if (*pw->pw_dir == '\0') 5509 a->q_home = NULL; 5510 else if (strcmp(pw->pw_dir, "/") == 0) 5511 a->q_home = ""; 5512 else 5513 a->q_home = sm_rpool_strdup_x(e->e_rpool, pw->pw_dir); 5514 a->q_uid = pw->pw_uid; 5515 a->q_gid = pw->pw_gid; 5516 a->q_flags |= QGOODUID; 5517 } 5518 } 5519 5520 a->q_flags |= QPRIMARY; /* flag as a "ctladdr" */ 5521 a->q_mailer = LocalMailer; 5522 if (p == NULL) 5523 a->q_paddr = sm_rpool_strdup_x(e->e_rpool, a->q_user); 5524 else 5525 a->q_paddr = sm_rpool_strdup_x(e->e_rpool, p); 5526 return a; 5527 } 5528 /* 5529 ** LOSEQFILE -- rename queue file with LOSEQF_LETTER & try to let someone know 5530 ** 5531 ** Parameters: 5532 ** e -- the envelope (e->e_id will be used). 5533 ** why -- reported to whomever can hear. 5534 ** 5535 ** Returns: 5536 ** none. 5537 */ 5538 5539 void 5540 loseqfile(e, why) 5541 register ENVELOPE *e; 5542 char *why; 5543 { 5544 bool loseit = true; 5545 char *p; 5546 char buf[MAXPATHLEN]; 5547 5548 if (e == NULL || e->e_id == NULL) 5549 return; 5550 p = queuename(e, ANYQFL_LETTER); 5551 if (sm_strlcpy(buf, p, sizeof buf) >= sizeof buf) 5552 return; 5553 if (!bitset(EF_INQUEUE, e->e_flags)) 5554 queueup(e, false, true); 5555 else if (QueueMode == QM_LOST) 5556 loseit = false; 5557 5558 /* if already lost, no need to re-lose */ 5559 if (loseit) 5560 { 5561 p = queuename(e, LOSEQF_LETTER); 5562 if (rename(buf, p) < 0) 5563 syserr("cannot rename(%s, %s), uid=%d", 5564 buf, p, (int) geteuid()); 5565 else if (LogLevel > 0) 5566 sm_syslog(LOG_ALERT, e->e_id, 5567 "Losing %s: %s", buf, why); 5568 } 5569 if (e->e_dfp != NULL) 5570 { 5571 (void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT); 5572 e->e_dfp = NULL; 5573 } 5574 e->e_flags &= ~EF_HAS_DF; 5575 } 5576 /* 5577 ** NAME2QID -- translate a queue group name to a queue group id 5578 ** 5579 ** Parameters: 5580 ** queuename -- name of queue group. 5581 ** 5582 ** Returns: 5583 ** queue group id if found. 5584 ** NOQGRP otherwise. 5585 */ 5586 5587 int 5588 name2qid(queuename) 5589 char *queuename; 5590 { 5591 register STAB *s; 5592 5593 s = stab(queuename, ST_QUEUE, ST_FIND); 5594 if (s == NULL) 5595 return NOQGRP; 5596 return s->s_quegrp->qg_index; 5597 } 5598 /* 5599 ** QID_PRINTNAME -- create externally printable version of queue id 5600 ** 5601 ** Parameters: 5602 ** e -- the envelope. 5603 ** 5604 ** Returns: 5605 ** a printable version 5606 */ 5607 5608 char * 5609 qid_printname(e) 5610 ENVELOPE *e; 5611 { 5612 char *id; 5613 static char idbuf[MAXQFNAME + 34]; 5614 5615 if (e == NULL) 5616 return ""; 5617 5618 if (e->e_id == NULL) 5619 id = ""; 5620 else 5621 id = e->e_id; 5622 5623 if (e->e_qdir == NOQDIR) 5624 return id; 5625 5626 (void) sm_snprintf(idbuf, sizeof idbuf, "%.32s/%s", 5627 Queue[e->e_qgrp]->qg_qpaths[e->e_qdir].qp_name, 5628 id); 5629 return idbuf; 5630 } 5631 /* 5632 ** QID_PRINTQUEUE -- create full version of queue directory for data files 5633 ** 5634 ** Parameters: 5635 ** qgrp -- index in queue group. 5636 ** qdir -- the short version of the queue directory 5637 ** 5638 ** Returns: 5639 ** the full pathname to the queue (might point to a static var) 5640 */ 5641 5642 char * 5643 qid_printqueue(qgrp, qdir) 5644 int qgrp; 5645 int qdir; 5646 { 5647 char *subdir; 5648 static char dir[MAXPATHLEN]; 5649 5650 if (qdir == NOQDIR) 5651 return Queue[qgrp]->qg_qdir; 5652 5653 if (strcmp(Queue[qgrp]->qg_qpaths[qdir].qp_name, ".") == 0) 5654 subdir = NULL; 5655 else 5656 subdir = Queue[qgrp]->qg_qpaths[qdir].qp_name; 5657 5658 (void) sm_strlcpyn(dir, sizeof dir, 4, 5659 Queue[qgrp]->qg_qdir, 5660 subdir == NULL ? "" : "/", 5661 subdir == NULL ? "" : subdir, 5662 (bitset(QP_SUBDF, 5663 Queue[qgrp]->qg_qpaths[qdir].qp_subdirs) 5664 ? "/df" : "")); 5665 return dir; 5666 } 5667 5668 /* 5669 ** PICKQDIR -- Pick a queue directory from a queue group 5670 ** 5671 ** Parameters: 5672 ** qg -- queue group 5673 ** fsize -- file size in bytes 5674 ** e -- envelope, or NULL 5675 ** 5676 ** Result: 5677 ** NOQDIR if no queue directory in qg has enough free space to 5678 ** hold a file of size 'fsize', otherwise the index of 5679 ** a randomly selected queue directory which resides on a 5680 ** file system with enough disk space. 5681 ** XXX This could be extended to select a queuedir with 5682 ** a few (the fewest?) number of entries. That data 5683 ** is available if shared memory is used. 5684 ** 5685 ** Side Effects: 5686 ** If the request fails and e != NULL then sm_syslog is called. 5687 */ 5688 5689 int 5690 pickqdir(qg, fsize, e) 5691 QUEUEGRP *qg; 5692 long fsize; 5693 ENVELOPE *e; 5694 { 5695 int qdir; 5696 int i; 5697 long avail = 0; 5698 5699 /* Pick a random directory, as a starting point. */ 5700 if (qg->qg_numqueues <= 1) 5701 qdir = 0; 5702 else 5703 qdir = get_rand_mod(qg->qg_numqueues); 5704 5705 if (MinBlocksFree <= 0 && fsize <= 0) 5706 return qdir; 5707 5708 /* 5709 ** Now iterate over the queue directories, 5710 ** looking for a directory with enough space for this message. 5711 */ 5712 5713 i = qdir; 5714 do 5715 { 5716 QPATHS *qp = &qg->qg_qpaths[i]; 5717 long needed = 0; 5718 long fsavail = 0; 5719 5720 if (fsize > 0) 5721 needed += fsize / FILE_SYS_BLKSIZE(qp->qp_fsysidx) 5722 + ((fsize % FILE_SYS_BLKSIZE(qp->qp_fsysidx) 5723 > 0) ? 1 : 0); 5724 if (MinBlocksFree > 0) 5725 needed += MinBlocksFree; 5726 fsavail = FILE_SYS_AVAIL(qp->qp_fsysidx); 5727 #if SM_CONF_SHM 5728 if (fsavail <= 0) 5729 { 5730 long blksize; 5731 5732 /* 5733 ** might be not correctly updated, 5734 ** let's try to get the info directly. 5735 */ 5736 5737 fsavail = freediskspace(FILE_SYS_NAME(qp->qp_fsysidx), 5738 &blksize); 5739 if (fsavail < 0) 5740 fsavail = 0; 5741 } 5742 #endif /* SM_CONF_SHM */ 5743 if (needed <= fsavail) 5744 return i; 5745 if (avail < fsavail) 5746 avail = fsavail; 5747 5748 if (qg->qg_numqueues > 0) 5749 i = (i + 1) % qg->qg_numqueues; 5750 } while (i != qdir); 5751 5752 if (e != NULL && LogLevel > 0) 5753 sm_syslog(LOG_ALERT, e->e_id, 5754 "low on space (%s needs %ld bytes + %ld blocks in %s), max avail: %ld", 5755 CurHostName == NULL ? "SMTP-DAEMON" : CurHostName, 5756 fsize, MinBlocksFree, 5757 qg->qg_qdir, avail); 5758 return NOQDIR; 5759 } 5760 /* 5761 ** SETNEWQUEUE -- Sets a new queue group and directory 5762 ** 5763 ** Assign a queue group and directory to an envelope and store the 5764 ** directory in e->e_qdir. 5765 ** 5766 ** Parameters: 5767 ** e -- envelope to assign a queue for. 5768 ** 5769 ** Returns: 5770 ** true if successful 5771 ** false otherwise 5772 ** 5773 ** Side Effects: 5774 ** On success, e->e_qgrp and e->e_qdir are non-negative. 5775 ** On failure (not enough disk space), 5776 ** e->qgrp = NOQGRP, e->e_qdir = NOQDIR 5777 ** and usrerr() is invoked (which could raise an exception). 5778 */ 5779 5780 bool 5781 setnewqueue(e) 5782 ENVELOPE *e; 5783 { 5784 if (tTd(41, 20)) 5785 sm_dprintf("setnewqueue: called\n"); 5786 5787 /* not set somewhere else */ 5788 if (e->e_qgrp == NOQGRP) 5789 { 5790 ADDRESS *q; 5791 5792 /* 5793 ** Use the queue group of the "first" recipient, as set by 5794 ** the "queuegroup" rule set. If that is not defined, then 5795 ** use the queue group of the mailer of the first recipient. 5796 ** If that is not defined either, then use the default 5797 ** queue group. 5798 ** Notice: "first" depends on the sorting of sendqueue 5799 ** in recipient(). 5800 ** To avoid problems with "bad" recipients look 5801 ** for a valid address first. 5802 */ 5803 5804 q = e->e_sendqueue; 5805 while (q != NULL && 5806 (QS_IS_BADADDR(q->q_state) || QS_IS_DEAD(q->q_state))) 5807 { 5808 q = q->q_next; 5809 } 5810 if (q == NULL) 5811 e->e_qgrp = 0; 5812 else if (q->q_qgrp >= 0) 5813 e->e_qgrp = q->q_qgrp; 5814 else if (q->q_mailer != NULL && 5815 ISVALIDQGRP(q->q_mailer->m_qgrp)) 5816 e->e_qgrp = q->q_mailer->m_qgrp; 5817 else 5818 e->e_qgrp = 0; 5819 e->e_dfqgrp = e->e_qgrp; 5820 } 5821 5822 if (ISVALIDQDIR(e->e_qdir) && ISVALIDQDIR(e->e_dfqdir)) 5823 { 5824 if (tTd(41, 20)) 5825 sm_dprintf("setnewqueue: e_qdir already assigned (%s)\n", 5826 qid_printqueue(e->e_qgrp, e->e_qdir)); 5827 return true; 5828 } 5829 5830 filesys_update(); 5831 e->e_qdir = pickqdir(Queue[e->e_qgrp], e->e_msgsize, e); 5832 if (e->e_qdir == NOQDIR) 5833 { 5834 e->e_qgrp = NOQGRP; 5835 if (!bitset(EF_FATALERRS, e->e_flags)) 5836 usrerr("452 4.4.5 Insufficient disk space; try again later"); 5837 e->e_flags |= EF_FATALERRS; 5838 return false; 5839 } 5840 5841 if (tTd(41, 3)) 5842 sm_dprintf("setnewqueue: Assigned queue directory %s\n", 5843 qid_printqueue(e->e_qgrp, e->e_qdir)); 5844 5845 if (e->e_xfqgrp == NOQGRP || e->e_xfqdir == NOQDIR) 5846 { 5847 e->e_xfqgrp = e->e_qgrp; 5848 e->e_xfqdir = e->e_qdir; 5849 } 5850 e->e_dfqdir = e->e_qdir; 5851 return true; 5852 } 5853 /* 5854 ** CHKQDIR -- check a queue directory 5855 ** 5856 ** Parameters: 5857 ** name -- name of queue directory 5858 ** sff -- flags for safefile() 5859 ** 5860 ** Returns: 5861 ** is it a queue directory? 5862 */ 5863 5864 static bool 5865 chkqdir(name, sff) 5866 char *name; 5867 long sff; 5868 { 5869 struct stat statb; 5870 int i; 5871 5872 /* skip over . and .. directories */ 5873 if (name[0] == '.' && 5874 (name[1] == '\0' || (name[1] == '.' && name[2] == '\0'))) 5875 return false; 5876 #if HASLSTAT 5877 if (lstat(name, &statb) < 0) 5878 #else /* HASLSTAT */ 5879 if (stat(name, &statb) < 0) 5880 #endif /* HASLSTAT */ 5881 { 5882 if (tTd(41, 2)) 5883 sm_dprintf("chkqdir: stat(\"%s\"): %s\n", 5884 name, sm_errstring(errno)); 5885 return false; 5886 } 5887 #if HASLSTAT 5888 if (S_ISLNK(statb.st_mode)) 5889 { 5890 /* 5891 ** For a symlink we need to make sure the 5892 ** target is a directory 5893 */ 5894 5895 if (stat(name, &statb) < 0) 5896 { 5897 if (tTd(41, 2)) 5898 sm_dprintf("chkqdir: stat(\"%s\"): %s\n", 5899 name, sm_errstring(errno)); 5900 return false; 5901 } 5902 } 5903 #endif /* HASLSTAT */ 5904 5905 if (!S_ISDIR(statb.st_mode)) 5906 { 5907 if (tTd(41, 2)) 5908 sm_dprintf("chkqdir: \"%s\": Not a directory\n", 5909 name); 5910 return false; 5911 } 5912 5913 /* Print a warning if unsafe (but still use it) */ 5914 /* XXX do this only if we want the warning? */ 5915 i = safedirpath(name, RunAsUid, RunAsGid, NULL, sff, 0, 0); 5916 if (i != 0) 5917 { 5918 if (tTd(41, 2)) 5919 sm_dprintf("chkqdir: \"%s\": Not safe: %s\n", 5920 name, sm_errstring(i)); 5921 #if _FFR_CHK_QUEUE 5922 if (LogLevel > 8) 5923 sm_syslog(LOG_WARNING, NOQID, 5924 "queue directory \"%s\": Not safe: %s", 5925 name, sm_errstring(i)); 5926 #endif /* _FFR_CHK_QUEUE */ 5927 } 5928 return true; 5929 } 5930 /* 5931 ** MULTIQUEUE_CACHE -- cache a list of paths to queues. 5932 ** 5933 ** Each potential queue is checked as the cache is built. 5934 ** Thereafter, each is blindly trusted. 5935 ** Note that we can be called again after a timeout to rebuild 5936 ** (although code for that is not ready yet). 5937 ** 5938 ** Parameters: 5939 ** basedir -- base of all queue directories. 5940 ** blen -- strlen(basedir). 5941 ** qg -- queue group. 5942 ** qn -- number of queue directories already cached. 5943 ** phash -- pointer to hash value over queue dirs. 5944 #if SM_CONF_SHM 5945 ** only used if shared memory is active. 5946 #endif * SM_CONF_SHM * 5947 ** 5948 ** Returns: 5949 ** new number of queue directories. 5950 */ 5951 5952 #define INITIAL_SLOTS 20 5953 #define ADD_SLOTS 10 5954 5955 static int 5956 multiqueue_cache(basedir, blen, qg, qn, phash) 5957 char *basedir; 5958 int blen; 5959 QUEUEGRP *qg; 5960 int qn; 5961 unsigned int *phash; 5962 { 5963 char *cp; 5964 int i, len; 5965 int slotsleft = 0; 5966 long sff = SFF_ANYFILE; 5967 char qpath[MAXPATHLEN]; 5968 char subdir[MAXPATHLEN]; 5969 char prefix[MAXPATHLEN]; /* dir relative to basedir */ 5970 5971 if (tTd(41, 20)) 5972 sm_dprintf("multiqueue_cache: called\n"); 5973 5974 /* Initialize to current directory */ 5975 prefix[0] = '.'; 5976 prefix[1] = '\0'; 5977 if (qg->qg_numqueues != 0 && qg->qg_qpaths != NULL) 5978 { 5979 for (i = 0; i < qg->qg_numqueues; i++) 5980 { 5981 if (qg->qg_qpaths[i].qp_name != NULL) 5982 (void) sm_free(qg->qg_qpaths[i].qp_name); /* XXX */ 5983 } 5984 (void) sm_free((char *) qg->qg_qpaths); /* XXX */ 5985 qg->qg_qpaths = NULL; 5986 qg->qg_numqueues = 0; 5987 } 5988 5989 /* If running as root, allow safedirpath() checks to use privs */ 5990 if (RunAsUid == 0) 5991 sff |= SFF_ROOTOK; 5992 #if _FFR_CHK_QUEUE 5993 sff |= SFF_SAFEDIRPATH|SFF_NOWWFILES; 5994 if (!UseMSP) 5995 sff |= SFF_NOGWFILES; 5996 #endif /* _FFR_CHK_QUEUE */ 5997 5998 if (!SM_IS_DIR_START(qg->qg_qdir)) 5999 { 6000 /* 6001 ** XXX we could add basedir, but then we have to realloc() 6002 ** the string... Maybe another time. 6003 */ 6004 6005 syserr("QueuePath %s not absolute", qg->qg_qdir); 6006 ExitStat = EX_CONFIG; 6007 return qn; 6008 } 6009 6010 /* qpath: directory of current workgroup */ 6011 len = sm_strlcpy(qpath, qg->qg_qdir, sizeof qpath); 6012 if (len >= sizeof qpath) 6013 { 6014 syserr("QueuePath %.256s too long (%d max)", 6015 qg->qg_qdir, (int) sizeof qpath); 6016 ExitStat = EX_CONFIG; 6017 return qn; 6018 } 6019 6020 /* begin of qpath must be same as basedir */ 6021 if (strncmp(basedir, qpath, blen) != 0 && 6022 (strncmp(basedir, qpath, blen - 1) != 0 || len != blen - 1)) 6023 { 6024 syserr("QueuePath %s not subpath of QueueDirectory %s", 6025 qpath, basedir); 6026 ExitStat = EX_CONFIG; 6027 return qn; 6028 } 6029 6030 /* Do we have a nested subdirectory? */ 6031 if (blen < len && SM_FIRST_DIR_DELIM(qg->qg_qdir + blen) != NULL) 6032 { 6033 6034 /* Copy subdirectory into prefix for later use */ 6035 if (sm_strlcpy(prefix, qg->qg_qdir + blen, sizeof prefix) >= 6036 sizeof prefix) 6037 { 6038 syserr("QueuePath %.256s too long (%d max)", 6039 qg->qg_qdir, (int) sizeof qpath); 6040 ExitStat = EX_CONFIG; 6041 return qn; 6042 } 6043 cp = SM_LAST_DIR_DELIM(prefix); 6044 SM_ASSERT(cp != NULL); 6045 *cp = '\0'; /* cut off trailing / */ 6046 } 6047 6048 /* This is guaranteed by the basedir check above */ 6049 SM_ASSERT(len >= blen - 1); 6050 cp = &qpath[len - 1]; 6051 if (*cp == '*') 6052 { 6053 register DIR *dp; 6054 register struct dirent *d; 6055 int off; 6056 char *delim; 6057 char relpath[MAXPATHLEN]; 6058 6059 *cp = '\0'; /* Overwrite wildcard */ 6060 if ((cp = SM_LAST_DIR_DELIM(qpath)) == NULL) 6061 { 6062 syserr("QueueDirectory: can not wildcard relative path"); 6063 if (tTd(41, 2)) 6064 sm_dprintf("multiqueue_cache: \"%s*\": Can not wildcard relative path.\n", 6065 qpath); 6066 ExitStat = EX_CONFIG; 6067 return qn; 6068 } 6069 if (cp == qpath) 6070 { 6071 /* 6072 ** Special case of top level wildcard, like /foo* 6073 ** Change to //foo* 6074 */ 6075 6076 (void) sm_strlcpy(qpath + 1, qpath, sizeof qpath - 1); 6077 ++cp; 6078 } 6079 delim = cp; 6080 *(cp++) = '\0'; /* Replace / with \0 */ 6081 len = strlen(cp); /* Last component of queue directory */ 6082 6083 /* 6084 ** Path relative to basedir, with trailing / 6085 ** It will be modified below to specify the subdirectories 6086 ** so they can be opened without chdir(). 6087 */ 6088 6089 off = sm_strlcpyn(relpath, sizeof relpath, 2, prefix, "/"); 6090 SM_ASSERT(off < sizeof relpath); 6091 6092 if (tTd(41, 2)) 6093 sm_dprintf("multiqueue_cache: prefix=\"%s%s\"\n", 6094 relpath, cp); 6095 6096 /* It is always basedir: we don't need to store it per group */ 6097 /* XXX: optimize this! -> one more global? */ 6098 qg->qg_qdir = newstr(basedir); 6099 qg->qg_qdir[blen - 1] = '\0'; /* cut off trailing / */ 6100 6101 /* 6102 ** XXX Should probably wrap this whole loop in a timeout 6103 ** in case some wag decides to NFS mount the queues. 6104 */ 6105 6106 /* Test path to get warning messages. */ 6107 if (qn == 0) 6108 { 6109 /* XXX qg_runasuid and qg_runasgid for specials? */ 6110 i = safedirpath(basedir, RunAsUid, RunAsGid, NULL, 6111 sff, 0, 0); 6112 if (i != 0 && tTd(41, 2)) 6113 sm_dprintf("multiqueue_cache: \"%s\": Not safe: %s\n", 6114 basedir, sm_errstring(i)); 6115 } 6116 6117 if ((dp = opendir(prefix)) == NULL) 6118 { 6119 syserr("can not opendir(%s/%s)", qg->qg_qdir, prefix); 6120 if (tTd(41, 2)) 6121 sm_dprintf("multiqueue_cache: opendir(\"%s/%s\"): %s\n", 6122 qg->qg_qdir, prefix, 6123 sm_errstring(errno)); 6124 ExitStat = EX_CONFIG; 6125 return qn; 6126 } 6127 while ((d = readdir(dp)) != NULL) 6128 { 6129 i = strlen(d->d_name); 6130 if (i < len || strncmp(d->d_name, cp, len) != 0) 6131 { 6132 if (tTd(41, 5)) 6133 sm_dprintf("multiqueue_cache: \"%s\", skipped\n", 6134 d->d_name); 6135 continue; 6136 } 6137 6138 /* Create relative pathname: prefix + local directory */ 6139 i = sizeof(relpath) - off; 6140 if (sm_strlcpy(relpath + off, d->d_name, i) >= i) 6141 continue; /* way too long */ 6142 6143 if (!chkqdir(relpath, sff)) 6144 continue; 6145 6146 if (qg->qg_qpaths == NULL) 6147 { 6148 slotsleft = INITIAL_SLOTS; 6149 qg->qg_qpaths = (QPATHS *)xalloc((sizeof *qg->qg_qpaths) * 6150 slotsleft); 6151 qg->qg_numqueues = 0; 6152 } 6153 else if (slotsleft < 1) 6154 { 6155 qg->qg_qpaths = (QPATHS *)sm_realloc((char *)qg->qg_qpaths, 6156 (sizeof *qg->qg_qpaths) * 6157 (qg->qg_numqueues + 6158 ADD_SLOTS)); 6159 if (qg->qg_qpaths == NULL) 6160 { 6161 (void) closedir(dp); 6162 return qn; 6163 } 6164 slotsleft += ADD_SLOTS; 6165 } 6166 6167 /* check subdirs */ 6168 qg->qg_qpaths[qg->qg_numqueues].qp_subdirs = QP_NOSUB; 6169 6170 #define CHKRSUBDIR(name, flag) \ 6171 (void) sm_strlcpyn(subdir, sizeof subdir, 3, relpath, "/", name); \ 6172 if (chkqdir(subdir, sff)) \ 6173 qg->qg_qpaths[qg->qg_numqueues].qp_subdirs |= flag; \ 6174 else 6175 6176 6177 CHKRSUBDIR("qf", QP_SUBQF); 6178 CHKRSUBDIR("df", QP_SUBDF); 6179 CHKRSUBDIR("xf", QP_SUBXF); 6180 6181 /* assert(strlen(d->d_name) < MAXPATHLEN - 14) */ 6182 /* maybe even - 17 (subdirs) */ 6183 6184 if (prefix[0] != '.') 6185 qg->qg_qpaths[qg->qg_numqueues].qp_name = 6186 newstr(relpath); 6187 else 6188 qg->qg_qpaths[qg->qg_numqueues].qp_name = 6189 newstr(d->d_name); 6190 6191 if (tTd(41, 2)) 6192 sm_dprintf("multiqueue_cache: %d: \"%s\" cached (%x).\n", 6193 qg->qg_numqueues, relpath, 6194 qg->qg_qpaths[qg->qg_numqueues].qp_subdirs); 6195 #if SM_CONF_SHM 6196 qg->qg_qpaths[qg->qg_numqueues].qp_idx = qn; 6197 *phash = hash_q(relpath, *phash); 6198 #endif /* SM_CONF_SHM */ 6199 qg->qg_numqueues++; 6200 ++qn; 6201 slotsleft--; 6202 } 6203 (void) closedir(dp); 6204 6205 /* undo damage */ 6206 *delim = '/'; 6207 } 6208 if (qg->qg_numqueues == 0) 6209 { 6210 qg->qg_qpaths = (QPATHS *) xalloc(sizeof *qg->qg_qpaths); 6211 6212 /* test path to get warning messages */ 6213 i = safedirpath(qpath, RunAsUid, RunAsGid, NULL, sff, 0, 0); 6214 if (i == ENOENT) 6215 { 6216 syserr("can not opendir(%s)", qpath); 6217 if (tTd(41, 2)) 6218 sm_dprintf("multiqueue_cache: opendir(\"%s\"): %s\n", 6219 qpath, sm_errstring(i)); 6220 ExitStat = EX_CONFIG; 6221 return qn; 6222 } 6223 6224 qg->qg_qpaths[0].qp_subdirs = QP_NOSUB; 6225 qg->qg_numqueues = 1; 6226 6227 /* check subdirs */ 6228 #define CHKSUBDIR(name, flag) \ 6229 (void) sm_strlcpyn(subdir, sizeof subdir, 3, qg->qg_qdir, "/", name); \ 6230 if (chkqdir(subdir, sff)) \ 6231 qg->qg_qpaths[0].qp_subdirs |= flag; \ 6232 else 6233 6234 CHKSUBDIR("qf", QP_SUBQF); 6235 CHKSUBDIR("df", QP_SUBDF); 6236 CHKSUBDIR("xf", QP_SUBXF); 6237 6238 if (qg->qg_qdir[blen - 1] != '\0' && 6239 qg->qg_qdir[blen] != '\0') 6240 { 6241 /* 6242 ** Copy the last component into qpaths and 6243 ** cut off qdir 6244 */ 6245 6246 qg->qg_qpaths[0].qp_name = newstr(qg->qg_qdir + blen); 6247 qg->qg_qdir[blen - 1] = '\0'; 6248 } 6249 else 6250 qg->qg_qpaths[0].qp_name = newstr("."); 6251 6252 #if SM_CONF_SHM 6253 qg->qg_qpaths[0].qp_idx = qn; 6254 *phash = hash_q(qg->qg_qpaths[0].qp_name, *phash); 6255 #endif /* SM_CONF_SHM */ 6256 ++qn; 6257 } 6258 return qn; 6259 } 6260 6261 /* 6262 ** FILESYS_FIND -- find entry in FileSys table, or add new one 6263 ** 6264 ** Given the pathname of a directory, determine the file system 6265 ** in which that directory resides, and return a pointer to the 6266 ** entry in the FileSys table that describes the file system. 6267 ** A new entry is added if necessary (and requested). 6268 ** If the directory does not exist, -1 is returned. 6269 ** 6270 ** Parameters: 6271 ** name -- name of directory (must be persistent!) 6272 ** path -- pathname of directory (name plus maybe "/df") 6273 ** add -- add to structure if not found. 6274 ** 6275 ** Returns: 6276 ** >=0: found: index in file system table 6277 ** <0: some error, i.e., 6278 ** FSF_TOO_MANY: too many filesystems (-> syserr()) 6279 ** FSF_STAT_FAIL: can't stat() filesystem (-> syserr()) 6280 ** FSF_NOT_FOUND: not in list 6281 */ 6282 6283 static short filesys_find __P((char *, char *, bool)); 6284 6285 #define FSF_NOT_FOUND (-1) 6286 #define FSF_STAT_FAIL (-2) 6287 #define FSF_TOO_MANY (-3) 6288 6289 static short 6290 filesys_find(name, path, add) 6291 char *name; 6292 char *path; 6293 bool add; 6294 { 6295 struct stat st; 6296 short i; 6297 6298 if (stat(path, &st) < 0) 6299 { 6300 syserr("cannot stat queue directory %s", path); 6301 return FSF_STAT_FAIL; 6302 } 6303 for (i = 0; i < NumFileSys; ++i) 6304 { 6305 if (FILE_SYS_DEV(i) == st.st_dev) 6306 return i; 6307 } 6308 if (i >= MAXFILESYS) 6309 { 6310 syserr("too many queue file systems (%d max)", MAXFILESYS); 6311 return FSF_TOO_MANY; 6312 } 6313 if (!add) 6314 return FSF_NOT_FOUND; 6315 6316 ++NumFileSys; 6317 FILE_SYS_NAME(i) = name; 6318 FILE_SYS_DEV(i) = st.st_dev; 6319 FILE_SYS_AVAIL(i) = 0; 6320 FILE_SYS_BLKSIZE(i) = 1024; /* avoid divide by zero */ 6321 return i; 6322 } 6323 6324 /* 6325 ** FILESYS_SETUP -- set up mapping from queue directories to file systems 6326 ** 6327 ** This data structure is used to efficiently check the amount of 6328 ** free space available in a set of queue directories. 6329 ** 6330 ** Parameters: 6331 ** add -- initialize structure if necessary. 6332 ** 6333 ** Returns: 6334 ** 0: success 6335 ** <0: some error, i.e., 6336 ** FSF_NOT_FOUND: not in list 6337 ** FSF_STAT_FAIL: can't stat() filesystem (-> syserr()) 6338 ** FSF_TOO_MANY: too many filesystems (-> syserr()) 6339 */ 6340 6341 static int filesys_setup __P((bool)); 6342 6343 static int 6344 filesys_setup(add) 6345 bool add; 6346 { 6347 int i, j; 6348 short fs; 6349 int ret; 6350 6351 ret = 0; 6352 for (i = 0; i < NumQueue && Queue[i] != NULL; i++) 6353 { 6354 for (j = 0; j < Queue[i]->qg_numqueues; ++j) 6355 { 6356 QPATHS *qp = &Queue[i]->qg_qpaths[j]; 6357 char qddf[MAXPATHLEN]; 6358 6359 (void) sm_strlcpyn(qddf, sizeof qddf, 2, qp->qp_name, 6360 (bitset(QP_SUBDF, qp->qp_subdirs) 6361 ? "/df" : "")); 6362 fs = filesys_find(qp->qp_name, qddf, add); 6363 if (fs >= 0) 6364 qp->qp_fsysidx = fs; 6365 else 6366 qp->qp_fsysidx = 0; 6367 if (fs < ret) 6368 ret = fs; 6369 } 6370 } 6371 return ret; 6372 } 6373 6374 /* 6375 ** FILESYS_UPDATE -- update amount of free space on all file systems 6376 ** 6377 ** The FileSys table is used to cache the amount of free space 6378 ** available on all queue directory file systems. 6379 ** This function updates the cached information if it has expired. 6380 ** 6381 ** Parameters: 6382 ** none. 6383 ** 6384 ** Returns: 6385 ** none. 6386 ** 6387 ** Side Effects: 6388 ** Updates FileSys table. 6389 */ 6390 6391 void 6392 filesys_update() 6393 { 6394 int i; 6395 long avail, blksize; 6396 time_t now; 6397 static time_t nextupdate = 0; 6398 6399 #if SM_CONF_SHM 6400 /* only the daemon updates this structure */ 6401 if (ShmId != SM_SHM_NO_ID && DaemonPid != CurrentPid) 6402 return; 6403 #endif /* SM_CONF_SHM */ 6404 now = curtime(); 6405 if (now < nextupdate) 6406 return; 6407 nextupdate = now + FILESYS_UPDATE_INTERVAL; 6408 for (i = 0; i < NumFileSys; ++i) 6409 { 6410 FILESYS *fs = &FILE_SYS(i); 6411 6412 avail = freediskspace(FILE_SYS_NAME(i), &blksize); 6413 if (avail < 0 || blksize <= 0) 6414 { 6415 if (LogLevel > 5) 6416 sm_syslog(LOG_ERR, NOQID, 6417 "filesys_update failed: %s, fs=%s, avail=%ld, blocksize=%ld", 6418 sm_errstring(errno), 6419 FILE_SYS_NAME(i), avail, blksize); 6420 fs->fs_avail = 0; 6421 fs->fs_blksize = 1024; /* avoid divide by zero */ 6422 nextupdate = now + 2; /* let's do this soon again */ 6423 } 6424 else 6425 { 6426 fs->fs_avail = avail; 6427 fs->fs_blksize = blksize; 6428 } 6429 } 6430 } 6431 6432 #if _FFR_ANY_FREE_FS 6433 /* 6434 ** FILESYS_FREE -- check whether there is at least one fs with enough space. 6435 ** 6436 ** Parameters: 6437 ** fsize -- file size in bytes 6438 ** 6439 ** Returns: 6440 ** true iff there is one fs with more than fsize bytes free. 6441 */ 6442 6443 bool 6444 filesys_free(fsize) 6445 long fsize; 6446 { 6447 int i; 6448 6449 if (fsize <= 0) 6450 return true; 6451 for (i = 0; i < NumFileSys; ++i) 6452 { 6453 long needed = 0; 6454 6455 if (FILE_SYS_AVAIL(i) < 0 || FILE_SYS_BLKSIZE(i) <= 0) 6456 continue; 6457 needed += fsize / FILE_SYS_BLKSIZE(i) 6458 + ((fsize % FILE_SYS_BLKSIZE(i) 6459 > 0) ? 1 : 0) 6460 + MinBlocksFree; 6461 if (needed <= FILE_SYS_AVAIL(i)) 6462 return true; 6463 } 6464 return false; 6465 } 6466 #endif /* _FFR_ANY_FREE_FS */ 6467 6468 #if _FFR_CONTROL_MSTAT 6469 /* 6470 ** DISK_STATUS -- show amount of free space in queue directories 6471 ** 6472 ** Parameters: 6473 ** out -- output file pointer. 6474 ** prefix -- string to output in front of each line. 6475 ** 6476 ** Returns: 6477 ** none. 6478 */ 6479 6480 void 6481 disk_status(out, prefix) 6482 SM_FILE_T *out; 6483 char *prefix; 6484 { 6485 int i; 6486 long avail, blksize; 6487 long free; 6488 6489 for (i = 0; i < NumFileSys; ++i) 6490 { 6491 avail = freediskspace(FILE_SYS_NAME(i), &blksize); 6492 if (avail >= 0 && blksize > 0) 6493 { 6494 free = (long)((double) avail * 6495 ((double) blksize / 1024)); 6496 } 6497 else 6498 free = -1; 6499 (void) sm_io_fprintf(out, SM_TIME_DEFAULT, 6500 "%s%d/%s/%ld\r\n", 6501 prefix, i, 6502 FILE_SYS_NAME(i), 6503 free); 6504 } 6505 } 6506 #endif /* _FFR_CONTROL_MSTAT */ 6507 6508 #if SM_CONF_SHM 6509 6510 /* 6511 ** INIT_SEM -- initialize semaphore system 6512 ** 6513 ** Parameters: 6514 ** owner -- is this the owner of semaphores? 6515 ** 6516 ** Returns: 6517 ** none. 6518 */ 6519 6520 #if _FFR_USE_SEM_LOCKING 6521 #if SM_CONF_SEM 6522 static int SemId = -1; /* Semaphore Id */ 6523 int SemKey = SM_SEM_KEY; 6524 #endif /* SM_CONF_SEM */ 6525 #endif /* _FFR_USE_SEM_LOCKING */ 6526 6527 static void init_sem __P((bool)); 6528 6529 static void 6530 init_sem(owner) 6531 bool owner; 6532 { 6533 #if _FFR_USE_SEM_LOCKING 6534 #if SM_CONF_SEM 6535 SemId = sm_sem_start(SemKey, 1, 0, owner); 6536 if (SemId < 0) 6537 { 6538 sm_syslog(LOG_ERR, NOQID, 6539 "func=init_sem, sem_key=%ld, sm_sem_start=%d", 6540 (long) SemKey, SemId); 6541 return; 6542 } 6543 #endif /* SM_CONF_SEM */ 6544 #endif /* _FFR_USE_SEM_LOCKING */ 6545 return; 6546 } 6547 6548 /* 6549 ** STOP_SEM -- stop semaphore system 6550 ** 6551 ** Parameters: 6552 ** owner -- is this the owner of semaphores? 6553 ** 6554 ** Returns: 6555 ** none. 6556 */ 6557 6558 static void stop_sem __P((bool)); 6559 6560 static void 6561 stop_sem(owner) 6562 bool owner; 6563 { 6564 #if _FFR_USE_SEM_LOCKING 6565 #if SM_CONF_SEM 6566 if (owner && SemId >= 0) 6567 sm_sem_stop(SemId); 6568 #endif /* SM_CONF_SEM */ 6569 #endif /* _FFR_USE_SEM_LOCKING */ 6570 return; 6571 } 6572 6573 /* 6574 ** UPD_QS -- update information about queue when adding/deleting an entry 6575 ** 6576 ** Parameters: 6577 ** e -- envelope. 6578 ** count -- add/remove entry (+1/0/-1: add/no change/remove) 6579 ** space -- update the space available as well. 6580 ** (>0/0/<0: add/no change/remove) 6581 ** where -- caller (for logging) 6582 ** 6583 ** Returns: 6584 ** none. 6585 ** 6586 ** Side Effects: 6587 ** Modifies available space in filesystem. 6588 ** Changes number of entries in queue directory. 6589 */ 6590 6591 void 6592 upd_qs(e, count, space, where) 6593 ENVELOPE *e; 6594 int count; 6595 int space; 6596 char *where; 6597 { 6598 short fidx; 6599 int idx; 6600 # if _FFR_USE_SEM_LOCKING 6601 int r; 6602 # endif /* _FFR_USE_SEM_LOCKING */ 6603 long s; 6604 6605 if (ShmId == SM_SHM_NO_ID || e == NULL) 6606 return; 6607 if (e->e_qgrp == NOQGRP || e->e_qdir == NOQDIR) 6608 return; 6609 idx = Queue[e->e_qgrp]->qg_qpaths[e->e_qdir].qp_idx; 6610 if (tTd(73,2)) 6611 sm_dprintf("func=upd_qs, count=%d, space=%d, where=%s, idx=%d, entries=%d\n", 6612 count, space, where, idx, QSHM_ENTRIES(idx)); 6613 6614 /* XXX in theory this needs to be protected with a mutex */ 6615 if (QSHM_ENTRIES(idx) >= 0 && count != 0) 6616 { 6617 # if _FFR_USE_SEM_LOCKING 6618 r = sm_sem_acq(SemId, 0, 1); 6619 # endif /* _FFR_USE_SEM_LOCKING */ 6620 QSHM_ENTRIES(idx) += count; 6621 # if _FFR_USE_SEM_LOCKING 6622 if (r >= 0) 6623 r = sm_sem_rel(SemId, 0, 1); 6624 # endif /* _FFR_USE_SEM_LOCKING */ 6625 } 6626 6627 fidx = Queue[e->e_qgrp]->qg_qpaths[e->e_qdir].qp_fsysidx; 6628 if (fidx < 0) 6629 return; 6630 6631 /* update available space also? (might be loseqfile) */ 6632 if (space == 0) 6633 return; 6634 6635 /* convert size to blocks; this causes rounding errors */ 6636 s = e->e_msgsize / FILE_SYS_BLKSIZE(fidx); 6637 if (s == 0) 6638 return; 6639 6640 /* XXX in theory this needs to be protected with a mutex */ 6641 if (space > 0) 6642 FILE_SYS_AVAIL(fidx) += s; 6643 else 6644 FILE_SYS_AVAIL(fidx) -= s; 6645 6646 } 6647 6648 #if _FFR_SELECT_SHM 6649 6650 static bool write_key_file __P((char *, long)); 6651 static long read_key_file __P((char *, long)); 6652 6653 /* 6654 ** WRITE_KEY_FILE -- record some key into a file. 6655 ** 6656 ** Parameters: 6657 ** keypath -- file name. 6658 ** key -- key to write. 6659 ** 6660 ** Returns: 6661 ** true iff file could be written. 6662 ** 6663 ** Side Effects: 6664 ** writes file. 6665 */ 6666 6667 static bool 6668 write_key_file(keypath, key) 6669 char *keypath; 6670 long key; 6671 { 6672 bool ok; 6673 long sff; 6674 SM_FILE_T *keyf; 6675 6676 ok = false; 6677 if (keypath == NULL || *keypath == '\0') 6678 return ok; 6679 sff = SFF_NOLINK|SFF_ROOTOK|SFF_REGONLY|SFF_CREAT; 6680 if (TrustedUid != 0 && RealUid == TrustedUid) 6681 sff |= SFF_OPENASROOT; 6682 keyf = safefopen(keypath, O_WRONLY|O_TRUNC, FileMode, sff); 6683 if (keyf == NULL) 6684 { 6685 sm_syslog(LOG_ERR, NOQID, "unable to write %s: %s", 6686 keypath, sm_errstring(errno)); 6687 } 6688 else 6689 { 6690 if (geteuid() == 0 && RunAsUid != 0) 6691 { 6692 # if HASFCHOWN 6693 int fd; 6694 6695 fd = keyf->f_file; 6696 if (fd >= 0 && fchown(fd, RunAsUid, -1) < 0) 6697 { 6698 int err = errno; 6699 6700 sm_syslog(LOG_ALERT, NOQID, 6701 "ownership change on %s to %d failed: %s", 6702 keypath, RunAsUid, sm_errstring(err)); 6703 } 6704 # endif /* HASFCHOWN */ 6705 } 6706 ok = sm_io_fprintf(keyf, SM_TIME_DEFAULT, "%ld\n", key) != 6707 SM_IO_EOF; 6708 ok = (sm_io_close(keyf, SM_TIME_DEFAULT) != SM_IO_EOF) && ok; 6709 } 6710 return ok; 6711 } 6712 6713 /* 6714 ** READ_KEY_FILE -- read a key from a file. 6715 ** 6716 ** Parameters: 6717 ** keypath -- file name. 6718 ** key -- default key. 6719 ** 6720 ** Returns: 6721 ** key. 6722 */ 6723 6724 static long 6725 read_key_file(keypath, key) 6726 char *keypath; 6727 long key; 6728 { 6729 int r; 6730 long sff, n; 6731 SM_FILE_T *keyf; 6732 6733 if (keypath == NULL || *keypath == '\0') 6734 return key; 6735 sff = SFF_NOLINK|SFF_ROOTOK|SFF_REGONLY; 6736 if (RealUid == 0 || (TrustedUid != 0 && RealUid == TrustedUid)) 6737 sff |= SFF_OPENASROOT; 6738 keyf = safefopen(keypath, O_RDONLY, FileMode, sff); 6739 if (keyf == NULL) 6740 { 6741 sm_syslog(LOG_ERR, NOQID, "unable to read %s: %s", 6742 keypath, sm_errstring(errno)); 6743 } 6744 else 6745 { 6746 r = sm_io_fscanf(keyf, SM_TIME_DEFAULT, "%ld", &n); 6747 if (r == 1) 6748 key = n; 6749 (void) sm_io_close(keyf, SM_TIME_DEFAULT); 6750 } 6751 return key; 6752 } 6753 #endif /* _FFR_SELECT_SHM */ 6754 6755 /* 6756 ** INIT_SHM -- initialize shared memory structure 6757 ** 6758 ** Initialize or attach to shared memory segment. 6759 ** Currently it is not a fatal error if this doesn't work. 6760 ** However, it causes us to have a "fallback" storage location 6761 ** for everything that is supposed to be in the shared memory, 6762 ** which makes the code slightly ugly. 6763 ** 6764 ** Parameters: 6765 ** qn -- number of queue directories. 6766 ** owner -- owner of shared memory. 6767 ** hash -- identifies data that is stored in shared memory. 6768 ** 6769 ** Returns: 6770 ** none. 6771 */ 6772 6773 static void init_shm __P((int, bool, unsigned int)); 6774 6775 static void 6776 init_shm(qn, owner, hash) 6777 int qn; 6778 bool owner; 6779 unsigned int hash; 6780 { 6781 int i; 6782 int count; 6783 int save_errno; 6784 #if _FFR_SELECT_SHM 6785 bool keyselect; 6786 #endif /* _FFR_SELECT_SHM */ 6787 6788 PtrFileSys = &FileSys[0]; 6789 PNumFileSys = &Numfilesys; 6790 #if _FFR_SELECT_SHM 6791 /* if this "key" is specified: select one yourself */ 6792 # define SEL_SHM_KEY ((key_t) -1) 6793 # define FIRST_SHM_KEY 25 6794 #endif /* _FFR_SELECT_SHM */ 6795 6796 /* This allows us to disable shared memory at runtime. */ 6797 if (ShmKey == 0) 6798 return; 6799 6800 count = 0; 6801 shms = SM_T_SIZE + qn * sizeof(QUEUE_SHM_T); 6802 #if _FFR_SELECT_SHM 6803 keyselect = ShmKey == SEL_SHM_KEY; 6804 if (keyselect) 6805 { 6806 if (owner) 6807 ShmKey = FIRST_SHM_KEY; 6808 else 6809 { 6810 ShmKey = read_key_file(ShmKeyFile, ShmKey); 6811 keyselect = false; 6812 if (ShmKey == SEL_SHM_KEY) 6813 goto error; 6814 } 6815 } 6816 #endif /* _FFR_SELECT_SHM */ 6817 for (;;) 6818 { 6819 /* allow read/write access for group? */ 6820 Pshm = sm_shmstart(ShmKey, shms, 6821 SHM_R|SHM_W|(SHM_R>>3)|(SHM_W>>3), 6822 &ShmId, owner); 6823 save_errno = errno; 6824 if (Pshm != NULL || !sm_file_exists(save_errno)) 6825 break; 6826 if (++count >= 3) 6827 { 6828 #if _FFR_SELECT_SHM 6829 if (keyselect) 6830 { 6831 ++ShmKey; 6832 6833 /* back where we started? */ 6834 if (ShmKey == SEL_SHM_KEY) 6835 break; 6836 continue; 6837 } 6838 #endif /* _FFR_SELECT_SHM */ 6839 break; 6840 } 6841 #if _FFR_SELECT_SHM 6842 /* only sleep if we are at the first key */ 6843 if (!keyselect || ShmKey == SEL_SHM_KEY) 6844 #endif /* _FFR_SELECT_SHM */ 6845 sleep(count); 6846 } 6847 if (Pshm != NULL) 6848 { 6849 int *p; 6850 6851 #if _FFR_SELECT_SHM 6852 if (keyselect) 6853 (void) write_key_file(ShmKeyFile, (long) ShmKey); 6854 #endif /* _FFR_SELECT_SHM */ 6855 if (owner && RunAsUid != 0) 6856 { 6857 i = sm_shmsetowner(ShmId, RunAsUid, RunAsGid, 6858 0660); 6859 if (i != 0) 6860 sm_syslog(LOG_ERR, NOQID, 6861 "key=%ld, sm_shmsetowner=%d, RunAsUid=%d, RunAsGid=%d", 6862 (long) ShmKey, i, 6863 RunAsUid, RunAsGid); 6864 } 6865 p = (int *) Pshm; 6866 if (owner) 6867 { 6868 *p = (int) shms; 6869 *((pid_t *) SHM_OFF_PID(Pshm)) = CurrentPid; 6870 p = (int *) SHM_OFF_TAG(Pshm); 6871 *p = hash; 6872 } 6873 else 6874 { 6875 if (*p != (int) shms) 6876 { 6877 save_errno = EINVAL; 6878 cleanup_shm(false); 6879 goto error; 6880 } 6881 p = (int *) SHM_OFF_TAG(Pshm); 6882 if (*p != (int) hash) 6883 { 6884 save_errno = EINVAL; 6885 cleanup_shm(false); 6886 goto error; 6887 } 6888 6889 /* 6890 ** XXX how to check the pid? 6891 ** Read it from the pid-file? That does 6892 ** not need to exist. 6893 ** We could disable shm if we can't confirm 6894 ** that it is the right one. 6895 */ 6896 } 6897 6898 PtrFileSys = (FILESYS *) OFF_FILE_SYS(Pshm); 6899 PNumFileSys = (int *) OFF_NUM_FILE_SYS(Pshm); 6900 QShm = (QUEUE_SHM_T *) OFF_QUEUE_SHM(Pshm); 6901 PRSATmpCnt = (int *) OFF_RSA_TMP_CNT(Pshm); 6902 *PRSATmpCnt = 0; 6903 if (owner) 6904 { 6905 /* initialize values in shared memory */ 6906 NumFileSys = 0; 6907 for (i = 0; i < qn; i++) 6908 QShm[i].qs_entries = -1; 6909 } 6910 init_sem(owner); 6911 return; 6912 } 6913 error: 6914 if (LogLevel > (owner ? 8 : 11)) 6915 { 6916 sm_syslog(owner ? LOG_ERR : LOG_NOTICE, NOQID, 6917 "can't %s shared memory, key=%ld: %s", 6918 owner ? "initialize" : "attach to", 6919 (long) ShmKey, sm_errstring(save_errno)); 6920 } 6921 } 6922 #endif /* SM_CONF_SHM */ 6923 6924 6925 /* 6926 ** SETUP_QUEUES -- setup all queue groups 6927 ** 6928 ** Parameters: 6929 ** owner -- owner of shared memory. 6930 ** 6931 ** Returns: 6932 ** none. 6933 ** 6934 #if SM_CONF_SHM 6935 ** Side Effects: 6936 ** attaches shared memory. 6937 #endif * SM_CONF_SHM * 6938 */ 6939 6940 void 6941 setup_queues(owner) 6942 bool owner; 6943 { 6944 int i, qn, len; 6945 unsigned int hashval; 6946 time_t now; 6947 char basedir[MAXPATHLEN]; 6948 struct stat st; 6949 6950 /* 6951 ** Determine basedir for all queue directories. 6952 ** All queue directories must be (first level) subdirectories 6953 ** of the basedir. The basedir is the QueueDir 6954 ** without wildcards, but with trailing / 6955 */ 6956 6957 hashval = 0; 6958 errno = 0; 6959 len = sm_strlcpy(basedir, QueueDir, sizeof basedir); 6960 6961 /* Provide space for trailing '/' */ 6962 if (len >= sizeof basedir - 1) 6963 { 6964 syserr("QueueDirectory: path too long: %d, max %d", 6965 len, (int) sizeof basedir - 1); 6966 ExitStat = EX_CONFIG; 6967 return; 6968 } 6969 SM_ASSERT(len > 0); 6970 if (basedir[len - 1] == '*') 6971 { 6972 char *cp; 6973 6974 cp = SM_LAST_DIR_DELIM(basedir); 6975 if (cp == NULL) 6976 { 6977 syserr("QueueDirectory: can not wildcard relative path \"%s\"", 6978 QueueDir); 6979 if (tTd(41, 2)) 6980 sm_dprintf("setup_queues: \"%s\": Can not wildcard relative path.\n", 6981 QueueDir); 6982 ExitStat = EX_CONFIG; 6983 return; 6984 } 6985 6986 /* cut off wildcard pattern */ 6987 *++cp = '\0'; 6988 len = cp - basedir; 6989 } 6990 else if (!SM_IS_DIR_DELIM(basedir[len - 1])) 6991 { 6992 /* append trailing slash since it is a directory */ 6993 basedir[len] = '/'; 6994 basedir[++len] = '\0'; 6995 } 6996 6997 /* len counts up to the last directory delimiter */ 6998 SM_ASSERT(basedir[len - 1] == '/'); 6999 7000 if (chdir(basedir) < 0) 7001 { 7002 int save_errno = errno; 7003 7004 syserr("can not chdir(%s)", basedir); 7005 if (save_errno == EACCES) 7006 (void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT, 7007 "Program mode requires special privileges, e.g., root or TrustedUser.\n"); 7008 if (tTd(41, 2)) 7009 sm_dprintf("setup_queues: \"%s\": %s\n", 7010 basedir, sm_errstring(errno)); 7011 ExitStat = EX_CONFIG; 7012 return; 7013 } 7014 #if SM_CONF_SHM 7015 hashval = hash_q(basedir, hashval); 7016 #endif /* SM_CONF_SHM */ 7017 7018 /* initialize for queue runs */ 7019 DoQueueRun = false; 7020 now = curtime(); 7021 for (i = 0; i < NumQueue && Queue[i] != NULL; i++) 7022 Queue[i]->qg_nextrun = now; 7023 7024 7025 if (UseMSP && OpMode != MD_TEST) 7026 { 7027 long sff = SFF_CREAT; 7028 7029 if (stat(".", &st) < 0) 7030 { 7031 syserr("can not stat(%s)", basedir); 7032 if (tTd(41, 2)) 7033 sm_dprintf("setup_queues: \"%s\": %s\n", 7034 basedir, sm_errstring(errno)); 7035 ExitStat = EX_CONFIG; 7036 return; 7037 } 7038 if (RunAsUid == 0) 7039 sff |= SFF_ROOTOK; 7040 7041 /* 7042 ** Check queue directory permissions. 7043 ** Can we write to a group writable queue directory? 7044 */ 7045 7046 if (bitset(S_IWGRP, QueueFileMode) && 7047 bitset(S_IWGRP, st.st_mode) && 7048 safefile(" ", RunAsUid, RunAsGid, RunAsUserName, sff, 7049 QueueFileMode, NULL) != 0) 7050 { 7051 syserr("can not write to queue directory %s (RunAsGid=%d, required=%d)", 7052 basedir, (int) RunAsGid, (int) st.st_gid); 7053 } 7054 if (bitset(S_IWOTH|S_IXOTH, st.st_mode)) 7055 { 7056 #if _FFR_MSP_PARANOIA 7057 syserr("dangerous permissions=%o on queue directory %s", 7058 (int) st.st_mode, basedir); 7059 #else /* _FFR_MSP_PARANOIA */ 7060 if (LogLevel > 0) 7061 sm_syslog(LOG_ERR, NOQID, 7062 "dangerous permissions=%o on queue directory %s", 7063 (int) st.st_mode, basedir); 7064 #endif /* _FFR_MSP_PARANOIA */ 7065 } 7066 #if _FFR_MSP_PARANOIA 7067 if (NumQueue > 1) 7068 syserr("can not use multiple queues for MSP"); 7069 #endif /* _FFR_MSP_PARANOIA */ 7070 } 7071 7072 /* initial number of queue directories */ 7073 qn = 0; 7074 for (i = 0; i < NumQueue && Queue[i] != NULL; i++) 7075 qn = multiqueue_cache(basedir, len, Queue[i], qn, &hashval); 7076 7077 #if SM_CONF_SHM 7078 init_shm(qn, owner, hashval); 7079 i = filesys_setup(owner || ShmId == SM_SHM_NO_ID); 7080 if (i == FSF_NOT_FOUND) 7081 { 7082 /* 7083 ** We didn't get the right filesystem data 7084 ** This may happen if we don't have the right shared memory. 7085 ** So let's do this without shared memory. 7086 */ 7087 7088 SM_ASSERT(!owner); 7089 cleanup_shm(false); /* release shared memory */ 7090 i = filesys_setup(false); 7091 if (i < 0) 7092 syserr("filesys_setup failed twice, result=%d", i); 7093 else if (LogLevel > 8) 7094 sm_syslog(LOG_WARNING, NOQID, 7095 "shared memory does not contain expected data, ignored"); 7096 } 7097 #else /* SM_CONF_SHM */ 7098 i = filesys_setup(true); 7099 #endif /* SM_CONF_SHM */ 7100 if (i < 0) 7101 ExitStat = EX_CONFIG; 7102 } 7103 7104 #if SM_CONF_SHM 7105 /* 7106 ** CLEANUP_SHM -- do some cleanup work for shared memory etc 7107 ** 7108 ** Parameters: 7109 ** owner -- owner of shared memory? 7110 ** 7111 ** Returns: 7112 ** none. 7113 ** 7114 ** Side Effects: 7115 ** detaches shared memory. 7116 */ 7117 7118 void 7119 cleanup_shm(owner) 7120 bool owner; 7121 { 7122 if (ShmId != SM_SHM_NO_ID) 7123 { 7124 if (sm_shmstop(Pshm, ShmId, owner) < 0 && LogLevel > 8) 7125 sm_syslog(LOG_INFO, NOQID, "sm_shmstop failed=%s", 7126 sm_errstring(errno)); 7127 Pshm = NULL; 7128 ShmId = SM_SHM_NO_ID; 7129 } 7130 stop_sem(owner); 7131 } 7132 #endif /* SM_CONF_SHM */ 7133 7134 /* 7135 ** CLEANUP_QUEUES -- do some cleanup work for queues 7136 ** 7137 ** Parameters: 7138 ** none. 7139 ** 7140 ** Returns: 7141 ** none. 7142 ** 7143 */ 7144 7145 void 7146 cleanup_queues() 7147 { 7148 sync_queue_time(); 7149 } 7150 /* 7151 ** SET_DEF_QUEUEVAL -- set default values for a queue group. 7152 ** 7153 ** Parameters: 7154 ** qg -- queue group 7155 ** all -- set all values (true for default group)? 7156 ** 7157 ** Returns: 7158 ** none. 7159 ** 7160 ** Side Effects: 7161 ** sets default values for the queue group. 7162 */ 7163 7164 void 7165 set_def_queueval(qg, all) 7166 QUEUEGRP *qg; 7167 bool all; 7168 { 7169 if (bitnset(QD_DEFINED, qg->qg_flags)) 7170 return; 7171 if (all) 7172 qg->qg_qdir = QueueDir; 7173 #if _FFR_QUEUE_GROUP_SORTORDER 7174 qg->qg_sortorder = QueueSortOrder; 7175 #endif /* _FFR_QUEUE_GROUP_SORTORDER */ 7176 qg->qg_maxqrun = all ? MaxRunnersPerQueue : -1; 7177 qg->qg_nice = NiceQueueRun; 7178 } 7179 /* 7180 ** MAKEQUEUE -- define a new queue. 7181 ** 7182 ** Parameters: 7183 ** line -- description of queue. This is in labeled fields. 7184 ** The fields are: 7185 ** F -- the flags associated with the queue 7186 ** I -- the interval between running the queue 7187 ** J -- the maximum # of jobs in work list 7188 ** [M -- the maximum # of jobs in a queue run] 7189 ** N -- the niceness at which to run 7190 ** P -- the path to the queue 7191 ** S -- the queue sorting order 7192 ** R -- number of parallel queue runners 7193 ** r -- max recipients per envelope 7194 ** The first word is the canonical name of the queue. 7195 ** qdef -- this is a 'Q' definition from .cf 7196 ** 7197 ** Returns: 7198 ** none. 7199 ** 7200 ** Side Effects: 7201 ** enters the queue into the queue table. 7202 */ 7203 7204 void 7205 makequeue(line, qdef) 7206 char *line; 7207 bool qdef; 7208 { 7209 register char *p; 7210 register QUEUEGRP *qg; 7211 register STAB *s; 7212 int i; 7213 char fcode; 7214 7215 /* allocate a queue and set up defaults */ 7216 qg = (QUEUEGRP *) xalloc(sizeof *qg); 7217 memset((char *) qg, '\0', sizeof *qg); 7218 7219 if (line[0] == '\0') 7220 { 7221 syserr("name required for queue"); 7222 return; 7223 } 7224 7225 /* collect the queue name */ 7226 for (p = line; 7227 *p != '\0' && *p != ',' && !(isascii(*p) && isspace(*p)); 7228 p++) 7229 continue; 7230 if (*p != '\0') 7231 *p++ = '\0'; 7232 qg->qg_name = newstr(line); 7233 7234 /* set default values, can be overridden below */ 7235 set_def_queueval(qg, false); 7236 7237 /* now scan through and assign info from the fields */ 7238 while (*p != '\0') 7239 { 7240 auto char *delimptr; 7241 7242 while (*p != '\0' && 7243 (*p == ',' || (isascii(*p) && isspace(*p)))) 7244 p++; 7245 7246 /* p now points to field code */ 7247 fcode = *p; 7248 while (*p != '\0' && *p != '=' && *p != ',') 7249 p++; 7250 if (*p++ != '=') 7251 { 7252 syserr("queue %s: `=' expected", qg->qg_name); 7253 return; 7254 } 7255 while (isascii(*p) && isspace(*p)) 7256 p++; 7257 7258 /* p now points to the field body */ 7259 p = munchstring(p, &delimptr, ','); 7260 7261 /* install the field into the queue struct */ 7262 switch (fcode) 7263 { 7264 case 'P': /* pathname */ 7265 if (*p == '\0') 7266 syserr("queue %s: empty path name", 7267 qg->qg_name); 7268 else 7269 qg->qg_qdir = newstr(p); 7270 break; 7271 7272 case 'F': /* flags */ 7273 for (; *p != '\0'; p++) 7274 if (!(isascii(*p) && isspace(*p))) 7275 setbitn(*p, qg->qg_flags); 7276 break; 7277 7278 /* 7279 ** Do we need two intervals here: 7280 ** One for persistent queue runners, 7281 ** one for "normal" queue runs? 7282 */ 7283 7284 case 'I': /* interval between running the queue */ 7285 qg->qg_queueintvl = convtime(p, 'm'); 7286 break; 7287 7288 case 'N': /* run niceness */ 7289 qg->qg_nice = atoi(p); 7290 break; 7291 7292 case 'R': /* maximum # of runners for the group */ 7293 i = atoi(p); 7294 7295 /* can't have more runners than allowed total */ 7296 if (MaxQueueChildren > 0 && i > MaxQueueChildren) 7297 { 7298 qg->qg_maxqrun = MaxQueueChildren; 7299 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 7300 "Q=%s: R=%d exceeds MaxQueueChildren=%d, set to MaxQueueChildren\n", 7301 qg->qg_name, i, 7302 MaxQueueChildren); 7303 } 7304 else 7305 qg->qg_maxqrun = i; 7306 break; 7307 7308 case 'J': /* maximum # of jobs in work list */ 7309 qg->qg_maxlist = atoi(p); 7310 break; 7311 7312 case 'r': /* max recipients per envelope */ 7313 qg->qg_maxrcpt = atoi(p); 7314 break; 7315 7316 #if _FFR_QUEUE_GROUP_SORTORDER 7317 case 'S': /* queue sorting order */ 7318 switch (*p) 7319 { 7320 case 'h': /* Host first */ 7321 case 'H': 7322 qg->qg_sortorder = QSO_BYHOST; 7323 break; 7324 7325 case 'p': /* Priority order */ 7326 case 'P': 7327 qg->qg_sortorder = QSO_BYPRIORITY; 7328 break; 7329 7330 case 't': /* Submission time */ 7331 case 'T': 7332 qg->qg_sortorder = QSO_BYTIME; 7333 break; 7334 7335 case 'f': /* File name */ 7336 case 'F': 7337 qg->qg_sortorder = QSO_BYFILENAME; 7338 break; 7339 7340 case 'm': /* Modification time */ 7341 case 'M': 7342 qg->qg_sortorder = QSO_BYMODTIME; 7343 break; 7344 7345 case 'r': /* Random */ 7346 case 'R': 7347 qg->qg_sortorder = QSO_RANDOM; 7348 break; 7349 7350 # if _FFR_RHS 7351 case 's': /* Shuffled host name */ 7352 case 'S': 7353 qg->qg_sortorder = QSO_BYSHUFFLE; 7354 break; 7355 # endif /* _FFR_RHS */ 7356 7357 case 'n': /* none */ 7358 case 'N': 7359 qg->qg_sortorder = QSO_NONE; 7360 break; 7361 7362 default: 7363 syserr("Invalid queue sort order \"%s\"", p); 7364 } 7365 break; 7366 #endif /* _FFR_QUEUE_GROUP_SORTORDER */ 7367 7368 default: 7369 syserr("Q%s: unknown queue equate %c=", 7370 qg->qg_name, fcode); 7371 break; 7372 } 7373 7374 p = delimptr; 7375 } 7376 7377 #if !HASNICE 7378 if (qg->qg_nice != NiceQueueRun) 7379 { 7380 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 7381 "Q%s: Warning: N= set on system that doesn't support nice()\n", 7382 qg->qg_name); 7383 } 7384 #endif /* !HASNICE */ 7385 7386 /* do some rationality checking */ 7387 if (NumQueue >= MAXQUEUEGROUPS) 7388 { 7389 syserr("too many queue groups defined (%d max)", 7390 MAXQUEUEGROUPS); 7391 return; 7392 } 7393 7394 if (qg->qg_qdir == NULL) 7395 { 7396 if (QueueDir == NULL || *QueueDir == '\0') 7397 { 7398 syserr("QueueDir must be defined before queue groups"); 7399 return; 7400 } 7401 qg->qg_qdir = newstr(QueueDir); 7402 } 7403 7404 if (qg->qg_maxqrun > 1 && !bitnset(QD_FORK, qg->qg_flags)) 7405 { 7406 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 7407 "Warning: Q=%s: R=%d: multiple queue runners specified\n\tbut flag '%c' is not set\n", 7408 qg->qg_name, qg->qg_maxqrun, QD_FORK); 7409 } 7410 7411 /* enter the queue into the symbol table */ 7412 if (tTd(37, 8)) 7413 sm_syslog(LOG_INFO, NOQID, 7414 "Adding %s to stab, path: %s", qg->qg_name, 7415 qg->qg_qdir); 7416 s = stab(qg->qg_name, ST_QUEUE, ST_ENTER); 7417 if (s->s_quegrp != NULL) 7418 { 7419 i = s->s_quegrp->qg_index; 7420 7421 /* XXX what about the pointers inside this struct? */ 7422 sm_free(s->s_quegrp); /* XXX */ 7423 } 7424 else 7425 i = NumQueue++; 7426 Queue[i] = s->s_quegrp = qg; 7427 qg->qg_index = i; 7428 7429 /* set default value for max queue runners */ 7430 if (qg->qg_maxqrun < 0) 7431 { 7432 if (MaxRunnersPerQueue > 0) 7433 qg->qg_maxqrun = MaxRunnersPerQueue; 7434 else 7435 qg->qg_maxqrun = 1; 7436 } 7437 if (qdef) 7438 setbitn(QD_DEFINED, qg->qg_flags); 7439 } 7440 #if 0 7441 /* 7442 ** HASHFQN -- calculate a hash value for a fully qualified host name 7443 ** 7444 ** Arguments: 7445 ** fqn -- an all lower-case host.domain string 7446 ** buckets -- the number of buckets (queue directories) 7447 ** 7448 ** Returns: 7449 ** a bucket number (signed integer) 7450 ** -1 on error 7451 ** 7452 ** Contributed by Exactis.com, Inc. 7453 */ 7454 7455 int 7456 hashfqn(fqn, buckets) 7457 register char *fqn; 7458 int buckets; 7459 { 7460 register char *p; 7461 register int h = 0, hash, cnt; 7462 7463 if (fqn == NULL) 7464 return -1; 7465 7466 /* 7467 ** A variation on the gdb hash 7468 ** This is the best as of Feb 19, 1996 --bcx 7469 */ 7470 7471 p = fqn; 7472 h = 0x238F13AF * strlen(p); 7473 for (cnt = 0; *p != 0; ++p, cnt++) 7474 { 7475 h = (h + (*p << (cnt * 5 % 24))) & 0x7FFFFFFF; 7476 } 7477 h = (1103515243 * h + 12345) & 0x7FFFFFFF; 7478 if (buckets < 2) 7479 hash = 0; 7480 else 7481 hash = (h % buckets); 7482 7483 return hash; 7484 } 7485 #endif /* 0 */ 7486 7487 /* 7488 ** A structure for sorting Queue according to maxqrun without 7489 ** screwing up Queue itself. 7490 */ 7491 7492 struct sortqgrp 7493 { 7494 int sg_idx; /* original index */ 7495 int sg_maxqrun; /* max queue runners */ 7496 }; 7497 typedef struct sortqgrp SORTQGRP_T; 7498 static int cmpidx __P((const void *, const void *)); 7499 7500 static int 7501 cmpidx(a, b) 7502 const void *a; 7503 const void *b; 7504 { 7505 /* The sort is highest to lowest, so the comparison is reversed */ 7506 if (((SORTQGRP_T *)a)->sg_maxqrun < ((SORTQGRP_T *)b)->sg_maxqrun) 7507 return 1; 7508 else if (((SORTQGRP_T *)a)->sg_maxqrun > ((SORTQGRP_T *)b)->sg_maxqrun) 7509 return -1; 7510 else 7511 return 0; 7512 } 7513 7514 /* 7515 ** MAKEWORKGROUP -- balance queue groups into work groups per MaxQueueChildren 7516 ** 7517 ** Take the now defined queue groups and assign them to work groups. 7518 ** This is done to balance out the number of concurrently active 7519 ** queue runners such that MaxQueueChildren is not exceeded. This may 7520 ** result in more than one queue group per work group. In such a case 7521 ** the number of running queue groups in that work group will have no 7522 ** more than the work group maximum number of runners (a "fair" portion 7523 ** of MaxQueueRunners). All queue groups within a work group will get a 7524 ** chance at running. 7525 ** 7526 ** Parameters: 7527 ** none. 7528 ** 7529 ** Returns: 7530 ** nothing. 7531 ** 7532 ** Side Effects: 7533 ** Sets up WorkGrp structure. 7534 */ 7535 7536 void 7537 makeworkgroups() 7538 { 7539 int i, j, total_runners, dir, h; 7540 SORTQGRP_T si[MAXQUEUEGROUPS + 1]; 7541 7542 total_runners = 0; 7543 if (NumQueue == 1 && strcmp(Queue[0]->qg_name, "mqueue") == 0) 7544 { 7545 /* 7546 ** There is only the "mqueue" queue group (a default) 7547 ** containing all of the queues. We want to provide to 7548 ** this queue group the maximum allowable queue runners. 7549 ** To match older behavior (8.10/8.11) we'll try for 7550 ** 1 runner per queue capping it at MaxQueueChildren. 7551 ** So if there are N queues, then there will be N runners 7552 ** for the "mqueue" queue group (where N is kept less than 7553 ** MaxQueueChildren). 7554 */ 7555 7556 NumWorkGroups = 1; 7557 WorkGrp[0].wg_numqgrp = 1; 7558 WorkGrp[0].wg_qgs = (QUEUEGRP **) xalloc(sizeof(QUEUEGRP *)); 7559 WorkGrp[0].wg_qgs[0] = Queue[0]; 7560 if (MaxQueueChildren > 0 && 7561 Queue[0]->qg_numqueues > MaxQueueChildren) 7562 WorkGrp[0].wg_runners = MaxQueueChildren; 7563 else 7564 WorkGrp[0].wg_runners = Queue[0]->qg_numqueues; 7565 7566 Queue[0]->qg_wgrp = 0; 7567 7568 /* can't have more runners than allowed total */ 7569 if (MaxQueueChildren > 0 && 7570 Queue[0]->qg_maxqrun > MaxQueueChildren) 7571 Queue[0]->qg_maxqrun = MaxQueueChildren; 7572 WorkGrp[0].wg_maxact = Queue[0]->qg_maxqrun; 7573 WorkGrp[0].wg_lowqintvl = Queue[0]->qg_queueintvl; 7574 return; 7575 } 7576 7577 for (i = 0; i < NumQueue; i++) 7578 { 7579 si[i].sg_maxqrun = Queue[i]->qg_maxqrun; 7580 si[i].sg_idx = i; 7581 } 7582 qsort(si, NumQueue, sizeof(si[0]), cmpidx); 7583 7584 NumWorkGroups = 0; 7585 for (i = 0; i < NumQueue; i++) 7586 { 7587 total_runners += si[i].sg_maxqrun; 7588 if (MaxQueueChildren <= 0 || total_runners <= MaxQueueChildren) 7589 NumWorkGroups++; 7590 else 7591 break; 7592 } 7593 7594 if (NumWorkGroups < 1) 7595 NumWorkGroups = 1; /* gotta have one at least */ 7596 else if (NumWorkGroups > MAXWORKGROUPS) 7597 NumWorkGroups = MAXWORKGROUPS; /* the limit */ 7598 7599 /* 7600 ** We now know the number of work groups to pack the queue groups 7601 ** into. The queue groups in 'Queue' are sorted from highest 7602 ** to lowest for the number of runners per queue group. 7603 ** We put the queue groups with the largest number of runners 7604 ** into work groups first. Then the smaller ones are fitted in 7605 ** where it looks best. 7606 */ 7607 7608 j = 0; 7609 dir = 1; 7610 for (i = 0; i < NumQueue; i++) 7611 { 7612 /* a to-and-fro packing scheme, continue from last position */ 7613 if (j >= NumWorkGroups) 7614 { 7615 dir = -1; 7616 j = NumWorkGroups - 1; 7617 } 7618 else if (j < 0) 7619 { 7620 j = 0; 7621 dir = 1; 7622 } 7623 7624 if (WorkGrp[j].wg_qgs == NULL) 7625 WorkGrp[j].wg_qgs = (QUEUEGRP **)sm_malloc(sizeof(QUEUEGRP *) * 7626 (WorkGrp[j].wg_numqgrp + 1)); 7627 else 7628 WorkGrp[j].wg_qgs = (QUEUEGRP **)sm_realloc(WorkGrp[j].wg_qgs, 7629 sizeof(QUEUEGRP *) * 7630 (WorkGrp[j].wg_numqgrp + 1)); 7631 if (WorkGrp[j].wg_qgs == NULL) 7632 { 7633 syserr("!cannot allocate memory for work queues, need %d bytes", 7634 (int) (sizeof(QUEUEGRP *) * 7635 (WorkGrp[j].wg_numqgrp + 1))); 7636 } 7637 7638 h = si[i].sg_idx; 7639 WorkGrp[j].wg_qgs[WorkGrp[j].wg_numqgrp] = Queue[h]; 7640 WorkGrp[j].wg_numqgrp++; 7641 WorkGrp[j].wg_runners += Queue[h]->qg_maxqrun; 7642 Queue[h]->qg_wgrp = j; 7643 7644 if (WorkGrp[j].wg_maxact == 0) 7645 { 7646 /* can't have more runners than allowed total */ 7647 if (MaxQueueChildren > 0 && 7648 Queue[h]->qg_maxqrun > MaxQueueChildren) 7649 Queue[h]->qg_maxqrun = MaxQueueChildren; 7650 WorkGrp[j].wg_maxact = Queue[h]->qg_maxqrun; 7651 } 7652 7653 /* 7654 ** XXX: must wg_lowqintvl be the GCD? 7655 ** qg1: 2m, qg2: 3m, minimum: 2m, when do queue runs for 7656 ** qg2 occur? 7657 */ 7658 7659 /* keep track of the lowest interval for a persistent runner */ 7660 if (Queue[h]->qg_queueintvl > 0 && 7661 WorkGrp[j].wg_lowqintvl < Queue[h]->qg_queueintvl) 7662 WorkGrp[j].wg_lowqintvl = Queue[h]->qg_queueintvl; 7663 j += dir; 7664 } 7665 if (tTd(41, 9)) 7666 { 7667 for (i = 0; i < NumWorkGroups; i++) 7668 { 7669 sm_dprintf("Workgroup[%d]=", i); 7670 for (j = 0; j < WorkGrp[i].wg_numqgrp; j++) 7671 { 7672 sm_dprintf("%s, ", 7673 WorkGrp[i].wg_qgs[j]->qg_name); 7674 } 7675 sm_dprintf("\n"); 7676 } 7677 } 7678 } 7679 7680 /* 7681 ** DUP_DF -- duplicate envelope data file 7682 ** 7683 ** Copy the data file from the 'old' envelope to the 'new' envelope 7684 ** in the most efficient way possible. 7685 ** 7686 ** Create a hard link from the 'old' data file to the 'new' data file. 7687 ** If the old and new queue directories are on different file systems, 7688 ** then the new data file link is created in the old queue directory, 7689 ** and the new queue file will contain a 'd' record pointing to the 7690 ** directory containing the new data file. 7691 ** 7692 ** Parameters: 7693 ** old -- old envelope. 7694 ** new -- new envelope. 7695 ** 7696 ** Results: 7697 ** Returns true on success, false on failure. 7698 ** 7699 ** Side Effects: 7700 ** On success, the new data file is created. 7701 ** On fatal failure, EF_FATALERRS is set in old->e_flags. 7702 */ 7703 7704 static bool dup_df __P((ENVELOPE *, ENVELOPE *)); 7705 7706 static bool 7707 dup_df(old, new) 7708 ENVELOPE *old; 7709 ENVELOPE *new; 7710 { 7711 int ofs, nfs, r; 7712 char opath[MAXPATHLEN]; 7713 char npath[MAXPATHLEN]; 7714 7715 if (!bitset(EF_HAS_DF, old->e_flags)) 7716 { 7717 /* 7718 ** this can happen if: SuperSafe != True 7719 ** and a bounce mail is sent that is split. 7720 */ 7721 7722 queueup(old, false, true); 7723 } 7724 SM_REQUIRE(ISVALIDQGRP(old->e_qgrp) && ISVALIDQDIR(old->e_qdir)); 7725 SM_REQUIRE(ISVALIDQGRP(new->e_qgrp) && ISVALIDQDIR(new->e_qdir)); 7726 7727 (void) sm_strlcpy(opath, queuename(old, DATAFL_LETTER), sizeof opath); 7728 (void) sm_strlcpy(npath, queuename(new, DATAFL_LETTER), sizeof npath); 7729 7730 if (old->e_dfp != NULL) 7731 { 7732 r = sm_io_setinfo(old->e_dfp, SM_BF_COMMIT, NULL); 7733 if (r < 0 && errno != EINVAL) 7734 { 7735 syserr("@can't commit %s", opath); 7736 old->e_flags |= EF_FATALERRS; 7737 return false; 7738 } 7739 } 7740 7741 /* 7742 ** Attempt to create a hard link, if we think both old and new 7743 ** are on the same file system, otherwise copy the file. 7744 ** 7745 ** Don't waste time attempting a hard link unless old and new 7746 ** are on the same file system. 7747 */ 7748 7749 SM_REQUIRE(ISVALIDQGRP(old->e_dfqgrp) && ISVALIDQDIR(old->e_dfqdir)); 7750 SM_REQUIRE(ISVALIDQGRP(new->e_dfqgrp) && ISVALIDQDIR(new->e_dfqdir)); 7751 7752 ofs = Queue[old->e_dfqgrp]->qg_qpaths[old->e_dfqdir].qp_fsysidx; 7753 nfs = Queue[new->e_dfqgrp]->qg_qpaths[new->e_dfqdir].qp_fsysidx; 7754 if (FILE_SYS_DEV(ofs) == FILE_SYS_DEV(nfs)) 7755 { 7756 if (link(opath, npath) == 0) 7757 { 7758 new->e_flags |= EF_HAS_DF; 7759 SYNC_DIR(npath, true); 7760 return true; 7761 } 7762 goto error; 7763 } 7764 7765 /* 7766 ** Can't link across queue directories, so try to create a hard 7767 ** link in the same queue directory as the old df file. 7768 ** The qf file will refer to the new df file using a 'd' record. 7769 */ 7770 7771 new->e_dfqgrp = old->e_dfqgrp; 7772 new->e_dfqdir = old->e_dfqdir; 7773 (void) sm_strlcpy(npath, queuename(new, DATAFL_LETTER), sizeof npath); 7774 if (link(opath, npath) == 0) 7775 { 7776 new->e_flags |= EF_HAS_DF; 7777 SYNC_DIR(npath, true); 7778 return true; 7779 } 7780 7781 error: 7782 if (LogLevel > 0) 7783 sm_syslog(LOG_ERR, old->e_id, 7784 "dup_df: can't link %s to %s, error=%s, envelope splitting failed", 7785 opath, npath, sm_errstring(errno)); 7786 return false; 7787 } 7788 7789 /* 7790 ** SPLIT_ENV -- Allocate a new envelope based on a given envelope. 7791 ** 7792 ** Parameters: 7793 ** e -- envelope. 7794 ** sendqueue -- sendqueue for new envelope. 7795 ** qgrp -- index of queue group. 7796 ** qdir -- queue directory. 7797 ** 7798 ** Results: 7799 ** new envelope. 7800 ** 7801 */ 7802 7803 static ENVELOPE *split_env __P((ENVELOPE *, ADDRESS *, int, int)); 7804 7805 static ENVELOPE * 7806 split_env(e, sendqueue, qgrp, qdir) 7807 ENVELOPE *e; 7808 ADDRESS *sendqueue; 7809 int qgrp; 7810 int qdir; 7811 { 7812 ENVELOPE *ee; 7813 7814 ee = (ENVELOPE *) sm_rpool_malloc_x(e->e_rpool, sizeof *ee); 7815 STRUCTCOPY(*e, *ee); 7816 ee->e_message = NULL; /* XXX use original message? */ 7817 ee->e_id = NULL; 7818 assign_queueid(ee); 7819 ee->e_sendqueue = sendqueue; 7820 ee->e_flags &= ~(EF_INQUEUE|EF_CLRQUEUE|EF_FATALERRS 7821 |EF_SENDRECEIPT|EF_RET_PARAM|EF_HAS_DF); 7822 ee->e_flags |= EF_NORECEIPT; /* XXX really? */ 7823 ee->e_from.q_state = QS_SENDER; 7824 ee->e_dfp = NULL; 7825 ee->e_lockfp = NULL; 7826 if (e->e_xfp != NULL) 7827 ee->e_xfp = sm_io_dup(e->e_xfp); 7828 7829 /* failed to dup e->e_xfp, start a new transcript */ 7830 if (ee->e_xfp == NULL) 7831 openxscript(ee); 7832 7833 ee->e_qgrp = ee->e_dfqgrp = qgrp; 7834 ee->e_qdir = ee->e_dfqdir = qdir; 7835 ee->e_errormode = EM_MAIL; 7836 ee->e_statmsg = NULL; 7837 if (e->e_quarmsg != NULL) 7838 ee->e_quarmsg = sm_rpool_strdup_x(ee->e_rpool, 7839 e->e_quarmsg); 7840 7841 /* 7842 ** XXX Not sure if this copying is necessary. 7843 ** sendall() does this copying, but I (dm) don't know if that is 7844 ** because of the storage management discipline we were using 7845 ** before rpools were introduced, or if it is because these lists 7846 ** can be modified later. 7847 */ 7848 7849 ee->e_header = copyheader(e->e_header, ee->e_rpool); 7850 ee->e_errorqueue = copyqueue(e->e_errorqueue, ee->e_rpool); 7851 7852 return ee; 7853 } 7854 7855 /* return values from split functions, check also below! */ 7856 #define SM_SPLIT_FAIL (0) 7857 #define SM_SPLIT_NONE (1) 7858 #define SM_SPLIT_NEW(n) (1 + (n)) 7859 7860 /* 7861 ** SPLIT_ACROSS_QUEUE_GROUPS 7862 ** 7863 ** This function splits an envelope across multiple queue groups 7864 ** based on the queue group of each recipient. 7865 ** 7866 ** Parameters: 7867 ** e -- envelope. 7868 ** 7869 ** Results: 7870 ** SM_SPLIT_FAIL on failure 7871 ** SM_SPLIT_NONE if no splitting occurred, 7872 ** or 1 + the number of additional envelopes created. 7873 ** 7874 ** Side Effects: 7875 ** On success, e->e_sibling points to a list of zero or more 7876 ** additional envelopes, and the associated data files exist 7877 ** on disk. But the queue files are not created. 7878 ** 7879 ** On failure, e->e_sibling is not changed. 7880 ** The order of recipients in e->e_sendqueue is permuted. 7881 ** Abandoned data files for additional envelopes that failed 7882 ** to be created may exist on disk. 7883 */ 7884 7885 static int q_qgrp_compare __P((const void *, const void *)); 7886 static int e_filesys_compare __P((const void *, const void *)); 7887 7888 static int 7889 q_qgrp_compare(p1, p2) 7890 const void *p1; 7891 const void *p2; 7892 { 7893 ADDRESS **pq1 = (ADDRESS **) p1; 7894 ADDRESS **pq2 = (ADDRESS **) p2; 7895 7896 return (*pq1)->q_qgrp - (*pq2)->q_qgrp; 7897 } 7898 7899 static int 7900 e_filesys_compare(p1, p2) 7901 const void *p1; 7902 const void *p2; 7903 { 7904 ENVELOPE **pe1 = (ENVELOPE **) p1; 7905 ENVELOPE **pe2 = (ENVELOPE **) p2; 7906 int fs1, fs2; 7907 7908 fs1 = Queue[(*pe1)->e_qgrp]->qg_qpaths[(*pe1)->e_qdir].qp_fsysidx; 7909 fs2 = Queue[(*pe2)->e_qgrp]->qg_qpaths[(*pe2)->e_qdir].qp_fsysidx; 7910 if (FILE_SYS_DEV(fs1) < FILE_SYS_DEV(fs2)) 7911 return -1; 7912 if (FILE_SYS_DEV(fs1) > FILE_SYS_DEV(fs2)) 7913 return 1; 7914 return 0; 7915 } 7916 7917 static int 7918 split_across_queue_groups(e) 7919 ENVELOPE *e; 7920 { 7921 int naddrs, nsplits, i; 7922 bool changed; 7923 char **pvp; 7924 ADDRESS *q, **addrs; 7925 ENVELOPE *ee, *es; 7926 ENVELOPE *splits[MAXQUEUEGROUPS]; 7927 char pvpbuf[PSBUFSIZE]; 7928 7929 SM_REQUIRE(ISVALIDQGRP(e->e_qgrp)); 7930 7931 /* Count addresses and assign queue groups. */ 7932 naddrs = 0; 7933 changed = false; 7934 for (q = e->e_sendqueue; q != NULL; q = q->q_next) 7935 { 7936 if (QS_IS_DEAD(q->q_state)) 7937 continue; 7938 ++naddrs; 7939 7940 /* bad addresses and those already sent stay put */ 7941 if (QS_IS_BADADDR(q->q_state) || 7942 QS_IS_SENT(q->q_state)) 7943 q->q_qgrp = e->e_qgrp; 7944 else if (!ISVALIDQGRP(q->q_qgrp)) 7945 { 7946 /* call ruleset which should return a queue group */ 7947 i = rscap(RS_QUEUEGROUP, q->q_user, NULL, e, &pvp, 7948 pvpbuf, sizeof(pvpbuf)); 7949 if (i == EX_OK && 7950 pvp != NULL && pvp[0] != NULL && 7951 (pvp[0][0] & 0377) == CANONNET && 7952 pvp[1] != NULL && pvp[1][0] != '\0') 7953 { 7954 i = name2qid(pvp[1]); 7955 if (ISVALIDQGRP(i)) 7956 { 7957 q->q_qgrp = i; 7958 changed = true; 7959 if (tTd(20, 4)) 7960 sm_syslog(LOG_INFO, NOQID, 7961 "queue group name %s -> %d", 7962 pvp[1], i); 7963 continue; 7964 } 7965 else if (LogLevel > 10) 7966 sm_syslog(LOG_INFO, NOQID, 7967 "can't find queue group name %s, selection ignored", 7968 pvp[1]); 7969 } 7970 if (q->q_mailer != NULL && 7971 ISVALIDQGRP(q->q_mailer->m_qgrp)) 7972 { 7973 changed = true; 7974 q->q_qgrp = q->q_mailer->m_qgrp; 7975 } 7976 else if (ISVALIDQGRP(e->e_qgrp)) 7977 q->q_qgrp = e->e_qgrp; 7978 else 7979 q->q_qgrp = 0; 7980 } 7981 } 7982 7983 /* only one address? nothing to split. */ 7984 if (naddrs <= 1 && !changed) 7985 return SM_SPLIT_NONE; 7986 7987 /* sort the addresses by queue group */ 7988 addrs = sm_rpool_malloc_x(e->e_rpool, naddrs * sizeof(ADDRESS *)); 7989 for (i = 0, q = e->e_sendqueue; q != NULL; q = q->q_next) 7990 { 7991 if (QS_IS_DEAD(q->q_state)) 7992 continue; 7993 addrs[i++] = q; 7994 } 7995 qsort(addrs, naddrs, sizeof(ADDRESS *), q_qgrp_compare); 7996 7997 /* split into multiple envelopes, by queue group */ 7998 nsplits = 0; 7999 es = NULL; 8000 e->e_sendqueue = NULL; 8001 for (i = 0; i < naddrs; ++i) 8002 { 8003 if (i == naddrs - 1 || addrs[i]->q_qgrp != addrs[i + 1]->q_qgrp) 8004 addrs[i]->q_next = NULL; 8005 else 8006 addrs[i]->q_next = addrs[i + 1]; 8007 8008 /* same queue group as original envelope? */ 8009 if (addrs[i]->q_qgrp == e->e_qgrp) 8010 { 8011 if (e->e_sendqueue == NULL) 8012 e->e_sendqueue = addrs[i]; 8013 continue; 8014 } 8015 8016 /* different queue group than original envelope */ 8017 if (es == NULL || addrs[i]->q_qgrp != es->e_qgrp) 8018 { 8019 ee = split_env(e, addrs[i], addrs[i]->q_qgrp, NOQDIR); 8020 es = ee; 8021 splits[nsplits++] = ee; 8022 } 8023 } 8024 8025 /* no splits? return right now. */ 8026 if (nsplits <= 0) 8027 return SM_SPLIT_NONE; 8028 8029 /* assign a queue directory to each additional envelope */ 8030 for (i = 0; i < nsplits; ++i) 8031 { 8032 es = splits[i]; 8033 #if 0 8034 es->e_qdir = pickqdir(Queue[es->e_qgrp], es->e_msgsize, es); 8035 #endif /* 0 */ 8036 if (!setnewqueue(es)) 8037 goto failure; 8038 } 8039 8040 /* sort the additional envelopes by queue file system */ 8041 qsort(splits, nsplits, sizeof(ENVELOPE *), e_filesys_compare); 8042 8043 /* create data files for each additional envelope */ 8044 if (!dup_df(e, splits[0])) 8045 { 8046 i = 0; 8047 goto failure; 8048 } 8049 for (i = 1; i < nsplits; ++i) 8050 { 8051 /* copy or link to the previous data file */ 8052 if (!dup_df(splits[i - 1], splits[i])) 8053 goto failure; 8054 } 8055 8056 /* success: prepend the new envelopes to the e->e_sibling list */ 8057 for (i = 0; i < nsplits; ++i) 8058 { 8059 es = splits[i]; 8060 es->e_sibling = e->e_sibling; 8061 e->e_sibling = es; 8062 } 8063 return SM_SPLIT_NEW(nsplits); 8064 8065 /* failure: clean up */ 8066 failure: 8067 if (i > 0) 8068 { 8069 int j; 8070 8071 for (j = 0; j < i; j++) 8072 (void) unlink(queuename(splits[j], DATAFL_LETTER)); 8073 } 8074 e->e_sendqueue = addrs[0]; 8075 for (i = 0; i < naddrs - 1; ++i) 8076 addrs[i]->q_next = addrs[i + 1]; 8077 addrs[naddrs - 1]->q_next = NULL; 8078 return SM_SPLIT_FAIL; 8079 } 8080 8081 /* 8082 ** SPLIT_WITHIN_QUEUE 8083 ** 8084 ** Split an envelope with multiple recipients into several 8085 ** envelopes within the same queue directory, if the number of 8086 ** recipients exceeds the limit for the queue group. 8087 ** 8088 ** Parameters: 8089 ** e -- envelope. 8090 ** 8091 ** Results: 8092 ** SM_SPLIT_FAIL on failure 8093 ** SM_SPLIT_NONE if no splitting occurred, 8094 ** or 1 + the number of additional envelopes created. 8095 */ 8096 8097 #define SPLIT_LOG_LEVEL 8 8098 8099 static int split_within_queue __P((ENVELOPE *)); 8100 8101 static int 8102 split_within_queue(e) 8103 ENVELOPE *e; 8104 { 8105 int maxrcpt, nrcpt, ndead, nsplit, i; 8106 int j, l; 8107 char *lsplits; 8108 ADDRESS *q, **addrs; 8109 ENVELOPE *ee, *firstsibling; 8110 8111 if (!ISVALIDQGRP(e->e_qgrp) || bitset(EF_SPLIT, e->e_flags)) 8112 return SM_SPLIT_NONE; 8113 8114 /* don't bother if there is no recipient limit */ 8115 maxrcpt = Queue[e->e_qgrp]->qg_maxrcpt; 8116 if (maxrcpt <= 0) 8117 return SM_SPLIT_NONE; 8118 8119 /* count recipients */ 8120 nrcpt = 0; 8121 for (q = e->e_sendqueue; q != NULL; q = q->q_next) 8122 { 8123 if (QS_IS_DEAD(q->q_state)) 8124 continue; 8125 ++nrcpt; 8126 } 8127 if (nrcpt <= maxrcpt) 8128 return SM_SPLIT_NONE; 8129 8130 /* 8131 ** Preserve the recipient list 8132 ** so that we can restore it in case of error. 8133 ** (But we discard dead addresses.) 8134 */ 8135 8136 addrs = sm_rpool_malloc_x(e->e_rpool, nrcpt * sizeof(ADDRESS *)); 8137 for (i = 0, q = e->e_sendqueue; q != NULL; q = q->q_next) 8138 { 8139 if (QS_IS_DEAD(q->q_state)) 8140 continue; 8141 addrs[i++] = q; 8142 } 8143 8144 /* 8145 ** Partition the recipient list so that bad and sent addresses 8146 ** come first. These will go with the original envelope, and 8147 ** do not count towards the maxrcpt limit. 8148 ** addrs[] does not contain QS_IS_DEAD() addresses. 8149 */ 8150 8151 ndead = 0; 8152 for (i = 0; i < nrcpt; ++i) 8153 { 8154 if (QS_IS_BADADDR(addrs[i]->q_state) || 8155 QS_IS_SENT(addrs[i]->q_state) || 8156 QS_IS_DEAD(addrs[i]->q_state)) /* for paranoia's sake */ 8157 { 8158 if (i > ndead) 8159 { 8160 ADDRESS *tmp = addrs[i]; 8161 8162 addrs[i] = addrs[ndead]; 8163 addrs[ndead] = tmp; 8164 } 8165 ++ndead; 8166 } 8167 } 8168 8169 /* Check if no splitting required. */ 8170 if (nrcpt - ndead <= maxrcpt) 8171 return SM_SPLIT_NONE; 8172 8173 /* fix links */ 8174 for (i = 0; i < nrcpt - 1; ++i) 8175 addrs[i]->q_next = addrs[i + 1]; 8176 addrs[nrcpt - 1]->q_next = NULL; 8177 e->e_sendqueue = addrs[0]; 8178 8179 /* prepare buffer for logging */ 8180 if (LogLevel > SPLIT_LOG_LEVEL) 8181 { 8182 l = MAXLINE; 8183 lsplits = sm_malloc(l); 8184 if (lsplits != NULL) 8185 *lsplits = '\0'; 8186 j = 0; 8187 } 8188 else 8189 { 8190 /* get rid of stupid compiler warnings */ 8191 lsplits = NULL; 8192 j = l = 0; 8193 } 8194 8195 /* split the envelope */ 8196 firstsibling = e->e_sibling; 8197 i = maxrcpt + ndead; 8198 nsplit = 0; 8199 for (;;) 8200 { 8201 addrs[i - 1]->q_next = NULL; 8202 ee = split_env(e, addrs[i], e->e_qgrp, e->e_qdir); 8203 if (!dup_df(e, ee)) 8204 { 8205 8206 ee = firstsibling; 8207 while (ee != NULL) 8208 { 8209 (void) unlink(queuename(ee, DATAFL_LETTER)); 8210 ee = ee->e_sibling; 8211 } 8212 8213 /* Error. Restore e's sibling & recipient lists. */ 8214 e->e_sibling = firstsibling; 8215 for (i = 0; i < nrcpt - 1; ++i) 8216 addrs[i]->q_next = addrs[i + 1]; 8217 if (lsplits != NULL) 8218 sm_free(lsplits); 8219 return SM_SPLIT_FAIL; 8220 } 8221 8222 /* prepend the new envelope to e->e_sibling */ 8223 ee->e_sibling = e->e_sibling; 8224 e->e_sibling = ee; 8225 ++nsplit; 8226 if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL) 8227 { 8228 if (j >= l - strlen(ee->e_id) - 3) 8229 { 8230 char *p; 8231 8232 l += MAXLINE; 8233 p = sm_realloc(lsplits, l); 8234 if (p == NULL) 8235 { 8236 /* let's try to get this done */ 8237 sm_free(lsplits); 8238 lsplits = NULL; 8239 } 8240 else 8241 lsplits = p; 8242 } 8243 if (lsplits != NULL) 8244 { 8245 if (j == 0) 8246 j += sm_strlcat(lsplits + j, 8247 ee->e_id, 8248 l - j); 8249 else 8250 j += sm_strlcat2(lsplits + j, 8251 "; ", 8252 ee->e_id, 8253 l - j); 8254 SM_ASSERT(j < l); 8255 } 8256 } 8257 if (nrcpt - i <= maxrcpt) 8258 break; 8259 i += maxrcpt; 8260 } 8261 if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL) 8262 { 8263 if (nsplit > 0) 8264 { 8265 sm_syslog(LOG_NOTICE, e->e_id, 8266 "split: maxrcpts=%d, rcpts=%d, count=%d, id%s=%s", 8267 maxrcpt, nrcpt - ndead, nsplit, 8268 nsplit > 1 ? "s" : "", lsplits); 8269 } 8270 sm_free(lsplits); 8271 } 8272 return SM_SPLIT_NEW(nsplit); 8273 } 8274 /* 8275 ** SPLIT_BY_RECIPIENT 8276 ** 8277 ** Split an envelope with multiple recipients into multiple 8278 ** envelopes as required by the sendmail configuration. 8279 ** 8280 ** Parameters: 8281 ** e -- envelope. 8282 ** 8283 ** Results: 8284 ** Returns true on success, false on failure. 8285 ** 8286 ** Side Effects: 8287 ** see split_across_queue_groups(), split_within_queue(e) 8288 */ 8289 8290 bool 8291 split_by_recipient(e) 8292 ENVELOPE *e; 8293 { 8294 int split, n, i, j, l; 8295 char *lsplits; 8296 ENVELOPE *ee, *next, *firstsibling; 8297 8298 if (OpMode == SM_VERIFY || !ISVALIDQGRP(e->e_qgrp) || 8299 bitset(EF_SPLIT, e->e_flags)) 8300 return true; 8301 n = split_across_queue_groups(e); 8302 if (n == SM_SPLIT_FAIL) 8303 return false; 8304 firstsibling = ee = e->e_sibling; 8305 if (n > 1 && LogLevel > SPLIT_LOG_LEVEL) 8306 { 8307 l = MAXLINE; 8308 lsplits = sm_malloc(l); 8309 if (lsplits != NULL) 8310 *lsplits = '\0'; 8311 j = 0; 8312 } 8313 else 8314 { 8315 /* get rid of stupid compiler warnings */ 8316 lsplits = NULL; 8317 j = l = 0; 8318 } 8319 for (i = 1; i < n; ++i) 8320 { 8321 next = ee->e_sibling; 8322 if (split_within_queue(ee) == SM_SPLIT_FAIL) 8323 { 8324 e->e_sibling = firstsibling; 8325 return false; 8326 } 8327 ee->e_flags |= EF_SPLIT; 8328 if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL) 8329 { 8330 if (j >= l - strlen(ee->e_id) - 3) 8331 { 8332 char *p; 8333 8334 l += MAXLINE; 8335 p = sm_realloc(lsplits, l); 8336 if (p == NULL) 8337 { 8338 /* let's try to get this done */ 8339 sm_free(lsplits); 8340 lsplits = NULL; 8341 } 8342 else 8343 lsplits = p; 8344 } 8345 if (lsplits != NULL) 8346 { 8347 if (j == 0) 8348 j += sm_strlcat(lsplits + j, 8349 ee->e_id, l - j); 8350 else 8351 j += sm_strlcat2(lsplits + j, "; ", 8352 ee->e_id, l - j); 8353 SM_ASSERT(j < l); 8354 } 8355 } 8356 ee = next; 8357 } 8358 if (LogLevel > SPLIT_LOG_LEVEL && lsplits != NULL && n > 1) 8359 { 8360 sm_syslog(LOG_NOTICE, e->e_id, "split: count=%d, id%s=%s", 8361 n - 1, n > 2 ? "s" : "", lsplits); 8362 sm_free(lsplits); 8363 } 8364 split = split_within_queue(e) != SM_SPLIT_FAIL; 8365 if (split) 8366 e->e_flags |= EF_SPLIT; 8367 return split; 8368 } 8369 8370 /* 8371 ** QUARANTINE_QUEUE_ITEM -- {un,}quarantine a single envelope 8372 ** 8373 ** Add/remove quarantine reason and requeue appropriately. 8374 ** 8375 ** Parameters: 8376 ** qgrp -- queue group for the item 8377 ** qdir -- queue directory in the given queue group 8378 ** e -- envelope information for the item 8379 ** reason -- quarantine reason, NULL means unquarantine. 8380 ** 8381 ** Results: 8382 ** true if item changed, false otherwise 8383 ** 8384 ** Side Effects: 8385 ** Changes quarantine tag in queue file and renames it. 8386 */ 8387 8388 static bool 8389 quarantine_queue_item(qgrp, qdir, e, reason) 8390 int qgrp; 8391 int qdir; 8392 ENVELOPE *e; 8393 char *reason; 8394 { 8395 bool dirty = false; 8396 bool failing = false; 8397 bool foundq = false; 8398 bool finished = false; 8399 int fd; 8400 int flags; 8401 int oldtype; 8402 int newtype; 8403 int save_errno; 8404 MODE_T oldumask = 0; 8405 SM_FILE_T *oldqfp, *tempqfp; 8406 char *bp; 8407 char oldqf[MAXPATHLEN]; 8408 char tempqf[MAXPATHLEN]; 8409 char newqf[MAXPATHLEN]; 8410 char buf[MAXLINE]; 8411 8412 oldtype = queue_letter(e, ANYQFL_LETTER); 8413 (void) sm_strlcpy(oldqf, queuename(e, ANYQFL_LETTER), sizeof oldqf); 8414 (void) sm_strlcpy(tempqf, queuename(e, NEWQFL_LETTER), sizeof tempqf); 8415 8416 /* 8417 ** Instead of duplicating all the open 8418 ** and lock code here, tell readqf() to 8419 ** do that work and return the open 8420 ** file pointer in e_lockfp. Note that 8421 ** we must release the locks properly when 8422 ** we are done. 8423 */ 8424 8425 if (!readqf(e, true)) 8426 { 8427 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 8428 "Skipping %s\n", qid_printname(e)); 8429 return false; 8430 } 8431 oldqfp = e->e_lockfp; 8432 8433 /* open the new queue file */ 8434 flags = O_CREAT|O_WRONLY|O_EXCL; 8435 if (bitset(S_IWGRP, QueueFileMode)) 8436 oldumask = umask(002); 8437 fd = open(tempqf, flags, QueueFileMode); 8438 if (bitset(S_IWGRP, QueueFileMode)) 8439 (void) umask(oldumask); 8440 RELEASE_QUEUE; 8441 8442 if (fd < 0) 8443 { 8444 save_errno = errno; 8445 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 8446 "Skipping %s: Could not open %s: %s\n", 8447 qid_printname(e), tempqf, 8448 sm_errstring(save_errno)); 8449 (void) sm_io_close(oldqfp, SM_TIME_DEFAULT); 8450 return false; 8451 } 8452 if (!lockfile(fd, tempqf, NULL, LOCK_EX|LOCK_NB)) 8453 { 8454 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 8455 "Skipping %s: Could not lock %s\n", 8456 qid_printname(e), tempqf); 8457 (void) close(fd); 8458 (void) sm_io_close(oldqfp, SM_TIME_DEFAULT); 8459 return false; 8460 } 8461 8462 tempqfp = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT, (void *) &fd, 8463 SM_IO_WRONLY_B, NULL); 8464 if (tempqfp == NULL) 8465 { 8466 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 8467 "Skipping %s: Could not lock %s\n", 8468 qid_printname(e), tempqf); 8469 (void) close(fd); 8470 (void) sm_io_close(oldqfp, SM_TIME_DEFAULT); 8471 return false; 8472 } 8473 8474 /* Copy the data over, changing the quarantine reason */ 8475 while ((bp = fgetfolded(buf, sizeof buf, oldqfp)) != NULL) 8476 { 8477 if (tTd(40, 4)) 8478 sm_dprintf("+++++ %s\n", bp); 8479 switch (bp[0]) 8480 { 8481 case 'q': /* quarantine reason */ 8482 foundq = true; 8483 if (reason == NULL) 8484 { 8485 if (Verbose) 8486 { 8487 (void) sm_io_fprintf(smioout, 8488 SM_TIME_DEFAULT, 8489 "%s: Removed quarantine of \"%s\"\n", 8490 e->e_id, &bp[1]); 8491 } 8492 sm_syslog(LOG_INFO, e->e_id, "unquarantine"); 8493 dirty = true; 8494 continue; 8495 } 8496 else if (strcmp(reason, &bp[1]) == 0) 8497 { 8498 if (Verbose) 8499 { 8500 (void) sm_io_fprintf(smioout, 8501 SM_TIME_DEFAULT, 8502 "%s: Already quarantined with \"%s\"\n", 8503 e->e_id, reason); 8504 } 8505 (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT, 8506 "q%s\n", reason); 8507 } 8508 else 8509 { 8510 if (Verbose) 8511 { 8512 (void) sm_io_fprintf(smioout, 8513 SM_TIME_DEFAULT, 8514 "%s: Quarantine changed from \"%s\" to \"%s\"\n", 8515 e->e_id, &bp[1], 8516 reason); 8517 } 8518 (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT, 8519 "q%s\n", reason); 8520 sm_syslog(LOG_INFO, e->e_id, "quarantine=%s", 8521 reason); 8522 dirty = true; 8523 } 8524 break; 8525 8526 case 'S': 8527 /* 8528 ** If we are quarantining an unquarantined item, 8529 ** need to put in a new 'q' line before it's 8530 ** too late. 8531 */ 8532 8533 if (!foundq && reason != NULL) 8534 { 8535 if (Verbose) 8536 { 8537 (void) sm_io_fprintf(smioout, 8538 SM_TIME_DEFAULT, 8539 "%s: Quarantined with \"%s\"\n", 8540 e->e_id, reason); 8541 } 8542 (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT, 8543 "q%s\n", reason); 8544 sm_syslog(LOG_INFO, e->e_id, "quarantine=%s", 8545 reason); 8546 foundq = true; 8547 dirty = true; 8548 } 8549 8550 /* Copy the line to the new file */ 8551 (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT, 8552 "%s\n", bp); 8553 break; 8554 8555 case '.': 8556 finished = true; 8557 /* FALLTHROUGH */ 8558 8559 default: 8560 /* Copy the line to the new file */ 8561 (void) sm_io_fprintf(tempqfp, SM_TIME_DEFAULT, 8562 "%s\n", bp); 8563 break; 8564 } 8565 } 8566 8567 /* Make sure we read the whole old file */ 8568 errno = sm_io_error(tempqfp); 8569 if (errno != 0 && errno != SM_IO_EOF) 8570 { 8571 save_errno = errno; 8572 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 8573 "Skipping %s: Error reading %s: %s\n", 8574 qid_printname(e), oldqf, 8575 sm_errstring(save_errno)); 8576 failing = true; 8577 } 8578 8579 if (!failing && !finished) 8580 { 8581 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 8582 "Skipping %s: Incomplete file: %s\n", 8583 qid_printname(e), oldqf); 8584 failing = true; 8585 } 8586 8587 /* Check if we actually changed anything or we can just bail now */ 8588 if (!dirty) 8589 { 8590 /* pretend we failed, even though we technically didn't */ 8591 failing = true; 8592 } 8593 8594 /* Make sure we wrote things out safely */ 8595 if (!failing && 8596 (sm_io_flush(tempqfp, SM_TIME_DEFAULT) != 0 || 8597 ((SuperSafe == SAFE_REALLY || 8598 SuperSafe == SAFE_REALLY_POSTMILTER || 8599 SuperSafe == SAFE_INTERACTIVE) && 8600 fsync(sm_io_getinfo(tempqfp, SM_IO_WHAT_FD, NULL)) < 0) || 8601 ((errno = sm_io_error(tempqfp)) != 0))) 8602 { 8603 save_errno = errno; 8604 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 8605 "Skipping %s: Error writing %s: %s\n", 8606 qid_printname(e), tempqf, 8607 sm_errstring(save_errno)); 8608 failing = true; 8609 } 8610 8611 8612 /* Figure out the new filename */ 8613 newtype = (reason == NULL ? NORMQF_LETTER : QUARQF_LETTER); 8614 if (oldtype == newtype) 8615 { 8616 /* going to rename tempqf to oldqf */ 8617 (void) sm_strlcpy(newqf, oldqf, sizeof newqf); 8618 } 8619 else 8620 { 8621 /* going to rename tempqf to new name based on newtype */ 8622 (void) sm_strlcpy(newqf, queuename(e, newtype), sizeof newqf); 8623 } 8624 8625 save_errno = 0; 8626 8627 /* rename tempqf to newqf */ 8628 if (!failing && 8629 rename(tempqf, newqf) < 0) 8630 save_errno = (errno == 0) ? EINVAL : errno; 8631 8632 /* Check rename() success */ 8633 if (!failing && save_errno != 0) 8634 { 8635 sm_syslog(LOG_DEBUG, e->e_id, 8636 "quarantine_queue_item: rename(%s, %s): %s", 8637 tempqf, newqf, sm_errstring(save_errno)); 8638 8639 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 8640 "Error renaming %s to %s: %s\n", 8641 tempqf, newqf, 8642 sm_errstring(save_errno)); 8643 if (oldtype == newtype) 8644 { 8645 /* 8646 ** Bail here since we don't know the state of 8647 ** the filesystem and may need to keep tempqf 8648 ** for the user to rescue us. 8649 */ 8650 8651 RELEASE_QUEUE; 8652 errno = save_errno; 8653 syserr("!452 Error renaming control file %s", tempqf); 8654 /* NOTREACHED */ 8655 } 8656 else 8657 { 8658 /* remove new file (if rename() half completed) */ 8659 if (xunlink(newqf) < 0) 8660 { 8661 save_errno = errno; 8662 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 8663 "Error removing %s: %s\n", 8664 newqf, 8665 sm_errstring(save_errno)); 8666 } 8667 8668 /* tempqf removed below */ 8669 failing = true; 8670 } 8671 8672 } 8673 8674 /* If changing file types, need to remove old type */ 8675 if (!failing && oldtype != newtype) 8676 { 8677 if (xunlink(oldqf) < 0) 8678 { 8679 save_errno = errno; 8680 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 8681 "Error removing %s: %s\n", 8682 oldqf, sm_errstring(save_errno)); 8683 } 8684 } 8685 8686 /* see if anything above failed */ 8687 if (failing) 8688 { 8689 /* Something failed: remove new file, old file still there */ 8690 (void) xunlink(tempqf); 8691 } 8692 8693 /* 8694 ** fsync() after file operations to make sure metadata is 8695 ** written to disk on filesystems in which renames are 8696 ** not guaranteed. It's ok if they fail, mail won't be lost. 8697 */ 8698 8699 if (SuperSafe != SAFE_NO) 8700 { 8701 /* for soft-updates */ 8702 (void) fsync(sm_io_getinfo(tempqfp, 8703 SM_IO_WHAT_FD, NULL)); 8704 8705 if (!failing) 8706 { 8707 /* for soft-updates */ 8708 (void) fsync(sm_io_getinfo(oldqfp, 8709 SM_IO_WHAT_FD, NULL)); 8710 } 8711 8712 /* for other odd filesystems */ 8713 SYNC_DIR(tempqf, false); 8714 } 8715 8716 /* Close up shop */ 8717 RELEASE_QUEUE; 8718 if (tempqfp != NULL) 8719 (void) sm_io_close(tempqfp, SM_TIME_DEFAULT); 8720 if (oldqfp != NULL) 8721 (void) sm_io_close(oldqfp, SM_TIME_DEFAULT); 8722 8723 /* All went well */ 8724 return !failing; 8725 } 8726 8727 /* 8728 ** QUARANTINE_QUEUE -- {un,}quarantine matching items in the queue 8729 ** 8730 ** Read all matching queue items, add/remove quarantine 8731 ** reason, and requeue appropriately. 8732 ** 8733 ** Parameters: 8734 ** reason -- quarantine reason, "." means unquarantine. 8735 ** qgrplimit -- limit to single queue group unless NOQGRP 8736 ** 8737 ** Results: 8738 ** none. 8739 ** 8740 ** Side Effects: 8741 ** Lots of changes to the queue. 8742 */ 8743 8744 void 8745 quarantine_queue(reason, qgrplimit) 8746 char *reason; 8747 int qgrplimit; 8748 { 8749 int changed = 0; 8750 int qgrp; 8751 8752 /* Convert internal representation of unquarantine */ 8753 if (reason != NULL && reason[0] == '.' && reason[1] == '\0') 8754 reason = NULL; 8755 8756 if (reason != NULL) 8757 { 8758 /* clean it */ 8759 reason = newstr(denlstring(reason, true, true)); 8760 } 8761 8762 for (qgrp = 0; qgrp < NumQueue && Queue[qgrp] != NULL; qgrp++) 8763 { 8764 int qdir; 8765 8766 if (qgrplimit != NOQGRP && qgrplimit != qgrp) 8767 continue; 8768 8769 for (qdir = 0; qdir < Queue[qgrp]->qg_numqueues; qdir++) 8770 { 8771 int i; 8772 int nrequests; 8773 8774 if (StopRequest) 8775 stop_sendmail(); 8776 8777 nrequests = gatherq(qgrp, qdir, true, NULL, NULL); 8778 8779 /* first see if there is anything */ 8780 if (nrequests <= 0) 8781 { 8782 if (Verbose) 8783 { 8784 (void) sm_io_fprintf(smioout, 8785 SM_TIME_DEFAULT, "%s: no matches\n", 8786 qid_printqueue(qgrp, qdir)); 8787 } 8788 continue; 8789 } 8790 8791 if (Verbose) 8792 { 8793 (void) sm_io_fprintf(smioout, 8794 SM_TIME_DEFAULT, "Processing %s:\n", 8795 qid_printqueue(qgrp, qdir)); 8796 } 8797 8798 for (i = 0; i < WorkListCount; i++) 8799 { 8800 ENVELOPE e; 8801 8802 if (StopRequest) 8803 stop_sendmail(); 8804 8805 /* setup envelope */ 8806 clearenvelope(&e, true, sm_rpool_new_x(NULL)); 8807 e.e_id = WorkList[i].w_name + 2; 8808 e.e_qgrp = qgrp; 8809 e.e_qdir = qdir; 8810 8811 if (tTd(70, 101)) 8812 { 8813 sm_io_fprintf(smioout, SM_TIME_DEFAULT, 8814 "Would do %s\n", e.e_id); 8815 changed++; 8816 } 8817 else if (quarantine_queue_item(qgrp, qdir, 8818 &e, reason)) 8819 changed++; 8820 8821 /* clean up */ 8822 sm_rpool_free(e.e_rpool); 8823 e.e_rpool = NULL; 8824 } 8825 if (WorkList != NULL) 8826 sm_free(WorkList); /* XXX */ 8827 WorkList = NULL; 8828 WorkListSize = 0; 8829 WorkListCount = 0; 8830 } 8831 } 8832 if (Verbose) 8833 { 8834 if (changed == 0) 8835 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 8836 "No changes\n"); 8837 else 8838 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, 8839 "%d change%s\n", 8840 changed, 8841 changed == 1 ? "" : "s"); 8842 } 8843 } 8844