r15837: starting sync up for 3.0.23rc1 (in sync with SAMBA_3_0 r15822)
[Samba.git] / source / client / smbspool.c
blobe5cd4f2e8e6573c5eaa0a8087102f218aa83c82d
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
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.
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.
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.
24 #include "includes.h"
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
36 * Globals...
39 extern BOOL in_client; /* Boolean for client library */
43 * Local functions...
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 *);
53 * 'main()' - Main entry for SMB backend.
56 int /* O - Exit status */
57 main(int argc, /* I - Number of command-line arguments */
58 char *argv[]) /* I - Command-line arguments */
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;
76 null_str[0] = '\0';
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--;
84 if (argc == 1)
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... :)
93 list_devices();
94 return (0);
97 if (argc < 6 || argc > 7)
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);
109 * If we have 7 arguments, print the file named on the command-line.
110 * Otherwise, print data from stdin...
114 if (argc == 6)
117 * Print from Copy stdin to a temporary file...
120 fp = stdin;
121 copies = 1;
123 else if ((fp = fopen(argv[6], "rb")) == NULL)
125 perror("ERROR: Unable to open print file");
126 return (1);
128 else
129 copies = atoi(argv[4]);
132 * Find the URI...
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
141 fputs("ERROR: No device URI found in DEVICE_URI environment variable or argv[0] !\n", stderr);
142 return (1);
145 uri[sizeof(uri) - 1] = '\0';
148 * Extract the destination from the URI...
151 if ((sep = strrchr_m(uri, '@')) != NULL)
153 username = uri + 6;
154 *sep++ = '\0';
156 server = sep;
159 * Extract password as needed...
162 if ((password = strchr_m(username, ':')) != NULL)
163 *password++ = '\0';
164 else
165 password = null_str;
167 else
169 username = null_str;
170 password = null_str;
171 server = uri + 6;
174 if ((sep = strchr_m(server, '/')) == NULL)
176 fputs("ERROR: Bad URI - need printer name!\n", stderr);
177 return (1);
180 *sep++ = '\0';
181 printer = sep;
183 if ((sep = strchr_m(printer, '/')) != NULL)
186 * Convert to smb://[username:password@]workgroup/server/printer...
189 *sep++ = '\0';
191 workgroup = server;
192 server = printer;
193 printer = sep;
195 else
196 workgroup = NULL;
198 if ((sep = strrchr_m(server, ':')) != NULL)
200 *sep++ = '\0';
202 port=atoi(sep);
204 else
205 port=0;
209 * Setup the SAMBA server state...
212 setup_logging("smbspool", True);
214 in_client = True; /* Make sure that we tell lp_load we are */
216 load_case_tables();
218 if (!lp_load(dyn_CONFIGFILE, True, False, False, True))
220 fprintf(stderr, "ERROR: Can't load %s - run testparm to debug it\n", dyn_CONFIGFILE);
221 return (1);
224 if (workgroup == NULL)
225 workgroup = lp_workgroup();
227 load_interfaces();
231 if ((cli = smb_connect(workgroup, server, port, printer, username, password, argv[2])) == NULL)
233 if (getenv("CLASS") == NULL)
235 fprintf(stderr, "ERROR: Unable to connect to CIFS host, will retry in 60 seconds...\n");
236 sleep (60); /* should just waiting and retrying fix authentication ??? */
237 tries++;
239 else
241 fprintf(stderr, "ERROR: Unable to connect to CIFS host, trying next printer...\n");
242 return (1);
246 while ((cli == NULL) && (tries < MAX_RETRY_CONNECT));
248 if (cli == NULL) {
249 fprintf(stderr, "ERROR: Unable to connect to CIFS host after (tried %d times)\n", tries);
250 return (1);
254 * Now that we are connected to the server, ignore SIGTERM so that we
255 * can finish out any page data the driver sends (e.g. to eject the
256 * current page... Only ignore SIGTERM if we are printing data from
257 * stdin (otherwise you can't cancel raw jobs...)
260 if (argc < 7)
261 CatchSignal(SIGTERM, SIG_IGN);
264 * Queue the job...
267 for (i = 0; i < copies; i ++)
268 if ((status = smb_print(cli, argv[3] /* title */, fp)) != 0)
269 break;
271 cli_shutdown(cli);
274 * Return the queue status...
277 return (status);
282 * 'list_devices()' - List the available printers seen on the network...
285 static void
286 list_devices(void)
289 * Eventually, search the local workgroup for available hosts and printers.
292 puts("network smb \"Unknown\" \"Windows Printer via SAMBA\"");
297 * get the name of the newest ticket cache for the uid user.
298 * pam_krb5 defines a non default ticket cache for each user
300 static
301 char * get_ticket_cache( uid_t uid )
303 char *ticket_file = NULL;
304 SMB_STRUCT_DIR *tcdir; /* directory where ticket caches are stored */
305 SMB_STRUCT_DIRENT *dirent; /* directory entry */
306 char *filename = NULL; /* holds file names on the tmp directory */
307 SMB_STRUCT_STAT buf;
308 char user_cache_prefix[CC_MAX_FILE_LEN];
309 char file_path[CC_MAX_FILE_PATH_LEN];
310 time_t t = 0;
312 snprintf(user_cache_prefix, CC_MAX_FILE_LEN, "%s%d", CC_PREFIX, uid );
313 tcdir = sys_opendir( TICKET_CC_DIR );
314 if ( tcdir == NULL )
315 return NULL;
317 while ( (dirent = sys_readdir( tcdir ) ) )
319 filename = dirent->d_name;
320 snprintf(file_path, CC_MAX_FILE_PATH_LEN,"%s/%s", TICKET_CC_DIR, filename);
321 if (sys_stat(file_path, &buf) == 0 )
323 if ( ( buf.st_uid == uid ) && ( S_ISREG(buf.st_mode) ) )
326 * check the user id of the file to prevent denial of
327 * service attacks by creating fake ticket caches for the
328 * user
330 if ( strstr( filename, user_cache_prefix ) )
332 if ( buf.st_mtime > t )
335 * a newer ticket cache found
337 free(ticket_file);
338 ticket_file=SMB_STRDUP(file_path);
339 t = buf.st_mtime;
346 sys_closedir(tcdir);
348 if ( ticket_file == NULL )
350 /* no ticket cache found */
351 fprintf(stderr, "ERROR: No ticket cache found for userid=%d\n", uid);
352 return NULL;
355 return ticket_file;
358 static struct cli_state
359 *smb_complete_connection(const char *myname,
360 const char *server,
361 int port,
362 const char *username,
363 const char *password,
364 const char *workgroup,
365 const char *share,
366 int flags)
368 struct cli_state *cli; /* New connection */
369 NTSTATUS nt_status;
371 /* Start the SMB connection */
372 nt_status = cli_start_connection( &cli, myname, server, NULL, port,
373 Undefined, flags, NULL);
374 if (!NT_STATUS_IS_OK(nt_status))
376 return NULL;
379 /* We pretty much guarentee password must be valid or a pointer
380 to a 0 char. */
381 if (!password) {
382 return NULL;
385 if ( (username) && (*username) &&
386 (strlen(password) == 0 ) &&
387 (cli->use_kerberos) )
389 /* Use kerberos authentication */
390 struct passwd *pw;
391 char *cache_file;
394 if ( !(pw = sys_getpwnam(username)) ) {
395 fprintf(stderr,"ERROR Can not get %s uid\n", username);
396 cli_shutdown(cli);
397 return NULL;
401 * Get the ticket cache of the user to set KRB5CCNAME env
402 * variable
404 cache_file = get_ticket_cache( pw->pw_uid );
405 if ( cache_file == NULL )
407 fprintf(stderr, "ERROR: Can not get the ticket cache for %s\n", username);
408 cli_shutdown(cli);
409 return NULL;
412 if ( setenv(KRB5CCNAME, cache_file, OVERWRITE) < 0 )
414 fprintf(stderr, "ERROR: Can not add KRB5CCNAME to the environment");
415 cli_shutdown(cli);
416 free(cache_file);
417 return NULL;
419 free(cache_file);
422 * Change the UID of the process to be able to read the kerberos
423 * ticket cache
425 setuid(pw->pw_uid);
430 if (!cli_session_setup(cli, username, password, strlen(password)+1,
431 password, strlen(password)+1,
432 workgroup))
434 fprintf(stderr,"ERROR: Session setup failed: %s\n", cli_errstr(cli));
435 if (NT_STATUS_V(cli_nt_error(cli)) ==
436 NT_STATUS_V(NT_STATUS_MORE_PROCESSING_REQUIRED))
438 fprintf(stderr, "did you forget to run kinit?\n");
440 cli_shutdown(cli);
442 return NULL;
445 if (!cli_send_tconX(cli, share, "?????", password, strlen(password)+1))
447 fprintf(stderr, "ERROR: Tree connect failed (%s)\n", cli_errstr(cli));
448 cli_shutdown(cli);
449 return NULL;
452 return cli;
456 * 'smb_connect()' - Return a connection to a server.
459 static struct cli_state * /* O - SMB connection */
460 smb_connect(const char *workgroup, /* I - Workgroup */
461 const char *server, /* I - Server */
462 const int port, /* I - Port */
463 const char *share, /* I - Printer */
464 const char *username, /* I - Username */
465 const char *password, /* I - Password */
466 const char *jobusername) /* I - User who issued the print job */
468 struct cli_state *cli; /* New connection */
469 pstring myname; /* Client name */
470 struct passwd *pwd;
473 * Get the names and addresses of the client and server...
476 get_myname(myname);
478 /* See if we have a username first. This is for backwards compatible
479 behavior with 3.0.14a */
481 if ( username && *username )
483 cli = smb_complete_connection(myname, server, port, username,
484 password, workgroup, share, 0 );
485 if (cli)
486 return cli;
490 * Try to use the user kerberos credentials (if any) to authenticate
492 cli = smb_complete_connection(myname, server, port, jobusername, "",
493 workgroup, share,
494 CLI_FULL_CONNECTION_USE_KERBEROS );
496 if (cli ) { return cli; }
498 /* give a chance for a passwordless NTLMSSP session setup */
500 pwd = getpwuid(geteuid());
501 if (pwd == NULL) {
502 return NULL;
505 cli = smb_complete_connection(myname, server, port, pwd->pw_name, "",
506 workgroup, share, 0);
508 if (cli) { return cli; }
511 * last try. Use anonymous authentication
514 cli = smb_complete_connection(myname, server, port, "", "",
515 workgroup, share, 0);
517 * Return the new connection...
520 return (cli);
525 * 'smb_print()' - Queue a job for printing using the SMB protocol.
528 static int /* O - 0 = success, non-0 = failure */
529 smb_print(struct cli_state *cli, /* I - SMB connection */
530 char *title, /* I - Title/job name */
531 FILE *fp) /* I - File to print */
533 int fnum; /* File number */
534 int nbytes, /* Number of bytes read */
535 tbytes; /* Total bytes read */
536 char buffer[8192], /* Buffer for copy */
537 *ptr; /* Pointer into tile */
541 * Sanitize the title...
544 for (ptr = title; *ptr; ptr ++)
545 if (!isalnum((int)*ptr) && !isspace((int)*ptr))
546 *ptr = '_';
549 * Open the printer device...
552 if ((fnum = cli_open(cli, title, O_RDWR | O_CREAT | O_TRUNC, DENY_NONE)) == -1)
554 fprintf(stderr, "ERROR: %s opening remote spool %s\n",
555 cli_errstr(cli), title);
556 return (1);
560 * Copy the file to the printer...
563 if (fp != stdin)
564 rewind(fp);
566 tbytes = 0;
568 while ((nbytes = fread(buffer, 1, sizeof(buffer), fp)) > 0)
570 if (cli_write(cli, fnum, 0, buffer, tbytes, nbytes) != nbytes)
572 fprintf(stderr, "ERROR: Error writing spool: %s\n", cli_errstr(cli));
573 break;
576 tbytes += nbytes;
579 if (!cli_close(cli, fnum))
581 fprintf(stderr, "ERROR: %s closing remote spool %s\n",
582 cli_errstr(cli), title);
583 return (1);
585 else
586 return (0);