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