printing: use housekeeping period that matches cache time
[gd/samba-autobuild/.git] / source3 / printing / queue_process.c
1 /*
2    Unix SMB/Netbios implementation.
3    Version 3.0
4    printing backend routines
5    Copyright (C) Andrew Tridgell 1992-2000
6    Copyright (C) Jeremy Allison 2002
7    Copyright (C) Simo Sorce 2011
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "smbd/globals.h"
25 #include "include/messages.h"
26 #include "lib/util/util_process.h"
27 #include "printing.h"
28 #include "printing/pcap.h"
29 #include "printing/queue_process.h"
30 #include "serverid.h"
31 #include "locking/proto.h"
32 #include "smbd/smbd.h"
33 #include "rpc_server/rpc_config.h"
34 #include "printing/load.h"
35 #include "rpc_server/spoolss/srv_spoolss_nt.h"
36 #include "auth.h"
37 #include "nt_printing.h"
38
39 extern pid_t start_spoolssd(struct tevent_context *ev_ctx,
40                             struct messaging_context *msg_ctx);
41
42 /**
43  * @brief Purge stale printers and reload from pre-populated pcap cache.
44  *
45  * This function should normally only be called as a callback on a successful
46  * pcap_cache_reload().
47  *
48  * This function can cause DELETION of printers and drivers from our registry,
49  * so calling it on a failed pcap reload may REMOVE permanently all printers
50  * and drivers.
51  *
52  * @param[in] ev        The event context.
53  *
54  * @param[in] msg_ctx   The messaging context.
55  */
56 static void delete_and_reload_printers_full(struct tevent_context *ev,
57                                             struct messaging_context *msg_ctx)
58 {
59         struct auth_session_info *session_info = NULL;
60         struct spoolss_PrinterInfo2 *pinfo2 = NULL;
61         int n_services;
62         int pnum;
63         int snum;
64         const char *pname;
65         const char *sname;
66         NTSTATUS status;
67
68         n_services = lp_numservices();
69         pnum = lp_servicenumber(PRINTERS_NAME);
70
71         status = make_session_info_system(talloc_tos(), &session_info);
72         if (!NT_STATUS_IS_OK(status)) {
73                 DEBUG(3, ("reload_printers: "
74                           "Could not create system session_info\n"));
75                 /* can't remove stale printers before we
76                  * are fully initilized */
77                 return;
78         }
79
80         /*
81          * Add default config for printers added to smb.conf file and remove
82          * stale printers
83          */
84         for (snum = 0; snum < n_services; snum++) {
85                 /* avoid removing PRINTERS_NAME */
86                 if (snum == pnum) {
87                         continue;
88                 }
89
90                 /* skip no-printer services */
91                 if (!snum_is_shared_printer(snum)) {
92                         continue;
93                 }
94
95                 sname = lp_const_servicename(snum);
96                 pname = lp_printername(session_info, snum);
97
98                 /* check printer, but avoid removing non-autoloaded printers */
99                 if (lp_autoloaded(snum) && !pcap_printername_ok(pname)) {
100                         DEBUG(3, ("removing stale printer %s\n", pname));
101
102                         if (is_printer_published(session_info, session_info,
103                                                  msg_ctx,
104                                                  NULL,
105                                                  lp_servicename(session_info,
106                                                                 snum),
107                                                  &pinfo2)) {
108                                 nt_printer_publish(session_info,
109                                                    session_info,
110                                                    msg_ctx,
111                                                    pinfo2,
112                                                    DSPRINT_UNPUBLISH);
113                                 TALLOC_FREE(pinfo2);
114                         }
115                         nt_printer_remove(session_info, session_info, msg_ctx,
116                                           pname);
117                 } else {
118                         DEBUG(8, ("Adding default registry entry for printer "
119                                   "[%s], if it doesn't exist.\n", sname));
120                         nt_printer_add(session_info, session_info, msg_ctx,
121                                        sname);
122                 }
123         }
124
125         /* finally, purge old snums */
126         delete_and_reload_printers(ev, msg_ctx);
127
128         TALLOC_FREE(session_info);
129 }
130
131
132 /****************************************************************************
133  Notify smbds of new printcap data
134 **************************************************************************/
135 static void reload_pcap_change_notify(struct tevent_context *ev,
136                                struct messaging_context *msg_ctx)
137 {
138         /*
139          * Reload the printers first in the background process so that
140          * newly added printers get default values created in the registry.
141          *
142          * This will block the process for some time (~1 sec per printer), but
143          * it doesn't block smbd's servering clients.
144          */
145         delete_and_reload_printers_full(ev, msg_ctx);
146
147         message_send_all(msg_ctx, MSG_PRINTER_PCAP, NULL, 0, NULL);
148 }
149
150 struct printing_queue_housekeeping_state {
151         struct tevent_context *ev;
152         struct messaging_context *msg;
153 };
154
155 static bool print_queue_housekeeping(const struct timeval *now, void *pvt)
156 {
157         struct printing_queue_housekeeping_state *state =
158                 talloc_get_type_abort(pvt,
159                 struct printing_queue_housekeeping_state);
160
161         DEBUG(5, ("print queue housekeeping\n"));
162         pcap_cache_reload(state->ev, state->msg, &reload_pcap_change_notify);
163
164         return true;
165 }
166
167 static bool printing_subsystem_queue_tasks(struct tevent_context *ev_ctx,
168                                            struct messaging_context *msg_ctx)
169 {
170         struct printing_queue_housekeeping_state *state;
171         uint32_t housekeeping_period = lp_printcap_cache_time();
172
173         state = talloc_zero(ev_ctx, struct printing_queue_housekeeping_state);
174         if (state == NULL) {
175                 DEBUG(0,("Could not talloc printing_queue_housekeeping_state\n"));
176                 return false;
177         }
178         state->ev = ev_ctx;
179         state->msg = msg_ctx;
180
181         if (housekeeping_period == 0) {
182                 DEBUG(4, ("background print queue housekeeping disabled\n"));
183                 return true;
184         }
185
186         if (!(event_add_idle(ev_ctx, NULL,
187                              timeval_set(housekeeping_period, 0),
188                              "print_queue_housekeeping",
189                              print_queue_housekeeping,
190                              state))) {
191                 DEBUG(0,("Could not add print_queue_housekeeping event\n"));
192                 return false;
193         }
194
195         return true;
196 }
197
198 static void bq_reopen_logs(char *logfile)
199 {
200         if (logfile) {
201                 lp_set_logfile(logfile);
202         }
203         reopen_logs();
204 }
205
206 static void bq_sig_term_handler(struct tevent_context *ev,
207                                 struct tevent_signal *se,
208                                 int signum,
209                                 int count,
210                                 void *siginfo,
211                                 void *private_data)
212 {
213         exit_server_cleanly("termination signal");
214 }
215
216 static void bq_setup_sig_term_handler(void)
217 {
218         struct tevent_signal *se;
219
220         se = tevent_add_signal(server_event_context(),
221                                server_event_context(),
222                                SIGTERM, 0,
223                                bq_sig_term_handler,
224                                NULL);
225         if (!se) {
226                 exit_server("failed to setup SIGTERM handler");
227         }
228 }
229
230 static void bq_sig_hup_handler(struct tevent_context *ev,
231                                 struct tevent_signal *se,
232                                 int signum,
233                                 int count,
234                                 void *siginfo,
235                                 void *pvt)
236 {
237         struct messaging_context *msg_ctx;
238
239         msg_ctx = talloc_get_type_abort(pvt, struct messaging_context);
240         change_to_root_user();
241
242         DEBUG(1, ("Reloading pcap cache after SIGHUP\n"));
243         pcap_cache_reload(ev, msg_ctx, &reload_pcap_change_notify);
244         bq_reopen_logs(NULL);
245 }
246
247 static void bq_setup_sig_hup_handler(struct tevent_context *ev,
248                                      struct messaging_context *msg_ctx)
249 {
250         struct tevent_signal *se;
251
252         se = tevent_add_signal(ev, ev, SIGHUP, 0, bq_sig_hup_handler,
253                                msg_ctx);
254         if (!se) {
255                 exit_server("failed to setup SIGHUP handler");
256         }
257 }
258
259 static void bq_sig_chld_handler(struct tevent_context *ev_ctx,
260                                 struct tevent_signal *se,
261                                 int signum, int count,
262                                 void *siginfo, void *pvt)
263 {
264         int status;
265         pid_t pid;
266
267         pid = waitpid(-1, &status, WNOHANG);
268         if (WIFEXITED(status)) {
269                 DEBUG(6, ("Bq child process %d terminated with %d\n",
270                           (int)pid, WEXITSTATUS(status)));
271         } else {
272                 DEBUG(3, ("Bq child process %d terminated abnormally\n",
273                           (int)pid));
274         }
275 }
276
277 static void bq_setup_sig_chld_handler(struct tevent_context *ev_ctx)
278 {
279         struct tevent_signal *se;
280
281         se = tevent_add_signal(ev_ctx, ev_ctx, SIGCHLD, 0,
282                                 bq_sig_chld_handler, NULL);
283         if (!se) {
284                 exit_server("failed to setup SIGCHLD handler");
285         }
286 }
287
288 static void bq_smb_conf_updated(struct messaging_context *msg_ctx,
289                                 void *private_data,
290                                 uint32_t msg_type,
291                                 struct server_id server_id,
292                                 DATA_BLOB *data)
293 {
294         struct tevent_context *ev_ctx =
295                 talloc_get_type_abort(private_data, struct tevent_context);
296
297         DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
298                   "updated. Reloading.\n"));
299         change_to_root_user();
300         pcap_cache_reload(ev_ctx, msg_ctx, &reload_pcap_change_notify);
301 }
302
303 static void printing_pause_fd_handler(struct tevent_context *ev,
304                                       struct tevent_fd *fde,
305                                       uint16_t flags,
306                                       void *private_data)
307 {
308         /*
309          * If pause_pipe[1] is closed it means the parent smbd
310          * and children exited or aborted.
311          */
312         exit_server_cleanly(NULL);
313 }
314
315 /****************************************************************************
316 main thread of the background lpq updater
317 ****************************************************************************/
318 pid_t start_background_queue(struct tevent_context *ev,
319                              struct messaging_context *msg_ctx,
320                              char *logfile)
321 {
322         pid_t pid;
323
324         /* Use local variables for this as we don't
325          * need to save the parent side of this, just
326          * ensure it closes when the process exits.
327          */
328         int pause_pipe[2];
329
330         DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
331
332         if (pipe(pause_pipe) == -1) {
333                 DEBUG(5,("start_background_queue: cannot create pipe. %s\n", strerror(errno) ));
334                 exit(1);
335         }
336
337         /*
338          * Block signals before forking child as it will have to
339          * set its own handlers. Child will re-enable SIGHUP as
340          * soon as the handlers are set up.
341          */
342         BlockSignals(true, SIGTERM);
343         BlockSignals(true, SIGHUP);
344
345         pid = fork();
346
347         /* parent or error */
348         if (pid != 0) {
349                 /* Re-enable SIGHUP before returnig */
350                 BlockSignals(false, SIGTERM);
351                 BlockSignals(false, SIGHUP);
352                 return pid;
353         }
354
355         if (pid == -1) {
356                 DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
357                 exit(1);
358         }
359
360         if (pid == 0) {
361                 struct tevent_fd *fde;
362                 int ret;
363                 NTSTATUS status;
364
365                 /* Child. */
366                 DEBUG(5,("start_background_queue: background LPQ thread started\n"));
367
368                 close(pause_pipe[0]);
369                 pause_pipe[0] = -1;
370
371                 status = smbd_reinit_after_fork(msg_ctx, ev, true, "lpqd");
372
373                 if (!NT_STATUS_IS_OK(status)) {
374                         DEBUG(0,("reinit_after_fork() failed\n"));
375                         smb_panic("reinit_after_fork() failed");
376                 }
377
378                 bq_reopen_logs(logfile);
379                 bq_setup_sig_term_handler();
380                 bq_setup_sig_hup_handler(ev, msg_ctx);
381                 bq_setup_sig_chld_handler(ev);
382
383                 BlockSignals(false, SIGTERM);
384                 BlockSignals(false, SIGHUP);
385
386                 if (!printing_subsystem_queue_tasks(ev, msg_ctx)) {
387                         exit(1);
388                 }
389
390                 if (!serverid_register(messaging_server_id(msg_ctx),
391                                        FLAG_MSG_GENERAL |
392                                        FLAG_MSG_PRINT_GENERAL)) {
393                         exit(1);
394                 }
395
396                 if (!locking_init()) {
397                         exit(1);
398                 }
399                 messaging_register(msg_ctx, ev, MSG_SMB_CONF_UPDATED,
400                                    bq_smb_conf_updated);
401                 messaging_register(msg_ctx, NULL, MSG_PRINTER_UPDATE,
402                                    print_queue_receive);
403                 /* Remove previous forwarder message set in parent. */
404                 messaging_deregister(msg_ctx, MSG_PRINTER_DRVUPGRADE, NULL);
405
406                 messaging_register(msg_ctx, NULL, MSG_PRINTER_DRVUPGRADE,
407                                    do_drv_upgrade_printer);
408
409                 fde = tevent_add_fd(ev, ev, pause_pipe[1], TEVENT_FD_READ,
410                                     printing_pause_fd_handler,
411                                     NULL);
412                 if (!fde) {
413                         DEBUG(0,("tevent_add_fd() failed for pause_pipe\n"));
414                         smb_panic("tevent_add_fd() failed for pause_pipe");
415                 }
416
417                 pcap_cache_reload(ev, msg_ctx, &reload_pcap_change_notify);
418
419                 DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
420                 ret = tevent_loop_wait(ev);
421                 /* should not be reached */
422                 DEBUG(0,("background_queue: tevent_loop_wait() exited with %d - %s\n",
423                          ret, (ret == 0) ? "out of events" : strerror(errno)));
424                 exit(1);
425         }
426
427         close(pause_pipe[1]);
428
429         return pid;
430 }
431
432 /* Run before the parent forks */
433 bool printing_subsystem_init(struct tevent_context *ev_ctx,
434                              struct messaging_context *msg_ctx,
435                              bool start_daemons,
436                              bool background_queue)
437 {
438         pid_t pid = -1;
439
440         if (!print_backend_init(msg_ctx)) {
441                 return false;
442         }
443
444         /* start spoolss daemon */
445         /* start as a separate daemon only if enabled */
446         if (start_daemons && rpc_spoolss_daemon() == RPC_DAEMON_FORK) {
447
448                 pid = start_spoolssd(ev_ctx, msg_ctx);
449
450         } else if (start_daemons && background_queue) {
451
452                 pid = start_background_queue(ev_ctx, msg_ctx, NULL);
453
454         } else {
455                 bool ret;
456
457                 ret = printing_subsystem_queue_tasks(ev_ctx, msg_ctx);
458
459                 /* Publish nt printers, this requires a working winreg pipe */
460                 pcap_cache_reload(ev_ctx, msg_ctx,
461                                   &delete_and_reload_printers_full);
462
463                 return ret;
464         }
465
466         if (pid == -1) {
467                 return false;
468         }
469         background_lpq_updater_pid = pid;
470
471         return true;
472 }
473
474 void printing_subsystem_update(struct tevent_context *ev_ctx,
475                                struct messaging_context *msg_ctx,
476                                bool force)
477 {
478         if (background_lpq_updater_pid != -1) {
479                 if (pcap_cache_loaded(NULL)) {
480                         load_printers(ev_ctx, msg_ctx);
481                 }
482                 if (force) {
483                         /* Send a sighup to the background process.
484                          * this will force it to reload printers */
485                         kill(background_lpq_updater_pid, SIGHUP);
486                 }
487                 return;
488         }
489
490         pcap_cache_reload(ev_ctx, msg_ctx,
491                           &delete_and_reload_printers_full);
492 }