r4348: syncing up for 3.0.11pre1
[Samba.git] / source / libsmb / libsmbclient.c
blobdf9c4ddcadcd8866df60fc473c8028124f295a68
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*)SMB_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 cli_shutdown(&c);
600 errno = ENETUNREACH;
601 return NULL;
605 if (!cli_session_request(&c, &calling, &called)) {
606 cli_shutdown(&c);
607 if (strcmp(called.name, "*SMBSERVER")) {
608 make_nmb_name(&called , "*SMBSERVER", 0x20);
609 goto again;
611 else { /* Try one more time, but ensure we don't loop */
613 /* Only try this if server is an IP address ... */
615 if (is_ipaddress(server) && !tried_reverse) {
616 fstring remote_name;
617 struct in_addr rem_ip;
619 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
620 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
621 errno = ENOENT;
622 return NULL;
625 tried_reverse++; /* Yuck */
627 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
628 make_nmb_name(&called, remote_name, 0x20);
629 goto again;
635 errno = ENOENT;
636 return NULL;
639 DEBUG(4,(" session request ok\n"));
641 if (!cli_negprot(&c)) {
642 cli_shutdown(&c);
643 errno = ENOENT;
644 return NULL;
647 if (!cli_session_setup(&c, username,
648 password, strlen(password),
649 password, strlen(password),
650 workgroup) &&
651 /* try an anonymous login if it failed */
652 !cli_session_setup(&c, "", "", 1,"", 0, workgroup)) {
653 cli_shutdown(&c);
654 errno = EPERM;
655 return NULL;
658 DEBUG(4,(" session setup ok\n"));
660 if (!cli_send_tconX(&c, share, "?????",
661 password, strlen(password)+1)) {
662 errno = smbc_errno(context, &c);
663 cli_shutdown(&c);
664 return NULL;
667 DEBUG(4,(" tconx ok\n"));
670 * Ok, we have got a nice connection
671 * Let's find a free server_fd
674 srv = SMB_MALLOC_P(SMBCSRV);
675 if (!srv) {
676 errno = ENOMEM;
677 goto failed;
680 ZERO_STRUCTP(srv);
681 srv->cli = c;
682 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
684 /* now add it to the cache (internal or external) */
685 /* Let the cache function set errno if it wants to */
686 errno = 0;
687 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
688 int saved_errno = errno;
689 DEBUG(3, (" Failed to add server to cache\n"));
690 errno = saved_errno;
691 if (errno == 0) {
692 errno = ENOMEM;
694 goto failed;
697 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
698 server, share, srv));
700 DLIST_ADD(context->internal->_servers, srv);
701 return srv;
703 failed:
704 cli_shutdown(&c);
705 if (!srv) return NULL;
707 SAFE_FREE(srv);
708 return NULL;
712 * Connect to a server for getting/setting attributes, possibly on an existing
713 * connection. This works similarly to smbc_server().
715 SMBCSRV *smbc_attr_server(SMBCCTX *context,
716 const char *server, const char *share,
717 fstring workgroup,
718 fstring username, fstring password,
719 POLICY_HND *pol)
721 struct in_addr ip;
722 struct cli_state *ipc_cli;
723 NTSTATUS nt_status;
724 SMBCSRV *ipc_srv=NULL;
727 * See if we've already created this special connection. Reference
728 * our "special" share name 'IPC$$'.
730 ipc_srv = find_server(context, server, "IPC$$",
731 workgroup, username, password);
732 if (!ipc_srv) {
734 /* We didn't find a cached connection. Get the password */
735 if (*password == '\0') {
736 /* ... then retrieve it now. */
737 context->callbacks.auth_fn(server, share,
738 workgroup, sizeof(fstring),
739 username, sizeof(fstring),
740 password, sizeof(fstring));
743 zero_ip(&ip);
744 nt_status = cli_full_connection(&ipc_cli,
745 global_myname(), server,
746 &ip, 0, "IPC$", "?????",
747 username, workgroup,
748 password, 0,
749 Undefined, NULL);
750 if (! NT_STATUS_IS_OK(nt_status)) {
751 DEBUG(1,("cli_full_connection failed! (%s)\n",
752 nt_errstr(nt_status)));
753 errno = ENOTSUP;
754 return NULL;
757 if (!cli_nt_session_open(ipc_cli, PI_LSARPC)) {
758 DEBUG(1, ("cli_nt_session_open fail!\n"));
759 errno = ENOTSUP;
760 cli_shutdown(ipc_cli);
761 return NULL;
764 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
765 but NT sends 0x2000000 so we might as well do it too. */
767 nt_status = cli_lsa_open_policy(ipc_cli,
768 ipc_cli->mem_ctx,
769 True,
770 GENERIC_EXECUTE_ACCESS,
771 pol);
773 if (!NT_STATUS_IS_OK(nt_status)) {
774 errno = smbc_errno(context, ipc_cli);
775 cli_shutdown(ipc_cli);
776 return NULL;
779 ipc_srv = SMB_MALLOC_P(SMBCSRV);
780 if (!ipc_srv) {
781 errno = ENOMEM;
782 cli_shutdown(ipc_cli);
783 return NULL;
786 ZERO_STRUCTP(ipc_srv);
787 ipc_srv->cli = *ipc_cli;
789 free(ipc_cli);
791 /* now add it to the cache (internal or external) */
793 errno = 0; /* let cache function set errno if it likes */
794 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
795 server,
796 "IPC$$",
797 workgroup,
798 username)) {
799 DEBUG(3, (" Failed to add server to cache\n"));
800 if (errno == 0) {
801 errno = ENOMEM;
803 cli_shutdown(&ipc_srv->cli);
804 free(ipc_srv);
805 return NULL;
808 DLIST_ADD(context->internal->_servers, ipc_srv);
811 return ipc_srv;
815 * Routine to open() a file ...
818 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
820 fstring server, share, user, password, workgroup;
821 pstring path;
822 SMBCSRV *srv = NULL;
823 SMBCFILE *file = NULL;
824 int fd;
826 if (!context || !context->internal ||
827 !context->internal->_initialized) {
829 errno = EINVAL; /* Best I can think of ... */
830 return NULL;
834 if (!fname) {
836 errno = EINVAL;
837 return NULL;
841 if (smbc_parse_path(context, fname,
842 server, sizeof(server),
843 share, sizeof(share),
844 path, sizeof(path),
845 user, sizeof(user),
846 password, sizeof(password),
847 NULL, 0)) {
848 errno = EINVAL;
849 return NULL;
852 if (user[0] == (char)0) fstrcpy(user, context->user);
854 fstrcpy(workgroup, context->workgroup);
856 srv = smbc_server(context, server, share, workgroup, user, password);
858 if (!srv) {
860 if (errno == EPERM) errno = EACCES;
861 return NULL; /* smbc_server sets errno */
865 /* Hmmm, the test for a directory is suspect here ... FIXME */
867 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
869 fd = -1;
872 else {
874 file = SMB_MALLOC_P(SMBCFILE);
876 if (!file) {
878 errno = ENOMEM;
879 return NULL;
883 ZERO_STRUCTP(file);
885 if ((fd = cli_open(&srv->cli, path, flags, DENY_NONE)) < 0) {
887 /* Handle the error ... */
889 SAFE_FREE(file);
890 errno = smbc_errno(context, &srv->cli);
891 return NULL;
895 /* Fill in file struct */
897 file->cli_fd = fd;
898 file->fname = SMB_STRDUP(fname);
899 file->srv = srv;
900 file->offset = 0;
901 file->file = True;
903 DLIST_ADD(context->internal->_files, file);
904 return file;
908 /* Check if opendir needed ... */
910 if (fd == -1) {
911 int eno = 0;
913 eno = smbc_errno(context, &srv->cli);
914 file = context->opendir(context, fname);
915 if (!file) errno = eno;
916 return file;
920 errno = EINVAL; /* FIXME, correct errno ? */
921 return NULL;
926 * Routine to create a file
929 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
931 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
934 if (!context || !context->internal ||
935 !context->internal->_initialized) {
937 errno = EINVAL;
938 return NULL;
942 return smbc_open_ctx(context, path, creat_bits, mode);
946 * Routine to read() a file ...
949 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
951 int ret;
953 if (!context || !context->internal ||
954 !context->internal->_initialized) {
956 errno = EINVAL;
957 return -1;
961 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
963 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
965 errno = EBADF;
966 return -1;
970 /* Check that the buffer exists ... */
972 if (buf == NULL) {
974 errno = EINVAL;
975 return -1;
979 ret = cli_read(&file->srv->cli, file->cli_fd, buf, file->offset, count);
981 if (ret < 0) {
983 errno = smbc_errno(context, &file->srv->cli);
984 return -1;
988 file->offset += ret;
990 DEBUG(4, (" --> %d\n", ret));
992 return ret; /* Success, ret bytes of data ... */
997 * Routine to write() a file ...
1000 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1002 int ret;
1004 if (!context || !context->internal ||
1005 !context->internal->_initialized) {
1007 errno = EINVAL;
1008 return -1;
1012 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1014 errno = EBADF;
1015 return -1;
1019 /* Check that the buffer exists ... */
1021 if (buf == NULL) {
1023 errno = EINVAL;
1024 return -1;
1028 ret = cli_write(&file->srv->cli, file->cli_fd, 0, buf, file->offset, count);
1030 if (ret <= 0) {
1032 errno = smbc_errno(context, &file->srv->cli);
1033 return -1;
1037 file->offset += ret;
1039 return ret; /* Success, 0 bytes of data ... */
1043 * Routine to close() a file ...
1046 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1048 SMBCSRV *srv;
1050 if (!context || !context->internal ||
1051 !context->internal->_initialized) {
1053 errno = EINVAL;
1054 return -1;
1058 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1060 errno = EBADF;
1061 return -1;
1065 /* IS a dir ... */
1066 if (!file->file) {
1068 return context->closedir(context, file);
1072 if (!cli_close(&file->srv->cli, file->cli_fd)) {
1074 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1075 file->fname));
1076 /* Deallocate slot and remove the server
1077 * from the server cache if unused */
1078 errno = smbc_errno(context, &file->srv->cli);
1079 srv = file->srv;
1080 DLIST_REMOVE(context->internal->_files, file);
1081 SAFE_FREE(file->fname);
1082 SAFE_FREE(file);
1083 context->callbacks.remove_unused_server_fn(context, srv);
1085 return -1;
1089 DLIST_REMOVE(context->internal->_files, file);
1090 SAFE_FREE(file->fname);
1091 SAFE_FREE(file);
1093 return 0;
1097 * Get info from an SMB server on a file. Use a qpathinfo call first
1098 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1100 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1101 uint16 *mode, size_t *size,
1102 time_t *c_time, time_t *a_time, time_t *m_time,
1103 SMB_INO_T *ino)
1106 if (!context || !context->internal ||
1107 !context->internal->_initialized) {
1109 errno = EINVAL;
1110 return -1;
1114 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1116 if (!srv->no_pathinfo2 &&
1117 cli_qpathinfo2(&srv->cli, path, c_time, a_time, m_time, NULL,
1118 size, mode, ino)) return True;
1120 /* if this is NT then don't bother with the getatr */
1121 if (srv->cli.capabilities & CAP_NT_SMBS) {
1122 errno = EPERM;
1123 return False;
1126 if (cli_getatr(&srv->cli, path, mode, size, m_time)) {
1127 a_time = c_time = m_time;
1128 srv->no_pathinfo2 = True;
1129 return True;
1132 errno = EPERM;
1133 return False;
1138 * Routine to unlink() a file
1141 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1143 fstring server, share, user, password, workgroup;
1144 pstring path;
1145 SMBCSRV *srv = NULL;
1147 if (!context || !context->internal ||
1148 !context->internal->_initialized) {
1150 errno = EINVAL; /* Best I can think of ... */
1151 return -1;
1155 if (!fname) {
1157 errno = EINVAL;
1158 return -1;
1162 if (smbc_parse_path(context, fname,
1163 server, sizeof(server),
1164 share, sizeof(share),
1165 path, sizeof(path),
1166 user, sizeof(user),
1167 password, sizeof(password),
1168 NULL, 0)) {
1169 errno = EINVAL;
1170 return -1;
1173 if (user[0] == (char)0) fstrcpy(user, context->user);
1175 fstrcpy(workgroup, context->workgroup);
1177 srv = smbc_server(context, server, share, workgroup, user, password);
1179 if (!srv) {
1181 return -1; /* smbc_server sets errno */
1185 /* if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
1187 int job = smbc_stat_printjob(srv, path, NULL, NULL);
1188 if (job == -1) {
1190 return -1;
1193 if ((err = cli_printjob_del(&srv->cli, job)) != 0) {
1196 return -1;
1199 } else */
1201 if (!cli_unlink(&srv->cli, path)) {
1203 errno = smbc_errno(context, &srv->cli);
1205 if (errno == EACCES) { /* Check if the file is a directory */
1207 int saverr = errno;
1208 size_t size = 0;
1209 uint16 mode = 0;
1210 time_t m_time = 0, a_time = 0, c_time = 0;
1211 SMB_INO_T ino = 0;
1213 if (!smbc_getatr(context, srv, path, &mode, &size,
1214 &c_time, &a_time, &m_time, &ino)) {
1216 /* Hmmm, bad error ... What? */
1218 errno = smbc_errno(context, &srv->cli);
1219 return -1;
1222 else {
1224 if (IS_DOS_DIR(mode))
1225 errno = EISDIR;
1226 else
1227 errno = saverr; /* Restore this */
1232 return -1;
1236 return 0; /* Success ... */
1241 * Routine to rename() a file
1244 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1245 SMBCCTX *ncontext, const char *nname)
1247 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1248 pstring path1, path2;
1249 SMBCSRV *srv = NULL;
1251 if (!ocontext || !ncontext ||
1252 !ocontext->internal || !ncontext->internal ||
1253 !ocontext->internal->_initialized ||
1254 !ncontext->internal->_initialized) {
1256 errno = EINVAL; /* Best I can think of ... */
1257 return -1;
1261 if (!oname || !nname) {
1263 errno = EINVAL;
1264 return -1;
1268 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1270 smbc_parse_path(ocontext, oname,
1271 server1, sizeof(server1),
1272 share1, sizeof(share1),
1273 path1, sizeof(path1),
1274 user1, sizeof(user1),
1275 password1, sizeof(password1),
1276 NULL, 0);
1278 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1280 smbc_parse_path(ncontext, nname,
1281 server2, sizeof(server2),
1282 share2, sizeof(share2),
1283 path2, sizeof(path2),
1284 user2, sizeof(user2),
1285 password2, sizeof(password2),
1286 NULL, 0);
1288 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1290 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1291 strcmp(user1, user2)) {
1293 /* Can't rename across file systems, or users?? */
1295 errno = EXDEV;
1296 return -1;
1300 fstrcpy(workgroup, ocontext->workgroup);
1301 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1302 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1303 if (!srv) {
1305 return -1;
1309 if (!cli_rename(&srv->cli, path1, path2)) {
1310 int eno = smbc_errno(ocontext, &srv->cli);
1312 if (eno != EEXIST ||
1313 !cli_unlink(&srv->cli, path2) ||
1314 !cli_rename(&srv->cli, path1, path2)) {
1316 errno = eno;
1317 return -1;
1322 return 0; /* Success */
1327 * A routine to lseek() a file
1330 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1332 size_t size;
1334 if (!context || !context->internal ||
1335 !context->internal->_initialized) {
1337 errno = EINVAL;
1338 return -1;
1342 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1344 errno = EBADF;
1345 return -1;
1349 if (!file->file) {
1351 errno = EINVAL;
1352 return -1; /* Can't lseek a dir ... */
1356 switch (whence) {
1357 case SEEK_SET:
1358 file->offset = offset;
1359 break;
1361 case SEEK_CUR:
1362 file->offset += offset;
1363 break;
1365 case SEEK_END:
1366 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
1367 NULL, NULL, NULL))
1369 SMB_BIG_UINT b_size = size;
1370 if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
1371 NULL))
1373 errno = EINVAL;
1374 return -1;
1375 } else
1376 size = b_size;
1378 file->offset = size + offset;
1379 break;
1381 default:
1382 errno = EINVAL;
1383 break;
1387 return file->offset;
1392 * Generate an inode number from file name for those things that need it
1395 static
1396 ino_t smbc_inode(SMBCCTX *context, const char *name)
1399 if (!context || !context->internal ||
1400 !context->internal->_initialized) {
1402 errno = EINVAL;
1403 return -1;
1407 if (!*name) return 2; /* FIXME, why 2 ??? */
1408 return (ino_t)str_checksum(name);
1413 * Routine to put basic stat info into a stat structure ... Used by stat and
1414 * fstat below.
1417 static
1418 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname, size_t size, int mode)
1421 st->st_mode = 0;
1423 if (IS_DOS_DIR(mode)) {
1424 st->st_mode = SMBC_DIR_MODE;
1425 } else {
1426 st->st_mode = SMBC_FILE_MODE;
1429 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1430 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1431 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1432 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1434 st->st_size = size;
1435 #ifdef HAVE_STAT_ST_BLKSIZE
1436 st->st_blksize = 512;
1437 #endif
1438 #ifdef HAVE_STAT_ST_BLOCKS
1439 st->st_blocks = (size+511)/512;
1440 #endif
1441 st->st_uid = getuid();
1442 st->st_gid = getgid();
1444 if (IS_DOS_DIR(mode)) {
1445 st->st_nlink = 2;
1446 } else {
1447 st->st_nlink = 1;
1450 if (st->st_ino == 0) {
1451 st->st_ino = smbc_inode(context, fname);
1454 return True; /* FIXME: Is this needed ? */
1459 * Routine to stat a file given a name
1462 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1464 SMBCSRV *srv;
1465 fstring server, share, user, password, workgroup;
1466 pstring path;
1467 time_t m_time = 0, a_time = 0, c_time = 0;
1468 size_t size = 0;
1469 uint16 mode = 0;
1470 SMB_INO_T ino = 0;
1472 if (!context || !context->internal ||
1473 !context->internal->_initialized) {
1475 errno = EINVAL; /* Best I can think of ... */
1476 return -1;
1480 if (!fname) {
1482 errno = EINVAL;
1483 return -1;
1487 DEBUG(4, ("smbc_stat(%s)\n", fname));
1489 if (smbc_parse_path(context, fname,
1490 server, sizeof(server),
1491 share, sizeof(share),
1492 path, sizeof(path),
1493 user, sizeof(user),
1494 password, sizeof(password),
1495 NULL, 0)) {
1496 errno = EINVAL;
1497 return -1;
1500 if (user[0] == (char)0) fstrcpy(user, context->user);
1502 fstrcpy(workgroup, context->workgroup);
1504 srv = smbc_server(context, server, share, workgroup, user, password);
1506 if (!srv) {
1507 return -1; /* errno set by smbc_server */
1510 if (!smbc_getatr(context, srv, path, &mode, &size,
1511 &c_time, &a_time, &m_time, &ino)) {
1513 errno = smbc_errno(context, &srv->cli);
1514 return -1;
1518 st->st_ino = ino;
1520 smbc_setup_stat(context, st, path, size, mode);
1522 st->st_atime = a_time;
1523 st->st_ctime = c_time;
1524 st->st_mtime = m_time;
1525 st->st_dev = srv->dev;
1527 return 0;
1532 * Routine to stat a file given an fd
1535 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1537 time_t c_time, a_time, m_time;
1538 size_t size;
1539 uint16 mode;
1540 SMB_INO_T ino = 0;
1542 if (!context || !context->internal ||
1543 !context->internal->_initialized) {
1545 errno = EINVAL;
1546 return -1;
1550 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1552 errno = EBADF;
1553 return -1;
1557 if (!file->file) {
1559 return context->fstatdir(context, file, st);
1563 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
1564 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
1565 SMB_BIG_UINT b_size = size;
1566 if (!cli_getattrE(&file->srv->cli, file->cli_fd,
1567 &mode, &b_size, &c_time, &a_time, &m_time)) {
1569 errno = EINVAL;
1570 return -1;
1571 } else
1572 size = b_size;
1576 st->st_ino = ino;
1578 smbc_setup_stat(context, st, file->fname, size, mode);
1580 st->st_atime = a_time;
1581 st->st_ctime = c_time;
1582 st->st_mtime = m_time;
1583 st->st_dev = file->srv->dev;
1585 return 0;
1590 * Routine to open a directory
1591 * We accept the URL syntax explained in smbc_parse_path(), above.
1594 static void smbc_remove_dir(SMBCFILE *dir)
1596 struct smbc_dir_list *d,*f;
1598 d = dir->dir_list;
1599 while (d) {
1601 f = d; d = d->next;
1603 SAFE_FREE(f->dirent);
1604 SAFE_FREE(f);
1608 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
1612 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
1614 struct smbc_dirent *dirent;
1615 int size;
1616 char *u_name = NULL, *u_comment = NULL;
1617 size_t u_name_len = 0, u_comment_len = 0;
1619 if (name)
1620 u_name_len = push_utf8_allocate(&u_name, name);
1621 if (comment)
1622 u_comment_len = push_utf8_allocate(&u_comment, comment);
1625 * Allocate space for the dirent, which must be increased by the
1626 * size of the name and the comment and 1 for the null on the comment.
1627 * The null on the name is already accounted for.
1630 size = sizeof(struct smbc_dirent) + u_name_len + u_comment_len + 1;
1632 dirent = SMB_MALLOC(size);
1634 if (!dirent) {
1636 dir->dir_error = ENOMEM;
1637 return -1;
1641 ZERO_STRUCTP(dirent);
1643 if (dir->dir_list == NULL) {
1645 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
1646 if (!dir->dir_list) {
1648 SAFE_FREE(dirent);
1649 dir->dir_error = ENOMEM;
1650 return -1;
1653 ZERO_STRUCTP(dir->dir_list);
1655 dir->dir_end = dir->dir_next = dir->dir_list;
1657 else {
1659 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
1661 if (!dir->dir_end->next) {
1663 SAFE_FREE(dirent);
1664 dir->dir_error = ENOMEM;
1665 return -1;
1668 ZERO_STRUCTP(dir->dir_end->next);
1670 dir->dir_end = dir->dir_end->next;
1673 dir->dir_end->next = NULL;
1674 dir->dir_end->dirent = dirent;
1676 dirent->smbc_type = type;
1677 dirent->namelen = u_name_len;
1678 dirent->commentlen = u_comment_len;
1679 dirent->dirlen = size;
1681 strncpy(dirent->name, (u_name?u_name:""), dirent->namelen + 1);
1683 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
1684 strncpy(dirent->comment, (u_comment?u_comment:""), dirent->commentlen + 1);
1686 SAFE_FREE(u_comment);
1687 SAFE_FREE(u_name);
1689 return 0;
1693 static void
1694 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
1696 SMBCFILE *dir = (SMBCFILE *)state;
1697 struct smbc_dir_list *dir_list;
1698 struct smbc_dirent *dirent;
1699 int dirent_type;
1700 int do_remove = 0;
1702 dirent_type = dir->dir_type;
1704 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1706 /* An error occurred, what do we do? */
1707 /* FIXME: Add some code here */
1710 /* Point to the one just added */
1711 dirent = dir->dir_end->dirent;
1713 /* See if this was a duplicate */
1714 for (dir_list = dir->dir_list;
1715 dir_list != dir->dir_end;
1716 dir_list = dir_list->next) {
1717 if (! do_remove &&
1718 strcmp(dir_list->dirent->name, dirent->name) == 0) {
1719 /* Duplicate. End end of list need to be removed. */
1720 do_remove = 1;
1723 if (do_remove && dir_list->next == dir->dir_end) {
1724 /* Found the end of the list. Remove it. */
1725 dir->dir_end = dir_list;
1726 free(dir_list->next);
1727 dir_list->next = NULL;
1728 break;
1733 static void
1734 list_fn(const char *name, uint32 type, const char *comment, void *state)
1736 SMBCFILE *dir = (SMBCFILE *)state;
1737 int dirent_type;
1739 /* We need to process the type a little ... */
1741 if (dir->dir_type == SMBC_FILE_SHARE) {
1743 switch (type) {
1744 case 0: /* Directory tree */
1745 dirent_type = SMBC_FILE_SHARE;
1746 break;
1748 case 1:
1749 dirent_type = SMBC_PRINTER_SHARE;
1750 break;
1752 case 2:
1753 dirent_type = SMBC_COMMS_SHARE;
1754 break;
1756 case 3:
1757 dirent_type = SMBC_IPC_SHARE;
1758 break;
1760 default:
1761 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
1762 break;
1765 else dirent_type = dir->dir_type;
1767 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1769 /* An error occurred, what do we do? */
1770 /* FIXME: Add some code here */
1775 static void
1776 dir_list_fn(file_info *finfo, const char *mask, void *state)
1779 if (add_dirent((SMBCFILE *)state, finfo->name, "",
1780 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
1782 /* Handle an error ... */
1784 /* FIXME: Add some code ... */
1790 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
1792 fstring server, share, user, password, options;
1793 pstring workgroup;
1794 pstring path;
1795 SMBCSRV *srv = NULL;
1796 SMBCFILE *dir = NULL;
1797 struct in_addr rem_ip;
1799 if (!context || !context->internal ||
1800 !context->internal->_initialized) {
1801 DEBUG(4, ("no valid context\n"));
1802 errno = EINVAL;
1803 return NULL;
1807 if (!fname) {
1808 DEBUG(4, ("no valid fname\n"));
1809 errno = EINVAL;
1810 return NULL;
1813 if (smbc_parse_path(context, fname,
1814 server, sizeof(server),
1815 share, sizeof(share),
1816 path, sizeof(path),
1817 user, sizeof(user),
1818 password, sizeof(password),
1819 options, sizeof(options))) {
1820 DEBUG(4, ("no valid path\n"));
1821 errno = EINVAL;
1822 return NULL;
1825 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
1827 /* Ensure the options are valid */
1828 if (smbc_check_options(server, share, path, options)) {
1829 DEBUG(4, ("unacceptable options (%s)\n", options));
1830 errno = EINVAL;
1831 return NULL;
1834 if (user[0] == (char)0) fstrcpy(user, context->user);
1836 pstrcpy(workgroup, context->workgroup);
1838 dir = SMB_MALLOC_P(SMBCFILE);
1840 if (!dir) {
1842 errno = ENOMEM;
1843 return NULL;
1847 ZERO_STRUCTP(dir);
1849 dir->cli_fd = 0;
1850 dir->fname = SMB_STRDUP(fname);
1851 dir->srv = NULL;
1852 dir->offset = 0;
1853 dir->file = False;
1854 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
1856 if (server[0] == (char)0 &&
1857 (! *options || strcmp(options, "mb=.any") == 0)) {
1858 struct in_addr server_ip;
1859 if (share[0] != (char)0 || path[0] != (char)0) {
1861 errno = EINVAL;
1862 if (dir) {
1863 SAFE_FREE(dir->fname);
1864 SAFE_FREE(dir);
1866 return NULL;
1870 * We have server and share and path empty ... so list the
1871 * workgroups first try to get the LMB for our workgroup, and
1872 * if that fails, try the DMB
1875 pstrcpy(workgroup, lp_workgroup());
1877 if (!find_master_ip(workgroup, &server_ip)) {
1878 struct user_auth_info u_info;
1879 struct cli_state *cli;
1881 DEBUG(4, ("Unable to find master browser for workgroup %s\n",
1882 workgroup));
1884 /* find the name of the server ... */
1885 pstrcpy(u_info.username, user);
1886 pstrcpy(u_info.password, password);
1888 if (!(cli = get_ipc_connect_master_ip_bcast(workgroup, &u_info))) {
1889 DEBUG(4, ("Unable to find master browser by "
1890 "broadcast\n"));
1891 errno = ENOENT;
1892 return NULL;
1895 fstrcpy(server, cli->desthost);
1897 cli_shutdown(cli);
1898 } else {
1900 * Do a name status query to find out the name of the
1901 * master browser. We use <01><02>__MSBROWSE__<02>#01 if
1902 * *#00 fails because a domain master browser will not
1903 * respond to a wildcard query (or, at least, an NT4
1904 * server acting as the domain master browser will not).
1906 * We might be able to use ONLY the query on MSBROWSE, but
1907 * that's not yet been tested with all Windows versions,
1908 * so until it is, leave the original wildcard query as
1909 * the first choice and fall back to MSBROWSE if the
1910 * wildcard query fails.
1912 if (!name_status_find("*", 0, 0x20, server_ip, server) &&
1913 !name_status_find(MSBROWSE, 1, 0x1b, server_ip, server)) {
1914 errno = ENOENT;
1915 return NULL;
1919 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
1922 * Get a connection to IPC$ on the server if we do not already
1923 * have one
1926 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
1927 if (!srv) {
1929 if (dir) {
1930 SAFE_FREE(dir->fname);
1931 SAFE_FREE(dir);
1933 return NULL;
1936 dir->srv = srv;
1937 dir->dir_type = SMBC_WORKGROUP;
1939 /* Now, list the stuff ... */
1941 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_fn,
1942 (void *)dir)) {
1944 DEBUG(1, ("Could not enumerate domains using '%s'\n", workgroup));
1945 if (dir) {
1946 SAFE_FREE(dir->fname);
1947 SAFE_FREE(dir);
1950 return NULL;
1953 } else if (server[0] == (char)0 &&
1954 (! *options || strcmp(options, "mb=.all") == 0)) {
1956 int i;
1957 int count;
1958 struct ip_service *ip_list;
1959 struct ip_service server_addr;
1960 struct user_auth_info u_info;
1961 struct cli_state *cli;
1963 if (share[0] != (char)0 || path[0] != (char)0) {
1965 errno = EINVAL;
1966 if (dir) {
1967 SAFE_FREE(dir->fname);
1968 SAFE_FREE(dir);
1970 return NULL;
1973 pstrcpy(u_info.username, user);
1974 pstrcpy(u_info.password, password);
1977 * We have server and share and path empty but options
1978 * requesting that we scan all master browsers for their list
1979 * of workgroups/domains. This implies that we must first try
1980 * broadcast queries to find all master browsers, and if that
1981 * doesn't work, then try our other methods which return only
1982 * a single master browser.
1985 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
1986 if (!find_master_ip(workgroup, &server_addr.ip)) {
1988 errno = ENOENT;
1989 return NULL;
1992 ip_list = &server_addr;
1993 count = 1;
1996 for (i = 0; i < count; i++) {
1997 DEBUG(99, ("Found master browser %s\n", inet_ntoa(ip_list[i].ip)));
1999 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2001 /* cli == NULL is the master browser refused to talk or
2002 could not be found */
2003 if ( !cli )
2004 continue;
2006 fstrcpy(server, cli->desthost);
2007 cli_shutdown(cli);
2009 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2012 * For each returned master browser IP address, get a
2013 * connection to IPC$ on the server if we do not
2014 * already have one, and determine the
2015 * workgroups/domains that it knows about.
2018 srv = smbc_server(context, server,
2019 "IPC$", workgroup, user, password);
2020 if (!srv) {
2022 if (dir) {
2023 SAFE_FREE(dir->fname);
2024 SAFE_FREE(dir);
2026 return NULL;
2029 dir->srv = srv;
2030 dir->dir_type = SMBC_WORKGROUP;
2032 /* Now, list the stuff ... */
2034 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2035 (void *)dir)) {
2037 if (dir) {
2038 SAFE_FREE(dir->fname);
2039 SAFE_FREE(dir);
2042 return NULL;
2046 } else {
2048 * Server not an empty string ... Check the rest and see what
2049 * gives
2051 if (share[0] == (char)0) {
2053 if (path[0] != (char)0) { /* Should not have empty share with path */
2055 errno = EINVAL;
2056 if (dir) {
2057 SAFE_FREE(dir->fname);
2058 SAFE_FREE(dir);
2060 return NULL;
2064 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2065 /* However, we check to see if <server> is an IP address first */
2067 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2068 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2069 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2070 fstring buserver;
2072 dir->dir_type = SMBC_SERVER;
2075 * Get the backup list ...
2079 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2081 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2082 errno = EPERM; /* FIXME, is this correct */
2083 return NULL;
2088 * Get a connection to IPC$ on the server if we do not already have one
2091 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2093 if (!srv) {
2094 DEBUG(0, ("got no contact to IPC$\n"));
2095 if (dir) {
2096 SAFE_FREE(dir->fname);
2097 SAFE_FREE(dir);
2099 return NULL;
2103 dir->srv = srv;
2105 /* Now, list the servers ... */
2107 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2108 (void *)dir)) {
2110 if (dir) {
2111 SAFE_FREE(dir->fname);
2112 SAFE_FREE(dir);
2114 return NULL;
2118 else {
2120 if (resolve_name(server, &rem_ip, 0x20)) {
2122 /* Now, list the shares ... */
2124 dir->dir_type = SMBC_FILE_SHARE;
2126 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2128 if (!srv) {
2130 if (dir) {
2131 SAFE_FREE(dir->fname);
2132 SAFE_FREE(dir);
2134 return NULL;
2138 dir->srv = srv;
2140 /* Now, list the servers ... */
2142 if (cli_RNetShareEnum(&srv->cli, list_fn,
2143 (void *)dir) < 0) {
2145 errno = cli_errno(&srv->cli);
2146 if (dir) {
2147 SAFE_FREE(dir->fname);
2148 SAFE_FREE(dir);
2150 return NULL;
2155 else {
2157 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2158 if (dir) {
2159 SAFE_FREE(dir->fname);
2160 SAFE_FREE(dir);
2162 return NULL;
2169 else { /* The server and share are specified ... work from there ... */
2171 /* Well, we connect to the server and list the directory */
2173 dir->dir_type = SMBC_FILE_SHARE;
2175 srv = smbc_server(context, server, share, workgroup, user, password);
2177 if (!srv) {
2179 if (dir) {
2180 SAFE_FREE(dir->fname);
2181 SAFE_FREE(dir);
2183 return NULL;
2187 dir->srv = srv;
2189 /* Now, list the files ... */
2191 pstrcat(path, "\\*");
2193 if (cli_list(&srv->cli, path, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2194 (void *)dir) < 0) {
2196 if (dir) {
2197 SAFE_FREE(dir->fname);
2198 SAFE_FREE(dir);
2200 errno = smbc_errno(context, &srv->cli);
2201 return NULL;
2208 DLIST_ADD(context->internal->_files, dir);
2209 return dir;
2214 * Routine to close a directory
2217 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2220 if (!context || !context->internal ||
2221 !context->internal->_initialized) {
2223 errno = EINVAL;
2224 return -1;
2228 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2230 errno = EBADF;
2231 return -1;
2235 smbc_remove_dir(dir); /* Clean it up */
2237 DLIST_REMOVE(context->internal->_files, dir);
2239 if (dir) {
2241 SAFE_FREE(dir->fname);
2242 SAFE_FREE(dir); /* Free the space too */
2245 return 0;
2250 * Routine to get a directory entry
2253 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2255 struct smbc_dirent *dirp, *dirent;
2257 /* Check that all is ok first ... */
2259 if (!context || !context->internal ||
2260 !context->internal->_initialized) {
2262 errno = EINVAL;
2263 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2264 return NULL;
2268 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2270 errno = EBADF;
2271 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2272 return NULL;
2276 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2278 errno = ENOTDIR;
2279 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2280 return NULL;
2284 if (!dir->dir_next) {
2285 return NULL;
2287 else {
2289 dirent = dir->dir_next->dirent;
2290 if (!dirent) {
2292 errno = ENOENT;
2293 return NULL;
2297 /* Hmmm, do I even need to copy it? */
2299 memcpy(context->internal->_dirent, dirent, dirent->dirlen); /* Copy the dirent */
2300 dirp = (struct smbc_dirent *)context->internal->_dirent;
2301 dirp->comment = (char *)(&dirp->name + dirent->namelen + 1);
2302 dir->dir_next = dir->dir_next->next;
2304 return (struct smbc_dirent *)context->internal->_dirent;
2310 * Routine to get directory entries
2313 static int smbc_getdents_ctx(SMBCCTX *context, SMBCFILE *dir, struct smbc_dirent *dirp, int count)
2315 struct smbc_dir_list *dirlist;
2316 int rem = count, reqd;
2317 char *ndir = (char *)dirp;
2319 /* Check that all is ok first ... */
2321 if (!context || !context->internal ||
2322 !context->internal->_initialized) {
2324 errno = EINVAL;
2325 return -1;
2329 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2331 errno = EBADF;
2332 return -1;
2336 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2338 errno = ENOTDIR;
2339 return -1;
2344 * Now, retrieve the number of entries that will fit in what was passed
2345 * We have to figure out if the info is in the list, or we need to
2346 * send a request to the server to get the info.
2349 while ((dirlist = dir->dir_next)) {
2350 struct smbc_dirent *dirent;
2352 if (!dirlist->dirent) {
2354 errno = ENOENT; /* Bad error */
2355 return -1;
2359 if (rem < (reqd = (sizeof(struct smbc_dirent) + dirlist->dirent->namelen +
2360 dirlist->dirent->commentlen + 1))) {
2362 if (rem < count) { /* We managed to copy something */
2364 errno = 0;
2365 return count - rem;
2368 else { /* Nothing copied ... */
2370 errno = EINVAL; /* Not enough space ... */
2371 return -1;
2377 dirent = dirlist->dirent;
2379 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2381 ((struct smbc_dirent *)ndir)->comment =
2382 (char *)(&((struct smbc_dirent *)ndir)->name + dirent->namelen + 1);
2384 ndir += reqd;
2386 rem -= reqd;
2388 dir->dir_next = dirlist = dirlist -> next;
2391 if (rem == count)
2392 return 0;
2393 else
2394 return count - rem;
2399 * Routine to create a directory ...
2402 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2404 SMBCSRV *srv;
2405 fstring server, share, user, password, workgroup;
2406 pstring path;
2408 if (!context || !context->internal ||
2409 !context->internal->_initialized) {
2411 errno = EINVAL;
2412 return -1;
2416 if (!fname) {
2418 errno = EINVAL;
2419 return -1;
2423 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2425 if (smbc_parse_path(context, fname,
2426 server, sizeof(server),
2427 share, sizeof(share),
2428 path, sizeof(path),
2429 user, sizeof(user),
2430 password, sizeof(password),
2431 NULL, 0)) {
2432 errno = EINVAL;
2433 return -1;
2436 if (user[0] == (char)0) fstrcpy(user, context->user);
2438 fstrcpy(workgroup, context->workgroup);
2440 srv = smbc_server(context, server, share, workgroup, user, password);
2442 if (!srv) {
2444 return -1; /* errno set by smbc_server */
2448 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2450 mode = aDIR | aRONLY;
2453 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2455 if (strcmp(path, "\\") == 0) {
2457 mode = aDIR | aRONLY;
2460 else {
2462 mode = aRONLY;
2463 smbc_stat_printjob(srv, path, &size, &m_time);
2464 c_time = a_time = m_time;
2467 else { */
2469 if (!cli_mkdir(&srv->cli, path)) {
2471 errno = smbc_errno(context, &srv->cli);
2472 return -1;
2476 return 0;
2481 * Our list function simply checks to see if a directory is not empty
2484 static int smbc_rmdir_dirempty = True;
2486 static void rmdir_list_fn(file_info *finfo, const char *mask, void *state)
2489 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2490 smbc_rmdir_dirempty = False;
2495 * Routine to remove a directory
2498 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2500 SMBCSRV *srv;
2501 fstring server, share, user, password, workgroup;
2502 pstring path;
2504 if (!context || !context->internal ||
2505 !context->internal->_initialized) {
2507 errno = EINVAL;
2508 return -1;
2512 if (!fname) {
2514 errno = EINVAL;
2515 return -1;
2519 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2521 if (smbc_parse_path(context, fname,
2522 server, sizeof(server),
2523 share, sizeof(share),
2524 path, sizeof(path),
2525 user, sizeof(user),
2526 password, sizeof(password),
2527 NULL, 0))
2529 errno = EINVAL;
2530 return -1;
2533 if (user[0] == (char)0) fstrcpy(user, context->user);
2535 fstrcpy(workgroup, context->workgroup);
2537 srv = smbc_server(context, server, share, workgroup, user, password);
2539 if (!srv) {
2541 return -1; /* errno set by smbc_server */
2545 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2547 mode = aDIR | aRONLY;
2550 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2552 if (strcmp(path, "\\") == 0) {
2554 mode = aDIR | aRONLY;
2557 else {
2559 mode = aRONLY;
2560 smbc_stat_printjob(srv, path, &size, &m_time);
2561 c_time = a_time = m_time;
2564 else { */
2566 if (!cli_rmdir(&srv->cli, path)) {
2568 errno = smbc_errno(context, &srv->cli);
2570 if (errno == EACCES) { /* Check if the dir empty or not */
2572 pstring lpath; /* Local storage to avoid buffer overflows */
2574 smbc_rmdir_dirempty = True; /* Make this so ... */
2576 pstrcpy(lpath, path);
2577 pstrcat(lpath, "\\*");
2579 if (cli_list(&srv->cli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2580 NULL) < 0) {
2582 /* Fix errno to ignore latest error ... */
2584 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
2585 smbc_errno(context, &srv->cli)));
2586 errno = EACCES;
2590 if (smbc_rmdir_dirempty)
2591 errno = EACCES;
2592 else
2593 errno = ENOTEMPTY;
2597 return -1;
2601 return 0;
2606 * Routine to return the current directory position
2609 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
2611 off_t ret_val; /* Squash warnings about cast */
2613 if (!context || !context->internal ||
2614 !context->internal->_initialized) {
2616 errno = EINVAL;
2617 return -1;
2621 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2623 errno = EBADF;
2624 return -1;
2628 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2630 errno = ENOTDIR;
2631 return -1;
2636 * We return the pointer here as the offset
2638 ret_val = (int)dir->dir_next;
2639 return ret_val;
2644 * A routine to run down the list and see if the entry is OK
2647 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
2648 struct smbc_dirent *dirent)
2651 /* Run down the list looking for what we want */
2653 if (dirent) {
2655 struct smbc_dir_list *tmp = list;
2657 while (tmp) {
2659 if (tmp->dirent == dirent)
2660 return tmp;
2662 tmp = tmp->next;
2668 return NULL; /* Not found, or an error */
2674 * Routine to seek on a directory
2677 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
2679 long int l_offset = offset; /* Handle problems of size */
2680 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
2681 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
2683 if (!context || !context->internal ||
2684 !context->internal->_initialized) {
2686 errno = EINVAL;
2687 return -1;
2691 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2693 errno = ENOTDIR;
2694 return -1;
2698 /* Now, check what we were passed and see if it is OK ... */
2700 if (dirent == NULL) { /* Seek to the begining of the list */
2702 dir->dir_next = dir->dir_list;
2703 return 0;
2707 /* Now, run down the list and make sure that the entry is OK */
2708 /* This may need to be changed if we change the format of the list */
2710 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
2712 errno = EINVAL; /* Bad entry */
2713 return -1;
2717 dir->dir_next = list_ent;
2719 return 0;
2724 * Routine to fstat a dir
2727 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
2730 if (!context || !context->internal ||
2731 !context->internal->_initialized) {
2733 errno = EINVAL;
2734 return -1;
2738 /* No code yet ... */
2740 return 0;
2744 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
2746 SMBCSRV *srv;
2747 fstring server, share, user, password, workgroup;
2748 pstring path;
2749 uint16 mode;
2751 if (!context || !context->internal ||
2752 !context->internal->_initialized) {
2754 errno = EINVAL; /* Best I can think of ... */
2755 return -1;
2759 if (!fname) {
2761 errno = EINVAL;
2762 return -1;
2766 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
2768 if (smbc_parse_path(context, fname,
2769 server, sizeof(server),
2770 share, sizeof(share),
2771 path, sizeof(path),
2772 user, sizeof(user),
2773 password, sizeof(password),
2774 NULL, 0)) {
2775 errno = EINVAL;
2776 return -1;
2779 if (user[0] == (char)0) fstrcpy(user, context->user);
2781 fstrcpy(workgroup, context->workgroup);
2783 srv = smbc_server(context, server, share, workgroup, user, password);
2785 if (!srv) {
2786 return -1; /* errno set by smbc_server */
2789 mode = 0;
2791 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
2792 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
2793 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
2794 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
2796 if (!cli_setatr(&srv->cli, path, mode, 0)) {
2797 errno = smbc_errno(context, &srv->cli);
2798 return -1;
2801 return 0;
2804 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
2806 SMBCSRV *srv;
2807 fstring server, share, user, password, workgroup;
2808 pstring path;
2809 uint16 mode;
2810 time_t t = (tbuf == NULL ? time(NULL) : tbuf->tv_sec);
2812 if (!context || !context->internal ||
2813 !context->internal->_initialized) {
2815 errno = EINVAL; /* Best I can think of ... */
2816 return -1;
2820 if (!fname) {
2822 errno = EINVAL;
2823 return -1;
2827 DEBUG(4, ("smbc_utimes(%s, [%s])\n", fname, ctime(&t)));
2829 if (smbc_parse_path(context, fname,
2830 server, sizeof(server),
2831 share, sizeof(share),
2832 path, sizeof(path),
2833 user, sizeof(user),
2834 password, sizeof(password),
2835 NULL, 0)) {
2836 errno = EINVAL;
2837 return -1;
2840 if (user[0] == (char)0) fstrcpy(user, context->user);
2842 fstrcpy(workgroup, context->workgroup);
2844 srv = smbc_server(context, server, share, workgroup, user, password);
2846 if (!srv) {
2847 return -1; /* errno set by smbc_server */
2850 if (!smbc_getatr(context, srv, path,
2851 &mode, NULL,
2852 NULL, NULL, NULL,
2853 NULL)) {
2854 return -1;
2857 if (!cli_setatr(&srv->cli, path, mode, t)) {
2858 /* some servers always refuse directory changes */
2859 if (!(mode & aDIR)) {
2860 errno = smbc_errno(context, &srv->cli);
2861 return -1;
2865 return 0;
2869 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
2870 However NT4 gives a "The information may have been modified by a
2871 computer running Windows NT 5.0" if denied ACEs do not appear before
2872 allowed ACEs. */
2874 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
2876 if (sec_ace_equal(ace1, ace2))
2877 return 0;
2879 if (ace1->type != ace2->type)
2880 return ace2->type - ace1->type;
2882 if (sid_compare(&ace1->trustee, &ace2->trustee))
2883 return sid_compare(&ace1->trustee, &ace2->trustee);
2885 if (ace1->flags != ace2->flags)
2886 return ace1->flags - ace2->flags;
2888 if (ace1->info.mask != ace2->info.mask)
2889 return ace1->info.mask - ace2->info.mask;
2891 if (ace1->size != ace2->size)
2892 return ace1->size - ace2->size;
2894 return memcmp(ace1, ace2, sizeof(SEC_ACE));
2898 static void sort_acl(SEC_ACL *the_acl)
2900 uint32 i;
2901 if (!the_acl) return;
2903 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
2905 for (i=1;i<the_acl->num_aces;) {
2906 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
2907 int j;
2908 for (j=i; j<the_acl->num_aces-1; j++) {
2909 the_acl->ace[j] = the_acl->ace[j+1];
2911 the_acl->num_aces--;
2912 } else {
2913 i++;
2918 /* convert a SID to a string, either numeric or username/group */
2919 static void convert_sid_to_string(struct cli_state *ipc_cli,
2920 POLICY_HND *pol,
2921 fstring str,
2922 BOOL numeric,
2923 DOM_SID *sid)
2925 char **domains = NULL;
2926 char **names = NULL;
2927 uint32 *types = NULL;
2929 sid_to_string(str, sid);
2931 if (numeric) return; /* no lookup desired */
2933 /* Ask LSA to convert the sid to a name */
2935 if (!NT_STATUS_IS_OK(cli_lsa_lookup_sids(ipc_cli, ipc_cli->mem_ctx,
2936 pol, 1, sid, &domains,
2937 &names, &types)) ||
2938 !domains || !domains[0] || !names || !names[0]) {
2939 return;
2942 /* Converted OK */
2944 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
2945 domains[0], lp_winbind_separator(),
2946 names[0]);
2949 /* convert a string to a SID, either numeric or username/group */
2950 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
2951 POLICY_HND *pol,
2952 BOOL numeric,
2953 DOM_SID *sid,
2954 const char *str)
2956 uint32 *types = NULL;
2957 DOM_SID *sids = NULL;
2958 BOOL result = True;
2960 if (numeric) {
2961 if (strncmp(str, "S-", 2) == 0) {
2962 return string_to_sid(sid, str);
2965 result = False;
2966 goto done;
2969 if (!NT_STATUS_IS_OK(cli_lsa_lookup_names(ipc_cli, ipc_cli->mem_ctx,
2970 pol, 1, &str, &sids,
2971 &types))) {
2972 result = False;
2973 goto done;
2976 sid_copy(sid, &sids[0]);
2977 done:
2979 return result;
2983 /* parse an ACE in the same format as print_ace() */
2984 static BOOL parse_ace(struct cli_state *ipc_cli,
2985 POLICY_HND *pol,
2986 SEC_ACE *ace,
2987 BOOL numeric,
2988 char *str)
2990 char *p;
2991 const char *cp;
2992 fstring tok;
2993 unsigned atype, aflags, amask;
2994 DOM_SID sid;
2995 SEC_ACCESS mask;
2996 const struct perm_value *v;
2997 struct perm_value {
2998 const char *perm;
2999 uint32 mask;
3002 /* These values discovered by inspection */
3003 static const struct perm_value special_values[] = {
3004 { "R", 0x00120089 },
3005 { "W", 0x00120116 },
3006 { "X", 0x001200a0 },
3007 { "D", 0x00010000 },
3008 { "P", 0x00040000 },
3009 { "O", 0x00080000 },
3010 { NULL, 0 },
3013 static const struct perm_value standard_values[] = {
3014 { "READ", 0x001200a9 },
3015 { "CHANGE", 0x001301bf },
3016 { "FULL", 0x001f01ff },
3017 { NULL, 0 },
3021 ZERO_STRUCTP(ace);
3022 p = strchr_m(str,':');
3023 if (!p) return False;
3024 *p = '\0';
3025 p++;
3026 /* Try to parse numeric form */
3028 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3029 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3030 goto done;
3033 /* Try to parse text form */
3035 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3036 return False;
3039 cp = p;
3040 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3041 return False;
3044 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3045 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3046 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3047 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3048 } else {
3049 return False;
3052 /* Only numeric form accepted for flags at present */
3054 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3055 sscanf(tok, "%i", &aflags))) {
3056 return False;
3059 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3060 return False;
3063 if (strncmp(tok, "0x", 2) == 0) {
3064 if (sscanf(tok, "%i", &amask) != 1) {
3065 return False;
3067 goto done;
3070 for (v = standard_values; v->perm; v++) {
3071 if (strcmp(tok, v->perm) == 0) {
3072 amask = v->mask;
3073 goto done;
3077 p = tok;
3079 while(*p) {
3080 BOOL found = False;
3082 for (v = special_values; v->perm; v++) {
3083 if (v->perm[0] == *p) {
3084 amask |= v->mask;
3085 found = True;
3089 if (!found) return False;
3090 p++;
3093 if (*p) {
3094 return False;
3097 done:
3098 mask.mask = amask;
3099 init_sec_ace(ace, &sid, atype, mask, aflags);
3100 return True;
3103 /* add an ACE to a list of ACEs in a SEC_ACL */
3104 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3106 SEC_ACL *new;
3107 SEC_ACE *aces;
3108 if (! *the_acl) {
3109 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3110 return True;
3113 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3114 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3115 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3116 new = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3117 SAFE_FREE(aces);
3118 (*the_acl) = new;
3119 return True;
3123 /* parse a ascii version of a security descriptor */
3124 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3125 struct cli_state *ipc_cli,
3126 POLICY_HND *pol,
3127 BOOL numeric,
3128 char *str)
3130 const char *p = str;
3131 fstring tok;
3132 SEC_DESC *ret;
3133 size_t sd_size;
3134 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3135 SEC_ACL *dacl=NULL;
3136 int revision=1;
3138 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3140 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3141 revision = strtol(tok+9, NULL, 16);
3142 continue;
3145 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3146 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3147 if (!owner_sid ||
3148 !convert_string_to_sid(ipc_cli, pol,
3149 numeric,
3150 owner_sid, tok+6)) {
3151 DEBUG(5, ("Failed to parse owner sid\n"));
3152 return NULL;
3154 continue;
3157 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3158 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3159 if (!owner_sid ||
3160 !convert_string_to_sid(ipc_cli, pol,
3161 False,
3162 owner_sid, tok+7)) {
3163 DEBUG(5, ("Failed to parse owner sid\n"));
3164 return NULL;
3166 continue;
3169 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3170 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3171 if (!grp_sid ||
3172 !convert_string_to_sid(ipc_cli, pol,
3173 numeric,
3174 grp_sid, tok+6)) {
3175 DEBUG(5, ("Failed to parse group sid\n"));
3176 return NULL;
3178 continue;
3181 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3182 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3183 if (!grp_sid ||
3184 !convert_string_to_sid(ipc_cli, pol,
3185 False,
3186 grp_sid, tok+6)) {
3187 DEBUG(5, ("Failed to parse group sid\n"));
3188 return NULL;
3190 continue;
3193 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3194 SEC_ACE ace;
3195 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3196 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3197 return NULL;
3199 if(!add_ace(&dacl, &ace, ctx)) {
3200 DEBUG(5, ("Failed to add ACL %s\n", tok));
3201 return NULL;
3203 continue;
3206 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3207 SEC_ACE ace;
3208 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3209 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3210 return NULL;
3212 if(!add_ace(&dacl, &ace, ctx)) {
3213 DEBUG(5, ("Failed to add ACL %s\n", tok));
3214 return NULL;
3216 continue;
3219 DEBUG(5, ("Failed to parse security descriptor\n"));
3220 return NULL;
3223 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3224 owner_sid, grp_sid, NULL, dacl, &sd_size);
3226 SAFE_FREE(grp_sid);
3227 SAFE_FREE(owner_sid);
3229 return ret;
3233 /*****************************************************
3234 retrieve the acls for a file
3235 *******************************************************/
3236 static int cacl_get(TALLOC_CTX *ctx, struct cli_state *cli,
3237 struct cli_state *ipc_cli, POLICY_HND *pol,
3238 char *filename, char *name, char *buf, int bufsize)
3240 uint32 i;
3241 int n = 0;
3242 int n_used;
3243 BOOL all;
3244 BOOL numeric = True;
3245 BOOL determine_size = (bufsize == 0);
3246 int fnum = -1;
3247 SEC_DESC *sd;
3248 fstring sidstr;
3249 char *p;
3251 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3253 if (fnum == -1) {
3254 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3255 filename, cli_errstr(cli)));
3256 errno = 0;
3257 return -1;
3260 sd = cli_query_secdesc(cli, fnum, ctx);
3262 if (!sd) {
3263 DEBUG(5, ("cacl_get Failed to query old descriptor\n"));
3264 errno = 0;
3265 return -1;
3268 cli_close(cli, fnum);
3270 all = (*name == '*');
3271 numeric = (* (name + strlen(name) - 1) != '+');
3273 n_used = 0;
3275 if (all) {
3276 if (determine_size) {
3277 p = talloc_asprintf(ctx,
3278 "REVISION:%d", sd->revision);
3279 if (!p) {
3280 errno = ENOMEM;
3281 return -1;
3283 n = strlen(p);
3284 } else {
3285 n = snprintf(buf, bufsize,
3286 "REVISION:%d", sd->revision);
3288 } else if (StrCaseCmp(name, "revision") == 0) {
3289 if (determine_size) {
3290 p = talloc_asprintf(ctx, "%d", sd->revision);
3291 if (!p) {
3292 errno = ENOMEM;
3293 return -1;
3295 n = strlen(p);
3296 } else {
3297 n = snprintf(buf, bufsize, "%d", sd->revision);
3301 if (!determine_size && n > bufsize) {
3302 errno = ERANGE;
3303 return -1;
3305 buf += n;
3306 n_used += n;
3307 bufsize -= n;
3309 /* Get owner and group sid */
3311 if (sd->owner_sid) {
3312 convert_sid_to_string(ipc_cli, pol,
3313 sidstr, numeric, sd->owner_sid);
3314 } else {
3315 fstrcpy(sidstr, "");
3318 if (all) {
3319 if (determine_size) {
3320 p = talloc_asprintf(ctx, ",OWNER:%s", sidstr);
3321 if (!p) {
3322 errno = ENOMEM;
3323 return -1;
3325 n = strlen(p);
3326 } else {
3327 n = snprintf(buf, bufsize, ",OWNER:%s", sidstr);
3329 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3330 if (determine_size) {
3331 p = talloc_asprintf(ctx, "%s", sidstr);
3332 if (!p) {
3333 errno = ENOMEM;
3334 return -1;
3336 n = strlen(p);
3337 } else {
3338 n = snprintf(buf, bufsize, "%s", sidstr);
3342 if (!determine_size && n > bufsize) {
3343 errno = ERANGE;
3344 return -1;
3346 buf += n;
3347 n_used += n;
3348 bufsize -= n;
3350 if (sd->grp_sid) {
3351 convert_sid_to_string(ipc_cli, pol,
3352 sidstr, numeric, sd->grp_sid);
3353 } else {
3354 fstrcpy(sidstr, "");
3357 if (all) {
3358 if (determine_size) {
3359 p = talloc_asprintf(ctx, ",GROUP:%s", sidstr);
3360 if (!p) {
3361 errno = ENOMEM;
3362 return -1;
3364 n = strlen(p);
3365 } else {
3366 n = snprintf(buf, bufsize, ",GROUP:%s", sidstr);
3368 } else if (StrnCaseCmp(name, "group", 5) == 0) {
3369 if (determine_size) {
3370 p = talloc_asprintf(ctx, "%s", sidstr);
3371 if (!p) {
3372 errno = ENOMEM;
3373 return -1;
3375 n = strlen(p);
3376 } else {
3377 n = snprintf(buf, bufsize, "%s", sidstr);
3381 if (!determine_size && n > bufsize) {
3382 errno = ERANGE;
3383 return -1;
3385 buf += n;
3386 n_used += n;
3387 bufsize -= n;
3389 /* Add aces to value buffer */
3390 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
3392 SEC_ACE *ace = &sd->dacl->ace[i];
3393 convert_sid_to_string(ipc_cli, pol,
3394 sidstr, numeric, &ace->trustee);
3396 if (all) {
3397 if (determine_size) {
3398 p = talloc_asprintf(ctx,
3399 ",ACL:%s:%d/%d/0x%08x",
3400 sidstr,
3401 ace->type,
3402 ace->flags,
3403 ace->info.mask);
3404 if (!p) {
3405 errno = ENOMEM;
3406 return -1;
3408 n = strlen(p);
3409 } else {
3410 n = snprintf(buf, bufsize,
3411 ",ACL:%s:%d/%d/0x%08x",
3412 sidstr,
3413 ace->type,
3414 ace->flags,
3415 ace->info.mask);
3417 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
3418 StrCaseCmp(name + 3, sidstr) == 0) ||
3419 (StrnCaseCmp(name, "acl+", 4) == 0 &&
3420 StrCaseCmp(name + 4, sidstr) == 0)) {
3421 if (determine_size) {
3422 p = talloc_asprintf(ctx,
3423 "%d/%d/0x%08x",
3424 ace->type,
3425 ace->flags,
3426 ace->info.mask);
3427 if (!p) {
3428 errno = ENOMEM;
3429 return -1;
3431 n = strlen(p);
3432 } else {
3433 n = snprintf(buf, bufsize,
3434 "%d/%d/0x%08x",
3435 ace->type, ace->flags, ace->info.mask);
3438 if (n > bufsize) {
3439 errno = ERANGE;
3440 return -1;
3442 buf += n;
3443 n_used += n;
3444 bufsize -= n;
3447 if (n_used == 0) {
3448 errno = ENOATTR;
3449 return -1;
3451 return n_used;
3455 /*****************************************************
3456 set the ACLs on a file given an ascii description
3457 *******************************************************/
3458 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
3459 struct cli_state *ipc_cli, POLICY_HND *pol,
3460 const char *filename, const char *the_acl,
3461 int mode, int flags)
3463 int fnum;
3464 int err = 0;
3465 SEC_DESC *sd = NULL, *old;
3466 SEC_ACL *dacl = NULL;
3467 DOM_SID *owner_sid = NULL;
3468 DOM_SID *grp_sid = NULL;
3469 uint32 i, j;
3470 size_t sd_size;
3471 int ret = 0;
3472 char *p;
3473 BOOL numeric = True;
3475 /* the_acl will be null for REMOVE_ALL operations */
3476 if (the_acl) {
3477 numeric = ((p = strchr(the_acl, ':')) != NULL &&
3478 p > the_acl &&
3479 p[-1] != '+');
3481 /* if this is to set the entire ACL... */
3482 if (*the_acl == '*') {
3483 /* ... then increment past the first colon */
3484 the_acl = p + 1;
3487 sd = sec_desc_parse(ctx, ipc_cli, pol,
3488 numeric, (char *) the_acl);
3490 if (!sd) {
3491 errno = EINVAL;
3492 return -1;
3496 /* The desired access below is the only one I could find that works
3497 with NT4, W2KP and Samba */
3499 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3501 if (fnum == -1) {
3502 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3503 filename, cli_errstr(cli)));
3504 errno = 0;
3505 return -1;
3508 old = cli_query_secdesc(cli, fnum, ctx);
3510 if (!old) {
3511 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
3512 errno = 0;
3513 return -1;
3516 cli_close(cli, fnum);
3518 switch (mode) {
3519 case SMBC_XATTR_MODE_REMOVE_ALL:
3520 old->dacl->num_aces = 0;
3521 SAFE_FREE(old->dacl->ace);
3522 SAFE_FREE(old->dacl);
3523 old->off_dacl = 0;
3524 dacl = old->dacl;
3525 break;
3527 case SMBC_XATTR_MODE_REMOVE:
3528 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3529 BOOL found = False;
3531 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3532 if (sec_ace_equal(&sd->dacl->ace[i],
3533 &old->dacl->ace[j])) {
3534 uint32 k;
3535 for (k=j; k<old->dacl->num_aces-1;k++) {
3536 old->dacl->ace[k] = old->dacl->ace[k+1];
3538 old->dacl->num_aces--;
3539 if (old->dacl->num_aces == 0) {
3540 SAFE_FREE(old->dacl->ace);
3541 SAFE_FREE(old->dacl);
3542 old->off_dacl = 0;
3544 found = True;
3545 dacl = old->dacl;
3546 break;
3550 if (!found) {
3551 err = ENOATTR;
3552 ret = -1;
3553 goto failed;
3556 break;
3558 case SMBC_XATTR_MODE_ADD:
3559 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3560 BOOL found = False;
3562 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3563 if (sid_equal(&sd->dacl->ace[i].trustee,
3564 &old->dacl->ace[j].trustee)) {
3565 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
3566 err = EEXIST;
3567 ret = -1;
3568 goto failed;
3570 old->dacl->ace[j] = sd->dacl->ace[i];
3571 ret = -1;
3572 found = True;
3576 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
3577 err = ENOATTR;
3578 ret = -1;
3579 goto failed;
3582 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3583 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
3586 dacl = old->dacl;
3587 break;
3589 case SMBC_XATTR_MODE_SET:
3590 old = sd;
3591 owner_sid = old->owner_sid;
3592 grp_sid = old->grp_sid;
3593 dacl = old->dacl;
3594 break;
3596 case SMBC_XATTR_MODE_CHOWN:
3597 owner_sid = sd->owner_sid;
3598 break;
3600 case SMBC_XATTR_MODE_CHGRP:
3601 grp_sid = sd->grp_sid;
3602 break;
3605 /* Denied ACE entries must come before allowed ones */
3606 sort_acl(old->dacl);
3608 /* Create new security descriptor and set it */
3609 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
3610 owner_sid, grp_sid, NULL, dacl, &sd_size);
3612 fnum = cli_nt_create(cli, filename,
3613 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
3615 if (fnum == -1) {
3616 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3617 filename, cli_errstr(cli)));
3618 errno = 0;
3619 return -1;
3622 if (!cli_set_secdesc(cli, fnum, sd)) {
3623 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
3624 ret = -1;
3627 /* Clean up */
3629 failed:
3630 cli_close(cli, fnum);
3632 if (err != 0) {
3633 errno = err;
3636 return ret;
3640 int smbc_setxattr_ctx(SMBCCTX *context,
3641 const char *fname,
3642 const char *name,
3643 const void *value,
3644 size_t size,
3645 int flags)
3647 int ret;
3648 SMBCSRV *srv;
3649 SMBCSRV *ipc_srv;
3650 fstring server, share, user, password, workgroup;
3651 pstring path;
3652 TALLOC_CTX *ctx;
3653 POLICY_HND pol;
3655 if (!context || !context->internal ||
3656 !context->internal->_initialized) {
3658 errno = EINVAL; /* Best I can think of ... */
3659 return -1;
3663 if (!fname) {
3665 errno = EINVAL;
3666 return -1;
3670 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
3671 fname, name, (int) size, (char *) value));
3673 if (smbc_parse_path(context, fname,
3674 server, sizeof(server),
3675 share, sizeof(share),
3676 path, sizeof(path),
3677 user, sizeof(user),
3678 password, sizeof(password),
3679 NULL, 0)) {
3680 errno = EINVAL;
3681 return -1;
3684 if (user[0] == (char)0) fstrcpy(user, context->user);
3686 fstrcpy(workgroup, context->workgroup);
3688 srv = smbc_server(context, server, share, workgroup, user, password);
3689 if (!srv) {
3690 return -1; /* errno set by smbc_server */
3693 ipc_srv = smbc_attr_server(context, server, share,
3694 workgroup, user, password,
3695 &pol);
3696 if (!ipc_srv) {
3697 return -1;
3700 ctx = talloc_init("smbc_setxattr");
3701 if (!ctx) {
3702 errno = ENOMEM;
3703 return -1;
3707 * Are they asking to set an access control element or to set
3708 * the entire access control list?
3710 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3711 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3712 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3713 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3714 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3716 /* Yup. */
3717 char *namevalue =
3718 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3719 if (! namevalue) {
3720 errno = ENOMEM;
3721 ret = -1;
3722 } else {
3723 ret = cacl_set(ctx, &srv->cli,
3724 &ipc_srv->cli, &pol, path,
3725 namevalue,
3726 (*namevalue == '*'
3727 ? SMBC_XATTR_MODE_SET
3728 : SMBC_XATTR_MODE_ADD),
3729 flags);
3731 talloc_destroy(ctx);
3732 return ret;
3736 * Are they asking to set the owner?
3738 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3739 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
3741 /* Yup. */
3742 char *namevalue =
3743 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3744 if (! namevalue) {
3745 errno = ENOMEM;
3746 ret = -1;
3747 } else {
3748 ret = cacl_set(ctx, &srv->cli,
3749 &ipc_srv->cli, &pol, path,
3750 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3752 talloc_destroy(ctx);
3753 return ret;
3757 * Are they asking to set the group?
3759 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3760 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
3762 /* Yup. */
3763 char *namevalue =
3764 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3765 if (! namevalue) {
3766 errno = ENOMEM;
3767 ret = -1;
3768 } else {
3769 ret = cacl_set(ctx, &srv->cli,
3770 &ipc_srv->cli, &pol, path,
3771 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3773 talloc_destroy(ctx);
3774 return ret;
3777 /* Unsupported attribute name */
3778 talloc_destroy(ctx);
3779 errno = EINVAL;
3780 return -1;
3783 int smbc_getxattr_ctx(SMBCCTX *context,
3784 const char *fname,
3785 const char *name,
3786 const void *value,
3787 size_t size)
3789 int ret;
3790 SMBCSRV *srv;
3791 SMBCSRV *ipc_srv;
3792 fstring server, share, user, password, workgroup;
3793 pstring path;
3794 TALLOC_CTX *ctx;
3795 POLICY_HND pol;
3797 if (!context || !context->internal ||
3798 !context->internal->_initialized) {
3800 errno = EINVAL; /* Best I can think of ... */
3801 return -1;
3805 if (!fname) {
3807 errno = EINVAL;
3808 return -1;
3812 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
3814 if (smbc_parse_path(context, fname,
3815 server, sizeof(server),
3816 share, sizeof(share),
3817 path, sizeof(path),
3818 user, sizeof(user),
3819 password, sizeof(password),
3820 NULL, 0)) {
3821 errno = EINVAL;
3822 return -1;
3825 if (user[0] == (char)0) fstrcpy(user, context->user);
3827 fstrcpy(workgroup, context->workgroup);
3829 srv = smbc_server(context, server, share, workgroup, user, password);
3830 if (!srv) {
3831 return -1; /* errno set by smbc_server */
3834 ipc_srv = smbc_attr_server(context, server, share,
3835 workgroup, user, password,
3836 &pol);
3837 if (!ipc_srv) {
3838 return -1;
3841 ctx = talloc_init("smbc:getxattr");
3842 if (!ctx) {
3843 errno = ENOMEM;
3844 return -1;
3847 /* Are they requesting a supported attribute? */
3848 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3849 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3850 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3851 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3852 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3853 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3854 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3855 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3856 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3858 /* Yup. */
3859 ret = cacl_get(ctx, &srv->cli,
3860 &ipc_srv->cli, &pol,
3861 (char *) path, (char *) name + 19,
3862 (char *) value, size);
3863 if (ret < 0 && errno == 0) {
3864 errno = smbc_errno(context, &srv->cli);
3866 talloc_destroy(ctx);
3867 return ret;
3870 /* Unsupported attribute name */
3871 talloc_destroy(ctx);
3872 errno = EINVAL;
3873 return -1;
3877 int smbc_removexattr_ctx(SMBCCTX *context,
3878 const char *fname,
3879 const char *name)
3881 int ret;
3882 SMBCSRV *srv;
3883 SMBCSRV *ipc_srv;
3884 fstring server, share, user, password, workgroup;
3885 pstring path;
3886 TALLOC_CTX *ctx;
3887 POLICY_HND pol;
3889 if (!context || !context->internal ||
3890 !context->internal->_initialized) {
3892 errno = EINVAL; /* Best I can think of ... */
3893 return -1;
3897 if (!fname) {
3899 errno = EINVAL;
3900 return -1;
3904 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
3906 if (smbc_parse_path(context, fname,
3907 server, sizeof(server),
3908 share, sizeof(share),
3909 path, sizeof(path),
3910 user, sizeof(user),
3911 password, sizeof(password),
3912 NULL, 0)) {
3913 errno = EINVAL;
3914 return -1;
3917 if (user[0] == (char)0) fstrcpy(user, context->user);
3919 fstrcpy(workgroup, context->workgroup);
3921 srv = smbc_server(context, server, share, workgroup, user, password);
3922 if (!srv) {
3923 return -1; /* errno set by smbc_server */
3926 ipc_srv = smbc_attr_server(context, server, share,
3927 workgroup, user, password,
3928 &pol);
3929 if (!ipc_srv) {
3930 return -1;
3933 ipc_srv = smbc_attr_server(context, server, share,
3934 workgroup, user, password,
3935 &pol);
3936 if (!ipc_srv) {
3937 return -1;
3940 ctx = talloc_init("smbc_removexattr");
3941 if (!ctx) {
3942 errno = ENOMEM;
3943 return -1;
3946 /* Are they asking to set the entire ACL? */
3947 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3948 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
3950 /* Yup. */
3951 ret = cacl_set(ctx, &srv->cli,
3952 &ipc_srv->cli, &pol, path,
3953 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
3954 talloc_destroy(ctx);
3955 return ret;
3959 * Are they asking to remove one or more spceific security descriptor
3960 * attributes?
3962 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3963 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3964 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3965 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3966 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3967 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3968 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3970 /* Yup. */
3971 ret = cacl_set(ctx, &srv->cli,
3972 &ipc_srv->cli, &pol, path,
3973 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
3974 talloc_destroy(ctx);
3975 return ret;
3978 /* Unsupported attribute name */
3979 talloc_destroy(ctx);
3980 errno = EINVAL;
3981 return -1;
3984 int smbc_listxattr_ctx(SMBCCTX *context,
3985 const char *fname,
3986 char *list,
3987 size_t size)
3990 * This isn't quite what listxattr() is supposed to do. This returns
3991 * the complete set of attributes, always, rather than only those
3992 * attribute names which actually exist for a file. Hmmm...
3994 const char supported[] =
3995 "system.nt_sec_desc.revision\0"
3996 "system.nt_sec_desc.owner\0"
3997 "system.nt_sec_desc.owner+\0"
3998 "system.nt_sec_desc.group\0"
3999 "system.nt_sec_desc.group+\0"
4000 "system.nt_sec_desc.acl\0"
4001 "system.nt_sec_desc.acl+\0"
4002 "system.nt_sec_desc.*\0"
4003 "system.nt_sec_desc.*+\0"
4006 if (size == 0) {
4007 return sizeof(supported);
4010 if (sizeof(supported) > size) {
4011 errno = ERANGE;
4012 return -1;
4015 /* this can't be strcpy() because there are embedded null characters */
4016 memcpy(list, supported, sizeof(supported));
4017 return sizeof(supported);
4022 * Open a print file to be written to by other calls
4025 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
4027 fstring server, share, user, password;
4028 pstring path;
4030 if (!context || !context->internal ||
4031 !context->internal->_initialized) {
4033 errno = EINVAL;
4034 return NULL;
4038 if (!fname) {
4040 errno = EINVAL;
4041 return NULL;
4045 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
4047 if (smbc_parse_path(context, fname,
4048 server, sizeof(server),
4049 share, sizeof(share),
4050 path, sizeof(path),
4051 user, sizeof(user),
4052 password, sizeof(password),
4053 NULL, 0)) {
4054 errno = EINVAL;
4055 return NULL;
4058 /* What if the path is empty, or the file exists? */
4060 return context->open(context, fname, O_WRONLY, 666);
4065 * Routine to print a file on a remote server ...
4067 * We open the file, which we assume to be on a remote server, and then
4068 * copy it to a print file on the share specified by printq.
4071 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
4073 SMBCFILE *fid1, *fid2;
4074 int bytes, saverr, tot_bytes = 0;
4075 char buf[4096];
4077 if (!c_file || !c_file->internal->_initialized || !c_print ||
4078 !c_print->internal->_initialized) {
4080 errno = EINVAL;
4081 return -1;
4085 if (!fname && !printq) {
4087 errno = EINVAL;
4088 return -1;
4092 /* Try to open the file for reading ... */
4094 if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
4096 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
4097 return -1; /* smbc_open sets errno */
4101 /* Now, try to open the printer file for writing */
4103 if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
4105 saverr = errno; /* Save errno */
4106 c_file->close(c_file, fid1);
4107 errno = saverr;
4108 return -1;
4112 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
4114 tot_bytes += bytes;
4116 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
4118 saverr = errno;
4119 c_file->close(c_file, fid1);
4120 c_print->close(c_print, fid2);
4121 errno = saverr;
4127 saverr = errno;
4129 c_file->close(c_file, fid1); /* We have to close these anyway */
4130 c_print->close(c_print, fid2);
4132 if (bytes < 0) {
4134 errno = saverr;
4135 return -1;
4139 return tot_bytes;
4144 * Routine to list print jobs on a printer share ...
4147 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
4149 SMBCSRV *srv;
4150 fstring server, share, user, password, workgroup;
4151 pstring path;
4153 if (!context || !context->internal ||
4154 !context->internal->_initialized) {
4156 errno = EINVAL;
4157 return -1;
4161 if (!fname) {
4163 errno = EINVAL;
4164 return -1;
4168 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
4170 if (smbc_parse_path(context, fname,
4171 server, sizeof(server),
4172 share, sizeof(share),
4173 path, sizeof(path),
4174 user, sizeof(user),
4175 password, sizeof(password),
4176 NULL, 0)) {
4177 errno = EINVAL;
4178 return -1;
4181 if (user[0] == (char)0) fstrcpy(user, context->user);
4183 fstrcpy(workgroup, context->workgroup);
4185 srv = smbc_server(context, server, share, workgroup, user, password);
4187 if (!srv) {
4189 return -1; /* errno set by smbc_server */
4193 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
4195 errno = smbc_errno(context, &srv->cli);
4196 return -1;
4200 return 0;
4205 * Delete a print job from a remote printer share
4208 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
4210 SMBCSRV *srv;
4211 fstring server, share, user, password, workgroup;
4212 pstring path;
4213 int err;
4215 if (!context || !context->internal ||
4216 !context->internal->_initialized) {
4218 errno = EINVAL;
4219 return -1;
4223 if (!fname) {
4225 errno = EINVAL;
4226 return -1;
4230 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
4232 if (smbc_parse_path(context, fname,
4233 server, sizeof(server),
4234 share, sizeof(share),
4235 path, sizeof(path),
4236 user, sizeof(user),
4237 password, sizeof(password),
4238 NULL, 0)) {
4239 errno = EINVAL;
4240 return -1;
4243 if (user[0] == (char)0) fstrcpy(user, context->user);
4245 fstrcpy(workgroup, context->workgroup);
4247 srv = smbc_server(context, server, share, workgroup, user, password);
4249 if (!srv) {
4251 return -1; /* errno set by smbc_server */
4255 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
4257 if (err < 0)
4258 errno = smbc_errno(context, &srv->cli);
4259 else if (err == ERRnosuchprintjob)
4260 errno = EINVAL;
4261 return -1;
4265 return 0;
4270 * Get a new empty handle to fill in with your own info
4272 SMBCCTX * smbc_new_context(void)
4274 SMBCCTX * context;
4276 context = SMB_MALLOC_P(SMBCCTX);
4277 if (!context) {
4278 errno = ENOMEM;
4279 return NULL;
4282 ZERO_STRUCTP(context);
4284 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
4285 if (!context->internal) {
4286 errno = ENOMEM;
4287 return NULL;
4290 ZERO_STRUCTP(context->internal);
4293 /* ADD REASONABLE DEFAULTS */
4294 context->debug = 0;
4295 context->timeout = 20000; /* 20 seconds */
4297 context->open = smbc_open_ctx;
4298 context->creat = smbc_creat_ctx;
4299 context->read = smbc_read_ctx;
4300 context->write = smbc_write_ctx;
4301 context->close = smbc_close_ctx;
4302 context->unlink = smbc_unlink_ctx;
4303 context->rename = smbc_rename_ctx;
4304 context->lseek = smbc_lseek_ctx;
4305 context->stat = smbc_stat_ctx;
4306 context->fstat = smbc_fstat_ctx;
4307 context->opendir = smbc_opendir_ctx;
4308 context->closedir = smbc_closedir_ctx;
4309 context->readdir = smbc_readdir_ctx;
4310 context->getdents = smbc_getdents_ctx;
4311 context->mkdir = smbc_mkdir_ctx;
4312 context->rmdir = smbc_rmdir_ctx;
4313 context->telldir = smbc_telldir_ctx;
4314 context->lseekdir = smbc_lseekdir_ctx;
4315 context->fstatdir = smbc_fstatdir_ctx;
4316 context->chmod = smbc_chmod_ctx;
4317 context->utimes = smbc_utimes_ctx;
4318 context->setxattr = smbc_setxattr_ctx;
4319 context->getxattr = smbc_getxattr_ctx;
4320 context->removexattr = smbc_removexattr_ctx;
4321 context->listxattr = smbc_listxattr_ctx;
4322 context->open_print_job = smbc_open_print_job_ctx;
4323 context->print_file = smbc_print_file_ctx;
4324 context->list_print_jobs = smbc_list_print_jobs_ctx;
4325 context->unlink_print_job = smbc_unlink_print_job_ctx;
4327 context->callbacks.check_server_fn = smbc_check_server;
4328 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
4330 smbc_default_cache_functions(context);
4332 return context;
4336 * Free a context
4338 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
4339 * and thus you'll be leaking memory if not handled properly.
4342 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
4344 if (!context) {
4345 errno = EBADF;
4346 return 1;
4349 if (shutdown_ctx) {
4350 SMBCFILE * f;
4351 DEBUG(1,("Performing aggressive shutdown.\n"));
4353 f = context->internal->_files;
4354 while (f) {
4355 context->close(context, f);
4356 f = f->next;
4358 context->internal->_files = NULL;
4360 /* First try to remove the servers the nice way. */
4361 if (context->callbacks.purge_cached_fn(context)) {
4362 SMBCSRV * s;
4363 SMBCSRV * next;
4364 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
4365 s = context->internal->_servers;
4366 while (s) {
4367 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
4368 cli_shutdown(&s->cli);
4369 context->callbacks.remove_cached_srv_fn(context, s);
4370 next = s->next;
4371 DLIST_REMOVE(context->internal->_servers, s);
4372 SAFE_FREE(s);
4373 s = next;
4375 context->internal->_servers = NULL;
4378 else {
4379 /* This is the polite way */
4380 if (context->callbacks.purge_cached_fn(context)) {
4381 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
4382 errno = EBUSY;
4383 return 1;
4385 if (context->internal->_servers) {
4386 DEBUG(1, ("Active servers in context, free_context failed.\n"));
4387 errno = EBUSY;
4388 return 1;
4390 if (context->internal->_files) {
4391 DEBUG(1, ("Active files in context, free_context failed.\n"));
4392 errno = EBUSY;
4393 return 1;
4397 /* Things we have to clean up */
4398 SAFE_FREE(context->workgroup);
4399 SAFE_FREE(context->netbios_name);
4400 SAFE_FREE(context->user);
4402 DEBUG(3, ("Context %p succesfully freed\n", context));
4403 SAFE_FREE(context->internal);
4404 SAFE_FREE(context);
4405 return 0;
4410 * Initialise the library etc
4412 * We accept a struct containing handle information.
4413 * valid values for info->debug from 0 to 100,
4414 * and insist that info->fn must be non-null.
4416 SMBCCTX * smbc_init_context(SMBCCTX * context)
4418 pstring conf;
4419 int pid;
4420 char *user = NULL, *home = NULL;
4422 if (!context || !context->internal) {
4423 errno = EBADF;
4424 return NULL;
4427 /* Do not initialise the same client twice */
4428 if (context->internal->_initialized) {
4429 return 0;
4432 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
4434 errno = EINVAL;
4435 return NULL;
4439 if (!smbc_initialized) {
4440 /* Do some library wide intialisations the first time we get called */
4442 /* Set this to what the user wants */
4443 DEBUGLEVEL = context->debug;
4445 setup_logging( "libsmbclient", True);
4447 /* Here we would open the smb.conf file if needed ... */
4449 home = getenv("HOME");
4451 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
4453 load_interfaces(); /* Load the list of interfaces ... */
4455 in_client = True; /* FIXME, make a param */
4457 if (!lp_load(conf, True, False, False)) {
4460 * Well, if that failed, try the dyn_CONFIGFILE
4461 * Which points to the standard locn, and if that
4462 * fails, silently ignore it and use the internal
4463 * defaults ...
4466 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
4467 DEBUG(5, ("Could not load either config file: %s or %s\n",
4468 conf, dyn_CONFIGFILE));
4472 reopen_logs(); /* Get logging working ... */
4475 * Block SIGPIPE (from lib/util_sock.c: write())
4476 * It is not needed and should not stop execution
4478 BlockSignals(True, SIGPIPE);
4480 /* Done with one-time initialisation */
4481 smbc_initialized = 1;
4485 if (!context->user) {
4487 * FIXME: Is this the best way to get the user info?
4489 user = getenv("USER");
4490 /* walk around as "guest" if no username can be found */
4491 if (!user) context->user = SMB_STRDUP("guest");
4492 else context->user = SMB_STRDUP(user);
4495 if (!context->netbios_name) {
4497 * We try to get our netbios name from the config. If that fails we fall
4498 * back on constructing our netbios name from our hostname etc
4500 if (global_myname()) {
4501 context->netbios_name = SMB_STRDUP(global_myname());
4503 else {
4505 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
4507 pid = sys_getpid();
4508 context->netbios_name = SMB_MALLOC(17);
4509 if (!context->netbios_name) {
4510 errno = ENOMEM;
4511 return NULL;
4513 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
4517 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
4519 if (!context->workgroup) {
4520 if (lp_workgroup()) {
4521 context->workgroup = SMB_STRDUP(lp_workgroup());
4523 else {
4524 /* TODO: Think about a decent default workgroup */
4525 context->workgroup = SMB_STRDUP("samba");
4529 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
4531 /* shortest timeout is 1 second */
4532 if (context->timeout > 0 && context->timeout < 1000)
4533 context->timeout = 1000;
4536 * FIXME: Should we check the function pointers here?
4539 context->internal->_initialized = 1;
4541 return context;