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