s3:client: Fix smbspool device uri handling
[Samba.git] / source3 / client / smbspool.c
blob8be1009c0a89049a529c1df3c73651bfa25cc2e3
1 /*
2 Unix SMB/CIFS implementation.
3 SMB backend for the Common UNIX Printing System ("CUPS")
5 Copyright (C) Michael R Sweet 1999
6 Copyright (C) Andrew Tridgell 1994-1998
7 Copyright (C) Andrew Bartlett 2002
8 Copyright (C) Rodrigo Fernandez-Vizarra 2005
9 Copyright (C) James Peach 2008
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 3 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "includes.h"
26 #include "system/filesys.h"
27 #include "system/passwd.h"
28 #include "system/kerberos.h"
29 #include "libsmb/libsmb.h"
30 #include "lib/param/param.h"
33 * Starting with CUPS 1.3, Kerberos support is provided by cupsd including
34 * the forwarding of user credentials via the authenticated session between
35 * user and server and the KRB5CCNAME environment variable which will point
36 * to a temporary file or an in-memory representation depending on the version
37 * of Kerberos you use. As a result, all of the ticket code that used to
38 * live here has been removed, and we depend on the user session (if you
39 * run smbspool by hand) or cupsd to provide the necessary Kerberos info.
41 * Also, the AUTH_USERNAME and AUTH_PASSWORD environment variables provide
42 * for per-job authentication for non-Kerberized printing. We use those
43 * if there is no username and password specified in the device URI.
45 * Finally, if we have an authentication failure we return exit code 2
46 * which tells CUPS to hold the job for authentication and bug the user
47 * to get the necessary credentials.
50 #define MAX_RETRY_CONNECT 3
54 * Globals...
60 * Local functions...
63 static int get_exit_code(struct cli_state * cli, NTSTATUS nt_status);
64 static void list_devices(void);
65 static struct cli_state *smb_complete_connection(const char *, const char *,
66 int, const char *, const char *, const char *, const char *, int, bool *need_auth);
67 static struct cli_state *smb_connect(const char *, const char *, int, const
68 char *, const char *, const char *, const char *, bool *need_auth);
69 static int smb_print(struct cli_state *, const char *, FILE *);
70 static char *uri_unescape_alloc(const char *);
71 #if 0
72 static bool smb_encrypt;
73 #endif
75 static const char *auth_info_required;
78 * 'main()' - Main entry for SMB backend.
81 int /* O - Exit status */
82 main(int argc, /* I - Number of command-line arguments */
83 char *argv[])
84 { /* I - Command-line arguments */
85 int i; /* Looping var */
86 int copies; /* Number of copies */
87 int port; /* Port number */
88 char uri[1024], /* URI */
89 *sep, /* Pointer to separator */
90 *tmp, *tmp2, /* Temp pointers to do escaping */
91 *password; /* Password */
92 char *username, /* Username */
93 *server, /* Server name */
94 *printer;/* Printer name */
95 const char *workgroup; /* Workgroup */
96 FILE *fp; /* File to print */
97 int status = 1; /* Status of LPD job */
98 struct cli_state *cli; /* SMB interface */
99 char empty_str[] = "";
100 int tries = 0;
101 bool need_auth = true;
102 const char *dev_uri = NULL;
103 const char *env = NULL;
104 const char *config_file = NULL;
105 TALLOC_CTX *frame = talloc_stackframe();
106 const char *print_user = NULL;
107 const char *print_title = NULL;
108 const char *print_file = NULL;
109 const char *print_copies = NULL;
110 int cmp;
111 int len;
113 if (argc == 1) {
115 * NEW! In CUPS 1.1 the backends are run with no arguments
116 * to list the available devices. These can be devices
117 * served by this backend or any other backends (i.e. you
118 * can have an SNMP backend that is only used to enumerate
119 * the available network printers... :)
122 list_devices();
123 status = 0;
124 goto done;
128 * We need at least 5 options if the DEVICE_URI is passed via an env
129 * variable and printing data comes via stdin.
130 * We don't accept more than 7 options in total, including optional.
132 if (argc < 5 || argc > 8) {
133 fprintf(stderr,
134 "Usage: %s [DEVICE_URI] job-id user title copies options [file]\n"
135 " The DEVICE_URI environment variable can also contain the\n"
136 " destination printer:\n"
137 "\n"
138 " smb://[username:password@][workgroup/]server[:port]/printer\n",
139 argv[0]);
140 goto done;
144 * Find out if we have the device_uri in the command line.
146 * If we are started as a CUPS backend argv[0] is normally the
147 * device_uri!
149 if (argc == 8) {
151 * smbspool <uri> <job> <user> <title> <copies> <options> <file>
152 * 0 1 2 3 4 5 6 7
155 dev_uri = argv[1];
157 print_user = argv[3];
158 print_title = argv[4];
159 print_copies = argv[5];
160 print_file = argv[7];
161 } else if (argc == 7) {
162 int cmp1;
163 int cmp2;
166 * <uri> <job> <user> <title> <copies> <options> <file>
167 * smbspool <uri> <job> <user> <title> <copies> <options>
168 * smbspool <job> <user> <title> <copies> <options> <file> | DEVICE_URI
170 cmp1 = strncmp(argv[0], "smb://", 6);
171 cmp2 = strncmp(argv[1], "smb://", 6);
173 if (cmp1 == 0) {
175 * <uri> <job> <user> <title> <copies> <options> <file>
176 * 0 1 2 3 4 5 6
178 dev_uri = argv[0];
180 print_user = argv[2];
181 print_title = argv[3];
182 print_copies = argv[4];
183 print_file = argv[6];
184 } else if (cmp2 == 0) {
186 * smbspool <uri> <job> <user> <title> <copies> <options>
187 * 0 1 2 3 4 5 6
189 dev_uri = argv[1];
191 print_user = argv[3];
192 print_title = argv[4];
193 print_copies = argv[5];
194 print_file = NULL;
195 } else {
197 * smbspool <job> <user> <title> <copies> <options> <file> | DEVICE_URI
198 * 0 1 2 3 4 5 6
200 print_user = argv[2];
201 print_title = argv[3];
202 print_copies = argv[4];
203 print_file = argv[6];
205 } else if (argc == 6) {
207 * <uri> <job> <user> <title> <copies> <options>
208 * smbspool <job> <user> <title> <copies> <options> | DEVICE_URI
209 * 0 1 2 3 4 5
211 cmp = strncmp(argv[0], "smb://", 6);
212 if (cmp == 0) {
213 dev_uri = argv[0];
216 print_user = argv[2];
217 print_title = argv[3];
218 print_copies = argv[4];
221 if (print_file != NULL) {
222 char *endp;
224 fp = fopen(print_file, "rb");
225 if (fp == NULL) {
226 perror("ERROR: Unable to open print file");
227 goto done;
230 copies = strtol(print_copies, &endp, 10);
231 if (print_copies == endp) {
232 perror("ERROR: Unable to determine number of copies");
233 goto done;
235 } else {
236 fp = stdin;
237 copies = 1;
241 * Find the URI ...
243 if (dev_uri == NULL) {
244 env = getenv("DEVICE_URI");
245 if (env != NULL && env[0] != '\0') {
246 dev_uri = env;
250 if (dev_uri == NULL) {
251 fprintf(stderr,
252 "ERROR: No valid device URI has been specified\n");
253 goto done;
256 cmp = strncmp(dev_uri, "smb://", 6);
257 if (cmp != 0) {
258 fprintf(stderr,
259 "ERROR: No valid device URI has been specified\n");
260 goto done;
262 len = snprintf(uri, sizeof(uri), "%s", dev_uri);
263 if (len >= sizeof(uri)) {
264 fprintf(stderr,
265 "ERROR: The URI is too long.\n");
266 goto done;
269 auth_info_required = getenv("AUTH_INFO_REQUIRED");
270 if (auth_info_required == NULL) {
271 auth_info_required = "none";
275 * Extract the destination from the URI...
278 if ((sep = strrchr_m(uri, '@')) != NULL) {
279 tmp = uri + 6;
280 *sep++ = '\0';
282 /* username is in tmp */
284 server = sep;
287 * Extract password as needed...
290 if ((tmp2 = strchr_m(tmp, ':')) != NULL) {
291 *tmp2++ = '\0';
292 password = uri_unescape_alloc(tmp2);
293 } else {
294 password = empty_str;
296 username = uri_unescape_alloc(tmp);
297 } else {
298 if ((username = getenv("AUTH_USERNAME")) == NULL) {
299 username = empty_str;
302 if ((password = getenv("AUTH_PASSWORD")) == NULL) {
303 password = empty_str;
306 server = uri + 6;
309 if (password != empty_str) {
310 auth_info_required = "username,password";
313 tmp = server;
315 if ((sep = strchr_m(tmp, '/')) == NULL) {
316 fputs("ERROR: Bad URI - need printer name!\n", stderr);
317 goto done;
320 *sep++ = '\0';
321 tmp2 = sep;
323 if ((sep = strchr_m(tmp2, '/')) != NULL) {
325 * Convert to smb://[username:password@]workgroup/server/printer...
328 *sep++ = '\0';
330 workgroup = uri_unescape_alloc(tmp);
331 server = uri_unescape_alloc(tmp2);
332 printer = uri_unescape_alloc(sep);
333 } else {
334 workgroup = NULL;
335 server = uri_unescape_alloc(tmp);
336 printer = uri_unescape_alloc(tmp2);
339 if ((sep = strrchr_m(server, ':')) != NULL) {
340 *sep++ = '\0';
342 port = atoi(sep);
343 } else {
344 port = 0;
348 * Setup the SAMBA server state...
351 setup_logging("smbspool", DEBUG_STDERR);
353 smb_init_locale();
355 config_file = lp_default_path();
356 if (!lp_load_client(config_file)) {
357 fprintf(stderr,
358 "ERROR: Can't load %s - run testparm to debug it\n",
359 config_file);
360 goto done;
363 if (workgroup == NULL) {
364 workgroup = lp_workgroup();
367 load_interfaces();
369 do {
370 cli = smb_connect(workgroup,
371 server,
372 port,
373 printer,
374 username,
375 password,
376 print_user,
377 &need_auth);
378 if (cli == NULL) {
379 if (need_auth) {
380 exit(2);
381 } else if (getenv("CLASS") == NULL) {
382 fprintf(stderr, "ERROR: Unable to connect to CIFS host, will retry in 60 seconds...\n");
383 sleep(60);
384 tries++;
385 } else {
386 fprintf(stderr, "ERROR: Unable to connect to CIFS host, trying next printer...\n");
387 goto done;
390 } while ((cli == NULL) && (tries < MAX_RETRY_CONNECT));
392 if (cli == NULL) {
393 fprintf(stderr, "ERROR: Unable to connect to CIFS host after (tried %d times)\n", tries);
394 goto done;
398 * Now that we are connected to the server, ignore SIGTERM so that we
399 * can finish out any page data the driver sends (e.g. to eject the
400 * current page... Only ignore SIGTERM if we are printing data from
401 * stdin (otherwise you can't cancel raw jobs...)
404 if (argc < 7) {
405 CatchSignal(SIGTERM, SIG_IGN);
409 * Queue the job...
412 for (i = 0; i < copies; i++) {
413 status = smb_print(cli, print_title, fp);
414 if (status != 0) {
415 break;
419 cli_shutdown(cli);
422 * Return the queue status...
425 done:
427 TALLOC_FREE(frame);
428 return (status);
433 * 'get_exit_code()' - Get the backend exit code based on the current error.
436 static int
437 get_exit_code(struct cli_state * cli,
438 NTSTATUS nt_status)
440 int i;
442 /* List of NTSTATUS errors that are considered
443 * authentication errors
445 static const NTSTATUS auth_errors[] =
447 NT_STATUS_ACCESS_DENIED, NT_STATUS_ACCESS_VIOLATION,
448 NT_STATUS_SHARING_VIOLATION, NT_STATUS_PRIVILEGE_NOT_HELD,
449 NT_STATUS_INVALID_ACCOUNT_NAME, NT_STATUS_NO_SUCH_USER,
450 NT_STATUS_WRONG_PASSWORD, NT_STATUS_LOGON_FAILURE,
451 NT_STATUS_ACCOUNT_RESTRICTION, NT_STATUS_INVALID_LOGON_HOURS,
452 NT_STATUS_PASSWORD_EXPIRED, NT_STATUS_ACCOUNT_DISABLED
456 fprintf(stderr, "DEBUG: get_exit_code(cli=%p, nt_status=%s [%x])\n",
457 cli, nt_errstr(nt_status), NT_STATUS_V(nt_status));
459 for (i = 0; i < ARRAY_SIZE(auth_errors); i++) {
460 if (!NT_STATUS_EQUAL(nt_status, auth_errors[i])) {
461 continue;
464 if (cli) {
465 fprintf(stderr, "ATTR: auth-info-required=%s\n", auth_info_required);
469 * 2 = authentication required...
472 return (2);
477 * 1 = fail
480 return (1);
485 * 'list_devices()' - List the available printers seen on the network...
488 static void
489 list_devices(void)
492 * Eventually, search the local workgroup for available hosts and printers.
495 puts("network smb \"Unknown\" \"Windows Printer via SAMBA\"");
499 static struct cli_state *
500 smb_complete_connection(const char *myname,
501 const char *server,
502 int port,
503 const char *username,
504 const char *password,
505 const char *workgroup,
506 const char *share,
507 int flags,
508 bool *need_auth)
510 struct cli_state *cli; /* New connection */
511 NTSTATUS nt_status;
512 struct cli_credentials *creds = NULL;
513 bool use_kerberos = false;
515 /* Start the SMB connection */
516 *need_auth = false;
517 nt_status = cli_start_connection(&cli, myname, server, NULL, port,
518 SMB_SIGNING_DEFAULT, flags);
519 if (!NT_STATUS_IS_OK(nt_status)) {
520 fprintf(stderr, "ERROR: Connection failed: %s\n", nt_errstr(nt_status));
521 return NULL;
525 * We pretty much guarantee password must be valid or a pointer to a
526 * 0 char.
528 if (!password) {
529 *need_auth = true;
530 return NULL;
533 if (flags & CLI_FULL_CONNECTION_USE_KERBEROS) {
534 auth_info_required = "negotiate";
535 use_kerberos = true;
538 creds = cli_session_creds_init(cli,
539 username,
540 workgroup,
541 NULL, /* realm */
542 password,
543 use_kerberos,
544 false, /* fallback_after_kerberos */
545 false, /* use_ccache */
546 false); /* password_is_nt_hash */
547 if (creds == NULL) {
548 fprintf(stderr, "ERROR: cli_session_creds_init failed\n");
549 cli_shutdown(cli);
550 return NULL;
553 nt_status = cli_session_setup_creds(cli, creds);
554 if (!NT_STATUS_IS_OK(nt_status)) {
555 fprintf(stderr, "ERROR: Session setup failed: %s\n", nt_errstr(nt_status));
557 if (get_exit_code(cli, nt_status) == 2) {
558 *need_auth = true;
561 cli_shutdown(cli);
563 return NULL;
566 nt_status = cli_tree_connect_creds(cli, share, "?????", creds);
567 if (!NT_STATUS_IS_OK(nt_status)) {
568 fprintf(stderr, "ERROR: Tree connect failed (%s)\n",
569 nt_errstr(nt_status));
571 if (get_exit_code(cli, nt_status) == 2) {
572 *need_auth = true;
575 cli_shutdown(cli);
577 return NULL;
579 #if 0
580 /* Need to work out how to specify this on the URL. */
581 if (smb_encrypt) {
582 if (!cli_cm_force_encryption_creds(cli, creds, share)) {
583 fprintf(stderr, "ERROR: encryption setup failed\n");
584 cli_shutdown(cli);
585 return NULL;
588 #endif
590 return cli;
593 static bool kerberos_ccache_is_valid(void) {
594 krb5_context ctx;
595 const char *ccache_name = NULL;
596 krb5_ccache ccache = NULL;
597 krb5_error_code code;
599 code = krb5_init_context(&ctx);
600 if (code != 0) {
601 return false;
604 ccache_name = krb5_cc_default_name(ctx);
605 if (ccache_name == NULL) {
606 return false;
609 code = krb5_cc_resolve(ctx, ccache_name, &ccache);
610 if (code != 0) {
611 krb5_free_context(ctx);
612 return false;
613 } else {
614 krb5_principal default_princ = NULL;
616 code = krb5_cc_get_principal(ctx,
617 ccache,
618 &default_princ);
619 if (code != 0) {
620 krb5_cc_close(ctx, ccache);
621 krb5_free_context(ctx);
622 return false;
624 krb5_free_principal(ctx, default_princ);
626 krb5_cc_close(ctx, ccache);
627 krb5_free_context(ctx);
629 return true;
633 * 'smb_connect()' - Return a connection to a server.
636 static struct cli_state * /* O - SMB connection */
637 smb_connect(const char *workgroup, /* I - Workgroup */
638 const char *server, /* I - Server */
639 const int port, /* I - Port */
640 const char *share, /* I - Printer */
641 const char *username, /* I - Username */
642 const char *password, /* I - Password */
643 const char *jobusername, /* I - User who issued the print job */
644 bool *need_auth)
645 { /* O - Need authentication? */
646 struct cli_state *cli; /* New connection */
647 char *myname = NULL; /* Client name */
648 struct passwd *pwd;
651 * Get the names and addresses of the client and server...
653 myname = get_myname(talloc_tos());
654 if (!myname) {
655 return NULL;
659 * See if we have a username first. This is for backwards compatible
660 * behavior with 3.0.14a
663 if (username != NULL && username[0] != '\0') {
664 if (kerberos_ccache_is_valid()) {
665 goto kerberos_auth;
669 cli = smb_complete_connection(myname,
670 server,
671 port,
672 username,
673 password,
674 workgroup,
675 share,
677 need_auth);
678 if (cli != NULL) {
679 fputs("DEBUG: Connected with username/password...\n", stderr);
680 return (cli);
683 kerberos_auth:
685 * Try to use the user kerberos credentials (if any) to authenticate
687 cli = smb_complete_connection(myname, server, port, jobusername, "",
688 workgroup, share,
689 CLI_FULL_CONNECTION_USE_KERBEROS, need_auth);
691 if (cli) {
692 fputs("DEBUG: Connected using Kerberos...\n", stderr);
693 return (cli);
696 /* give a chance for a passwordless NTLMSSP session setup */
697 pwd = getpwuid(geteuid());
698 if (pwd == NULL) {
699 return NULL;
702 cli = smb_complete_connection(myname, server, port, pwd->pw_name, "",
703 workgroup, share, 0, need_auth);
705 if (cli) {
706 fputs("DEBUG: Connected with NTLMSSP...\n", stderr);
707 return (cli);
711 * last try. Use anonymous authentication
714 cli = smb_complete_connection(myname, server, port, "", "",
715 workgroup, share, 0, need_auth);
717 * Return the new connection...
720 return (cli);
725 * 'smb_print()' - Queue a job for printing using the SMB protocol.
728 static int /* O - 0 = success, non-0 = failure */
729 smb_print(struct cli_state * cli, /* I - SMB connection */
730 const char *print_title, /* I - Title/job name */
731 FILE * fp)
732 { /* I - File to print */
733 uint16_t fnum; /* File number */
734 int nbytes, /* Number of bytes read */
735 tbytes; /* Total bytes read */
736 char buffer[8192], /* Buffer for copy */
737 *ptr; /* Pointer into title */
738 char title[1024] = {0};
739 int len;
740 NTSTATUS nt_status;
744 * Sanitize the title...
746 len = snprintf(title, sizeof(title), "%s", print_title);
747 if (len != strlen(print_title)) {
748 return 2;
751 for (ptr = title; *ptr; ptr++) {
752 if (!isalnum((int) *ptr) && !isspace((int) *ptr)) {
753 *ptr = '_';
758 * Open the printer device...
761 nt_status = cli_open(cli, title, O_RDWR | O_CREAT | O_TRUNC, DENY_NONE,
762 &fnum);
763 if (!NT_STATUS_IS_OK(nt_status)) {
764 fprintf(stderr, "ERROR: %s opening remote spool %s\n",
765 nt_errstr(nt_status), title);
766 return get_exit_code(cli, nt_status);
770 * Copy the file to the printer...
773 if (fp != stdin)
774 rewind(fp);
776 tbytes = 0;
778 while ((nbytes = fread(buffer, 1, sizeof(buffer), fp)) > 0) {
779 NTSTATUS status;
781 status = cli_writeall(cli, fnum, 0, (uint8_t *)buffer,
782 tbytes, nbytes, NULL);
783 if (!NT_STATUS_IS_OK(status)) {
784 int ret = get_exit_code(cli, status);
785 fprintf(stderr, "ERROR: Error writing spool: %s\n",
786 nt_errstr(status));
787 fprintf(stderr, "DEBUG: Returning status %d...\n",
788 ret);
789 cli_close(cli, fnum);
791 return (ret);
793 tbytes += nbytes;
796 nt_status = cli_close(cli, fnum);
797 if (!NT_STATUS_IS_OK(nt_status)) {
798 fprintf(stderr, "ERROR: %s closing remote spool %s\n",
799 nt_errstr(nt_status), title);
800 return get_exit_code(cli, nt_status);
801 } else {
802 return (0);
806 static char *
807 uri_unescape_alloc(const char *uritok)
809 char *ret;
811 ret = (char *) SMB_STRDUP(uritok);
812 if (!ret) {
813 return NULL;
816 rfc1738_unescape(ret);
817 return ret;