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