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