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