s3:printing: Move pcap_cache_loaded() to load.c
[samba.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 <spawn.h>
25 #include "smbd/globals.h"
26 #include "include/messages.h"
27 #include "lib/util/util_process.h"
28 #include "lib/util/sys_rw.h"
29 #include "printing.h"
30 #include "printing/pcap.h"
31 #include "printing/printer_list.h"
32 #include "printing/queue_process.h"
33 #include "locking/proto.h"
34 #include "locking/share_mode_lock.h"
35 #include "smbd/smbd.h"
36 #include "rpc_server/rpc_config.h"
37 #include "printing/load.h"
38 #include "printing/spoolssd.h"
39 #include "rpc_server/spoolss/srv_spoolss_nt.h"
40 #include "auth.h"
41 #include "nt_printing.h"
42 #include "util_event.h"
43 #include "lib/global_contexts.h"
44 #include "lib/util/pidfile.h"
45
46 /**
47  * @brief Purge stale printers and reload from pre-populated pcap cache.
48  *
49  * This function should normally only be called as a callback on a successful
50  * pcap_cache_reload().
51  *
52  * This function can cause DELETION of printers and drivers from our registry,
53  * so calling it on a failed pcap reload may REMOVE permanently all printers
54  * and drivers.
55  *
56  * @param[in] ev        The event context.
57  *
58  * @param[in] msg_ctx   The messaging context.
59  */
60 static void delete_and_reload_printers_full(struct tevent_context *ev,
61                                             struct messaging_context *msg_ctx)
62 {
63         struct auth_session_info *session_info = NULL;
64         struct spoolss_PrinterInfo2 *pinfo2 = NULL;
65         const struct loadparm_substitution *lp_sub =
66                 loadparm_s3_global_substitution();
67         int n_services;
68         int pnum;
69         int snum;
70         const char *pname;
71         const char *sname;
72         NTSTATUS status;
73
74         n_services = lp_numservices();
75         pnum = lp_servicenumber(PRINTERS_NAME);
76
77         status = make_session_info_system(talloc_tos(), &session_info);
78         if (!NT_STATUS_IS_OK(status)) {
79                 DEBUG(3, ("reload_printers: "
80                           "Could not create system session_info\n"));
81                 /* can't remove stale printers before we
82                  * are fully initialized */
83                 return;
84         }
85
86         /*
87          * Add default config for printers added to smb.conf file and remove
88          * stale printers
89          */
90         for (snum = 0; snum < n_services; snum++) {
91                 /* avoid removing PRINTERS_NAME */
92                 if (snum == pnum) {
93                         continue;
94                 }
95
96                 /* skip no-printer services */
97                 if (!snum_is_shared_printer(snum)) {
98                         continue;
99                 }
100
101                 sname = lp_const_servicename(snum);
102                 pname = lp_printername(session_info, lp_sub, snum);
103
104                 /* check printer, but avoid removing non-autoloaded printers */
105                 if (lp_autoloaded(snum) &&
106                     !printer_list_printername_exists(pname)) {
107                         DEBUG(3, ("removing stale printer %s\n", pname));
108
109                         if (is_printer_published(session_info, session_info,
110                                                  msg_ctx,
111                                                  NULL,
112                                                  lp_servicename(session_info,
113                                                                 lp_sub,
114                                                                 snum),
115                                                  &pinfo2)) {
116                                 nt_printer_publish(session_info,
117                                                    session_info,
118                                                    msg_ctx,
119                                                    pinfo2,
120                                                    DSPRINT_UNPUBLISH);
121                                 TALLOC_FREE(pinfo2);
122                         }
123                         nt_printer_remove(session_info, session_info, msg_ctx,
124                                           pname);
125                 } else {
126                         DEBUG(8, ("Adding default registry entry for printer "
127                                   "[%s], if it doesn't exist.\n", sname));
128                         nt_printer_add(session_info, session_info, msg_ctx,
129                                        sname);
130                 }
131         }
132
133         /* finally, purge old snums */
134         delete_and_reload_printers();
135
136         TALLOC_FREE(session_info);
137 }
138
139
140 /****************************************************************************
141  Notify smbds of new printcap data
142 **************************************************************************/
143 static void reload_pcap_change_notify(struct tevent_context *ev,
144                                struct messaging_context *msg_ctx)
145 {
146         /*
147          * Reload the printers first in the background process so that
148          * newly added printers get default values created in the registry.
149          *
150          * This will block the process for some time (~1 sec per printer), but
151          * it doesn't block smbd's serving clients.
152          */
153         delete_and_reload_printers_full(ev, msg_ctx);
154
155         messaging_send_all(msg_ctx, MSG_PRINTER_PCAP, NULL, 0);
156 }
157
158 struct bq_state {
159         struct tevent_context *ev;
160         struct messaging_context *msg;
161         struct idle_event *housekeep;
162         struct tevent_signal *sighup_handler;
163         struct tevent_signal *sigchld_handler;
164 };
165
166 static bool print_queue_housekeeping(const struct timeval *now, void *pvt)
167 {
168         struct bq_state *state;
169
170         state = talloc_get_type_abort(pvt, struct bq_state);
171
172         DEBUG(5, ("print queue housekeeping\n"));
173         pcap_cache_reload(state->ev, state->msg, reload_pcap_change_notify);
174
175         return true;
176 }
177
178 static bool printing_subsystem_queue_tasks(struct bq_state *state)
179 {
180         uint32_t housekeeping_period = lp_printcap_cache_time();
181
182         /* cancel any existing housekeeping event */
183         TALLOC_FREE(state->housekeep);
184
185         if ((housekeeping_period == 0) || !lp_load_printers()) {
186                 DEBUG(4, ("background print queue housekeeping disabled\n"));
187                 return true;
188         }
189
190         state->housekeep = event_add_idle(state->ev, NULL,
191                                           timeval_set(housekeeping_period, 0),
192                                           "print_queue_housekeeping",
193                                           print_queue_housekeeping, state);
194         if (state->housekeep == NULL) {
195                 DEBUG(0,("Could not add print_queue_housekeeping event\n"));
196                 return false;
197         }
198
199         return true;
200 }
201
202 static void bq_reopen_logs(char *logfile)
203 {
204         if (logfile) {
205                 lp_set_logfile(logfile);
206         }
207         reopen_logs();
208 }
209
210 static void bq_sig_hup_handler(struct tevent_context *ev,
211                                 struct tevent_signal *se,
212                                 int signum,
213                                 int count,
214                                 void *siginfo,
215                                 void *pvt)
216 {
217         struct bq_state *state;
218
219         state = talloc_get_type_abort(pvt, struct bq_state);
220         change_to_root_user();
221
222         DEBUG(1, ("Reloading pcap cache after SIGHUP\n"));
223         pcap_cache_reload(state->ev, state->msg,
224                           reload_pcap_change_notify);
225         printing_subsystem_queue_tasks(state);
226         bq_reopen_logs(NULL);
227 }
228
229 static void bq_sig_chld_handler(struct tevent_context *ev_ctx,
230                                 struct tevent_signal *se,
231                                 int signum, int count,
232                                 void *siginfo, void *pvt)
233 {
234         int status;
235         pid_t pid;
236
237         do {
238                 do {
239                         pid = waitpid(-1, &status, WNOHANG);
240                 } while ((pid == -1) && (errno == EINTR));
241
242                 if (WIFEXITED(status)) {
243                         DBG_INFO("Bq child process %d terminated with %d\n",
244                                  (int)pid,
245                                  WEXITSTATUS(status));
246                 } else {
247                         DBG_NOTICE("Bq child process %d terminated abnormally\n",
248                                    (int)pid);
249                 }
250         } while (pid > 0);
251 }
252
253 static void bq_smb_conf_updated(struct messaging_context *msg_ctx,
254                                 void *private_data,
255                                 uint32_t msg_type,
256                                 struct server_id server_id,
257                                 DATA_BLOB *data)
258 {
259         struct bq_state *state;
260
261         state = talloc_get_type_abort(private_data, struct bq_state);
262
263         DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
264                   "updated. Reloading.\n"));
265         change_to_root_user();
266         pcap_cache_reload(state->ev, msg_ctx, reload_pcap_change_notify);
267         printing_subsystem_queue_tasks(state);
268 }
269
270 static int bq_state_destructor(struct bq_state *s)
271 {
272         struct messaging_context *msg_ctx = s->msg;
273         TALLOC_FREE(s->sighup_handler);
274         TALLOC_FREE(s->sigchld_handler);
275         messaging_deregister(msg_ctx, MSG_PRINTER_DRVUPGRADE, NULL);
276         messaging_deregister(msg_ctx, MSG_PRINTER_UPDATE, NULL);
277         messaging_deregister(msg_ctx, MSG_SMB_CONF_UPDATED, s);
278         return 0;
279 }
280
281 struct bq_state *register_printing_bq_handlers(
282         TALLOC_CTX *mem_ctx,
283         struct messaging_context *msg_ctx)
284 {
285         struct bq_state *state = NULL;
286         NTSTATUS status;
287         bool ok;
288
289         state = talloc_zero(mem_ctx, struct bq_state);
290         if (state == NULL) {
291                 return NULL;
292         }
293         state->ev = messaging_tevent_context(msg_ctx);
294         state->msg = msg_ctx;
295
296         status = messaging_register(
297                 msg_ctx, state, MSG_SMB_CONF_UPDATED, bq_smb_conf_updated);
298         if (!NT_STATUS_IS_OK(status)) {
299                 goto fail;
300         }
301         status = messaging_register(
302                 msg_ctx, NULL, MSG_PRINTER_UPDATE, print_queue_receive);
303         if (!NT_STATUS_IS_OK(status)) {
304                 goto fail_dereg_smb_conf_updated;
305         }
306         status = messaging_register(
307                 msg_ctx, NULL, MSG_PRINTER_DRVUPGRADE, do_drv_upgrade_printer);
308         if (!NT_STATUS_IS_OK(status)) {
309                 goto fail_dereg_printer_update;
310         }
311
312         state->sighup_handler = tevent_add_signal(
313                 state->ev, state, SIGHUP, 0, bq_sig_hup_handler, state);
314         if (state->sighup_handler == NULL) {
315                 goto fail_dereg_printer_drvupgrade;
316         }
317         state->sigchld_handler = tevent_add_signal(
318                 state->ev, state, SIGCHLD, 0, bq_sig_chld_handler, NULL);
319         if (state->sigchld_handler == NULL) {
320                 goto fail_free_handlers;
321         }
322
323         ok = printing_subsystem_queue_tasks(state);
324         if (!ok) {
325                 goto fail_free_handlers;
326         }
327
328         talloc_set_destructor(state, bq_state_destructor);
329
330         return state;
331
332 fail_free_handlers:
333         TALLOC_FREE(state->sighup_handler);
334         TALLOC_FREE(state->sigchld_handler);
335 fail_dereg_printer_drvupgrade:
336         messaging_deregister(msg_ctx, MSG_PRINTER_DRVUPGRADE, NULL);
337 fail_dereg_printer_update:
338         messaging_deregister(msg_ctx, MSG_PRINTER_UPDATE, NULL);
339 fail_dereg_smb_conf_updated:
340         messaging_deregister(msg_ctx, MSG_SMB_CONF_UPDATED, state);
341 fail:
342         TALLOC_FREE(state);
343         return NULL;
344 }
345
346 /****************************************************************************
347 main thread of the background lpq updater
348 ****************************************************************************/
349 pid_t start_background_queue(struct tevent_context *ev,
350                              struct messaging_context *msg_ctx,
351                              char *logfile)
352 {
353         pid_t pid;
354         int ret;
355         ssize_t nread;
356         char **argv = NULL;
357         int ready_fds[2];
358
359         DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));
360
361         ret = pipe(ready_fds);
362         if (ret == -1) {
363                 return -1;
364         }
365
366         argv = str_list_make_empty(talloc_tos());
367         str_list_add_printf(
368                 &argv, "%s/samba-bgqd", get_dyn_SAMBA_LIBEXECDIR());
369         str_list_add_printf(
370                 &argv, "--ready-signal-fd=%d", ready_fds[1]);
371         str_list_add_printf(
372                 &argv, "--parent-watch-fd=%d", parent_watch_fd());
373         str_list_add_printf(
374                 &argv, "--debuglevel=%d", debuglevel_get_class(DBGC_RPC_SRV));
375         if (!is_default_dyn_CONFIGFILE()) {
376                 str_list_add_printf(
377                         &argv, "--configfile=%s", get_dyn_CONFIGFILE());
378         }
379         if (!is_default_dyn_LOGFILEBASE()) {
380                 str_list_add_printf(
381                         &argv, "--log-basename=%s", get_dyn_LOGFILEBASE());
382         }
383         str_list_add_printf(&argv, "-F");
384         if (argv == NULL) {
385                 goto nomem;
386         }
387
388         ret = posix_spawn(&pid, argv[0], NULL, NULL, argv, environ);
389         if (ret == -1) {
390                 goto fail;
391         }
392         TALLOC_FREE(argv);
393
394         close(ready_fds[1]);
395
396         nread = sys_read(ready_fds[0], &pid, sizeof(pid));
397         close(ready_fds[0]);
398         if (nread != sizeof(pid)) {
399                 goto fail;
400         }
401
402         return pid;
403
404 nomem:
405         errno = ENOMEM;
406 fail:
407         {
408                 int err = errno;
409                 TALLOC_FREE(argv);
410                 errno = err;
411         }
412
413         return -1;
414 }
415
416
417 /* Run before the parent forks */
418 bool printing_subsystem_init(struct tevent_context *ev_ctx,
419                              struct messaging_context *msg_ctx,
420                              struct dcesrv_context *dce_ctx,
421                              bool start_daemons,
422                              bool background_queue)
423 {
424         pid_t pid = -1;
425
426         if (!print_backend_init(msg_ctx)) {
427                 return false;
428         }
429
430         /* start spoolss daemon */
431         /* start as a separate daemon only if enabled */
432         if (start_daemons && rpc_spoolss_daemon() == RPC_DAEMON_FORK) {
433
434                 pid = start_spoolssd(ev_ctx, msg_ctx, dce_ctx);
435
436         } else if (start_daemons && background_queue) {
437
438                 pid = start_background_queue(ev_ctx, msg_ctx, NULL);
439
440         } else {
441                 bool ret;
442                 struct bq_state *state;
443
444                 state = talloc_zero(NULL, struct bq_state);
445                 if (state == NULL) {
446                         exit(1);
447                 }
448                 state->ev = ev_ctx;
449                 state->msg = msg_ctx;
450
451                 ret = printing_subsystem_queue_tasks(state);
452
453                 /* Publish nt printers, this requires a working winreg pipe */
454                 pcap_cache_reload(ev_ctx, msg_ctx,
455                                   delete_and_reload_printers_full);
456
457                 return ret;
458         }
459
460         if (pid == -1) {
461                 return false;
462         }
463         background_lpq_updater_pid = pid;
464
465         return true;
466 }
467
468 void printing_subsystem_update(struct tevent_context *ev_ctx,
469                                struct messaging_context *msg_ctx,
470                                bool force)
471 {
472         if (background_lpq_updater_pid != -1) {
473                 load_printers();
474                 if (force) {
475                         /* Send a sighup to the background process.
476                          * this will force it to reload printers */
477                         kill(background_lpq_updater_pid, SIGHUP);
478                 }
479                 return;
480         }
481
482         pcap_cache_reload(ev_ctx, msg_ctx,
483                           delete_and_reload_printers_full);
484 }
485
486 void send_to_bgqd(struct messaging_context *msg_ctx,
487                   uint32_t msg_type,
488                   const uint8_t *buf,
489                   size_t buflen)
490 {
491         pid_t bgqd = pidfile_pid(lp_pid_directory(), "samba-bgqd");
492
493         if (bgqd == -1) {
494                 return;
495         }
496         messaging_send_buf(
497                 msg_ctx, pid_to_procid(bgqd), msg_type, buf, buflen);
498 }