]> git.ipfire.org Git - thirdparty/cups.git/blame - scheduler/main.c
To prepare to load cups into easysw/current, perform 4 renames.
[thirdparty/cups.git] / scheduler / main.c
CommitLineData
ef416fc2 1/*
2 * "$Id: main.c 4838 2005-11-14 18:34:27Z mike $"
3 *
4 * Scheduler main loop for the Common UNIX Printing System (CUPS).
5 *
6 * Copyright 1997-2005 by Easy Software Products, all rights reserved.
7 *
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
13 * at:
14 *
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636 USA
19 *
20 * Voice: (301) 373-9600
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
23 *
24 * Contents:
25 *
26 * main() - Main entry for the CUPS scheduler.
27 * cupsdClosePipe() - Close a pipe as necessary.
28 * cupsdOpenPipe() - Create a pipe which is closed on exec.
29 * cupsdCatchChildSignals() - Catch SIGCHLD signals...
30 * cupsdHoldSignals() - Hold child and termination signals.
31 * cupsdIgnoreChildSignals() - Ignore SIGCHLD signals...
32 * cupsdReleaseSignals() - Release signals for delivery.
33 * cupsdSetString() - Set a string value.
34 * cupsdSetStringf() - Set a formatted string value.
35 * parent_handler() - Catch USR1/CHLD signals...
36 * process_children() - Process all dead children...
37 * sigchld_handler() - Handle 'child' signals from old processes.
38 * sighup_handler() - Handle 'hangup' signals to reconfigure the
39 * scheduler.
40 * sigterm_handler() - Handle 'terminate' signals that stop the
41 * scheduler.
42 * select_timeout() - Calculate the select timeout value.
43 * usage() - Show scheduler usage.
44 */
45
46/*
47 * Include necessary headers...
48 */
49
50#define _MAIN_C_
51#include "cupsd.h"
52#include <sys/resource.h>
53#include <syslog.h>
54#include <grp.h>
55
56#if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
57# include <malloc.h>
58#endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
59
60
61/*
62 * Local functions...
63 */
64
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);
71static void usage(void);
72
73
74/*
75 * Local globals...
76 */
77
78static int parent_signal = 0; /* Set to signal number from child */
79static int holdcount = 0; /* Number of times "hold" was called */
80#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
81static sigset_t holdmask; /* Old POSIX signal mask */
82#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
83static int dead_children = 0; /* Dead children? */
84static int stop_scheduler = 0; /* Should the scheduler stop? */
85
86
87/*
88 * 'main()' - Main entry for the CUPS scheduler.
89 */
90
91int /* O - Exit status */
92main(int argc, /* I - Number of command-line arguments */
93 char *argv[]) /* I - Command-line arguments */
94{
95 int i; /* Looping var */
96 char *opt; /* Option character */
97 int fg; /* Run in the foreground */
98 int fds; /* Number of ready descriptors select returns */
99 fd_set *input, /* Input set for select() */
100 *output; /* Output set for select() */
101 cupsd_client_t *con; /* Current client */
102 cupsd_job_t *job; /* Current job */
103 cupsd_listener_t *lis; /* Current listener */
104 time_t current_time, /* Current time */
105 activity, /* Activity timer */
106 browse_time, /* Next browse send time */
107 senddoc_time, /* Send-Document time */
108 expire_time; /* Subscription expire time */
109#ifdef HAVE_MALLINFO
110 time_t mallinfo_time; /* Malloc information time */
111#endif /* HAVE_MALLINFO */
112 struct timeval timeout; /* select() timeout */
113 struct rlimit limit; /* Runtime limit */
114#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
115 struct sigaction action; /* Actions for POSIX signals */
116#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
117#ifdef __sgi
118 cups_file_t *fp; /* Fake lpsched lock file */
119 struct stat statbuf; /* Needed for checking lpsched FIFO */
120#endif /* __sgi */
121
122
123 /*
124 * Check for command-line arguments...
125 */
126
127 fg = 0;
128
129 for (i = 1; i < argc; i ++)
130 if (argv[i][0] == '-')
131 for (opt = argv[i] + 1; *opt != '\0'; opt ++)
132 switch (*opt)
133 {
134 case 'c' : /* Configuration file */
135 i ++;
136 if (i >= argc)
137 usage();
138
139 if (argv[i][0] == '/')
140 {
141 /*
142 * Absolute directory...
143 */
144
145 cupsdSetString(&ConfigurationFile, argv[i]);
146 }
147 else
148 {
149 /*
150 * Relative directory...
151 */
152
153 char current[1024]; /* Current directory */
154
155
156 getcwd(current, sizeof(current));
157 cupsdSetStringf(&ConfigurationFile, "%s/%s", current, argv[i]);
158 }
159 break;
160
161 case 'f' : /* Run in foreground... */
162 fg = 1;
163 break;
164
165 case 'F' : /* Run in foreground, but still disconnect from terminal... */
166 fg = -1;
167 break;
168
169 default : /* Unknown option */
170 fprintf(stderr, "cupsd: Unknown option \'%c\' - aborting!\n",
171 *opt);
172 usage();
173 break;
174 }
175 else
176 {
177 fprintf(stderr, "cupsd: Unknown argument \'%s\' - aborting!\n", argv[i]);
178 usage();
179 }
180
181 if (!ConfigurationFile)
182 cupsdSetString(&ConfigurationFile, CUPS_SERVERROOT "/cupsd.conf");
183
184 /*
185 * If the user hasn't specified "-f", run in the background...
186 */
187
188 if (!fg)
189 {
190 /*
191 * Setup signal handlers for the parent...
192 */
193
194#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
195 sigset(SIGUSR1, parent_handler);
196 sigset(SIGCHLD, parent_handler);
197
198 sigset(SIGHUP, SIG_IGN);
199#elif defined(HAVE_SIGACTION)
200 memset(&action, 0, sizeof(action));
201 sigemptyset(&action.sa_mask);
202 sigaddset(&action.sa_mask, SIGUSR1);
203 action.sa_handler = parent_handler;
204 sigaction(SIGUSR1, &action, NULL);
205 sigaction(SIGCHLD, &action, NULL);
206
207 sigemptyset(&action.sa_mask);
208 action.sa_handler = SIG_IGN;
209 sigaction(SIGHUP, &action, NULL);
210#else
211 signal(SIGUSR1, parent_handler);
212 signal(SIGCLD, parent_handler);
213
214 signal(SIGHUP, SIG_IGN);
215#endif /* HAVE_SIGSET */
216
217 if (fork() > 0)
218 {
219 /*
220 * OK, wait for the child to startup and send us SIGUSR1 or to crash
221 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
222 * might be sent by the init script to restart the scheduler...
223 */
224
225 for (; parent_signal == 0;)
226 sleep(1);
227
228 if (parent_signal == SIGUSR1)
229 return (0);
230
231 if (wait(&i) < 0)
232 {
233 perror("cupsd");
234 return (1);
235 }
236 else if (WIFEXITED(i))
237 {
238 fprintf(stderr, "cupsd: Child exited with status %d!\n", WEXITSTATUS(i));
239 return (2);
240 }
241 else
242 {
243 fprintf(stderr, "cupsd: Child exited on signal %d!\n", WTERMSIG(i));
244 return (3);
245 }
246 }
247 }
248
249 if (fg < 1)
250 {
251 /*
252 * Make sure we aren't tying up any filesystems...
253 */
254
255 chdir("/");
256
257#ifndef DEBUG
258 /*
259 * Disable core dumps...
260 */
261
262 getrlimit(RLIMIT_CORE, &limit);
263 limit.rlim_cur = 0;
264 setrlimit(RLIMIT_CORE, &limit);
265
266 /*
267 * Disconnect from the controlling terminal...
268 */
269
270 setsid();
271
272 /*
273 * Close all open files...
274 */
275
276 getrlimit(RLIMIT_NOFILE, &limit);
277
278 for (i = 0; i < limit.rlim_cur; i ++)
279 close(i);
280#endif /* DEBUG */
281 }
282
283 /*
284 * Set the timezone info...
285 */
286
287 tzset();
288
289#ifdef LC_TIME
290 setlocale(LC_TIME, "");
291#endif /* LC_TIME */
292
293 /*
294 * Set the maximum number of files...
295 */
296
297 getrlimit(RLIMIT_NOFILE, &limit);
298
299 if (limit.rlim_max > CUPS_MAX_FDS)
300 MaxFDs = CUPS_MAX_FDS;
301 else
302 MaxFDs = limit.rlim_max;
303
304 limit.rlim_cur = MaxFDs;
305
306 setrlimit(RLIMIT_NOFILE, &limit);
307
308 /*
309 * Allocate memory for the input and output sets...
310 */
311
312 SetSize = (MaxFDs + 31) / 8 + 4;
313 if (SetSize < sizeof(fd_set))
314 SetSize = sizeof(fd_set);
315
316 InputSet = (fd_set *)calloc(1, SetSize);
317 OutputSet = (fd_set *)calloc(1, SetSize);
318 input = (fd_set *)calloc(1, SetSize);
319 output = (fd_set *)calloc(1, SetSize);
320
321 if (InputSet == NULL || OutputSet == NULL || input == NULL || output == NULL)
322 {
323 syslog(LOG_LPR, "Unable to allocate memory for select() sets - exiting!");
324 return (1);
325 }
326
327 /*
328 * Read configuration...
329 */
330
331 if (!cupsdReadConfiguration())
332 {
333 syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
334 ConfigurationFile);
335 return (1);
336 }
337
338 /*
339 * Catch hangup and child signals and ignore broken pipes...
340 */
341
342#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
343 if (RunAsUser)
344 sigset(SIGHUP, sigterm_handler);
345 else
346 sigset(SIGHUP, sighup_handler);
347
348 sigset(SIGPIPE, SIG_IGN);
349 sigset(SIGTERM, sigterm_handler);
350#elif defined(HAVE_SIGACTION)
351 memset(&action, 0, sizeof(action));
352
353 sigemptyset(&action.sa_mask);
354 sigaddset(&action.sa_mask, SIGHUP);
355
356 if (RunAsUser)
357 action.sa_handler = sigterm_handler;
358 else
359 action.sa_handler = sighup_handler;
360
361 sigaction(SIGHUP, &action, NULL);
362
363 sigemptyset(&action.sa_mask);
364 action.sa_handler = SIG_IGN;
365 sigaction(SIGPIPE, &action, NULL);
366
367 sigemptyset(&action.sa_mask);
368 sigaddset(&action.sa_mask, SIGTERM);
369 sigaddset(&action.sa_mask, SIGCHLD);
370 action.sa_handler = sigterm_handler;
371 sigaction(SIGTERM, &action, NULL);
372#else
373 if (RunAsUser)
374 signal(SIGHUP, sigterm_handler);
375 else
376 signal(SIGHUP, sighup_handler);
377
378 signal(SIGPIPE, SIG_IGN);
379 signal(SIGTERM, sigterm_handler);
380#endif /* HAVE_SIGSET */
381
382#ifdef __sgi
383 /*
384 * Try to create a fake lpsched lock file if one is not already there.
385 * Some Adobe applications need it under IRIX in order to enable
386 * printing...
387 */
388
389 if ((fp = cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL)
390 {
391 syslog(LOG_LPR, "Unable to create fake lpsched lock file "
392 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
393 strerror(errno));
394 }
395 else
396 {
397 fchmod(cupsFileNumber(fp), 0644);
398 fchown(cupsFileNumber(fp), User, Group);
399
400 cupsFileClose(fp);
401 }
402#endif /* __sgi */
403
404 /*
405 * Initialize authentication certificates...
406 */
407
408 cupsdInitCerts();
409
410 /*
411 * If we are running in the background, signal the parent process that
412 * we are up and running...
413 */
414
415 if (!fg)
416 {
417 /*
418 * Send a signal to the parent process, but only if the parent is
419 * not PID 1 (init). This avoids accidentally shutting down the
420 * system on OpenBSD if you CTRL-C the server before it is up...
421 */
422
423 i = getppid(); /* Save parent PID to avoid race condition */
424
425 if (i != 1)
426 kill(i, SIGUSR1);
427 }
428
429 /*
430 * If the administrator has configured the server to run as an unpriviledged
431 * user, change to that user now...
432 */
433
434 if (RunAsUser)
435 {
436 setgid(Group);
437 setgroups(1, &Group);
438 setuid(User);
439 }
440
441 /*
442 * Catch signals...
443 */
444
445 cupsdCatchChildSignals();
446
447 /*
448 * Start any pending print jobs...
449 */
450
451 cupsdCheckJobs();
452
453 /*
454 * Loop forever...
455 */
456
457#ifdef HAVE_MALLINFO
458 mallinfo_time = 0;
459#endif /* HAVE_MALLINFO */
460 browse_time = time(NULL);
461 senddoc_time = time(NULL);
462 expire_time = time(NULL);
463 fds = 1;
464
465 while (!stop_scheduler)
466 {
467#ifdef DEBUG
468 cupsdLogMessage(CUPSD_LOG_DEBUG2,
469 "main: Top of loop, dead_children=%d, NeedReload=%d",
470 dead_children, NeedReload);
471#endif /* DEBUG */
472
473 /*
474 * Check if there are dead children to handle...
475 */
476
477 if (dead_children)
478 process_children();
479
480 /*
481 * Check if we need to load the server configuration file...
482 */
483
484 if (NeedReload)
485 {
486 /*
487 * Close any idle clients...
488 */
489
490 if (NumClients > 0)
491 {
492 for (i = NumClients, con = Clients; i > 0; i --, con ++)
493 if (con->http.state == HTTP_WAITING)
494 {
495 cupsdCloseClient(con);
496 con --;
497 }
498 else
499 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
500
501 cupsdPauseListening();
502 }
503
504 /*
505 * Check for any active jobs...
506 */
507
508 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
509 job;
510 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
511 if (job->state->values[0].integer == IPP_JOB_PROCESSING)
512 break;
513
514 /*
515 * Restart if all clients are closed and all jobs finished, or
516 * if the reload timeout has elapsed...
517 */
518
519 if ((NumClients == 0 && (!job || NeedReload != RELOAD_ALL)) ||
520 (time(NULL) - ReloadTime) >= ReloadTimeout)
521 {
522 if (!cupsdReadConfiguration())
523 {
524 syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
525 ConfigurationFile);
526 break;
527 }
528 }
529 }
530
531 /*
532 * Check for available input or ready output. If select() returns
533 * 0 or -1, something bad happened and we should exit immediately.
534 *
535 * Note that we at least have one listening socket open at all
536 * times.
537 */
538
539 memcpy(input, InputSet, SetSize);
540 memcpy(output, OutputSet, SetSize);
541
542 timeout.tv_sec = select_timeout(fds);
543 timeout.tv_usec = 0;
544
545 if ((fds = select(MaxFDs, input, output, NULL, &timeout)) < 0)
546 {
547 char s[16384], /* String buffer */
548 *sptr; /* Pointer into buffer */
549 int slen; /* Length of string buffer */
550
551
552 /*
553 * Got an error from select!
554 */
555
556 if (errno == EINTR) /* Just interrupted by a signal */
557 continue;
558
559 /*
560 * Log all sorts of debug info to help track down the problem.
561 */
562
563 cupsdLogMessage(CUPSD_LOG_EMERG, "select() failed - %s!",
564 strerror(errno));
565
566 strcpy(s, "InputSet =");
567 slen = 10;
568 sptr = s + 10;
569
570 for (i = 0; i < MaxFDs; i ++)
571 if (FD_ISSET(i, InputSet))
572 {
573 snprintf(sptr, sizeof(s) - slen, " %d", i);
574 slen += strlen(sptr);
575 sptr += strlen(sptr);
576 }
577
578 cupsdLogMessage(CUPSD_LOG_EMERG, s);
579
580 strcpy(s, "OutputSet =");
581 slen = 11;
582 sptr = s + 11;
583
584 for (i = 0; i < MaxFDs; i ++)
585 if (FD_ISSET(i, OutputSet))
586 {
587 snprintf(sptr, sizeof(s) - slen, " %d", i);
588 slen += strlen(sptr);
589 sptr += strlen(sptr);
590 }
591
592 cupsdLogMessage(CUPSD_LOG_EMERG, s);
593
594 for (i = 0, con = Clients; i < NumClients; i ++, con ++)
595 cupsdLogMessage(CUPSD_LOG_EMERG,
596 "Clients[%d] = %d, file = %d, state = %d",
597 i, con->http.fd, con->file, con->http.state);
598
599 for (i = 0, lis = Listeners; i < NumListeners; i ++, lis ++)
600 cupsdLogMessage(CUPSD_LOG_EMERG, "Listeners[%d] = %d", i, lis->fd);
601
602 cupsdLogMessage(CUPSD_LOG_EMERG, "BrowseSocket = %d", BrowseSocket);
603
604 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
605 job;
606 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
607 cupsdLogMessage(CUPSD_LOG_EMERG, "Jobs[%d] = %d < [%d %d] > [%d %d]",
608 job->id,
609 job->status_buffer ? job->status_buffer->fd : -1,
610 job->print_pipes[0], job->print_pipes[1],
611 job->back_pipes[0], job->back_pipes[1]);
612 break;
613 }
614
615 current_time = time(NULL);
616
617 /*
618 * Check for status info from job filters...
619 */
620
621 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
622 job;
623 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
624 if (job->status_buffer && FD_ISSET(job->status_buffer->fd, input))
625 {
626 /*
627 * Clear the input bit to avoid updating the next job
628 * using the same status pipe file descriptor...
629 */
630
631 FD_CLR(job->status_buffer->fd, input);
632
633 /*
634 * Read any status messages from the filters...
635 */
636
637 cupsdUpdateJob(job);
638 }
639
640 /*
641 * Update CGI messages as needed...
642 */
643
644 if (CGIPipes[0] >= 0 && FD_ISSET(CGIPipes[0], input))
645 cupsdUpdateCGI();
646
647 /*
648 * Update notifier messages as needed...
649 */
650
651 if (NotifierPipes[0] >= 0 && FD_ISSET(NotifierPipes[0], input))
652 cupsdUpdateNotifierStatus();
653
654 /*
655 * Expire subscriptions as needed...
656 */
657
658 if (cupsArrayCount(Subscriptions) > 0 && current_time > expire_time)
659 {
660 cupsdExpireSubscriptions(NULL, NULL);
661
662 expire_time = current_time;
663 }
664
665 /*
666 * Update the browse list as needed...
667 */
668
669 if (Browsing && (BrowseLocalProtocols | BrowseRemoteProtocols))
670 {
671 if (BrowseSocket >= 0 && FD_ISSET(BrowseSocket, input))
672 cupsdUpdateCUPSBrowse();
673
674 if (PollPipe >= 0 && FD_ISSET(PollPipe, input))
675 cupsdUpdatePolling();
676
677#ifdef HAVE_LIBSLP
678 if (((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_SLP) &&
679 BrowseSLPRefresh <= current_time)
680 cupsdUpdateSLPBrowse();
681#endif /* HAVE_LIBSLP */
682
683 if (current_time > browse_time)
684 {
685 cupsdSendBrowseList();
686 browse_time = current_time;
687 }
688 }
689
690 /*
691 * Check for new connections on the "listen" sockets...
692 */
693
694 for (i = NumListeners, lis = Listeners; i > 0; i --, lis ++)
695 if (lis->fd >= 0 && FD_ISSET(lis->fd, input))
696 {
697 FD_CLR(lis->fd, input);
698 cupsdAcceptClient(lis);
699 }
700
701 /*
702 * Check for new data on the client sockets...
703 */
704
705 for (i = NumClients, con = Clients; i > 0; i --, con ++)
706 {
707 /*
708 * Process the input buffer...
709 */
710
711 if (FD_ISSET(con->http.fd, input) || con->http.used)
712 {
713 FD_CLR(con->http.fd, input);
714
715 if (!cupsdReadClient(con))
716 {
717 if (con->pipe_pid)
718 FD_CLR(con->file, input);
719
720 con --;
721 continue;
722 }
723 }
724
725 /*
726 * Write data as needed...
727 */
728
729 if (con->pipe_pid && FD_ISSET(con->file, input))
730 {
731 /*
732 * Keep track of pending input from the file/pipe separately
733 * so that we don't needlessly spin on select() when the web
734 * client is not ready to receive data...
735 */
736
737 FD_CLR(con->file, input);
738 con->file_ready = 1;
739
740#ifdef DEBUG
741 cupsdLogMessage(CUPSD_LOG_DEBUG2, "main: Data ready file %d!",
742 con->file);
743#endif /* DEBUG */
744
745 if (!FD_ISSET(con->http.fd, output))
746 {
747 cupsdLogMessage(CUPSD_LOG_DEBUG2,
748 "main: Removing fd %d from InputSet...", con->file);
749 FD_CLR(con->file, InputSet);
750 }
751 }
752
753 if (FD_ISSET(con->http.fd, output))
754 {
755 FD_CLR(con->http.fd, output);
756
757 if (!con->pipe_pid || con->file_ready)
758 if (!cupsdWriteClient(con))
759 {
760 con --;
761 continue;
762 }
763 }
764
765 /*
766 * Check the activity and close old clients...
767 */
768
769 activity = current_time - Timeout;
770 if (con->http.activity < activity && !con->pipe_pid)
771 {
772 cupsdLogMessage(CUPSD_LOG_DEBUG,
773 "Closing client %d after %d seconds of inactivity...",
774 con->http.fd, Timeout);
775
776 cupsdCloseClient(con);
777 con --;
778 continue;
779 }
780 }
781
782 /*
783 * Update any pending multi-file documents...
784 */
785
786 if ((current_time - senddoc_time) >= 10)
787 {
788 cupsdCheckJobs();
789 senddoc_time = current_time;
790 }
791
792#ifdef HAVE_MALLINFO
793 /*
794 * Log memory usage every minute...
795 */
796
797 if ((current_time - mallinfo_time) >= 60 && LogLevel >= CUPSD_LOG_DEBUG)
798 {
799 struct mallinfo mem; /* Malloc information */
800
801
802 mem = mallinfo();
803 cupsdLogMessage(CUPSD_LOG_DEBUG,
804 "mallinfo: arena = %d, used = %d, free = %d\n",
805 mem.arena, mem.usmblks + mem.uordblks,
806 mem.fsmblks + mem.fordblks);
807 mallinfo_time = current_time;
808 }
809#endif /* HAVE_MALLINFO */
810
811 /*
812 * Update the root certificate once every 5 minutes...
813 */
814
815 if ((current_time - RootCertTime) >= RootCertDuration && RootCertDuration &&
816 !RunUser)
817 {
818 /*
819 * Update the root certificate...
820 */
821
822 cupsdDeleteCert(0);
823 cupsdAddCert(0, "root");
824 }
825 }
826
827 /*
828 * Log a message based on what happened...
829 */
830
831 if (stop_scheduler)
832 cupsdLogMessage(CUPSD_LOG_INFO, "Scheduler shutting down normally.");
833 else
834 cupsdLogMessage(CUPSD_LOG_ERROR,
835 "Scheduler shutting down due to program error.");
836
837 /*
838 * Close all network clients and stop all jobs...
839 */
840
841 cupsdStopServer();
842
843 cupsdStopAllJobs();
844
845#ifdef __sgi
846 /*
847 * Remove the fake IRIX lpsched lock file, but only if the existing
848 * file is not a FIFO which indicates that the real IRIX lpsched is
849 * running...
850 */
851
852 if (!stat("/var/spool/lp/FIFO", &statbuf))
853 if (!S_ISFIFO(statbuf.st_mode))
854 unlink("/var/spool/lp/SCHEDLOCK");
855#endif /* __sgi */
856
857 /*
858 * Free memory used by FD sets and return...
859 */
860
861 free(InputSet);
862 free(OutputSet);
863 free(input);
864 free(output);
865
866 return (!stop_scheduler);
867}
868
869
870/*
871 * 'cupsdClosePipe()' - Close a pipe as necessary.
872 */
873
874void
875cupsdClosePipe(int *fds) /* I - Pipe file descriptors (2) */
876{
877 /*
878 * Close file descriptors as needed...
879 */
880
881 if (fds[0] >= 0)
882 {
883 close(fds[0]);
884 fds[0] = -1;
885 }
886
887 if (fds[1] >= 0)
888 {
889 close(fds[1]);
890 fds[1] = -1;
891 }
892}
893
894
895/*
896 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
897 */
898
899int /* O - 0 on success, -1 on error */
900cupsdOpenPipe(int *fds) /* O - Pipe file descriptors (2) */
901{
902 /*
903 * Create the pipe...
904 */
905
906 if (pipe(fds))
907 return (-1);
908
909 /*
910 * Set the "close on exec" flag on each end of the pipe...
911 */
912
913 if (fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC))
914 {
915 close(fds[0]);
916 close(fds[1]);
917 return (-1);
918 }
919
920 if (fcntl(fds[1], F_SETFD, fcntl(fds[1], F_GETFD) | FD_CLOEXEC))
921 {
922 close(fds[0]);
923 close(fds[1]);
924 return (-1);
925 }
926
927 /*
928 * Return 0 indicating success...
929 */
930
931 return (0);
932}
933
934
935/*
936 * 'cupsdCatchChildSignals()' - Catch SIGCHLD signals...
937 */
938
939void
940cupsdCatchChildSignals(void)
941{
942#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
943 struct sigaction action; /* Actions for POSIX signals */
944#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
945
946
947#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
948 sigset(SIGCHLD, sigchld_handler);
949#elif defined(HAVE_SIGACTION)
950 memset(&action, 0, sizeof(action));
951
952 sigemptyset(&action.sa_mask);
953 sigaddset(&action.sa_mask, SIGTERM);
954 sigaddset(&action.sa_mask, SIGCHLD);
955 action.sa_handler = sigchld_handler;
956 sigaction(SIGCHLD, &action, NULL);
957#else
958 signal(SIGCLD, sigchld_handler); /* No, SIGCLD isn't a typo... */
959#endif /* HAVE_SIGSET */
960}
961
962
963/*
964 * 'cupsdClearString()' - Clear a string.
965 */
966
967void
968cupsdClearString(char **s) /* O - String value */
969{
970 if (s && *s)
971 {
972 free(*s);
973 *s = NULL;
974 }
975}
976
977
978/*
979 * 'cupsdHoldSignals()' - Hold child and termination signals.
980 */
981
982void
983cupsdHoldSignals(void)
984{
985#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
986 sigset_t newmask; /* New POSIX signal mask */
987#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
988
989
990 holdcount ++;
991 if (holdcount > 1)
992 return;
993
994#ifdef HAVE_SIGSET
995 sighold(SIGTERM);
996 sighold(SIGCHLD);
997#elif defined(HAVE_SIGACTION)
998 sigemptyset(&newmask);
999 sigaddset(&newmask, SIGTERM);
1000 sigaddset(&newmask, SIGCHLD);
1001 sigprocmask(SIG_BLOCK, &newmask, &holdmask);
1002#endif /* HAVE_SIGSET */
1003}
1004
1005
1006/*
1007 * 'cupsdIgnoreChildSignals()' - Ignore SIGCHLD signals...
1008 *
1009 * We don't really ignore them, we set the signal handler to SIG_DFL,
1010 * since some OS's rely on signals for the wait4() function to work.
1011 */
1012
1013void
1014cupsdIgnoreChildSignals(void)
1015{
1016#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1017 struct sigaction action; /* Actions for POSIX signals */
1018#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1019
1020
1021#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
1022 sigset(SIGCHLD, SIG_DFL);
1023#elif defined(HAVE_SIGACTION)
1024 memset(&action, 0, sizeof(action));
1025
1026 sigemptyset(&action.sa_mask);
1027 sigaddset(&action.sa_mask, SIGCHLD);
1028 action.sa_handler = SIG_DFL;
1029 sigaction(SIGCHLD, &action, NULL);
1030#else
1031 signal(SIGCLD, SIG_DFL); /* No, SIGCLD isn't a typo... */
1032#endif /* HAVE_SIGSET */
1033}
1034
1035
1036/*
1037 * 'cupsdReleaseSignals()' - Release signals for delivery.
1038 */
1039
1040void
1041cupsdReleaseSignals(void)
1042{
1043 holdcount --;
1044 if (holdcount > 0)
1045 return;
1046
1047#ifdef HAVE_SIGSET
1048 sigrelse(SIGTERM);
1049 sigrelse(SIGCHLD);
1050#elif defined(HAVE_SIGACTION)
1051 sigprocmask(SIG_SETMASK, &holdmask, NULL);
1052#endif /* HAVE_SIGSET */
1053}
1054
1055
1056/*
1057 * 'cupsdSetString()' - Set a string value.
1058 */
1059
1060void
1061cupsdSetString(char **s, /* O - New string */
1062 const char *v) /* I - String value */
1063{
1064 if (!s || *s == v)
1065 return;
1066
1067 if (*s)
1068 free(*s);
1069
1070 if (v)
1071 *s = strdup(v);
1072 else
1073 *s = NULL;
1074}
1075
1076
1077/*
1078 * 'cupsdSetStringf()' - Set a formatted string value.
1079 */
1080
1081void
1082cupsdSetStringf(char **s, /* O - New string */
1083 const char *f, /* I - Printf-style format string */
1084 ...) /* I - Additional args as needed */
1085{
1086 char v[4096]; /* Formatting string value */
1087 va_list ap; /* Argument pointer */
1088 char *olds; /* Old string */
1089
1090
1091 if (!s)
1092 return;
1093
1094 olds = *s;
1095
1096 if (f)
1097 {
1098 va_start(ap, f);
1099 vsnprintf(v, sizeof(v), f, ap);
1100 va_end(ap);
1101
1102 *s = strdup(v);
1103 }
1104 else
1105 *s = NULL;
1106
1107 if (olds)
1108 free(olds);
1109}
1110
1111
1112/*
1113 * 'parent_handler()' - Catch USR1/CHLD signals...
1114 */
1115
1116static void
1117parent_handler(int sig) /* I - Signal */
1118{
1119 /*
1120 * Store the signal we got from the OS and return...
1121 */
1122
1123 parent_signal = sig;
1124}
1125
1126
1127/*
1128 * 'process_children()' - Process all dead children...
1129 */
1130
1131static void
1132process_children(void)
1133{
1134 int status; /* Exit status of child */
1135 int pid; /* Process ID of child */
1136 cupsd_job_t *job; /* Current job */
1137 int i; /* Looping var */
1138
1139
1140 cupsdLogMessage(CUPSD_LOG_DEBUG2, "process_children()");
1141
1142 /*
1143 * Reset the dead_children flag...
1144 */
1145
1146 dead_children = 0;
1147
1148 /*
1149 * Collect the exit status of some children...
1150 */
1151
1152#ifdef HAVE_WAITPID
1153 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1154#elif defined(HAVE_WAIT3)
1155 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1156#else
1157 if ((pid = wait(&status)) > 0)
1158#endif /* HAVE_WAITPID */
1159 {
1160 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1161 "process_children: pid = %d, status = %d\n", pid, status);
1162
1163 /*
1164 * Ignore SIGTERM errors - that comes when a job is cancelled...
1165 */
1166
1167 if (status == SIGTERM)
1168 status = 0;
1169
1170 if (status)
1171 {
1172 if (WIFEXITED(status))
1173 cupsdLogMessage(CUPSD_LOG_ERROR, "PID %d stopped with status %d!", pid,
1174 WEXITSTATUS(status));
1175 else
1176 cupsdLogMessage(CUPSD_LOG_ERROR, "PID %d crashed on signal %d!", pid,
1177 WTERMSIG(status));
1178
1179 if (LogLevel < CUPSD_LOG_DEBUG)
1180 cupsdLogMessage(CUPSD_LOG_INFO,
1181 "Hint: Try setting the LogLevel to \"debug\" to find out more.");
1182 }
1183 else
1184 cupsdLogMessage(CUPSD_LOG_DEBUG2, "PID %d exited with no errors.", pid);
1185
1186 /*
1187 * Delete certificates for CGI processes...
1188 */
1189
1190 if (pid)
1191 cupsdDeleteCert(pid);
1192
1193 /*
1194 * Lookup the PID in the jobs list...
1195 */
1196
1197 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
1198 job;
1199 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
1200 if (job->state != NULL &&
1201 job->state->values[0].integer == IPP_JOB_PROCESSING)
1202 {
1203 for (i = 0; job->filters[i]; i ++)
1204 if (job->filters[i] == pid)
1205 break;
1206
1207 if (job->filters[i] || job->backend == pid)
1208 {
1209 /*
1210 * OK, this process has gone away; what's left?
1211 */
1212
1213 if (job->filters[i])
1214 job->filters[i] = -pid;
1215 else
1216 job->backend = -pid;
1217
1218 if (status && job->status >= 0)
1219 {
1220 /*
1221 * An error occurred; save the exit status so we know to stop
1222 * the printer or cancel the job when all of the filters finish...
1223 *
1224 * A negative status indicates that the backend failed and the
1225 * printer needs to be stopped.
1226 */
1227
1228 if (job->filters[i])
1229 job->status = status; /* Filter failed */
1230 else
1231 job->status = -status; /* Backend failed */
1232 }
1233
1234 /*
1235 * If this is not the last file in a job, see if all of the
1236 * filters are done, and if so move to the next file.
1237 */
1238
1239 if (job->current_file < job->num_files)
1240 {
1241 for (i = 0; job->filters[i] < 0; i ++);
1242
1243 if (!job->filters[i])
1244 {
1245 /*
1246 * Process the next file...
1247 */
1248
1249 cupsdFinishJob(job);
1250 }
1251 }
1252 break;
1253 }
1254 }
1255 }
1256}
1257
1258
1259/*
1260 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1261 */
1262
1263static void
1264sigchld_handler(int sig) /* I - Signal number */
1265{
1266 (void)sig;
1267
1268 /*
1269 * Flag that we have dead children...
1270 */
1271
1272 dead_children = 1;
1273
1274 /*
1275 * Reset the signal handler as needed...
1276 */
1277
1278#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1279 signal(SIGCLD, sigchld_handler);
1280#endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1281}
1282
1283
1284/*
1285 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1286 */
1287
1288static void
1289sighup_handler(int sig) /* I - Signal number */
1290{
1291 (void)sig;
1292
1293 NeedReload = RELOAD_ALL;
1294 ReloadTime = time(NULL);
1295
1296#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1297 signal(SIGHUP, sighup_handler);
1298#endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1299}
1300
1301
1302/*
1303 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1304 */
1305
1306static void
1307sigterm_handler(int sig) /* I - Signal */
1308{
1309 (void)sig; /* remove compiler warnings... */
1310
1311 /*
1312 * Flag that we should stop and return...
1313 */
1314
1315 stop_scheduler = 1;
1316}
1317
1318
1319/*
1320 * 'select_timeout()' - Calculate the select timeout value.
1321 *
1322 */
1323
1324static long /* O - Number of seconds */
1325select_timeout(int fds) /* I - Number of ready descriptors select returned */
1326{
1327 int i; /* Looping var */
1328 long timeout; /* Timeout for select */
1329 time_t now; /* Current time */
1330 cupsd_client_t *con; /* Client information */
1331 cupsd_printer_t *p; /* Printer information */
1332 cupsd_job_t *job; /* Job information */
1333 cupsd_subscription_t *sub; /* Subscription information */
1334 const char *why; /* Debugging aid */
1335
1336
1337 /*
1338 * Check to see if any of the clients have pending data to be
1339 * processed; if so, the timeout should be 0...
1340 */
1341
1342 for (i = NumClients, con = Clients; i > 0; i --, con ++)
1343 if (con->http.used > 0)
1344 return (0);
1345
1346 /*
1347 * If select has been active in the last second (fds != 0) or we have
1348 * many resources in use then don't bother trying to optimize the
1349 * timeout, just make it 1 second.
1350 */
1351
1352 if (fds || NumClients > 50)
1353 return (1);
1354
1355 /*
1356 * Otherwise, check all of the possible events that we need to wake for...
1357 */
1358
1359 now = time(NULL);
1360 timeout = now + 86400; /* 86400 == 1 day */
1361 why = "do nothing";
1362
1363 /*
1364 * Check the activity and close old clients...
1365 */
1366
1367 for (i = NumClients, con = Clients; i > 0; i --, con ++)
1368 if ((con->http.activity + Timeout) < timeout)
1369 {
1370 timeout = con->http.activity + Timeout;
1371 why = "timeout a client connection";
1372 }
1373
1374 /*
1375 * Update the browse list as needed...
1376 */
1377
1378 if (Browsing && BrowseLocalProtocols)
1379 {
1380#ifdef HAVE_LIBSLP
1381 if ((BrowseLocalProtocols & BROWSE_SLP) && (BrowseSLPRefresh < timeout))
1382 {
1383 timeout = BrowseSLPRefresh;
1384 why = "update SLP browsing";
1385 }
1386#endif /* HAVE_LIBSLP */
1387
1388 if (BrowseLocalProtocols & BROWSE_CUPS)
1389 {
1390 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
1391 p;
1392 p = (cupsd_printer_t *)cupsArrayNext(Printers))
1393 {
1394 if (p->type & CUPS_PRINTER_REMOTE)
1395 {
1396 if ((p->browse_time + BrowseTimeout) < timeout)
1397 {
1398 timeout = p->browse_time + BrowseTimeout;
1399 why = "browse timeout a printer";
1400 }
1401 }
1402 else if (!(p->type & CUPS_PRINTER_IMPLICIT))
1403 {
1404 if (BrowseInterval && (p->browse_time + BrowseInterval) < timeout)
1405 {
1406 timeout = p->browse_time + BrowseInterval;
1407 why = "send browse update";
1408 }
1409 }
1410 }
1411 }
1412 }
1413
1414 /*
1415 * Check for any active jobs...
1416 */
1417
1418 if (timeout > (now + 10) && ActiveJobs)
1419 {
1420 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
1421 job;
1422 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
1423 if (job->state->values[0].integer <= IPP_JOB_PROCESSING)
1424 {
1425 timeout = now + 10;
1426 why = "process active jobs";
1427 break;
1428 }
1429 }
1430
1431#ifdef HAVE_MALLINFO
1432 /*
1433 * Log memory usage every minute...
1434 */
1435
1436 if (LogLevel >= CUPSD_LOG_DEBUG && (mallinfo_time + 60) < timeout)
1437 {
1438 timeout = mallinfo_time + 60;
1439 why = "display memory usage";
1440 }
1441#endif /* HAVE_MALLINFO */
1442
1443 /*
1444 * Update the root certificate when needed...
1445 */
1446
1447 if (!RunUser && RootCertDuration &&
1448 (RootCertTime + RootCertDuration) < timeout)
1449 {
1450 timeout = RootCertTime + RootCertDuration;
1451 why = "update root certificate";
1452 }
1453
1454 /*
1455 * Expire subscriptions as needed...
1456 */
1457
1458 for (sub = (cupsd_subscription_t *)cupsArrayFirst(Subscriptions);
1459 sub;
1460 sub = (cupsd_subscription_t *)cupsArrayNext(Subscriptions))
1461 if (!sub->job && sub->expire < timeout)
1462 {
1463 timeout = sub->expire;
1464 why = "expire subscription";
1465 }
1466
1467 /*
1468 * Adjust from absolute to relative time. If p->browse_time above
1469 * was 0 then we can end up with a negative value here, so check.
1470 * We add 1 second to the timeout since events occur after the
1471 * timeout expires, and limit the timeout to 86400 seconds (1 day)
1472 * to avoid select() timeout limits present on some operating
1473 * systems...
1474 */
1475
1476 timeout = timeout - now + 1;
1477
1478 if (timeout < 1)
1479 timeout = 1;
1480 else if (timeout > 86400)
1481 timeout = 86400;
1482
1483 /*
1484 * Log and return the timeout value...
1485 */
1486
1487 cupsdLogMessage(CUPSD_LOG_DEBUG2, "select_timeout: %ld seconds to %s",
1488 timeout, why);
1489
1490 return (timeout);
1491}
1492
1493
1494/*
1495 * 'usage()' - Show scheduler usage.
1496 */
1497
1498static void
1499usage(void)
1500{
1501 fputs("Usage: cupsd [-c config-file] [-f] [-F]\n", stderr);
1502 exit(1);
1503}
1504
1505
1506/*
1507 * End of "$Id: main.c 4838 2005-11-14 18:34:27Z mike $".
1508 */