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