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