s3/rpc_server/spoolss: remove SETUP_SPOOLSS_NOTIFY_DATA_SECDESC
[samba.git] / source3 / rpc_server / spoolss / srv_spoolss_nt.c
1 /*
2  *  Unix SMB/CIFS implementation.
3  *  RPC Pipe client / server routines
4  *  Copyright (C) Andrew Tridgell              1992-2000,
5  *  Copyright (C) Luke Kenneth Casson Leighton 1996-2000,
6  *  Copyright (C) Jean Fran├žois Micouleau      1998-2000,
7  *  Copyright (C) Jeremy Allison               2001-2002,
8  *  Copyright (C) Gerald Carter                2000-2004,
9  *  Copyright (C) Tim Potter                   2001-2002.
10  *  Copyright (C) Guenther Deschner            2009-2010.
11  *  Copyright (C) Andreas Schneider            2010.
12  *
13  *  This program is free software; you can redistribute it and/or modify
14  *  it under the terms of the GNU General Public License as published by
15  *  the Free Software Foundation; either version 3 of the License, or
16  *  (at your option) any later version.
17  *
18  *  This program is distributed in the hope that it will be useful,
19  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *  GNU General Public License for more details.
22  *
23  *  You should have received a copy of the GNU General Public License
24  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
25  */
26
27 /* Since the SPOOLSS rpc routines are basically DOS 16-bit calls wrapped
28    up, all the errors returned are DOS errors, not NT status codes. */
29
30 #include "includes.h"
31 #include "ntdomain.h"
32 #include "nt_printing.h"
33 #include "srv_spoolss_util.h"
34 #include "../librpc/gen_ndr/srv_spoolss.h"
35 #include "../librpc/gen_ndr/ndr_spoolss_c.h"
36 #include "rpc_client/init_spoolss.h"
37 #include "rpc_client/cli_pipe.h"
38 #include "../libcli/security/security.h"
39 #include "librpc/gen_ndr/ndr_security.h"
40 #include "registry.h"
41 #include "include/printing.h"
42 #include "secrets.h"
43 #include "../librpc/gen_ndr/netlogon.h"
44 #include "rpc_misc.h"
45 #include "printing/notify.h"
46 #include "serverid.h"
47 #include "../libcli/registry/util_reg.h"
48 #include "smbd/smbd.h"
49 #include "smbd/globals.h"
50 #include "auth.h"
51 #include "messages.h"
52 #include "rpc_server/spoolss/srv_spoolss_nt.h"
53 #include "util_tdb.h"
54 #include "libsmb/libsmb.h"
55 #include "printing/printer_list.h"
56 #include "../lib/tsocket/tsocket.h"
57 #include "rpc_client/cli_winreg_spoolss.h"
58 #include "../libcli/smb/smbXcli_base.h"
59
60 /* macros stolen from s4 spoolss server */
61 #define SPOOLSS_BUFFER_UNION(fn,info,level) \
62         ((info)?ndr_size_##fn(info, level, 0):0)
63
64 #define SPOOLSS_BUFFER_UNION_ARRAY(mem_ctx,fn,info,level,count) \
65         ((info)?ndr_size_##fn##_info(mem_ctx, level, count, info):0)
66
67 #define SPOOLSS_BUFFER_ARRAY(mem_ctx,fn,info,count) \
68         ((info)?ndr_size_##fn##_info(mem_ctx, count, info):0)
69
70 #define SPOOLSS_BUFFER_OK(val_true,val_false) ((r->in.offered >= *r->out.needed)?val_true:val_false)
71
72 #undef DBGC_CLASS
73 #define DBGC_CLASS DBGC_RPC_SRV
74
75 #ifndef MAX_OPEN_PRINTER_EXS
76 #define MAX_OPEN_PRINTER_EXS 50
77 #endif
78
79 struct notify_back_channel;
80
81 /* structure to store the printer handles */
82 /* and a reference to what it's pointing to */
83 /* and the notify info asked about */
84 /* that's the central struct */
85 struct printer_handle {
86         struct printer_handle *prev, *next;
87         bool document_started;
88         bool page_started;
89         uint32 jobid; /* jobid in printing backend */
90         int printer_type;
91         const char *servername;
92         fstring sharename;
93         uint32 type;
94         uint32 access_granted;
95         struct {
96                 uint32 flags;
97                 uint32 options;
98                 fstring localmachine;
99                 uint32 printerlocal;
100                 struct spoolss_NotifyOption *option;
101                 struct policy_handle cli_hnd;
102                 struct notify_back_channel *cli_chan;
103                 uint32 change;
104                 /* are we in a FindNextPrinterChangeNotify() call? */
105                 bool fnpcn;
106                 struct messaging_context *msg_ctx;
107         } notify;
108         struct {
109                 fstring machine;
110                 fstring user;
111         } client;
112
113         /* devmode sent in the OpenPrinter() call */
114         struct spoolss_DeviceMode *devmode;
115
116         /* TODO cache the printer info2 structure */
117         struct spoolss_PrinterInfo2 *info2;
118
119 };
120
121 static struct printer_handle *printers_list;
122
123 struct printer_session_counter {
124         struct printer_session_counter *next;
125         struct printer_session_counter *prev;
126
127         int snum;
128         uint32_t counter;
129 };
130
131 static struct printer_session_counter *counter_list;
132
133 struct notify_back_channel {
134         struct notify_back_channel *prev, *next;
135
136         /* associated client */
137         struct sockaddr_storage client_address;
138
139         /* print notify back-channel pipe handle*/
140         struct rpc_pipe_client *cli_pipe;
141         struct cli_state *cli;
142         uint32_t active_connections;
143 };
144
145 static struct notify_back_channel *back_channels;
146
147 /* Map generic permissions to printer object specific permissions */
148
149 const struct standard_mapping printer_std_mapping = {
150         PRINTER_READ,
151         PRINTER_WRITE,
152         PRINTER_EXECUTE,
153         PRINTER_ALL_ACCESS
154 };
155
156 /* Map generic permissions to print server object specific permissions */
157
158 const struct standard_mapping printserver_std_mapping = {
159         SERVER_READ,
160         SERVER_WRITE,
161         SERVER_EXECUTE,
162         SERVER_ALL_ACCESS
163 };
164
165 /* API table for Xcv Monitor functions */
166
167 struct xcv_api_table {
168         const char *name;
169         WERROR(*fn) (TALLOC_CTX *mem_ctx, struct security_token *token, DATA_BLOB *in, DATA_BLOB *out, uint32_t *needed);
170 };
171
172 static void prune_printername_cache(void);
173
174 /********************************************************************
175  * Canonicalize servername.
176  ********************************************************************/
177
178 static const char *canon_servername(const char *servername)
179 {
180         const char *pservername = servername;
181         while (*pservername == '\\') {
182                 pservername++;
183         }
184         return pservername;
185 }
186
187 /* translate between internal status numbers and NT status numbers */
188 static int nt_printj_status(int v)
189 {
190         switch (v) {
191         case LPQ_QUEUED:
192                 return 0;
193         case LPQ_PAUSED:
194                 return JOB_STATUS_PAUSED;
195         case LPQ_SPOOLING:
196                 return JOB_STATUS_SPOOLING;
197         case LPQ_PRINTING:
198                 return JOB_STATUS_PRINTING;
199         case LPQ_ERROR:
200                 return JOB_STATUS_ERROR;
201         case LPQ_DELETING:
202                 return JOB_STATUS_DELETING;
203         case LPQ_OFFLINE:
204                 return JOB_STATUS_OFFLINE;
205         case LPQ_PAPEROUT:
206                 return JOB_STATUS_PAPEROUT;
207         case LPQ_PRINTED:
208                 return JOB_STATUS_PRINTED;
209         case LPQ_DELETED:
210                 return JOB_STATUS_DELETED;
211         case LPQ_BLOCKED:
212                 return JOB_STATUS_BLOCKED_DEVQ;
213         case LPQ_USER_INTERVENTION:
214                 return JOB_STATUS_USER_INTERVENTION;
215         }
216         return 0;
217 }
218
219 static int nt_printq_status(int v)
220 {
221         switch (v) {
222         case LPQ_PAUSED:
223                 return PRINTER_STATUS_PAUSED;
224         case LPQ_QUEUED:
225         case LPQ_SPOOLING:
226         case LPQ_PRINTING:
227                 return 0;
228         }
229         return 0;
230 }
231
232 /***************************************************************************
233  Disconnect from the client
234 ****************************************************************************/
235
236 static void srv_spoolss_replycloseprinter(int snum,
237                                           struct printer_handle *prn_hnd)
238 {
239         WERROR result;
240         NTSTATUS status;
241
242         /*
243          * Tell the specific printing tdb we no longer want messages for this printer
244          * by deregistering our PID.
245          */
246
247         if (!print_notify_deregister_pid(snum)) {
248                 DEBUG(0, ("Failed to register our pid for printer %s\n",
249                           lp_const_servicename(snum)));
250         }
251
252         /* weird if the test succeeds !!! */
253         if (prn_hnd->notify.cli_chan == NULL ||
254             prn_hnd->notify.cli_chan->cli_pipe == NULL ||
255             prn_hnd->notify.cli_chan->cli_pipe->binding_handle == NULL ||
256             prn_hnd->notify.cli_chan->active_connections == 0) {
257                 DEBUG(0, ("Trying to close unexisting backchannel!\n"));
258                 DLIST_REMOVE(back_channels, prn_hnd->notify.cli_chan);
259                 TALLOC_FREE(prn_hnd->notify.cli_chan);
260                 return;
261         }
262
263         status = dcerpc_spoolss_ReplyClosePrinter(
264                                         prn_hnd->notify.cli_chan->cli_pipe->binding_handle,
265                                         talloc_tos(),
266                                         &prn_hnd->notify.cli_hnd,
267                                         &result);
268         if (!NT_STATUS_IS_OK(status)) {
269                 DEBUG(0, ("dcerpc_spoolss_ReplyClosePrinter failed [%s].\n",
270                           nt_errstr(status)));
271                 result = ntstatus_to_werror(status);
272         } else if (!W_ERROR_IS_OK(result)) {
273                 DEBUG(0, ("reply_close_printer failed [%s].\n",
274                           win_errstr(result)));
275         }
276
277         /* if it's the last connection, deconnect the IPC$ share */
278         if (prn_hnd->notify.cli_chan->active_connections == 1) {
279
280                 cli_shutdown(prn_hnd->notify.cli_chan->cli);
281                 DLIST_REMOVE(back_channels, prn_hnd->notify.cli_chan);
282                 TALLOC_FREE(prn_hnd->notify.cli_chan);
283
284                 if (prn_hnd->notify.msg_ctx != NULL) {
285                         messaging_deregister(prn_hnd->notify.msg_ctx,
286                                              MSG_PRINTER_NOTIFY2, NULL);
287                 }
288         }
289
290         if (prn_hnd->notify.cli_chan) {
291                 prn_hnd->notify.cli_chan->active_connections--;
292                 prn_hnd->notify.cli_chan = NULL;
293         }
294 }
295
296 /****************************************************************************
297  Functions to free a printer entry datastruct.
298 ****************************************************************************/
299
300 static int printer_entry_destructor(struct printer_handle *Printer)
301 {
302         if (Printer->notify.cli_chan != NULL &&
303             Printer->notify.cli_chan->active_connections > 0) {
304                 int snum = -1;
305
306                 switch(Printer->printer_type) {
307                 case SPLHND_SERVER:
308                         srv_spoolss_replycloseprinter(snum, Printer);
309                         break;
310
311                 case SPLHND_PRINTER:
312                         snum = print_queue_snum(Printer->sharename);
313                         if (snum != -1) {
314                                 srv_spoolss_replycloseprinter(snum, Printer);
315                         }
316                         break;
317                 default:
318                         break;
319                 }
320         }
321
322         Printer->notify.flags=0;
323         Printer->notify.options=0;
324         Printer->notify.localmachine[0]='\0';
325         Printer->notify.printerlocal=0;
326         TALLOC_FREE(Printer->notify.option);
327         TALLOC_FREE(Printer->devmode);
328
329         /* Remove from the internal list. */
330         DLIST_REMOVE(printers_list, Printer);
331         return 0;
332 }
333
334 /****************************************************************************
335   find printer index by handle
336 ****************************************************************************/
337
338 static struct printer_handle *find_printer_index_by_hnd(struct pipes_struct *p,
339                                                         struct policy_handle *hnd)
340 {
341         struct printer_handle *find_printer = NULL;
342
343         if(!find_policy_by_hnd(p,hnd,(void **)(void *)&find_printer)) {
344                 DEBUG(2,("find_printer_index_by_hnd: Printer handle not found: "));
345                 return NULL;
346         }
347
348         return find_printer;
349 }
350
351 /****************************************************************************
352  Close printer index by handle.
353 ****************************************************************************/
354
355 static bool close_printer_handle(struct pipes_struct *p, struct policy_handle *hnd)
356 {
357         struct printer_handle *Printer = find_printer_index_by_hnd(p, hnd);
358
359         if (!Printer) {
360                 DEBUG(2,("close_printer_handle: Invalid handle (%s:%u:%u)\n",
361                         OUR_HANDLE(hnd)));
362                 return false;
363         }
364
365         close_policy_hnd(p, hnd);
366
367         return true;
368 }
369
370 /****************************************************************************
371  Delete a printer given a handle.
372 ****************************************************************************/
373
374 static WERROR delete_printer_hook(TALLOC_CTX *ctx, struct security_token *token,
375                                   const char *sharename,
376                                   struct messaging_context *msg_ctx)
377 {
378         char *cmd = lp_deleteprinter_command(talloc_tos());
379         char *command = NULL;
380         int ret;
381         bool is_print_op = false;
382
383         /* can't fail if we don't try */
384
385         if ( !*cmd )
386                 return WERR_OK;
387
388         command = talloc_asprintf(ctx,
389                         "%s \"%s\"",
390                         cmd, sharename);
391         if (!command) {
392                 return WERR_NOMEM;
393         }
394         if ( token )
395                 is_print_op = security_token_has_privilege(token, SEC_PRIV_PRINT_OPERATOR);
396
397         DEBUG(10,("Running [%s]\n", command));
398
399         /********** BEGIN SePrintOperatorPrivlege BLOCK **********/
400
401         if ( is_print_op )
402                 become_root();
403
404         if ( (ret = smbrun(command, NULL)) == 0 ) {
405                 /* Tell everyone we updated smb.conf. */
406                 message_send_all(msg_ctx, MSG_SMB_CONF_UPDATED, NULL, 0, NULL);
407         }
408
409         if ( is_print_op )
410                 unbecome_root();
411
412         /********** END SePrintOperatorPrivlege BLOCK **********/
413
414         DEBUGADD(10,("returned [%d]\n", ret));
415
416         TALLOC_FREE(command);
417
418         if (ret != 0)
419                 return WERR_BADFID; /* What to return here? */
420
421         return WERR_OK;
422 }
423
424 /****************************************************************************
425  Delete a printer given a handle.
426 ****************************************************************************/
427
428 static WERROR delete_printer_handle(struct pipes_struct *p, struct policy_handle *hnd)
429 {
430         struct printer_handle *Printer = find_printer_index_by_hnd(p, hnd);
431         WERROR result;
432
433         if (!Printer) {
434                 DEBUG(2,("delete_printer_handle: Invalid handle (%s:%u:%u)\n",
435                         OUR_HANDLE(hnd)));
436                 return WERR_BADFID;
437         }
438
439         /*
440          * It turns out that Windows allows delete printer on a handle
441          * opened by an admin user, then used on a pipe handle created
442          * by an anonymous user..... but they're working on security.... riiight !
443          * JRA.
444          */
445
446         if (Printer->access_granted != PRINTER_ACCESS_ADMINISTER) {
447                 DEBUG(3, ("delete_printer_handle: denied by handle\n"));
448                 return WERR_ACCESS_DENIED;
449         }
450
451         /* this does not need a become root since the access check has been
452            done on the handle already */
453
454         result = winreg_delete_printer_key_internal(p->mem_ctx,
455                                            get_session_info_system(),
456                                            p->msg_ctx,
457                                            Printer->sharename,
458                                            "");
459         if (!W_ERROR_IS_OK(result)) {
460                 DEBUG(3,("Error deleting printer %s\n", Printer->sharename));
461                 return WERR_BADFID;
462         }
463
464         result = delete_printer_hook(p->mem_ctx, p->session_info->security_token,
465                                      Printer->sharename, p->msg_ctx);
466         if (!W_ERROR_IS_OK(result)) {
467                 return result;
468         }
469         prune_printername_cache();
470         return WERR_OK;
471 }
472
473 /****************************************************************************
474  Return the snum of a printer corresponding to an handle.
475 ****************************************************************************/
476
477 static bool get_printer_snum(struct pipes_struct *p, struct policy_handle *hnd,
478                              int *number, struct share_params **params)
479 {
480         struct printer_handle *Printer = find_printer_index_by_hnd(p, hnd);
481
482         if (!Printer) {
483                 DEBUG(2,("get_printer_snum: Invalid handle (%s:%u:%u)\n",
484                         OUR_HANDLE(hnd)));
485                 return false;
486         }
487
488         switch (Printer->printer_type) {
489                 case SPLHND_PRINTER:
490                         DEBUG(4,("short name:%s\n", Printer->sharename));
491                         *number = print_queue_snum(Printer->sharename);
492                         return (*number != -1);
493                 case SPLHND_SERVER:
494                         return false;
495                 default:
496                         return false;
497         }
498 }
499
500 /****************************************************************************
501  Set printer handle type.
502  Check if it's \\server or \\server\printer
503 ****************************************************************************/
504
505 static bool set_printer_hnd_printertype(struct printer_handle *Printer, const char *handlename)
506 {
507         DEBUG(3,("Setting printer type=%s\n", handlename));
508
509         /* it's a print server */
510         if (handlename && *handlename=='\\' && *(handlename+1)=='\\' && !strchr_m(handlename+2, '\\')) {
511                 DEBUGADD(4,("Printer is a print server\n"));
512                 Printer->printer_type = SPLHND_SERVER;
513         }
514         /* it's a printer (set_printer_hnd_name() will handle port monitors */
515         else {
516                 DEBUGADD(4,("Printer is a printer\n"));
517                 Printer->printer_type = SPLHND_PRINTER;
518         }
519
520         return true;
521 }
522
523 static void prune_printername_cache_fn(const char *key, const char *value,
524                                        time_t timeout, void *private_data)
525 {
526         gencache_del(key);
527 }
528
529 static void prune_printername_cache(void)
530 {
531         gencache_iterate(prune_printername_cache_fn, NULL, "PRINTERNAME/*");
532 }
533
534 /****************************************************************************
535  Set printer handle name..  Accept names like \\server, \\server\printer,
536  \\server\SHARE, & "\\server\,XcvMonitor Standard TCP/IP Port"    See
537  the MSDN docs regarding OpenPrinter() for details on the XcvData() and
538  XcvDataPort() interface.
539 ****************************************************************************/
540
541 static WERROR set_printer_hnd_name(TALLOC_CTX *mem_ctx,
542                                    const struct auth_session_info *session_info,
543                                    struct messaging_context *msg_ctx,
544                                    struct printer_handle *Printer,
545                                    const char *handlename)
546 {
547         int snum;
548         int n_services=lp_numservices();
549         char *aprinter;
550         const char *printername;
551         const char *servername = NULL;
552         fstring sname;
553         bool found = false;
554         struct spoolss_PrinterInfo2 *info2 = NULL;
555         WERROR result;
556         char *p;
557
558         /*
559          * Hopefully nobody names his printers like this. Maybe \ or ,
560          * are illegal in printer names even?
561          */
562         const char printer_not_found[] = "Printer \\, !@#$%^&*( not found";
563         char *cache_key;
564         char *tmp;
565
566         DEBUG(4,("Setting printer name=%s (len=%lu)\n", handlename,
567                 (unsigned long)strlen(handlename)));
568
569         aprinter = discard_const_p(char, handlename);
570         if ( *handlename == '\\' ) {
571                 servername = canon_servername(handlename);
572                 if ( (aprinter = strchr_m( servername, '\\' )) != NULL ) {
573                         *aprinter = '\0';
574                         aprinter++;
575                 }
576                 if (!is_myname_or_ipaddr(servername)) {
577                         return WERR_INVALID_PRINTER_NAME;
578                 }
579                 Printer->servername = talloc_asprintf(Printer, "\\\\%s", servername);
580                 if (Printer->servername == NULL) {
581                         return WERR_NOMEM;
582                 }
583         }
584
585         if (Printer->printer_type == SPLHND_SERVER) {
586                 return WERR_OK;
587         }
588
589         if (Printer->printer_type != SPLHND_PRINTER) {
590                 return WERR_INVALID_HANDLE;
591         }
592
593         DEBUGADD(5, ("searching for [%s]\n", aprinter));
594
595         p = strchr(aprinter, ',');
596         if (p != NULL) {
597                 char *p2 = p;
598                 p++;
599                 if (*p == ' ') {
600                         p++;
601                 }
602                 if (strncmp(p, "DrvConvert", strlen("DrvConvert")) == 0) {
603                         *p2 = '\0';
604                 } else if (strncmp(p, "LocalOnly", strlen("LocalOnly")) == 0) {
605                         *p2 = '\0';
606                 }
607         }
608
609         if (p) {
610                 DEBUGADD(5, ("stripped handlename: [%s]\n", aprinter));
611         }
612
613         /* check for the Port Monitor Interface */
614         if ( strequal( aprinter, SPL_XCV_MONITOR_TCPMON ) ) {
615                 Printer->printer_type = SPLHND_PORTMON_TCP;
616                 fstrcpy(sname, SPL_XCV_MONITOR_TCPMON);
617                 found = true;
618         }
619         else if ( strequal( aprinter, SPL_XCV_MONITOR_LOCALMON ) ) {
620                 Printer->printer_type = SPLHND_PORTMON_LOCAL;
621                 fstrcpy(sname, SPL_XCV_MONITOR_LOCALMON);
622                 found = true;
623         }
624
625         /*
626          * With hundreds of printers, the "for" loop iterating all
627          * shares can be quite expensive, as it is done on every
628          * OpenPrinter. The loop maps "aprinter" to "sname", the
629          * result of which we cache in gencache.
630          */
631
632         cache_key = talloc_asprintf(talloc_tos(), "PRINTERNAME/%s",
633                                     aprinter);
634         if ((cache_key != NULL) &&
635             gencache_get(cache_key, talloc_tos(), &tmp, NULL)) {
636
637                 found = (strcmp(tmp, printer_not_found) != 0);
638                 if (!found) {
639                         DEBUG(4, ("Printer %s not found\n", aprinter));
640                         TALLOC_FREE(tmp);
641                         return WERR_INVALID_PRINTER_NAME;
642                 }
643                 fstrcpy(sname, tmp);
644                 TALLOC_FREE(tmp);
645         }
646
647         /* Search all sharenames first as this is easier than pulling
648            the printer_info_2 off of disk. Don't use find_service() since
649            that calls out to map_username() */
650
651         /* do another loop to look for printernames */
652         for (snum = 0; !found && snum < n_services; snum++) {
653                 const char *printer = lp_const_servicename(snum);
654
655                 /* no point going on if this is not a printer */
656                 if (!(lp_snum_ok(snum) && lp_printable(snum))) {
657                         continue;
658                 }
659
660                 /* ignore [printers] share */
661                 if (strequal(printer, "printers")) {
662                         continue;
663                 }
664
665                 fstrcpy(sname, printer);
666                 if (strequal(aprinter, printer)) {
667                         found = true;
668                         break;
669                 }
670
671                 /* no point looking up the printer object if
672                    we aren't allowing printername != sharename */
673                 if (lp_force_printername(snum)) {
674                         continue;
675                 }
676
677                 result = winreg_get_printer_internal(mem_ctx,
678                                             session_info,
679                                             msg_ctx,
680                                             sname,
681                                             &info2);
682                 if ( !W_ERROR_IS_OK(result) ) {
683                         DEBUG(2,("set_printer_hnd_name: failed to lookup printer [%s] -- result [%s]\n",
684                                  sname, win_errstr(result)));
685                         continue;
686                 }
687
688                 printername = strrchr(info2->printername, '\\');
689                 if (printername == NULL) {
690                         printername = info2->printername;
691                 } else {
692                         printername++;
693                 }
694
695                 if (strequal(printername, aprinter)) {
696                         found = true;
697                         break;
698                 }
699
700                 DEBUGADD(10, ("printername: %s\n", printername));
701
702                 TALLOC_FREE(info2);
703         }
704
705         if ( !found ) {
706                 if (cache_key != NULL) {
707                         gencache_set(cache_key, printer_not_found,
708                                      time(NULL)+300);
709                         TALLOC_FREE(cache_key);
710                 }
711                 DEBUGADD(4,("Printer not found\n"));
712                 return WERR_INVALID_PRINTER_NAME;
713         }
714
715         if (cache_key != NULL) {
716                 gencache_set(cache_key, sname, time(NULL)+300);
717                 TALLOC_FREE(cache_key);
718         }
719
720         DEBUGADD(4,("set_printer_hnd_name: Printer found: %s -> %s\n", aprinter, sname));
721
722         strlcpy(Printer->sharename, sname, sizeof(Printer->sharename));
723
724         return WERR_OK;
725 }
726
727 /****************************************************************************
728  Find first available printer slot. creates a printer handle for you.
729  ****************************************************************************/
730
731 static WERROR open_printer_hnd(struct pipes_struct *p,
732                                struct policy_handle *hnd,
733                                const char *name,
734                                uint32_t access_granted)
735 {
736         struct printer_handle *new_printer;
737         WERROR result;
738
739         DEBUG(10,("open_printer_hnd: name [%s]\n", name));
740
741         new_printer = talloc_zero(p->mem_ctx, struct printer_handle);
742         if (new_printer == NULL) {
743                 return WERR_NOMEM;
744         }
745         talloc_set_destructor(new_printer, printer_entry_destructor);
746
747         /* This also steals the printer_handle on the policy_handle */
748         if (!create_policy_hnd(p, hnd, new_printer)) {
749                 TALLOC_FREE(new_printer);
750                 return WERR_INVALID_HANDLE;
751         }
752
753         /* Add to the internal list. */
754         DLIST_ADD(printers_list, new_printer);
755
756         new_printer->notify.option=NULL;
757
758         if (!set_printer_hnd_printertype(new_printer, name)) {
759                 close_printer_handle(p, hnd);
760                 return WERR_INVALID_HANDLE;
761         }
762
763         result = set_printer_hnd_name(p->mem_ctx,
764                                       get_session_info_system(),
765                                       p->msg_ctx,
766                                       new_printer, name);
767         if (!W_ERROR_IS_OK(result)) {
768                 close_printer_handle(p, hnd);
769                 return result;
770         }
771
772         new_printer->access_granted = access_granted;
773
774         DEBUG(5, ("%d printer handles active\n",
775                   (int)num_pipe_handles(p)));
776
777         return WERR_OK;
778 }
779
780 /***************************************************************************
781  check to see if the client motify handle is monitoring the notification
782  given by (notify_type, notify_field).
783  **************************************************************************/
784
785 static bool is_monitoring_event_flags(uint32_t flags, uint16_t notify_type,
786                                       uint16_t notify_field)
787 {
788         return true;
789 }
790
791 static bool is_monitoring_event(struct printer_handle *p, uint16_t notify_type,
792                                 uint16_t notify_field)
793 {
794         struct spoolss_NotifyOption *option = p->notify.option;
795         uint32_t i, j;
796
797         /*
798          * Flags should always be zero when the change notify
799          * is registered by the client's spooler.  A user Win32 app
800          * might use the flags though instead of the NOTIFY_OPTION_INFO
801          * --jerry
802          */
803
804         if (!option) {
805                 return false;
806         }
807
808         if (p->notify.flags)
809                 return is_monitoring_event_flags(
810                         p->notify.flags, notify_type, notify_field);
811
812         for (i = 0; i < option->count; i++) {
813
814                 /* Check match for notify_type */
815
816                 if (option->types[i].type != notify_type)
817                         continue;
818
819                 /* Check match for field */
820
821                 for (j = 0; j < option->types[i].count; j++) {
822                         if (option->types[i].fields[j].field == notify_field) {
823                                 return true;
824                         }
825                 }
826         }
827
828         DEBUG(10, ("Open handle for \\\\%s\\%s is not monitoring 0x%02x/0x%02x\n",
829                    p->servername, p->sharename, notify_type, notify_field));
830
831         return false;
832 }
833
834 #define SETUP_SPOOLSS_NOTIFY_DATA_INTEGER(_data, _integer) \
835         _data->data.integer[0] = _integer; \
836         _data->data.integer[1] = 0;
837
838
839 #define SETUP_SPOOLSS_NOTIFY_DATA_STRING(_data, _p) \
840         _data->data.string.string = talloc_strdup(mem_ctx, _p); \
841         if (!_data->data.string.string) {\
842                 _data->data.string.size = 0; \
843         } \
844         _data->data.string.size = strlen_m_term(_p) * 2;
845
846 #define SETUP_SPOOLSS_NOTIFY_DATA_DEVMODE(_data, _devmode) \
847         _data->data.devmode.devmode = _devmode;
848
849 static void init_systemtime_buffer(TALLOC_CTX *mem_ctx,
850                                    struct tm *t,
851                                    const char **pp,
852                                    uint32_t *plen)
853 {
854         struct spoolss_Time st;
855         uint32_t len = 16;
856         char *p;
857
858         if (!init_systemtime(&st, t)) {
859                 return;
860         }
861
862         p = talloc_array(mem_ctx, char, len);
863         if (!p) {
864                 return;
865         }
866
867         /*
868          * Systemtime must be linearized as a set of UINT16's.
869          * Fix from Benjamin (Bj) Kuit bj@it.uts.edu.au
870          */
871
872         SSVAL(p, 0, st.year);
873         SSVAL(p, 2, st.month);
874         SSVAL(p, 4, st.day_of_week);
875         SSVAL(p, 6, st.day);
876         SSVAL(p, 8, st.hour);
877         SSVAL(p, 10, st.minute);
878         SSVAL(p, 12, st.second);
879         SSVAL(p, 14, st.millisecond);
880
881         *pp = p;
882         *plen = len;
883 }
884
885 /* Convert a notification message to a struct spoolss_Notify */
886
887 static void notify_one_value(struct spoolss_notify_msg *msg,
888                              struct spoolss_Notify *data,
889                              TALLOC_CTX *mem_ctx)
890 {
891         SETUP_SPOOLSS_NOTIFY_DATA_INTEGER(data, msg->notify.value[0]);
892 }
893
894 static void notify_string(struct spoolss_notify_msg *msg,
895                           struct spoolss_Notify *data,
896                           TALLOC_CTX *mem_ctx)
897 {
898         /* The length of the message includes the trailing \0 */
899
900         data->data.string.size = msg->len * 2;
901         data->data.string.string = talloc_strdup(mem_ctx, msg->notify.data);
902         if (!data->data.string.string) {
903                 data->data.string.size = 0;
904                 return;
905         }
906 }
907
908 static void notify_system_time(struct spoolss_notify_msg *msg,
909                                struct spoolss_Notify *data,
910                                TALLOC_CTX *mem_ctx)
911 {
912         data->data.string.string = NULL;
913         data->data.string.size = 0;
914
915         if (msg->len != sizeof(time_t)) {
916                 DEBUG(5, ("notify_system_time: received wrong sized message (%d)\n",
917                           msg->len));
918                 return;
919         }
920
921         init_systemtime_buffer(mem_ctx, gmtime((time_t *)msg->notify.data),
922                                &data->data.string.string,
923                                &data->data.string.size);
924 }
925
926 struct notify2_message_table {
927         const char *name;
928         void (*fn)(struct spoolss_notify_msg *msg,
929                    struct spoolss_Notify *data, TALLOC_CTX *mem_ctx);
930 };
931
932 static struct notify2_message_table printer_notify_table[] = {
933         /* 0x00 */ { "PRINTER_NOTIFY_FIELD_SERVER_NAME", notify_string },
934         /* 0x01 */ { "PRINTER_NOTIFY_FIELD_PRINTER_NAME", notify_string },
935         /* 0x02 */ { "PRINTER_NOTIFY_FIELD_SHARE_NAME", notify_string },
936         /* 0x03 */ { "PRINTER_NOTIFY_FIELD_PORT_NAME", notify_string },
937         /* 0x04 */ { "PRINTER_NOTIFY_FIELD_DRIVER_NAME", notify_string },
938         /* 0x05 */ { "PRINTER_NOTIFY_FIELD_COMMENT", notify_string },
939         /* 0x06 */ { "PRINTER_NOTIFY_FIELD_LOCATION", notify_string },
940         /* 0x07 */ { "PRINTER_NOTIFY_FIELD_DEVMODE", NULL },
941         /* 0x08 */ { "PRINTER_NOTIFY_FIELD_SEPFILE", notify_string },
942         /* 0x09 */ { "PRINTER_NOTIFY_FIELD_PRINT_PROCESSOR", notify_string },
943         /* 0x0a */ { "PRINTER_NOTIFY_FIELD_PARAMETERS", NULL },
944         /* 0x0b */ { "PRINTER_NOTIFY_FIELD_DATATYPE", notify_string },
945         /* 0x0c */ { "PRINTER_NOTIFY_FIELD_SECURITY_DESCRIPTOR", NULL },
946         /* 0x0d */ { "PRINTER_NOTIFY_FIELD_ATTRIBUTES", notify_one_value },
947         /* 0x0e */ { "PRINTER_NOTIFY_FIELD_PRIORITY", notify_one_value },
948         /* 0x0f */ { "PRINTER_NOTIFY_FIELD_DEFAULT_PRIORITY", NULL },
949         /* 0x10 */ { "PRINTER_NOTIFY_FIELD_START_TIME", NULL },
950         /* 0x11 */ { "PRINTER_NOTIFY_FIELD_UNTIL_TIME", NULL },
951         /* 0x12 */ { "PRINTER_NOTIFY_FIELD_STATUS", notify_one_value },
952 };
953
954 static struct notify2_message_table job_notify_table[] = {
955         /* 0x00 */ { "JOB_NOTIFY_FIELD_PRINTER_NAME", NULL },
956         /* 0x01 */ { "JOB_NOTIFY_FIELD_MACHINE_NAME", NULL },
957         /* 0x02 */ { "JOB_NOTIFY_FIELD_PORT_NAME", NULL },
958         /* 0x03 */ { "JOB_NOTIFY_FIELD_USER_NAME", notify_string },
959         /* 0x04 */ { "JOB_NOTIFY_FIELD_NOTIFY_NAME", NULL },
960         /* 0x05 */ { "JOB_NOTIFY_FIELD_DATATYPE", NULL },
961         /* 0x06 */ { "JOB_NOTIFY_FIELD_PRINT_PROCESSOR", NULL },
962         /* 0x07 */ { "JOB_NOTIFY_FIELD_PARAMETERS", NULL },
963         /* 0x08 */ { "JOB_NOTIFY_FIELD_DRIVER_NAME", NULL },
964         /* 0x09 */ { "JOB_NOTIFY_FIELD_DEVMODE", NULL },
965         /* 0x0a */ { "JOB_NOTIFY_FIELD_STATUS", notify_one_value },
966         /* 0x0b */ { "JOB_NOTIFY_FIELD_STATUS_STRING", NULL },
967         /* 0x0c */ { "JOB_NOTIFY_FIELD_SECURITY_DESCRIPTOR", NULL },
968         /* 0x0d */ { "JOB_NOTIFY_FIELD_DOCUMENT", notify_string },
969         /* 0x0e */ { "JOB_NOTIFY_FIELD_PRIORITY", NULL },
970         /* 0x0f */ { "JOB_NOTIFY_FIELD_POSITION", NULL },
971         /* 0x10 */ { "JOB_NOTIFY_FIELD_SUBMITTED", notify_system_time },
972         /* 0x11 */ { "JOB_NOTIFY_FIELD_START_TIME", NULL },
973         /* 0x12 */ { "JOB_NOTIFY_FIELD_UNTIL_TIME", NULL },
974         /* 0x13 */ { "JOB_NOTIFY_FIELD_TIME", NULL },
975         /* 0x14 */ { "JOB_NOTIFY_FIELD_TOTAL_PAGES", notify_one_value },
976         /* 0x15 */ { "JOB_NOTIFY_FIELD_PAGES_PRINTED", NULL },
977         /* 0x16 */ { "JOB_NOTIFY_FIELD_TOTAL_BYTES", notify_one_value },
978         /* 0x17 */ { "JOB_NOTIFY_FIELD_BYTES_PRINTED", NULL },
979 };
980
981
982 /***********************************************************************
983  Allocate talloc context for container object
984  **********************************************************************/
985
986 static void notify_msg_ctr_init( SPOOLSS_NOTIFY_MSG_CTR *ctr )
987 {
988         if ( !ctr )
989                 return;
990
991         ctr->ctx = talloc_init("notify_msg_ctr_init %p", ctr);
992
993         return;
994 }
995
996 /***********************************************************************
997  release all allocated memory and zero out structure
998  **********************************************************************/
999
1000 static void notify_msg_ctr_destroy( SPOOLSS_NOTIFY_MSG_CTR *ctr )
1001 {
1002         if ( !ctr )
1003                 return;
1004
1005         if ( ctr->ctx )
1006                 talloc_destroy(ctr->ctx);
1007
1008         ZERO_STRUCTP(ctr);
1009
1010         return;
1011 }
1012
1013 /***********************************************************************
1014  **********************************************************************/
1015
1016 static TALLOC_CTX* notify_ctr_getctx( SPOOLSS_NOTIFY_MSG_CTR *ctr )
1017 {
1018         if ( !ctr )
1019                 return NULL;
1020
1021         return ctr->ctx;
1022 }
1023
1024 /***********************************************************************
1025  **********************************************************************/
1026
1027 static SPOOLSS_NOTIFY_MSG_GROUP* notify_ctr_getgroup( SPOOLSS_NOTIFY_MSG_CTR *ctr, uint32_t idx )
1028 {
1029         if ( !ctr || !ctr->msg_groups )
1030                 return NULL;
1031
1032         if ( idx >= ctr->num_groups )
1033                 return NULL;
1034
1035         return &ctr->msg_groups[idx];
1036
1037 }
1038
1039 /***********************************************************************
1040  How many groups of change messages do we have ?
1041  **********************************************************************/
1042
1043 static int notify_msg_ctr_numgroups( SPOOLSS_NOTIFY_MSG_CTR *ctr )
1044 {
1045         if ( !ctr )
1046                 return 0;
1047
1048         return ctr->num_groups;
1049 }
1050
1051 /***********************************************************************
1052  Add a SPOOLSS_NOTIFY_MSG_CTR to the correct group
1053  **********************************************************************/
1054
1055 static int notify_msg_ctr_addmsg( SPOOLSS_NOTIFY_MSG_CTR *ctr, SPOOLSS_NOTIFY_MSG *msg )
1056 {
1057         SPOOLSS_NOTIFY_MSG_GROUP        *groups = NULL;
1058         SPOOLSS_NOTIFY_MSG_GROUP        *msg_grp = NULL;
1059         SPOOLSS_NOTIFY_MSG              *msg_list = NULL;
1060         int                             i, new_slot;
1061
1062         if ( !ctr || !msg )
1063                 return 0;
1064
1065         /* loop over all groups looking for a matching printer name */
1066
1067         for ( i=0; i<ctr->num_groups; i++ ) {
1068                 if ( strcmp(ctr->msg_groups[i].printername, msg->printer) == 0 )
1069                         break;
1070         }
1071
1072         /* add a new group? */
1073
1074         if ( i == ctr->num_groups ) {
1075                 ctr->num_groups++;
1076
1077                 if ( !(groups = talloc_realloc( ctr->ctx, ctr->msg_groups, SPOOLSS_NOTIFY_MSG_GROUP, ctr->num_groups)) ) {
1078                         DEBUG(0,("notify_msg_ctr_addmsg: talloc_realloc() failed!\n"));
1079                         return 0;
1080                 }
1081                 ctr->msg_groups = groups;
1082
1083                 /* clear the new entry and set the printer name */
1084
1085                 ZERO_STRUCT( ctr->msg_groups[ctr->num_groups-1] );
1086                 fstrcpy( ctr->msg_groups[ctr->num_groups-1].printername, msg->printer );
1087         }
1088
1089         /* add the change messages; 'i' is the correct index now regardless */
1090
1091         msg_grp = &ctr->msg_groups[i];
1092
1093         msg_grp->num_msgs++;
1094
1095         if ( !(msg_list = talloc_realloc( ctr->ctx, msg_grp->msgs, SPOOLSS_NOTIFY_MSG, msg_grp->num_msgs )) ) {
1096                 DEBUG(0,("notify_msg_ctr_addmsg: talloc_realloc() failed for new message [%d]!\n", msg_grp->num_msgs));
1097                 return 0;
1098         }
1099         msg_grp->msgs = msg_list;
1100
1101         new_slot = msg_grp->num_msgs-1;
1102         memcpy( &msg_grp->msgs[new_slot], msg, sizeof(SPOOLSS_NOTIFY_MSG) );
1103
1104         /* need to allocate own copy of data */
1105
1106         if ( msg->len != 0 )
1107                 msg_grp->msgs[new_slot].notify.data = (char *)
1108                         talloc_memdup( ctr->ctx, msg->notify.data, msg->len );
1109
1110         return ctr->num_groups;
1111 }
1112
1113 static void construct_info_data(struct spoolss_Notify *info_data,
1114                                 enum spoolss_NotifyType type,
1115                                 uint16_t field, int id);
1116
1117 /***********************************************************************
1118  Send a change notication message on all handles which have a call
1119  back registered
1120  **********************************************************************/
1121
1122 static int build_notify2_messages(TALLOC_CTX *mem_ctx,
1123                                   struct printer_handle *prn_hnd,
1124                                   SPOOLSS_NOTIFY_MSG *messages,
1125                                   uint32_t num_msgs,
1126                                   struct spoolss_Notify **_notifies,
1127                                   int *_count)
1128 {
1129         struct spoolss_Notify *notifies;
1130         SPOOLSS_NOTIFY_MSG *msg;
1131         int count = 0;
1132         uint32_t id;
1133         int i;
1134
1135         notifies = talloc_zero_array(mem_ctx,
1136                                      struct spoolss_Notify, num_msgs);
1137         if (!notifies) {
1138                 return ENOMEM;
1139         }
1140
1141         for (i = 0; i < num_msgs; i++) {
1142
1143                 msg = &messages[i];
1144
1145                 /* Are we monitoring this event? */
1146
1147                 if (!is_monitoring_event(prn_hnd, msg->type, msg->field)) {
1148                         continue;
1149                 }
1150
1151                 DEBUG(10, ("Sending message type [0x%x] field [0x%2x] "
1152                            "for printer [%s]\n",
1153                            msg->type, msg->field, prn_hnd->sharename));
1154
1155                 /*
1156                  * if the is a printer notification handle and not a job
1157                  * notification type, then set the id to 0.
1158                  * Otherwise just use what was specified in the message.
1159                  *
1160                  * When registering change notification on a print server
1161                  * handle we always need to send back the id (snum) matching
1162                  * the printer for which the change took place.
1163                  * For change notify registered on a printer handle,
1164                  * this does not matter and the id should be 0.
1165                  *
1166                  * --jerry
1167                  */
1168
1169                 if ((msg->type == PRINTER_NOTIFY_TYPE) &&
1170                     (prn_hnd->printer_type == SPLHND_PRINTER)) {
1171                         id = 0;
1172                 } else {
1173                         id = msg->id;
1174                 }
1175
1176                 /* Convert unix jobid to smb jobid */
1177
1178                 if (msg->flags & SPOOLSS_NOTIFY_MSG_UNIX_JOBID) {
1179                         id = sysjob_to_jobid(msg->id);
1180
1181                         if (id == -1) {
1182                                 DEBUG(3, ("no such unix jobid %d\n",
1183                                           msg->id));
1184                                 continue;
1185                         }
1186                 }
1187
1188                 construct_info_data(&notifies[count],
1189                                     msg->type, msg->field, id);
1190
1191                 switch(msg->type) {
1192                 case PRINTER_NOTIFY_TYPE:
1193                         if (printer_notify_table[msg->field].fn) {
1194                                 printer_notify_table[msg->field].fn(msg,
1195                                                 &notifies[count], mem_ctx);
1196                         }
1197                         break;
1198
1199                 case JOB_NOTIFY_TYPE:
1200                         if (job_notify_table[msg->field].fn) {
1201                                 job_notify_table[msg->field].fn(msg,
1202                                                 &notifies[count], mem_ctx);
1203                         }
1204                         break;
1205
1206                 default:
1207                         DEBUG(5, ("Unknown notification type %d\n",
1208                                   msg->type));
1209                         continue;
1210                 }
1211
1212                 count++;
1213         }
1214
1215         *_notifies = notifies;
1216         *_count = count;
1217
1218         return 0;
1219 }
1220
1221 static int send_notify2_printer(TALLOC_CTX *mem_ctx,
1222                                 struct printer_handle *prn_hnd,
1223                                 SPOOLSS_NOTIFY_MSG_GROUP *msg_group)
1224 {
1225         struct spoolss_Notify *notifies;
1226         int count = 0;
1227         union spoolss_ReplyPrinterInfo info;
1228         struct spoolss_NotifyInfo info0;
1229         uint32_t reply_result;
1230         NTSTATUS status;
1231         WERROR werr;
1232         int ret;
1233
1234         /* Is there notification on this handle? */
1235         if (prn_hnd->notify.cli_chan == NULL ||
1236             prn_hnd->notify.cli_chan->cli_pipe == NULL ||
1237             prn_hnd->notify.cli_chan->cli_pipe->binding_handle == NULL ||
1238             prn_hnd->notify.cli_chan->active_connections == 0) {
1239                 return 0;
1240         }
1241
1242         DEBUG(10, ("Client connected! [\\\\%s\\%s]\n",
1243                    prn_hnd->servername, prn_hnd->sharename));
1244
1245         /* For this printer? Print servers always receive notifications. */
1246         if ((prn_hnd->printer_type == SPLHND_PRINTER)  &&
1247             (!strequal(msg_group->printername, prn_hnd->sharename))) {
1248                 return 0;
1249         }
1250
1251         DEBUG(10,("Our printer\n"));
1252
1253         /* build the array of change notifications */
1254         ret = build_notify2_messages(mem_ctx, prn_hnd,
1255                                      msg_group->msgs,
1256                                      msg_group->num_msgs,
1257                                      &notifies, &count);
1258         if (ret) {
1259                 return ret;
1260         }
1261
1262         info0.version   = 0x2;
1263         info0.flags     = count ? 0x00020000 /* ??? */ : PRINTER_NOTIFY_INFO_DISCARDED;
1264         info0.count     = count;
1265         info0.notifies  = notifies;
1266
1267         info.info0 = &info0;
1268
1269         status = dcerpc_spoolss_RouterReplyPrinterEx(
1270                                 prn_hnd->notify.cli_chan->cli_pipe->binding_handle,
1271                                 mem_ctx,
1272                                 &prn_hnd->notify.cli_hnd,
1273                                 prn_hnd->notify.change, /* color */
1274                                 prn_hnd->notify.flags,
1275                                 &reply_result,
1276                                 0, /* reply_type, must be 0 */
1277                                 info, &werr);
1278         if (!NT_STATUS_IS_OK(status)) {
1279                 DEBUG(1, ("dcerpc_spoolss_RouterReplyPrinterEx to client: %s "
1280                           "failed: %s\n",
1281                           prn_hnd->notify.cli_chan->cli_pipe->srv_name_slash,
1282                           nt_errstr(status)));
1283                 werr = ntstatus_to_werror(status);
1284         } else if (!W_ERROR_IS_OK(werr)) {
1285                 DEBUG(1, ("RouterReplyPrinterEx to client: %s "
1286                           "failed: %s\n",
1287                           prn_hnd->notify.cli_chan->cli_pipe->srv_name_slash,
1288                           win_errstr(werr)));
1289         }
1290         switch (reply_result) {
1291         case 0:
1292                 break;
1293         case PRINTER_NOTIFY_INFO_DISCARDED:
1294         case PRINTER_NOTIFY_INFO_DISCARDNOTED:
1295         case PRINTER_NOTIFY_INFO_COLOR_MISMATCH:
1296                 break;
1297         default:
1298                 break;
1299         }
1300
1301         return 0;
1302 }
1303
1304 static void send_notify2_changes( SPOOLSS_NOTIFY_MSG_CTR *ctr, uint32_t idx )
1305 {
1306         struct printer_handle    *p;
1307         TALLOC_CTX               *mem_ctx = notify_ctr_getctx( ctr );
1308         SPOOLSS_NOTIFY_MSG_GROUP *msg_group = notify_ctr_getgroup( ctr, idx );
1309         int ret;
1310
1311         if ( !msg_group ) {
1312                 DEBUG(5,("send_notify2_changes() called with no msg group!\n"));
1313                 return;
1314         }
1315
1316         if (!msg_group->msgs) {
1317                 DEBUG(5, ("send_notify2_changes() called with no messages!\n"));
1318                 return;
1319         }
1320
1321         DEBUG(8,("send_notify2_changes: Enter...[%s]\n", msg_group->printername));
1322
1323         /* loop over all printers */
1324
1325         for (p = printers_list; p; p = p->next) {
1326                 ret = send_notify2_printer(mem_ctx, p, msg_group);
1327                 if (ret) {
1328                         goto done;
1329                 }
1330         }
1331
1332 done:
1333         DEBUG(8,("send_notify2_changes: Exit...\n"));
1334         return;
1335 }
1336
1337 /***********************************************************************
1338  **********************************************************************/
1339
1340 static bool notify2_unpack_msg( SPOOLSS_NOTIFY_MSG *msg, struct timeval *tv, void *buf, size_t len )
1341 {
1342
1343         uint32_t tv_sec, tv_usec;
1344         size_t offset = 0;
1345
1346         /* Unpack message */
1347
1348         offset += tdb_unpack((uint8_t *)buf + offset, len - offset, "f",
1349                              msg->printer);
1350
1351         offset += tdb_unpack((uint8_t *)buf + offset, len - offset, "ddddddd",
1352                                 &tv_sec, &tv_usec,
1353                                 &msg->type, &msg->field, &msg->id, &msg->len, &msg->flags);
1354
1355         if (msg->len == 0)
1356                 tdb_unpack((uint8_t *)buf + offset, len - offset, "dd",
1357                            &msg->notify.value[0], &msg->notify.value[1]);
1358         else
1359                 tdb_unpack((uint8_t *)buf + offset, len - offset, "B",
1360                            &msg->len, &msg->notify.data);
1361
1362         DEBUG(3, ("notify2_unpack_msg: got NOTIFY2 message for printer %s, jobid %u type %d, field 0x%02x, flags 0x%04x\n",
1363                   msg->printer, (unsigned int)msg->id, msg->type, msg->field, msg->flags));
1364
1365         tv->tv_sec = tv_sec;
1366         tv->tv_usec = tv_usec;
1367
1368         if (msg->len == 0)
1369                 DEBUG(3, ("notify2_unpack_msg: value1 = %d, value2 = %d\n", msg->notify.value[0],
1370                           msg->notify.value[1]));
1371         else
1372                 dump_data(3, (uint8_t *)msg->notify.data, msg->len);
1373
1374         return true;
1375 }
1376
1377 /********************************************************************
1378  Receive a notify2 message list
1379  ********************************************************************/
1380
1381 static void receive_notify2_message_list(struct messaging_context *msg,
1382                                          void *private_data,
1383                                          uint32_t msg_type,
1384                                          struct server_id server_id,
1385                                          DATA_BLOB *data)
1386 {
1387         size_t                  msg_count, i;
1388         char                    *buf = (char *)data->data;
1389         char                    *msg_ptr;
1390         size_t                  msg_len;
1391         SPOOLSS_NOTIFY_MSG      notify;
1392         SPOOLSS_NOTIFY_MSG_CTR  messages;
1393         int                     num_groups;
1394
1395         if (data->length < 4) {
1396                 DEBUG(0,("receive_notify2_message_list: bad message format (len < 4)!\n"));
1397                 return;
1398         }
1399
1400         msg_count = IVAL(buf, 0);
1401         msg_ptr = buf + 4;
1402
1403         DEBUG(5, ("receive_notify2_message_list: got %lu messages in list\n", (unsigned long)msg_count));
1404
1405         if (msg_count == 0) {
1406                 DEBUG(0,("receive_notify2_message_list: bad message format (msg_count == 0) !\n"));
1407                 return;
1408         }
1409
1410         /* initialize the container */
1411
1412         ZERO_STRUCT( messages );
1413         notify_msg_ctr_init( &messages );
1414
1415         /*
1416          * build message groups for each printer identified
1417          * in a change_notify msg.  Remember that a PCN message
1418          * includes the handle returned for the srv_spoolss_replyopenprinter()
1419          * call.  Therefore messages are grouped according to printer handle.
1420          */
1421
1422         for ( i=0; i<msg_count; i++ ) {
1423                 struct timeval msg_tv;
1424
1425                 if (msg_ptr + 4 - buf > data->length) {
1426                         DEBUG(0,("receive_notify2_message_list: bad message format (len > buf_size) !\n"));
1427                         return;
1428                 }
1429
1430                 msg_len = IVAL(msg_ptr,0);
1431                 msg_ptr += 4;
1432
1433                 if (msg_ptr + msg_len - buf > data->length) {
1434                         DEBUG(0,("receive_notify2_message_list: bad message format (bad len) !\n"));
1435                         return;
1436                 }
1437
1438                 /* unpack messages */
1439
1440                 ZERO_STRUCT( notify );
1441                 notify2_unpack_msg( &notify, &msg_tv, msg_ptr, msg_len );
1442                 msg_ptr += msg_len;
1443
1444                 /* add to correct list in container */
1445
1446                 notify_msg_ctr_addmsg( &messages, &notify );
1447
1448                 /* free memory that might have been allocated by notify2_unpack_msg() */
1449
1450                 if ( notify.len != 0 )
1451                         SAFE_FREE( notify.notify.data );
1452         }
1453
1454         /* process each group of messages */
1455
1456         num_groups = notify_msg_ctr_numgroups( &messages );
1457         for ( i=0; i<num_groups; i++ )
1458                 send_notify2_changes( &messages, i );
1459
1460
1461         /* cleanup */
1462
1463         DEBUG(10,("receive_notify2_message_list: processed %u messages\n",
1464                 (uint32_t)msg_count ));
1465
1466         notify_msg_ctr_destroy( &messages );
1467
1468         return;
1469 }
1470
1471 /********************************************************************
1472  Send a message to ourself about new driver being installed
1473  so we can upgrade the information for each printer bound to this
1474  driver
1475  ********************************************************************/
1476
1477 static bool srv_spoolss_drv_upgrade_printer(const char *drivername,
1478                                             struct messaging_context *msg_ctx)
1479 {
1480         int len = strlen(drivername);
1481
1482         if (!len)
1483                 return false;
1484
1485         DEBUG(10,("srv_spoolss_drv_upgrade_printer: Sending message about driver upgrade [%s]\n",
1486                 drivername));
1487
1488         messaging_send_buf(msg_ctx, messaging_server_id(msg_ctx),
1489                            MSG_PRINTER_DRVUPGRADE,
1490                            (const uint8_t *)drivername, len+1);
1491
1492         return true;
1493 }
1494
1495 void srv_spoolss_cleanup(void)
1496 {
1497         struct printer_session_counter *session_counter;
1498
1499         for (session_counter = counter_list;
1500              session_counter != NULL;
1501              session_counter = counter_list) {
1502                 DLIST_REMOVE(counter_list, session_counter);
1503                 TALLOC_FREE(session_counter);
1504         }
1505 }
1506
1507 /**********************************************************************
1508  callback to receive a MSG_PRINTER_DRVUPGRADE message and interate
1509  over all printers, upgrading ones as necessary
1510  This is now *ONLY* called inside the background lpq updater. JRA.
1511  **********************************************************************/
1512
1513 void do_drv_upgrade_printer(struct messaging_context *msg,
1514                             void *private_data,
1515                             uint32_t msg_type,
1516                             struct server_id server_id,
1517                             DATA_BLOB *data)
1518 {
1519         TALLOC_CTX *tmp_ctx;
1520         const struct auth_session_info *session_info = get_session_info_system();
1521         struct spoolss_PrinterInfo2 *pinfo2;
1522         WERROR result;
1523         const char *drivername;
1524         int snum;
1525         int n_services = lp_numservices();
1526         struct dcerpc_binding_handle *b = NULL;
1527
1528         tmp_ctx = talloc_new(NULL);
1529         if (!tmp_ctx) return;
1530
1531         drivername = talloc_strndup(tmp_ctx, (const char *)data->data, data->length);
1532         if (!drivername) {
1533                 DEBUG(0, ("do_drv_upgrade_printer: Out of memoery ?!\n"));
1534                 goto done;
1535         }
1536
1537         DEBUG(10, ("do_drv_upgrade_printer: "
1538                    "Got message for new driver [%s]\n", drivername));
1539
1540         /* Iterate the printer list */
1541
1542         for (snum = 0; snum < n_services; snum++) {
1543                 if (!lp_snum_ok(snum) || !lp_printable(snum)) {
1544                         continue;
1545                 }
1546
1547                 /* ignore [printers] share */
1548                 if (strequal(lp_const_servicename(snum), "printers")) {
1549                         continue;
1550                 }
1551
1552                 if (b == NULL) {
1553                         result = winreg_printer_binding_handle(tmp_ctx,
1554                                                                session_info,
1555                                                                msg,
1556                                                                &b);
1557                         if (!W_ERROR_IS_OK(result)) {
1558                                 break;
1559                         }
1560                 }
1561
1562                 result = winreg_get_printer(tmp_ctx, b,
1563                                             lp_const_servicename(snum),
1564                                             &pinfo2);
1565
1566                 if (!W_ERROR_IS_OK(result)) {
1567                         continue;
1568                 }
1569
1570                 if (!pinfo2->drivername) {
1571                         continue;
1572                 }
1573
1574                 if (strcmp(drivername, pinfo2->drivername) != 0) {
1575                         continue;
1576                 }
1577
1578                 DEBUG(6,("Updating printer [%s]\n", pinfo2->printername));
1579
1580                 /* all we care about currently is the change_id */
1581                 result = winreg_printer_update_changeid(tmp_ctx, b,
1582                                                         pinfo2->printername);
1583
1584                 if (!W_ERROR_IS_OK(result)) {
1585                         DEBUG(3, ("do_drv_upgrade_printer: "
1586                                   "Failed to update changeid [%s]\n",
1587                                   win_errstr(result)));
1588                 }
1589         }
1590
1591         /* all done */
1592 done:
1593         talloc_free(tmp_ctx);
1594 }
1595
1596 /********************************************************************
1597  Update the cache for all printq's with a registered client
1598  connection
1599  ********************************************************************/
1600
1601 void update_monitored_printq_cache(struct messaging_context *msg_ctx)
1602 {
1603         struct printer_handle *printer = printers_list;
1604         int snum;
1605
1606         /* loop through all printers and update the cache where
1607            a client is connected */
1608         while (printer) {
1609                 if ((printer->printer_type == SPLHND_PRINTER) &&
1610                     ((printer->notify.cli_chan != NULL) &&
1611                      (printer->notify.cli_chan->active_connections > 0))) {
1612                         snum = print_queue_snum(printer->sharename);
1613                         print_queue_status(msg_ctx, snum, NULL, NULL);
1614                 }
1615
1616                 printer = printer->next;
1617         }
1618
1619         return;
1620 }
1621
1622 /****************************************************************
1623  _spoolss_OpenPrinter
1624 ****************************************************************/
1625
1626 WERROR _spoolss_OpenPrinter(struct pipes_struct *p,
1627                             struct spoolss_OpenPrinter *r)
1628 {
1629         struct spoolss_OpenPrinterEx e;
1630         struct spoolss_UserLevel1 level1;
1631         WERROR werr;
1632
1633         ZERO_STRUCT(level1);
1634
1635         e.in.printername        = r->in.printername;
1636         e.in.datatype           = r->in.datatype;
1637         e.in.devmode_ctr        = r->in.devmode_ctr;
1638         e.in.access_mask        = r->in.access_mask;
1639         e.in.userlevel_ctr.level                = 1;
1640         e.in.userlevel_ctr.user_info.level1     = &level1;
1641
1642         e.out.handle            = r->out.handle;
1643
1644         werr = _spoolss_OpenPrinterEx(p, &e);
1645
1646         if (W_ERROR_EQUAL(werr, WERR_INVALID_PARAM)) {
1647                 /* OpenPrinterEx returns this for a bad
1648                  * printer name. We must return WERR_INVALID_PRINTER_NAME
1649                  * instead.
1650                  */
1651                 werr = WERR_INVALID_PRINTER_NAME;
1652         }
1653
1654         return werr;
1655 }
1656
1657 static WERROR copy_devicemode(TALLOC_CTX *mem_ctx,
1658                               struct spoolss_DeviceMode *orig,
1659                               struct spoolss_DeviceMode **dest)
1660 {
1661         struct spoolss_DeviceMode *dm;
1662
1663         dm = talloc(mem_ctx, struct spoolss_DeviceMode);
1664         if (!dm) {
1665                 return WERR_NOMEM;
1666         }
1667
1668         /* copy all values, then duplicate strings and structs */
1669         *dm = *orig;
1670
1671         dm->devicename = talloc_strdup(dm, orig->devicename);
1672         if (!dm->devicename) {
1673                 return WERR_NOMEM;
1674         }
1675         dm->formname = talloc_strdup(dm, orig->formname);
1676         if (!dm->formname) {
1677                 return WERR_NOMEM;
1678         }
1679         if (orig->driverextra_data.data) {
1680                 dm->driverextra_data.data =
1681                         (uint8_t *) talloc_memdup(dm, orig->driverextra_data.data,
1682                                         orig->driverextra_data.length);
1683                 if (!dm->driverextra_data.data) {
1684                         return WERR_NOMEM;
1685                 }
1686         }
1687
1688         *dest = dm;
1689         return WERR_OK;
1690 }
1691
1692 /****************************************************************
1693  _spoolss_OpenPrinterEx
1694 ****************************************************************/
1695
1696 WERROR _spoolss_OpenPrinterEx(struct pipes_struct *p,
1697                               struct spoolss_OpenPrinterEx *r)
1698 {
1699         int snum;
1700         char *raddr;
1701         char *rhost;
1702         struct printer_handle *Printer=NULL;
1703         WERROR result;
1704         int rc;
1705
1706         if (!r->in.printername) {
1707                 return WERR_INVALID_PARAM;
1708         }
1709
1710         if (!*r->in.printername) {
1711                 return WERR_INVALID_PARAM;
1712         }
1713
1714         if (r->in.userlevel_ctr.level > 3) {
1715                 return WERR_INVALID_PARAM;
1716         }
1717         if ((r->in.userlevel_ctr.level == 1 && !r->in.userlevel_ctr.user_info.level1) ||
1718             (r->in.userlevel_ctr.level == 2 && !r->in.userlevel_ctr.user_info.level2) ||
1719             (r->in.userlevel_ctr.level == 3 && !r->in.userlevel_ctr.user_info.level3)) {
1720                 return WERR_INVALID_PARAM;
1721         }
1722
1723         /* some sanity check because you can open a printer or a print server */
1724         /* aka: \\server\printer or \\server */
1725
1726         DEBUGADD(3,("checking name: %s\n", r->in.printername));
1727
1728         result = open_printer_hnd(p, r->out.handle, r->in.printername, 0);
1729         if (!W_ERROR_IS_OK(result)) {
1730                 DEBUG(3,("_spoolss_OpenPrinterEx: Cannot open a printer handle "
1731                         "for printer %s\n", r->in.printername));
1732                 ZERO_STRUCTP(r->out.handle);
1733                 return result;
1734         }
1735
1736         Printer = find_printer_index_by_hnd(p, r->out.handle);
1737         if ( !Printer ) {
1738                 DEBUG(0,("_spoolss_OpenPrinterEx: logic error.  Can't find printer "
1739                         "handle we created for printer %s\n", r->in.printername));
1740                 close_printer_handle(p, r->out.handle);
1741                 ZERO_STRUCTP(r->out.handle);
1742                 return WERR_INVALID_PARAM;
1743         }
1744
1745         /*
1746          * First case: the user is opening the print server:
1747          *
1748          * Disallow MS AddPrinterWizard if parameter disables it. A Win2k
1749          * client 1st tries an OpenPrinterEx with access==0, MUST be allowed.
1750          *
1751          * Then both Win2k and WinNT clients try an OpenPrinterEx with
1752          * SERVER_ALL_ACCESS, which we allow only if the user is root (uid=0)
1753          * or if the user is listed in the smb.conf printer admin parameter.
1754          *
1755          * Then they try OpenPrinterEx with SERVER_READ which we allow. This lets the
1756          * client view printer folder, but does not show the MSAPW.
1757          *
1758          * Note: this test needs code to check access rights here too. Jeremy
1759          * could you look at this?
1760          *
1761          * Second case: the user is opening a printer:
1762          * NT doesn't let us connect to a printer if the connecting user
1763          * doesn't have print permission.
1764          *
1765          * Third case: user is opening a Port Monitor
1766          * access checks same as opening a handle to the print server.
1767          */
1768
1769         switch (Printer->printer_type )
1770         {
1771         case SPLHND_SERVER:
1772         case SPLHND_PORTMON_TCP:
1773         case SPLHND_PORTMON_LOCAL:
1774                 /* Printserver handles use global struct... */
1775
1776                 snum = -1;
1777
1778                 /* Map standard access rights to object specific access rights */
1779
1780                 se_map_standard(&r->in.access_mask,
1781                                 &printserver_std_mapping);
1782
1783                 /* Deny any object specific bits that don't apply to print
1784                    servers (i.e printer and job specific bits) */
1785
1786                 r->in.access_mask &= SEC_MASK_SPECIFIC;
1787
1788                 if (r->in.access_mask &
1789                     ~(SERVER_ACCESS_ADMINISTER | SERVER_ACCESS_ENUMERATE)) {
1790                         DEBUG(3, ("access DENIED for non-printserver bits\n"));
1791                         close_printer_handle(p, r->out.handle);
1792                         ZERO_STRUCTP(r->out.handle);
1793                         return WERR_ACCESS_DENIED;
1794                 }
1795
1796                 /* Allow admin access */
1797
1798                 if ( r->in.access_mask & SERVER_ACCESS_ADMINISTER )
1799                 {
1800                         if (!lp_show_add_printer_wizard()) {
1801                                 close_printer_handle(p, r->out.handle);
1802                                 ZERO_STRUCTP(r->out.handle);
1803                                 return WERR_ACCESS_DENIED;
1804                         }
1805
1806                         /* if the user is not root, doesn't have SE_PRINT_OPERATOR privilege,
1807                            and not a printer admin, then fail */
1808
1809                         if ((p->session_info->unix_token->uid != sec_initial_uid()) &&
1810                             !security_token_has_privilege(p->session_info->security_token, SEC_PRIV_PRINT_OPERATOR) &&
1811                             !nt_token_check_sid(&global_sid_Builtin_Print_Operators,
1812                                                 p->session_info->security_token)) {
1813                                 close_printer_handle(p, r->out.handle);
1814                                 ZERO_STRUCTP(r->out.handle);
1815                                 DEBUG(3,("access DENIED as user is not root, "
1816                                         "has no printoperator privilege, "
1817                                         "not a member of the printoperator builtin group and "
1818                                         "is not in printer admin list"));
1819                                 return WERR_ACCESS_DENIED;
1820                         }
1821
1822                         r->in.access_mask = SERVER_ACCESS_ADMINISTER;
1823                 }
1824                 else
1825                 {
1826                         r->in.access_mask = SERVER_ACCESS_ENUMERATE;
1827                 }
1828
1829                 DEBUG(4,("Setting print server access = %s\n", (r->in.access_mask == SERVER_ACCESS_ADMINISTER)
1830                         ? "SERVER_ACCESS_ADMINISTER" : "SERVER_ACCESS_ENUMERATE" ));
1831
1832                 /* We fall through to return WERR_OK */
1833                 break;
1834
1835         case SPLHND_PRINTER:
1836                 /* NT doesn't let us connect to a printer if the connecting user
1837                    doesn't have print permission.  */
1838
1839                 if (!get_printer_snum(p, r->out.handle, &snum, NULL)) {
1840                         close_printer_handle(p, r->out.handle);
1841                         ZERO_STRUCTP(r->out.handle);
1842                         return WERR_BADFID;
1843                 }
1844
1845                 if (r->in.access_mask == SEC_FLAG_MAXIMUM_ALLOWED) {
1846                         r->in.access_mask = PRINTER_ACCESS_ADMINISTER;
1847                 }
1848
1849                 se_map_standard(&r->in.access_mask, &printer_std_mapping);
1850
1851                 /* map an empty access mask to the minimum access mask */
1852                 if (r->in.access_mask == 0x0)
1853                         r->in.access_mask = PRINTER_ACCESS_USE;
1854
1855                 /*
1856                  * If we are not serving the printer driver for this printer,
1857                  * map PRINTER_ACCESS_ADMINISTER to PRINTER_ACCESS_USE.  This
1858                  * will keep NT clients happy  --jerry
1859                  */
1860
1861                 if (lp_use_client_driver(snum)
1862                         && (r->in.access_mask & PRINTER_ACCESS_ADMINISTER))
1863                 {
1864                         r->in.access_mask = PRINTER_ACCESS_USE;
1865                 }
1866
1867                 /* check smb.conf parameters and the the sec_desc */
1868                 raddr = tsocket_address_inet_addr_string(p->remote_address,
1869                                                          p->mem_ctx);
1870                 if (raddr == NULL) {
1871                         return WERR_NOMEM;
1872                 }
1873
1874                 rc = get_remote_hostname(p->remote_address,
1875                                          &rhost,
1876                                          p->mem_ctx);
1877                 if (rc < 0) {
1878                         return WERR_NOMEM;
1879                 }
1880                 if (strequal(rhost, "UNKNOWN")) {
1881                         rhost = raddr;
1882                 }
1883
1884                 if (!allow_access(lp_hosts_deny(snum), lp_hosts_allow(snum),
1885                                   rhost, raddr)) {
1886                         DEBUG(3, ("access DENIED (hosts allow/deny) for printer open\n"));
1887                         ZERO_STRUCTP(r->out.handle);
1888                         return WERR_ACCESS_DENIED;
1889                 }
1890
1891                 if (!user_ok_token(uidtoname(p->session_info->unix_token->uid), NULL,
1892                                    p->session_info->security_token, snum) ||
1893                     !W_ERROR_IS_OK(print_access_check(p->session_info,
1894                                                       p->msg_ctx,
1895                                                       snum,
1896                                                       r->in.access_mask))) {
1897                         DEBUG(3, ("access DENIED for printer open\n"));
1898                         close_printer_handle(p, r->out.handle);
1899                         ZERO_STRUCTP(r->out.handle);
1900                         return WERR_ACCESS_DENIED;
1901                 }
1902
1903                 if ((r->in.access_mask & SEC_MASK_SPECIFIC)& ~(PRINTER_ACCESS_ADMINISTER|PRINTER_ACCESS_USE)) {
1904                         DEBUG(3, ("access DENIED for printer open - unknown bits\n"));
1905                         close_printer_handle(p, r->out.handle);
1906                         ZERO_STRUCTP(r->out.handle);
1907                         return WERR_ACCESS_DENIED;
1908                 }
1909
1910                 if (r->in.access_mask & PRINTER_ACCESS_ADMINISTER)
1911                         r->in.access_mask = PRINTER_ACCESS_ADMINISTER;
1912                 else
1913                         r->in.access_mask = PRINTER_ACCESS_USE;
1914
1915                 DEBUG(4,("Setting printer access = %s\n", (r->in.access_mask == PRINTER_ACCESS_ADMINISTER)
1916                         ? "PRINTER_ACCESS_ADMINISTER" : "PRINTER_ACCESS_USE" ));
1917
1918                 winreg_create_printer_internal(p->mem_ctx,
1919                                       get_session_info_system(),
1920                                       p->msg_ctx,
1921                                       lp_const_servicename(snum));
1922
1923                 break;
1924
1925         default:
1926                 /* sanity check to prevent programmer error */
1927                 ZERO_STRUCTP(r->out.handle);
1928                 return WERR_BADFID;
1929         }
1930
1931         Printer->access_granted = r->in.access_mask;
1932
1933         /*
1934          * If the client sent a devmode in the OpenPrinter() call, then
1935          * save it here in case we get a job submission on this handle
1936          */
1937
1938          if ((Printer->printer_type != SPLHND_SERVER)
1939           && (r->in.devmode_ctr.devmode != NULL)) {
1940                 copy_devicemode(NULL, r->in.devmode_ctr.devmode,
1941                                 &Printer->devmode);
1942          }
1943
1944         return WERR_OK;
1945 }
1946
1947 /****************************************************************
1948  _spoolss_ClosePrinter
1949 ****************************************************************/
1950
1951 WERROR _spoolss_ClosePrinter(struct pipes_struct *p,
1952                              struct spoolss_ClosePrinter *r)
1953 {
1954         struct printer_handle *Printer = find_printer_index_by_hnd(p, r->in.handle);
1955
1956         if (Printer && Printer->document_started) {
1957                 struct spoolss_EndDocPrinter e;
1958
1959                 e.in.handle = r->in.handle;
1960
1961                 _spoolss_EndDocPrinter(p, &e);
1962         }
1963
1964         if (!close_printer_handle(p, r->in.handle))
1965                 return WERR_BADFID;
1966
1967         /* clear the returned printer handle.  Observed behavior
1968            from Win2k server.  Don't think this really matters.
1969            Previous code just copied the value of the closed
1970            handle.    --jerry */
1971
1972         ZERO_STRUCTP(r->out.handle);
1973
1974         return WERR_OK;
1975 }
1976
1977 /****************************************************************
1978  _spoolss_DeletePrinter
1979 ****************************************************************/
1980
1981 WERROR _spoolss_DeletePrinter(struct pipes_struct *p,
1982                               struct spoolss_DeletePrinter *r)
1983 {
1984         struct printer_handle *Printer = find_printer_index_by_hnd(p, r->in.handle);
1985         WERROR result;
1986         int snum;
1987
1988         if (Printer && Printer->document_started) {
1989                 struct spoolss_EndDocPrinter e;
1990
1991                 e.in.handle = r->in.handle;
1992
1993                 _spoolss_EndDocPrinter(p, &e);
1994         }
1995
1996         if (get_printer_snum(p, r->in.handle, &snum, NULL)) {
1997                 winreg_delete_printer_key_internal(p->mem_ctx,
1998                                           get_session_info_system(),
1999                                           p->msg_ctx,
2000                                           lp_const_servicename(snum),
2001                                           "");
2002         }
2003
2004         result = delete_printer_handle(p, r->in.handle);
2005
2006         return result;
2007 }
2008
2009 /*******************************************************************
2010  * static function to lookup the version id corresponding to an
2011  * long architecture string
2012  ******************************************************************/
2013
2014 static const struct print_architecture_table_node archi_table[]= {
2015
2016         {"Windows 4.0",          SPL_ARCH_WIN40,        0 },
2017         {"Windows NT x86",       SPL_ARCH_W32X86,       2 },
2018         {"Windows NT R4000",     SPL_ARCH_W32MIPS,      2 },
2019         {"Windows NT Alpha_AXP", SPL_ARCH_W32ALPHA,     2 },
2020         {"Windows NT PowerPC",   SPL_ARCH_W32PPC,       2 },
2021         {"Windows IA64",         SPL_ARCH_IA64,         3 },
2022         {"Windows x64",          SPL_ARCH_X64,          3 },
2023         {NULL,                   "",            -1 }
2024 };
2025
2026 static const int drv_cversion[] = {SPOOLSS_DRIVER_VERSION_9X,
2027                                    SPOOLSS_DRIVER_VERSION_NT35,
2028                                    SPOOLSS_DRIVER_VERSION_NT4,
2029                                    SPOOLSS_DRIVER_VERSION_200X,
2030                                    -1};
2031
2032 static int get_version_id(const char *arch)
2033 {
2034         int i;
2035
2036         for (i=0; archi_table[i].long_archi != NULL; i++)
2037         {
2038                 if (strcmp(arch, archi_table[i].long_archi) == 0)
2039                         return (archi_table[i].version);
2040         }
2041
2042         return -1;
2043 }
2044
2045 /****************************************************************
2046  _spoolss_DeletePrinterDriver
2047 ****************************************************************/
2048
2049 WERROR _spoolss_DeletePrinterDriver(struct pipes_struct *p,
2050                                     struct spoolss_DeletePrinterDriver *r)
2051 {
2052
2053         struct spoolss_DriverInfo8 *info = NULL;
2054         int                             version;
2055         WERROR                          status;
2056         struct dcerpc_binding_handle *b;
2057         TALLOC_CTX *tmp_ctx = NULL;
2058         int i;
2059         bool found;
2060
2061         /* if the user is not root, doesn't have SE_PRINT_OPERATOR privilege,
2062            and not a printer admin, then fail */
2063
2064         if ((p->session_info->unix_token->uid != sec_initial_uid()) &&
2065             !security_token_has_privilege(p->session_info->security_token,
2066                                           SEC_PRIV_PRINT_OPERATOR)) {
2067                 return WERR_ACCESS_DENIED;
2068         }
2069
2070         /* check that we have a valid driver name first */
2071
2072         if ((version = get_version_id(r->in.architecture)) == -1) {
2073                 return WERR_INVALID_ENVIRONMENT;
2074         }
2075
2076         tmp_ctx = talloc_new(p->mem_ctx);
2077         if (!tmp_ctx) {
2078                 return WERR_NOMEM;
2079         }
2080
2081         status = winreg_printer_binding_handle(tmp_ctx,
2082                                                get_session_info_system(),
2083                                                p->msg_ctx,
2084                                                &b);
2085         if (!W_ERROR_IS_OK(status)) {
2086                 goto done;
2087         }
2088
2089         for (found = false, i = 0; drv_cversion[i] >= 0; i++) {
2090                 status = winreg_get_driver(tmp_ctx, b,
2091                                            r->in.architecture, r->in.driver,
2092                                            drv_cversion[i], &info);
2093                 if (!W_ERROR_IS_OK(status)) {
2094                         DEBUG(5, ("skipping del of driver with version %d\n",
2095                                   drv_cversion[i]));
2096                         continue;
2097                 }
2098                 found = true;
2099
2100                 if (printer_driver_in_use(tmp_ctx, b, info)) {
2101                         status = WERR_PRINTER_DRIVER_IN_USE;
2102                         goto done;
2103                 }
2104
2105                 status = winreg_del_driver(tmp_ctx, b, info, drv_cversion[i]);
2106                 if (!W_ERROR_IS_OK(status)) {
2107                         DEBUG(0, ("failed del of driver with version %d\n",
2108                                   drv_cversion[i]));
2109                         goto done;
2110                 }
2111         }
2112         if (found == false) {
2113                 DEBUG(0, ("driver %s not found for deletion\n", r->in.driver));
2114                 status = WERR_UNKNOWN_PRINTER_DRIVER;
2115         } else {
2116                 status = WERR_OK;
2117         }
2118
2119 done:
2120         talloc_free(tmp_ctx);
2121
2122         return status;
2123 }
2124
2125 static WERROR spoolss_dpd_version(TALLOC_CTX *mem_ctx,
2126                                   struct pipes_struct *p,
2127                                   struct spoolss_DeletePrinterDriverEx *r,
2128                                   struct dcerpc_binding_handle *b,
2129                                   struct spoolss_DriverInfo8 *info)
2130 {
2131         WERROR status;
2132         bool delete_files;
2133
2134         if (printer_driver_in_use(mem_ctx, b, info)) {
2135                 status = WERR_PRINTER_DRIVER_IN_USE;
2136                 goto done;
2137         }
2138
2139         /*
2140          * we have a couple of cases to consider.
2141          * (1) Are any files in use?  If so and DPD_DELETE_ALL_FILES is set,
2142          *     then the delete should fail if **any** files overlap with
2143          *     other drivers
2144          * (2) If DPD_DELETE_UNUSED_FILES is set, then delete all
2145          *     non-overlapping files
2146          * (3) If neither DPD_DELETE_ALL_FILES nor DPD_DELETE_UNUSED_FILES
2147          *     are set, then do not delete any files
2148          * Refer to MSDN docs on DeletePrinterDriverEx() for details.
2149          */
2150
2151         delete_files = r->in.delete_flags
2152                         & (DPD_DELETE_ALL_FILES | DPD_DELETE_UNUSED_FILES);
2153
2154
2155         if (delete_files) {
2156                 bool in_use = printer_driver_files_in_use(mem_ctx, b, info);
2157                 if (in_use && (r->in.delete_flags & DPD_DELETE_ALL_FILES)) {
2158                         status = WERR_PRINTER_DRIVER_IN_USE;
2159                         goto done;
2160                 }
2161                 /*
2162                  * printer_driver_files_in_use() has trimmed overlapping files
2163                  * from info so they are not removed on DPD_DELETE_UNUSED_FILES
2164                  */
2165         }
2166
2167
2168         status = winreg_del_driver(mem_ctx, b, info, info->version);
2169         if (!W_ERROR_IS_OK(status)) {
2170                 goto done;
2171         }
2172
2173         /*
2174          * now delete any associated files if delete_files is
2175          * true. Even if this part failes, we return succes
2176          * because the driver doesn not exist any more
2177          */
2178         if (delete_files) {
2179                 delete_driver_files(p->session_info, info);
2180         }
2181
2182 done:
2183         return status;
2184 }
2185
2186 /****************************************************************
2187  _spoolss_DeletePrinterDriverEx
2188 ****************************************************************/
2189
2190 WERROR _spoolss_DeletePrinterDriverEx(struct pipes_struct *p,
2191                                       struct spoolss_DeletePrinterDriverEx *r)
2192 {
2193         struct spoolss_DriverInfo8 *info = NULL;
2194         WERROR                          status;
2195         struct dcerpc_binding_handle *b;
2196         TALLOC_CTX *tmp_ctx = NULL;
2197         int i;
2198         bool found;
2199
2200         /* if the user is not root, doesn't have SE_PRINT_OPERATOR privilege,
2201            and not a printer admin, then fail */
2202
2203         if ((p->session_info->unix_token->uid != sec_initial_uid()) &&
2204             !security_token_has_privilege(p->session_info->security_token,
2205                                           SEC_PRIV_PRINT_OPERATOR)) {
2206                 return WERR_ACCESS_DENIED;
2207         }
2208
2209         /* check that we have a valid driver name first */
2210         if (get_version_id(r->in.architecture) == -1) {
2211                 /* this is what NT returns */
2212                 return WERR_INVALID_ENVIRONMENT;
2213         }
2214
2215         tmp_ctx = talloc_new(p->mem_ctx);
2216         if (!tmp_ctx) {
2217                 return WERR_NOMEM;
2218         }
2219
2220         status = winreg_printer_binding_handle(tmp_ctx,
2221                                                get_session_info_system(),
2222                                                p->msg_ctx,
2223                                                &b);
2224         if (!W_ERROR_IS_OK(status)) {
2225                 goto done;
2226         }
2227
2228         for (found = false, i = 0; drv_cversion[i] >= 0; i++) {
2229                 if ((r->in.delete_flags & DPD_DELETE_SPECIFIC_VERSION)
2230                  && (drv_cversion[i] != r->in.version)) {
2231                         continue;
2232                 }
2233
2234                 /* check if a driver with this version exists before delete */
2235                 status = winreg_get_driver(tmp_ctx, b,
2236                                            r->in.architecture, r->in.driver,
2237                                            drv_cversion[i], &info);
2238                 if (!W_ERROR_IS_OK(status)) {
2239                         DEBUG(5, ("skipping del of driver with version %d\n",
2240                                   drv_cversion[i]));
2241                         continue;
2242                 }
2243                 found = true;
2244
2245                 status = spoolss_dpd_version(tmp_ctx, p, r, b, info);
2246                 if (!W_ERROR_IS_OK(status)) {
2247                         DEBUG(0, ("failed to delete driver with version %d\n",
2248                                   drv_cversion[i]));
2249                         goto done;
2250                 }
2251         }
2252         if (found == false) {
2253                 DEBUG(0, ("driver %s not found for deletion\n", r->in.driver));
2254                 status = WERR_UNKNOWN_PRINTER_DRIVER;
2255         } else {
2256                 status = WERR_OK;
2257         }
2258
2259 done:
2260         talloc_free(tmp_ctx);
2261         return status;
2262 }
2263
2264
2265 /********************************************************************
2266  GetPrinterData on a printer server Handle.
2267 ********************************************************************/
2268
2269 static WERROR getprinterdata_printer_server(TALLOC_CTX *mem_ctx,
2270                                             const char *value,
2271                                             enum winreg_Type *type,
2272                                             union spoolss_PrinterData *data)
2273 {
2274         DEBUG(8,("getprinterdata_printer_server:%s\n", value));
2275
2276         if (!strcasecmp_m(value, "W3SvcInstalled")) {
2277                 *type = REG_DWORD;
2278                 SIVAL(&data->value, 0, 0x00);
2279                 return WERR_OK;
2280         }
2281
2282         if (!strcasecmp_m(value, "BeepEnabled")) {
2283                 *type = REG_DWORD;
2284                 SIVAL(&data->value, 0, 0x00);
2285                 return WERR_OK;
2286         }
2287
2288         if (!strcasecmp_m(value, "EventLog")) {
2289                 *type = REG_DWORD;
2290                 /* formally was 0x1b */
2291                 SIVAL(&data->value, 0, 0x00);
2292                 return WERR_OK;
2293         }
2294
2295         if (!strcasecmp_m(value, "NetPopup")) {
2296                 *type = REG_DWORD;
2297                 SIVAL(&data->value, 0, 0x00);
2298                 return WERR_OK;
2299         }
2300
2301         if (!strcasecmp_m(value, "MajorVersion")) {
2302                 *type = REG_DWORD;
2303
2304                 /* Windows NT 4.0 seems to not allow uploading of drivers
2305                    to a server that reports 0x3 as the MajorVersion.
2306                    need to investigate more how Win2k gets around this .
2307                    -- jerry */
2308
2309                 if (RA_WINNT == get_remote_arch()) {
2310                         SIVAL(&data->value, 0, 0x02);
2311                 } else {
2312                         SIVAL(&data->value, 0, 0x03);
2313                 }
2314
2315                 return WERR_OK;
2316         }
2317
2318         if (!strcasecmp_m(value, "MinorVersion")) {
2319                 *type = REG_DWORD;
2320                 SIVAL(&data->value, 0, 0x00);
2321                 return WERR_OK;
2322         }
2323
2324         /* REG_BINARY
2325          *  uint32_t size        = 0x114
2326          *  uint32_t major       = 5
2327          *  uint32_t minor       = [0|1]
2328          *  uint32_t build       = [2195|2600]
2329          *  extra unicode string = e.g. "Service Pack 3"
2330          */
2331         if (!strcasecmp_m(value, "OSVersion")) {
2332                 DATA_BLOB blob;
2333                 enum ndr_err_code ndr_err;
2334                 struct spoolss_OSVersion os;
2335
2336                 os.major                = lp_parm_int(GLOBAL_SECTION_SNUM,
2337                                                       "spoolss", "os_major", 5);
2338                                                       /* Windows 2000 == 5.0 */
2339                 os.minor                = lp_parm_int(GLOBAL_SECTION_SNUM,
2340                                                       "spoolss", "os_minor", 0);
2341                 os.build                = lp_parm_int(GLOBAL_SECTION_SNUM,
2342                                                       "spoolss", "os_build", 2195);
2343                 os.extra_string         = "";   /* leave extra string empty */
2344
2345                 ndr_err = ndr_push_struct_blob(&blob, mem_ctx, &os,
2346                         (ndr_push_flags_fn_t)ndr_push_spoolss_OSVersion);
2347                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2348                         return WERR_GENERAL_FAILURE;
2349                 }
2350
2351                 if (DEBUGLEVEL >= 10) {
2352                         NDR_PRINT_DEBUG(spoolss_OSVersion, &os);
2353                 }
2354
2355                 *type = REG_BINARY;
2356                 data->binary = blob;
2357
2358                 return WERR_OK;
2359         }
2360
2361
2362         if (!strcasecmp_m(value, "DefaultSpoolDirectory")) {
2363                 *type = REG_SZ;
2364
2365                 data->string = talloc_strdup(mem_ctx, "C:\\PRINTERS");
2366                 W_ERROR_HAVE_NO_MEMORY(data->string);
2367
2368                 return WERR_OK;
2369         }
2370
2371         if (!strcasecmp_m(value, "Architecture")) {
2372                 *type = REG_SZ;
2373                 data->string = talloc_strdup(mem_ctx,
2374                         lp_parm_const_string(GLOBAL_SECTION_SNUM, "spoolss", "architecture", SPOOLSS_ARCHITECTURE_NT_X86));
2375                 W_ERROR_HAVE_NO_MEMORY(data->string);
2376
2377                 return WERR_OK;
2378         }
2379
2380         if (!strcasecmp_m(value, "DsPresent")) {
2381                 *type = REG_DWORD;
2382
2383                 /* only show the publish check box if we are a
2384                    member of a AD domain */
2385
2386                 if (lp_security() == SEC_ADS) {
2387                         SIVAL(&data->value, 0, 0x01);
2388                 } else {
2389                         SIVAL(&data->value, 0, 0x00);
2390                 }
2391                 return WERR_OK;
2392         }
2393
2394         if (!strcasecmp_m(value, "DNSMachineName")) {
2395                 const char *hostname = get_mydnsfullname();
2396
2397                 if (!hostname) {
2398                         return WERR_BADFILE;
2399                 }
2400
2401                 *type = REG_SZ;
2402                 data->string = talloc_strdup(mem_ctx, hostname);
2403                 W_ERROR_HAVE_NO_MEMORY(data->string);
2404
2405                 return WERR_OK;
2406         }
2407
2408         *type = REG_NONE;
2409
2410         return WERR_INVALID_PARAM;
2411 }
2412
2413 /****************************************************************
2414  _spoolss_GetPrinterData
2415 ****************************************************************/
2416
2417 WERROR _spoolss_GetPrinterData(struct pipes_struct *p,
2418                                struct spoolss_GetPrinterData *r)
2419 {
2420         struct spoolss_GetPrinterDataEx r2;
2421
2422         r2.in.handle            = r->in.handle;
2423         r2.in.key_name          = "PrinterDriverData";
2424         r2.in.value_name        = r->in.value_name;
2425         r2.in.offered           = r->in.offered;
2426         r2.out.type             = r->out.type;
2427         r2.out.data             = r->out.data;
2428         r2.out.needed           = r->out.needed;
2429
2430         return _spoolss_GetPrinterDataEx(p, &r2);
2431 }
2432
2433 /*********************************************************
2434  Connect to the client machine.
2435 **********************************************************/
2436
2437 static bool spoolss_connect_to_client(struct rpc_pipe_client **pp_pipe, struct cli_state **pp_cli,
2438                                       struct sockaddr_storage *client_ss, const char *remote_machine)
2439 {
2440         NTSTATUS ret;
2441         struct sockaddr_storage rm_addr;
2442         char addr[INET6_ADDRSTRLEN];
2443
2444         if ( is_zero_addr(client_ss) ) {
2445                 DEBUG(2,("spoolss_connect_to_client: resolving %s\n",
2446                         remote_machine));
2447                 if ( !resolve_name( remote_machine, &rm_addr, 0x20, false) ) {
2448                         DEBUG(2,("spoolss_connect_to_client: Can't resolve address for %s\n", remote_machine));
2449                         return false;
2450                 }
2451                 print_sockaddr(addr, sizeof(addr), &rm_addr);
2452         } else {
2453                 rm_addr = *client_ss;
2454                 print_sockaddr(addr, sizeof(addr), &rm_addr);
2455                 DEBUG(5,("spoolss_connect_to_client: Using address %s (no name resolution necessary)\n",
2456                         addr));
2457         }
2458
2459         if (ismyaddr((struct sockaddr *)(void *)&rm_addr)) {
2460                 DEBUG(0,("spoolss_connect_to_client: Machine %s is one of our addresses. Cannot add to ourselves.\n",
2461                         addr));
2462                 return false;
2463         }
2464
2465         /* setup the connection */
2466         ret = cli_full_connection( pp_cli, lp_netbios_name(), remote_machine,
2467                 &rm_addr, 0, "IPC$", "IPC",
2468                 "", /* username */
2469                 "", /* domain */
2470                 "", /* password */
2471                 0, lp_client_signing());
2472
2473         if ( !NT_STATUS_IS_OK( ret ) ) {
2474                 DEBUG(2,("spoolss_connect_to_client: connection to [%s] failed!\n",
2475                         remote_machine ));
2476                 return false;
2477         }
2478
2479         if ( smbXcli_conn_protocol((*pp_cli)->conn) != PROTOCOL_NT1 ) {
2480                 DEBUG(0,("spoolss_connect_to_client: machine %s didn't negotiate NT protocol.\n", remote_machine));
2481                 cli_shutdown(*pp_cli);
2482                 return false;
2483         }
2484
2485         /*
2486          * Ok - we have an anonymous connection to the IPC$ share.
2487          * Now start the NT Domain stuff :-).
2488          */
2489
2490         ret = cli_rpc_pipe_open_noauth(*pp_cli, &ndr_table_spoolss, pp_pipe);
2491         if (!NT_STATUS_IS_OK(ret)) {
2492                 DEBUG(2,("spoolss_connect_to_client: unable to open the spoolss pipe on machine %s. Error was : %s.\n",
2493                         remote_machine, nt_errstr(ret)));
2494                 cli_shutdown(*pp_cli);
2495                 return false;
2496         }
2497
2498         return true;
2499 }
2500
2501 /***************************************************************************
2502  Connect to the client.
2503 ****************************************************************************/
2504
2505 static bool srv_spoolss_replyopenprinter(int snum, const char *printer,
2506                                         uint32_t localprinter,
2507                                         enum winreg_Type type,
2508                                         struct policy_handle *handle,
2509                                         struct notify_back_channel **_chan,
2510                                         struct sockaddr_storage *client_ss,
2511                                         struct messaging_context *msg_ctx)
2512 {
2513         WERROR result;
2514         NTSTATUS status;
2515         struct notify_back_channel *chan;
2516
2517         for (chan = back_channels; chan; chan = chan->next) {
2518                 if (memcmp(&chan->client_address, client_ss,
2519                            sizeof(struct sockaddr_storage)) == 0) {
2520                         break;
2521                 }
2522         }
2523
2524         /*
2525          * If it's the first connection, contact the client
2526          * and connect to the IPC$ share anonymously
2527          */
2528         if (!chan) {
2529                 fstring unix_printer;
2530
2531                 /* the +2 is to strip the leading 2 backslashs */
2532                 fstrcpy(unix_printer, printer + 2);
2533
2534                 chan = talloc_zero(NULL, struct notify_back_channel);
2535                 if (!chan) {
2536                         return false;
2537                 }
2538                 chan->client_address = *client_ss;
2539
2540                 if (!spoolss_connect_to_client(&chan->cli_pipe, &chan->cli, client_ss, unix_printer)) {
2541                         TALLOC_FREE(chan);
2542                         return false;
2543                 }
2544
2545                 DLIST_ADD(back_channels, chan);
2546
2547                 messaging_register(msg_ctx, NULL, MSG_PRINTER_NOTIFY2,
2548                                    receive_notify2_message_list);
2549         }
2550
2551         if (chan->cli_pipe == NULL ||
2552             chan->cli_pipe->binding_handle == NULL) {
2553                 DEBUG(0, ("srv_spoolss_replyopenprinter: error - "
2554                         "NULL %s for printer %s\n",
2555                         chan->cli_pipe == NULL ?
2556                         "chan->cli_pipe" : "chan->cli_pipe->binding_handle",
2557                         printer));
2558                 return false;
2559         }
2560
2561         /*
2562          * Tell the specific printing tdb we want messages for this printer
2563          * by registering our PID.
2564          */
2565
2566         if (!print_notify_register_pid(snum)) {
2567                 DEBUG(0, ("Failed to register our pid for printer %s\n",
2568                           printer));
2569         }
2570
2571         status = dcerpc_spoolss_ReplyOpenPrinter(chan->cli_pipe->binding_handle,
2572                                                  talloc_tos(),
2573                                                  printer,
2574                                                  localprinter,
2575                                                  type,
2576                                                  0,
2577                                                  NULL,
2578                                                  handle,
2579                                                  &result);
2580         if (!NT_STATUS_IS_OK(status)) {
2581                 DEBUG(5, ("dcerpc_spoolss_ReplyOpenPrinter returned [%s]\n", nt_errstr(status)));
2582                 result = ntstatus_to_werror(status);
2583         } else if (!W_ERROR_IS_OK(result)) {
2584                 DEBUG(5, ("ReplyOpenPrinter returned [%s]\n", win_errstr(result)));
2585         }
2586
2587         chan->active_connections++;
2588         *_chan = chan;
2589
2590         return (W_ERROR_IS_OK(result));
2591 }
2592
2593 /****************************************************************
2594  ****************************************************************/
2595
2596 static struct spoolss_NotifyOption *dup_spoolss_NotifyOption(TALLOC_CTX *mem_ctx,
2597                                                              const struct spoolss_NotifyOption *r)
2598 {
2599         struct spoolss_NotifyOption *option;
2600         uint32_t i,k;
2601
2602         if (!r) {
2603                 return NULL;
2604         }
2605
2606         option = talloc_zero(mem_ctx, struct spoolss_NotifyOption);
2607         if (!option) {
2608                 return NULL;
2609         }
2610
2611         *option = *r;
2612
2613         if (!option->count) {
2614                 return option;
2615         }
2616
2617         option->types = talloc_zero_array(option,
2618                 struct spoolss_NotifyOptionType, option->count);
2619         if (!option->types) {
2620                 talloc_free(option);
2621                 return NULL;
2622         }
2623
2624         for (i=0; i < option->count; i++) {
2625                 option->types[i] = r->types[i];
2626
2627                 if (option->types[i].count) {
2628                         option->types[i].fields = talloc_zero_array(option,
2629                                 union spoolss_Field, option->types[i].count);
2630                         if (!option->types[i].fields) {
2631                                 talloc_free(option);
2632                                 return NULL;
2633                         }
2634                         for (k=0; k<option->types[i].count; k++) {
2635                                 option->types[i].fields[k] =
2636                                         r->types[i].fields[k];
2637                         }
2638                 }
2639         }
2640
2641         return option;
2642 }
2643
2644 /****************************************************************
2645  * _spoolss_RemoteFindFirstPrinterChangeNotifyEx
2646  *
2647  * before replying OK: status=0 a rpc call is made to the workstation
2648  * asking ReplyOpenPrinter
2649  *
2650  * in fact ReplyOpenPrinter is the changenotify equivalent on the spoolss pipe
2651  * called from api_spoolss_rffpcnex
2652 ****************************************************************/
2653
2654 WERROR _spoolss_RemoteFindFirstPrinterChangeNotifyEx(struct pipes_struct *p,
2655                                                      struct spoolss_RemoteFindFirstPrinterChangeNotifyEx *r)
2656 {
2657         int snum = -1;
2658         struct spoolss_NotifyOption *option = r->in.notify_options;
2659         struct sockaddr_storage client_ss;
2660         ssize_t client_len;
2661
2662         /* store the notify value in the printer struct */
2663
2664         struct printer_handle *Printer = find_printer_index_by_hnd(p, r->in.handle);
2665
2666         if (!Printer) {
2667                 DEBUG(2,("_spoolss_RemoteFindFirstPrinterChangeNotifyEx: "
2668                         "Invalid handle (%s:%u:%u).\n",
2669                         OUR_HANDLE(r->in.handle)));
2670                 return WERR_BADFID;
2671         }
2672
2673         Printer->notify.flags           = r->in.flags;
2674         Printer->notify.options         = r->in.options;
2675         Printer->notify.printerlocal    = r->in.printer_local;
2676         Printer->notify.msg_ctx         = p->msg_ctx;
2677
2678         TALLOC_FREE(Printer->notify.option);
2679         Printer->notify.option = dup_spoolss_NotifyOption(Printer, option);
2680
2681         fstrcpy(Printer->notify.localmachine, r->in.local_machine);
2682
2683         /* Connect to the client machine and send a ReplyOpenPrinter */
2684
2685         if ( Printer->printer_type == SPLHND_SERVER)
2686                 snum = -1;
2687         else if ( (Printer->printer_type == SPLHND_PRINTER) &&
2688                         !get_printer_snum(p, r->in.handle, &snum, NULL) )
2689                 return WERR_BADFID;
2690
2691         DEBUG(10,("_spoolss_RemoteFindFirstPrinterChangeNotifyEx: "
2692                   "remote_address is %s\n",
2693                   tsocket_address_string(p->remote_address, p->mem_ctx)));
2694
2695         if (!lp_print_notify_backchannel(snum)) {
2696                 DEBUG(10, ("_spoolss_RemoteFindFirstPrinterChangeNotifyEx: "
2697                         "backchannel disabled\n"));
2698                 return WERR_SERVER_UNAVAILABLE;
2699         }
2700
2701         client_len = tsocket_address_bsd_sockaddr(p->remote_address,
2702                                                   (struct sockaddr *) &client_ss,
2703                                                   sizeof(struct sockaddr_storage));
2704         if (client_len < 0) {
2705                 return WERR_NOMEM;
2706         }
2707
2708         if(!srv_spoolss_replyopenprinter(snum, Printer->notify.localmachine,
2709                                         Printer->notify.printerlocal, REG_SZ,
2710                                         &Printer->notify.cli_hnd,
2711                                         &Printer->notify.cli_chan,
2712                                         &client_ss, p->msg_ctx)) {
2713                 return WERR_SERVER_UNAVAILABLE;
2714         }
2715
2716         return WERR_OK;
2717 }
2718
2719 /*******************************************************************
2720  * fill a notify_info_data with the servername
2721  ********************************************************************/
2722
2723 static void spoolss_notify_server_name(struct messaging_context *msg_ctx,
2724                                        int snum,
2725                                        struct spoolss_Notify *data,
2726                                        print_queue_struct *queue,
2727                                        struct spoolss_PrinterInfo2 *pinfo2,
2728                                        TALLOC_CTX *mem_ctx)
2729 {
2730         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, pinfo2->servername);
2731 }
2732
2733 /*******************************************************************
2734  * fill a notify_info_data with the printername (not including the servername).
2735  ********************************************************************/
2736
2737 static void spoolss_notify_printer_name(struct messaging_context *msg_ctx,
2738                                         int snum,
2739                                         struct spoolss_Notify *data,
2740                                         print_queue_struct *queue,
2741                                         struct spoolss_PrinterInfo2 *pinfo2,
2742                                         TALLOC_CTX *mem_ctx)
2743 {
2744         /* the notify name should not contain the \\server\ part */
2745         const char *p = strrchr(pinfo2->printername, '\\');
2746
2747         if (!p) {
2748                 p = pinfo2->printername;
2749         } else {
2750                 p++;
2751         }
2752
2753         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, p);
2754 }
2755
2756 /*******************************************************************
2757  * fill a notify_info_data with the servicename
2758  ********************************************************************/
2759
2760 static void spoolss_notify_share_name(struct messaging_context *msg_ctx,
2761                                       int snum,
2762                                       struct spoolss_Notify *data,
2763                                       print_queue_struct *queue,
2764                                       struct spoolss_PrinterInfo2 *pinfo2,
2765                                       TALLOC_CTX *mem_ctx)
2766 {
2767         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, lp_servicename(talloc_tos(), snum));
2768 }
2769
2770 /*******************************************************************
2771  * fill a notify_info_data with the port name
2772  ********************************************************************/
2773
2774 static void spoolss_notify_port_name(struct messaging_context *msg_ctx,
2775                                      int snum,
2776                                      struct spoolss_Notify *data,
2777                                      print_queue_struct *queue,
2778                                      struct spoolss_PrinterInfo2 *pinfo2,
2779                                      TALLOC_CTX *mem_ctx)
2780 {
2781         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, pinfo2->portname);
2782 }
2783
2784 /*******************************************************************
2785  * fill a notify_info_data with the printername
2786  * but it doesn't exist, have to see what to do
2787  ********************************************************************/
2788
2789 static void spoolss_notify_driver_name(struct messaging_context *msg_ctx,
2790                                        int snum,
2791                                        struct spoolss_Notify *data,
2792                                        print_queue_struct *queue,
2793                                        struct spoolss_PrinterInfo2 *pinfo2,
2794                                        TALLOC_CTX *mem_ctx)
2795 {
2796         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, pinfo2->drivername);
2797 }
2798
2799 /*******************************************************************
2800  * fill a notify_info_data with the comment
2801  ********************************************************************/
2802
2803 static void spoolss_notify_comment(struct messaging_context *msg_ctx,
2804                                    int snum,
2805                                    struct spoolss_Notify *data,
2806                                    print_queue_struct *queue,
2807                                    struct spoolss_PrinterInfo2 *pinfo2,
2808                                    TALLOC_CTX *mem_ctx)
2809 {
2810         const char *p;
2811
2812         if (*pinfo2->comment == '\0') {
2813                 p = lp_comment(talloc_tos(), snum);
2814         } else {
2815                 p = pinfo2->comment;
2816         }
2817
2818         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, p);
2819 }
2820
2821 /*******************************************************************
2822  * fill a notify_info_data with the comment
2823  * location = "Room 1, floor 2, building 3"
2824  ********************************************************************/
2825
2826 static void spoolss_notify_location(struct messaging_context *msg_ctx,
2827                                     int snum,
2828                                     struct spoolss_Notify *data,
2829                                     print_queue_struct *queue,
2830                                     struct spoolss_PrinterInfo2 *pinfo2,
2831                                     TALLOC_CTX *mem_ctx)
2832 {
2833         const char *loc = pinfo2->location;
2834         NTSTATUS status;
2835
2836         status = printer_list_get_printer(mem_ctx,
2837                                           pinfo2->sharename,
2838                                           NULL,
2839                                           &loc,
2840                                           NULL);
2841         if (NT_STATUS_IS_OK(status)) {
2842                 if (loc == NULL) {
2843                         loc = pinfo2->location;
2844                 }
2845         }
2846
2847         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, loc);
2848 }
2849
2850 /*******************************************************************
2851  * fill a notify_info_data with the device mode
2852  * jfm:xxxx don't to it for know but that's a real problem !!!
2853  ********************************************************************/
2854
2855 static void spoolss_notify_devmode(struct messaging_context *msg_ctx,
2856                                    int snum,
2857                                    struct spoolss_Notify *data,
2858                                    print_queue_struct *queue,
2859                                    struct spoolss_PrinterInfo2 *pinfo2,
2860                                    TALLOC_CTX *mem_ctx)
2861 {
2862         /* for a dummy implementation we have to zero the fields */
2863         SETUP_SPOOLSS_NOTIFY_DATA_DEVMODE(data, NULL);
2864 }
2865
2866 /*******************************************************************
2867  * fill a notify_info_data with the separator file name
2868  ********************************************************************/
2869
2870 static void spoolss_notify_sepfile(struct messaging_context *msg_ctx,
2871                                    int snum,
2872                                    struct spoolss_Notify *data,
2873                                    print_queue_struct *queue,
2874                                    struct spoolss_PrinterInfo2 *pinfo2,
2875                                    TALLOC_CTX *mem_ctx)
2876 {
2877         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, pinfo2->sepfile);
2878 }
2879
2880 /*******************************************************************
2881  * fill a notify_info_data with the print processor
2882  * jfm:xxxx return always winprint to indicate we don't do anything to it
2883  ********************************************************************/
2884
2885 static void spoolss_notify_print_processor(struct messaging_context *msg_ctx,
2886                                            int snum,
2887                                            struct spoolss_Notify *data,
2888                                            print_queue_struct *queue,
2889                                            struct spoolss_PrinterInfo2 *pinfo2,
2890                                            TALLOC_CTX *mem_ctx)
2891 {
2892         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, pinfo2->printprocessor);
2893 }
2894
2895 /*******************************************************************
2896  * fill a notify_info_data with the print processor options
2897  * jfm:xxxx send an empty string
2898  ********************************************************************/
2899
2900 static void spoolss_notify_parameters(struct messaging_context *msg_ctx,
2901                                       int snum,
2902                                       struct spoolss_Notify *data,
2903                                       print_queue_struct *queue,
2904                                       struct spoolss_PrinterInfo2 *pinfo2,
2905                                       TALLOC_CTX *mem_ctx)
2906 {
2907         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, pinfo2->parameters);
2908 }
2909
2910 /*******************************************************************
2911  * fill a notify_info_data with the data type
2912  * jfm:xxxx always send RAW as data type
2913  ********************************************************************/
2914
2915 static void spoolss_notify_datatype(struct messaging_context *msg_ctx,
2916                                     int snum,
2917                                     struct spoolss_Notify *data,
2918                                     print_queue_struct *queue,
2919                                     struct spoolss_PrinterInfo2 *pinfo2,
2920                                     TALLOC_CTX *mem_ctx)
2921 {
2922         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, pinfo2->datatype);
2923 }
2924
2925 /*******************************************************************
2926  * fill a notify_info_data with the security descriptor
2927  * jfm:xxxx send an null pointer to say no security desc
2928  * have to implement security before !
2929  ********************************************************************/
2930
2931 static void spoolss_notify_security_desc(struct messaging_context *msg_ctx,
2932                                          int snum,
2933                                          struct spoolss_Notify *data,
2934                                          print_queue_struct *queue,
2935                                          struct spoolss_PrinterInfo2 *pinfo2,
2936                                          TALLOC_CTX *mem_ctx)
2937 {
2938         data->data.sd.sd = dup_sec_desc(mem_ctx, pinfo2->secdesc);
2939         data->data.sd.sd_size = ndr_size_security_descriptor(data->data.sd.sd,
2940                                                              0);
2941 }
2942
2943 /*******************************************************************
2944  * fill a notify_info_data with the attributes
2945  * jfm:xxxx a samba printer is always shared
2946  ********************************************************************/
2947
2948 static void spoolss_notify_attributes(struct messaging_context *msg_ctx,
2949                                       int snum,
2950                                       struct spoolss_Notify *data,
2951                                       print_queue_struct *queue,
2952                                       struct spoolss_PrinterInfo2 *pinfo2,
2953                                       TALLOC_CTX *mem_ctx)
2954 {
2955         SETUP_SPOOLSS_NOTIFY_DATA_INTEGER(data, pinfo2->attributes);
2956 }
2957
2958 /*******************************************************************
2959  * fill a notify_info_data with the priority
2960  ********************************************************************/
2961
2962 static void spoolss_notify_priority(struct messaging_context *msg_ctx,
2963                                     int snum,
2964                                     struct spoolss_Notify *data,
2965                                     print_queue_struct *queue,
2966                                     struct spoolss_PrinterInfo2 *pinfo2,
2967                                     TALLOC_CTX *mem_ctx)
2968 {
2969         SETUP_SPOOLSS_NOTIFY_DATA_INTEGER(data, pinfo2->priority);
2970 }
2971
2972 /*******************************************************************
2973  * fill a notify_info_data with the default priority
2974  ********************************************************************/
2975
2976 static void spoolss_notify_default_priority(struct messaging_context *msg_ctx,
2977                                             int snum,
2978                                             struct spoolss_Notify *data,
2979                                             print_queue_struct *queue,
2980                                             struct spoolss_PrinterInfo2 *pinfo2,
2981                                             TALLOC_CTX *mem_ctx)
2982 {
2983         SETUP_SPOOLSS_NOTIFY_DATA_INTEGER(data, pinfo2->defaultpriority);
2984 }
2985
2986 /*******************************************************************
2987  * fill a notify_info_data with the start time
2988  ********************************************************************/
2989
2990 static void spoolss_notify_start_time(struct messaging_context *msg_ctx,
2991                                       int snum,
2992                                       struct spoolss_Notify *data,
2993                                       print_queue_struct *queue,
2994                                       struct spoolss_PrinterInfo2 *pinfo2,
2995                                       TALLOC_CTX *mem_ctx)
2996 {
2997         SETUP_SPOOLSS_NOTIFY_DATA_INTEGER(data, pinfo2->starttime);
2998 }
2999
3000 /*******************************************************************
3001  * fill a notify_info_data with the until time
3002  ********************************************************************/
3003
3004 static void spoolss_notify_until_time(struct messaging_context *msg_ctx,
3005                                       int snum,
3006                                       struct spoolss_Notify *data,
3007                                       print_queue_struct *queue,
3008                                       struct spoolss_PrinterInfo2 *pinfo2,
3009                                       TALLOC_CTX *mem_ctx)
3010 {
3011         SETUP_SPOOLSS_NOTIFY_DATA_INTEGER(data, pinfo2->untiltime);
3012 }
3013
3014 /*******************************************************************
3015  * fill a notify_info_data with the status
3016  ********************************************************************/
3017
3018 static void spoolss_notify_status(struct messaging_context *msg_ctx,
3019                                   int snum,
3020                                   struct spoolss_Notify *data,
3021                                   print_queue_struct *queue,
3022                                   struct spoolss_PrinterInfo2 *pinfo2,
3023                                   TALLOC_CTX *mem_ctx)
3024 {
3025         print_status_struct status;
3026
3027         print_queue_length(msg_ctx, snum, &status);
3028         SETUP_SPOOLSS_NOTIFY_DATA_INTEGER(data, status.status);
3029 }
3030
3031 /*******************************************************************
3032  * fill a notify_info_data with the number of jobs queued
3033  ********************************************************************/
3034
3035 static void spoolss_notify_cjobs(struct messaging_context *msg_ctx,
3036                                  int snum,
3037                                  struct spoolss_Notify *data,
3038                                  print_queue_struct *queue,
3039                                  struct spoolss_PrinterInfo2 *pinfo2,
3040                                  TALLOC_CTX *mem_ctx)
3041 {
3042         SETUP_SPOOLSS_NOTIFY_DATA_INTEGER(
3043                 data, print_queue_length(msg_ctx, snum, NULL));
3044 }
3045
3046 /*******************************************************************
3047  * fill a notify_info_data with the average ppm
3048  ********************************************************************/
3049
3050 static void spoolss_notify_average_ppm(struct messaging_context *msg_ctx,
3051                                        int snum,
3052                                        struct spoolss_Notify *data,
3053                                        print_queue_struct *queue,
3054                                        struct spoolss_PrinterInfo2 *pinfo2,
3055                                        TALLOC_CTX *mem_ctx)
3056 {
3057         /* always respond 8 pages per minutes */
3058         /* a little hard ! */
3059         SETUP_SPOOLSS_NOTIFY_DATA_INTEGER(data, pinfo2->averageppm);
3060 }
3061
3062 /*******************************************************************
3063  * fill a notify_info_data with username
3064  ********************************************************************/
3065
3066 static void spoolss_notify_username(struct messaging_context *msg_ctx,
3067                                     int snum,
3068                                     struct spoolss_Notify *data,
3069                                     print_queue_struct *queue,
3070                                     struct spoolss_PrinterInfo2 *pinfo2,
3071                                     TALLOC_CTX *mem_ctx)
3072 {
3073         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, queue->fs_user);
3074 }
3075
3076 /*******************************************************************
3077  * fill a notify_info_data with job status
3078  ********************************************************************/
3079
3080 static void spoolss_notify_job_status(struct messaging_context *msg_ctx,
3081                                       int snum,
3082                                       struct spoolss_Notify *data,
3083                                       print_queue_struct *queue,
3084                                       struct spoolss_PrinterInfo2 *pinfo2,
3085                                       TALLOC_CTX *mem_ctx)
3086 {
3087         SETUP_SPOOLSS_NOTIFY_DATA_INTEGER(data, nt_printj_status(queue->status));
3088 }
3089
3090 /*******************************************************************
3091  * fill a notify_info_data with job name
3092  ********************************************************************/
3093
3094 static void spoolss_notify_job_name(struct messaging_context *msg_ctx,
3095                                     int snum,
3096                                     struct spoolss_Notify *data,
3097                                     print_queue_struct *queue,
3098                                     struct spoolss_PrinterInfo2 *pinfo2,
3099                                     TALLOC_CTX *mem_ctx)
3100 {
3101         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, queue->fs_file);
3102 }
3103
3104 /*******************************************************************
3105  * fill a notify_info_data with job status
3106  ********************************************************************/
3107
3108 static void spoolss_notify_job_status_string(struct messaging_context *msg_ctx,
3109                                              int snum,
3110                                              struct spoolss_Notify *data,
3111                                              print_queue_struct *queue,
3112                                              struct spoolss_PrinterInfo2 *pinfo2,
3113                                              TALLOC_CTX *mem_ctx)
3114 {
3115         /*
3116          * Now we're returning job status codes we just return a "" here. JRA.
3117          */
3118
3119         const char *p = "";
3120
3121 #if 0 /* NO LONGER NEEDED - JRA. 02/22/2001 */
3122         p = "unknown";
3123
3124         switch (queue->status) {
3125         case LPQ_QUEUED:
3126                 p = "Queued";
3127                 break;
3128         case LPQ_PAUSED:
3129                 p = "";    /* NT provides the paused string */
3130                 break;
3131         case LPQ_SPOOLING:
3132                 p = "Spooling";
3133                 break;
3134         case LPQ_PRINTING:
3135                 p = "Printing";
3136                 break;
3137         }
3138 #endif /* NO LONGER NEEDED. */
3139
3140         SETUP_SPOOLSS_NOTIFY_DATA_STRING(data, p);
3141 }
3142
3143 /*******************************************************************
3144  * fill a notify_info_data with job time
3145  ********************************************************************/
3146
3147 static void spoolss_notify_job_time(struct messaging_context *msg_ctx,
3148                                     int snum,
3149                                     struct spoolss_Notify *data,
3150                                     print_queue_struct *queue,
3151                             &n