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