]> git.ipfire.org Git - thirdparty/cups.git/blame - scheduler/main.c
Full sweep of all Clang warnings, plus some bug fixes for incorrect memcpy usage.
[thirdparty/cups.git] / scheduler / main.c
CommitLineData
ef416fc2 1/*
f2d18633 2 * "$Id$"
ef416fc2 3 *
581dae2d 4 * Main loop for the CUPS scheduler.
ef416fc2 5 *
7e86f2f6 6 * Copyright 2007-2014 by Apple Inc.
581dae2d 7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
ef416fc2 8 *
581dae2d
MS
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * "LICENSE" which should have been included with this file. If this
13 * file is missing or damaged, see the license at "http://www.cups.org/".
ef416fc2 14 */
15
16/*
17 * Include necessary headers...
18 */
19
20#define _MAIN_C_
21#include "cupsd.h"
22#include <sys/resource.h>
23#include <syslog.h>
24#include <grp.h>
25
a4d04587 26#ifdef HAVE_LAUNCH_H
27# include <launch.h>
28# include <libgen.h>
ba55dc12 29# define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
f7deaa1a 30 /* Name of the launchd KeepAlive file */
31# ifndef LAUNCH_JOBKEY_KEEPALIVE
32# define LAUNCH_JOBKEY_KEEPALIVE "KeepAlive"
33# endif /* !LAUNCH_JOBKEY_KEEPALIVE */
34# ifndef LAUNCH_JOBKEY_PATHSTATE
35# define LAUNCH_JOBKEY_PATHSTATE "PathState"
36# endif /* !LAUNCH_JOBKEY_PATHSTATE */
37# ifndef LAUNCH_JOBKEY_SERVICEIPC
38# define LAUNCH_JOBKEY_SERVICEIPC "ServiceIPC"
39# endif /* !LAUNCH_JOBKEY_SERVICEIPC */
a4d04587 40#endif /* HAVE_LAUNCH_H */
41
ef416fc2 42#if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
43# include <malloc.h>
44#endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
3dd9c340 45
fa73b229 46#ifdef HAVE_NOTIFY_H
47# include <notify.h>
48#endif /* HAVE_NOTIFY_H */
ef416fc2 49
3dd9c340
MS
50#ifdef HAVE_SYS_PARAM_H
51# include <sys/param.h>
52#endif /* HAVE_SYS_PARAM_H */
53
ef416fc2 54
55/*
56 * Local functions...
57 */
58
a4d04587 59#ifdef HAVE_LAUNCHD
411affcf 60static void launchd_checkin(void);
f7deaa1a 61static void launchd_checkout(void);
a4d04587 62#endif /* HAVE_LAUNCHD */
411affcf 63static void parent_handler(int sig);
64static void process_children(void);
65static void sigchld_handler(int sig);
66static void sighup_handler(int sig);
67static void sigterm_handler(int sig);
68static long select_timeout(int fds);
85dda01c 69static void usage(int status) __attribute__((noreturn));
ef416fc2 70
71
72/*
73 * Local globals...
74 */
75
411affcf 76static int parent_signal = 0;
77 /* Set to signal number from child */
78static int holdcount = 0; /* Number of times "hold" was called */
ef416fc2 79#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
411affcf 80static sigset_t holdmask; /* Old POSIX signal mask */
ef416fc2 81#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
411affcf 82static int dead_children = 0;
83 /* Dead children? */
84static int stop_scheduler = 0;
85 /* Should the scheduler stop? */
86
ef416fc2 87
88/*
89 * 'main()' - Main entry for the CUPS scheduler.
90 */
91
92int /* O - Exit status */
bd7854cb 93main(int argc, /* I - Number of command-line args */
ef416fc2 94 char *argv[]) /* I - Command-line arguments */
95{
96 int i; /* Looping var */
97 char *opt; /* Option character */
98 int fg; /* Run in the foreground */
bd7854cb 99 int fds; /* Number of ready descriptors */
ef416fc2 100 cupsd_client_t *con; /* Current client */
101 cupsd_job_t *job; /* Current job */
102 cupsd_listener_t *lis; /* Current listener */
103 time_t current_time, /* Current time */
a4d04587 104 activity, /* Client activity timer */
ef416fc2 105 senddoc_time, /* Send-Document time */
411affcf 106 expire_time, /* Subscription expire time */
50fe7201 107 report_time, /* Malloc/client/job report time */
5a662dc0 108 event_time; /* Last event notification time */
f7deaa1a 109 long timeout; /* Timeout for cupsdDoSelect() */
ef416fc2 110 struct rlimit limit; /* Runtime limit */
111#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
112 struct sigaction action; /* Actions for POSIX signals */
113#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
68b10830
MS
114 int run_as_child = 0;
115 /* Needed for background fork/exec */
a41f09e2 116#ifdef __APPLE__
68b10830 117 int use_sysman = !getuid();
d7871c8c 118 /* Use system management functions? */
a4924f6c
MS
119#else
120 time_t netif_time = 0; /* Time since last network update */
a41f09e2 121#endif /* __APPLE__ */
a4d04587 122#if HAVE_LAUNCHD
4400e98d 123 int launchd_idle_exit;
a4d04587 124 /* Idle exit on select timeout? */
125#endif /* HAVE_LAUNCHD */
ef416fc2 126
127
db1f069b
MS
128#ifdef HAVE_GETEUID
129 /*
130 * Check for setuid invocation, which we do not support!
131 */
132
133 if (getuid() != geteuid())
134 {
4d301e69 135 fputs("cupsd: Cannot run as a setuid program\n", stderr);
db1f069b
MS
136 return (1);
137 }
138#endif /* HAVE_GETEUID */
139
ef416fc2 140 /*
141 * Check for command-line arguments...
142 */
143
4400e98d 144 fg = 0;
ef416fc2 145
09a101d6 146#ifdef HAVE_LAUNCHD
147 if (getenv("CUPSD_LAUNCHD"))
148 {
149 Launchd = 1;
150 fg = 1;
151 }
152#endif /* HAVE_LAUNCHD */
153
ef416fc2 154 for (i = 1; i < argc; i ++)
155 if (argv[i][0] == '-')
156 for (opt = argv[i] + 1; *opt != '\0'; opt ++)
157 switch (*opt)
158 {
a41f09e2
MS
159 case 'C' : /* Run as child with config file */
160 run_as_child = 1;
161 fg = -1;
a41f09e2 162
ef416fc2 163 case 'c' : /* Configuration file */
164 i ++;
165 if (i >= argc)
a4d04587 166 {
167 _cupsLangPuts(stderr, _("cupsd: Expected config filename "
0837b7e8 168 "after \"-c\" option."));
a4d04587 169 usage(1);
170 }
ef416fc2 171
172 if (argv[i][0] == '/')
173 {
174 /*
175 * Absolute directory...
176 */
177
178 cupsdSetString(&ConfigurationFile, argv[i]);
179 }
180 else
181 {
182 /*
183 * Relative directory...
184 */
185
09ec0018 186 char *current; /* Current directory */
ef416fc2 187
09ec0018 188 /*
189 * Allocate a buffer for the current working directory to
190 * reduce run-time stack usage; this approximates the
191 * behavior of some implementations of getcwd() when they
192 * are passed a NULL pointer.
193 */
194
91c84a35
MS
195 if ((current = malloc(1024)) == NULL)
196 {
197 _cupsLangPuts(stderr,
0837b7e8 198 _("cupsd: Unable to get current directory."));
91c84a35
MS
199 return (1);
200 }
201
202 if (!getcwd(current, 1024))
203 {
204 _cupsLangPuts(stderr,
0837b7e8 205 _("cupsd: Unable to get current directory."));
91c84a35
MS
206 free(current);
207 return (1);
208 }
09ec0018 209
ef416fc2 210 cupsdSetStringf(&ConfigurationFile, "%s/%s", current, argv[i]);
09ec0018 211 free(current);
ef416fc2 212 }
213 break;
214
215 case 'f' : /* Run in foreground... */
216 fg = 1;
217 break;
218
bd7854cb 219 case 'F' : /* Run in foreground, but disconnect from terminal... */
ef416fc2 220 fg = -1;
221 break;
222
a4d04587 223 case 'h' : /* Show usage/help */
224 usage(0);
225 break;
226
227 case 'l' : /* Started by launchd... */
228#ifdef HAVE_LAUNCHD
4400e98d 229 Launchd = 1;
a4d04587 230 fg = 1;
231#else
232 _cupsLangPuts(stderr, _("cupsd: launchd(8) support not compiled "
0837b7e8 233 "in, running in normal mode."));
a4d04587 234 fg = 0;
235#endif /* HAVE_LAUNCHD */
236 break;
237
a74454a7 238 case 'p' : /* Stop immediately for profiling */
5a662dc0
MS
239 fputs("cupsd: -p (startup profiling) is for internal testing "
240 "use only!\n", stderr);
a74454a7 241 stop_scheduler = 1;
242 fg = 1;
243 break;
244
1340db2d 245 case 'P' : /* Disable security profiles */
5a662dc0
MS
246 fputs("cupsd: -P (disable security profiles) is for internal "
247 "testing use only!\n", stderr);
1340db2d
MS
248 UseProfiles = 0;
249 break;
250
c41769ff
MS
251 case 's' : /* Set cups-files.conf location */
252 i ++;
253 if (i >= argc)
254 {
255 _cupsLangPuts(stderr, _("cupsd: Expected cups-files.conf "
256 "filename after \"-s\" option."));
257 usage(1);
258 }
259
260 if (argv[i][0] != '/')
261 {
262 /*
263 * Relative filename not allowed...
264 */
265
266 _cupsLangPuts(stderr, _("cupsd: Relative cups-files.conf "
267 "filename not allowed."));
268 usage(1);
269 }
270
271 cupsdSetString(&CupsFilesFile, argv[i]);
272 break;
273
68b10830
MS
274#ifdef __APPLE__
275 case 'S' : /* Disable system management functions */
5a662dc0
MS
276 fputs("cupsd: -S (disable system management) for internal "
277 "testing use only!\n", stderr);
68b10830
MS
278 use_sysman = 0;
279 break;
280#endif /* __APPLE__ */
281
2e4ff8af
MS
282 case 't' : /* Test the cupsd.conf file... */
283 TestConfigFile = 1;
284 fg = 1;
285 break;
286
ef416fc2 287 default : /* Unknown option */
a4d04587 288 _cupsLangPrintf(stderr, _("cupsd: Unknown option \"%c\" - "
0837b7e8 289 "aborting."), *opt);
a4d04587 290 usage(1);
ef416fc2 291 break;
292 }
293 else
294 {
0837b7e8 295 _cupsLangPrintf(stderr, _("cupsd: Unknown argument \"%s\" - aborting."),
a4d04587 296 argv[i]);
297 usage(1);
ef416fc2 298 }
299
300 if (!ConfigurationFile)
301 cupsdSetString(&ConfigurationFile, CUPS_SERVERROOT "/cupsd.conf");
302
cb7f98ee
MS
303 if (!CupsFilesFile)
304 {
305 char *filename, /* Copy of cupsd.conf filename */
306 *slash; /* Final slash in cupsd.conf filename */
307 size_t len; /* Size of buffer */
308
309 len = strlen(ConfigurationFile) + 15;
310 if ((filename = malloc(len)) == NULL)
311 {
312 _cupsLangPrintf(stderr,
313 _("cupsd: Unable to get path to "
314 "cups-files.conf file."));
315 return (1);
316 }
317
318 strlcpy(filename, ConfigurationFile, len);
319 if ((slash = strrchr(filename, '/')) == NULL)
320 {
321 _cupsLangPrintf(stderr,
322 _("cupsd: Unable to get path to "
323 "cups-files.conf file."));
324 return (1);
325 }
326
7e86f2f6 327 strlcpy(slash, "/cups-files.conf", len - (size_t)(slash - filename));
cb7f98ee
MS
328 cupsdSetString(&CupsFilesFile, filename);
329 free(filename);
330 }
331
ef416fc2 332 /*
333 * If the user hasn't specified "-f", run in the background...
334 */
335
336 if (!fg)
337 {
338 /*
339 * Setup signal handlers for the parent...
340 */
341
342#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
343 sigset(SIGUSR1, parent_handler);
344 sigset(SIGCHLD, parent_handler);
345
346 sigset(SIGHUP, SIG_IGN);
347#elif defined(HAVE_SIGACTION)
348 memset(&action, 0, sizeof(action));
349 sigemptyset(&action.sa_mask);
350 sigaddset(&action.sa_mask, SIGUSR1);
351 action.sa_handler = parent_handler;
352 sigaction(SIGUSR1, &action, NULL);
353 sigaction(SIGCHLD, &action, NULL);
354
355 sigemptyset(&action.sa_mask);
356 action.sa_handler = SIG_IGN;
357 sigaction(SIGHUP, &action, NULL);
358#else
359 signal(SIGUSR1, parent_handler);
360 signal(SIGCLD, parent_handler);
361
362 signal(SIGHUP, SIG_IGN);
363#endif /* HAVE_SIGSET */
364
365 if (fork() > 0)
366 {
367 /*
368 * OK, wait for the child to startup and send us SIGUSR1 or to crash
369 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
370 * might be sent by the init script to restart the scheduler...
371 */
372
373 for (; parent_signal == 0;)
374 sleep(1);
375
376 if (parent_signal == SIGUSR1)
377 return (0);
378
379 if (wait(&i) < 0)
380 {
381 perror("cupsd");
382 return (1);
383 }
384 else if (WIFEXITED(i))
385 {
4d301e69 386 fprintf(stderr, "cupsd: Child exited with status %d\n",
bd7854cb 387 WEXITSTATUS(i));
ef416fc2 388 return (2);
389 }
390 else
391 {
4d301e69 392 fprintf(stderr, "cupsd: Child exited on signal %d\n", WTERMSIG(i));
ef416fc2 393 return (3);
394 }
395 }
a41f09e2 396
3dd9c340 397#if defined(__OpenBSD__) && OpenBSD < 201211
68b10830
MS
398 /*
399 * Call _thread_sys_closefrom() so the child process doesn't reset the
400 * parent's file descriptors to be blocking. This is a workaround for a
3dd9c340 401 * limitation of userland libpthread on older versions of OpenBSD.
68b10830 402 */
ef55b745 403
68b10830 404 _thread_sys_closefrom(0);
3dd9c340 405#endif /* __OpenBSD__ && OpenBSD < 201211 */
68b10830 406
a41f09e2 407 /*
68b10830
MS
408 * Since CoreFoundation and DBUS both create fork-unsafe data on execution of
409 * a program, and since this kind of really unfriendly behavior seems to be
410 * more common these days in system libraries, we need to re-execute the
411 * background cupsd with the "-C" option to avoid problems. Unfortunately,
412 * we also have to assume that argv[0] contains the name of the cupsd
413 * executable - there is no portable way to get the real pathname...
a41f09e2
MS
414 */
415
416 execlp(argv[0], argv[0], "-C", ConfigurationFile, (char *)0);
417 exit(errno);
ef416fc2 418 }
419
420 if (fg < 1)
421 {
422 /*
423 * Make sure we aren't tying up any filesystems...
424 */
425
426 chdir("/");
427
428#ifndef DEBUG
429 /*
430 * Disable core dumps...
431 */
432
433 getrlimit(RLIMIT_CORE, &limit);
434 limit.rlim_cur = 0;
435 setrlimit(RLIMIT_CORE, &limit);
436
437 /*
438 * Disconnect from the controlling terminal...
439 */
440
441 setsid();
442
443 /*
444 * Close all open files...
445 */
446
447 getrlimit(RLIMIT_NOFILE, &limit);
448
b94498cf 449 for (i = 0; i < limit.rlim_cur && i < 1024; i ++)
ef416fc2 450 close(i);
a4924f6c
MS
451
452 /*
453 * Redirect stdin/out/err to /dev/null...
454 */
455
68b10830
MS
456 if ((i = open("/dev/null", O_RDONLY)) != 0)
457 {
458 dup2(i, 0);
459 close(i);
460 }
461
462 if ((i = open("/dev/null", O_WRONLY)) != 1)
463 {
464 dup2(i, 1);
465 close(i);
466 }
467
468 if ((i = open("/dev/null", O_WRONLY)) != 2)
469 {
470 dup2(i, 2);
471 close(i);
472 }
ef416fc2 473#endif /* DEBUG */
474 }
475
476 /*
477 * Set the timezone info...
478 */
479
480 tzset();
481
482#ifdef LC_TIME
483 setlocale(LC_TIME, "");
484#endif /* LC_TIME */
485
486 /*
487 * Set the maximum number of files...
488 */
489
490 getrlimit(RLIMIT_NOFILE, &limit);
491
f7deaa1a 492#if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
f7faf1f5 493 if (limit.rlim_max > FD_SETSIZE)
494 MaxFDs = FD_SETSIZE;
ef416fc2 495 else
f7deaa1a 496#endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
497#ifdef RLIM_INFINITY
498 if (limit.rlim_max == RLIM_INFINITY)
499 MaxFDs = 16384;
500 else
501#endif /* RLIM_INFINITY */
ef416fc2 502 MaxFDs = limit.rlim_max;
503
7e86f2f6 504 limit.rlim_cur = (rlim_t)MaxFDs;
ef416fc2 505
506 setrlimit(RLIMIT_NOFILE, &limit);
507
f7deaa1a 508 cupsdStartSelect();
ef416fc2 509
510 /*
511 * Read configuration...
512 */
513
514 if (!cupsdReadConfiguration())
ef416fc2 515 return (1);
2e4ff8af
MS
516 else if (TestConfigFile)
517 {
cb7f98ee
MS
518 printf("\"%s\" is OK.\n", CupsFilesFile);
519 printf("\"%s\" is OK.\n", ConfigurationFile);
2e4ff8af
MS
520 return (0);
521 }
ef416fc2 522
ba55dc12
MS
523 /*
524 * Clean out old temp files and printer cache data.
525 */
cc0d019f 526
ba55dc12 527 if (!strncmp(TempDir, RequestRoot, strlen(RequestRoot)))
321d8d57 528 cupsdCleanFiles(TempDir, NULL);
cc0d019f 529
321d8d57 530 cupsdCleanFiles(CacheDir, "*.ipp");
cc0d019f 531
a4d04587 532#if HAVE_LAUNCHD
4400e98d 533 if (Launchd)
a4d04587 534 {
535 /*
b94498cf 536 * If we were started by launchd get the listen sockets file descriptors...
f7deaa1a 537 */
a4d04587 538
539 launchd_checkin();
e4572d57 540 launchd_checkout();
a4d04587 541 }
542#endif /* HAVE_LAUNCHD */
543
544 /*
545 * Startup the server...
546 */
547
6d2f911b
MS
548 httpInitialize();
549
a4d04587 550 cupsdStartServer();
551
ef416fc2 552 /*
553 * Catch hangup and child signals and ignore broken pipes...
554 */
555
556#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
e1d6a774 557 sigset(SIGCHLD, sigchld_handler);
4744bd90 558 sigset(SIGHUP, sighup_handler);
ef416fc2 559 sigset(SIGPIPE, SIG_IGN);
560 sigset(SIGTERM, sigterm_handler);
561#elif defined(HAVE_SIGACTION)
562 memset(&action, 0, sizeof(action));
563
e1d6a774 564 sigemptyset(&action.sa_mask);
565 sigaddset(&action.sa_mask, SIGTERM);
566 sigaddset(&action.sa_mask, SIGCHLD);
567 action.sa_handler = sigchld_handler;
568 sigaction(SIGCHLD, &action, NULL);
569
ef416fc2 570 sigemptyset(&action.sa_mask);
571 sigaddset(&action.sa_mask, SIGHUP);
4744bd90 572 action.sa_handler = sighup_handler;
ef416fc2 573 sigaction(SIGHUP, &action, NULL);
574
575 sigemptyset(&action.sa_mask);
576 action.sa_handler = SIG_IGN;
577 sigaction(SIGPIPE, &action, NULL);
578
579 sigemptyset(&action.sa_mask);
580 sigaddset(&action.sa_mask, SIGTERM);
581 sigaddset(&action.sa_mask, SIGCHLD);
582 action.sa_handler = sigterm_handler;
583 sigaction(SIGTERM, &action, NULL);
584#else
e1d6a774 585 signal(SIGCLD, sigchld_handler); /* No, SIGCLD isn't a typo... */
4744bd90 586 signal(SIGHUP, sighup_handler);
ef416fc2 587 signal(SIGPIPE, SIG_IGN);
588 signal(SIGTERM, sigterm_handler);
589#endif /* HAVE_SIGSET */
590
ef416fc2 591 /*
592 * Initialize authentication certificates...
593 */
594
595 cupsdInitCerts();
596
597 /*
598 * If we are running in the background, signal the parent process that
599 * we are up and running...
600 */
601
a41f09e2 602 if (!fg || run_as_child)
ef416fc2 603 {
604 /*
605 * Send a signal to the parent process, but only if the parent is
606 * not PID 1 (init). This avoids accidentally shutting down the
607 * system on OpenBSD if you CTRL-C the server before it is up...
608 */
609
610 i = getppid(); /* Save parent PID to avoid race condition */
611
612 if (i != 1)
613 kill(i, SIGUSR1);
614 }
615
e1d6a774 616#ifdef __APPLE__
09ec0018 617 /*
618 * Start power management framework...
619 */
620
1340db2d
MS
621 if (use_sysman)
622 cupsdStartSystemMonitor();
e1d6a774 623#endif /* __APPLE__ */
ef416fc2 624
49d87452
MS
625 /*
626 * Send server-started event...
627 */
628
629#ifdef HAVE_LAUNCHD
630 if (Launchd)
631 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL,
632 "Scheduler started via launchd.");
633 else
634#endif /* HAVE_LAUNCHD */
635 if (fg)
636 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL,
637 "Scheduler started in foreground.");
638 else
639 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL,
640 "Scheduler started in background.");
641
ef416fc2 642 /*
643 * Start any pending print jobs...
644 */
645
646 cupsdCheckJobs();
647
648 /*
649 * Loop forever...
650 */
651
50fe7201 652 current_time = time(NULL);
50fe7201
MS
653 event_time = current_time;
654 expire_time = current_time;
ef416fc2 655 fds = 1;
5bd77a73 656 report_time = 0;
50fe7201 657 senddoc_time = current_time;
ef416fc2 658
659 while (!stop_scheduler)
660 {
ef416fc2 661 /*
662 * Check if there are dead children to handle...
663 */
664
665 if (dead_children)
666 process_children();
667
668 /*
669 * Check if we need to load the server configuration file...
670 */
671
672 if (NeedReload)
673 {
674 /*
675 * Close any idle clients...
676 */
677
bd7854cb 678 if (cupsArrayCount(Clients) > 0)
ef416fc2 679 {
bd7854cb 680 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
681 con;
682 con = (cupsd_client_t *)cupsArrayNext(Clients))
996acce8 683 if (httpGetState(con->http) == HTTP_WAITING)
ef416fc2 684 cupsdCloseClient(con);
ef416fc2 685 else
996acce8 686 con->http->keep_alive = HTTP_KEEPALIVE_OFF;
ef416fc2 687
688 cupsdPauseListening();
689 }
690
ef416fc2 691 /*
692 * Restart if all clients are closed and all jobs finished, or
693 * if the reload timeout has elapsed...
694 */
695
bd7854cb 696 if ((cupsArrayCount(Clients) == 0 &&
238c3832 697 (cupsArrayCount(PrintingJobs) == 0 || NeedReload != RELOAD_ALL)) ||
ef416fc2 698 (time(NULL) - ReloadTime) >= ReloadTimeout)
699 {
a4d04587 700 /*
701 * Shutdown the server...
702 */
703
7cf5915e
MS
704 DoingShutdown = 1;
705
a4d04587 706 cupsdStopServer();
707
708 /*
709 * Read configuration...
710 */
711
ef416fc2 712 if (!cupsdReadConfiguration())
713 {
714 syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
715 ConfigurationFile);
716 break;
717 }
a4d04587 718
719#if HAVE_LAUNCHD
4400e98d 720 if (Launchd)
a4d04587 721 {
b94498cf 722 /*
5a662dc0
MS
723 * If we were started by launchd, get the listen socket file
724 * descriptors...
b94498cf 725 */
726
a4d04587 727 launchd_checkin();
e4572d57 728 launchd_checkout();
a4d04587 729 }
730#endif /* HAVE_LAUNCHD */
731
732 /*
733 * Startup the server...
734 */
735
7cf5915e
MS
736 DoingShutdown = 0;
737
a4d04587 738 cupsdStartServer();
49d87452
MS
739
740 /*
741 * Send a server-restarted event...
742 */
743
744 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED, NULL, NULL,
745 "Scheduler restarted.");
ef416fc2 746 }
747 }
748
749 /*
f7deaa1a 750 * Check for available input or ready output. If cupsdDoSelect()
751 * returns 0 or -1, something bad happened and we should exit
752 * immediately.
ef416fc2 753 *
754 * Note that we at least have one listening socket open at all
755 * times.
756 */
757
50fe7201
MS
758 if ((timeout = select_timeout(fds)) > 1 && LastEvent)
759 timeout = 1;
ef416fc2 760
a4d04587 761#if HAVE_LAUNCHD
762 /*
763 * If no other work is scheduled and we're being controlled by
411affcf 764 * launchd then timeout after 'LaunchdTimeout' seconds of
a4d04587 765 * inactivity...
766 */
767
a2326b5b 768 if (timeout == 86400 && Launchd && LaunchdTimeout &&
bc44d920 769 !cupsArrayCount(ActiveJobs) &&
a2326b5b 770 (!Browsing || !BrowseLocalProtocols || !cupsArrayCount(Printers)))
a4d04587 771 {
f7deaa1a 772 timeout = LaunchdTimeout;
a4d04587 773 launchd_idle_exit = 1;
774 }
775 else
776 launchd_idle_exit = 0;
777#endif /* HAVE_LAUNCHD */
778
f7deaa1a 779 if ((fds = cupsdDoSelect(timeout)) < 0)
ef416fc2 780 {
ef416fc2 781 /*
782 * Got an error from select!
783 */
784
37e7e6e0 785#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
f7deaa1a 786 cupsd_printer_t *p; /* Current printer */
37e7e6e0 787#endif /* HAVE_DNSSD || HAVE_AVAHI */
f7deaa1a 788
789
790 if (errno == EINTR) /* Just interrupted by a signal */
ef416fc2 791 continue;
792
793 /*
794 * Log all sorts of debug info to help track down the problem.
795 */
796
f7deaa1a 797 cupsdLogMessage(CUPSD_LOG_EMERG, "cupsdDoSelect() failed - %s!",
ef416fc2 798 strerror(errno));
799
bd7854cb 800 for (i = 0, con = (cupsd_client_t *)cupsArrayFirst(Clients);
801 con;
802 i ++, con = (cupsd_client_t *)cupsArrayNext(Clients))
ef416fc2 803 cupsdLogMessage(CUPSD_LOG_EMERG,
804 "Clients[%d] = %d, file = %d, state = %d",
996acce8 805 i, con->number, con->file, httpGetState(con->http));
ef416fc2 806
bd7854cb 807 for (i = 0, lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
808 lis;
809 i ++, lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
ef416fc2 810 cupsdLogMessage(CUPSD_LOG_EMERG, "Listeners[%d] = %d", i, lis->fd);
811
923edb68 812 cupsdLogMessage(CUPSD_LOG_EMERG, "CGIPipes[0] = %d", CGIPipes[0]);
813
09ec0018 814#ifdef __APPLE__
815 cupsdLogMessage(CUPSD_LOG_EMERG, "SysEventPipes[0] = %d",
816 SysEventPipes[0]);
817#endif /* __APPLE__ */
818
ef416fc2 819 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
820 job;
821 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
822 cupsdLogMessage(CUPSD_LOG_EMERG, "Jobs[%d] = %d < [%d %d] > [%d %d]",
823 job->id,
824 job->status_buffer ? job->status_buffer->fd : -1,
825 job->print_pipes[0], job->print_pipes[1],
826 job->back_pipes[0], job->back_pipes[1]);
f7deaa1a 827
37e7e6e0 828#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
f7deaa1a 829 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
830 p;
831 p = (cupsd_printer_t *)cupsArrayNext(Printers))
7a14d768
MS
832 cupsdLogMessage(CUPSD_LOG_EMERG, "printer[%s] reg_name=\"%s\"", p->name,
833 p->reg_name ? p->reg_name : "(null)");
37e7e6e0 834#endif /* HAVE_DNSSD || HAVE_AVAHI */
f7deaa1a 835
ef416fc2 836 break;
837 }
838
839 current_time = time(NULL);
840
3dfe78b3
MS
841 /*
842 * Write dirty config/state files...
843 */
844
845 if (DirtyCleanTime && current_time >= DirtyCleanTime)
3dfe78b3 846 cupsdCleanDirty();
3dfe78b3 847
e6013cfa
MS
848#ifdef __APPLE__
849 /*
850 * If we are going to sleep and still have pending jobs, stop them after
851 * a period of time...
852 */
853
854 if (SleepJobs > 0 && current_time >= SleepJobs &&
855 cupsArrayCount(PrintingJobs) > 0)
856 {
857 SleepJobs = 0;
e60ec91f 858 cupsdStopAllJobs(CUPSD_JOB_DEFAULT, 5);
e6013cfa
MS
859 }
860#endif /* __APPLE__ */
861
a4924f6c
MS
862#ifndef __APPLE__
863 /*
864 * Update the network interfaces once a minute...
865 */
866
867 if ((current_time - netif_time) >= 60)
868 {
869 netif_time = current_time;
870 NetIFUpdate = 1;
871 }
872#endif /* !__APPLE__ */
873
a4d04587 874#if HAVE_LAUNCHD
875 /*
411affcf 876 * If no other work was scheduled and we're being controlled by launchd
a4d04587 877 * then timeout after 'LaunchdTimeout' seconds of inactivity...
878 */
879
880 if (!fds && launchd_idle_exit)
881 {
882 cupsdLogMessage(CUPSD_LOG_INFO,
883 "Printer sharing is off and there are no jobs pending, "
884 "will restart on demand.");
885 stop_scheduler = 1;
886 break;
887 }
888#endif /* HAVE_LAUNCHD */
889
76cd9e37
MS
890 /*
891 * Resume listening for new connections as needed...
892 */
893
894 if (ListeningPaused && ListeningPaused <= current_time &&
895 cupsArrayCount(Clients) < MaxClients)
896 cupsdResumeListening();
897
ef416fc2 898 /*
bd7854cb 899 * Expire subscriptions and unload completed jobs as needed...
ef416fc2 900 */
901
bd7854cb 902 if (current_time > expire_time)
ef416fc2 903 {
bd7854cb 904 if (cupsArrayCount(Subscriptions) > 0)
905 cupsdExpireSubscriptions(NULL, NULL);
906
907 cupsdUnloadCompletedJobs();
ef416fc2 908
909 expire_time = current_time;
910 }
911
07ed0e9a 912#ifndef HAVE_AUTHORIZATION_H
ef416fc2 913 /*
f7deaa1a 914 * Update the root certificate once every 5 minutes if we have client
915 * connections...
ef416fc2 916 */
917
f7deaa1a 918 if ((current_time - RootCertTime) >= RootCertDuration && RootCertDuration &&
919 !RunUser && cupsArrayCount(Clients))
920 {
921 /*
922 * Update the root certificate...
923 */
924
925 cupsdDeleteCert(0);
0fa6c7fa 926 cupsdAddCert(0, "root", cupsdDefaultAuthType());
f7deaa1a 927 }
07ed0e9a 928#endif /* !HAVE_AUTHORIZATION_H */
ef416fc2 929
930 /*
931 * Check for new data on the client sockets...
932 */
933
bd7854cb 934 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
935 con;
936 con = (cupsd_client_t *)cupsArrayNext(Clients))
ef416fc2 937 {
938 /*
f7deaa1a 939 * Process pending data in the input buffer...
ef416fc2 940 */
941
996acce8
MS
942 // TODO: Use httpGetReady()
943 if (con->http->used)
ef416fc2 944 {
f7deaa1a 945 cupsdReadClient(con);
946 continue;
ef416fc2 947 }
948
949 /*
950 * Check the activity and close old clients...
951 */
952
996acce8 953 // TODO: Use httpGetActivity()
ef416fc2 954 activity = current_time - Timeout;
996acce8 955 if (con->http->activity < activity && !con->pipe_pid)
ef416fc2 956 {
957 cupsdLogMessage(CUPSD_LOG_DEBUG,
958 "Closing client %d after %d seconds of inactivity...",
996acce8 959 con->number, Timeout);
ef416fc2 960
961 cupsdCloseClient(con);
ef416fc2 962 continue;
963 }
964 }
965
966 /*
967 * Update any pending multi-file documents...
968 */
969
970 if ((current_time - senddoc_time) >= 10)
971 {
972 cupsdCheckJobs();
973 senddoc_time = current_time;
974 }
975
82cc1f9a
MS
976 /*
977 * Clean job history...
978 */
979
980 if (JobHistoryUpdate && current_time >= JobHistoryUpdate)
981 cupsdCleanJobs();
982
ef416fc2 983 /*
5bd77a73 984 * Log statistics at most once a minute when in debug mode...
ef416fc2 985 */
986
5bd77a73 987 if ((current_time - report_time) >= 60 && LogLevel >= CUPSD_LOG_DEBUG)
ef416fc2 988 {
5bd77a73
MS
989 size_t string_count, /* String count */
990 alloc_bytes, /* Allocated string bytes */
991 total_bytes; /* Total string bytes */
4400e98d 992#ifdef HAVE_MALLINFO
5bd77a73 993 struct mallinfo mem; /* Malloc information */
ef416fc2 994
995
996 mem = mallinfo();
5bd77a73
MS
997 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-arena=%lu", mem.arena);
998 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-used=%lu",
999 mem.usmblks + mem.uordblks);
1000 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-free=%lu",
ef416fc2 1001 mem.fsmblks + mem.fordblks);
4400e98d 1002#endif /* HAVE_MALLINFO */
1003
5bd77a73
MS
1004 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: clients=%d",
1005 cupsArrayCount(Clients));
1006 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs=%d",
1007 cupsArrayCount(Jobs));
1008 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs-active=%d",
1009 cupsArrayCount(ActiveJobs));
1010 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: printers=%d",
1011 cupsArrayCount(Printers));
5bd77a73 1012
757d2cad 1013 string_count = _cupsStrStatistics(&alloc_bytes, &total_bytes);
5bd77a73
MS
1014 cupsdLogMessage(CUPSD_LOG_DEBUG,
1015 "Report: stringpool-string-count=" CUPS_LLFMT,
1016 CUPS_LLCAST string_count);
1017 cupsdLogMessage(CUPSD_LOG_DEBUG,
1018 "Report: stringpool-alloc-bytes=" CUPS_LLFMT,
1019 CUPS_LLCAST alloc_bytes);
1020 cupsdLogMessage(CUPSD_LOG_DEBUG,
1021 "Report: stringpool-total-bytes=" CUPS_LLFMT,
4400e98d 1022 CUPS_LLCAST total_bytes);
1023
5bd77a73 1024 report_time = current_time;
ef416fc2 1025 }
ef416fc2 1026
fa73b229 1027 /*
1028 * Handle OS-specific event notification for any events that have
1029 * accumulated. Don't send these more than once a second...
1030 */
1031
50fe7201 1032 if (LastEvent && (current_time - event_time) >= 1)
fa73b229 1033 {
1034#ifdef HAVE_NOTIFY_POST
a41f09e2
MS
1035 if (LastEvent & (CUPSD_EVENT_PRINTER_ADDED |
1036 CUPSD_EVENT_PRINTER_DELETED |
1037 CUPSD_EVENT_PRINTER_MODIFIED))
fa73b229 1038 {
e00b005a 1039 cupsdLogMessage(CUPSD_LOG_DEBUG2,
fa73b229 1040 "notify_post(\"com.apple.printerListChange\")");
1041 notify_post("com.apple.printerListChange");
1042 }
1043
1044 if (LastEvent & CUPSD_EVENT_PRINTER_STATE_CHANGED)
1045 {
e00b005a 1046 cupsdLogMessage(CUPSD_LOG_DEBUG2,
fa73b229 1047 "notify_post(\"com.apple.printerHistoryChange\")");
1048 notify_post("com.apple.printerHistoryChange");
1049 }
1050
1051 if (LastEvent & (CUPSD_EVENT_JOB_STATE_CHANGED |
1052 CUPSD_EVENT_JOB_CONFIG_CHANGED |
1053 CUPSD_EVENT_JOB_PROGRESS))
1054 {
e00b005a 1055 cupsdLogMessage(CUPSD_LOG_DEBUG2,
fa73b229 1056 "notify_post(\"com.apple.jobChange\")");
1057 notify_post("com.apple.jobChange");
1058 }
1059#endif /* HAVE_NOTIFY_POST */
1060
1061 /*
e53920b9 1062 * Reset the accumulated events...
fa73b229 1063 */
1064
50fe7201
MS
1065 LastEvent = CUPSD_EVENT_NONE;
1066 event_time = current_time;
fa73b229 1067 }
ef416fc2 1068 }
1069
1070 /*
1071 * Log a message based on what happened...
1072 */
1073
1074 if (stop_scheduler)
49d87452 1075 {
ef416fc2 1076 cupsdLogMessage(CUPSD_LOG_INFO, "Scheduler shutting down normally.");
49d87452
MS
1077 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
1078 "Scheduler shutting down normally.");
1079 }
ef416fc2 1080 else
49d87452 1081 {
ef416fc2 1082 cupsdLogMessage(CUPSD_LOG_ERROR,
1083 "Scheduler shutting down due to program error.");
49d87452
MS
1084 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
1085 "Scheduler shutting down due to program error.");
1086 }
ef416fc2 1087
1088 /*
7ff4fea9 1089 * Close all network clients...
ef416fc2 1090 */
1091
7cf5915e
MS
1092 DoingShutdown = 1;
1093
ef416fc2 1094 cupsdStopServer();
1095
7ff4fea9
MS
1096#ifdef HAVE_LAUNCHD
1097 /*
1098 * Update the launchd KeepAlive file as needed...
1099 */
1100
1101 if (Launchd)
1102 launchd_checkout();
1103#endif /* HAVE_LAUNCHD */
1104
1105 /*
1106 * Stop all jobs...
1107 */
1108
bd7854cb 1109 cupsdFreeAllJobs();
ef416fc2 1110
e1d6a774 1111#ifdef __APPLE__
7ff4fea9
MS
1112 /*
1113 * Stop monitoring system event monitoring...
1114 */
1115
1340db2d
MS
1116 if (use_sysman)
1117 cupsdStopSystemMonitor();
e1d6a774 1118#endif /* __APPLE__ */
09ec0018 1119
f7deaa1a 1120 cupsdStopSelect();
ef416fc2 1121
1122 return (!stop_scheduler);
1123}
1124
1125
10d09e33
MS
1126/*
1127 * 'cupsdAddString()' - Copy and add a string to an array.
1128 */
1129
1130int /* O - 1 on success, 0 on failure */
1131cupsdAddString(cups_array_t **a, /* IO - String array */
1132 const char *s) /* I - String to copy and add */
1133{
1134 if (!*a)
1135 *a = cupsArrayNew3((cups_array_func_t)strcmp, NULL,
1136 (cups_ahash_func_t)NULL, 0,
1137 (cups_acopy_func_t)_cupsStrAlloc,
1138 (cups_afree_func_t)_cupsStrFree);
1139
1140 return (cupsArrayAdd(*a, (char *)s));
1141}
1142
1143
d7871c8c
MS
1144/*
1145 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1146 */
1147
1148void
1149cupsdCheckProcess(void)
1150{
1151 /*
1152 * Flag that we have dead children...
1153 */
1154
1155 dead_children = 1;
1156}
1157
1158
10d09e33
MS
1159/*
1160 * 'cupsdClearString()' - Clear a string.
1161 */
1162
1163void
1164cupsdClearString(char **s) /* O - String value */
1165{
1166 if (s && *s)
1167 {
1168 _cupsStrFree(*s);
1169 *s = NULL;
1170 }
1171}
1172
1173
10d09e33
MS
1174/*
1175 * 'cupsdFreeStrings()' - Free an array of strings.
1176 */
1177
1178void
1179cupsdFreeStrings(cups_array_t **a) /* IO - String array */
1180{
1181 if (*a)
1182 {
1183 cupsArrayDelete(*a);
1184 *a = NULL;
1185 }
1186}
1187
1188
1189/*
1190 * 'cupsdHoldSignals()' - Hold child and termination signals.
1191 */
1192
1193void
1194cupsdHoldSignals(void)
1195{
1196#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1197 sigset_t newmask; /* New POSIX signal mask */
1198#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1199
1200
1201 holdcount ++;
1202 if (holdcount > 1)
1203 return;
1204
1205#ifdef HAVE_SIGSET
1206 sighold(SIGTERM);
1207 sighold(SIGCHLD);
1208#elif defined(HAVE_SIGACTION)
1209 sigemptyset(&newmask);
1210 sigaddset(&newmask, SIGTERM);
1211 sigaddset(&newmask, SIGCHLD);
1212 sigprocmask(SIG_BLOCK, &newmask, &holdmask);
1213#endif /* HAVE_SIGSET */
1214}
1215
1216
ef416fc2 1217/*
1218 * 'cupsdReleaseSignals()' - Release signals for delivery.
1219 */
1220
1221void
1222cupsdReleaseSignals(void)
1223{
1224 holdcount --;
1225 if (holdcount > 0)
1226 return;
1227
1228#ifdef HAVE_SIGSET
1229 sigrelse(SIGTERM);
1230 sigrelse(SIGCHLD);
1231#elif defined(HAVE_SIGACTION)
1232 sigprocmask(SIG_SETMASK, &holdmask, NULL);
1233#endif /* HAVE_SIGSET */
1234}
1235
1236
1237/*
1238 * 'cupsdSetString()' - Set a string value.
1239 */
1240
1241void
1242cupsdSetString(char **s, /* O - New string */
1243 const char *v) /* I - String value */
1244{
1245 if (!s || *s == v)
1246 return;
1247
1248 if (*s)
e53920b9 1249 _cupsStrFree(*s);
ef416fc2 1250
1251 if (v)
e53920b9 1252 *s = _cupsStrAlloc(v);
ef416fc2 1253 else
1254 *s = NULL;
1255}
1256
1257
1258/*
1259 * 'cupsdSetStringf()' - Set a formatted string value.
1260 */
1261
1262void
1263cupsdSetStringf(char **s, /* O - New string */
1264 const char *f, /* I - Printf-style format string */
1265 ...) /* I - Additional args as needed */
1266{
94436c5a 1267 char v[65536 + 64]; /* Formatting string value */
ef416fc2 1268 va_list ap; /* Argument pointer */
1269 char *olds; /* Old string */
1270
1271
1272 if (!s)
1273 return;
1274
1275 olds = *s;
1276
1277 if (f)
1278 {
1279 va_start(ap, f);
1280 vsnprintf(v, sizeof(v), f, ap);
1281 va_end(ap);
1282
e53920b9 1283 *s = _cupsStrAlloc(v);
ef416fc2 1284 }
1285 else
1286 *s = NULL;
1287
1288 if (olds)
e53920b9 1289 _cupsStrFree(olds);
ef416fc2 1290}
1291
1292
a4d04587 1293#ifdef HAVE_LAUNCHD
1294/*
1295 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1296 */
1297
1298static void
1299launchd_checkin(void)
1300{
06d4e77b 1301 size_t i, /* Looping var */
f8b3a85b 1302 count; /* Number of listeners */
a4d04587 1303 launch_data_t ld_msg, /* Launch data message */
1304 ld_resp, /* Launch data response */
1305 ld_array, /* Launch data array */
1306 ld_sockets, /* Launch data sockets dictionary */
a4d04587 1307 tmp; /* Launch data */
1308 cupsd_listener_t *lis; /* Listeners array */
1309 http_addr_t addr; /* Address variable */
1310 socklen_t addrlen; /* Length of address */
f7deaa1a 1311 int fd; /* File descriptor */
1312 char s[256]; /* String addresss */
a4d04587 1313
1314
1315 cupsdLogMessage(CUPSD_LOG_DEBUG, "launchd_checkin: pid=%d", (int)getpid());
1316
1317 /*
1318 * Check-in with launchd...
1319 */
1320
1321 ld_msg = launch_data_new_string(LAUNCH_KEY_CHECKIN);
1322 if ((ld_resp = launch_msg(ld_msg)) == NULL)
1323 {
bd7854cb 1324 cupsdLogMessage(CUPSD_LOG_ERROR,
a4d04587 1325 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1326 "\") IPC failure");
1327 exit(EXIT_FAILURE);
749b1e90 1328 return; /* anti-compiler-warning */
a4d04587 1329 }
bd7854cb 1330
a4d04587 1331 if (launch_data_get_type(ld_resp) == LAUNCH_DATA_ERRNO)
1332 {
1333 errno = launch_data_get_errno(ld_resp);
1334 cupsdLogMessage(CUPSD_LOG_ERROR, "launchd_checkin: Check-in failed: %s",
1335 strerror(errno));
1336 exit(EXIT_FAILURE);
749b1e90 1337 return; /* anti-compiler-warning */
a4d04587 1338 }
1339
a4d04587 1340 /*
1341 * Get the sockets dictionary...
1342 */
1343
749b1e90
MS
1344 if ((ld_sockets = launch_data_dict_lookup(ld_resp, LAUNCH_JOBKEY_SOCKETS))
1345 == NULL)
a4d04587 1346 {
1347 cupsdLogMessage(CUPSD_LOG_ERROR,
1348 "launchd_checkin: No sockets found to answer requests on!");
1349 exit(EXIT_FAILURE);
749b1e90 1350 return; /* anti-compiler-warning */
a4d04587 1351 }
bd7854cb 1352
a4d04587 1353 /*
1354 * Get the array of listener sockets...
1355 */
1356
749b1e90 1357 if ((ld_array = launch_data_dict_lookup(ld_sockets, "Listeners")) == NULL)
a4d04587 1358 {
1359 cupsdLogMessage(CUPSD_LOG_ERROR,
1360 "launchd_checkin: No sockets found to answer requests on!");
1361 exit(EXIT_FAILURE);
749b1e90 1362 return; /* anti-compiler-warning */
a4d04587 1363 }
1364
1365 /*
1366 * Add listening fd(s) to the Listener array...
1367 */
1368
1369 if (launch_data_get_type(ld_array) == LAUNCH_DATA_ARRAY)
1370 {
f7deaa1a 1371 count = launch_data_array_get_count(ld_array);
bd7854cb 1372
1373 for (i = 0; i < count; i ++)
a4d04587 1374 {
1375 /*
f7deaa1a 1376 * Get the launchd file descriptor and address...
a4d04587 1377 */
bd7854cb 1378
749b1e90 1379 if ((tmp = launch_data_array_get_index(ld_array, i)) != NULL)
bd7854cb 1380 {
749b1e90
MS
1381 fd = launch_data_get_fd(tmp);
1382 addrlen = sizeof(addr);
bd7854cb 1383
749b1e90
MS
1384 if (getsockname(fd, (struct sockaddr *)&addr, &addrlen))
1385 {
1386 cupsdLogMessage(CUPSD_LOG_ERROR,
1387 "launchd_checkin: Unable to get local address - %s",
1388 strerror(errno));
1389 continue;
1390 }
bd7854cb 1391
749b1e90
MS
1392 /*
1393 * Try to match the launchd socket address to one of the listeners...
1394 */
f7deaa1a 1395
749b1e90
MS
1396 for (lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
1397 lis;
1398 lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
1399 if (httpAddrEqual(&lis->address, &addr))
1400 break;
a4d04587 1401
749b1e90
MS
1402 /*
1403 * Add a new listener If there's no match...
1404 */
f7deaa1a 1405
749b1e90
MS
1406 if (lis)
1407 {
ef55b745 1408 cupsdLogMessage(CUPSD_LOG_DEBUG,
749b1e90
MS
1409 "launchd_checkin: Matched existing listener %s with fd %d...",
1410 httpAddrString(&(lis->address), s, sizeof(s)), fd);
1411 }
1412 else
1413 {
ef55b745 1414 cupsdLogMessage(CUPSD_LOG_DEBUG,
749b1e90
MS
1415 "launchd_checkin: Adding new listener %s with fd %d...",
1416 httpAddrString(&addr, s, sizeof(s)), fd);
f7deaa1a 1417
749b1e90
MS
1418 if ((lis = calloc(1, sizeof(cupsd_listener_t))) == NULL)
1419 {
1420 cupsdLogMessage(CUPSD_LOG_ERROR,
5a662dc0
MS
1421 "launchd_checkin: Unable to allocate listener - "
1422 "%s.", strerror(errno));
749b1e90
MS
1423 exit(EXIT_FAILURE);
1424 }
f7deaa1a 1425
749b1e90 1426 cupsArrayAdd(Listeners, lis);
bd7854cb 1427
749b1e90
MS
1428 memcpy(&lis->address, &addr, sizeof(lis->address));
1429 }
1430
1431 lis->fd = fd;
f7deaa1a 1432
a4d04587 1433# ifdef HAVE_SSL
a469f8a5 1434 if (httpAddrPort(&(lis->address)) == 443)
749b1e90 1435 lis->encryption = HTTP_ENCRYPT_ALWAYS;
a4d04587 1436# endif /* HAVE_SSL */
749b1e90 1437 }
a4d04587 1438 }
1439 }
1440
a4d04587 1441 launch_data_free(ld_msg);
1442 launch_data_free(ld_resp);
1443}
1444
1445
f7deaa1a 1446/*
1447 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1448 */
1449
1450static void
1451launchd_checkout(void)
1452{
1453 int fd; /* File descriptor */
1454
1455
1456 /*
1457 * Create or remove the launchd KeepAlive file based on whether
ef55b745 1458 * there are active jobs, polling, browsing for remote printers or
f7deaa1a 1459 * shared printers to advertise...
1460 */
1461
a2326b5b
MS
1462 if (cupsArrayCount(ActiveJobs) ||
1463 (Browsing && BrowseLocalProtocols && cupsArrayCount(Printers)))
f7deaa1a 1464 {
1465 cupsdLogMessage(CUPSD_LOG_DEBUG,
5a662dc0
MS
1466 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
1467 "\"...");
f7deaa1a 1468
1469 if ((fd = open(CUPS_KEEPALIVE, O_RDONLY | O_CREAT | O_EXCL, S_IRUSR)) >= 0)
1470 close(fd);
1471 }
1472 else
1473 {
1474 cupsdLogMessage(CUPSD_LOG_DEBUG,
5a662dc0
MS
1475 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
1476 "\"...");
f7deaa1a 1477
1478 unlink(CUPS_KEEPALIVE);
1479 }
1480}
a4d04587 1481#endif /* HAVE_LAUNCHD */
1482
1483
ef416fc2 1484/*
1485 * 'parent_handler()' - Catch USR1/CHLD signals...
1486 */
1487
1488static void
1489parent_handler(int sig) /* I - Signal */
1490{
1491 /*
1492 * Store the signal we got from the OS and return...
1493 */
1494
1495 parent_signal = sig;
1496}
1497
1498
1499/*
1500 * 'process_children()' - Process all dead children...
1501 */
1502
1503static void
1504process_children(void)
1505{
1506 int status; /* Exit status of child */
b9faaae1
MS
1507 int pid, /* Process ID of child */
1508 job_id; /* Job ID of child */
ef416fc2 1509 cupsd_job_t *job; /* Current job */
1510 int i; /* Looping var */
e00b005a 1511 char name[1024]; /* Process name */
dcb445bc 1512 const char *type; /* Type of program */
ef416fc2 1513
1514
1515 cupsdLogMessage(CUPSD_LOG_DEBUG2, "process_children()");
1516
1517 /*
1518 * Reset the dead_children flag...
1519 */
1520
1521 dead_children = 0;
1522
1523 /*
1524 * Collect the exit status of some children...
1525 */
1526
1527#ifdef HAVE_WAITPID
1528 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1529#elif defined(HAVE_WAIT3)
1530 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1531#else
1532 if ((pid = wait(&status)) > 0)
1533#endif /* HAVE_WAITPID */
1534 {
ef416fc2 1535 /*
745129be 1536 * Collect the name of the process that finished...
ef416fc2 1537 */
1538
b9faaae1 1539 cupsdFinishProcess(pid, name, sizeof(name), &job_id);
e00b005a 1540
ef416fc2 1541 /*
1542 * Delete certificates for CGI processes...
1543 */
1544
1545 if (pid)
1546 cupsdDeleteCert(pid);
1547
1548 /*
b9faaae1 1549 * Handle completed job filters...
ef416fc2 1550 */
1551
dcb445bc
MS
1552 if (job_id > 0)
1553 job = cupsdFindJob(job_id);
1554 else
1555 job = NULL;
1556
1557 if (job)
b9faaae1
MS
1558 {
1559 for (i = 0; job->filters[i]; i ++)
1560 if (job->filters[i] == pid)
1561 break;
1562
1563 if (job->filters[i] || job->backend == pid)
ef416fc2 1564 {
b9faaae1
MS
1565 /*
1566 * OK, this process has gone away; what's left?
1567 */
1568
1569 if (job->filters[i])
dcb445bc 1570 {
b9faaae1 1571 job->filters[i] = -pid;
dcb445bc
MS
1572 type = "Filter";
1573 }
b9faaae1 1574 else
dcb445bc 1575 {
b9faaae1 1576 job->backend = -pid;
dcb445bc
MS
1577 type = "Backend";
1578 }
ef416fc2 1579
b9faaae1 1580 if (status && status != SIGTERM && status != SIGKILL &&
f3c17241 1581 status != SIGPIPE)
ef416fc2 1582 {
1583 /*
b9faaae1
MS
1584 * An error occurred; save the exit status so we know to stop
1585 * the printer or cancel the job when all of the filters finish...
1586 *
1587 * A negative status indicates that the backend failed and the
1588 * printer needs to be stopped.
f3c17241
MS
1589 *
1590 * In order to preserve the most serious status, we always log
1591 * when a process dies due to a signal (e.g. SIGABRT, SIGSEGV,
1592 * and SIGBUS) and prefer to log the backend exit status over a
1593 * filter's.
ef416fc2 1594 */
1595
f3c17241
MS
1596 int old_status = abs(job->status);
1597
1598 if (WIFSIGNALED(status) || /* This process crashed, or */
1599 !job->status || /* No process had a status, or */
1600 (!job->filters[i] && WIFEXITED(old_status)))
1601 { /* Backend and filter didn't crash */
1602 if (job->filters[i])
1603 job->status = status; /* Filter failed */
1604 else
1605 job->status = -status; /* Backend failed */
1606 }
ef416fc2 1607
f11a948a 1608 if (job->state_value == IPP_JOB_PROCESSING &&
dcb445bc
MS
1609 job->status_level > CUPSD_LOG_ERROR &&
1610 (job->filters[i] || !WIFEXITED(status)))
ef416fc2 1611 {
f11a948a
MS
1612 char message[1024]; /* New printer-state-message */
1613
1614
b9faaae1 1615 job->status_level = CUPSD_LOG_ERROR;
ef416fc2 1616
dcb445bc 1617 snprintf(message, sizeof(message), "%s failed", type);
f11a948a 1618
e07d4801
MS
1619 if (job->printer)
1620 {
f11a948a
MS
1621 strlcpy(job->printer->state_message, message,
1622 sizeof(job->printer->state_message));
e07d4801
MS
1623 }
1624
1625 if (!job->attrs)
1626 cupsdLoadJob(job);
e00b005a 1627
e07d4801 1628 if (!job->printer_message && job->attrs)
e00b005a 1629 {
b9faaae1
MS
1630 if ((job->printer_message =
1631 ippFindAttribute(job->attrs, "job-printer-state-message",
1632 IPP_TAG_TEXT)) == NULL)
1633 job->printer_message = ippAddString(job->attrs, IPP_TAG_JOB,
1634 IPP_TAG_TEXT,
1635 "job-printer-state-message",
5a662dc0 1636 NULL, NULL);
e00b005a 1637 }
b9faaae1 1638
e07d4801
MS
1639 if (job->printer_message)
1640 cupsdSetString(&(job->printer_message->values[0].string.text),
f11a948a 1641 message);
ef416fc2 1642 }
b9faaae1 1643 }
ef416fc2 1644
b9faaae1
MS
1645 /*
1646 * If this is not the last file in a job, see if all of the
1647 * filters are done, and if so move to the next file.
1648 */
ef416fc2 1649
5a662dc0 1650 if (job->current_file < job->num_files && job->printer)
b9faaae1
MS
1651 {
1652 for (i = 0; job->filters[i] < 0; i ++);
ef416fc2 1653
82f97232
MS
1654 if (!job->filters[i] &&
1655 (!job->printer->pc || !job->printer->pc->single_file ||
1656 job->backend <= 0))
b9faaae1
MS
1657 {
1658 /*
1659 * Process the next file...
1660 */
ef416fc2 1661
b9faaae1 1662 cupsdContinueJob(job);
ef416fc2 1663 }
ef416fc2 1664 }
5a662dc0 1665 else if (job->state_value >= IPP_JOB_CANCELED)
7a0cbd5e
MS
1666 {
1667 /*
1668 * Remove the job from the active list if there are no processes still
1669 * running for it...
1670 */
1671
1672 for (i = 0; job->filters[i] < 0; i++);
1673
1674 if (!job->filters[i] && job->backend <= 0)
1675 cupsArrayRemove(ActiveJobs, job);
1676 }
ef416fc2 1677 }
b9faaae1 1678 }
3dfe78b3
MS
1679
1680 /*
745129be
MS
1681 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1682 * since they come when we kill/end a process...
3dfe78b3
MS
1683 */
1684
745129be
MS
1685 if (status == SIGTERM || status == SIGKILL)
1686 {
dcb445bc
MS
1687 cupsdLogJob(job, CUPSD_LOG_DEBUG,
1688 "PID %d (%s) was terminated normally with signal %d.", pid,
1689 name, status);
745129be 1690 }
5a6b583a
MS
1691 else if (status == SIGPIPE)
1692 {
dcb445bc
MS
1693 cupsdLogJob(job, CUPSD_LOG_DEBUG,
1694 "PID %d (%s) did not catch or ignore signal %d.", pid, name,
1695 status);
5a6b583a 1696 }
745129be 1697 else if (status)
3dfe78b3
MS
1698 {
1699 if (WIFEXITED(status))
88f9aafc
MS
1700 {
1701 int code = WEXITSTATUS(status); /* Exit code */
1702
1703 if (code > 100)
dcb445bc
MS
1704 cupsdLogJob(job, CUPSD_LOG_DEBUG,
1705 "PID %d (%s) stopped with status %d (%s)", pid, name,
1706 code, strerror(code - 100));
88f9aafc 1707 else
dcb445bc
MS
1708 cupsdLogJob(job, CUPSD_LOG_DEBUG,
1709 "PID %d (%s) stopped with status %d.", pid, name, code);
88f9aafc 1710 }
3dfe78b3 1711 else
dcb445bc
MS
1712 cupsdLogJob(job, CUPSD_LOG_DEBUG, "PID %d (%s) crashed on signal %d.",
1713 pid, name, WTERMSIG(status));
3dfe78b3
MS
1714
1715 if (LogLevel < CUPSD_LOG_DEBUG)
dcb445bc
MS
1716 cupsdLogJob(job, CUPSD_LOG_INFO,
1717 "Hint: Try setting the LogLevel to \"debug\" to find out "
1718 "more.");
3dfe78b3
MS
1719 }
1720 else
dcb445bc
MS
1721 cupsdLogJob(job, CUPSD_LOG_DEBUG, "PID %d (%s) exited with no errors.",
1722 pid, name);
ef416fc2 1723 }
dfd5680b
MS
1724
1725 /*
1726 * If wait*() is interrupted by a signal, tell main() to call us again...
1727 */
1728
1729 if (pid < 0 && errno == EINTR)
1730 dead_children = 1;
ef416fc2 1731}
1732
1733
ef416fc2 1734/*
1735 * 'select_timeout()' - Calculate the select timeout value.
1736 *
1737 */
1738
1739static long /* O - Number of seconds */
bd7854cb 1740select_timeout(int fds) /* I - Number of descriptors returned */
ef416fc2 1741{
ef416fc2 1742 long timeout; /* Timeout for select */
1743 time_t now; /* Current time */
1744 cupsd_client_t *con; /* Client information */
ef416fc2 1745 cupsd_job_t *job; /* Job information */
1746 cupsd_subscription_t *sub; /* Subscription information */
1747 const char *why; /* Debugging aid */
1748
1749
82cc1f9a
MS
1750 cupsdLogMessage(CUPSD_LOG_DEBUG2, "select_timeout: JobHistoryUpdate=%ld",
1751 (long)JobHistoryUpdate);
1752
ef416fc2 1753 /*
1754 * Check to see if any of the clients have pending data to be
1755 * processed; if so, the timeout should be 0...
1756 */
1757
996acce8 1758 // TODO: Use httpGetReady()
bd7854cb 1759 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
1760 con;
1761 con = (cupsd_client_t *)cupsArrayNext(Clients))
996acce8 1762 if (con->http->used > 0)
ef416fc2 1763 return (0);
1764
1765 /*
f7deaa1a 1766 * If select has been active in the last second (fds > 0) or we have
ef416fc2 1767 * many resources in use then don't bother trying to optimize the
1768 * timeout, just make it 1 second.
1769 */
1770
f7deaa1a 1771 if (fds > 0 || cupsArrayCount(Clients) > 50)
ef416fc2 1772 return (1);
1773
1774 /*
1775 * Otherwise, check all of the possible events that we need to wake for...
1776 */
1777
1778 now = time(NULL);
1779 timeout = now + 86400; /* 86400 == 1 day */
1780 why = "do nothing";
1781
e6013cfa
MS
1782#ifdef __APPLE__
1783 /*
1784 * When going to sleep, wake up to cancel jobs that don't complete in time.
1785 */
1786
1787 if (SleepJobs > 0 && SleepJobs < timeout)
1788 {
1789 timeout = SleepJobs;
1790 why = "cancel jobs before sleeping";
1791 }
1792#endif /* __APPLE__ */
1793
76cd9e37
MS
1794 /*
1795 * Check whether we are accepting new connections...
1796 */
1797
1798 if (ListeningPaused > 0 && cupsArrayCount(Clients) < MaxClients &&
1799 ListeningPaused < timeout)
1800 {
1801 if (ListeningPaused <= now)
1802 timeout = now;
1803 else
1804 timeout = ListeningPaused;
1805
1806 why = "resume listening";
1807 }
1808
ef416fc2 1809 /*
1810 * Check the activity and close old clients...
1811 */
1812
996acce8 1813 // TODO: Use httpGetActivity()
bd7854cb 1814 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
1815 con;
1816 con = (cupsd_client_t *)cupsArrayNext(Clients))
996acce8 1817 if ((con->http->activity + Timeout) < timeout)
ef416fc2 1818 {
996acce8 1819 timeout = con->http->activity + Timeout;
ef416fc2 1820 why = "timeout a client connection";
1821 }
1822
3dfe78b3 1823 /*
bf3816c7 1824 * Write out changes to configuration and state files...
3dfe78b3
MS
1825 */
1826
1827 if (DirtyCleanTime && timeout > DirtyCleanTime)
1828 {
1829 timeout = DirtyCleanTime;
1830 why = "write dirty config/state files";
1831 }
1832
ef416fc2 1833 /*
82cc1f9a 1834 * Check for any job activity...
ef416fc2 1835 */
1836
82cc1f9a
MS
1837 if (JobHistoryUpdate && timeout > JobHistoryUpdate)
1838 {
1839 timeout = JobHistoryUpdate;
1840 why = "update job history";
1841 }
1842
238c3832
MS
1843 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
1844 job;
1845 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
ef416fc2 1846 {
82cc1f9a
MS
1847 if (job->cancel_time && job->cancel_time < timeout)
1848 {
1849 timeout = job->cancel_time;
1850 why = "cancel stuck jobs";
1851 }
1852
238c3832
MS
1853 if (job->kill_time && job->kill_time < timeout)
1854 {
1855 timeout = job->kill_time;
1856 why = "kill unresponsive jobs";
1857 }
82cc1f9a
MS
1858
1859 if (job->state_value == IPP_JOB_HELD && job->hold_until < timeout)
238c3832
MS
1860 {
1861 timeout = job->hold_until;
1862 why = "release held jobs";
1863 }
82cc1f9a
MS
1864
1865 if (job->state_value == IPP_JOB_PENDING && timeout > (now + 10))
238c3832
MS
1866 {
1867 timeout = now + 10;
1868 why = "start pending jobs";
1869 break;
1870 }
ef416fc2 1871 }
1872
1873#ifdef HAVE_MALLINFO
1874 /*
1875 * Log memory usage every minute...
1876 */
1877
1878 if (LogLevel >= CUPSD_LOG_DEBUG && (mallinfo_time + 60) < timeout)
1879 {
1880 timeout = mallinfo_time + 60;
1881 why = "display memory usage";
1882 }
1883#endif /* HAVE_MALLINFO */
1884
ef416fc2 1885 /*
1886 * Expire subscriptions as needed...
1887 */
1888
1889 for (sub = (cupsd_subscription_t *)cupsArrayFirst(Subscriptions);
1890 sub;
1891 sub = (cupsd_subscription_t *)cupsArrayNext(Subscriptions))
bd7854cb 1892 if (!sub->job && sub->expire && sub->expire < timeout)
ef416fc2 1893 {
1894 timeout = sub->expire;
1895 why = "expire subscription";
1896 }
1897
1898 /*
dcb445bc
MS
1899 * Adjust from absolute to relative time. We add 1 second to the timeout since
1900 * events occur after the timeout expires, and limit the timeout to 86400
1901 * seconds (1 day) to avoid select() timeout limits present on some operating
ef416fc2 1902 * systems...
1903 */
1904
1905 timeout = timeout - now + 1;
1906
1907 if (timeout < 1)
1908 timeout = 1;
1909 else if (timeout > 86400)
1910 timeout = 86400;
1911
1912 /*
1913 * Log and return the timeout value...
1914 */
1915
f7deaa1a 1916 cupsdLogMessage(CUPSD_LOG_DEBUG2, "select_timeout(%d): %ld seconds to %s",
1917 fds, timeout, why);
ef416fc2 1918
1919 return (timeout);
1920}
1921
1922
e6013cfa
MS
1923/*
1924 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1925 */
1926
1927static void
1928sigchld_handler(int sig) /* I - Signal number */
1929{
1930 (void)sig;
1931
1932 /*
1933 * Flag that we have dead children...
1934 */
1935
1936 dead_children = 1;
1937
1938 /*
1939 * Reset the signal handler as needed...
1940 */
1941
1942#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1943 signal(SIGCLD, sigchld_handler);
1944#endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1945}
1946
1947
1948/*
1949 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1950 */
1951
1952static void
1953sighup_handler(int sig) /* I - Signal number */
1954{
1955 (void)sig;
1956
1957 NeedReload = RELOAD_ALL;
1958 ReloadTime = time(NULL);
1959
1960#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1961 signal(SIGHUP, sighup_handler);
1962#endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1963}
1964
1965
1966/*
1967 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1968 */
1969
1970static void
1971sigterm_handler(int sig) /* I - Signal number */
1972{
1973 (void)sig; /* remove compiler warnings... */
1974
1975 /*
1976 * Flag that we should stop and return...
1977 */
1978
1979 stop_scheduler = 1;
1980}
1981
1982
ef416fc2 1983/*
1984 * 'usage()' - Show scheduler usage.
1985 */
1986
1987static void
a4d04587 1988usage(int status) /* O - Exit status */
ef416fc2 1989{
0837b7e8
MS
1990 FILE *fp = status ? stderr : stdout; /* Output file */
1991
1992
1993 _cupsLangPuts(fp, _("Usage: cupsd [options]"));
1994 _cupsLangPuts(fp, _("Options:"));
f3c17241 1995 _cupsLangPuts(fp, _(" -c cupsd.conf Set cupsd.conf file to use."));
84315f46
MS
1996 _cupsLangPuts(fp, _(" -f Run in the foreground."));
1997 _cupsLangPuts(fp, _(" -F Run in the foreground but "
1998 "detach from console."));
1999 _cupsLangPuts(fp, _(" -h Show this usage message."));
2000 _cupsLangPuts(fp, _(" -l Run cupsd from launchd(8)."));
2001 _cupsLangPuts(fp, _(" -t Test the configuration "
0837b7e8 2002 "file."));
0837b7e8 2003
a4d04587 2004 exit(status);
ef416fc2 2005}
2006
2007
2008/*
f2d18633 2009 * End of "$Id$".
ef416fc2 2010 */