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