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