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