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