r14145: Add missing WITH_KCM hunks from my local tree.
[Samba/nascimento.git] / source3 / client / smbspool.c
blob92e0bb4b674b3ec57567accd2635fd6d2db8e647
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 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 #define MAX_RETRY_CONNECT 3
37 * Globals...
40 extern BOOL in_client; /* Boolean for client library */
44 * Local functions...
47 static void list_devices(void);
48 static struct cli_state *smb_complete_connection(const char *, const char *,int , const char *, const char *, const char *, const char *, int);
49 static struct cli_state *smb_connect(const char *, const char *, int, const char *, const char *, const char *, const char *);
50 static int smb_print(struct cli_state *, char *, FILE *);
54 * 'main()' - Main entry for SMB backend.
57 int /* O - Exit status */
58 main(int argc, /* I - Number of command-line arguments */
59 char *argv[]) /* I - Command-line arguments */
61 int i; /* Looping var */
62 int copies; /* Number of copies */
63 int port; /* Port number */
64 char uri[1024], /* URI */
65 *sep, /* Pointer to separator */
66 *password; /* Password */
67 const char *username, /* Username */
68 *server, /* Server name */
69 *printer; /* Printer name */
70 const char *workgroup; /* Workgroup */
71 FILE *fp; /* File to print */
72 int status=0; /* Status of LPD job */
73 struct cli_state *cli; /* SMB interface */
74 char null_str[1];
75 int tries = 0;
77 null_str[0] = '\0';
79 /* we expect the URI in argv[0]. Detect the case where it is in argv[1] and cope */
80 if (argc > 2 && strncmp(argv[0],"smb://", 6) && !strncmp(argv[1],"smb://", 6)) {
81 argv++;
82 argc--;
85 if (argc == 1)
88 * NEW! In CUPS 1.1 the backends are run with no arguments to list the
89 * available devices. These can be devices served by this backend
90 * or any other backends (i.e. you can have an SNMP backend that
91 * is only used to enumerate the available network printers... :)
94 list_devices();
95 return (0);
98 if (argc < 6 || argc > 7)
100 fprintf(stderr, "Usage: %s [DEVICE_URI] job-id user title copies options [file]\n",
101 argv[0]);
102 fputs(" The DEVICE_URI environment variable can also contain the\n", stderr);
103 fputs(" destination printer:\n", stderr);
104 fputs("\n", stderr);
105 fputs(" smb://[username:password@][workgroup/]server[:port]/printer\n", stderr);
106 return (1);
110 * If we have 7 arguments, print the file named on the command-line.
111 * Otherwise, print data from stdin...
115 if (argc == 6)
118 * Print from Copy stdin to a temporary file...
121 fp = stdin;
122 copies = 1;
124 else if ((fp = fopen(argv[6], "rb")) == NULL)
126 perror("ERROR: Unable to open print file");
127 return (1);
129 else
130 copies = atoi(argv[4]);
133 * Find the URI...
136 if (getenv("DEVICE_URI") != NULL)
137 strncpy(uri, getenv("DEVICE_URI"), sizeof(uri) - 1);
138 else if (strncmp(argv[0], "smb://", 6) == 0)
139 strncpy(uri, argv[0], sizeof(uri) - 1);
140 else
142 fputs("ERROR: No device URI found in DEVICE_URI environment variable or argv[0] !\n", stderr);
143 return (1);
146 uri[sizeof(uri) - 1] = '\0';
149 * Extract the destination from the URI...
152 if ((sep = strrchr_m(uri, '@')) != NULL)
154 username = uri + 6;
155 *sep++ = '\0';
157 server = sep;
160 * Extract password as needed...
163 if ((password = strchr_m(username, ':')) != NULL)
164 *password++ = '\0';
165 else
166 password = null_str;
168 else
170 username = null_str;
171 password = null_str;
172 server = uri + 6;
175 if ((sep = strchr_m(server, '/')) == NULL)
177 fputs("ERROR: Bad URI - need printer name!\n", stderr);
178 return (1);
181 *sep++ = '\0';
182 printer = sep;
184 if ((sep = strchr_m(printer, '/')) != NULL)
187 * Convert to smb://[username:password@]workgroup/server/printer...
190 *sep++ = '\0';
192 workgroup = server;
193 server = printer;
194 printer = sep;
196 else
197 workgroup = NULL;
199 if ((sep = strrchr_m(server, ':')) != NULL)
201 *sep++ = '\0';
203 port=atoi(sep);
205 else
206 port=0;
210 * Setup the SAMBA server state...
213 setup_logging("smbspool", True);
215 in_client = True; /* Make sure that we tell lp_load we are */
217 if (!lp_load(dyn_CONFIGFILE, True, False, False, True))
219 fprintf(stderr, "ERROR: Can't load %s - run testparm to debug it\n", dyn_CONFIGFILE);
220 return (1);
223 if (workgroup == NULL)
224 workgroup = lp_workgroup();
226 load_interfaces();
230 if ((cli = smb_connect(workgroup, server, port, printer, username, password, argv[2])) == NULL)
232 if (getenv("CLASS") == NULL)
234 fprintf(stderr, "ERROR: Unable to connect to CIFS host, will retry in 60 seconds...\n");
235 sleep (60); /* should just waiting and retrying fix authentication ??? */
236 tries++;
238 else
240 fprintf(stderr, "ERROR: Unable to connect to CIFS host, trying next printer...\n");
241 return (1);
245 while ((cli == NULL) && (tries < MAX_RETRY_CONNECT));
247 if (cli == NULL) {
248 fprintf(stderr, "ERROR: Unable to connect to CIFS host after (tried %d times)\n", tries);
249 return (1);
253 * Now that we are connected to the server, ignore SIGTERM so that we
254 * can finish out any page data the driver sends (e.g. to eject the
255 * current page... Only ignore SIGTERM if we are printing data from
256 * stdin (otherwise you can't cancel raw jobs...)
259 if (argc < 7)
260 CatchSignal(SIGTERM, SIG_IGN);
263 * Queue the job...
266 for (i = 0; i < copies; i ++)
267 if ((status = smb_print(cli, argv[3] /* title */, fp)) != 0)
268 break;
270 cli_shutdown(cli);
273 * Return the queue status...
276 return (status);
281 * 'list_devices()' - List the available printers seen on the network...
284 static void
285 list_devices(void)
288 * Eventually, search the local workgroup for available hosts and printers.
291 puts("network smb \"Unknown\" \"Windows Printer via SAMBA\"");
296 * get the name of the newest ticket cache for the uid user.
297 * pam_krb5 defines a non default ticket cache for each user
299 static
300 char * get_ticket_cache( uid_t uid )
302 char *ticket_file = NULL;
304 #ifdef WITH_KCM
305 snprintf(ticket_file, CC_MAX_FILE_LEN, "KCM:%d", uid );
306 goto done;
307 #else
309 SMB_STRUCT_DIR *tcdir; /* directory where ticket caches are stored */
310 SMB_STRUCT_DIRENT *dirent; /* directory entry */
311 char *filename = NULL; /* holds file names on the tmp directory */
312 SMB_STRUCT_STAT buf;
313 char user_cache_prefix[CC_MAX_FILE_LEN];
314 char file_path[CC_MAX_FILE_PATH_LEN];
315 time_t t = 0;
317 snprintf(user_cache_prefix, CC_MAX_FILE_LEN, "%s%d", CC_PREFIX, uid );
318 tcdir = sys_opendir( TICKET_CC_DIR );
319 if ( tcdir == NULL )
320 return NULL;
322 while ( (dirent = sys_readdir( tcdir ) ) )
324 filename = dirent->d_name;
325 snprintf(file_path, CC_MAX_FILE_PATH_LEN,"%s/%s", TICKET_CC_DIR, filename);
326 if (sys_stat(file_path, &buf) == 0 )
328 if ( ( buf.st_uid == uid ) && ( S_ISREG(buf.st_mode) ) )
331 * check the user id of the file to prevent denial of
332 * service attacks by creating fake ticket caches for the
333 * user
335 if ( strstr( filename, user_cache_prefix ) )
337 if ( buf.st_mtime > t )
340 * a newer ticket cache found
342 free(ticket_file);
343 ticket_file=SMB_STRDUP(file_path);
344 t = buf.st_mtime;
351 sys_closedir(tcdir);
353 #endif
355 done:
357 if ( ticket_file == NULL )
359 /* no ticket cache found */
360 fprintf(stderr, "ERROR: No ticket cache found for userid=%d\n", uid);
361 return NULL;
364 return ticket_file;
367 static struct cli_state
368 *smb_complete_connection(const char *myname,
369 const char *server,
370 int port,
371 const char *username,
372 const char *password,
373 const char *workgroup,
374 const char *share,
375 int flags)
377 struct cli_state *cli; /* New connection */
378 NTSTATUS nt_status;
380 /* Start the SMB connection */
381 nt_status = cli_start_connection( &cli, myname, server, NULL, port,
382 Undefined, flags, NULL);
383 if (!NT_STATUS_IS_OK(nt_status))
385 return NULL;
389 if ( (username) && (*username) &&
390 ((!password) || ((password) && (strlen(password) == 0 ))) &&
391 (cli->use_kerberos) )
393 /* Use kerberos authentication */
394 struct passwd *pw;
395 char *cache_file;
398 if ( !(pw = sys_getpwnam(username)) ) {
399 fprintf(stderr,"ERROR Can not get %s uid\n", username);
400 cli_shutdown(cli);
401 return NULL;
405 * Get the ticket cache of the user to set KRB5CCNAME env
406 * variable
408 cache_file = get_ticket_cache( pw->pw_uid );
409 if ( cache_file == NULL )
411 fprintf(stderr, "ERROR: Can not get the ticket cache for %s\n", username);
412 cli_shutdown(cli);
413 return NULL;
416 if ( setenv(KRB5CCNAME, cache_file, OVERWRITE) < 0 )
418 fprintf(stderr, "ERROR: Can not add KRB5CCNAME to the environment");
419 cli_shutdown(cli);
420 free(cache_file);
421 return NULL;
423 free(cache_file);
426 * Change the UID of the process to be able to read the kerberos
427 * ticket cache
429 setuid(pw->pw_uid);
434 if (!cli_session_setup(cli, username, password, strlen(password)+1,
435 password, strlen(password)+1,
436 workgroup))
438 fprintf(stderr,"ERROR: Session setup failed: %s\n", cli_errstr(cli));
439 if (NT_STATUS_V(cli_nt_error(cli)) ==
440 NT_STATUS_V(NT_STATUS_MORE_PROCESSING_REQUIRED))
442 fprintf(stderr, "did you forget to run kinit?\n");
444 cli_shutdown(cli);
446 return NULL;
449 if (!cli_send_tconX(cli, share, "?????", password, strlen(password)+1))
451 fprintf(stderr, "ERROR: Tree connect failed (%s)\n", cli_errstr(cli));
452 cli_shutdown(cli);
453 return NULL;
456 return cli;
460 * 'smb_connect()' - Return a connection to a server.
463 static struct cli_state * /* O - SMB connection */
464 smb_connect(const char *workgroup, /* I - Workgroup */
465 const char *server, /* I - Server */
466 const int port, /* I - Port */
467 const char *share, /* I - Printer */
468 const char *username, /* I - Username */
469 const char *password, /* I - Password */
470 const char *jobusername) /* I - User who issued the print job */
472 struct cli_state *cli; /* New connection */
473 pstring myname; /* Client name */
474 struct passwd *pwd;
477 * Get the names and addresses of the client and server...
480 get_myname(myname);
482 /* See if we have a username first. This is for backwards compatible
483 behavior with 3.0.14a */
485 if ( username && *username )
487 cli = smb_complete_connection(myname, server, port, username,
488 password, workgroup, share, 0 );
489 if (cli)
490 return cli;
494 * Try to use the user kerberos credentials (if any) to authenticate
496 cli = smb_complete_connection(myname, server, port, jobusername, "",
497 workgroup, share,
498 CLI_FULL_CONNECTION_USE_KERBEROS );
500 if (cli ) { return cli; }
502 /* give a chance for a passwordless NTLMSSP session setup */
504 pwd = getpwuid(geteuid());
505 if (pwd == NULL) {
506 return NULL;
509 cli = smb_complete_connection(myname, server, port, pwd->pw_name, "",
510 workgroup, share, 0);
512 if (cli) { return cli; }
515 * last try. Use anonymous authentication
518 cli = smb_complete_connection(myname, server, port, "", "",
519 workgroup, share, 0);
521 * Return the new connection...
524 return (cli);
529 * 'smb_print()' - Queue a job for printing using the SMB protocol.
532 static int /* O - 0 = success, non-0 = failure */
533 smb_print(struct cli_state *cli, /* I - SMB connection */
534 char *title, /* I - Title/job name */
535 FILE *fp) /* I - File to print */
537 int fnum; /* File number */
538 int nbytes, /* Number of bytes read */
539 tbytes; /* Total bytes read */
540 char buffer[8192], /* Buffer for copy */
541 *ptr; /* Pointer into tile */
545 * Sanitize the title...
548 for (ptr = title; *ptr; ptr ++)
549 if (!isalnum((int)*ptr) && !isspace((int)*ptr))
550 *ptr = '_';
553 * Open the printer device...
556 if ((fnum = cli_open(cli, title, O_RDWR | O_CREAT | O_TRUNC, DENY_NONE)) == -1)
558 fprintf(stderr, "ERROR: %s opening remote spool %s\n",
559 cli_errstr(cli), title);
560 return (1);
564 * Copy the file to the printer...
567 if (fp != stdin)
568 rewind(fp);
570 tbytes = 0;
572 while ((nbytes = fread(buffer, 1, sizeof(buffer), fp)) > 0)
574 if (cli_write(cli, fnum, 0, buffer, tbytes, nbytes) != nbytes)
576 fprintf(stderr, "ERROR: Error writing spool: %s\n", cli_errstr(cli));
577 break;
580 tbytes += nbytes;
583 if (!cli_close(cli, fnum))
585 fprintf(stderr, "ERROR: %s closing remote spool %s\n",
586 cli_errstr(cli), title);
587 return (1);
589 else
590 return (0);