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