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