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