r557: another patch from Stephan Kulow <coolo@suse.de> -- check cli * before derefere...
[Samba.git] / source / libsmb / libsmbclient.c
blob2ef054473ba84a082e2eeb641353645836c6d13d
1 /*
2 Unix SMB/Netbios implementation.
3 SMB client library implementation
4 Copyright (C) Andrew Tridgell 1998
5 Copyright (C) Richard Sharpe 2000, 2002
6 Copyright (C) John Terpstra 2000
7 Copyright (C) Tom Jansen (Ninja ISD) 2002
8 Copyright (C) Derrell Lipman 2003
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 #include "includes.h"
27 #include "../include/libsmb_internal.h"
30 * Internal flags for extended attributes
33 /* internal mode values */
34 #define SMBC_XATTR_MODE_ADD 1
35 #define SMBC_XATTR_MODE_REMOVE 2
36 #define SMBC_XATTR_MODE_REMOVE_ALL 3
37 #define SMBC_XATTR_MODE_SET 4
38 #define SMBC_XATTR_MODE_CHOWN 5
39 #define SMBC_XATTR_MODE_CHGRP 6
41 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
43 /*We should test for this in configure ... */
44 #ifndef ENOTSUP
45 #define ENOTSUP EOPNOTSUPP
46 #endif
49 * Functions exported by libsmb_cache.c that we need here
51 int smbc_default_cache_functions(SMBCCTX *context);
53 /*
54 * check if an element is part of the list.
55 * FIXME: Does not belong here !
56 * Can anyone put this in a macro in dlinklist.h ?
57 * -- Tom
59 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
60 if (!p || !list) return False;
61 do {
62 if (p == list) return True;
63 list = list->next;
64 } while (list);
65 return False;
68 extern BOOL in_client;
71 * Is the logging working / configfile read ?
73 static int smbc_initialized = 0;
75 static int
76 hex2int( unsigned int _char )
78 if ( _char >= 'A' && _char <='F')
79 return _char - 'A' + 10;
80 if ( _char >= 'a' && _char <='f')
81 return _char - 'a' + 10;
82 if ( _char >= '0' && _char <='9')
83 return _char - '0';
84 return -1;
87 static void
88 decode_urlpart(char *segment, size_t sizeof_segment)
90 int old_length = strlen(segment);
91 int new_length = 0;
92 int new_length2 = 0;
93 int i = 0;
94 pstring new_segment;
95 char *new_usegment = 0;
97 if ( !old_length ) {
98 return;
101 /* make a copy of the old one */
102 new_usegment = (char*)malloc( old_length * 3 + 1 );
104 while( i < old_length ) {
105 int bReencode = False;
106 unsigned char character = segment[ i++ ];
107 if ((character <= ' ') || (character > 127))
108 bReencode = True;
110 new_usegment [ new_length2++ ] = character;
111 if (character == '%' ) {
112 int a = i+1 < old_length ? hex2int( segment[i] ) : -1;
113 int b = i+1 < old_length ? hex2int( segment[i+1] ) : -1;
114 if ((a == -1) || (b == -1)) { /* Only replace if sequence is valid */
115 /* Contains stray %, make sure to re-encode! */
116 bReencode = True;
117 } else {
118 /* Valid %xx sequence */
119 character = a * 16 + b; /* Replace with value of %dd */
120 if (!character)
121 break; /* Stop at %00 */
123 new_usegment [ new_length2++ ] = (unsigned char) segment[i++];
124 new_usegment [ new_length2++ ] = (unsigned char) segment[i++];
127 if (bReencode) {
128 unsigned int c = character / 16;
129 new_length2--;
130 new_usegment [ new_length2++ ] = '%';
132 c += (c > 9) ? ('A' - 10) : '0';
133 new_usegment[ new_length2++ ] = c;
135 c = character % 16;
136 c += (c > 9) ? ('A' - 10) : '0';
137 new_usegment[ new_length2++ ] = c;
140 new_segment [ new_length++ ] = character;
142 new_segment [ new_length ] = 0;
144 free(new_usegment);
146 /* realloc it with unix charset */
147 pull_utf8_allocate(&new_usegment, new_segment);
149 /* this assumes (very safely) that removing %aa sequences
150 only shortens the string */
151 strncpy(segment, new_usegment, sizeof_segment);
153 free(new_usegment);
157 * Function to parse a path and turn it into components
159 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
160 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
161 * general format ("smb:" only; we do not look for "cifs:"), and expand on
162 * what he calls "context", herein called "options" to avoid conflict with the
163 * SMBCCTX context used throughout this library. We add the "mb" keyword
164 * which applies as follows:
167 * We accept:
168 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
170 * Meaning of URLs:
172 * smb:// show all workgroups known by the first master browser found
173 * smb://?mb=.any same as smb:// (i.e. without any options)
175 * smb://?mb=.all show all workgroups known by every master browser found.
176 * Why might you want this? In an "appliance" application
177 * where the workgroup/domain being used on the local network
178 * is not known ahead of time, but where one wanted to
179 * provide network services via samba, a unique workgroup
180 * could be used. However, when the appliance is first
181 * started, the local samba instance's master browser has not
182 * synchronized with the other master browser(s) on the
183 * network (and might not synchronize for 12 minutes) and
184 * therefore is not aware of the workgroup/ domain names
185 * available on the network. This option may be used to
186 * overcome the problem of a libsmbclient application
187 * arbitrarily selecting the local (still ignorant) master
188 * browser to obtain its list of workgroups/domains and
189 * getting back a practically emmpty list. By requesting
190 * the list of workgroups/domains from each found master
191 * browser on the local network, a complete list of
192 * workgroups/domains can be built.
194 * smb://?mb=name NOT YET IMPLEMENTED -- show all workgroups known by the
195 * master browser whose name is "name"
197 * smb://name/ if name<1D> or name<1B> exists, list servers in
198 * workgroup, else, if name<20> exists, list all shares
199 * for server ...
201 * If "options" are provided, this function returns the entire option list as
202 * a string, for later parsing by the caller.
205 static const char *smbc_prefix = "smb:";
207 static int
208 smbc_parse_path(SMBCCTX *context,
209 const char *fname,
210 char *server, int server_len,
211 char *share, int share_len,
212 char *path, int path_len,
213 char *user, int user_len,
214 char *password, int password_len,
215 char *options, int options_len)
217 static pstring s;
218 pstring userinfo;
219 const char *p;
220 char *q, *r;
221 int len;
223 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
224 if (options != NULL && options_len > 0) {
225 options[0] = (char)0;
227 pstrcpy(s, fname);
229 /* see if it has the right prefix */
230 len = strlen(smbc_prefix);
231 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
232 return -1; /* What about no smb: ? */
235 p = s + len;
237 /* Watch the test below, we are testing to see if we should exit */
239 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
241 DEBUG(1, ("Invalid path (does not begin with smb://"));
242 return -1;
246 p += 2; /* Skip the double slash */
248 /* See if any options were specified */
249 if ( (q = strrchr(p, '?')) != NULL ) {
250 /* There are options. Null terminate here and point to them */
251 *q++ = '\0';
253 DEBUG(4, ("Found options '%s'", q));
255 /* Copy the options */
256 if (options != NULL && options_len > 0) {
257 safe_strcpy(options, q, options_len - 1);
261 if (*p == (char)0)
262 goto decoding;
264 if (*p == '/') {
266 strncpy(server, context->workgroup,
267 (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
268 return 0;
273 * ok, its for us. Now parse out the server, share etc.
275 * However, we want to parse out [[domain;]user[:password]@] if it
276 * exists ...
279 /* check that '@' occurs before '/', if '/' exists at all */
280 q = strchr_m(p, '@');
281 r = strchr_m(p, '/');
282 if (q && (!r || q < r)) {
283 pstring username, passwd, domain;
284 const char *u = userinfo;
286 next_token(&p, userinfo, "@", sizeof(fstring));
288 username[0] = passwd[0] = domain[0] = 0;
290 if (strchr_m(u, ';')) {
292 next_token(&u, domain, ";", sizeof(fstring));
296 if (strchr_m(u, ':')) {
298 next_token(&u, username, ":", sizeof(fstring));
300 pstrcpy(passwd, u);
303 else {
305 pstrcpy(username, u);
309 if (username[0])
310 strncpy(user, username, user_len); /* FIXME, domain */
312 if (passwd[0])
313 strncpy(password, passwd, password_len);
317 if (!next_token(&p, server, "/", sizeof(fstring))) {
319 return -1;
323 if (*p == (char)0) goto decoding; /* That's it ... */
325 if (!next_token(&p, share, "/", sizeof(fstring))) {
327 return -1;
331 safe_strcpy(path, p, path_len - 1);
333 all_string_sub(path, "/", "\\", 0);
335 decoding:
336 decode_urlpart(path, path_len);
337 decode_urlpart(server, server_len);
338 decode_urlpart(share, share_len);
339 decode_urlpart(user, user_len);
340 decode_urlpart(password, password_len);
342 return 0;
346 * Verify that the options specified in a URL are valid
348 static int smbc_check_options(char *server, char *share, char *path, char *options)
350 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' path='%s' options='%s'\n", server, share, path, options));
352 /* No options at all is always ok */
353 if (! *options) return 0;
356 * For right now, we only support a very few options possibilities.
357 * No options are supported if server, share, or path are not empty.
358 * If all are empty, then we support the following two choices right
359 * now:
361 * mb=.any
362 * mb=.all
364 if ((*server || *share || *path) && *options) {
365 /* Invalid: options provided with server, share, or path */
366 DEBUG(1, ("Found unsupported options (%s) with non-empty server, share, or path\n", options));
367 return -1;
370 if (strcmp(options, "mb=.any") != 0 &&
371 strcmp(options, "mb=.all") != 0) {
372 DEBUG(1, ("Found unsupported options (%s)\n", options));
373 return -1;
376 return 0;
380 * Convert an SMB error into a UNIX error ...
382 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
384 int ret = cli_errno(c);
386 if (cli_is_dos_error(c)) {
387 uint8 eclass;
388 uint32 ecode;
390 cli_dos_error(c, &eclass, &ecode);
392 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
393 (int)eclass, (int)ecode, (int)ecode, ret));
394 } else {
395 NTSTATUS status;
397 status = cli_nt_error(c);
399 DEBUG(3,("smbc errno %s -> %d\n",
400 nt_errstr(status), ret));
403 return ret;
407 * Check a server_fd.
408 * returns 0 if the server is in shape. Returns 1 on error
410 * Also useable outside libsmbclient to enable external cache
411 * to do some checks too.
413 int smbc_check_server(SMBCCTX * context, SMBCSRV * server)
415 if ( send_keepalive(server->cli.fd) == False )
416 return 1;
418 /* connection is ok */
419 return 0;
423 * Remove a server from the cached server list it's unused.
424 * On success, 0 is returned. 1 is returned if the server could not be removed.
426 * Also useable outside libsmbclient
428 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
430 SMBCFILE * file;
432 /* are we being fooled ? */
433 if (!context || !context->internal ||
434 !context->internal->_initialized || !srv) return 1;
437 /* Check all open files/directories for a relation with this server */
438 for (file = context->internal->_files; file; file=file->next) {
439 if (file->srv == srv) {
440 /* Still used */
441 DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n",
442 srv, file));
443 return 1;
447 DLIST_REMOVE(context->internal->_servers, srv);
449 cli_shutdown(&srv->cli);
451 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
453 context->callbacks.remove_cached_srv_fn(context, srv);
455 SAFE_FREE(srv);
457 return 0;
460 SMBCSRV *find_server(SMBCCTX *context,
461 const char *server,
462 const char *share,
463 fstring workgroup,
464 fstring username,
465 fstring password)
467 SMBCSRV *srv;
468 int auth_called = 0;
470 check_server_cache:
472 srv = context->callbacks.get_cached_srv_fn(context, server, share,
473 workgroup, username);
475 if (!auth_called && !srv && (!username[0] || !password[0])) {
476 context->callbacks.auth_fn(server, share,
477 workgroup, sizeof(fstring),
478 username, sizeof(fstring),
479 password, sizeof(fstring));
481 * However, smbc_auth_fn may have picked up info relating to
482 * an existing connection, so try for an existing connection
483 * again ...
485 auth_called = 1;
486 goto check_server_cache;
490 if (srv) {
491 if (context->callbacks.check_server_fn(context, srv)) {
493 * This server is no good anymore
494 * Try to remove it and check for more possible
495 * servers in the cache
497 if (context->callbacks.remove_unused_server_fn(context,
498 srv)) {
500 * We could not remove the server completely,
501 * remove it from the cache so we will not get
502 * it again. It will be removed when the last
503 * file/dir is closed.
505 context->callbacks.remove_cached_srv_fn(context,
506 srv);
510 * Maybe there are more cached connections to this
511 * server
513 goto check_server_cache;
515 return srv;
518 return NULL;
522 * Connect to a server, possibly on an existing connection
524 * Here, what we want to do is: If the server and username
525 * match an existing connection, reuse that, otherwise, establish a
526 * new connection.
528 * If we have to create a new connection, call the auth_fn to get the
529 * info we need, unless the username and password were passed in.
532 SMBCSRV *smbc_server(SMBCCTX *context,
533 const char *server, const char *share,
534 fstring workgroup, fstring username,
535 fstring password)
537 SMBCSRV *srv=NULL;
538 struct cli_state c;
539 struct nmb_name called, calling;
540 const char *server_n = server;
541 pstring ipenv;
542 struct in_addr ip;
543 int tried_reverse = 0;
545 zero_ip(&ip);
546 ZERO_STRUCT(c);
548 if (server[0] == 0) {
549 errno = EPERM;
550 return NULL;
553 srv = find_server(context, server, share,
554 workgroup, username, password);
555 if (srv)
556 return srv;
558 make_nmb_name(&calling, context->netbios_name, 0x0);
559 make_nmb_name(&called , server, 0x20);
561 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
563 #if 0 /* djl: obsolete code? neither group nor p is used beyond here */
564 if ((p=strchr_m(server_n,'#')) &&
565 (strcmp(p+1,"1D")==0 || strcmp(p+1,"01")==0)) {
567 fstrcpy(group, server_n);
568 p = strchr_m(group,'#');
569 *p = 0;
572 #endif
574 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
576 again:
577 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
579 zero_ip(&ip);
581 /* have to open a new connection */
582 if (!cli_initialise(&c)) {
583 errno = ENOMEM;
584 return NULL;
587 c.timeout = context->timeout;
589 /* Force use of port 139 for first try, so browse lists can work */
590 c.port = 139;
592 if (!cli_connect(&c, server_n, &ip)) {
594 * Port 139 connection failed. Try port 445 to handle
595 * connections to newer (e.g. XP) hosts with NetBIOS disabled.
597 c.port = 445;
598 if (!cli_connect(&c, server_n, &ip)) {
599 errno = ENETUNREACH;
600 return NULL;
604 if (!cli_session_request(&c, &calling, &called)) {
605 cli_shutdown(&c);
606 if (strcmp(called.name, "*SMBSERVER")) {
607 make_nmb_name(&called , "*SMBSERVER", 0x20);
608 goto again;
610 else { /* Try one more time, but ensure we don't loop */
612 /* Only try this if server is an IP address ... */
614 if (is_ipaddress(server) && !tried_reverse) {
615 fstring remote_name;
616 struct in_addr rem_ip;
618 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
619 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
620 errno = ENOENT;
621 return NULL;
624 tried_reverse++; /* Yuck */
626 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
627 make_nmb_name(&called, remote_name, 0x20);
628 goto again;
634 errno = ENOENT;
635 return NULL;
638 DEBUG(4,(" session request ok\n"));
640 if (!cli_negprot(&c)) {
641 cli_shutdown(&c);
642 errno = ENOENT;
643 return NULL;
646 if (!cli_session_setup(&c, username,
647 password, strlen(password),
648 password, strlen(password),
649 workgroup) &&
650 /* try an anonymous login if it failed */
651 !cli_session_setup(&c, "", "", 1,"", 0, workgroup)) {
652 cli_shutdown(&c);
653 errno = EPERM;
654 return NULL;
657 DEBUG(4,(" session setup ok\n"));
659 if (!cli_send_tconX(&c, share, "?????",
660 password, strlen(password)+1)) {
661 errno = smbc_errno(context, &c);
662 cli_shutdown(&c);
663 return NULL;
666 DEBUG(4,(" tconx ok\n"));
669 * Ok, we have got a nice connection
670 * Let's find a free server_fd
673 srv = (SMBCSRV *)malloc(sizeof(*srv));
674 if (!srv) {
675 errno = ENOMEM;
676 goto failed;
679 ZERO_STRUCTP(srv);
680 srv->cli = c;
681 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
683 /* now add it to the cache (internal or external) */
684 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
685 DEBUG(3, (" Failed to add server to cache\n"));
686 goto failed;
690 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
691 server, share, srv));
693 DLIST_ADD(context->internal->_servers, srv);
694 return srv;
696 failed:
697 cli_shutdown(&c);
698 if (!srv) return NULL;
700 SAFE_FREE(srv);
701 return NULL;
705 * Connect to a server for getting/setting attributes, possibly on an existing
706 * connection. This works similarly to smbc_server().
708 SMBCSRV *smbc_attr_server(SMBCCTX *context,
709 const char *server, const char *share,
710 fstring workgroup,
711 fstring username, fstring password,
712 POLICY_HND *pol)
714 struct in_addr ip;
715 struct cli_state *ipc_cli;
716 NTSTATUS nt_status;
717 SMBCSRV *ipc_srv=NULL;
720 * See if we've already created this special connection. Reference
721 * our "special" share name 'IPC$$'.
723 ipc_srv = find_server(context, server, "IPC$$",
724 workgroup, username, password);
725 if (!ipc_srv) {
727 /* We didn't find a cached connection. Get the password */
728 if (*password == '\0') {
729 /* ... then retrieve it now. */
730 context->callbacks.auth_fn(server, share,
731 workgroup, sizeof(fstring),
732 username, sizeof(fstring),
733 password, sizeof(fstring));
736 zero_ip(&ip);
737 nt_status = cli_full_connection(&ipc_cli,
738 global_myname(), server,
739 &ip, 0, "IPC$", "?????",
740 username, workgroup,
741 password, 0,
742 Undefined, NULL);
743 if (! NT_STATUS_IS_OK(nt_status)) {
744 DEBUG(1,("cli_full_connection failed! (%s)\n",
745 nt_errstr(nt_status)));
746 errno = ENOTSUP;
747 return NULL;
750 if (!cli_nt_session_open(ipc_cli, PI_LSARPC)) {
751 DEBUG(1, ("cli_nt_session_open fail!\n"));
752 errno = ENOTSUP;
753 cli_shutdown(ipc_cli);
754 return NULL;
757 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
758 but NT sends 0x2000000 so we might as well do it too. */
760 nt_status = cli_lsa_open_policy(ipc_cli,
761 ipc_cli->mem_ctx,
762 True,
763 GENERIC_EXECUTE_ACCESS,
764 pol);
766 if (!NT_STATUS_IS_OK(nt_status)) {
767 errno = smbc_errno(context, ipc_cli);
768 cli_shutdown(ipc_cli);
769 return NULL;
772 ipc_srv = (SMBCSRV *)malloc(sizeof(*ipc_srv));
773 if (!ipc_srv) {
774 errno = ENOMEM;
775 cli_shutdown(ipc_cli);
776 return NULL;
779 ZERO_STRUCTP(ipc_srv);
780 ipc_srv->cli = *ipc_cli;
782 free(ipc_cli);
784 /* now add it to the cache (internal or external) */
786 errno = 0; /* let cache function set errno if it likes */
787 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
788 server,
789 "IPC$$",
790 workgroup,
791 username)) {
792 DEBUG(3, (" Failed to add server to cache\n"));
793 if (errno == 0) {
794 errno = ENOMEM;
796 cli_shutdown(&ipc_srv->cli);
797 free(ipc_srv);
798 return NULL;
801 DLIST_ADD(context->internal->_servers, ipc_srv);
804 return ipc_srv;
808 * Routine to open() a file ...
811 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
813 fstring server, share, user, password, workgroup;
814 pstring path;
815 SMBCSRV *srv = NULL;
816 SMBCFILE *file = NULL;
817 int fd;
819 if (!context || !context->internal ||
820 !context->internal->_initialized) {
822 errno = EINVAL; /* Best I can think of ... */
823 return NULL;
827 if (!fname) {
829 errno = EINVAL;
830 return NULL;
834 if (smbc_parse_path(context, fname,
835 server, sizeof(server),
836 share, sizeof(share),
837 path, sizeof(path),
838 user, sizeof(user),
839 password, sizeof(password),
840 NULL, 0)) {
841 errno = EINVAL;
842 return NULL;
845 if (user[0] == (char)0) fstrcpy(user, context->user);
847 fstrcpy(workgroup, context->workgroup);
849 srv = smbc_server(context, server, share, workgroup, user, password);
851 if (!srv) {
853 if (errno == EPERM) errno = EACCES;
854 return NULL; /* smbc_server sets errno */
858 /* Hmmm, the test for a directory is suspect here ... FIXME */
860 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
862 fd = -1;
865 else {
867 file = malloc(sizeof(SMBCFILE));
869 if (!file) {
871 errno = ENOMEM;
872 return NULL;
876 ZERO_STRUCTP(file);
878 if ((fd = cli_open(&srv->cli, path, flags, DENY_NONE)) < 0) {
880 /* Handle the error ... */
882 SAFE_FREE(file);
883 errno = smbc_errno(context, &srv->cli);
884 return NULL;
888 /* Fill in file struct */
890 file->cli_fd = fd;
891 file->fname = strdup(fname);
892 file->srv = srv;
893 file->offset = 0;
894 file->file = True;
896 DLIST_ADD(context->internal->_files, file);
897 return file;
901 /* Check if opendir needed ... */
903 if (fd == -1) {
904 int eno = 0;
906 eno = smbc_errno(context, &srv->cli);
907 file = context->opendir(context, fname);
908 if (!file) errno = eno;
909 return file;
913 errno = EINVAL; /* FIXME, correct errno ? */
914 return NULL;
919 * Routine to create a file
922 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
924 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
927 if (!context || !context->internal ||
928 !context->internal->_initialized) {
930 errno = EINVAL;
931 return NULL;
935 return smbc_open_ctx(context, path, creat_bits, mode);
939 * Routine to read() a file ...
942 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
944 int ret;
946 if (!context || !context->internal ||
947 !context->internal->_initialized) {
949 errno = EINVAL;
950 return -1;
954 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
956 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
958 errno = EBADF;
959 return -1;
963 /* Check that the buffer exists ... */
965 if (buf == NULL) {
967 errno = EINVAL;
968 return -1;
972 ret = cli_read(&file->srv->cli, file->cli_fd, buf, file->offset, count);
974 if (ret < 0) {
976 errno = smbc_errno(context, &file->srv->cli);
977 return -1;
981 file->offset += ret;
983 DEBUG(4, (" --> %d\n", ret));
985 return ret; /* Success, ret bytes of data ... */
990 * Routine to write() a file ...
993 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
995 int ret;
997 if (!context || !context->internal ||
998 !context->internal->_initialized) {
1000 errno = EINVAL;
1001 return -1;
1005 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1007 errno = EBADF;
1008 return -1;
1012 /* Check that the buffer exists ... */
1014 if (buf == NULL) {
1016 errno = EINVAL;
1017 return -1;
1021 ret = cli_write(&file->srv->cli, file->cli_fd, 0, buf, file->offset, count);
1023 if (ret <= 0) {
1025 errno = smbc_errno(context, &file->srv->cli);
1026 return -1;
1030 file->offset += ret;
1032 return ret; /* Success, 0 bytes of data ... */
1036 * Routine to close() a file ...
1039 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1041 SMBCSRV *srv;
1043 if (!context || !context->internal ||
1044 !context->internal->_initialized) {
1046 errno = EINVAL;
1047 return -1;
1051 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1053 errno = EBADF;
1054 return -1;
1058 /* IS a dir ... */
1059 if (!file->file) {
1061 return context->closedir(context, file);
1065 if (!cli_close(&file->srv->cli, file->cli_fd)) {
1067 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1068 file->fname));
1069 /* Deallocate slot and remove the server
1070 * from the server cache if unused */
1071 errno = smbc_errno(context, &file->srv->cli);
1072 srv = file->srv;
1073 DLIST_REMOVE(context->internal->_files, file);
1074 SAFE_FREE(file->fname);
1075 SAFE_FREE(file);
1076 context->callbacks.remove_unused_server_fn(context, srv);
1078 return -1;
1082 DLIST_REMOVE(context->internal->_files, file);
1083 SAFE_FREE(file->fname);
1084 SAFE_FREE(file);
1086 return 0;
1090 * Get info from an SMB server on a file. Use a qpathinfo call first
1091 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1093 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1094 uint16 *mode, size_t *size,
1095 time_t *c_time, time_t *a_time, time_t *m_time,
1096 SMB_INO_T *ino)
1099 if (!context || !context->internal ||
1100 !context->internal->_initialized) {
1102 errno = EINVAL;
1103 return -1;
1107 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1109 if (!srv->no_pathinfo2 &&
1110 cli_qpathinfo2(&srv->cli, path, c_time, a_time, m_time, NULL,
1111 size, mode, ino)) return True;
1113 /* if this is NT then don't bother with the getatr */
1114 if (srv->cli.capabilities & CAP_NT_SMBS) {
1115 errno = EPERM;
1116 return False;
1119 if (cli_getatr(&srv->cli, path, mode, size, m_time)) {
1120 a_time = c_time = m_time;
1121 srv->no_pathinfo2 = True;
1122 return True;
1125 errno = EPERM;
1126 return False;
1131 * Routine to unlink() a file
1134 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1136 fstring server, share, user, password, workgroup;
1137 pstring path;
1138 SMBCSRV *srv = NULL;
1140 if (!context || !context->internal ||
1141 !context->internal->_initialized) {
1143 errno = EINVAL; /* Best I can think of ... */
1144 return -1;
1148 if (!fname) {
1150 errno = EINVAL;
1151 return -1;
1155 if (smbc_parse_path(context, fname,
1156 server, sizeof(server),
1157 share, sizeof(share),
1158 path, sizeof(path),
1159 user, sizeof(user),
1160 password, sizeof(password),
1161 NULL, 0)) {
1162 errno = EINVAL;
1163 return -1;
1166 if (user[0] == (char)0) fstrcpy(user, context->user);
1168 fstrcpy(workgroup, context->workgroup);
1170 srv = smbc_server(context, server, share, workgroup, user, password);
1172 if (!srv) {
1174 return -1; /* smbc_server sets errno */
1178 /* if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
1180 int job = smbc_stat_printjob(srv, path, NULL, NULL);
1181 if (job == -1) {
1183 return -1;
1186 if ((err = cli_printjob_del(&srv->cli, job)) != 0) {
1189 return -1;
1192 } else */
1194 if (!cli_unlink(&srv->cli, path)) {
1196 errno = smbc_errno(context, &srv->cli);
1198 if (errno == EACCES) { /* Check if the file is a directory */
1200 int saverr = errno;
1201 size_t size = 0;
1202 uint16 mode = 0;
1203 time_t m_time = 0, a_time = 0, c_time = 0;
1204 SMB_INO_T ino = 0;
1206 if (!smbc_getatr(context, srv, path, &mode, &size,
1207 &c_time, &a_time, &m_time, &ino)) {
1209 /* Hmmm, bad error ... What? */
1211 errno = smbc_errno(context, &srv->cli);
1212 return -1;
1215 else {
1217 if (IS_DOS_DIR(mode))
1218 errno = EISDIR;
1219 else
1220 errno = saverr; /* Restore this */
1225 return -1;
1229 return 0; /* Success ... */
1234 * Routine to rename() a file
1237 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1238 SMBCCTX *ncontext, const char *nname)
1240 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1241 pstring path1, path2;
1242 SMBCSRV *srv = NULL;
1244 if (!ocontext || !ncontext ||
1245 !ocontext->internal || !ncontext->internal ||
1246 !ocontext->internal->_initialized ||
1247 !ncontext->internal->_initialized) {
1249 errno = EINVAL; /* Best I can think of ... */
1250 return -1;
1254 if (!oname || !nname) {
1256 errno = EINVAL;
1257 return -1;
1261 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1263 smbc_parse_path(ocontext, oname,
1264 server1, sizeof(server1),
1265 share1, sizeof(share1),
1266 path1, sizeof(path1),
1267 user1, sizeof(user1),
1268 password1, sizeof(password1),
1269 NULL, 0);
1271 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1273 smbc_parse_path(ncontext, nname,
1274 server2, sizeof(server2),
1275 share2, sizeof(share2),
1276 path2, sizeof(path2),
1277 user2, sizeof(user2),
1278 password2, sizeof(password2),
1279 NULL, 0);
1281 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1283 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1284 strcmp(user1, user2)) {
1286 /* Can't rename across file systems, or users?? */
1288 errno = EXDEV;
1289 return -1;
1293 fstrcpy(workgroup, ocontext->workgroup);
1294 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1295 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1296 if (!srv) {
1298 return -1;
1302 if (!cli_rename(&srv->cli, path1, path2)) {
1303 int eno = smbc_errno(ocontext, &srv->cli);
1305 if (eno != EEXIST ||
1306 !cli_unlink(&srv->cli, path2) ||
1307 !cli_rename(&srv->cli, path1, path2)) {
1309 errno = eno;
1310 return -1;
1315 return 0; /* Success */
1320 * A routine to lseek() a file
1323 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1325 size_t size;
1327 if (!context || !context->internal ||
1328 !context->internal->_initialized) {
1330 errno = EINVAL;
1331 return -1;
1335 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1337 errno = EBADF;
1338 return -1;
1342 if (!file->file) {
1344 errno = EINVAL;
1345 return -1; /* Can't lseek a dir ... */
1349 switch (whence) {
1350 case SEEK_SET:
1351 file->offset = offset;
1352 break;
1354 case SEEK_CUR:
1355 file->offset += offset;
1356 break;
1358 case SEEK_END:
1359 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
1360 NULL, NULL, NULL))
1362 SMB_BIG_UINT b_size = size;
1363 if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
1364 NULL))
1366 errno = EINVAL;
1367 return -1;
1368 } else
1369 size = b_size;
1371 file->offset = size + offset;
1372 break;
1374 default:
1375 errno = EINVAL;
1376 break;
1380 return file->offset;
1385 * Generate an inode number from file name for those things that need it
1388 static
1389 ino_t smbc_inode(SMBCCTX *context, const char *name)
1392 if (!context || !context->internal ||
1393 !context->internal->_initialized) {
1395 errno = EINVAL;
1396 return -1;
1400 if (!*name) return 2; /* FIXME, why 2 ??? */
1401 return (ino_t)str_checksum(name);
1406 * Routine to put basic stat info into a stat structure ... Used by stat and
1407 * fstat below.
1410 static
1411 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname, size_t size, int mode)
1414 st->st_mode = 0;
1416 if (IS_DOS_DIR(mode)) {
1417 st->st_mode = SMBC_DIR_MODE;
1418 } else {
1419 st->st_mode = SMBC_FILE_MODE;
1422 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1423 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1424 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1425 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1427 st->st_size = size;
1428 #ifdef HAVE_STAT_ST_BLKSIZE
1429 st->st_blksize = 512;
1430 #endif
1431 #ifdef HAVE_STAT_ST_BLOCKS
1432 st->st_blocks = (size+511)/512;
1433 #endif
1434 st->st_uid = getuid();
1435 st->st_gid = getgid();
1437 if (IS_DOS_DIR(mode)) {
1438 st->st_nlink = 2;
1439 } else {
1440 st->st_nlink = 1;
1443 if (st->st_ino == 0) {
1444 st->st_ino = smbc_inode(context, fname);
1447 return True; /* FIXME: Is this needed ? */
1452 * Routine to stat a file given a name
1455 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1457 SMBCSRV *srv;
1458 fstring server, share, user, password, workgroup;
1459 pstring path;
1460 time_t m_time = 0, a_time = 0, c_time = 0;
1461 size_t size = 0;
1462 uint16 mode = 0;
1463 SMB_INO_T ino = 0;
1465 if (!context || !context->internal ||
1466 !context->internal->_initialized) {
1468 errno = EINVAL; /* Best I can think of ... */
1469 return -1;
1473 if (!fname) {
1475 errno = EINVAL;
1476 return -1;
1480 DEBUG(4, ("smbc_stat(%s)\n", fname));
1482 if (smbc_parse_path(context, fname,
1483 server, sizeof(server),
1484 share, sizeof(share),
1485 path, sizeof(path),
1486 user, sizeof(user),
1487 password, sizeof(password),
1488 NULL, 0)) {
1489 errno = EINVAL;
1490 return -1;
1493 if (user[0] == (char)0) fstrcpy(user, context->user);
1495 fstrcpy(workgroup, context->workgroup);
1497 srv = smbc_server(context, server, share, workgroup, user, password);
1499 if (!srv) {
1500 return -1; /* errno set by smbc_server */
1503 if (!smbc_getatr(context, srv, path, &mode, &size,
1504 &c_time, &a_time, &m_time, &ino)) {
1506 errno = smbc_errno(context, &srv->cli);
1507 return -1;
1511 st->st_ino = ino;
1513 smbc_setup_stat(context, st, path, size, mode);
1515 st->st_atime = a_time;
1516 st->st_ctime = c_time;
1517 st->st_mtime = m_time;
1518 st->st_dev = srv->dev;
1520 return 0;
1525 * Routine to stat a file given an fd
1528 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1530 time_t c_time, a_time, m_time;
1531 size_t size;
1532 uint16 mode;
1533 SMB_INO_T ino = 0;
1535 if (!context || !context->internal ||
1536 !context->internal->_initialized) {
1538 errno = EINVAL;
1539 return -1;
1543 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1545 errno = EBADF;
1546 return -1;
1550 if (!file->file) {
1552 return context->fstatdir(context, file, st);
1556 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
1557 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
1558 SMB_BIG_UINT b_size = size;
1559 if (!cli_getattrE(&file->srv->cli, file->cli_fd,
1560 &mode, &b_size, &c_time, &a_time, &m_time)) {
1562 errno = EINVAL;
1563 return -1;
1564 } else
1565 size = b_size;
1569 st->st_ino = ino;
1571 smbc_setup_stat(context, st, file->fname, size, mode);
1573 st->st_atime = a_time;
1574 st->st_ctime = c_time;
1575 st->st_mtime = m_time;
1576 st->st_dev = file->srv->dev;
1578 return 0;
1583 * Routine to open a directory
1584 * We accept the URL syntax explained in smbc_parse_path(), above.
1587 static void smbc_remove_dir(SMBCFILE *dir)
1589 struct smbc_dir_list *d,*f;
1591 d = dir->dir_list;
1592 while (d) {
1594 f = d; d = d->next;
1596 SAFE_FREE(f->dirent);
1597 SAFE_FREE(f);
1601 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
1605 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
1607 struct smbc_dirent *dirent;
1608 int size;
1609 char *u_name = NULL, *u_comment = NULL;
1610 size_t u_name_len = 0, u_comment_len = 0;
1612 if (name)
1613 u_name_len = push_utf8_allocate(&u_name, name);
1614 if (comment)
1615 u_comment_len = push_utf8_allocate(&u_comment, comment);
1618 * Allocate space for the dirent, which must be increased by the
1619 * size of the name and the comment and 1 for the null on the comment.
1620 * The null on the name is already accounted for.
1623 size = sizeof(struct smbc_dirent) + u_name_len + u_comment_len + 1;
1625 dirent = malloc(size);
1627 if (!dirent) {
1629 dir->dir_error = ENOMEM;
1630 return -1;
1634 ZERO_STRUCTP(dirent);
1636 if (dir->dir_list == NULL) {
1638 dir->dir_list = malloc(sizeof(struct smbc_dir_list));
1639 if (!dir->dir_list) {
1641 SAFE_FREE(dirent);
1642 dir->dir_error = ENOMEM;
1643 return -1;
1646 ZERO_STRUCTP(dir->dir_list);
1648 dir->dir_end = dir->dir_next = dir->dir_list;
1650 else {
1652 dir->dir_end->next = malloc(sizeof(struct smbc_dir_list));
1654 if (!dir->dir_end->next) {
1656 SAFE_FREE(dirent);
1657 dir->dir_error = ENOMEM;
1658 return -1;
1661 ZERO_STRUCTP(dir->dir_end->next);
1663 dir->dir_end = dir->dir_end->next;
1666 dir->dir_end->next = NULL;
1667 dir->dir_end->dirent = dirent;
1669 dirent->smbc_type = type;
1670 dirent->namelen = u_name_len;
1671 dirent->commentlen = u_comment_len;
1672 dirent->dirlen = size;
1674 strncpy(dirent->name, (u_name?u_name:""), dirent->namelen + 1);
1676 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
1677 strncpy(dirent->comment, (u_comment?u_comment:""), dirent->commentlen + 1);
1679 SAFE_FREE(u_comment);
1680 SAFE_FREE(u_name);
1682 return 0;
1686 static void
1687 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
1689 SMBCFILE *dir = (SMBCFILE *)state;
1690 struct smbc_dir_list *dir_list;
1691 struct smbc_dirent *dirent;
1692 int dirent_type;
1693 int remove = 0;
1695 dirent_type = dir->dir_type;
1697 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1699 /* An error occurred, what do we do? */
1700 /* FIXME: Add some code here */
1703 /* Point to the one just added */
1704 dirent = dir->dir_end->dirent;
1706 /* See if this was a duplicate */
1707 for (dir_list = dir->dir_list;
1708 dir_list != dir->dir_end;
1709 dir_list = dir_list->next) {
1710 if (! remove &&
1711 strcmp(dir_list->dirent->name, dirent->name) == 0) {
1712 /* Duplicate. End end of list need to be removed. */
1713 remove = 1;
1716 if (remove && dir_list->next == dir->dir_end) {
1717 /* Found the end of the list. Remove it. */
1718 dir->dir_end = dir_list;
1719 free(dir_list->next);
1720 dir_list->next = NULL;
1721 break;
1726 static void
1727 list_fn(const char *name, uint32 type, const char *comment, void *state)
1729 SMBCFILE *dir = (SMBCFILE *)state;
1730 int dirent_type;
1732 /* We need to process the type a little ... */
1734 if (dir->dir_type == SMBC_FILE_SHARE) {
1736 switch (type) {
1737 case 0: /* Directory tree */
1738 dirent_type = SMBC_FILE_SHARE;
1739 break;
1741 case 1:
1742 dirent_type = SMBC_PRINTER_SHARE;
1743 break;
1745 case 2:
1746 dirent_type = SMBC_COMMS_SHARE;
1747 break;
1749 case 3:
1750 dirent_type = SMBC_IPC_SHARE;
1751 break;
1753 default:
1754 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
1755 break;
1758 else dirent_type = dir->dir_type;
1760 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1762 /* An error occurred, what do we do? */
1763 /* FIXME: Add some code here */
1768 static void
1769 dir_list_fn(file_info *finfo, const char *mask, void *state)
1772 if (add_dirent((SMBCFILE *)state, finfo->name, "",
1773 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
1775 /* Handle an error ... */
1777 /* FIXME: Add some code ... */
1783 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
1785 fstring server, share, user, password, options;
1786 pstring workgroup;
1787 pstring path;
1788 SMBCSRV *srv = NULL;
1789 SMBCFILE *dir = NULL;
1790 struct in_addr rem_ip;
1792 if (!context || !context->internal ||
1793 !context->internal->_initialized) {
1794 DEBUG(4, ("no valid context\n"));
1795 errno = EINVAL;
1796 return NULL;
1800 if (!fname) {
1801 DEBUG(4, ("no valid fname\n"));
1802 errno = EINVAL;
1803 return NULL;
1806 if (smbc_parse_path(context, fname,
1807 server, sizeof(server),
1808 share, sizeof(share),
1809 path, sizeof(path),
1810 user, sizeof(user),
1811 password, sizeof(password),
1812 options, sizeof(options))) {
1813 DEBUG(4, ("no valid path\n"));
1814 errno = EINVAL;
1815 return NULL;
1818 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
1820 /* Ensure the options are valid */
1821 if (smbc_check_options(server, share, path, options)) {
1822 DEBUG(4, ("unacceptable options (%s)\n", options));
1823 errno = EINVAL;
1824 return NULL;
1827 if (user[0] == (char)0) fstrcpy(user, context->user);
1829 pstrcpy(workgroup, context->workgroup);
1831 dir = malloc(sizeof(*dir));
1833 if (!dir) {
1835 errno = ENOMEM;
1836 return NULL;
1840 ZERO_STRUCTP(dir);
1842 dir->cli_fd = 0;
1843 dir->fname = strdup(fname);
1844 dir->srv = NULL;
1845 dir->offset = 0;
1846 dir->file = False;
1847 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
1849 if (server[0] == (char)0 &&
1850 (! *options || strcmp(options, "mb=.any") == 0)) {
1851 struct in_addr server_ip;
1852 if (share[0] != (char)0 || path[0] != (char)0) {
1854 errno = EINVAL;
1855 if (dir) {
1856 SAFE_FREE(dir->fname);
1857 SAFE_FREE(dir);
1859 return NULL;
1863 * We have server and share and path empty ... so list the
1864 * workgroups first try to get the LMB for our workgroup, and
1865 * if that fails, try the DMB
1868 pstrcpy(workgroup, lp_workgroup());
1870 if (!find_master_ip(workgroup, &server_ip)) {
1871 struct user_auth_info u_info;
1872 struct cli_state *cli;
1874 DEBUG(4, ("Unable to find master browser for workgroup %s\n",
1875 workgroup));
1877 /* find the name of the server ... */
1878 pstrcpy(u_info.username, user);
1879 pstrcpy(u_info.password, password);
1881 if (!(cli = get_ipc_connect_master_ip_bcast(workgroup, &u_info))) {
1882 DEBUG(4, ("Unable to find master browser by "
1883 "broadcast\n"));
1884 errno = ENOENT;
1885 return NULL;
1888 fstrcpy(server, cli->desthost);
1890 cli_shutdown(cli);
1891 } else {
1893 * Do a name status query to find out the name of the
1894 * master browser. We use <01><02>__MSBROWSE__<02>#01 if
1895 * *#00 fails because a domain master browser will not
1896 * respond to a wildcard query (or, at least, an NT4
1897 * server acting as the domain master browser will not).
1899 * We might be able to use ONLY the query on MSBROWSE, but
1900 * that's not yet been tested with all Windows versions,
1901 * so until it is, leave the original wildcard query as
1902 * the first choice and fall back to MSBROWSE if the
1903 * wildcard query fails.
1905 if (!name_status_find("*", 0, 0x1d, server_ip, server) &&
1906 !name_status_find(MSBROWSE, 1, 0x1d, server_ip, server)) {
1907 errno = ENOENT;
1908 return NULL;
1912 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
1915 * Get a connection to IPC$ on the server if we do not already
1916 * have one
1919 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
1920 if (!srv) {
1922 if (dir) {
1923 SAFE_FREE(dir->fname);
1924 SAFE_FREE(dir);
1926 return NULL;
1929 dir->srv = srv;
1930 dir->dir_type = SMBC_WORKGROUP;
1932 /* Now, list the stuff ... */
1934 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_fn,
1935 (void *)dir)) {
1937 DEBUG(1, ("Could not enumerate domains using '%s'\n", workgroup));
1938 if (dir) {
1939 SAFE_FREE(dir->fname);
1940 SAFE_FREE(dir);
1942 errno = cli_errno(&srv->cli);
1944 return NULL;
1947 } else if (server[0] == (char)0 &&
1948 (! *options || strcmp(options, "mb=.all") == 0)) {
1950 int i;
1951 int count;
1952 struct ip_service *ip_list;
1953 struct ip_service server_addr;
1954 struct user_auth_info u_info;
1955 struct cli_state *cli;
1957 if (share[0] != (char)0 || path[0] != (char)0) {
1959 errno = EINVAL;
1960 if (dir) {
1961 SAFE_FREE(dir->fname);
1962 SAFE_FREE(dir);
1964 return NULL;
1967 pstrcpy(u_info.username, user);
1968 pstrcpy(u_info.password, password);
1971 * We have server and share and path empty but options
1972 * requesting that we scan all master browsers for their list
1973 * of workgroups/domains. This implies that we must first try
1974 * broadcast queries to find all master browsers, and if that
1975 * doesn't work, then try our other methods which return only
1976 * a single master browser.
1979 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
1980 if (!find_master_ip(workgroup, &server_addr.ip)) {
1982 errno = ENOENT;
1983 return NULL;
1986 ip_list = &server_addr;
1987 count = 1;
1990 for (i = 0; i < count; i++) {
1991 DEBUG(99, ("Found master browser %s\n", inet_ntoa(ip_list[i].ip)));
1993 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
1995 /* cli == NULL is the master browser refused to talk or
1996 could not be found */
1997 if ( !cli )
1998 continue;
2000 fstrcpy(server, cli->desthost);
2001 cli_shutdown(cli);
2003 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2006 * For each returned master browser IP address, get a
2007 * connection to IPC$ on the server if we do not
2008 * already have one, and determine the
2009 * workgroups/domains that it knows about.
2012 srv = smbc_server(context, server,
2013 "IPC$", workgroup, user, password);
2014 if (!srv) {
2016 if (dir) {
2017 SAFE_FREE(dir->fname);
2018 SAFE_FREE(dir);
2020 return NULL;
2023 dir->srv = srv;
2024 dir->dir_type = SMBC_WORKGROUP;
2026 /* Now, list the stuff ... */
2028 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2029 (void *)dir)) {
2031 if (dir) {
2032 SAFE_FREE(dir->fname);
2033 SAFE_FREE(dir);
2035 errno = cli_errno(&srv->cli);
2037 return NULL;
2041 } else {
2043 * Server not an empty string ... Check the rest and see what
2044 * gives
2046 if (share[0] == (char)0) {
2048 if (path[0] != (char)0) { /* Should not have empty share with path */
2050 errno = EINVAL;
2051 if (dir) {
2052 SAFE_FREE(dir->fname);
2053 SAFE_FREE(dir);
2055 return NULL;
2059 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2060 /* However, we check to see if <server> is an IP address first */
2062 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2063 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2064 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2065 fstring buserver;
2067 dir->dir_type = SMBC_SERVER;
2070 * Get the backup list ...
2074 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2076 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2077 errno = EPERM; /* FIXME, is this correct */
2078 return NULL;
2083 * Get a connection to IPC$ on the server if we do not already have one
2086 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2088 if (!srv) {
2089 DEBUG(0, ("got no contact to IPC$\n"));
2090 if (dir) {
2091 SAFE_FREE(dir->fname);
2092 SAFE_FREE(dir);
2094 return NULL;
2098 dir->srv = srv;
2100 /* Now, list the servers ... */
2102 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2103 (void *)dir)) {
2105 if (dir) {
2106 SAFE_FREE(dir->fname);
2107 SAFE_FREE(dir);
2109 errno = cli_errno(&srv->cli);
2110 return NULL;
2114 else {
2116 if (resolve_name(server, &rem_ip, 0x20)) {
2118 /* Now, list the shares ... */
2120 dir->dir_type = SMBC_FILE_SHARE;
2122 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2124 if (!srv) {
2126 if (dir) {
2127 SAFE_FREE(dir->fname);
2128 SAFE_FREE(dir);
2130 return NULL;
2134 dir->srv = srv;
2136 /* Now, list the servers ... */
2138 if (cli_RNetShareEnum(&srv->cli, list_fn,
2139 (void *)dir) < 0) {
2141 errno = cli_errno(&srv->cli);
2142 if (dir) {
2143 SAFE_FREE(dir->fname);
2144 SAFE_FREE(dir);
2146 return NULL;
2151 else {
2153 errno = ENODEV; /* Neither the workgroup nor server exists */
2154 if (dir) {
2155 SAFE_FREE(dir->fname);
2156 SAFE_FREE(dir);
2158 return NULL;
2165 else { /* The server and share are specified ... work from there ... */
2167 /* Well, we connect to the server and list the directory */
2169 dir->dir_type = SMBC_FILE_SHARE;
2171 srv = smbc_server(context, server, share, workgroup, user, password);
2173 if (!srv) {
2175 if (dir) {
2176 SAFE_FREE(dir->fname);
2177 SAFE_FREE(dir);
2179 return NULL;
2183 dir->srv = srv;
2185 /* Now, list the files ... */
2187 pstrcat(path, "\\*");
2189 if (cli_list(&srv->cli, path, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2190 (void *)dir) < 0) {
2192 if (dir) {
2193 SAFE_FREE(dir->fname);
2194 SAFE_FREE(dir);
2196 errno = smbc_errno(context, &srv->cli);
2197 return NULL;
2204 DLIST_ADD(context->internal->_files, dir);
2205 return dir;
2210 * Routine to close a directory
2213 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2216 if (!context || !context->internal ||
2217 !context->internal->_initialized) {
2219 errno = EINVAL;
2220 return -1;
2224 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2226 errno = EBADF;
2227 return -1;
2231 smbc_remove_dir(dir); /* Clean it up */
2233 DLIST_REMOVE(context->internal->_files, dir);
2235 if (dir) {
2237 SAFE_FREE(dir->fname);
2238 SAFE_FREE(dir); /* Free the space too */
2241 return 0;
2246 * Routine to get a directory entry
2249 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2251 struct smbc_dirent *dirp, *dirent;
2253 /* Check that all is ok first ... */
2255 if (!context || !context->internal ||
2256 !context->internal->_initialized) {
2258 errno = EINVAL;
2259 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2260 return NULL;
2264 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2266 errno = EBADF;
2267 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2268 return NULL;
2272 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2274 errno = ENOTDIR;
2275 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2276 return NULL;
2280 if (!dir->dir_next) {
2281 return NULL;
2283 else {
2285 dirent = dir->dir_next->dirent;
2286 if (!dirent) {
2288 errno = ENOENT;
2289 return NULL;
2293 /* Hmmm, do I even need to copy it? */
2295 memcpy(context->internal->_dirent, dirent, dirent->dirlen); /* Copy the dirent */
2296 dirp = (struct smbc_dirent *)context->internal->_dirent;
2297 dirp->comment = (char *)(&dirp->name + dirent->namelen + 1);
2298 dir->dir_next = dir->dir_next->next;
2300 return (struct smbc_dirent *)context->internal->_dirent;
2306 * Routine to get directory entries
2309 static int smbc_getdents_ctx(SMBCCTX *context, SMBCFILE *dir, struct smbc_dirent *dirp, int count)
2311 struct smbc_dir_list *dirlist;
2312 int rem = count, reqd;
2313 char *ndir = (char *)dirp;
2315 /* Check that all is ok first ... */
2317 if (!context || !context->internal ||
2318 !context->internal->_initialized) {
2320 errno = EINVAL;
2321 return -1;
2325 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2327 errno = EBADF;
2328 return -1;
2332 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2334 errno = ENOTDIR;
2335 return -1;
2340 * Now, retrieve the number of entries that will fit in what was passed
2341 * We have to figure out if the info is in the list, or we need to
2342 * send a request to the server to get the info.
2345 while ((dirlist = dir->dir_next)) {
2346 struct smbc_dirent *dirent;
2348 if (!dirlist->dirent) {
2350 errno = ENOENT; /* Bad error */
2351 return -1;
2355 if (rem < (reqd = (sizeof(struct smbc_dirent) + dirlist->dirent->namelen +
2356 dirlist->dirent->commentlen + 1))) {
2358 if (rem < count) { /* We managed to copy something */
2360 errno = 0;
2361 return count - rem;
2364 else { /* Nothing copied ... */
2366 errno = EINVAL; /* Not enough space ... */
2367 return -1;
2373 dirent = dirlist->dirent;
2375 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2377 ((struct smbc_dirent *)ndir)->comment =
2378 (char *)(&((struct smbc_dirent *)ndir)->name + dirent->namelen + 1);
2380 ndir += reqd;
2382 rem -= reqd;
2384 dir->dir_next = dirlist = dirlist -> next;
2387 if (rem == count)
2388 return 0;
2389 else
2390 return count - rem;
2395 * Routine to create a directory ...
2398 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2400 SMBCSRV *srv;
2401 fstring server, share, user, password, workgroup;
2402 pstring path;
2404 if (!context || !context->internal ||
2405 !context->internal->_initialized) {
2407 errno = EINVAL;
2408 return -1;
2412 if (!fname) {
2414 errno = EINVAL;
2415 return -1;
2419 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2421 if (smbc_parse_path(context, fname,
2422 server, sizeof(server),
2423 share, sizeof(share),
2424 path, sizeof(path),
2425 user, sizeof(user),
2426 password, sizeof(password),
2427 NULL, 0)) {
2428 errno = EINVAL;
2429 return -1;
2432 if (user[0] == (char)0) fstrcpy(user, context->user);
2434 fstrcpy(workgroup, context->workgroup);
2436 srv = smbc_server(context, server, share, workgroup, user, password);
2438 if (!srv) {
2440 return -1; /* errno set by smbc_server */
2444 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2446 mode = aDIR | aRONLY;
2449 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2451 if (strcmp(path, "\\") == 0) {
2453 mode = aDIR | aRONLY;
2456 else {
2458 mode = aRONLY;
2459 smbc_stat_printjob(srv, path, &size, &m_time);
2460 c_time = a_time = m_time;
2463 else { */
2465 if (!cli_mkdir(&srv->cli, path)) {
2467 errno = smbc_errno(context, &srv->cli);
2468 return -1;
2472 return 0;
2477 * Our list function simply checks to see if a directory is not empty
2480 static int smbc_rmdir_dirempty = True;
2482 static void rmdir_list_fn(file_info *finfo, const char *mask, void *state)
2485 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2486 smbc_rmdir_dirempty = False;
2491 * Routine to remove a directory
2494 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2496 SMBCSRV *srv;
2497 fstring server, share, user, password, workgroup;
2498 pstring path;
2500 if (!context || !context->internal ||
2501 !context->internal->_initialized) {
2503 errno = EINVAL;
2504 return -1;
2508 if (!fname) {
2510 errno = EINVAL;
2511 return -1;
2515 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2517 if (smbc_parse_path(context, fname,
2518 server, sizeof(server),
2519 share, sizeof(share),
2520 path, sizeof(path),
2521 user, sizeof(user),
2522 password, sizeof(password),
2523 NULL, 0))
2525 errno = EINVAL;
2526 return -1;
2529 if (user[0] == (char)0) fstrcpy(user, context->user);
2531 fstrcpy(workgroup, context->workgroup);
2533 srv = smbc_server(context, server, share, workgroup, user, password);
2535 if (!srv) {
2537 return -1; /* errno set by smbc_server */
2541 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2543 mode = aDIR | aRONLY;
2546 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2548 if (strcmp(path, "\\") == 0) {
2550 mode = aDIR | aRONLY;
2553 else {
2555 mode = aRONLY;
2556 smbc_stat_printjob(srv, path, &size, &m_time);
2557 c_time = a_time = m_time;
2560 else { */
2562 if (!cli_rmdir(&srv->cli, path)) {
2564 errno = smbc_errno(context, &srv->cli);
2566 if (errno == EACCES) { /* Check if the dir empty or not */
2568 pstring lpath; /* Local storage to avoid buffer overflows */
2570 smbc_rmdir_dirempty = True; /* Make this so ... */
2572 pstrcpy(lpath, path);
2573 pstrcat(lpath, "\\*");
2575 if (cli_list(&srv->cli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2576 NULL) < 0) {
2578 /* Fix errno to ignore latest error ... */
2580 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
2581 smbc_errno(context, &srv->cli)));
2582 errno = EACCES;
2586 if (smbc_rmdir_dirempty)
2587 errno = EACCES;
2588 else
2589 errno = ENOTEMPTY;
2593 return -1;
2597 return 0;
2602 * Routine to return the current directory position
2605 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
2607 off_t ret_val; /* Squash warnings about cast */
2609 if (!context || !context->internal ||
2610 !context->internal->_initialized) {
2612 errno = EINVAL;
2613 return -1;
2617 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2619 errno = EBADF;
2620 return -1;
2624 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2626 errno = ENOTDIR;
2627 return -1;
2632 * We return the pointer here as the offset
2634 ret_val = (int)dir->dir_next;
2635 return ret_val;
2640 * A routine to run down the list and see if the entry is OK
2643 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
2644 struct smbc_dirent *dirent)
2647 /* Run down the list looking for what we want */
2649 if (dirent) {
2651 struct smbc_dir_list *tmp = list;
2653 while (tmp) {
2655 if (tmp->dirent == dirent)
2656 return tmp;
2658 tmp = tmp->next;
2664 return NULL; /* Not found, or an error */
2670 * Routine to seek on a directory
2673 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
2675 long int l_offset = offset; /* Handle problems of size */
2676 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
2677 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
2679 if (!context || !context->internal ||
2680 !context->internal->_initialized) {
2682 errno = EINVAL;
2683 return -1;
2687 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2689 errno = ENOTDIR;
2690 return -1;
2694 /* Now, check what we were passed and see if it is OK ... */
2696 if (dirent == NULL) { /* Seek to the begining of the list */
2698 dir->dir_next = dir->dir_list;
2699 return 0;
2703 /* Now, run down the list and make sure that the entry is OK */
2704 /* This may need to be changed if we change the format of the list */
2706 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
2708 errno = EINVAL; /* Bad entry */
2709 return -1;
2713 dir->dir_next = list_ent;
2715 return 0;
2720 * Routine to fstat a dir
2723 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
2726 if (!context || !context->internal ||
2727 !context->internal->_initialized) {
2729 errno = EINVAL;
2730 return -1;
2734 /* No code yet ... */
2736 return 0;
2740 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
2742 SMBCSRV *srv;
2743 fstring server, share, user, password, workgroup;
2744 pstring path;
2745 uint16 mode;
2747 if (!context || !context->internal ||
2748 !context->internal->_initialized) {
2750 errno = EINVAL; /* Best I can think of ... */
2751 return -1;
2755 if (!fname) {
2757 errno = EINVAL;
2758 return -1;
2762 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
2764 if (smbc_parse_path(context, fname,
2765 server, sizeof(server),
2766 share, sizeof(share),
2767 path, sizeof(path),
2768 user, sizeof(user),
2769 password, sizeof(password),
2770 NULL, 0)) {
2771 errno = EINVAL;
2772 return -1;
2775 if (user[0] == (char)0) fstrcpy(user, context->user);
2777 fstrcpy(workgroup, context->workgroup);
2779 srv = smbc_server(context, server, share, workgroup, user, password);
2781 if (!srv) {
2782 return -1; /* errno set by smbc_server */
2785 mode = 0;
2787 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
2788 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
2789 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
2790 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
2792 if (!cli_setatr(&srv->cli, path, mode, 0)) {
2793 errno = smbc_errno(context, &srv->cli);
2794 return -1;
2797 return 0;
2800 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
2802 SMBCSRV *srv;
2803 fstring server, share, user, password, workgroup;
2804 pstring path;
2805 uint16 mode;
2806 time_t t = (tbuf == NULL ? time(NULL) : tbuf->tv_sec);
2808 if (!context || !context->internal ||
2809 !context->internal->_initialized) {
2811 errno = EINVAL; /* Best I can think of ... */
2812 return -1;
2816 if (!fname) {
2818 errno = EINVAL;
2819 return -1;
2823 DEBUG(4, ("smbc_utimes(%s, [%s])\n", fname, ctime(&t)));
2825 if (smbc_parse_path(context, fname,
2826 server, sizeof(server),
2827 share, sizeof(share),
2828 path, sizeof(path),
2829 user, sizeof(user),
2830 password, sizeof(password),
2831 NULL, 0)) {
2832 errno = EINVAL;
2833 return -1;
2836 if (user[0] == (char)0) fstrcpy(user, context->user);
2838 fstrcpy(workgroup, context->workgroup);
2840 srv = smbc_server(context, server, share, workgroup, user, password);
2842 if (!srv) {
2843 return -1; /* errno set by smbc_server */
2846 if (!smbc_getatr(context, srv, path,
2847 &mode, NULL,
2848 NULL, NULL, NULL,
2849 NULL)) {
2850 return -1;
2853 if (!cli_setatr(&srv->cli, path, mode, t)) {
2854 /* some servers always refuse directory changes */
2855 if (!(mode & aDIR)) {
2856 errno = smbc_errno(context, &srv->cli);
2857 return -1;
2861 return 0;
2865 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
2866 However NT4 gives a "The information may have been modified by a
2867 computer running Windows NT 5.0" if denied ACEs do not appear before
2868 allowed ACEs. */
2870 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
2872 if (sec_ace_equal(ace1, ace2))
2873 return 0;
2875 if (ace1->type != ace2->type)
2876 return ace2->type - ace1->type;
2878 if (sid_compare(&ace1->trustee, &ace2->trustee))
2879 return sid_compare(&ace1->trustee, &ace2->trustee);
2881 if (ace1->flags != ace2->flags)
2882 return ace1->flags - ace2->flags;
2884 if (ace1->info.mask != ace2->info.mask)
2885 return ace1->info.mask - ace2->info.mask;
2887 if (ace1->size != ace2->size)
2888 return ace1->size - ace2->size;
2890 return memcmp(ace1, ace2, sizeof(SEC_ACE));
2894 static void sort_acl(SEC_ACL *the_acl)
2896 uint32 i;
2897 if (!the_acl) return;
2899 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
2901 for (i=1;i<the_acl->num_aces;) {
2902 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
2903 int j;
2904 for (j=i; j<the_acl->num_aces-1; j++) {
2905 the_acl->ace[j] = the_acl->ace[j+1];
2907 the_acl->num_aces--;
2908 } else {
2909 i++;
2914 /* convert a SID to a string, either numeric or username/group */
2915 static void convert_sid_to_string(struct cli_state *ipc_cli,
2916 POLICY_HND *pol,
2917 fstring str,
2918 BOOL numeric,
2919 DOM_SID *sid)
2921 char **domains = NULL;
2922 char **names = NULL;
2923 uint32 *types = NULL;
2925 sid_to_string(str, sid);
2927 if (numeric) return; /* no lookup desired */
2929 /* Ask LSA to convert the sid to a name */
2931 if (!NT_STATUS_IS_OK(cli_lsa_lookup_sids(ipc_cli, ipc_cli->mem_ctx,
2932 pol, 1, sid, &domains,
2933 &names, &types)) ||
2934 !domains || !domains[0] || !names || !names[0]) {
2935 return;
2938 /* Converted OK */
2940 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
2941 domains[0], lp_winbind_separator(),
2942 names[0]);
2945 /* convert a string to a SID, either numeric or username/group */
2946 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
2947 POLICY_HND *pol,
2948 BOOL numeric,
2949 DOM_SID *sid,
2950 const char *str)
2952 uint32 *types = NULL;
2953 DOM_SID *sids = NULL;
2954 BOOL result = True;
2956 if (numeric) {
2957 if (strncmp(str, "S-", 2) == 0) {
2958 return string_to_sid(sid, str);
2961 result = False;
2962 goto done;
2965 if (!NT_STATUS_IS_OK(cli_lsa_lookup_names(ipc_cli, ipc_cli->mem_ctx,
2966 pol, 1, &str, &sids,
2967 &types))) {
2968 result = False;
2969 goto done;
2972 sid_copy(sid, &sids[0]);
2973 done:
2975 return result;
2979 /* parse an ACE in the same format as print_ace() */
2980 static BOOL parse_ace(struct cli_state *ipc_cli,
2981 POLICY_HND *pol,
2982 SEC_ACE *ace,
2983 BOOL numeric,
2984 char *str)
2986 char *p;
2987 const char *cp;
2988 fstring tok;
2989 unsigned atype, aflags, amask;
2990 DOM_SID sid;
2991 SEC_ACCESS mask;
2992 const struct perm_value *v;
2993 struct perm_value {
2994 const char *perm;
2995 uint32 mask;
2998 /* These values discovered by inspection */
2999 static const struct perm_value special_values[] = {
3000 { "R", 0x00120089 },
3001 { "W", 0x00120116 },
3002 { "X", 0x001200a0 },
3003 { "D", 0x00010000 },
3004 { "P", 0x00040000 },
3005 { "O", 0x00080000 },
3006 { NULL, 0 },
3009 static const struct perm_value standard_values[] = {
3010 { "READ", 0x001200a9 },
3011 { "CHANGE", 0x001301bf },
3012 { "FULL", 0x001f01ff },
3013 { NULL, 0 },
3017 ZERO_STRUCTP(ace);
3018 p = strchr_m(str,':');
3019 if (!p) return False;
3020 *p = '\0';
3021 p++;
3022 /* Try to parse numeric form */
3024 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3025 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3026 goto done;
3029 /* Try to parse text form */
3031 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3032 return False;
3035 cp = p;
3036 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3037 return False;
3040 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3041 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3042 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3043 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3044 } else {
3045 return False;
3048 /* Only numeric form accepted for flags at present */
3050 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3051 sscanf(tok, "%i", &aflags))) {
3052 return False;
3055 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3056 return False;
3059 if (strncmp(tok, "0x", 2) == 0) {
3060 if (sscanf(tok, "%i", &amask) != 1) {
3061 return False;
3063 goto done;
3066 for (v = standard_values; v->perm; v++) {
3067 if (strcmp(tok, v->perm) == 0) {
3068 amask = v->mask;
3069 goto done;
3073 p = tok;
3075 while(*p) {
3076 BOOL found = False;
3078 for (v = special_values; v->perm; v++) {
3079 if (v->perm[0] == *p) {
3080 amask |= v->mask;
3081 found = True;
3085 if (!found) return False;
3086 p++;
3089 if (*p) {
3090 return False;
3093 done:
3094 mask.mask = amask;
3095 init_sec_ace(ace, &sid, atype, mask, aflags);
3096 return True;
3099 /* add an ACE to a list of ACEs in a SEC_ACL */
3100 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3102 SEC_ACL *new;
3103 SEC_ACE *aces;
3104 if (! *the_acl) {
3105 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3106 return True;
3109 aces = calloc(1+(*the_acl)->num_aces,sizeof(SEC_ACE));
3110 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3111 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3112 new = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3113 SAFE_FREE(aces);
3114 (*the_acl) = new;
3115 return True;
3119 /* parse a ascii version of a security descriptor */
3120 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3121 struct cli_state *ipc_cli,
3122 POLICY_HND *pol,
3123 BOOL numeric,
3124 char *str)
3126 const char *p = str;
3127 fstring tok;
3128 SEC_DESC *ret;
3129 size_t sd_size;
3130 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3131 SEC_ACL *dacl=NULL;
3132 int revision=1;
3134 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3136 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3137 revision = strtol(tok+9, NULL, 16);
3138 continue;
3141 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3142 owner_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3143 if (!owner_sid ||
3144 !convert_string_to_sid(ipc_cli, pol,
3145 numeric,
3146 owner_sid, tok+6)) {
3147 DEBUG(5, ("Failed to parse owner sid\n"));
3148 return NULL;
3150 continue;
3153 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3154 owner_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3155 if (!owner_sid ||
3156 !convert_string_to_sid(ipc_cli, pol,
3157 False,
3158 owner_sid, tok+7)) {
3159 DEBUG(5, ("Failed to parse owner sid\n"));
3160 return NULL;
3162 continue;
3165 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3166 grp_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3167 if (!grp_sid ||
3168 !convert_string_to_sid(ipc_cli, pol,
3169 numeric,
3170 grp_sid, tok+6)) {
3171 DEBUG(5, ("Failed to parse group sid\n"));
3172 return NULL;
3174 continue;
3177 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3178 grp_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3179 if (!grp_sid ||
3180 !convert_string_to_sid(ipc_cli, pol,
3181 False,
3182 grp_sid, tok+6)) {
3183 DEBUG(5, ("Failed to parse group sid\n"));
3184 return NULL;
3186 continue;
3189 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3190 SEC_ACE ace;
3191 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3192 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3193 return NULL;
3195 if(!add_ace(&dacl, &ace, ctx)) {
3196 DEBUG(5, ("Failed to add ACL %s\n", tok));
3197 return NULL;
3199 continue;
3202 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3203 SEC_ACE ace;
3204 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3205 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3206 return NULL;
3208 if(!add_ace(&dacl, &ace, ctx)) {
3209 DEBUG(5, ("Failed to add ACL %s\n", tok));
3210 return NULL;
3212 continue;
3215 DEBUG(5, ("Failed to parse security descriptor\n"));
3216 return NULL;
3219 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3220 owner_sid, grp_sid, NULL, dacl, &sd_size);
3222 SAFE_FREE(grp_sid);
3223 SAFE_FREE(owner_sid);
3225 return ret;
3229 /*****************************************************
3230 retrieve the acls for a file
3231 *******************************************************/
3232 static int cacl_get(TALLOC_CTX *ctx, struct cli_state *cli,
3233 struct cli_state *ipc_cli, POLICY_HND *pol,
3234 char *filename, char *name, char *buf, int bufsize)
3236 uint32 i;
3237 int n = 0;
3238 int n_used;
3239 BOOL all;
3240 BOOL numeric = True;
3241 BOOL determine_size = (bufsize == 0);
3242 int fnum = -1;
3243 SEC_DESC *sd;
3244 fstring sidstr;
3245 char *p;
3247 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3249 if (fnum == -1) {
3250 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3251 filename, cli_errstr(cli)));
3252 errno = 0;
3253 return -1;
3256 sd = cli_query_secdesc(cli, fnum, ctx);
3258 if (!sd) {
3259 DEBUG(5, ("cacl_get Failed to query old descriptor\n"));
3260 errno = 0;
3261 return -1;
3264 cli_close(cli, fnum);
3266 all = (*name == '*');
3267 numeric = (* (name + strlen(name) - 1) != '+');
3269 n_used = 0;
3271 if (all) {
3272 if (determine_size) {
3273 p = talloc_asprintf(ctx,
3274 "REVISION:%d", sd->revision);
3275 if (!p) {
3276 errno = ENOMEM;
3277 return -1;
3279 n = strlen(p);
3280 } else {
3281 n = snprintf(buf, bufsize,
3282 "REVISION:%d", sd->revision);
3284 } else if (StrCaseCmp(name, "revision") == 0) {
3285 if (determine_size) {
3286 p = talloc_asprintf(ctx, "%d", sd->revision);
3287 if (!p) {
3288 errno = ENOMEM;
3289 return -1;
3291 n = strlen(p);
3292 } else {
3293 n = snprintf(buf, bufsize, "%d", sd->revision);
3297 if (!determine_size && n > bufsize) {
3298 errno = ERANGE;
3299 return -1;
3301 buf += n;
3302 n_used += n;
3303 bufsize -= n;
3305 /* Get owner and group sid */
3307 if (sd->owner_sid) {
3308 convert_sid_to_string(ipc_cli, pol,
3309 sidstr, numeric, sd->owner_sid);
3310 } else {
3311 fstrcpy(sidstr, "");
3314 if (all) {
3315 if (determine_size) {
3316 p = talloc_asprintf(ctx, ",OWNER:%s", sidstr);
3317 if (!p) {
3318 errno = ENOMEM;
3319 return -1;
3321 n = strlen(p);
3322 } else {
3323 n = snprintf(buf, bufsize, ",OWNER:%s", sidstr);
3325 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3326 if (determine_size) {
3327 p = talloc_asprintf(ctx, "%s", sidstr);
3328 if (!p) {
3329 errno = ENOMEM;
3330 return -1;
3332 n = strlen(p);
3333 } else {
3334 n = snprintf(buf, bufsize, "%s", sidstr);
3338 if (!determine_size && n > bufsize) {
3339 errno = ERANGE;
3340 return -1;
3342 buf += n;
3343 n_used += n;
3344 bufsize -= n;
3346 if (sd->grp_sid) {
3347 convert_sid_to_string(ipc_cli, pol,
3348 sidstr, numeric, sd->grp_sid);
3349 } else {
3350 fstrcpy(sidstr, "");
3353 if (all) {
3354 if (determine_size) {
3355 p = talloc_asprintf(ctx, ",GROUP:%s", sidstr);
3356 if (!p) {
3357 errno = ENOMEM;
3358 return -1;
3360 n = strlen(p);
3361 } else {
3362 n = snprintf(buf, bufsize, ",GROUP:%s", sidstr);
3364 } else if (StrnCaseCmp(name, "group", 5) == 0) {
3365 if (determine_size) {
3366 p = talloc_asprintf(ctx, "%s", sidstr);
3367 if (!p) {
3368 errno = ENOMEM;
3369 return -1;
3371 n = strlen(p);
3372 } else {
3373 n = snprintf(buf, bufsize, "%s", sidstr);
3377 if (!determine_size && n > bufsize) {
3378 errno = ERANGE;
3379 return -1;
3381 buf += n;
3382 n_used += n;
3383 bufsize -= n;
3385 /* Add aces to value buffer */
3386 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
3388 SEC_ACE *ace = &sd->dacl->ace[i];
3389 convert_sid_to_string(ipc_cli, pol,
3390 sidstr, numeric, &ace->trustee);
3392 if (all) {
3393 if (determine_size) {
3394 p = talloc_asprintf(ctx,
3395 ",ACL:%s:%d/%d/0x%08x",
3396 sidstr,
3397 ace->type,
3398 ace->flags,
3399 ace->info.mask);
3400 if (!p) {
3401 errno = ENOMEM;
3402 return -1;
3404 n = strlen(p);
3405 } else {
3406 n = snprintf(buf, bufsize,
3407 ",ACL:%s:%d/%d/0x%08x",
3408 sidstr,
3409 ace->type,
3410 ace->flags,
3411 ace->info.mask);
3413 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
3414 StrCaseCmp(name + 3, sidstr) == 0) ||
3415 (StrnCaseCmp(name, "acl+", 4) == 0 &&
3416 StrCaseCmp(name + 4, sidstr) == 0)) {
3417 if (determine_size) {
3418 p = talloc_asprintf(ctx,
3419 "%d/%d/0x%08x",
3420 ace->type,
3421 ace->flags,
3422 ace->info.mask);
3423 if (!p) {
3424 errno = ENOMEM;
3425 return -1;
3427 n = strlen(p);
3428 } else {
3429 n = snprintf(buf, bufsize,
3430 "%d/%d/0x%08x",
3431 ace->type, ace->flags, ace->info.mask);
3434 if (n > bufsize) {
3435 errno = ERANGE;
3436 return -1;
3438 buf += n;
3439 n_used += n;
3440 bufsize -= n;
3443 if (n_used == 0) {
3444 errno = ENOATTR;
3445 return -1;
3447 return n_used;
3451 /*****************************************************
3452 set the ACLs on a file given an ascii description
3453 *******************************************************/
3454 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
3455 struct cli_state *ipc_cli, POLICY_HND *pol,
3456 const char *filename, const char *the_acl,
3457 int mode, int flags)
3459 int fnum;
3460 int err = 0;
3461 SEC_DESC *sd = NULL, *old;
3462 SEC_ACL *dacl = NULL;
3463 DOM_SID *owner_sid = NULL;
3464 DOM_SID *grp_sid = NULL;
3465 uint32 i, j;
3466 size_t sd_size;
3467 int ret = 0;
3468 char *p;
3469 BOOL numeric = True;
3471 /* the_acl will be null for REMOVE_ALL operations */
3472 if (the_acl) {
3473 numeric = ((p = strchr(the_acl, ':')) != NULL &&
3474 p > the_acl &&
3475 p[-1] != '+');
3477 /* if this is to set the entire ACL... */
3478 if (*the_acl == '*') {
3479 /* ... then increment past the first colon */
3480 the_acl = p + 1;
3483 sd = sec_desc_parse(ctx, ipc_cli, pol,
3484 numeric, (char *) the_acl);
3486 if (!sd) {
3487 errno = EINVAL;
3488 return -1;
3492 /* The desired access below is the only one I could find that works
3493 with NT4, W2KP and Samba */
3495 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3497 if (fnum == -1) {
3498 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3499 filename, cli_errstr(cli)));
3500 errno = 0;
3501 return -1;
3504 old = cli_query_secdesc(cli, fnum, ctx);
3506 if (!old) {
3507 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
3508 errno = 0;
3509 return -1;
3512 cli_close(cli, fnum);
3514 switch (mode) {
3515 case SMBC_XATTR_MODE_REMOVE_ALL:
3516 old->dacl->num_aces = 0;
3517 SAFE_FREE(old->dacl->ace);
3518 SAFE_FREE(old->dacl);
3519 old->off_dacl = 0;
3520 dacl = old->dacl;
3521 break;
3523 case SMBC_XATTR_MODE_REMOVE:
3524 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3525 BOOL found = False;
3527 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3528 if (sec_ace_equal(&sd->dacl->ace[i],
3529 &old->dacl->ace[j])) {
3530 uint32 k;
3531 for (k=j; k<old->dacl->num_aces-1;k++) {
3532 old->dacl->ace[k] = old->dacl->ace[k+1];
3534 old->dacl->num_aces--;
3535 if (old->dacl->num_aces == 0) {
3536 SAFE_FREE(old->dacl->ace);
3537 SAFE_FREE(old->dacl);
3538 old->off_dacl = 0;
3540 found = True;
3541 dacl = old->dacl;
3542 break;
3546 if (!found) {
3547 err = ENOATTR;
3548 ret = -1;
3549 goto failed;
3552 break;
3554 case SMBC_XATTR_MODE_ADD:
3555 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3556 BOOL found = False;
3558 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3559 if (sid_equal(&sd->dacl->ace[i].trustee,
3560 &old->dacl->ace[j].trustee)) {
3561 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
3562 err = EEXIST;
3563 ret = -1;
3564 goto failed;
3566 old->dacl->ace[j] = sd->dacl->ace[i];
3567 ret = -1;
3568 found = True;
3572 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
3573 err = ENOATTR;
3574 ret = -1;
3575 goto failed;
3578 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3579 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
3582 dacl = old->dacl;
3583 break;
3585 case SMBC_XATTR_MODE_SET:
3586 old = sd;
3587 owner_sid = old->owner_sid;
3588 grp_sid = old->grp_sid;
3589 dacl = old->dacl;
3590 break;
3592 case SMBC_XATTR_MODE_CHOWN:
3593 owner_sid = sd->owner_sid;
3594 break;
3596 case SMBC_XATTR_MODE_CHGRP:
3597 grp_sid = sd->grp_sid;
3598 break;
3601 /* Denied ACE entries must come before allowed ones */
3602 sort_acl(old->dacl);
3604 /* Create new security descriptor and set it */
3605 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
3606 owner_sid, grp_sid, NULL, dacl, &sd_size);
3608 fnum = cli_nt_create(cli, filename,
3609 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
3611 if (fnum == -1) {
3612 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3613 filename, cli_errstr(cli)));
3614 errno = 0;
3615 return -1;
3618 if (!cli_set_secdesc(cli, fnum, sd)) {
3619 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
3620 ret = -1;
3623 /* Clean up */
3625 failed:
3626 cli_close(cli, fnum);
3628 if (err != 0) {
3629 errno = err;
3632 return ret;
3636 int smbc_setxattr_ctx(SMBCCTX *context,
3637 const char *fname,
3638 const char *name,
3639 const void *value,
3640 size_t size,
3641 int flags)
3643 int ret;
3644 SMBCSRV *srv;
3645 SMBCSRV *ipc_srv;
3646 fstring server, share, user, password, workgroup;
3647 pstring path;
3648 TALLOC_CTX *ctx;
3649 POLICY_HND pol;
3651 if (!context || !context->internal ||
3652 !context->internal->_initialized) {
3654 errno = EINVAL; /* Best I can think of ... */
3655 return -1;
3659 if (!fname) {
3661 errno = EINVAL;
3662 return -1;
3666 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
3667 fname, name, (int) size, (char *) value));
3669 if (smbc_parse_path(context, fname,
3670 server, sizeof(server),
3671 share, sizeof(share),
3672 path, sizeof(path),
3673 user, sizeof(user),
3674 password, sizeof(password),
3675 NULL, 0)) {
3676 errno = EINVAL;
3677 return -1;
3680 if (user[0] == (char)0) fstrcpy(user, context->user);
3682 fstrcpy(workgroup, context->workgroup);
3684 srv = smbc_server(context, server, share, workgroup, user, password);
3685 if (!srv) {
3686 return -1; /* errno set by smbc_server */
3689 ipc_srv = smbc_attr_server(context, server, share,
3690 workgroup, user, password,
3691 &pol);
3692 if (!ipc_srv) {
3693 return -1;
3696 ctx = talloc_init("smbc_setxattr");
3697 if (!ctx) {
3698 errno = ENOMEM;
3699 return -1;
3703 * Are they asking to set an access control element or to set
3704 * the entire access control list?
3706 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3707 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3708 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3709 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3710 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3712 /* Yup. */
3713 char *namevalue =
3714 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3715 if (! namevalue) {
3716 errno = ENOMEM;
3717 ret = -1;
3718 } else {
3719 ret = cacl_set(ctx, &srv->cli,
3720 &ipc_srv->cli, &pol, path,
3721 namevalue,
3722 (*namevalue == '*'
3723 ? SMBC_XATTR_MODE_SET
3724 : SMBC_XATTR_MODE_ADD),
3725 flags);
3727 talloc_destroy(ctx);
3728 return ret;
3732 * Are they asking to set the owner?
3734 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3735 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
3737 /* Yup. */
3738 char *namevalue =
3739 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3740 if (! namevalue) {
3741 errno = ENOMEM;
3742 ret = -1;
3743 } else {
3744 ret = cacl_set(ctx, &srv->cli,
3745 &ipc_srv->cli, &pol, path,
3746 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3748 talloc_destroy(ctx);
3749 return ret;
3753 * Are they asking to set the group?
3755 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3756 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
3758 /* Yup. */
3759 char *namevalue =
3760 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3761 if (! namevalue) {
3762 errno = ENOMEM;
3763 ret = -1;
3764 } else {
3765 ret = cacl_set(ctx, &srv->cli,
3766 &ipc_srv->cli, &pol, path,
3767 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3769 talloc_destroy(ctx);
3770 return ret;
3773 /* Unsupported attribute name */
3774 talloc_destroy(ctx);
3775 errno = EINVAL;
3776 return -1;
3779 int smbc_getxattr_ctx(SMBCCTX *context,
3780 const char *fname,
3781 const char *name,
3782 const void *value,
3783 size_t size)
3785 int ret;
3786 SMBCSRV *srv;
3787 SMBCSRV *ipc_srv;
3788 fstring server, share, user, password, workgroup;
3789 pstring path;
3790 TALLOC_CTX *ctx;
3791 POLICY_HND pol;
3793 if (!context || !context->internal ||
3794 !context->internal->_initialized) {
3796 errno = EINVAL; /* Best I can think of ... */
3797 return -1;
3801 if (!fname) {
3803 errno = EINVAL;
3804 return -1;
3808 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
3810 if (smbc_parse_path(context, fname,
3811 server, sizeof(server),
3812 share, sizeof(share),
3813 path, sizeof(path),
3814 user, sizeof(user),
3815 password, sizeof(password),
3816 NULL, 0)) {
3817 errno = EINVAL;
3818 return -1;
3821 if (user[0] == (char)0) fstrcpy(user, context->user);
3823 fstrcpy(workgroup, context->workgroup);
3825 srv = smbc_server(context, server, share, workgroup, user, password);
3826 if (!srv) {
3827 return -1; /* errno set by smbc_server */
3830 ipc_srv = smbc_attr_server(context, server, share,
3831 workgroup, user, password,
3832 &pol);
3833 if (!ipc_srv) {
3834 return -1;
3837 ctx = talloc_init("smbc:getxattr");
3838 if (!ctx) {
3839 errno = ENOMEM;
3840 return -1;
3843 /* Are they requesting a supported attribute? */
3844 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3845 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3846 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3847 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3848 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3849 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3850 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3851 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3852 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3854 /* Yup. */
3855 ret = cacl_get(ctx, &srv->cli,
3856 &ipc_srv->cli, &pol,
3857 (char *) path, (char *) name + 19,
3858 (char *) value, size);
3859 if (ret < 0 && errno == 0) {
3860 errno = smbc_errno(context, &srv->cli);
3862 talloc_destroy(ctx);
3863 return ret;
3866 /* Unsupported attribute name */
3867 talloc_destroy(ctx);
3868 errno = EINVAL;
3869 return -1;
3873 int smbc_removexattr_ctx(SMBCCTX *context,
3874 const char *fname,
3875 const char *name)
3877 int ret;
3878 SMBCSRV *srv;
3879 SMBCSRV *ipc_srv;
3880 fstring server, share, user, password, workgroup;
3881 pstring path;
3882 TALLOC_CTX *ctx;
3883 POLICY_HND pol;
3885 if (!context || !context->internal ||
3886 !context->internal->_initialized) {
3888 errno = EINVAL; /* Best I can think of ... */
3889 return -1;
3893 if (!fname) {
3895 errno = EINVAL;
3896 return -1;
3900 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
3902 if (smbc_parse_path(context, fname,
3903 server, sizeof(server),
3904 share, sizeof(share),
3905 path, sizeof(path),
3906 user, sizeof(user),
3907 password, sizeof(password),
3908 NULL, 0)) {
3909 errno = EINVAL;
3910 return -1;
3913 if (user[0] == (char)0) fstrcpy(user, context->user);
3915 fstrcpy(workgroup, context->workgroup);
3917 srv = smbc_server(context, server, share, workgroup, user, password);
3918 if (!srv) {
3919 return -1; /* errno set by smbc_server */
3922 ipc_srv = smbc_attr_server(context, server, share,
3923 workgroup, user, password,
3924 &pol);
3925 if (!ipc_srv) {
3926 return -1;
3929 ipc_srv = smbc_attr_server(context, server, share,
3930 workgroup, user, password,
3931 &pol);
3932 if (!ipc_srv) {
3933 return -1;
3936 ctx = talloc_init("smbc_removexattr");
3937 if (!ctx) {
3938 errno = ENOMEM;
3939 return -1;
3942 /* Are they asking to set the entire ACL? */
3943 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3944 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
3946 /* Yup. */
3947 ret = cacl_set(ctx, &srv->cli,
3948 &ipc_srv->cli, &pol, path,
3949 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
3950 talloc_destroy(ctx);
3951 return ret;
3955 * Are they asking to remove one or more spceific security descriptor
3956 * attributes?
3958 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3959 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3960 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3961 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3962 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3963 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3964 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3966 /* Yup. */
3967 ret = cacl_set(ctx, &srv->cli,
3968 &ipc_srv->cli, &pol, path,
3969 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
3970 talloc_destroy(ctx);
3971 return ret;
3974 /* Unsupported attribute name */
3975 talloc_destroy(ctx);
3976 errno = EINVAL;
3977 return -1;
3980 int smbc_listxattr_ctx(SMBCCTX *context,
3981 const char *fname,
3982 char *list,
3983 size_t size)
3986 * This isn't quite what listxattr() is supposed to do. This returns
3987 * the complete set of attributes, always, rather than only those
3988 * attribute names which actually exist for a file. Hmmm...
3990 const char supported[] =
3991 "system.nt_sec_desc.revision\0"
3992 "system.nt_sec_desc.owner\0"
3993 "system.nt_sec_desc.owner+\0"
3994 "system.nt_sec_desc.group\0"
3995 "system.nt_sec_desc.group+\0"
3996 "system.nt_sec_desc.acl\0"
3997 "system.nt_sec_desc.acl+\0"
3998 "system.nt_sec_desc.*\0"
3999 "system.nt_sec_desc.*+\0"
4002 if (size == 0) {
4003 return sizeof(supported);
4006 if (sizeof(supported) > size) {
4007 errno = ERANGE;
4008 return -1;
4011 /* this can't be strcpy() because there are embedded null characters */
4012 memcpy(list, supported, sizeof(supported));
4013 return sizeof(supported);
4018 * Open a print file to be written to by other calls
4021 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
4023 fstring server, share, user, password;
4024 pstring path;
4026 if (!context || !context->internal ||
4027 !context->internal->_initialized) {
4029 errno = EINVAL;
4030 return NULL;
4034 if (!fname) {
4036 errno = EINVAL;
4037 return NULL;
4041 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
4043 if (smbc_parse_path(context, fname,
4044 server, sizeof(server),
4045 share, sizeof(share),
4046 path, sizeof(path),
4047 user, sizeof(user),
4048 password, sizeof(password),
4049 NULL, 0)) {
4050 errno = EINVAL;
4051 return NULL;
4054 /* What if the path is empty, or the file exists? */
4056 return context->open(context, fname, O_WRONLY, 666);
4061 * Routine to print a file on a remote server ...
4063 * We open the file, which we assume to be on a remote server, and then
4064 * copy it to a print file on the share specified by printq.
4067 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
4069 SMBCFILE *fid1, *fid2;
4070 int bytes, saverr, tot_bytes = 0;
4071 char buf[4096];
4073 if (!c_file || !c_file->internal->_initialized || !c_print ||
4074 !c_print->internal->_initialized) {
4076 errno = EINVAL;
4077 return -1;
4081 if (!fname && !printq) {
4083 errno = EINVAL;
4084 return -1;
4088 /* Try to open the file for reading ... */
4090 if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
4092 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
4093 return -1; /* smbc_open sets errno */
4097 /* Now, try to open the printer file for writing */
4099 if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
4101 saverr = errno; /* Save errno */
4102 c_file->close(c_file, fid1);
4103 errno = saverr;
4104 return -1;
4108 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
4110 tot_bytes += bytes;
4112 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
4114 saverr = errno;
4115 c_file->close(c_file, fid1);
4116 c_print->close(c_print, fid2);
4117 errno = saverr;
4123 saverr = errno;
4125 c_file->close(c_file, fid1); /* We have to close these anyway */
4126 c_print->close(c_print, fid2);
4128 if (bytes < 0) {
4130 errno = saverr;
4131 return -1;
4135 return tot_bytes;
4140 * Routine to list print jobs on a printer share ...
4143 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
4145 SMBCSRV *srv;
4146 fstring server, share, user, password, workgroup;
4147 pstring path;
4149 if (!context || !context->internal ||
4150 !context->internal->_initialized) {
4152 errno = EINVAL;
4153 return -1;
4157 if (!fname) {
4159 errno = EINVAL;
4160 return -1;
4164 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
4166 if (smbc_parse_path(context, fname,
4167 server, sizeof(server),
4168 share, sizeof(share),
4169 path, sizeof(path),
4170 user, sizeof(user),
4171 password, sizeof(password),
4172 NULL, 0)) {
4173 errno = EINVAL;
4174 return -1;
4177 if (user[0] == (char)0) fstrcpy(user, context->user);
4179 fstrcpy(workgroup, context->workgroup);
4181 srv = smbc_server(context, server, share, workgroup, user, password);
4183 if (!srv) {
4185 return -1; /* errno set by smbc_server */
4189 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
4191 errno = smbc_errno(context, &srv->cli);
4192 return -1;
4196 return 0;
4201 * Delete a print job from a remote printer share
4204 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
4206 SMBCSRV *srv;
4207 fstring server, share, user, password, workgroup;
4208 pstring path;
4209 int err;
4211 if (!context || !context->internal ||
4212 !context->internal->_initialized) {
4214 errno = EINVAL;
4215 return -1;
4219 if (!fname) {
4221 errno = EINVAL;
4222 return -1;
4226 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
4228 if (smbc_parse_path(context, fname,
4229 server, sizeof(server),
4230 share, sizeof(share),
4231 path, sizeof(path),
4232 user, sizeof(user),
4233 password, sizeof(password),
4234 NULL, 0)) {
4235 errno = EINVAL;
4236 return -1;
4239 if (user[0] == (char)0) fstrcpy(user, context->user);
4241 fstrcpy(workgroup, context->workgroup);
4243 srv = smbc_server(context, server, share, workgroup, user, password);
4245 if (!srv) {
4247 return -1; /* errno set by smbc_server */
4251 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
4253 if (err < 0)
4254 errno = smbc_errno(context, &srv->cli);
4255 else if (err == ERRnosuchprintjob)
4256 errno = EINVAL;
4257 return -1;
4261 return 0;
4266 * Get a new empty handle to fill in with your own info
4268 SMBCCTX * smbc_new_context(void)
4270 SMBCCTX * context;
4272 context = malloc(sizeof(SMBCCTX));
4273 if (!context) {
4274 errno = ENOMEM;
4275 return NULL;
4278 ZERO_STRUCTP(context);
4280 context->internal = malloc(sizeof(struct smbc_internal_data));
4281 if (!context->internal) {
4282 errno = ENOMEM;
4283 return NULL;
4286 ZERO_STRUCTP(context->internal);
4289 /* ADD REASONABLE DEFAULTS */
4290 context->debug = 0;
4291 context->timeout = 20000; /* 20 seconds */
4293 context->open = smbc_open_ctx;
4294 context->creat = smbc_creat_ctx;
4295 context->read = smbc_read_ctx;
4296 context->write = smbc_write_ctx;
4297 context->close = smbc_close_ctx;
4298 context->unlink = smbc_unlink_ctx;
4299 context->rename = smbc_rename_ctx;
4300 context->lseek = smbc_lseek_ctx;
4301 context->stat = smbc_stat_ctx;
4302 context->fstat = smbc_fstat_ctx;
4303 context->opendir = smbc_opendir_ctx;
4304 context->closedir = smbc_closedir_ctx;
4305 context->readdir = smbc_readdir_ctx;
4306 context->getdents = smbc_getdents_ctx;
4307 context->mkdir = smbc_mkdir_ctx;
4308 context->rmdir = smbc_rmdir_ctx;
4309 context->telldir = smbc_telldir_ctx;
4310 context->lseekdir = smbc_lseekdir_ctx;
4311 context->fstatdir = smbc_fstatdir_ctx;
4312 context->chmod = smbc_chmod_ctx;
4313 context->utimes = smbc_utimes_ctx;
4314 context->setxattr = smbc_setxattr_ctx;
4315 context->getxattr = smbc_getxattr_ctx;
4316 context->removexattr = smbc_removexattr_ctx;
4317 context->listxattr = smbc_listxattr_ctx;
4318 context->open_print_job = smbc_open_print_job_ctx;
4319 context->print_file = smbc_print_file_ctx;
4320 context->list_print_jobs = smbc_list_print_jobs_ctx;
4321 context->unlink_print_job = smbc_unlink_print_job_ctx;
4323 context->callbacks.check_server_fn = smbc_check_server;
4324 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
4326 smbc_default_cache_functions(context);
4328 return context;
4332 * Free a context
4334 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
4335 * and thus you'll be leaking memory if not handled properly.
4338 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
4340 if (!context) {
4341 errno = EBADF;
4342 return 1;
4345 if (shutdown_ctx) {
4346 SMBCFILE * f;
4347 DEBUG(1,("Performing aggressive shutdown.\n"));
4349 f = context->internal->_files;
4350 while (f) {
4351 context->close(context, f);
4352 f = f->next;
4354 context->internal->_files = NULL;
4356 /* First try to remove the servers the nice way. */
4357 if (context->callbacks.purge_cached_fn(context)) {
4358 SMBCSRV * s;
4359 SMBCSRV * next;
4360 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
4361 s = context->internal->_servers;
4362 while (s) {
4363 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
4364 cli_shutdown(&s->cli);
4365 context->callbacks.remove_cached_srv_fn(context, s);
4366 next = s->next;
4367 DLIST_REMOVE(context->internal->_servers, s);
4368 SAFE_FREE(s);
4369 s = next;
4371 context->internal->_servers = NULL;
4374 else {
4375 /* This is the polite way */
4376 if (context->callbacks.purge_cached_fn(context)) {
4377 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
4378 errno = EBUSY;
4379 return 1;
4381 if (context->internal->_servers) {
4382 DEBUG(1, ("Active servers in context, free_context failed.\n"));
4383 errno = EBUSY;
4384 return 1;
4386 if (context->internal->_files) {
4387 DEBUG(1, ("Active files in context, free_context failed.\n"));
4388 errno = EBUSY;
4389 return 1;
4393 /* Things we have to clean up */
4394 SAFE_FREE(context->workgroup);
4395 SAFE_FREE(context->netbios_name);
4396 SAFE_FREE(context->user);
4398 DEBUG(3, ("Context %p succesfully freed\n", context));
4399 SAFE_FREE(context->internal);
4400 SAFE_FREE(context);
4401 return 0;
4406 * Initialise the library etc
4408 * We accept a struct containing handle information.
4409 * valid values for info->debug from 0 to 100,
4410 * and insist that info->fn must be non-null.
4412 SMBCCTX * smbc_init_context(SMBCCTX * context)
4414 pstring conf;
4415 int pid;
4416 char *user = NULL, *home = NULL;
4418 if (!context || !context->internal) {
4419 errno = EBADF;
4420 return NULL;
4423 /* Do not initialise the same client twice */
4424 if (context->internal->_initialized) {
4425 return 0;
4428 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
4430 errno = EINVAL;
4431 return NULL;
4435 if (!smbc_initialized) {
4436 /* Do some library wide intialisations the first time we get called */
4438 /* Set this to what the user wants */
4439 DEBUGLEVEL = context->debug;
4441 setup_logging( "libsmbclient", True);
4443 /* Here we would open the smb.conf file if needed ... */
4445 home = getenv("HOME");
4447 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
4449 load_interfaces(); /* Load the list of interfaces ... */
4451 in_client = True; /* FIXME, make a param */
4453 if (!lp_load(conf, True, False, False)) {
4456 * Well, if that failed, try the dyn_CONFIGFILE
4457 * Which points to the standard locn, and if that
4458 * fails, silently ignore it and use the internal
4459 * defaults ...
4462 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
4463 DEBUG(5, ("Could not load either config file: %s or %s\n",
4464 conf, dyn_CONFIGFILE));
4468 reopen_logs(); /* Get logging working ... */
4471 * Block SIGPIPE (from lib/util_sock.c: write())
4472 * It is not needed and should not stop execution
4474 BlockSignals(True, SIGPIPE);
4476 /* Done with one-time initialisation */
4477 smbc_initialized = 1;
4481 if (!context->user) {
4483 * FIXME: Is this the best way to get the user info?
4485 user = getenv("USER");
4486 /* walk around as "guest" if no username can be found */
4487 if (!user) context->user = strdup("guest");
4488 else context->user = strdup(user);
4491 if (!context->netbios_name) {
4493 * We try to get our netbios name from the config. If that fails we fall
4494 * back on constructing our netbios name from our hostname etc
4496 if (global_myname()) {
4497 context->netbios_name = strdup(global_myname());
4499 else {
4501 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
4503 pid = sys_getpid();
4504 context->netbios_name = malloc(17);
4505 if (!context->netbios_name) {
4506 errno = ENOMEM;
4507 return NULL;
4509 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
4513 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
4515 if (!context->workgroup) {
4516 if (lp_workgroup()) {
4517 context->workgroup = strdup(lp_workgroup());
4519 else {
4520 /* TODO: Think about a decent default workgroup */
4521 context->workgroup = strdup("samba");
4525 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
4527 /* shortest timeout is 1 second */
4528 if (context->timeout > 0 && context->timeout < 1000)
4529 context->timeout = 1000;
4532 * FIXME: Should we check the function pointers here?
4535 context->internal->_initialized = 1;
4537 return context;