Eliminate global variable in_client and a plethora of extern declarations.
[vlendec/samba-autobuild/.git] / source3 / client / smbspool.c
1 /* 
2    Unix SMB/CIFS implementation.
3    SMB backend for the Common UNIX Printing System ("CUPS")
4    Copyright 1999 by Easy Software Products
5    Copyright Andrew Tridgell 1994-1998
6    Copyright Andrew Bartlett 2002
7    Copyright Rodrigo Fernandez-Vizarra 2005 
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24
25 #define TICKET_CC_DIR            "/tmp"
26 #define CC_PREFIX                "krb5cc_" /* prefix of the ticket cache */
27 #define CC_MAX_FILE_LEN          24   
28 #define CC_MAX_FILE_PATH_LEN     (sizeof(TICKET_CC_DIR)-1)+ CC_MAX_FILE_LEN+2   
29 #define OVERWRITE                1   
30 #define KRB5CCNAME               "KRB5CCNAME"
31 #define MAX_RETRY_CONNECT        3
32
33
34 /*
35  * Globals...
36  */
37
38
39
40 /*
41  * Local functions...
42  */
43
44 static void             list_devices(void);
45 static struct cli_state *smb_complete_connection(const char *, const char *,int , const char *, const char *, const char *, const char *, int);
46 static struct cli_state *smb_connect(const char *, const char *, int, const char *, const char *, const char *, const char *);
47 static int              smb_print(struct cli_state *, char *, FILE *);
48 static char *           uri_unescape_alloc(const char *);
49 #if 0
50 static bool smb_encrypt;
51 #endif
52
53 /*
54  * 'main()' - Main entry for SMB backend.
55  */
56
57  int                            /* O - Exit status */
58  main(int  argc,                        /* I - Number of command-line arguments */
59      char *argv[])              /* I - Command-line arguments */
60 {
61   int           i;              /* Looping var */
62   int           copies;         /* Number of copies */
63   int           port;           /* Port number */
64   char          uri[1024],      /* URI */
65                 *sep,           /* Pointer to separator */
66                 *tmp, *tmp2,    /* Temp pointers to do escaping */
67                 *password;      /* Password */
68   char          *username,      /* Username */
69                 *server,        /* Server name */
70                 *printer;       /* Printer name */
71   const char    *workgroup;     /* Workgroup */
72   FILE          *fp;            /* File to print */
73   int           status=1;               /* Status of LPD job */
74   struct cli_state *cli;        /* SMB interface */
75   char null_str[1];
76   int tries = 0;
77   const char *dev_uri;
78   TALLOC_CTX *frame = talloc_stackframe();
79
80   null_str[0] = '\0';
81
82   /* we expect the URI in argv[0]. Detect the case where it is in argv[1] and cope */
83   if (argc > 2 && strncmp(argv[0],"smb://", 6) && !strncmp(argv[1],"smb://", 6)) {
84           argv++;
85           argc--;
86   }
87
88   if (argc == 1)
89   {
90    /*
91     * NEW!  In CUPS 1.1 the backends are run with no arguments to list the
92     *       available devices.  These can be devices served by this backend
93     *       or any other backends (i.e. you can have an SNMP backend that
94     *       is only used to enumerate the available network printers... :)
95     */
96
97     list_devices();
98     status = 0;
99     goto done;
100   }
101
102   if (argc < 6 || argc > 7)
103   {
104     fprintf(stderr, "Usage: %s [DEVICE_URI] job-id user title copies options [file]\n",
105             argv[0]);
106     fputs("       The DEVICE_URI environment variable can also contain the\n", stderr);
107     fputs("       destination printer:\n", stderr);
108     fputs("\n", stderr);
109     fputs("           smb://[username:password@][workgroup/]server[:port]/printer\n", stderr);
110     goto done;
111   }
112
113  /*
114   * If we have 7 arguments, print the file named on the command-line.
115   * Otherwise, print data from stdin...
116   */
117
118
119   if (argc == 6)
120   {
121    /*
122     * Print from Copy stdin to a temporary file...
123     */
124
125     fp     = stdin;
126     copies = 1;
127   }
128   else if ((fp = fopen(argv[6], "rb")) == NULL)
129   {
130     perror("ERROR: Unable to open print file");
131     goto done;
132   }
133   else
134     copies = atoi(argv[4]);
135
136  /*
137   * Find the URI...
138   */
139
140   dev_uri = getenv("DEVICE_URI");
141   if (dev_uri)
142     strncpy(uri, dev_uri, sizeof(uri) - 1);
143   else if (strncmp(argv[0], "smb://", 6) == 0)
144     strncpy(uri, argv[0], sizeof(uri) - 1);
145   else
146   {
147     fputs("ERROR: No device URI found in DEVICE_URI environment variable or argv[0] !\n", stderr);
148     goto done;
149   }
150
151   uri[sizeof(uri) - 1] = '\0';
152
153  /*
154   * Extract the destination from the URI...
155   */
156
157   if ((sep = strrchr_m(uri, '@')) != NULL)
158   {
159     tmp = uri + 6;
160     *sep++ = '\0';
161
162     /* username is in tmp */
163
164     server = sep;
165
166    /*
167     * Extract password as needed...
168     */
169
170     if ((tmp2 = strchr_m(tmp, ':')) != NULL) {
171       *tmp2++ = '\0';
172       password = uri_unescape_alloc(tmp2);
173     } else {
174       password = null_str;
175     }
176     username = uri_unescape_alloc(tmp);
177   }
178   else
179   {
180     username = null_str;
181     password = null_str;
182     server   = uri + 6;
183   }
184
185   tmp = server;
186
187   if ((sep = strchr_m(tmp, '/')) == NULL)
188   {
189     fputs("ERROR: Bad URI - need printer name!\n", stderr);
190     goto done;
191   }
192
193   *sep++ = '\0';
194   tmp2 = sep;
195
196   if ((sep = strchr_m(tmp2, '/')) != NULL)
197   {
198    /*
199     * Convert to smb://[username:password@]workgroup/server/printer...
200     */
201
202     *sep++ = '\0';
203
204     workgroup = uri_unescape_alloc(tmp);
205     server    = uri_unescape_alloc(tmp2);
206     printer   = uri_unescape_alloc(sep);
207   }
208   else {
209     workgroup = NULL;
210     server = uri_unescape_alloc(tmp);
211     printer = uri_unescape_alloc(tmp2);
212   }
213   
214   if ((sep = strrchr_m(server, ':')) != NULL)
215   {
216     *sep++ = '\0';
217
218     port=atoi(sep);
219   }
220   else 
221         port=0;
222         
223  
224  /*
225   * Setup the SAMBA server state...
226   */
227
228   setup_logging("smbspool", True);
229
230   lp_set_in_client(True);       /* Make sure that we tell lp_load we are */
231
232   load_case_tables();
233
234   if (!lp_load(get_dyn_CONFIGFILE(), True, False, False, True))
235   {
236     fprintf(stderr, "ERROR: Can't load %s - run testparm to debug it\n", get_dyn_CONFIGFILE());
237     goto done;
238   }
239
240   if (workgroup == NULL)
241     workgroup = lp_workgroup();
242
243   load_interfaces();
244
245   do
246   {
247     if ((cli = smb_connect(workgroup, server, port, printer, username, password, argv[2])) == NULL)
248     {
249       if (getenv("CLASS") == NULL)
250       {
251         fprintf(stderr, "ERROR: Unable to connect to CIFS host, will retry in 60 seconds...\n");
252         sleep (60); /* should just waiting and retrying fix authentication  ??? */
253         tries++;
254       }
255       else
256       {
257         fprintf(stderr, "ERROR: Unable to connect to CIFS host, trying next printer...\n");
258         goto done;
259       }
260     }
261   }
262   while ((cli == NULL) && (tries < MAX_RETRY_CONNECT));
263
264   if (cli == NULL) {
265         fprintf(stderr, "ERROR: Unable to connect to CIFS host after (tried %d times)\n", tries);
266         goto done;
267   }
268
269  /*
270   * Now that we are connected to the server, ignore SIGTERM so that we
271   * can finish out any page data the driver sends (e.g. to eject the
272   * current page...  Only ignore SIGTERM if we are printing data from
273   * stdin (otherwise you can't cancel raw jobs...)
274   */
275
276   if (argc < 7)
277     CatchSignal(SIGTERM, SIG_IGN);
278
279  /*
280   * Queue the job...
281   */
282
283   for (i = 0; i < copies; i ++)
284     if ((status = smb_print(cli, argv[3] /* title */, fp)) != 0)
285       break;
286
287   cli_shutdown(cli);
288
289  /*
290   * Return the queue status...
291   */
292
293   done:
294
295   TALLOC_FREE(frame);
296   return (status);
297 }
298
299
300 /*
301  * 'list_devices()' - List the available printers seen on the network...
302  */
303
304 static void
305 list_devices(void)
306 {
307  /*
308   * Eventually, search the local workgroup for available hosts and printers.
309   */
310
311   puts("network smb \"Unknown\" \"Windows Printer via SAMBA\"");
312 }
313
314
315 /*
316  * get the name of the newest ticket cache for the uid user.
317  * pam_krb5 defines a non default ticket cache for each user
318  */
319 static
320 char * get_ticket_cache( uid_t uid )
321 {
322   char *ticket_file = NULL;
323   SMB_STRUCT_DIR *tcdir;                  /* directory where ticket caches are stored */
324   SMB_STRUCT_DIRENT *dirent;   /* directory entry */
325   char *filename = NULL;       /* holds file names on the tmp directory */
326   SMB_STRUCT_STAT buf;        
327   char user_cache_prefix[CC_MAX_FILE_LEN];
328   char file_path[CC_MAX_FILE_PATH_LEN];
329   time_t t = 0;
330
331   snprintf(user_cache_prefix, CC_MAX_FILE_LEN, "%s%d", CC_PREFIX, uid );
332   tcdir = sys_opendir( TICKET_CC_DIR );
333   if ( tcdir == NULL ) 
334     return NULL; 
335   
336   while ( (dirent = sys_readdir( tcdir ) ) ) 
337   { 
338     filename = dirent->d_name;
339     snprintf(file_path, CC_MAX_FILE_PATH_LEN,"%s/%s", TICKET_CC_DIR, filename); 
340     if (sys_stat(file_path, &buf) == 0 ) 
341     {
342       if ( ( buf.st_uid == uid ) && ( S_ISREG(buf.st_mode) ) ) 
343       {
344         /*
345          * check the user id of the file to prevent denial of
346          * service attacks by creating fake ticket caches for the 
347          * user
348          */
349         if ( strstr( filename, user_cache_prefix ) ) 
350         {
351           if ( buf.st_mtime > t ) 
352           { 
353             /*
354              * a newer ticket cache found 
355              */
356             free(ticket_file);
357             ticket_file=SMB_STRDUP(file_path);
358             t = buf.st_mtime;
359           }
360         }
361       }
362     }
363   }
364
365   sys_closedir(tcdir);
366
367   if ( ticket_file == NULL )
368   {
369     /* no ticket cache found */
370     fprintf(stderr, "ERROR: No ticket cache found for userid=%d\n", uid);
371     return NULL;
372   }
373
374   return ticket_file;
375 }
376
377 static struct cli_state 
378 *smb_complete_connection(const char *myname,
379             const char *server,
380             int port,
381             const char *username, 
382             const char *password, 
383             const char *workgroup, 
384             const char *share,
385             int flags)
386 {
387   struct cli_state  *cli;    /* New connection */    
388   NTSTATUS nt_status;
389   
390   /* Start the SMB connection */
391   nt_status = cli_start_connection( &cli, myname, server, NULL, port, 
392                                     Undefined, flags, NULL);
393   if (!NT_STATUS_IS_OK(nt_status)) 
394   {
395     return NULL;      
396   }
397     
398   /* We pretty much guarentee password must be valid or a pointer
399      to a 0 char. */
400   if (!password) {
401     return NULL;
402   }
403   
404   if ( (username) && (*username) && 
405       (strlen(password) == 0 ) && 
406        (cli->use_kerberos) ) 
407   {
408     /* Use kerberos authentication */
409     struct passwd *pw;
410     char *cache_file;
411     
412     
413     if ( !(pw = sys_getpwnam(username)) ) {
414       fprintf(stderr,"ERROR Can not get %s uid\n", username);
415       cli_shutdown(cli);
416       return NULL;
417     }
418
419     /*
420      * Get the ticket cache of the user to set KRB5CCNAME env
421      * variable
422      */
423     cache_file = get_ticket_cache( pw->pw_uid );
424     if ( cache_file == NULL ) 
425     {
426       fprintf(stderr, "ERROR: Can not get the ticket cache for %s\n", username);
427       cli_shutdown(cli);
428       return NULL;
429     }
430
431     if ( setenv(KRB5CCNAME, cache_file, OVERWRITE) < 0 ) 
432     {
433       fprintf(stderr, "ERROR: Can not add KRB5CCNAME to the environment");
434       cli_shutdown(cli);
435       free(cache_file);
436       return NULL;
437     }
438     free(cache_file);
439
440     /*
441      * Change the UID of the process to be able to read the kerberos
442      * ticket cache
443      */
444     setuid(pw->pw_uid);
445
446   }
447    
448    
449   if (!NT_STATUS_IS_OK(cli_session_setup(cli, username,
450                                          password, strlen(password)+1, 
451                                          password, strlen(password)+1,
452                                          workgroup)))
453   {
454     fprintf(stderr,"ERROR: Session setup failed: %s\n", cli_errstr(cli));
455     if (NT_STATUS_V(cli_nt_error(cli)) == 
456         NT_STATUS_V(NT_STATUS_MORE_PROCESSING_REQUIRED))
457     {
458       fprintf(stderr, "did you forget to run kinit?\n");
459     }
460     cli_shutdown(cli);
461
462     return NULL;
463   }
464     
465   if (!cli_send_tconX(cli, share, "?????", password, strlen(password)+1)) 
466   {
467     fprintf(stderr, "ERROR: Tree connect failed (%s)\n", cli_errstr(cli));
468     cli_shutdown(cli);
469     return NULL;
470   }
471     
472 #if 0
473   /* Need to work out how to specify this on the URL. */
474   if (smb_encrypt)
475   {
476     if (!cli_cm_force_encryption(cli,
477                         username,
478                         password,
479                         workgroup,
480                         share))
481     {
482       fprintf(stderr, "ERROR: encryption setup failed\n");
483       cli_shutdown(cli);
484       return NULL;
485     }
486   }
487 #endif
488
489   return cli;
490 }
491
492 /*
493  * 'smb_connect()' - Return a connection to a server.
494  */
495
496 static struct cli_state *    /* O - SMB connection */
497 smb_connect(const char *workgroup,    /* I - Workgroup */
498             const char *server,    /* I - Server */
499             const int port,    /* I - Port */
500             const char *share,    /* I - Printer */
501             const char *username,    /* I - Username */
502             const char *password,    /* I - Password */
503       const char *jobusername)   /* I - User who issued the print job */
504 {
505   struct cli_state  *cli;    /* New connection */
506   char *myname = NULL;    /* Client name */
507   struct passwd *pwd;
508
509  /*
510   * Get the names and addresses of the client and server...
511   */
512
513   myname = get_myname(talloc_tos());
514   if (!myname) {
515         return NULL;
516   }
517
518   /* See if we have a username first.  This is for backwards compatible 
519      behavior with 3.0.14a */
520
521   if ( username &&  *username )
522   {
523       cli = smb_complete_connection(myname, server, port, username, 
524                                     password, workgroup, share, 0 );
525       if (cli) 
526         return cli;
527   }
528   
529   /* 
530    * Try to use the user kerberos credentials (if any) to authenticate
531    */
532   cli = smb_complete_connection(myname, server, port, jobusername, "", 
533                                 workgroup, share, 
534                                 CLI_FULL_CONNECTION_USE_KERBEROS );
535
536   if (cli ) { return cli; }
537
538   /* give a chance for a passwordless NTLMSSP session setup */
539
540   pwd = getpwuid(geteuid());
541   if (pwd == NULL) {
542      return NULL;
543   }
544
545   cli = smb_complete_connection(myname, server, port, pwd->pw_name, "", 
546                                 workgroup, share, 0);
547
548   if (cli) { return cli; }
549
550   /*
551    * last try. Use anonymous authentication
552    */
553
554   cli = smb_complete_connection(myname, server, port, "", "", 
555                                 workgroup, share, 0);
556   /*
557    * Return the new connection...
558    */
559   
560   return (cli);
561 }
562
563
564 /*
565  * 'smb_print()' - Queue a job for printing using the SMB protocol.
566  */
567
568 static int                              /* O - 0 = success, non-0 = failure */
569 smb_print(struct cli_state *cli,        /* I - SMB connection */
570           char             *title,      /* I - Title/job name */
571           FILE             *fp)         /* I - File to print */
572 {
573   int   fnum;           /* File number */
574   int   nbytes,         /* Number of bytes read */
575         tbytes;         /* Total bytes read */
576   char  buffer[8192],   /* Buffer for copy */
577         *ptr;           /* Pointer into tile */
578
579
580  /*
581   * Sanitize the title...
582   */
583
584   for (ptr = title; *ptr; ptr ++)
585     if (!isalnum((int)*ptr) && !isspace((int)*ptr))
586       *ptr = '_';
587
588  /*
589   * Open the printer device...
590   */
591
592   if ((fnum = cli_open(cli, title, O_RDWR | O_CREAT | O_TRUNC, DENY_NONE)) == -1)
593   {
594     fprintf(stderr, "ERROR: %s opening remote spool %s\n",
595             cli_errstr(cli), title);
596     return (1);
597   }
598
599  /*
600   * Copy the file to the printer...
601   */
602
603   if (fp != stdin)
604     rewind(fp);
605
606   tbytes = 0;
607
608   while ((nbytes = fread(buffer, 1, sizeof(buffer), fp)) > 0)
609   {
610     if (cli_write(cli, fnum, 0, buffer, tbytes, nbytes) != nbytes)
611     {
612       fprintf(stderr, "ERROR: Error writing spool: %s\n", cli_errstr(cli));
613       break;
614     }
615
616     tbytes += nbytes;
617   } 
618
619   if (!cli_close(cli, fnum))
620   {
621     fprintf(stderr, "ERROR: %s closing remote spool %s\n",
622             cli_errstr(cli), title);
623     return (1);
624   }
625   else
626     return (0);
627 }
628
629 static char *uri_unescape_alloc(const char *uritok)
630 {
631         char *ret;
632
633         ret = (char *)SMB_STRDUP(uritok);
634         if (!ret) return NULL;
635
636         rfc1738_unescape(ret);
637         return ret;
638 }