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