r616: Bug #1333.
[Samba/gebeck_regimport.git] / source3 / libsmb / libsmbclient.c
blob949c5ffab670f0ec1b928a2df922e2fddf04be9b
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 /* Let the cache function set errno if it wants to */
685 errno = 0;
686 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
687 int saved_errno = errno;
688 DEBUG(3, (" Failed to add server to cache\n"));
689 saved_errno = errno;
690 if (errno == 0) {
691 errno = ENOMEM;
693 goto failed;
696 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
697 server, share, srv));
699 DLIST_ADD(context->internal->_servers, srv);
700 return srv;
702 failed:
703 cli_shutdown(&c);
704 if (!srv) return NULL;
706 SAFE_FREE(srv);
707 return NULL;
711 * Connect to a server for getting/setting attributes, possibly on an existing
712 * connection. This works similarly to smbc_server().
714 SMBCSRV *smbc_attr_server(SMBCCTX *context,
715 const char *server, const char *share,
716 fstring workgroup,
717 fstring username, fstring password,
718 POLICY_HND *pol)
720 struct in_addr ip;
721 struct cli_state *ipc_cli;
722 NTSTATUS nt_status;
723 SMBCSRV *ipc_srv=NULL;
726 * See if we've already created this special connection. Reference
727 * our "special" share name 'IPC$$'.
729 ipc_srv = find_server(context, server, "IPC$$",
730 workgroup, username, password);
731 if (!ipc_srv) {
733 /* We didn't find a cached connection. Get the password */
734 if (*password == '\0') {
735 /* ... then retrieve it now. */
736 context->callbacks.auth_fn(server, share,
737 workgroup, sizeof(fstring),
738 username, sizeof(fstring),
739 password, sizeof(fstring));
742 zero_ip(&ip);
743 nt_status = cli_full_connection(&ipc_cli,
744 global_myname(), server,
745 &ip, 0, "IPC$", "?????",
746 username, workgroup,
747 password, 0,
748 Undefined, NULL);
749 if (! NT_STATUS_IS_OK(nt_status)) {
750 DEBUG(1,("cli_full_connection failed! (%s)\n",
751 nt_errstr(nt_status)));
752 errno = ENOTSUP;
753 return NULL;
756 if (!cli_nt_session_open(ipc_cli, PI_LSARPC)) {
757 DEBUG(1, ("cli_nt_session_open fail!\n"));
758 errno = ENOTSUP;
759 cli_shutdown(ipc_cli);
760 return NULL;
763 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
764 but NT sends 0x2000000 so we might as well do it too. */
766 nt_status = cli_lsa_open_policy(ipc_cli,
767 ipc_cli->mem_ctx,
768 True,
769 GENERIC_EXECUTE_ACCESS,
770 pol);
772 if (!NT_STATUS_IS_OK(nt_status)) {
773 errno = smbc_errno(context, ipc_cli);
774 cli_shutdown(ipc_cli);
775 return NULL;
778 ipc_srv = (SMBCSRV *)malloc(sizeof(*ipc_srv));
779 if (!ipc_srv) {
780 errno = ENOMEM;
781 cli_shutdown(ipc_cli);
782 return NULL;
785 ZERO_STRUCTP(ipc_srv);
786 ipc_srv->cli = *ipc_cli;
788 free(ipc_cli);
790 /* now add it to the cache (internal or external) */
792 errno = 0; /* let cache function set errno if it likes */
793 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
794 server,
795 "IPC$$",
796 workgroup,
797 username)) {
798 DEBUG(3, (" Failed to add server to cache\n"));
799 if (errno == 0) {
800 errno = ENOMEM;
802 cli_shutdown(&ipc_srv->cli);
803 free(ipc_srv);
804 return NULL;
807 DLIST_ADD(context->internal->_servers, ipc_srv);
810 return ipc_srv;
814 * Routine to open() a file ...
817 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
819 fstring server, share, user, password, workgroup;
820 pstring path;
821 SMBCSRV *srv = NULL;
822 SMBCFILE *file = NULL;
823 int fd;
825 if (!context || !context->internal ||
826 !context->internal->_initialized) {
828 errno = EINVAL; /* Best I can think of ... */
829 return NULL;
833 if (!fname) {
835 errno = EINVAL;
836 return NULL;
840 if (smbc_parse_path(context, fname,
841 server, sizeof(server),
842 share, sizeof(share),
843 path, sizeof(path),
844 user, sizeof(user),
845 password, sizeof(password),
846 NULL, 0)) {
847 errno = EINVAL;
848 return NULL;
851 if (user[0] == (char)0) fstrcpy(user, context->user);
853 fstrcpy(workgroup, context->workgroup);
855 srv = smbc_server(context, server, share, workgroup, user, password);
857 if (!srv) {
859 if (errno == EPERM) errno = EACCES;
860 return NULL; /* smbc_server sets errno */
864 /* Hmmm, the test for a directory is suspect here ... FIXME */
866 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
868 fd = -1;
871 else {
873 file = malloc(sizeof(SMBCFILE));
875 if (!file) {
877 errno = ENOMEM;
878 return NULL;
882 ZERO_STRUCTP(file);
884 if ((fd = cli_open(&srv->cli, path, flags, DENY_NONE)) < 0) {
886 /* Handle the error ... */
888 SAFE_FREE(file);
889 errno = smbc_errno(context, &srv->cli);
890 return NULL;
894 /* Fill in file struct */
896 file->cli_fd = fd;
897 file->fname = strdup(fname);
898 file->srv = srv;
899 file->offset = 0;
900 file->file = True;
902 DLIST_ADD(context->internal->_files, file);
903 return file;
907 /* Check if opendir needed ... */
909 if (fd == -1) {
910 int eno = 0;
912 eno = smbc_errno(context, &srv->cli);
913 file = context->opendir(context, fname);
914 if (!file) errno = eno;
915 return file;
919 errno = EINVAL; /* FIXME, correct errno ? */
920 return NULL;
925 * Routine to create a file
928 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
930 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
933 if (!context || !context->internal ||
934 !context->internal->_initialized) {
936 errno = EINVAL;
937 return NULL;
941 return smbc_open_ctx(context, path, creat_bits, mode);
945 * Routine to read() a file ...
948 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
950 int ret;
952 if (!context || !context->internal ||
953 !context->internal->_initialized) {
955 errno = EINVAL;
956 return -1;
960 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
962 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
964 errno = EBADF;
965 return -1;
969 /* Check that the buffer exists ... */
971 if (buf == NULL) {
973 errno = EINVAL;
974 return -1;
978 ret = cli_read(&file->srv->cli, file->cli_fd, buf, file->offset, count);
980 if (ret < 0) {
982 errno = smbc_errno(context, &file->srv->cli);
983 return -1;
987 file->offset += ret;
989 DEBUG(4, (" --> %d\n", ret));
991 return ret; /* Success, ret bytes of data ... */
996 * Routine to write() a file ...
999 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1001 int ret;
1003 if (!context || !context->internal ||
1004 !context->internal->_initialized) {
1006 errno = EINVAL;
1007 return -1;
1011 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1013 errno = EBADF;
1014 return -1;
1018 /* Check that the buffer exists ... */
1020 if (buf == NULL) {
1022 errno = EINVAL;
1023 return -1;
1027 ret = cli_write(&file->srv->cli, file->cli_fd, 0, buf, file->offset, count);
1029 if (ret <= 0) {
1031 errno = smbc_errno(context, &file->srv->cli);
1032 return -1;
1036 file->offset += ret;
1038 return ret; /* Success, 0 bytes of data ... */
1042 * Routine to close() a file ...
1045 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1047 SMBCSRV *srv;
1049 if (!context || !context->internal ||
1050 !context->internal->_initialized) {
1052 errno = EINVAL;
1053 return -1;
1057 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1059 errno = EBADF;
1060 return -1;
1064 /* IS a dir ... */
1065 if (!file->file) {
1067 return context->closedir(context, file);
1071 if (!cli_close(&file->srv->cli, file->cli_fd)) {
1073 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1074 file->fname));
1075 /* Deallocate slot and remove the server
1076 * from the server cache if unused */
1077 errno = smbc_errno(context, &file->srv->cli);
1078 srv = file->srv;
1079 DLIST_REMOVE(context->internal->_files, file);
1080 SAFE_FREE(file->fname);
1081 SAFE_FREE(file);
1082 context->callbacks.remove_unused_server_fn(context, srv);
1084 return -1;
1088 DLIST_REMOVE(context->internal->_files, file);
1089 SAFE_FREE(file->fname);
1090 SAFE_FREE(file);
1092 return 0;
1096 * Get info from an SMB server on a file. Use a qpathinfo call first
1097 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1099 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1100 uint16 *mode, size_t *size,
1101 time_t *c_time, time_t *a_time, time_t *m_time,
1102 SMB_INO_T *ino)
1105 if (!context || !context->internal ||
1106 !context->internal->_initialized) {
1108 errno = EINVAL;
1109 return -1;
1113 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1115 if (!srv->no_pathinfo2 &&
1116 cli_qpathinfo2(&srv->cli, path, c_time, a_time, m_time, NULL,
1117 size, mode, ino)) return True;
1119 /* if this is NT then don't bother with the getatr */
1120 if (srv->cli.capabilities & CAP_NT_SMBS) {
1121 errno = EPERM;
1122 return False;
1125 if (cli_getatr(&srv->cli, path, mode, size, m_time)) {
1126 a_time = c_time = m_time;
1127 srv->no_pathinfo2 = True;
1128 return True;
1131 errno = EPERM;
1132 return False;
1137 * Routine to unlink() a file
1140 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1142 fstring server, share, user, password, workgroup;
1143 pstring path;
1144 SMBCSRV *srv = NULL;
1146 if (!context || !context->internal ||
1147 !context->internal->_initialized) {
1149 errno = EINVAL; /* Best I can think of ... */
1150 return -1;
1154 if (!fname) {
1156 errno = EINVAL;
1157 return -1;
1161 if (smbc_parse_path(context, fname,
1162 server, sizeof(server),
1163 share, sizeof(share),
1164 path, sizeof(path),
1165 user, sizeof(user),
1166 password, sizeof(password),
1167 NULL, 0)) {
1168 errno = EINVAL;
1169 return -1;
1172 if (user[0] == (char)0) fstrcpy(user, context->user);
1174 fstrcpy(workgroup, context->workgroup);
1176 srv = smbc_server(context, server, share, workgroup, user, password);
1178 if (!srv) {
1180 return -1; /* smbc_server sets errno */
1184 /* if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
1186 int job = smbc_stat_printjob(srv, path, NULL, NULL);
1187 if (job == -1) {
1189 return -1;
1192 if ((err = cli_printjob_del(&srv->cli, job)) != 0) {
1195 return -1;
1198 } else */
1200 if (!cli_unlink(&srv->cli, path)) {
1202 errno = smbc_errno(context, &srv->cli);
1204 if (errno == EACCES) { /* Check if the file is a directory */
1206 int saverr = errno;
1207 size_t size = 0;
1208 uint16 mode = 0;
1209 time_t m_time = 0, a_time = 0, c_time = 0;
1210 SMB_INO_T ino = 0;
1212 if (!smbc_getatr(context, srv, path, &mode, &size,
1213 &c_time, &a_time, &m_time, &ino)) {
1215 /* Hmmm, bad error ... What? */
1217 errno = smbc_errno(context, &srv->cli);
1218 return -1;
1221 else {
1223 if (IS_DOS_DIR(mode))
1224 errno = EISDIR;
1225 else
1226 errno = saverr; /* Restore this */
1231 return -1;
1235 return 0; /* Success ... */
1240 * Routine to rename() a file
1243 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1244 SMBCCTX *ncontext, const char *nname)
1246 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1247 pstring path1, path2;
1248 SMBCSRV *srv = NULL;
1250 if (!ocontext || !ncontext ||
1251 !ocontext->internal || !ncontext->internal ||
1252 !ocontext->internal->_initialized ||
1253 !ncontext->internal->_initialized) {
1255 errno = EINVAL; /* Best I can think of ... */
1256 return -1;
1260 if (!oname || !nname) {
1262 errno = EINVAL;
1263 return -1;
1267 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1269 smbc_parse_path(ocontext, oname,
1270 server1, sizeof(server1),
1271 share1, sizeof(share1),
1272 path1, sizeof(path1),
1273 user1, sizeof(user1),
1274 password1, sizeof(password1),
1275 NULL, 0);
1277 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1279 smbc_parse_path(ncontext, nname,
1280 server2, sizeof(server2),
1281 share2, sizeof(share2),
1282 path2, sizeof(path2),
1283 user2, sizeof(user2),
1284 password2, sizeof(password2),
1285 NULL, 0);
1287 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1289 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1290 strcmp(user1, user2)) {
1292 /* Can't rename across file systems, or users?? */
1294 errno = EXDEV;
1295 return -1;
1299 fstrcpy(workgroup, ocontext->workgroup);
1300 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1301 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1302 if (!srv) {
1304 return -1;
1308 if (!cli_rename(&srv->cli, path1, path2)) {
1309 int eno = smbc_errno(ocontext, &srv->cli);
1311 if (eno != EEXIST ||
1312 !cli_unlink(&srv->cli, path2) ||
1313 !cli_rename(&srv->cli, path1, path2)) {
1315 errno = eno;
1316 return -1;
1321 return 0; /* Success */
1326 * A routine to lseek() a file
1329 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1331 size_t size;
1333 if (!context || !context->internal ||
1334 !context->internal->_initialized) {
1336 errno = EINVAL;
1337 return -1;
1341 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1343 errno = EBADF;
1344 return -1;
1348 if (!file->file) {
1350 errno = EINVAL;
1351 return -1; /* Can't lseek a dir ... */
1355 switch (whence) {
1356 case SEEK_SET:
1357 file->offset = offset;
1358 break;
1360 case SEEK_CUR:
1361 file->offset += offset;
1362 break;
1364 case SEEK_END:
1365 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
1366 NULL, NULL, NULL))
1368 SMB_BIG_UINT b_size = size;
1369 if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
1370 NULL))
1372 errno = EINVAL;
1373 return -1;
1374 } else
1375 size = b_size;
1377 file->offset = size + offset;
1378 break;
1380 default:
1381 errno = EINVAL;
1382 break;
1386 return file->offset;
1391 * Generate an inode number from file name for those things that need it
1394 static
1395 ino_t smbc_inode(SMBCCTX *context, const char *name)
1398 if (!context || !context->internal ||
1399 !context->internal->_initialized) {
1401 errno = EINVAL;
1402 return -1;
1406 if (!*name) return 2; /* FIXME, why 2 ??? */
1407 return (ino_t)str_checksum(name);
1412 * Routine to put basic stat info into a stat structure ... Used by stat and
1413 * fstat below.
1416 static
1417 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname, size_t size, int mode)
1420 st->st_mode = 0;
1422 if (IS_DOS_DIR(mode)) {
1423 st->st_mode = SMBC_DIR_MODE;
1424 } else {
1425 st->st_mode = SMBC_FILE_MODE;
1428 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1429 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1430 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1431 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1433 st->st_size = size;
1434 #ifdef HAVE_STAT_ST_BLKSIZE
1435 st->st_blksize = 512;
1436 #endif
1437 #ifdef HAVE_STAT_ST_BLOCKS
1438 st->st_blocks = (size+511)/512;
1439 #endif
1440 st->st_uid = getuid();
1441 st->st_gid = getgid();
1443 if (IS_DOS_DIR(mode)) {
1444 st->st_nlink = 2;
1445 } else {
1446 st->st_nlink = 1;
1449 if (st->st_ino == 0) {
1450 st->st_ino = smbc_inode(context, fname);
1453 return True; /* FIXME: Is this needed ? */
1458 * Routine to stat a file given a name
1461 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1463 SMBCSRV *srv;
1464 fstring server, share, user, password, workgroup;
1465 pstring path;
1466 time_t m_time = 0, a_time = 0, c_time = 0;
1467 size_t size = 0;
1468 uint16 mode = 0;
1469 SMB_INO_T ino = 0;
1471 if (!context || !context->internal ||
1472 !context->internal->_initialized) {
1474 errno = EINVAL; /* Best I can think of ... */
1475 return -1;
1479 if (!fname) {
1481 errno = EINVAL;
1482 return -1;
1486 DEBUG(4, ("smbc_stat(%s)\n", fname));
1488 if (smbc_parse_path(context, fname,
1489 server, sizeof(server),
1490 share, sizeof(share),
1491 path, sizeof(path),
1492 user, sizeof(user),
1493 password, sizeof(password),
1494 NULL, 0)) {
1495 errno = EINVAL;
1496 return -1;
1499 if (user[0] == (char)0) fstrcpy(user, context->user);
1501 fstrcpy(workgroup, context->workgroup);
1503 srv = smbc_server(context, server, share, workgroup, user, password);
1505 if (!srv) {
1506 return -1; /* errno set by smbc_server */
1509 if (!smbc_getatr(context, srv, path, &mode, &size,
1510 &c_time, &a_time, &m_time, &ino)) {
1512 errno = smbc_errno(context, &srv->cli);
1513 return -1;
1517 st->st_ino = ino;
1519 smbc_setup_stat(context, st, path, size, mode);
1521 st->st_atime = a_time;
1522 st->st_ctime = c_time;
1523 st->st_mtime = m_time;
1524 st->st_dev = srv->dev;
1526 return 0;
1531 * Routine to stat a file given an fd
1534 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1536 time_t c_time, a_time, m_time;
1537 size_t size;
1538 uint16 mode;
1539 SMB_INO_T ino = 0;
1541 if (!context || !context->internal ||
1542 !context->internal->_initialized) {
1544 errno = EINVAL;
1545 return -1;
1549 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1551 errno = EBADF;
1552 return -1;
1556 if (!file->file) {
1558 return context->fstatdir(context, file, st);
1562 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
1563 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
1564 SMB_BIG_UINT b_size = size;
1565 if (!cli_getattrE(&file->srv->cli, file->cli_fd,
1566 &mode, &b_size, &c_time, &a_time, &m_time)) {
1568 errno = EINVAL;
1569 return -1;
1570 } else
1571 size = b_size;
1575 st->st_ino = ino;
1577 smbc_setup_stat(context, st, file->fname, size, mode);
1579 st->st_atime = a_time;
1580 st->st_ctime = c_time;
1581 st->st_mtime = m_time;
1582 st->st_dev = file->srv->dev;
1584 return 0;
1589 * Routine to open a directory
1590 * We accept the URL syntax explained in smbc_parse_path(), above.
1593 static void smbc_remove_dir(SMBCFILE *dir)
1595 struct smbc_dir_list *d,*f;
1597 d = dir->dir_list;
1598 while (d) {
1600 f = d; d = d->next;
1602 SAFE_FREE(f->dirent);
1603 SAFE_FREE(f);
1607 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
1611 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
1613 struct smbc_dirent *dirent;
1614 int size;
1615 char *u_name = NULL, *u_comment = NULL;
1616 size_t u_name_len = 0, u_comment_len = 0;
1618 if (name)
1619 u_name_len = push_utf8_allocate(&u_name, name);
1620 if (comment)
1621 u_comment_len = push_utf8_allocate(&u_comment, comment);
1624 * Allocate space for the dirent, which must be increased by the
1625 * size of the name and the comment and 1 for the null on the comment.
1626 * The null on the name is already accounted for.
1629 size = sizeof(struct smbc_dirent) + u_name_len + u_comment_len + 1;
1631 dirent = malloc(size);
1633 if (!dirent) {
1635 dir->dir_error = ENOMEM;
1636 return -1;
1640 ZERO_STRUCTP(dirent);
1642 if (dir->dir_list == NULL) {
1644 dir->dir_list = malloc(sizeof(struct smbc_dir_list));
1645 if (!dir->dir_list) {
1647 SAFE_FREE(dirent);
1648 dir->dir_error = ENOMEM;
1649 return -1;
1652 ZERO_STRUCTP(dir->dir_list);
1654 dir->dir_end = dir->dir_next = dir->dir_list;
1656 else {
1658 dir->dir_end->next = malloc(sizeof(struct smbc_dir_list));
1660 if (!dir->dir_end->next) {
1662 SAFE_FREE(dirent);
1663 dir->dir_error = ENOMEM;
1664 return -1;
1667 ZERO_STRUCTP(dir->dir_end->next);
1669 dir->dir_end = dir->dir_end->next;
1672 dir->dir_end->next = NULL;
1673 dir->dir_end->dirent = dirent;
1675 dirent->smbc_type = type;
1676 dirent->namelen = u_name_len;
1677 dirent->commentlen = u_comment_len;
1678 dirent->dirlen = size;
1680 strncpy(dirent->name, (u_name?u_name:""), dirent->namelen + 1);
1682 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
1683 strncpy(dirent->comment, (u_comment?u_comment:""), dirent->commentlen + 1);
1685 SAFE_FREE(u_comment);
1686 SAFE_FREE(u_name);
1688 return 0;
1692 static void
1693 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
1695 SMBCFILE *dir = (SMBCFILE *)state;
1696 struct smbc_dir_list *dir_list;
1697 struct smbc_dirent *dirent;
1698 int dirent_type;
1699 int remove = 0;
1701 dirent_type = dir->dir_type;
1703 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1705 /* An error occurred, what do we do? */
1706 /* FIXME: Add some code here */
1709 /* Point to the one just added */
1710 dirent = dir->dir_end->dirent;
1712 /* See if this was a duplicate */
1713 for (dir_list = dir->dir_list;
1714 dir_list != dir->dir_end;
1715 dir_list = dir_list->next) {
1716 if (! remove &&
1717 strcmp(dir_list->dirent->name, dirent->name) == 0) {
1718 /* Duplicate. End end of list need to be removed. */
1719 remove = 1;
1722 if (remove && dir_list->next == dir->dir_end) {
1723 /* Found the end of the list. Remove it. */
1724 dir->dir_end = dir_list;
1725 free(dir_list->next);
1726 dir_list->next = NULL;
1727 break;
1732 static void
1733 list_fn(const char *name, uint32 type, const char *comment, void *state)
1735 SMBCFILE *dir = (SMBCFILE *)state;
1736 int dirent_type;
1738 /* We need to process the type a little ... */
1740 if (dir->dir_type == SMBC_FILE_SHARE) {
1742 switch (type) {
1743 case 0: /* Directory tree */
1744 dirent_type = SMBC_FILE_SHARE;
1745 break;
1747 case 1:
1748 dirent_type = SMBC_PRINTER_SHARE;
1749 break;
1751 case 2:
1752 dirent_type = SMBC_COMMS_SHARE;
1753 break;
1755 case 3:
1756 dirent_type = SMBC_IPC_SHARE;
1757 break;
1759 default:
1760 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
1761 break;
1764 else dirent_type = dir->dir_type;
1766 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1768 /* An error occurred, what do we do? */
1769 /* FIXME: Add some code here */
1774 static void
1775 dir_list_fn(file_info *finfo, const char *mask, void *state)
1778 if (add_dirent((SMBCFILE *)state, finfo->name, "",
1779 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
1781 /* Handle an error ... */
1783 /* FIXME: Add some code ... */
1789 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
1791 fstring server, share, user, password, options;
1792 pstring workgroup;
1793 pstring path;
1794 SMBCSRV *srv = NULL;
1795 SMBCFILE *dir = NULL;
1796 struct in_addr rem_ip;
1798 if (!context || !context->internal ||
1799 !context->internal->_initialized) {
1800 DEBUG(4, ("no valid context\n"));
1801 errno = EINVAL;
1802 return NULL;
1806 if (!fname) {
1807 DEBUG(4, ("no valid fname\n"));
1808 errno = EINVAL;
1809 return NULL;
1812 if (smbc_parse_path(context, fname,
1813 server, sizeof(server),
1814 share, sizeof(share),
1815 path, sizeof(path),
1816 user, sizeof(user),
1817 password, sizeof(password),
1818 options, sizeof(options))) {
1819 DEBUG(4, ("no valid path\n"));
1820 errno = EINVAL;
1821 return NULL;
1824 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
1826 /* Ensure the options are valid */
1827 if (smbc_check_options(server, share, path, options)) {
1828 DEBUG(4, ("unacceptable options (%s)\n", options));
1829 errno = EINVAL;
1830 return NULL;
1833 if (user[0] == (char)0) fstrcpy(user, context->user);
1835 pstrcpy(workgroup, context->workgroup);
1837 dir = malloc(sizeof(*dir));
1839 if (!dir) {
1841 errno = ENOMEM;
1842 return NULL;
1846 ZERO_STRUCTP(dir);
1848 dir->cli_fd = 0;
1849 dir->fname = strdup(fname);
1850 dir->srv = NULL;
1851 dir->offset = 0;
1852 dir->file = False;
1853 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
1855 if (server[0] == (char)0 &&
1856 (! *options || strcmp(options, "mb=.any") == 0)) {
1857 struct in_addr server_ip;
1858 if (share[0] != (char)0 || path[0] != (char)0) {
1860 errno = EINVAL;
1861 if (dir) {
1862 SAFE_FREE(dir->fname);
1863 SAFE_FREE(dir);
1865 return NULL;
1869 * We have server and share and path empty ... so list the
1870 * workgroups first try to get the LMB for our workgroup, and
1871 * if that fails, try the DMB
1874 pstrcpy(workgroup, lp_workgroup());
1876 if (!find_master_ip(workgroup, &server_ip)) {
1877 struct user_auth_info u_info;
1878 struct cli_state *cli;
1880 DEBUG(4, ("Unable to find master browser for workgroup %s\n",
1881 workgroup));
1883 /* find the name of the server ... */
1884 pstrcpy(u_info.username, user);
1885 pstrcpy(u_info.password, password);
1887 if (!(cli = get_ipc_connect_master_ip_bcast(workgroup, &u_info))) {
1888 DEBUG(4, ("Unable to find master browser by "
1889 "broadcast\n"));
1890 errno = ENOENT;
1891 return NULL;
1894 fstrcpy(server, cli->desthost);
1896 cli_shutdown(cli);
1897 } else {
1899 * Do a name status query to find out the name of the
1900 * master browser. We use <01><02>__MSBROWSE__<02>#01 if
1901 * *#00 fails because a domain master browser will not
1902 * respond to a wildcard query (or, at least, an NT4
1903 * server acting as the domain master browser will not).
1905 * We might be able to use ONLY the query on MSBROWSE, but
1906 * that's not yet been tested with all Windows versions,
1907 * so until it is, leave the original wildcard query as
1908 * the first choice and fall back to MSBROWSE if the
1909 * wildcard query fails.
1911 if (!name_status_find("*", 0, 0x20, server_ip, server) &&
1912 !name_status_find(MSBROWSE, 1, 0x1b, server_ip, server)) {
1913 errno = ENOENT;
1914 return NULL;
1918 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
1921 * Get a connection to IPC$ on the server if we do not already
1922 * have one
1925 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
1926 if (!srv) {
1928 if (dir) {
1929 SAFE_FREE(dir->fname);
1930 SAFE_FREE(dir);
1932 return NULL;
1935 dir->srv = srv;
1936 dir->dir_type = SMBC_WORKGROUP;
1938 /* Now, list the stuff ... */
1940 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_fn,
1941 (void *)dir)) {
1943 DEBUG(1, ("Could not enumerate domains using '%s'\n", workgroup));
1944 if (dir) {
1945 SAFE_FREE(dir->fname);
1946 SAFE_FREE(dir);
1949 return NULL;
1952 } else if (server[0] == (char)0 &&
1953 (! *options || strcmp(options, "mb=.all") == 0)) {
1955 int i;
1956 int count;
1957 struct ip_service *ip_list;
1958 struct ip_service server_addr;
1959 struct user_auth_info u_info;
1960 struct cli_state *cli;
1962 if (share[0] != (char)0 || path[0] != (char)0) {
1964 errno = EINVAL;
1965 if (dir) {
1966 SAFE_FREE(dir->fname);
1967 SAFE_FREE(dir);
1969 return NULL;
1972 pstrcpy(u_info.username, user);
1973 pstrcpy(u_info.password, password);
1976 * We have server and share and path empty but options
1977 * requesting that we scan all master browsers for their list
1978 * of workgroups/domains. This implies that we must first try
1979 * broadcast queries to find all master browsers, and if that
1980 * doesn't work, then try our other methods which return only
1981 * a single master browser.
1984 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
1985 if (!find_master_ip(workgroup, &server_addr.ip)) {
1987 errno = ENOENT;
1988 return NULL;
1991 ip_list = &server_addr;
1992 count = 1;
1995 for (i = 0; i < count; i++) {
1996 DEBUG(99, ("Found master browser %s\n", inet_ntoa(ip_list[i].ip)));
1998 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2000 /* cli == NULL is the master browser refused to talk or
2001 could not be found */
2002 if ( !cli )
2003 continue;
2005 fstrcpy(server, cli->desthost);
2006 cli_shutdown(cli);
2008 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2011 * For each returned master browser IP address, get a
2012 * connection to IPC$ on the server if we do not
2013 * already have one, and determine the
2014 * workgroups/domains that it knows about.
2017 srv = smbc_server(context, server,
2018 "IPC$", workgroup, user, password);
2019 if (!srv) {
2021 if (dir) {
2022 SAFE_FREE(dir->fname);
2023 SAFE_FREE(dir);
2025 return NULL;
2028 dir->srv = srv;
2029 dir->dir_type = SMBC_WORKGROUP;
2031 /* Now, list the stuff ... */
2033 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2034 (void *)dir)) {
2036 if (dir) {
2037 SAFE_FREE(dir->fname);
2038 SAFE_FREE(dir);
2041 return NULL;
2045 } else {
2047 * Server not an empty string ... Check the rest and see what
2048 * gives
2050 if (share[0] == (char)0) {
2052 if (path[0] != (char)0) { /* Should not have empty share with path */
2054 errno = EINVAL;
2055 if (dir) {
2056 SAFE_FREE(dir->fname);
2057 SAFE_FREE(dir);
2059 return NULL;
2063 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2064 /* However, we check to see if <server> is an IP address first */
2066 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2067 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2068 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2069 fstring buserver;
2071 dir->dir_type = SMBC_SERVER;
2074 * Get the backup list ...
2078 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2080 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2081 errno = EPERM; /* FIXME, is this correct */
2082 return NULL;
2087 * Get a connection to IPC$ on the server if we do not already have one
2090 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2092 if (!srv) {
2093 DEBUG(0, ("got no contact to IPC$\n"));
2094 if (dir) {
2095 SAFE_FREE(dir->fname);
2096 SAFE_FREE(dir);
2098 return NULL;
2102 dir->srv = srv;
2104 /* Now, list the servers ... */
2106 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2107 (void *)dir)) {
2109 if (dir) {
2110 SAFE_FREE(dir->fname);
2111 SAFE_FREE(dir);
2113 return NULL;
2117 else {
2119 if (resolve_name(server, &rem_ip, 0x20)) {
2121 /* Now, list the shares ... */
2123 dir->dir_type = SMBC_FILE_SHARE;
2125 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2127 if (!srv) {
2129 if (dir) {
2130 SAFE_FREE(dir->fname);
2131 SAFE_FREE(dir);
2133 return NULL;
2137 dir->srv = srv;
2139 /* Now, list the servers ... */
2141 if (cli_RNetShareEnum(&srv->cli, list_fn,
2142 (void *)dir) < 0) {
2144 errno = cli_errno(&srv->cli);
2145 if (dir) {
2146 SAFE_FREE(dir->fname);
2147 SAFE_FREE(dir);
2149 return NULL;
2154 else {
2156 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2157 if (dir) {
2158 SAFE_FREE(dir->fname);
2159 SAFE_FREE(dir);
2161 return NULL;
2168 else { /* The server and share are specified ... work from there ... */
2170 /* Well, we connect to the server and list the directory */
2172 dir->dir_type = SMBC_FILE_SHARE;
2174 srv = smbc_server(context, server, share, workgroup, user, password);
2176 if (!srv) {
2178 if (dir) {
2179 SAFE_FREE(dir->fname);
2180 SAFE_FREE(dir);
2182 return NULL;
2186 dir->srv = srv;
2188 /* Now, list the files ... */
2190 pstrcat(path, "\\*");
2192 if (cli_list(&srv->cli, path, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2193 (void *)dir) < 0) {
2195 if (dir) {
2196 SAFE_FREE(dir->fname);
2197 SAFE_FREE(dir);
2199 errno = smbc_errno(context, &srv->cli);
2200 return NULL;
2207 DLIST_ADD(context->internal->_files, dir);
2208 return dir;
2213 * Routine to close a directory
2216 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2219 if (!context || !context->internal ||
2220 !context->internal->_initialized) {
2222 errno = EINVAL;
2223 return -1;
2227 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2229 errno = EBADF;
2230 return -1;
2234 smbc_remove_dir(dir); /* Clean it up */
2236 DLIST_REMOVE(context->internal->_files, dir);
2238 if (dir) {
2240 SAFE_FREE(dir->fname);
2241 SAFE_FREE(dir); /* Free the space too */
2244 return 0;
2249 * Routine to get a directory entry
2252 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2254 struct smbc_dirent *dirp, *dirent;
2256 /* Check that all is ok first ... */
2258 if (!context || !context->internal ||
2259 !context->internal->_initialized) {
2261 errno = EINVAL;
2262 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2263 return NULL;
2267 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2269 errno = EBADF;
2270 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2271 return NULL;
2275 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2277 errno = ENOTDIR;
2278 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2279 return NULL;
2283 if (!dir->dir_next) {
2284 return NULL;
2286 else {
2288 dirent = dir->dir_next->dirent;
2289 if (!dirent) {
2291 errno = ENOENT;
2292 return NULL;
2296 /* Hmmm, do I even need to copy it? */
2298 memcpy(context->internal->_dirent, dirent, dirent->dirlen); /* Copy the dirent */
2299 dirp = (struct smbc_dirent *)context->internal->_dirent;
2300 dirp->comment = (char *)(&dirp->name + dirent->namelen + 1);
2301 dir->dir_next = dir->dir_next->next;
2303 return (struct smbc_dirent *)context->internal->_dirent;
2309 * Routine to get directory entries
2312 static int smbc_getdents_ctx(SMBCCTX *context, SMBCFILE *dir, struct smbc_dirent *dirp, int count)
2314 struct smbc_dir_list *dirlist;
2315 int rem = count, reqd;
2316 char *ndir = (char *)dirp;
2318 /* Check that all is ok first ... */
2320 if (!context || !context->internal ||
2321 !context->internal->_initialized) {
2323 errno = EINVAL;
2324 return -1;
2328 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2330 errno = EBADF;
2331 return -1;
2335 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2337 errno = ENOTDIR;
2338 return -1;
2343 * Now, retrieve the number of entries that will fit in what was passed
2344 * We have to figure out if the info is in the list, or we need to
2345 * send a request to the server to get the info.
2348 while ((dirlist = dir->dir_next)) {
2349 struct smbc_dirent *dirent;
2351 if (!dirlist->dirent) {
2353 errno = ENOENT; /* Bad error */
2354 return -1;
2358 if (rem < (reqd = (sizeof(struct smbc_dirent) + dirlist->dirent->namelen +
2359 dirlist->dirent->commentlen + 1))) {
2361 if (rem < count) { /* We managed to copy something */
2363 errno = 0;
2364 return count - rem;
2367 else { /* Nothing copied ... */
2369 errno = EINVAL; /* Not enough space ... */
2370 return -1;
2376 dirent = dirlist->dirent;
2378 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2380 ((struct smbc_dirent *)ndir)->comment =
2381 (char *)(&((struct smbc_dirent *)ndir)->name + dirent->namelen + 1);
2383 ndir += reqd;
2385 rem -= reqd;
2387 dir->dir_next = dirlist = dirlist -> next;
2390 if (rem == count)
2391 return 0;
2392 else
2393 return count - rem;
2398 * Routine to create a directory ...
2401 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2403 SMBCSRV *srv;
2404 fstring server, share, user, password, workgroup;
2405 pstring path;
2407 if (!context || !context->internal ||
2408 !context->internal->_initialized) {
2410 errno = EINVAL;
2411 return -1;
2415 if (!fname) {
2417 errno = EINVAL;
2418 return -1;
2422 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2424 if (smbc_parse_path(context, fname,
2425 server, sizeof(server),
2426 share, sizeof(share),
2427 path, sizeof(path),
2428 user, sizeof(user),
2429 password, sizeof(password),
2430 NULL, 0)) {
2431 errno = EINVAL;
2432 return -1;
2435 if (user[0] == (char)0) fstrcpy(user, context->user);
2437 fstrcpy(workgroup, context->workgroup);
2439 srv = smbc_server(context, server, share, workgroup, user, password);
2441 if (!srv) {
2443 return -1; /* errno set by smbc_server */
2447 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2449 mode = aDIR | aRONLY;
2452 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2454 if (strcmp(path, "\\") == 0) {
2456 mode = aDIR | aRONLY;
2459 else {
2461 mode = aRONLY;
2462 smbc_stat_printjob(srv, path, &size, &m_time);
2463 c_time = a_time = m_time;
2466 else { */
2468 if (!cli_mkdir(&srv->cli, path)) {
2470 errno = smbc_errno(context, &srv->cli);
2471 return -1;
2475 return 0;
2480 * Our list function simply checks to see if a directory is not empty
2483 static int smbc_rmdir_dirempty = True;
2485 static void rmdir_list_fn(file_info *finfo, const char *mask, void *state)
2488 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2489 smbc_rmdir_dirempty = False;
2494 * Routine to remove a directory
2497 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2499 SMBCSRV *srv;
2500 fstring server, share, user, password, workgroup;
2501 pstring path;
2503 if (!context || !context->internal ||
2504 !context->internal->_initialized) {
2506 errno = EINVAL;
2507 return -1;
2511 if (!fname) {
2513 errno = EINVAL;
2514 return -1;
2518 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2520 if (smbc_parse_path(context, fname,
2521 server, sizeof(server),
2522 share, sizeof(share),
2523 path, sizeof(path),
2524 user, sizeof(user),
2525 password, sizeof(password),
2526 NULL, 0))
2528 errno = EINVAL;
2529 return -1;
2532 if (user[0] == (char)0) fstrcpy(user, context->user);
2534 fstrcpy(workgroup, context->workgroup);
2536 srv = smbc_server(context, server, share, workgroup, user, password);
2538 if (!srv) {
2540 return -1; /* errno set by smbc_server */
2544 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2546 mode = aDIR | aRONLY;
2549 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2551 if (strcmp(path, "\\") == 0) {
2553 mode = aDIR | aRONLY;
2556 else {
2558 mode = aRONLY;
2559 smbc_stat_printjob(srv, path, &size, &m_time);
2560 c_time = a_time = m_time;
2563 else { */
2565 if (!cli_rmdir(&srv->cli, path)) {
2567 errno = smbc_errno(context, &srv->cli);
2569 if (errno == EACCES) { /* Check if the dir empty or not */
2571 pstring lpath; /* Local storage to avoid buffer overflows */
2573 smbc_rmdir_dirempty = True; /* Make this so ... */
2575 pstrcpy(lpath, path);
2576 pstrcat(lpath, "\\*");
2578 if (cli_list(&srv->cli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2579 NULL) < 0) {
2581 /* Fix errno to ignore latest error ... */
2583 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
2584 smbc_errno(context, &srv->cli)));
2585 errno = EACCES;
2589 if (smbc_rmdir_dirempty)
2590 errno = EACCES;
2591 else
2592 errno = ENOTEMPTY;
2596 return -1;
2600 return 0;
2605 * Routine to return the current directory position
2608 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
2610 off_t ret_val; /* Squash warnings about cast */
2612 if (!context || !context->internal ||
2613 !context->internal->_initialized) {
2615 errno = EINVAL;
2616 return -1;
2620 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2622 errno = EBADF;
2623 return -1;
2627 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2629 errno = ENOTDIR;
2630 return -1;
2635 * We return the pointer here as the offset
2637 ret_val = (int)dir->dir_next;
2638 return ret_val;
2643 * A routine to run down the list and see if the entry is OK
2646 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
2647 struct smbc_dirent *dirent)
2650 /* Run down the list looking for what we want */
2652 if (dirent) {
2654 struct smbc_dir_list *tmp = list;
2656 while (tmp) {
2658 if (tmp->dirent == dirent)
2659 return tmp;
2661 tmp = tmp->next;
2667 return NULL; /* Not found, or an error */
2673 * Routine to seek on a directory
2676 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
2678 long int l_offset = offset; /* Handle problems of size */
2679 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
2680 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
2682 if (!context || !context->internal ||
2683 !context->internal->_initialized) {
2685 errno = EINVAL;
2686 return -1;
2690 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2692 errno = ENOTDIR;
2693 return -1;
2697 /* Now, check what we were passed and see if it is OK ... */
2699 if (dirent == NULL) { /* Seek to the begining of the list */
2701 dir->dir_next = dir->dir_list;
2702 return 0;
2706 /* Now, run down the list and make sure that the entry is OK */
2707 /* This may need to be changed if we change the format of the list */
2709 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
2711 errno = EINVAL; /* Bad entry */
2712 return -1;
2716 dir->dir_next = list_ent;
2718 return 0;
2723 * Routine to fstat a dir
2726 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
2729 if (!context || !context->internal ||
2730 !context->internal->_initialized) {
2732 errno = EINVAL;
2733 return -1;
2737 /* No code yet ... */
2739 return 0;
2743 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
2745 SMBCSRV *srv;
2746 fstring server, share, user, password, workgroup;
2747 pstring path;
2748 uint16 mode;
2750 if (!context || !context->internal ||
2751 !context->internal->_initialized) {
2753 errno = EINVAL; /* Best I can think of ... */
2754 return -1;
2758 if (!fname) {
2760 errno = EINVAL;
2761 return -1;
2765 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
2767 if (smbc_parse_path(context, fname,
2768 server, sizeof(server),
2769 share, sizeof(share),
2770 path, sizeof(path),
2771 user, sizeof(user),
2772 password, sizeof(password),
2773 NULL, 0)) {
2774 errno = EINVAL;
2775 return -1;
2778 if (user[0] == (char)0) fstrcpy(user, context->user);
2780 fstrcpy(workgroup, context->workgroup);
2782 srv = smbc_server(context, server, share, workgroup, user, password);
2784 if (!srv) {
2785 return -1; /* errno set by smbc_server */
2788 mode = 0;
2790 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
2791 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
2792 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
2793 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
2795 if (!cli_setatr(&srv->cli, path, mode, 0)) {
2796 errno = smbc_errno(context, &srv->cli);
2797 return -1;
2800 return 0;
2803 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
2805 SMBCSRV *srv;
2806 fstring server, share, user, password, workgroup;
2807 pstring path;
2808 uint16 mode;
2809 time_t t = (tbuf == NULL ? time(NULL) : tbuf->tv_sec);
2811 if (!context || !context->internal ||
2812 !context->internal->_initialized) {
2814 errno = EINVAL; /* Best I can think of ... */
2815 return -1;
2819 if (!fname) {
2821 errno = EINVAL;
2822 return -1;
2826 DEBUG(4, ("smbc_utimes(%s, [%s])\n", fname, ctime(&t)));
2828 if (smbc_parse_path(context, fname,
2829 server, sizeof(server),
2830 share, sizeof(share),
2831 path, sizeof(path),
2832 user, sizeof(user),
2833 password, sizeof(password),
2834 NULL, 0)) {
2835 errno = EINVAL;
2836 return -1;
2839 if (user[0] == (char)0) fstrcpy(user, context->user);
2841 fstrcpy(workgroup, context->workgroup);
2843 srv = smbc_server(context, server, share, workgroup, user, password);
2845 if (!srv) {
2846 return -1; /* errno set by smbc_server */
2849 if (!smbc_getatr(context, srv, path,
2850 &mode, NULL,
2851 NULL, NULL, NULL,
2852 NULL)) {
2853 return -1;
2856 if (!cli_setatr(&srv->cli, path, mode, t)) {
2857 /* some servers always refuse directory changes */
2858 if (!(mode & aDIR)) {
2859 errno = smbc_errno(context, &srv->cli);
2860 return -1;
2864 return 0;
2868 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
2869 However NT4 gives a "The information may have been modified by a
2870 computer running Windows NT 5.0" if denied ACEs do not appear before
2871 allowed ACEs. */
2873 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
2875 if (sec_ace_equal(ace1, ace2))
2876 return 0;
2878 if (ace1->type != ace2->type)
2879 return ace2->type - ace1->type;
2881 if (sid_compare(&ace1->trustee, &ace2->trustee))
2882 return sid_compare(&ace1->trustee, &ace2->trustee);
2884 if (ace1->flags != ace2->flags)
2885 return ace1->flags - ace2->flags;
2887 if (ace1->info.mask != ace2->info.mask)
2888 return ace1->info.mask - ace2->info.mask;
2890 if (ace1->size != ace2->size)
2891 return ace1->size - ace2->size;
2893 return memcmp(ace1, ace2, sizeof(SEC_ACE));
2897 static void sort_acl(SEC_ACL *the_acl)
2899 uint32 i;
2900 if (!the_acl) return;
2902 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
2904 for (i=1;i<the_acl->num_aces;) {
2905 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
2906 int j;
2907 for (j=i; j<the_acl->num_aces-1; j++) {
2908 the_acl->ace[j] = the_acl->ace[j+1];
2910 the_acl->num_aces--;
2911 } else {
2912 i++;
2917 /* convert a SID to a string, either numeric or username/group */
2918 static void convert_sid_to_string(struct cli_state *ipc_cli,
2919 POLICY_HND *pol,
2920 fstring str,
2921 BOOL numeric,
2922 DOM_SID *sid)
2924 char **domains = NULL;
2925 char **names = NULL;
2926 uint32 *types = NULL;
2928 sid_to_string(str, sid);
2930 if (numeric) return; /* no lookup desired */
2932 /* Ask LSA to convert the sid to a name */
2934 if (!NT_STATUS_IS_OK(cli_lsa_lookup_sids(ipc_cli, ipc_cli->mem_ctx,
2935 pol, 1, sid, &domains,
2936 &names, &types)) ||
2937 !domains || !domains[0] || !names || !names[0]) {
2938 return;
2941 /* Converted OK */
2943 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
2944 domains[0], lp_winbind_separator(),
2945 names[0]);
2948 /* convert a string to a SID, either numeric or username/group */
2949 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
2950 POLICY_HND *pol,
2951 BOOL numeric,
2952 DOM_SID *sid,
2953 const char *str)
2955 uint32 *types = NULL;
2956 DOM_SID *sids = NULL;
2957 BOOL result = True;
2959 if (numeric) {
2960 if (strncmp(str, "S-", 2) == 0) {
2961 return string_to_sid(sid, str);
2964 result = False;
2965 goto done;
2968 if (!NT_STATUS_IS_OK(cli_lsa_lookup_names(ipc_cli, ipc_cli->mem_ctx,
2969 pol, 1, &str, &sids,
2970 &types))) {
2971 result = False;
2972 goto done;
2975 sid_copy(sid, &sids[0]);
2976 done:
2978 return result;
2982 /* parse an ACE in the same format as print_ace() */
2983 static BOOL parse_ace(struct cli_state *ipc_cli,
2984 POLICY_HND *pol,
2985 SEC_ACE *ace,
2986 BOOL numeric,
2987 char *str)
2989 char *p;
2990 const char *cp;
2991 fstring tok;
2992 unsigned atype, aflags, amask;
2993 DOM_SID sid;
2994 SEC_ACCESS mask;
2995 const struct perm_value *v;
2996 struct perm_value {
2997 const char *perm;
2998 uint32 mask;
3001 /* These values discovered by inspection */
3002 static const struct perm_value special_values[] = {
3003 { "R", 0x00120089 },
3004 { "W", 0x00120116 },
3005 { "X", 0x001200a0 },
3006 { "D", 0x00010000 },
3007 { "P", 0x00040000 },
3008 { "O", 0x00080000 },
3009 { NULL, 0 },
3012 static const struct perm_value standard_values[] = {
3013 { "READ", 0x001200a9 },
3014 { "CHANGE", 0x001301bf },
3015 { "FULL", 0x001f01ff },
3016 { NULL, 0 },
3020 ZERO_STRUCTP(ace);
3021 p = strchr_m(str,':');
3022 if (!p) return False;
3023 *p = '\0';
3024 p++;
3025 /* Try to parse numeric form */
3027 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3028 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3029 goto done;
3032 /* Try to parse text form */
3034 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3035 return False;
3038 cp = p;
3039 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3040 return False;
3043 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3044 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3045 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3046 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3047 } else {
3048 return False;
3051 /* Only numeric form accepted for flags at present */
3053 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3054 sscanf(tok, "%i", &aflags))) {
3055 return False;
3058 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3059 return False;
3062 if (strncmp(tok, "0x", 2) == 0) {
3063 if (sscanf(tok, "%i", &amask) != 1) {
3064 return False;
3066 goto done;
3069 for (v = standard_values; v->perm; v++) {
3070 if (strcmp(tok, v->perm) == 0) {
3071 amask = v->mask;
3072 goto done;
3076 p = tok;
3078 while(*p) {
3079 BOOL found = False;
3081 for (v = special_values; v->perm; v++) {
3082 if (v->perm[0] == *p) {
3083 amask |= v->mask;
3084 found = True;
3088 if (!found) return False;
3089 p++;
3092 if (*p) {
3093 return False;
3096 done:
3097 mask.mask = amask;
3098 init_sec_ace(ace, &sid, atype, mask, aflags);
3099 return True;
3102 /* add an ACE to a list of ACEs in a SEC_ACL */
3103 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3105 SEC_ACL *new;
3106 SEC_ACE *aces;
3107 if (! *the_acl) {
3108 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3109 return True;
3112 aces = calloc(1+(*the_acl)->num_aces,sizeof(SEC_ACE));
3113 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3114 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3115 new = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3116 SAFE_FREE(aces);
3117 (*the_acl) = new;
3118 return True;
3122 /* parse a ascii version of a security descriptor */
3123 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3124 struct cli_state *ipc_cli,
3125 POLICY_HND *pol,
3126 BOOL numeric,
3127 char *str)
3129 const char *p = str;
3130 fstring tok;
3131 SEC_DESC *ret;
3132 size_t sd_size;
3133 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3134 SEC_ACL *dacl=NULL;
3135 int revision=1;
3137 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3139 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3140 revision = strtol(tok+9, NULL, 16);
3141 continue;
3144 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3145 owner_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3146 if (!owner_sid ||
3147 !convert_string_to_sid(ipc_cli, pol,
3148 numeric,
3149 owner_sid, tok+6)) {
3150 DEBUG(5, ("Failed to parse owner sid\n"));
3151 return NULL;
3153 continue;
3156 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3157 owner_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3158 if (!owner_sid ||
3159 !convert_string_to_sid(ipc_cli, pol,
3160 False,
3161 owner_sid, tok+7)) {
3162 DEBUG(5, ("Failed to parse owner sid\n"));
3163 return NULL;
3165 continue;
3168 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3169 grp_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3170 if (!grp_sid ||
3171 !convert_string_to_sid(ipc_cli, pol,
3172 numeric,
3173 grp_sid, tok+6)) {
3174 DEBUG(5, ("Failed to parse group sid\n"));
3175 return NULL;
3177 continue;
3180 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3181 grp_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3182 if (!grp_sid ||
3183 !convert_string_to_sid(ipc_cli, pol,
3184 False,
3185 grp_sid, tok+6)) {
3186 DEBUG(5, ("Failed to parse group sid\n"));
3187 return NULL;
3189 continue;
3192 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3193 SEC_ACE ace;
3194 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3195 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3196 return NULL;
3198 if(!add_ace(&dacl, &ace, ctx)) {
3199 DEBUG(5, ("Failed to add ACL %s\n", tok));
3200 return NULL;
3202 continue;
3205 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3206 SEC_ACE ace;
3207 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3208 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3209 return NULL;
3211 if(!add_ace(&dacl, &ace, ctx)) {
3212 DEBUG(5, ("Failed to add ACL %s\n", tok));
3213 return NULL;
3215 continue;
3218 DEBUG(5, ("Failed to parse security descriptor\n"));
3219 return NULL;
3222 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3223 owner_sid, grp_sid, NULL, dacl, &sd_size);
3225 SAFE_FREE(grp_sid);
3226 SAFE_FREE(owner_sid);
3228 return ret;
3232 /*****************************************************
3233 retrieve the acls for a file
3234 *******************************************************/
3235 static int cacl_get(TALLOC_CTX *ctx, struct cli_state *cli,
3236 struct cli_state *ipc_cli, POLICY_HND *pol,
3237 char *filename, char *name, char *buf, int bufsize)
3239 uint32 i;
3240 int n = 0;
3241 int n_used;
3242 BOOL all;
3243 BOOL numeric = True;
3244 BOOL determine_size = (bufsize == 0);
3245 int fnum = -1;
3246 SEC_DESC *sd;
3247 fstring sidstr;
3248 char *p;
3250 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3252 if (fnum == -1) {
3253 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3254 filename, cli_errstr(cli)));
3255 errno = 0;
3256 return -1;
3259 sd = cli_query_secdesc(cli, fnum, ctx);
3261 if (!sd) {
3262 DEBUG(5, ("cacl_get Failed to query old descriptor\n"));
3263 errno = 0;
3264 return -1;
3267 cli_close(cli, fnum);
3269 all = (*name == '*');
3270 numeric = (* (name + strlen(name) - 1) != '+');
3272 n_used = 0;
3274 if (all) {
3275 if (determine_size) {
3276 p = talloc_asprintf(ctx,
3277 "REVISION:%d", sd->revision);
3278 if (!p) {
3279 errno = ENOMEM;
3280 return -1;
3282 n = strlen(p);
3283 } else {
3284 n = snprintf(buf, bufsize,
3285 "REVISION:%d", sd->revision);
3287 } else if (StrCaseCmp(name, "revision") == 0) {
3288 if (determine_size) {
3289 p = talloc_asprintf(ctx, "%d", sd->revision);
3290 if (!p) {
3291 errno = ENOMEM;
3292 return -1;
3294 n = strlen(p);
3295 } else {
3296 n = snprintf(buf, bufsize, "%d", sd->revision);
3300 if (!determine_size && n > bufsize) {
3301 errno = ERANGE;
3302 return -1;
3304 buf += n;
3305 n_used += n;
3306 bufsize -= n;
3308 /* Get owner and group sid */
3310 if (sd->owner_sid) {
3311 convert_sid_to_string(ipc_cli, pol,
3312 sidstr, numeric, sd->owner_sid);
3313 } else {
3314 fstrcpy(sidstr, "");
3317 if (all) {
3318 if (determine_size) {
3319 p = talloc_asprintf(ctx, ",OWNER:%s", sidstr);
3320 if (!p) {
3321 errno = ENOMEM;
3322 return -1;
3324 n = strlen(p);
3325 } else {
3326 n = snprintf(buf, bufsize, ",OWNER:%s", sidstr);
3328 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3329 if (determine_size) {
3330 p = talloc_asprintf(ctx, "%s", sidstr);
3331 if (!p) {
3332 errno = ENOMEM;
3333 return -1;
3335 n = strlen(p);
3336 } else {
3337 n = snprintf(buf, bufsize, "%s", sidstr);
3341 if (!determine_size && n > bufsize) {
3342 errno = ERANGE;
3343 return -1;
3345 buf += n;
3346 n_used += n;
3347 bufsize -= n;
3349 if (sd->grp_sid) {
3350 convert_sid_to_string(ipc_cli, pol,
3351 sidstr, numeric, sd->grp_sid);
3352 } else {
3353 fstrcpy(sidstr, "");
3356 if (all) {
3357 if (determine_size) {
3358 p = talloc_asprintf(ctx, ",GROUP:%s", sidstr);
3359 if (!p) {
3360 errno = ENOMEM;
3361 return -1;
3363 n = strlen(p);
3364 } else {
3365 n = snprintf(buf, bufsize, ",GROUP:%s", sidstr);
3367 } else if (StrnCaseCmp(name, "group", 5) == 0) {
3368 if (determine_size) {
3369 p = talloc_asprintf(ctx, "%s", sidstr);
3370 if (!p) {
3371 errno = ENOMEM;
3372 return -1;
3374 n = strlen(p);
3375 } else {
3376 n = snprintf(buf, bufsize, "%s", sidstr);
3380 if (!determine_size && n > bufsize) {
3381 errno = ERANGE;
3382 return -1;
3384 buf += n;
3385 n_used += n;
3386 bufsize -= n;
3388 /* Add aces to value buffer */
3389 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
3391 SEC_ACE *ace = &sd->dacl->ace[i];
3392 convert_sid_to_string(ipc_cli, pol,
3393 sidstr, numeric, &ace->trustee);
3395 if (all) {
3396 if (determine_size) {
3397 p = talloc_asprintf(ctx,
3398 ",ACL:%s:%d/%d/0x%08x",
3399 sidstr,
3400 ace->type,
3401 ace->flags,
3402 ace->info.mask);
3403 if (!p) {
3404 errno = ENOMEM;
3405 return -1;
3407 n = strlen(p);
3408 } else {
3409 n = snprintf(buf, bufsize,
3410 ",ACL:%s:%d/%d/0x%08x",
3411 sidstr,
3412 ace->type,
3413 ace->flags,
3414 ace->info.mask);
3416 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
3417 StrCaseCmp(name + 3, sidstr) == 0) ||
3418 (StrnCaseCmp(name, "acl+", 4) == 0 &&
3419 StrCaseCmp(name + 4, sidstr) == 0)) {
3420 if (determine_size) {
3421 p = talloc_asprintf(ctx,
3422 "%d/%d/0x%08x",
3423 ace->type,
3424 ace->flags,
3425 ace->info.mask);
3426 if (!p) {
3427 errno = ENOMEM;
3428 return -1;
3430 n = strlen(p);
3431 } else {
3432 n = snprintf(buf, bufsize,
3433 "%d/%d/0x%08x",
3434 ace->type, ace->flags, ace->info.mask);
3437 if (n > bufsize) {
3438 errno = ERANGE;
3439 return -1;
3441 buf += n;
3442 n_used += n;
3443 bufsize -= n;
3446 if (n_used == 0) {
3447 errno = ENOATTR;
3448 return -1;
3450 return n_used;
3454 /*****************************************************
3455 set the ACLs on a file given an ascii description
3456 *******************************************************/
3457 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
3458 struct cli_state *ipc_cli, POLICY_HND *pol,
3459 const char *filename, const char *the_acl,
3460 int mode, int flags)
3462 int fnum;
3463 int err = 0;
3464 SEC_DESC *sd = NULL, *old;
3465 SEC_ACL *dacl = NULL;
3466 DOM_SID *owner_sid = NULL;
3467 DOM_SID *grp_sid = NULL;
3468 uint32 i, j;
3469 size_t sd_size;
3470 int ret = 0;
3471 char *p;
3472 BOOL numeric = True;
3474 /* the_acl will be null for REMOVE_ALL operations */
3475 if (the_acl) {
3476 numeric = ((p = strchr(the_acl, ':')) != NULL &&
3477 p > the_acl &&
3478 p[-1] != '+');
3480 /* if this is to set the entire ACL... */
3481 if (*the_acl == '*') {
3482 /* ... then increment past the first colon */
3483 the_acl = p + 1;
3486 sd = sec_desc_parse(ctx, ipc_cli, pol,
3487 numeric, (char *) the_acl);
3489 if (!sd) {
3490 errno = EINVAL;
3491 return -1;
3495 /* The desired access below is the only one I could find that works
3496 with NT4, W2KP and Samba */
3498 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3500 if (fnum == -1) {
3501 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3502 filename, cli_errstr(cli)));
3503 errno = 0;
3504 return -1;
3507 old = cli_query_secdesc(cli, fnum, ctx);
3509 if (!old) {
3510 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
3511 errno = 0;
3512 return -1;
3515 cli_close(cli, fnum);
3517 switch (mode) {
3518 case SMBC_XATTR_MODE_REMOVE_ALL:
3519 old->dacl->num_aces = 0;
3520 SAFE_FREE(old->dacl->ace);
3521 SAFE_FREE(old->dacl);
3522 old->off_dacl = 0;
3523 dacl = old->dacl;
3524 break;
3526 case SMBC_XATTR_MODE_REMOVE:
3527 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3528 BOOL found = False;
3530 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3531 if (sec_ace_equal(&sd->dacl->ace[i],
3532 &old->dacl->ace[j])) {
3533 uint32 k;
3534 for (k=j; k<old->dacl->num_aces-1;k++) {
3535 old->dacl->ace[k] = old->dacl->ace[k+1];
3537 old->dacl->num_aces--;
3538 if (old->dacl->num_aces == 0) {
3539 SAFE_FREE(old->dacl->ace);
3540 SAFE_FREE(old->dacl);
3541 old->off_dacl = 0;
3543 found = True;
3544 dacl = old->dacl;
3545 break;
3549 if (!found) {
3550 err = ENOATTR;
3551 ret = -1;
3552 goto failed;
3555 break;
3557 case SMBC_XATTR_MODE_ADD:
3558 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3559 BOOL found = False;
3561 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3562 if (sid_equal(&sd->dacl->ace[i].trustee,
3563 &old->dacl->ace[j].trustee)) {
3564 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
3565 err = EEXIST;
3566 ret = -1;
3567 goto failed;
3569 old->dacl->ace[j] = sd->dacl->ace[i];
3570 ret = -1;
3571 found = True;
3575 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
3576 err = ENOATTR;
3577 ret = -1;
3578 goto failed;
3581 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3582 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
3585 dacl = old->dacl;
3586 break;
3588 case SMBC_XATTR_MODE_SET:
3589 old = sd;
3590 owner_sid = old->owner_sid;
3591 grp_sid = old->grp_sid;
3592 dacl = old->dacl;
3593 break;
3595 case SMBC_XATTR_MODE_CHOWN:
3596 owner_sid = sd->owner_sid;
3597 break;
3599 case SMBC_XATTR_MODE_CHGRP:
3600 grp_sid = sd->grp_sid;
3601 break;
3604 /* Denied ACE entries must come before allowed ones */
3605 sort_acl(old->dacl);
3607 /* Create new security descriptor and set it */
3608 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
3609 owner_sid, grp_sid, NULL, dacl, &sd_size);
3611 fnum = cli_nt_create(cli, filename,
3612 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
3614 if (fnum == -1) {
3615 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3616 filename, cli_errstr(cli)));
3617 errno = 0;
3618 return -1;
3621 if (!cli_set_secdesc(cli, fnum, sd)) {
3622 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
3623 ret = -1;
3626 /* Clean up */
3628 failed:
3629 cli_close(cli, fnum);
3631 if (err != 0) {
3632 errno = err;
3635 return ret;
3639 int smbc_setxattr_ctx(SMBCCTX *context,
3640 const char *fname,
3641 const char *name,
3642 const void *value,
3643 size_t size,
3644 int flags)
3646 int ret;
3647 SMBCSRV *srv;
3648 SMBCSRV *ipc_srv;
3649 fstring server, share, user, password, workgroup;
3650 pstring path;
3651 TALLOC_CTX *ctx;
3652 POLICY_HND pol;
3654 if (!context || !context->internal ||
3655 !context->internal->_initialized) {
3657 errno = EINVAL; /* Best I can think of ... */
3658 return -1;
3662 if (!fname) {
3664 errno = EINVAL;
3665 return -1;
3669 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
3670 fname, name, (int) size, (char *) value));
3672 if (smbc_parse_path(context, fname,
3673 server, sizeof(server),
3674 share, sizeof(share),
3675 path, sizeof(path),
3676 user, sizeof(user),
3677 password, sizeof(password),
3678 NULL, 0)) {
3679 errno = EINVAL;
3680 return -1;
3683 if (user[0] == (char)0) fstrcpy(user, context->user);
3685 fstrcpy(workgroup, context->workgroup);
3687 srv = smbc_server(context, server, share, workgroup, user, password);
3688 if (!srv) {
3689 return -1; /* errno set by smbc_server */
3692 ipc_srv = smbc_attr_server(context, server, share,
3693 workgroup, user, password,
3694 &pol);
3695 if (!ipc_srv) {
3696 return -1;
3699 ctx = talloc_init("smbc_setxattr");
3700 if (!ctx) {
3701 errno = ENOMEM;
3702 return -1;
3706 * Are they asking to set an access control element or to set
3707 * the entire access control list?
3709 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3710 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3711 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3712 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3713 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3715 /* Yup. */
3716 char *namevalue =
3717 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3718 if (! namevalue) {
3719 errno = ENOMEM;
3720 ret = -1;
3721 } else {
3722 ret = cacl_set(ctx, &srv->cli,
3723 &ipc_srv->cli, &pol, path,
3724 namevalue,
3725 (*namevalue == '*'
3726 ? SMBC_XATTR_MODE_SET
3727 : SMBC_XATTR_MODE_ADD),
3728 flags);
3730 talloc_destroy(ctx);
3731 return ret;
3735 * Are they asking to set the owner?
3737 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3738 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
3740 /* Yup. */
3741 char *namevalue =
3742 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3743 if (! namevalue) {
3744 errno = ENOMEM;
3745 ret = -1;
3746 } else {
3747 ret = cacl_set(ctx, &srv->cli,
3748 &ipc_srv->cli, &pol, path,
3749 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3751 talloc_destroy(ctx);
3752 return ret;
3756 * Are they asking to set the group?
3758 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3759 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
3761 /* Yup. */
3762 char *namevalue =
3763 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3764 if (! namevalue) {
3765 errno = ENOMEM;
3766 ret = -1;
3767 } else {
3768 ret = cacl_set(ctx, &srv->cli,
3769 &ipc_srv->cli, &pol, path,
3770 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3772 talloc_destroy(ctx);
3773 return ret;
3776 /* Unsupported attribute name */
3777 talloc_destroy(ctx);
3778 errno = EINVAL;
3779 return -1;
3782 int smbc_getxattr_ctx(SMBCCTX *context,
3783 const char *fname,
3784 const char *name,
3785 const void *value,
3786 size_t size)
3788 int ret;
3789 SMBCSRV *srv;
3790 SMBCSRV *ipc_srv;
3791 fstring server, share, user, password, workgroup;
3792 pstring path;
3793 TALLOC_CTX *ctx;
3794 POLICY_HND pol;
3796 if (!context || !context->internal ||
3797 !context->internal->_initialized) {
3799 errno = EINVAL; /* Best I can think of ... */
3800 return -1;
3804 if (!fname) {
3806 errno = EINVAL;
3807 return -1;
3811 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
3813 if (smbc_parse_path(context, fname,
3814 server, sizeof(server),
3815 share, sizeof(share),
3816 path, sizeof(path),
3817 user, sizeof(user),
3818 password, sizeof(password),
3819 NULL, 0)) {
3820 errno = EINVAL;
3821 return -1;
3824 if (user[0] == (char)0) fstrcpy(user, context->user);
3826 fstrcpy(workgroup, context->workgroup);
3828 srv = smbc_server(context, server, share, workgroup, user, password);
3829 if (!srv) {
3830 return -1; /* errno set by smbc_server */
3833 ipc_srv = smbc_attr_server(context, server, share,
3834 workgroup, user, password,
3835 &pol);
3836 if (!ipc_srv) {
3837 return -1;
3840 ctx = talloc_init("smbc:getxattr");
3841 if (!ctx) {
3842 errno = ENOMEM;
3843 return -1;
3846 /* Are they requesting a supported attribute? */
3847 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3848 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3849 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3850 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3851 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3852 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3853 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3854 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3855 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3857 /* Yup. */
3858 ret = cacl_get(ctx, &srv->cli,
3859 &ipc_srv->cli, &pol,
3860 (char *) path, (char *) name + 19,
3861 (char *) value, size);
3862 if (ret < 0 && errno == 0) {
3863 errno = smbc_errno(context, &srv->cli);
3865 talloc_destroy(ctx);
3866 return ret;
3869 /* Unsupported attribute name */
3870 talloc_destroy(ctx);
3871 errno = EINVAL;
3872 return -1;
3876 int smbc_removexattr_ctx(SMBCCTX *context,
3877 const char *fname,
3878 const char *name)
3880 int ret;
3881 SMBCSRV *srv;
3882 SMBCSRV *ipc_srv;
3883 fstring server, share, user, password, workgroup;
3884 pstring path;
3885 TALLOC_CTX *ctx;
3886 POLICY_HND pol;
3888 if (!context || !context->internal ||
3889 !context->internal->_initialized) {
3891 errno = EINVAL; /* Best I can think of ... */
3892 return -1;
3896 if (!fname) {
3898 errno = EINVAL;
3899 return -1;
3903 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
3905 if (smbc_parse_path(context, fname,
3906 server, sizeof(server),
3907 share, sizeof(share),
3908 path, sizeof(path),
3909 user, sizeof(user),
3910 password, sizeof(password),
3911 NULL, 0)) {
3912 errno = EINVAL;
3913 return -1;
3916 if (user[0] == (char)0) fstrcpy(user, context->user);
3918 fstrcpy(workgroup, context->workgroup);
3920 srv = smbc_server(context, server, share, workgroup, user, password);
3921 if (!srv) {
3922 return -1; /* errno set by smbc_server */
3925 ipc_srv = smbc_attr_server(context, server, share,
3926 workgroup, user, password,
3927 &pol);
3928 if (!ipc_srv) {
3929 return -1;
3932 ipc_srv = smbc_attr_server(context, server, share,
3933 workgroup, user, password,
3934 &pol);
3935 if (!ipc_srv) {
3936 return -1;
3939 ctx = talloc_init("smbc_removexattr");
3940 if (!ctx) {
3941 errno = ENOMEM;
3942 return -1;
3945 /* Are they asking to set the entire ACL? */
3946 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3947 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
3949 /* Yup. */
3950 ret = cacl_set(ctx, &srv->cli,
3951 &ipc_srv->cli, &pol, path,
3952 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
3953 talloc_destroy(ctx);
3954 return ret;
3958 * Are they asking to remove one or more spceific security descriptor
3959 * attributes?
3961 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3962 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3963 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3964 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3965 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3966 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3967 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3969 /* Yup. */
3970 ret = cacl_set(ctx, &srv->cli,
3971 &ipc_srv->cli, &pol, path,
3972 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
3973 talloc_destroy(ctx);
3974 return ret;
3977 /* Unsupported attribute name */
3978 talloc_destroy(ctx);
3979 errno = EINVAL;
3980 return -1;
3983 int smbc_listxattr_ctx(SMBCCTX *context,
3984 const char *fname,
3985 char *list,
3986 size_t size)
3989 * This isn't quite what listxattr() is supposed to do. This returns
3990 * the complete set of attributes, always, rather than only those
3991 * attribute names which actually exist for a file. Hmmm...
3993 const char supported[] =
3994 "system.nt_sec_desc.revision\0"
3995 "system.nt_sec_desc.owner\0"
3996 "system.nt_sec_desc.owner+\0"
3997 "system.nt_sec_desc.group\0"
3998 "system.nt_sec_desc.group+\0"
3999 "system.nt_sec_desc.acl\0"
4000 "system.nt_sec_desc.acl+\0"
4001 "system.nt_sec_desc.*\0"
4002 "system.nt_sec_desc.*+\0"
4005 if (size == 0) {
4006 return sizeof(supported);
4009 if (sizeof(supported) > size) {
4010 errno = ERANGE;
4011 return -1;
4014 /* this can't be strcpy() because there are embedded null characters */
4015 memcpy(list, supported, sizeof(supported));
4016 return sizeof(supported);
4021 * Open a print file to be written to by other calls
4024 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
4026 fstring server, share, user, password;
4027 pstring path;
4029 if (!context || !context->internal ||
4030 !context->internal->_initialized) {
4032 errno = EINVAL;
4033 return NULL;
4037 if (!fname) {
4039 errno = EINVAL;
4040 return NULL;
4044 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
4046 if (smbc_parse_path(context, fname,
4047 server, sizeof(server),
4048 share, sizeof(share),
4049 path, sizeof(path),
4050 user, sizeof(user),
4051 password, sizeof(password),
4052 NULL, 0)) {
4053 errno = EINVAL;
4054 return NULL;
4057 /* What if the path is empty, or the file exists? */
4059 return context->open(context, fname, O_WRONLY, 666);
4064 * Routine to print a file on a remote server ...
4066 * We open the file, which we assume to be on a remote server, and then
4067 * copy it to a print file on the share specified by printq.
4070 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
4072 SMBCFILE *fid1, *fid2;
4073 int bytes, saverr, tot_bytes = 0;
4074 char buf[4096];
4076 if (!c_file || !c_file->internal->_initialized || !c_print ||
4077 !c_print->internal->_initialized) {
4079 errno = EINVAL;
4080 return -1;
4084 if (!fname && !printq) {
4086 errno = EINVAL;
4087 return -1;
4091 /* Try to open the file for reading ... */
4093 if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
4095 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
4096 return -1; /* smbc_open sets errno */
4100 /* Now, try to open the printer file for writing */
4102 if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
4104 saverr = errno; /* Save errno */
4105 c_file->close(c_file, fid1);
4106 errno = saverr;
4107 return -1;
4111 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
4113 tot_bytes += bytes;
4115 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
4117 saverr = errno;
4118 c_file->close(c_file, fid1);
4119 c_print->close(c_print, fid2);
4120 errno = saverr;
4126 saverr = errno;
4128 c_file->close(c_file, fid1); /* We have to close these anyway */
4129 c_print->close(c_print, fid2);
4131 if (bytes < 0) {
4133 errno = saverr;
4134 return -1;
4138 return tot_bytes;
4143 * Routine to list print jobs on a printer share ...
4146 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
4148 SMBCSRV *srv;
4149 fstring server, share, user, password, workgroup;
4150 pstring path;
4152 if (!context || !context->internal ||
4153 !context->internal->_initialized) {
4155 errno = EINVAL;
4156 return -1;
4160 if (!fname) {
4162 errno = EINVAL;
4163 return -1;
4167 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
4169 if (smbc_parse_path(context, fname,
4170 server, sizeof(server),
4171 share, sizeof(share),
4172 path, sizeof(path),
4173 user, sizeof(user),
4174 password, sizeof(password),
4175 NULL, 0)) {
4176 errno = EINVAL;
4177 return -1;
4180 if (user[0] == (char)0) fstrcpy(user, context->user);
4182 fstrcpy(workgroup, context->workgroup);
4184 srv = smbc_server(context, server, share, workgroup, user, password);
4186 if (!srv) {
4188 return -1; /* errno set by smbc_server */
4192 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
4194 errno = smbc_errno(context, &srv->cli);
4195 return -1;
4199 return 0;
4204 * Delete a print job from a remote printer share
4207 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
4209 SMBCSRV *srv;
4210 fstring server, share, user, password, workgroup;
4211 pstring path;
4212 int err;
4214 if (!context || !context->internal ||
4215 !context->internal->_initialized) {
4217 errno = EINVAL;
4218 return -1;
4222 if (!fname) {
4224 errno = EINVAL;
4225 return -1;
4229 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
4231 if (smbc_parse_path(context, fname,
4232 server, sizeof(server),
4233 share, sizeof(share),
4234 path, sizeof(path),
4235 user, sizeof(user),
4236 password, sizeof(password),
4237 NULL, 0)) {
4238 errno = EINVAL;
4239 return -1;
4242 if (user[0] == (char)0) fstrcpy(user, context->user);
4244 fstrcpy(workgroup, context->workgroup);
4246 srv = smbc_server(context, server, share, workgroup, user, password);
4248 if (!srv) {
4250 return -1; /* errno set by smbc_server */
4254 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
4256 if (err < 0)
4257 errno = smbc_errno(context, &srv->cli);
4258 else if (err == ERRnosuchprintjob)
4259 errno = EINVAL;
4260 return -1;
4264 return 0;
4269 * Get a new empty handle to fill in with your own info
4271 SMBCCTX * smbc_new_context(void)
4273 SMBCCTX * context;
4275 context = malloc(sizeof(SMBCCTX));
4276 if (!context) {
4277 errno = ENOMEM;
4278 return NULL;
4281 ZERO_STRUCTP(context);
4283 context->internal = malloc(sizeof(struct smbc_internal_data));
4284 if (!context->internal) {
4285 errno = ENOMEM;
4286 return NULL;
4289 ZERO_STRUCTP(context->internal);
4292 /* ADD REASONABLE DEFAULTS */
4293 context->debug = 0;
4294 context->timeout = 20000; /* 20 seconds */
4296 context->open = smbc_open_ctx;
4297 context->creat = smbc_creat_ctx;
4298 context->read = smbc_read_ctx;
4299 context->write = smbc_write_ctx;
4300 context->close = smbc_close_ctx;
4301 context->unlink = smbc_unlink_ctx;
4302 context->rename = smbc_rename_ctx;
4303 context->lseek = smbc_lseek_ctx;
4304 context->stat = smbc_stat_ctx;
4305 context->fstat = smbc_fstat_ctx;
4306 context->opendir = smbc_opendir_ctx;
4307 context->closedir = smbc_closedir_ctx;
4308 context->readdir = smbc_readdir_ctx;
4309 context->getdents = smbc_getdents_ctx;
4310 context->mkdir = smbc_mkdir_ctx;
4311 context->rmdir = smbc_rmdir_ctx;
4312 context->telldir = smbc_telldir_ctx;
4313 context->lseekdir = smbc_lseekdir_ctx;
4314 context->fstatdir = smbc_fstatdir_ctx;
4315 context->chmod = smbc_chmod_ctx;
4316 context->utimes = smbc_utimes_ctx;
4317 context->setxattr = smbc_setxattr_ctx;
4318 context->getxattr = smbc_getxattr_ctx;
4319 context->removexattr = smbc_removexattr_ctx;
4320 context->listxattr = smbc_listxattr_ctx;
4321 context->open_print_job = smbc_open_print_job_ctx;
4322 context->print_file = smbc_print_file_ctx;
4323 context->list_print_jobs = smbc_list_print_jobs_ctx;
4324 context->unlink_print_job = smbc_unlink_print_job_ctx;
4326 context->callbacks.check_server_fn = smbc_check_server;
4327 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
4329 smbc_default_cache_functions(context);
4331 return context;
4335 * Free a context
4337 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
4338 * and thus you'll be leaking memory if not handled properly.
4341 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
4343 if (!context) {
4344 errno = EBADF;
4345 return 1;
4348 if (shutdown_ctx) {
4349 SMBCFILE * f;
4350 DEBUG(1,("Performing aggressive shutdown.\n"));
4352 f = context->internal->_files;
4353 while (f) {
4354 context->close(context, f);
4355 f = f->next;
4357 context->internal->_files = NULL;
4359 /* First try to remove the servers the nice way. */
4360 if (context->callbacks.purge_cached_fn(context)) {
4361 SMBCSRV * s;
4362 SMBCSRV * next;
4363 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
4364 s = context->internal->_servers;
4365 while (s) {
4366 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
4367 cli_shutdown(&s->cli);
4368 context->callbacks.remove_cached_srv_fn(context, s);
4369 next = s->next;
4370 DLIST_REMOVE(context->internal->_servers, s);
4371 SAFE_FREE(s);
4372 s = next;
4374 context->internal->_servers = NULL;
4377 else {
4378 /* This is the polite way */
4379 if (context->callbacks.purge_cached_fn(context)) {
4380 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
4381 errno = EBUSY;
4382 return 1;
4384 if (context->internal->_servers) {
4385 DEBUG(1, ("Active servers in context, free_context failed.\n"));
4386 errno = EBUSY;
4387 return 1;
4389 if (context->internal->_files) {
4390 DEBUG(1, ("Active files in context, free_context failed.\n"));
4391 errno = EBUSY;
4392 return 1;
4396 /* Things we have to clean up */
4397 SAFE_FREE(context->workgroup);
4398 SAFE_FREE(context->netbios_name);
4399 SAFE_FREE(context->user);
4401 DEBUG(3, ("Context %p succesfully freed\n", context));
4402 SAFE_FREE(context->internal);
4403 SAFE_FREE(context);
4404 return 0;
4409 * Initialise the library etc
4411 * We accept a struct containing handle information.
4412 * valid values for info->debug from 0 to 100,
4413 * and insist that info->fn must be non-null.
4415 SMBCCTX * smbc_init_context(SMBCCTX * context)
4417 pstring conf;
4418 int pid;
4419 char *user = NULL, *home = NULL;
4421 if (!context || !context->internal) {
4422 errno = EBADF;
4423 return NULL;
4426 /* Do not initialise the same client twice */
4427 if (context->internal->_initialized) {
4428 return 0;
4431 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
4433 errno = EINVAL;
4434 return NULL;
4438 if (!smbc_initialized) {
4439 /* Do some library wide intialisations the first time we get called */
4441 /* Set this to what the user wants */
4442 DEBUGLEVEL = context->debug;
4444 setup_logging( "libsmbclient", True);
4446 /* Here we would open the smb.conf file if needed ... */
4448 home = getenv("HOME");
4450 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
4452 load_interfaces(); /* Load the list of interfaces ... */
4454 in_client = True; /* FIXME, make a param */
4456 if (!lp_load(conf, True, False, False)) {
4459 * Well, if that failed, try the dyn_CONFIGFILE
4460 * Which points to the standard locn, and if that
4461 * fails, silently ignore it and use the internal
4462 * defaults ...
4465 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
4466 DEBUG(5, ("Could not load either config file: %s or %s\n",
4467 conf, dyn_CONFIGFILE));
4471 reopen_logs(); /* Get logging working ... */
4474 * Block SIGPIPE (from lib/util_sock.c: write())
4475 * It is not needed and should not stop execution
4477 BlockSignals(True, SIGPIPE);
4479 /* Done with one-time initialisation */
4480 smbc_initialized = 1;
4484 if (!context->user) {
4486 * FIXME: Is this the best way to get the user info?
4488 user = getenv("USER");
4489 /* walk around as "guest" if no username can be found */
4490 if (!user) context->user = strdup("guest");
4491 else context->user = strdup(user);
4494 if (!context->netbios_name) {
4496 * We try to get our netbios name from the config. If that fails we fall
4497 * back on constructing our netbios name from our hostname etc
4499 if (global_myname()) {
4500 context->netbios_name = strdup(global_myname());
4502 else {
4504 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
4506 pid = sys_getpid();
4507 context->netbios_name = malloc(17);
4508 if (!context->netbios_name) {
4509 errno = ENOMEM;
4510 return NULL;
4512 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
4516 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
4518 if (!context->workgroup) {
4519 if (lp_workgroup()) {
4520 context->workgroup = strdup(lp_workgroup());
4522 else {
4523 /* TODO: Think about a decent default workgroup */
4524 context->workgroup = strdup("samba");
4528 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
4530 /* shortest timeout is 1 second */
4531 if (context->timeout > 0 && context->timeout < 1000)
4532 context->timeout = 1000;
4535 * FIXME: Should we check the function pointers here?
4538 context->internal->_initialized = 1;
4540 return context;