s3-spoolssd: Fix spoolss logging.
[mat/samba.git] / source3 / printing / spoolssd.c
1 /*
2    Unix SMB/Netbios implementation.
3    SPOOLSS Daemon
4    Copyright (C) Simo Sorce 2010
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19 #include "includes.h"
20 #include "serverid.h"
21 #include "smbd/smbd.h"
22
23 #include "messages.h"
24 #include "include/printing.h"
25 #include "printing/nt_printing_migrate_internal.h"
26 #include "printing/queue_process.h"
27 #include "printing/pcap.h"
28 #include "printing/load.h"
29 #include "ntdomain.h"
30 #include "librpc/gen_ndr/srv_winreg.h"
31 #include "librpc/gen_ndr/srv_spoolss.h"
32 #include "rpc_server/rpc_server.h"
33 #include "rpc_server/rpc_ep_register.h"
34 #include "rpc_server/spoolss/srv_spoolss_nt.h"
35 #include "librpc/rpc/dcerpc_ep.h"
36 #include "lib/server_prefork.h"
37
38 #define SPOOLSS_PIPE_NAME "spoolss"
39 #define DAEMON_NAME "spoolssd"
40
41 #define SPOOLSS_MIN_CHILDREN 5
42 #define SPOOLSS_MAX_CHILDREN 25
43 #define SPOOLSS_SPAWN_RATE 5
44 #define SPOOLSS_MIN_LIFE 60 /* 1 minute minimum life time */
45
46 #define SPOOLSS_INIT     0x00
47 #define SPOOLSS_NEW_MAX  0x01
48 #define SPOLLSS_ENOSPC   0x02
49
50 static struct prefork_pool *spoolss_pool;
51 static int spoolss_min_children;
52 static int spoolss_max_children;
53 static int spoolss_spawn_rate;
54 static int spoolss_prefork_status;
55 static int spoolss_child_id = 0;
56
57 pid_t start_spoolssd(struct tevent_context *ev_ctx,
58                      struct messaging_context *msg_ctx);
59
60 static void spoolss_prefork_config(void)
61 {
62         static int spoolss_prefork_config_init = false;
63         const char *prefork_str;
64         int min, max, rate;
65         bool use_defaults = false;
66         int ret;
67
68         if (!spoolss_prefork_config_init) {
69                 spoolss_pool = NULL;
70                 spoolss_prefork_status = SPOOLSS_INIT;
71                 spoolss_min_children = 0;
72                 spoolss_max_children = 0;
73                 spoolss_spawn_rate = 0;
74                 spoolss_prefork_config_init = true;
75         }
76
77         prefork_str = lp_parm_const_string(GLOBAL_SECTION_SNUM,
78                                            "spoolssd", "prefork", "none");
79         if (strcmp(prefork_str, "none") == 0) {
80                 use_defaults = true;
81         } else {
82                 ret = sscanf(prefork_str, "%d:%d:%d", &min, &max, &rate);
83                 if (ret != 3) {
84                         DEBUG(0, ("invalid format for spoolssd:prefork!\n"));
85                         use_defaults = true;
86                 }
87         }
88
89         if (use_defaults) {
90                 min = SPOOLSS_MIN_CHILDREN;
91                 max = SPOOLSS_MAX_CHILDREN;
92                 rate = SPOOLSS_SPAWN_RATE;
93         }
94
95         if (max > spoolss_max_children && spoolss_max_children != 0) {
96                 spoolss_prefork_status |= SPOOLSS_NEW_MAX;
97         }
98
99         spoolss_min_children = min;
100         spoolss_max_children = max;
101         spoolss_spawn_rate = rate;
102 }
103
104 static void spoolss_reopen_logs(int child_id)
105 {
106         char *lfile = lp_logfile();
107         char *ext;
108         int rc;
109
110         if (child_id) {
111                 rc = asprintf(&ext, "%s.%d", DAEMON_NAME, child_id);
112         } else {
113                 rc = asprintf(&ext, "%s", DAEMON_NAME);
114         }
115
116         if (rc == -1) {
117                 return;
118         }
119
120         rc = 0;
121         if (lfile == NULL || lfile[0] == '\0') {
122                 rc = asprintf(&lfile, "%s/log.%s",
123                               get_dyn_LOGFILEBASE(), ext);
124         } else {
125                 if (strstr(lfile, ext) == NULL) {
126                         if (child_id) {
127                                 rc = asprintf(&lfile, "%s.%d",
128                                               lp_logfile(), child_id);
129                         } else {
130                                 rc = asprintf(&lfile, "%s.%s",
131                                               lp_logfile(), ext);
132                         }
133                 }
134         }
135
136         if (rc > 0) {
137                 lp_set_logfile(lfile);
138                 SAFE_FREE(lfile);
139         }
140
141         SAFE_FREE(ext);
142
143         reopen_logs();
144 }
145
146 static void update_conf(struct tevent_context *ev,
147                         struct messaging_context *msg)
148 {
149         change_to_root_user();
150         lp_load(get_dyn_CONFIGFILE(), true, false, false, true);
151         reload_printers(ev, msg);
152
153         spoolss_reopen_logs(spoolss_child_id);
154         if (spoolss_child_id == 0) {
155                 spoolss_prefork_config();
156         }
157 }
158
159 static void smb_conf_updated(struct messaging_context *msg,
160                              void *private_data,
161                              uint32_t msg_type,
162                              struct server_id server_id,
163                              DATA_BLOB *data)
164 {
165         struct tevent_context *ev_ctx = talloc_get_type_abort(private_data,
166                                                              struct tevent_context);
167
168         DEBUG(10, ("Got message saying smb.conf was updated. Reloading.\n"));
169         update_conf(ev_ctx, msg);
170 }
171
172 static void update_pcap(struct tevent_context *ev_ctx,
173                         struct messaging_context *msg_ctx)
174 {
175         change_to_root_user();
176         reload_printers(ev_ctx, msg_ctx);
177 }
178
179 static void pcap_updated(struct messaging_context *msg,
180                          void *private_data,
181                          uint32_t msg_type,
182                          struct server_id server_id,
183                          DATA_BLOB *data)
184 {
185         struct tevent_context *ev_ctx;
186
187         ev_ctx = talloc_get_type_abort(private_data, struct tevent_context);
188
189         DEBUG(10, ("Got message that pcap updated. Reloading.\n"));
190         update_pcap(ev_ctx, msg);
191 }
192
193 static void spoolss_sig_term_handler(struct tevent_context *ev,
194                                      struct tevent_signal *se,
195                                      int signum,
196                                      int count,
197                                      void *siginfo,
198                                      void *private_data)
199 {
200         exit_server_cleanly("termination signal");
201 }
202
203 static void spoolss_setup_sig_term_handler(struct tevent_context *ev_ctx)
204 {
205         struct tevent_signal *se;
206
207         se = tevent_add_signal(ev_ctx,
208                                ev_ctx,
209                                SIGTERM, 0,
210                                spoolss_sig_term_handler,
211                                NULL);
212         if (!se) {
213                 exit_server("failed to setup SIGTERM handler");
214         }
215 }
216
217 static void spoolss_sig_hup_handler(struct tevent_context *ev,
218                                     struct tevent_signal *se,
219                                     int signum,
220                                     int count,
221                                     void *siginfo,
222                                     void *pvt)
223 {
224         struct messaging_context *msg_ctx;
225
226         msg_ctx = talloc_get_type_abort(pvt, struct messaging_context);
227
228         DEBUG(1,("Reloading printers after SIGHUP\n"));
229         update_conf(ev, msg_ctx);
230
231         /* relay to all children */
232         if (spoolss_pool) {
233                 prefork_send_signal_to_all(spoolss_pool, SIGHUP);
234         }
235 }
236
237 static void spoolss_setup_sig_hup_handler(struct tevent_context *ev_ctx,
238                                           struct messaging_context *msg_ctx)
239 {
240         struct tevent_signal *se;
241
242         se = tevent_add_signal(ev_ctx,
243                                ev_ctx,
244                                SIGHUP, 0,
245                                spoolss_sig_hup_handler,
246                                msg_ctx);
247         if (!se) {
248                 exit_server("failed to setup SIGHUP handler");
249         }
250 }
251
252 static bool spoolss_init_cb(void *ptr)
253 {
254         struct messaging_context *msg_ctx = talloc_get_type_abort(
255                 ptr, struct messaging_context);
256
257         return nt_printing_tdb_migrate(msg_ctx);
258 }
259
260 static bool spoolss_shutdown_cb(void *ptr)
261 {
262         srv_spoolss_cleanup();
263
264         return true;
265 }
266
267 /* Children */
268
269 struct spoolss_chld_sig_hup_ctx {
270         struct messaging_context *msg_ctx;
271         struct pf_worker_data *pf;
272 };
273
274 static void spoolss_chld_sig_hup_handler(struct tevent_context *ev,
275                                          struct tevent_signal *se,
276                                          int signum,
277                                          int count,
278                                          void *siginfo,
279                                          void *pvt)
280 {
281         struct spoolss_chld_sig_hup_ctx *shc;
282
283         shc = talloc_get_type_abort(pvt, struct spoolss_chld_sig_hup_ctx);
284
285         /* avoid wasting CPU cycles if we are going to exit soon anyways */
286         if (shc->pf != NULL &&
287             shc->pf->cmds == PF_SRV_MSG_EXIT) {
288                 return;
289         }
290
291         change_to_root_user();
292         DEBUG(1,("Reloading printers after SIGHUP\n"));
293         reload_printers(ev, shc->msg_ctx);
294         spoolss_reopen_logs(spoolss_child_id);
295 }
296
297 static bool spoolss_setup_chld_hup_handler(struct tevent_context *ev_ctx,
298                                            struct messaging_context *msg_ctx,
299                                            struct pf_worker_data *pf)
300 {
301         struct spoolss_chld_sig_hup_ctx *shc;
302         struct tevent_signal *se;
303
304         shc = talloc(ev_ctx, struct spoolss_chld_sig_hup_ctx);
305         if (!shc) {
306                 DEBUG(1, ("failed to setup SIGHUP handler"));
307                 return false;
308         }
309         shc->pf = pf;
310         shc->msg_ctx = msg_ctx;
311
312         se = tevent_add_signal(ev_ctx,
313                                ev_ctx,
314                                SIGHUP, 0,
315                                spoolss_chld_sig_hup_handler,
316                                shc);
317         if (!se) {
318                 DEBUG(1, ("failed to setup SIGHUP handler"));
319                 return false;
320         }
321
322         return true;
323 }
324
325 static bool spoolss_child_init(struct tevent_context *ev_ctx,
326                                int child_id, struct pf_worker_data *pf)
327 {
328         NTSTATUS status;
329         struct rpc_srv_callbacks spoolss_cb;
330         struct messaging_context *msg_ctx = server_messaging_context();
331         bool ok;
332
333         status = reinit_after_fork(msg_ctx, ev_ctx,
334                                    procid_self(), true);
335         if (!NT_STATUS_IS_OK(status)) {
336                 DEBUG(0,("reinit_after_fork() failed\n"));
337                 smb_panic("reinit_after_fork() failed");
338         }
339
340         spoolss_child_id = child_id;
341         spoolss_reopen_logs(child_id);
342
343         ok = spoolss_setup_chld_hup_handler(ev_ctx, msg_ctx, pf);
344         if (!ok) {
345                 return false;
346         }
347
348         if (!serverid_register(procid_self(),
349                                 FLAG_MSG_GENERAL |
350                                 FLAG_MSG_PRINT_GENERAL)) {
351                 return false;
352         }
353
354         if (!locking_init()) {
355                 return false;
356         }
357
358         messaging_register(msg_ctx, ev_ctx,
359                            MSG_SMB_CONF_UPDATED, smb_conf_updated);
360         messaging_register(msg_ctx, ev_ctx, MSG_PRINTER_PCAP,
361                            pcap_updated);
362
363         /* As soon as messaging is up check if pcap has been loaded already.
364          * If so then we probably missed a message and should load_printers()
365          * ourselves. If pcap has not been loaded yet, then ignore, we will get
366          * a message as soon as the bq process completes the reload. */
367         if (pcap_cache_loaded()) {
368                 load_printers(ev_ctx, msg_ctx);
369         }
370
371         /* try to reinit rpc queues */
372         spoolss_cb.init = spoolss_init_cb;
373         spoolss_cb.shutdown = spoolss_shutdown_cb;
374         spoolss_cb.private_data = msg_ctx;
375
376         status = rpc_winreg_init(NULL);
377         if (!NT_STATUS_IS_OK(status)) {
378                 DEBUG(0, ("Failed to register winreg rpc inteface! (%s)\n",
379                           nt_errstr(status)));
380                 return false;
381         }
382
383         status = rpc_spoolss_init(&spoolss_cb);
384         if (!NT_STATUS_IS_OK(status)) {
385                 DEBUG(0, ("Failed to register spoolss rpc inteface! (%s)\n",
386                           nt_errstr(status)));
387                 return false;
388         }
389
390         return true;
391 }
392
393 struct spoolss_children_data {
394         struct tevent_context *ev_ctx;
395         struct messaging_context *msg_ctx;
396         struct pf_worker_data *pf;
397         int listen_fd_size;
398         int *listen_fds;
399         int lock_fd;
400
401         bool listening;
402 };
403
404 static void spoolss_next_client(void *pvt);
405
406 static int spoolss_children_main(struct tevent_context *ev_ctx,
407                                  struct messaging_context *msg_ctx,
408                                  struct pf_worker_data *pf,
409                                  int child_id,
410                                  int listen_fd_size,
411                                  int *listen_fds,
412                                  int lock_fd,
413                                  void *private_data)
414 {
415         struct spoolss_children_data *data;
416         bool ok;
417         int ret;
418
419         ok = spoolss_child_init(ev_ctx, child_id, pf);
420         if (!ok) {
421                 return 1;
422         }
423
424         data = talloc(ev_ctx, struct spoolss_children_data);
425         if (!data) {
426                 return 1;
427         }
428         data->pf = pf;
429         data->ev_ctx = ev_ctx;
430         data->msg_ctx = msg_ctx;
431         data->lock_fd = lock_fd;
432         data->listen_fd_size = listen_fd_size;
433         data->listen_fds = listen_fds;
434         data->listening = false;
435
436         /* loop until it is time to exit */
437         while (pf->status != PF_WORKER_EXITING) {
438                 /* try to see if it is time to schedule the next client */
439                 spoolss_next_client(data);
440
441                 ret = tevent_loop_once(ev_ctx);
442                 if (ret != 0) {
443                         DEBUG(0, ("tevent_loop_once() exited with %d: %s\n",
444                                   ret, strerror(errno)));
445                         pf->status = PF_WORKER_EXITING;
446                 }
447         }
448
449         return ret;
450 }
451
452 static void spoolss_client_terminated(void *pvt)
453 {
454         struct spoolss_children_data *data;
455
456         data = talloc_get_type_abort(pvt, struct spoolss_children_data);
457
458         if (data->pf->num_clients) {
459                 data->pf->num_clients--;
460         } else {
461                 DEBUG(2, ("Invalid num clients, aborting!\n"));
462                 data->pf->status = PF_WORKER_EXITING;
463                 return;
464         }
465
466         spoolss_next_client(pvt);
467 }
468
469 struct spoolss_new_client {
470         struct spoolss_children_data *data;
471         struct tsocket_address *srv_addr;
472         struct tsocket_address *cli_addr;
473 };
474
475 static void spoolss_handle_client(struct tevent_req *req);
476
477 static void spoolss_next_client(void *pvt)
478 {
479         struct tevent_req *req;
480         struct spoolss_children_data *data;
481         struct spoolss_new_client *next;
482
483         data = talloc_get_type_abort(pvt, struct spoolss_children_data);
484
485         if (data->pf->num_clients == 0) {
486                 data->pf->status = PF_WORKER_IDLE;
487         }
488
489         if (data->pf->cmds == PF_SRV_MSG_EXIT) {
490                 DEBUG(2, ("Parent process commands we terminate!\n"));
491                 return;
492         }
493
494         if (data->listening ||
495             data->pf->num_clients >= data->pf->allowed_clients) {
496                 /* nothing to do for now we are already listening
497                  * or reached the number of clients we are allowed
498                  * to handle in parallel */
499                 return;
500         }
501
502         next = talloc_zero(data, struct spoolss_new_client);
503         if (!next) {
504                 DEBUG(1, ("Out of memory!?\n"));
505                 return;
506         }
507         next->data = data;
508
509         req = prefork_listen_send(next, data->ev_ctx, data->pf,
510                                   data->listen_fd_size,
511                                   data->listen_fds,
512                                   data->lock_fd);
513         if (!req) {
514                 DEBUG(1, ("Failed to make listening request!?\n"));
515                 talloc_free(next);
516                 return;
517         }
518         tevent_req_set_callback(req, spoolss_handle_client, next);
519
520         data->listening = true;
521 }
522
523 static void spoolss_handle_client(struct tevent_req *req)
524 {
525         struct spoolss_children_data *data;
526         struct spoolss_new_client *client;
527         int ret;
528         int sd;
529
530         client = tevent_req_callback_data(req, struct spoolss_new_client);
531         data = client->data;
532
533         ret = prefork_listen_recv(req, client, &sd,
534                                   &client->srv_addr, &client->cli_addr);
535
536         /* this will free the request too */
537         talloc_free(client);
538         /* we are done listening */
539         data->listening = false;
540
541         if (ret > 0) {
542                 DEBUG(1, ("Failed to accept client connection!\n"));
543                 /* bail out if we are not serving any other client */
544                 if (data->pf->num_clients == 0) {
545                         data->pf->status = PF_WORKER_EXITING;
546                 }
547                 return;
548         }
549
550         if (ret == -2) {
551                 DEBUG(1, ("Server asks us to die!\n"));
552                 data->pf->status = PF_WORKER_EXITING;
553                 return;
554         }
555
556         DEBUG(2, ("Spoolss preforked child %d got client connection!\n",
557                   (int)(data->pf->pid)));
558
559         named_pipe_accept_function(data->ev_ctx, data->msg_ctx,
560                                    SPOOLSS_PIPE_NAME, sd,
561                                    spoolss_client_terminated, data);
562 }
563
564 /* ==== Main Process Functions ==== */
565
566 extern pid_t background_lpq_updater_pid;
567 static char *bq_logfile;
568
569 static void check_updater_child(void)
570 {
571         int status;
572         pid_t pid;
573
574         if (background_lpq_updater_pid == -1) {
575                 return;
576         }
577
578         pid = sys_waitpid(background_lpq_updater_pid, &status, WNOHANG);
579         if (pid > 0) {
580                 DEBUG(2, ("The background queue child died... Restarting!\n"));
581                 pid = start_background_queue(server_event_context(),
582                                              server_messaging_context(),
583                                              bq_logfile);
584                 background_lpq_updater_pid = pid;
585         }
586 }
587
588 static bool spoolssd_schedule_check(struct tevent_context *ev_ctx,
589                                     struct messaging_context *msg_ctx,
590                                     struct timeval current_time);
591 static void spoolssd_check_children(struct tevent_context *ev_ctx,
592                                     struct tevent_timer *te,
593                                     struct timeval current_time,
594                                     void *pvt);
595
596 static void spoolssd_sigchld_handler(struct tevent_context *ev_ctx,
597                                      struct prefork_pool *pfp,
598                                      void *pvt)
599 {
600         struct messaging_context *msg_ctx;
601         int active, total;
602         int n, r;
603
604         msg_ctx = talloc_get_type_abort(pvt, struct messaging_context);
605
606         /* now check we do not descend below the minimum */
607         active = prefork_count_active_children(pfp, &total);
608
609         n = 0;
610         if (total < spoolss_min_children) {
611                 n = total - spoolss_min_children;
612         } else if (total - active < (total / 4)) {
613                 n = spoolss_min_children;
614         }
615
616         if (n > 0) {
617                 r = prefork_add_children(ev_ctx, msg_ctx, pfp, n);
618                 if (r < n) {
619                         DEBUG(10, ("Tried to start %d children but only,"
620                                    "%d were actually started.!\n", n, r));
621                 }
622         }
623
624         /* also check if the updater child is alive and well */
625         check_updater_child();
626 }
627
628 static bool spoolssd_setup_children_monitor(struct tevent_context *ev_ctx,
629                                             struct messaging_context *msg_ctx)
630 {
631         bool ok;
632
633         /* add our oun sigchld callback */
634         prefork_set_sigchld_callback(spoolss_pool,
635                                      spoolssd_sigchld_handler, msg_ctx);
636
637         ok = spoolssd_schedule_check(ev_ctx, msg_ctx,
638                                      tevent_timeval_current());
639         return ok;
640 }
641
642 static bool spoolssd_schedule_check(struct tevent_context *ev_ctx,
643                                     struct messaging_context *msg_ctx,
644                                     struct timeval current_time)
645 {
646         struct tevent_timer *te;
647         struct timeval next_event;
648
649         /* check situation again in 10 seconds */
650         next_event = tevent_timeval_current_ofs(10, 0);
651
652         /* TODO: check when the socket becomes readable, so that children
653          * are checked only when there is some activity ? */
654         te = tevent_add_timer(ev_ctx, spoolss_pool, next_event,
655                                 spoolssd_check_children, msg_ctx);
656         if (!te) {
657                 DEBUG(2, ("Failed to set up children monitoring!\n"));
658                 return false;
659         }
660
661         return true;
662 }
663
664 static void spoolssd_check_children(struct tevent_context *ev_ctx,
665                                     struct tevent_timer *te,
666                                     struct timeval current_time,
667                                     void *pvt)
668 {
669         struct messaging_context *msg_ctx;
670         time_t now = time(NULL);
671         int active, total;
672         int ret, n;
673
674         msg_ctx = talloc_get_type_abort(pvt, struct messaging_context);
675
676         if ((spoolss_prefork_status & SPOOLSS_NEW_MAX) &&
677             !(spoolss_prefork_status & SPOLLSS_ENOSPC)) {
678                 ret = prefork_expand_pool(spoolss_pool, spoolss_max_children);
679                 if (ret == ENOSPC) {
680                         spoolss_prefork_status |= SPOLLSS_ENOSPC;
681                 }
682                 spoolss_prefork_status &= ~SPOOLSS_NEW_MAX;
683         }
684
685         active = prefork_count_active_children(spoolss_pool, &total);
686
687         if (total - active < spoolss_spawn_rate) {
688                 n = prefork_add_children(ev_ctx, msg_ctx,
689                                          spoolss_pool, spoolss_spawn_rate);
690                 if (n < spoolss_spawn_rate) {
691                         DEBUG(10, ("Tried to start 5 children but only,"
692                                    "%d were actually started.!\n", n));
693                 }
694         }
695
696         if (total - active > spoolss_min_children) {
697                 if ((total - spoolss_min_children) >= spoolss_spawn_rate) {
698                         prefork_retire_children(spoolss_pool,
699                                                 spoolss_spawn_rate,
700                                                 now - SPOOLSS_MIN_LIFE);
701                 }
702         }
703
704         ret = spoolssd_schedule_check(ev_ctx, msg_ctx, current_time);
705 }
706
707 static void print_queue_forward(struct messaging_context *msg,
708                                 void *private_data,
709                                 uint32_t msg_type,
710                                 struct server_id server_id,
711                                 DATA_BLOB *data)
712 {
713         messaging_send_buf(msg, pid_to_procid(background_lpq_updater_pid),
714                            MSG_PRINTER_UPDATE, data->data, data->length);
715 }
716
717 static char *get_bq_logfile(void)
718 {
719         char *lfile = lp_logfile();
720         int rc;
721
722         if (lfile == NULL || lfile[0] == '\0') {
723                 rc = asprintf(&lfile, "%s/log.%s.bq",
724                                         get_dyn_LOGFILEBASE(), DAEMON_NAME);
725         } else {
726                 rc = asprintf(&lfile, "%s.bq", lp_logfile());
727         }
728         if (rc == -1) {
729                 lfile = NULL;
730         }
731         return lfile;
732 }
733
734 pid_t start_spoolssd(struct tevent_context *ev_ctx,
735                     struct messaging_context *msg_ctx)
736 {
737         struct rpc_srv_callbacks spoolss_cb;
738         struct dcerpc_binding_vector *v;
739         TALLOC_CTX *mem_ctx;
740         pid_t pid;
741         NTSTATUS status;
742         int listen_fd;
743         int ret;
744         bool ok;
745
746         DEBUG(1, ("Forking SPOOLSS Daemon\n"));
747
748         /*
749          * Block signals before forking child as it will have to
750          * set its own handlers. Child will re-enable SIGHUP as
751          * soon as the handlers are set up.
752          */
753         BlockSignals(true, SIGTERM);
754         BlockSignals(true, SIGHUP);
755
756         pid = sys_fork();
757
758         if (pid == -1) {
759                 DEBUG(0, ("Failed to fork SPOOLSS [%s]\n",
760                            strerror(errno)));
761         }
762
763         /* parent or error */
764         if (pid != 0) {
765
766                 /* Re-enable SIGHUP before returnig */
767                 BlockSignals(false, SIGTERM);
768                 BlockSignals(false, SIGHUP);
769                 return pid;
770         }
771
772         /* child */
773         close_low_fds(false);
774
775         status = reinit_after_fork(msg_ctx,
776                                    ev_ctx,
777                                    procid_self(), true);
778         if (!NT_STATUS_IS_OK(status)) {
779                 DEBUG(0,("reinit_after_fork() failed\n"));
780                 smb_panic("reinit_after_fork() failed");
781         }
782
783         spoolss_reopen_logs(0);
784         spoolss_prefork_config();
785
786         spoolss_setup_sig_term_handler(ev_ctx);
787         spoolss_setup_sig_hup_handler(ev_ctx, msg_ctx);
788
789         BlockSignals(false, SIGTERM);
790         BlockSignals(false, SIGHUP);
791
792         /* always start the backgroundqueue listner in spoolssd */
793         bq_logfile = get_bq_logfile();
794         pid = start_background_queue(ev_ctx, msg_ctx, bq_logfile);
795         if (pid > 0) {
796                 background_lpq_updater_pid = pid;
797         }
798
799         /* the listening fd must be created before the children are actually
800          * forked out. */
801         listen_fd = create_named_pipe_socket(SPOOLSS_PIPE_NAME);
802         if (listen_fd == -1) {
803                 exit(1);
804         }
805
806         ret = listen(listen_fd, spoolss_max_children);
807         if (ret == -1) {
808                 DEBUG(0, ("Failed to listen on spoolss pipe - %s\n",
809                           strerror(errno)));
810                 exit(1);
811         }
812
813         /* start children before any more initialization is done */
814         ok = prefork_create_pool(ev_ctx, /* mem_ctx */
815                                  ev_ctx, msg_ctx,
816                                  1, &listen_fd,
817                                  spoolss_min_children,
818                                  spoolss_max_children,
819                                  &spoolss_children_main, NULL,
820                                  &spoolss_pool);
821         if (!ok) {
822                 exit(1);
823         }
824
825         if (!serverid_register(procid_self(),
826                                 FLAG_MSG_GENERAL |
827                                 FLAG_MSG_PRINT_GENERAL)) {
828                 exit(1);
829         }
830
831         if (!locking_init()) {
832                 exit(1);
833         }
834
835         messaging_register(msg_ctx, ev_ctx,
836                            MSG_SMB_CONF_UPDATED, smb_conf_updated);
837         messaging_register(msg_ctx, NULL, MSG_PRINTER_UPDATE,
838                            print_queue_forward);
839         messaging_register(msg_ctx, ev_ctx, MSG_PRINTER_PCAP,
840                            pcap_updated);
841
842         /* As soon as messaging is up check if pcap has been loaded already.
843          * If so then we probably missed a message and should load_printers()
844          * ourselves. If pcap has not been loaded yet, then ignore, we will get
845          * a message as soon as the bq process completes the reload. */
846         if (pcap_cache_loaded()) {
847                 load_printers(ev_ctx, msg_ctx);
848         }
849
850         mem_ctx = talloc_new(NULL);
851         if (mem_ctx == NULL) {
852                 exit(1);
853         }
854
855         /*
856          * Initialize spoolss with an init function to convert printers first.
857          * static_init_rpc will try to initialize the spoolss server too but you
858          * can't register it twice.
859          */
860         spoolss_cb.init = spoolss_init_cb;
861         spoolss_cb.shutdown = spoolss_shutdown_cb;
862         spoolss_cb.private_data = msg_ctx;
863
864         status = rpc_winreg_init(NULL);
865         if (!NT_STATUS_IS_OK(status)) {
866                 DEBUG(0, ("Failed to register winreg rpc inteface! (%s)\n",
867                           nt_errstr(status)));
868                 exit(1);
869         }
870
871         status = rpc_spoolss_init(&spoolss_cb);
872         if (!NT_STATUS_IS_OK(status)) {
873                 DEBUG(0, ("Failed to register spoolss rpc inteface! (%s)\n",
874                           nt_errstr(status)));
875                 exit(1);
876         }
877
878         status = dcerpc_binding_vector_new(mem_ctx, &v);
879         if (!NT_STATUS_IS_OK(status)) {
880                 DEBUG(0, ("Failed to create binding vector (%s)\n",
881                           nt_errstr(status)));
882                 exit(1);
883         }
884
885         status = dcerpc_binding_vector_add_np_default(&ndr_table_spoolss, v);
886         if (!NT_STATUS_IS_OK(status)) {
887                 DEBUG(0, ("Failed to add np to binding vector (%s)\n",
888                           nt_errstr(status)));
889                 exit(1);
890         }
891
892         status = rpc_ep_register(ev_ctx, msg_ctx, &ndr_table_spoolss, v);
893         if (!NT_STATUS_IS_OK(status)) {
894                 DEBUG(0, ("Failed to register spoolss endpoint! (%s)\n",
895                           nt_errstr(status)));
896                 exit(1);
897         }
898
899         talloc_free(mem_ctx);
900
901         ok = spoolssd_setup_children_monitor(ev_ctx, msg_ctx);
902         if (!ok) {
903                 DEBUG(0, ("Failed to setup children monitoring!\n"));
904                 exit(1);
905         }
906
907         DEBUG(1, ("SPOOLSS Daemon Started (%d)\n", getpid()));
908
909         /* loop forever */
910         ret = tevent_loop_wait(ev_ctx);
911
912         /* should not be reached */
913         DEBUG(0,("spoolssd tevent_loop_wait() exited with %d - %s\n",
914                  ret, (ret == 0) ? "out of events" : strerror(errno)));
915         exit(1);
916 }