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