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