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