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