Commit Derrell Lipman's changes and fixes to libsmbclient. The build but
[Samba/gebeck_regimport.git] / source / libsmb / libsmbclient.c
blob68bb6661ebdd6041a0c2ede5d2cf10b676db46c6
1 /*
2 Unix SMB/Netbios implementation.
3 SMB client library implementation
4 Copyright (C) Andrew Tridgell 1998
5 Copyright (C) Richard Sharpe 2000, 2002
6 Copyright (C) John Terpstra 2000
7 Copyright (C) Tom Jansen (Ninja ISD) 2002
8 Copyright (C) Derrell Lipman 2003
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 #include "includes.h"
27 #include "../include/libsmb_internal.h"
30 * Internal flags for extended attributes
33 /* internal mode values */
34 #define SMBC_XATTR_MODE_ADD 1
35 #define SMBC_XATTR_MODE_REMOVE 2
36 #define SMBC_XATTR_MODE_REMOVE_ALL 3
37 #define SMBC_XATTR_MODE_SET 4
38 #define SMBC_XATTR_MODE_CHOWN 5
39 #define SMBC_XATTR_MODE_CHGRP 6
41 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
43 /*We should test for this in configure ... */
44 #ifndef ENOTSUP
45 #define ENOTSUP EOPNOTSUPP
46 #endif
49 * Functions exported by libsmb_cache.c that we need here
51 int smbc_default_cache_functions(SMBCCTX *context);
53 /*
54 * check if an element is part of the list.
55 * FIXME: Does not belong here !
56 * Can anyone put this in a macro in dlinklist.h ?
57 * -- Tom
59 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
60 if (!p || !list) return False;
61 do {
62 if (p == list) return True;
63 list = list->next;
64 } while (list);
65 return False;
68 extern BOOL in_client;
71 * Is the logging working / configfile read ?
73 static int smbc_initialized = 0;
75 static int
76 hex2int( unsigned int _char )
78 if ( _char >= 'A' && _char <='F')
79 return _char - 'A' + 10;
80 if ( _char >= 'a' && _char <='f')
81 return _char - 'a' + 10;
82 if ( _char >= '0' && _char <='9')
83 return _char - '0';
84 return -1;
87 static void
88 decode_urlpart(char *segment, size_t sizeof_segment)
90 int old_length = strlen(segment);
91 int new_length = 0;
92 int new_length2 = 0;
93 int i = 0;
94 pstring new_segment;
95 char *new_usegment = 0;
97 if ( !old_length ) {
98 return;
101 /* make a copy of the old one */
102 new_usegment = (char*)malloc( old_length * 3 + 1 );
104 while( i < old_length ) {
105 int bReencode = False;
106 unsigned char character = segment[ i++ ];
107 if ((character <= ' ') || (character > 127))
108 bReencode = True;
110 new_usegment [ new_length2++ ] = character;
111 if (character == '%' ) {
112 int a = i+1 < old_length ? hex2int( segment[i] ) : -1;
113 int b = i+1 < old_length ? hex2int( segment[i+1] ) : -1;
114 if ((a == -1) || (b == -1)) { /* Only replace if sequence is valid */
115 /* Contains stray %, make sure to re-encode! */
116 bReencode = True;
117 } else {
118 /* Valid %xx sequence */
119 character = a * 16 + b; /* Replace with value of %dd */
120 if (!character)
121 break; /* Stop at %00 */
123 new_usegment [ new_length2++ ] = (unsigned char) segment[i++];
124 new_usegment [ new_length2++ ] = (unsigned char) segment[i++];
127 if (bReencode) {
128 unsigned int c = character / 16;
129 new_length2--;
130 new_usegment [ new_length2++ ] = '%';
132 c += (c > 9) ? ('A' - 10) : '0';
133 new_usegment[ new_length2++ ] = c;
135 c = character % 16;
136 c += (c > 9) ? ('A' - 10) : '0';
137 new_usegment[ new_length2++ ] = c;
140 new_segment [ new_length++ ] = character;
142 new_segment [ new_length ] = 0;
144 free(new_usegment);
146 /* realloc it with unix charset */
147 pull_utf8_allocate(&new_usegment, new_segment);
149 /* this assumes (very safely) that removing %aa sequences
150 only shortens the string */
151 strncpy(segment, new_usegment, sizeof_segment);
153 free(new_usegment);
157 * Function to parse a path and turn it into components
159 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
160 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
161 * general format ("smb:" only; we do not look for "cifs:"), and expand on
162 * what he calls "context", herein called "options" to avoid conflict with the
163 * SMBCCTX context used throughout this library. We add the "mb" keyword
164 * which applies as follows:
167 * We accept:
168 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
170 * Meaning of URLs:
172 * smb:// show all workgroups known by the first master browser found
173 * smb://?mb=.any same as smb:// (i.e. without any options)
175 * smb://?mb=.all show all workgroups known by every master browser found.
176 * Why might you want this? In an "appliance" application
177 * where the workgroup/domain being used on the local network
178 * is not known ahead of time, but where one wanted to
179 * provide network services via samba, a unique workgroup
180 * could be used. However, when the appliance is first
181 * started, the local samba instance's master browser has not
182 * synchronized with the other master browser(s) on the
183 * network (and might not synchronize for 12 minutes) and
184 * therefore is not aware of the workgroup/ domain names
185 * available on the network. This option may be used to
186 * overcome the problem of a libsmbclient application
187 * arbitrarily selecting the local (still ignorant) master
188 * browser to obtain its list of workgroups/domains and
189 * getting back a practically emmpty list. By requesting
190 * the list of workgroups/domains from each found master
191 * browser on the local network, a complete list of
192 * workgroups/domains can be built.
194 * smb://?mb=name NOT YET IMPLEMENTED -- show all workgroups known by the
195 * master browser whose name is "name"
197 * smb://name/ if name<1D> or name<1B> exists, list servers in
198 * workgroup, else, if name<20> exists, list all shares
199 * for server ...
201 * If "options" are provided, this function returns the entire option list as
202 * a string, for later parsing by the caller.
205 static const char *smbc_prefix = "smb:";
207 static int
208 smbc_parse_path(SMBCCTX *context,
209 const char *fname,
210 char *server, int server_len,
211 char *share, int share_len,
212 char *path, int path_len,
213 char *user, int user_len,
214 char *password, int password_len,
215 char *options, int options_len)
217 static pstring s;
218 pstring userinfo;
219 const char *p;
220 char *q, *r;
221 int len;
223 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
224 if (options != NULL && options_len > 0) {
225 options[0] = (char)0;
227 pstrcpy(s, fname);
229 /* see if it has the right prefix */
230 len = strlen(smbc_prefix);
231 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
232 return -1; /* What about no smb: ? */
235 p = s + len;
237 /* Watch the test below, we are testing to see if we should exit */
239 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
241 DEBUG(1, ("Invalid path (does not begin with smb://"));
242 return -1;
246 p += 2; /* Skip the double slash */
248 /* See if any options were specified */
249 if (q = strrchr(p, '?')) {
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 char *p;
541 const char *server_n = server;
542 fstring group;
543 pstring ipenv;
544 struct in_addr ip;
545 int tried_reverse = 0;
547 zero_ip(&ip);
548 ZERO_STRUCT(c);
550 if (server[0] == 0) {
551 errno = EPERM;
552 return NULL;
555 srv = find_server(context, server, share,
556 workgroup, username, password);
557 if (srv)
558 return srv;
560 make_nmb_name(&calling, context->netbios_name, 0x0);
561 make_nmb_name(&called , server, 0x20);
563 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
565 #if 0 /* djl: obsolete code? neither group nor p is used beyond here */
566 if ((p=strchr_m(server_n,'#')) &&
567 (strcmp(p+1,"1D")==0 || strcmp(p+1,"01")==0)) {
569 fstrcpy(group, server_n);
570 p = strchr_m(group,'#');
571 *p = 0;
574 #endif
576 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
578 again:
579 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
581 zero_ip(&ip);
583 /* have to open a new connection */
584 if (!cli_initialise(&c)) {
585 errno = ENOMEM;
586 return NULL;
589 c.timeout = context->timeout;
591 /* Force use of port 139 for first try, so browse lists can work */
592 c.port = 139;
594 if (!cli_connect(&c, server_n, &ip)) {
596 * Port 139 connection failed. Try port 445 to handle
597 * connections to newer (e.g. XP) hosts with NetBIOS disabled.
599 c.port = 445;
600 if (!cli_connect(&c, server_n, &ip)) {
601 errno = ENETUNREACH;
602 return NULL;
606 if (!cli_session_request(&c, &calling, &called)) {
607 cli_shutdown(&c);
608 if (strcmp(called.name, "*SMBSERVER")) {
609 make_nmb_name(&called , "*SMBSERVER", 0x20);
610 goto again;
612 else { /* Try one more time, but ensure we don't loop */
614 /* Only try this if server is an IP address ... */
616 if (is_ipaddress(server) && !tried_reverse) {
617 fstring remote_name;
618 struct in_addr rem_ip;
620 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
621 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
622 errno = ENOENT;
623 return NULL;
626 tried_reverse++; /* Yuck */
628 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
629 make_nmb_name(&called, remote_name, 0x20);
630 goto again;
636 errno = ENOENT;
637 return NULL;
640 DEBUG(4,(" session request ok\n"));
642 if (!cli_negprot(&c)) {
643 cli_shutdown(&c);
644 errno = ENOENT;
645 return NULL;
648 if (!cli_session_setup(&c, username,
649 password, strlen(password),
650 password, strlen(password),
651 workgroup) &&
652 /* try an anonymous login if it failed */
653 !cli_session_setup(&c, "", "", 1,"", 0, workgroup)) {
654 cli_shutdown(&c);
655 errno = EPERM;
656 return NULL;
659 DEBUG(4,(" session setup ok\n"));
661 if (!cli_send_tconX(&c, share, "?????",
662 password, strlen(password)+1)) {
663 errno = smbc_errno(context, &c);
664 cli_shutdown(&c);
665 return NULL;
668 DEBUG(4,(" tconx ok\n"));
671 * Ok, we have got a nice connection
672 * Let's find a free server_fd
675 srv = (SMBCSRV *)malloc(sizeof(*srv));
676 if (!srv) {
677 errno = ENOMEM;
678 goto failed;
681 ZERO_STRUCTP(srv);
682 srv->cli = c;
683 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
685 /* now add it to the cache (internal or external) */
686 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
687 DEBUG(3, (" Failed to add server to cache\n"));
688 goto failed;
692 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
693 server, share, srv));
695 DLIST_ADD(context->internal->_servers, srv);
696 return srv;
698 failed:
699 cli_shutdown(&c);
700 if (!srv) return NULL;
702 SAFE_FREE(srv);
703 return NULL;
707 * Connect to a server for getting/setting attributes, possibly on an existing
708 * connection. This works similarly to smbc_server().
710 SMBCSRV *smbc_attr_server(SMBCCTX *context,
711 const char *server, const char *share,
712 fstring workgroup,
713 fstring username, fstring password,
714 POLICY_HND *pol)
716 struct in_addr ip;
717 struct cli_state *ipc_cli;
718 NTSTATUS nt_status;
719 SMBCSRV *ipc_srv=NULL;
722 * See if we've already created this special connection. Reference
723 * our "special" share name 'IPC$$'.
725 ipc_srv = find_server(context, server, "IPC$$",
726 workgroup, username, password);
727 if (!ipc_srv) {
729 /* We didn't find a cached connection. Get the password */
730 if (*password == '\0') {
731 /* ... then retrieve it now. */
732 context->callbacks.auth_fn(server, share,
733 workgroup, sizeof(fstring),
734 username, sizeof(fstring),
735 password, sizeof(fstring));
738 zero_ip(&ip);
739 nt_status = cli_full_connection(&ipc_cli,
740 global_myname(), server,
741 &ip, 0, "IPC$", "?????",
742 username, workgroup,
743 password, 0,
744 Undefined, NULL);
745 if (! NT_STATUS_IS_OK(nt_status)) {
746 DEBUG(1,("cli_full_connection failed! (%s)\n",
747 nt_errstr(nt_status)));
748 errno = ENOTSUP;
749 return NULL;
752 if (!cli_nt_session_open(ipc_cli, PI_LSARPC)) {
753 DEBUG(1, ("cli_nt_session_open fail!\n"));
754 errno = ENOTSUP;
755 cli_shutdown(ipc_cli);
756 return NULL;
759 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
760 but NT sends 0x2000000 so we might as well do it too. */
762 nt_status = cli_lsa_open_policy(ipc_cli,
763 ipc_cli->mem_ctx,
764 True,
765 GENERIC_EXECUTE_ACCESS,
766 pol);
768 if (!NT_STATUS_IS_OK(nt_status)) {
769 errno = smbc_errno(context, ipc_cli);
770 cli_shutdown(ipc_cli);
771 return NULL;
774 ipc_srv = (SMBCSRV *)malloc(sizeof(*ipc_srv));
775 if (!ipc_srv) {
776 errno = ENOMEM;
777 cli_shutdown(ipc_cli);
778 return NULL;
781 ZERO_STRUCTP(ipc_srv);
782 ipc_srv->cli = *ipc_cli;
784 free(ipc_cli);
786 /* now add it to the cache (internal or external) */
788 errno = 0; /* let cache function set errno if it likes */
789 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
790 server,
791 "IPC$$",
792 workgroup,
793 username)) {
794 DEBUG(3, (" Failed to add server to cache\n"));
795 if (errno == 0) {
796 errno = ENOMEM;
798 cli_shutdown(&ipc_srv->cli);
799 free(ipc_srv);
800 return NULL;
803 DLIST_ADD(context->internal->_servers, ipc_srv);
806 return ipc_srv;
810 * Routine to open() a file ...
813 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
815 fstring server, share, user, password, workgroup;
816 pstring path;
817 SMBCSRV *srv = NULL;
818 SMBCFILE *file = NULL;
819 int fd;
821 if (!context || !context->internal ||
822 !context->internal->_initialized) {
824 errno = EINVAL; /* Best I can think of ... */
825 return NULL;
829 if (!fname) {
831 errno = EINVAL;
832 return NULL;
836 if (smbc_parse_path(context, fname,
837 server, sizeof(server),
838 share, sizeof(share),
839 path, sizeof(path),
840 user, sizeof(user),
841 password, sizeof(password),
842 NULL, 0)) {
843 errno = EINVAL;
844 return NULL;
847 if (user[0] == (char)0) fstrcpy(user, context->user);
849 fstrcpy(workgroup, context->workgroup);
851 srv = smbc_server(context, server, share, workgroup, user, password);
853 if (!srv) {
855 if (errno == EPERM) errno = EACCES;
856 return NULL; /* smbc_server sets errno */
860 /* Hmmm, the test for a directory is suspect here ... FIXME */
862 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
864 fd = -1;
867 else {
869 file = malloc(sizeof(SMBCFILE));
871 if (!file) {
873 errno = ENOMEM;
874 return NULL;
878 ZERO_STRUCTP(file);
880 if ((fd = cli_open(&srv->cli, path, flags, DENY_NONE)) < 0) {
882 /* Handle the error ... */
884 SAFE_FREE(file);
885 errno = smbc_errno(context, &srv->cli);
886 return NULL;
890 /* Fill in file struct */
892 file->cli_fd = fd;
893 file->fname = strdup(fname);
894 file->srv = srv;
895 file->offset = 0;
896 file->file = True;
898 DLIST_ADD(context->internal->_files, file);
899 return file;
903 /* Check if opendir needed ... */
905 if (fd == -1) {
906 int eno = 0;
908 eno = smbc_errno(context, &srv->cli);
909 file = context->opendir(context, fname);
910 if (!file) errno = eno;
911 return file;
915 errno = EINVAL; /* FIXME, correct errno ? */
916 return NULL;
921 * Routine to create a file
924 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
926 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
929 if (!context || !context->internal ||
930 !context->internal->_initialized) {
932 errno = EINVAL;
933 return NULL;
937 return smbc_open_ctx(context, path, creat_bits, mode);
941 * Routine to read() a file ...
944 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
946 int ret;
948 if (!context || !context->internal ||
949 !context->internal->_initialized) {
951 errno = EINVAL;
952 return -1;
956 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
958 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
960 errno = EBADF;
961 return -1;
965 /* Check that the buffer exists ... */
967 if (buf == NULL) {
969 errno = EINVAL;
970 return -1;
974 ret = cli_read(&file->srv->cli, file->cli_fd, buf, file->offset, count);
976 if (ret < 0) {
978 errno = smbc_errno(context, &file->srv->cli);
979 return -1;
983 file->offset += ret;
985 DEBUG(4, (" --> %d\n", ret));
987 return ret; /* Success, ret bytes of data ... */
992 * Routine to write() a file ...
995 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
997 int ret;
999 if (!context || !context->internal ||
1000 !context->internal->_initialized) {
1002 errno = EINVAL;
1003 return -1;
1007 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1009 errno = EBADF;
1010 return -1;
1014 /* Check that the buffer exists ... */
1016 if (buf == NULL) {
1018 errno = EINVAL;
1019 return -1;
1023 ret = cli_write(&file->srv->cli, file->cli_fd, 0, buf, file->offset, count);
1025 if (ret <= 0) {
1027 errno = smbc_errno(context, &file->srv->cli);
1028 return -1;
1032 file->offset += ret;
1034 return ret; /* Success, 0 bytes of data ... */
1038 * Routine to close() a file ...
1041 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1043 SMBCSRV *srv;
1045 if (!context || !context->internal ||
1046 !context->internal->_initialized) {
1048 errno = EINVAL;
1049 return -1;
1053 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1055 errno = EBADF;
1056 return -1;
1060 /* IS a dir ... */
1061 if (!file->file) {
1063 return context->closedir(context, file);
1067 if (!cli_close(&file->srv->cli, file->cli_fd)) {
1069 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1070 file->fname));
1071 /* Deallocate slot and remove the server
1072 * from the server cache if unused */
1073 errno = smbc_errno(context, &file->srv->cli);
1074 srv = file->srv;
1075 DLIST_REMOVE(context->internal->_files, file);
1076 SAFE_FREE(file->fname);
1077 SAFE_FREE(file);
1078 context->callbacks.remove_unused_server_fn(context, srv);
1080 return -1;
1084 DLIST_REMOVE(context->internal->_files, file);
1085 SAFE_FREE(file->fname);
1086 SAFE_FREE(file);
1088 return 0;
1092 * Get info from an SMB server on a file. Use a qpathinfo call first
1093 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1095 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1096 uint16 *mode, size_t *size,
1097 time_t *c_time, time_t *a_time, time_t *m_time,
1098 SMB_INO_T *ino)
1101 if (!context || !context->internal ||
1102 !context->internal->_initialized) {
1104 errno = EINVAL;
1105 return -1;
1109 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1111 if (!srv->no_pathinfo2 &&
1112 cli_qpathinfo2(&srv->cli, path, c_time, a_time, m_time, NULL,
1113 size, mode, ino)) return True;
1115 /* if this is NT then don't bother with the getatr */
1116 if (srv->cli.capabilities & CAP_NT_SMBS) {
1117 errno = EPERM;
1118 return False;
1121 if (cli_getatr(&srv->cli, path, mode, size, m_time)) {
1122 a_time = c_time = m_time;
1123 srv->no_pathinfo2 = True;
1124 return True;
1127 errno = EPERM;
1128 return False;
1133 * Routine to unlink() a file
1136 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1138 fstring server, share, user, password, workgroup;
1139 pstring path;
1140 SMBCSRV *srv = NULL;
1142 if (!context || !context->internal ||
1143 !context->internal->_initialized) {
1145 errno = EINVAL; /* Best I can think of ... */
1146 return -1;
1150 if (!fname) {
1152 errno = EINVAL;
1153 return -1;
1157 if (smbc_parse_path(context, fname,
1158 server, sizeof(server),
1159 share, sizeof(share),
1160 path, sizeof(path),
1161 user, sizeof(user),
1162 password, sizeof(password),
1163 NULL, 0)) {
1164 errno = EINVAL;
1165 return -1;
1168 if (user[0] == (char)0) fstrcpy(user, context->user);
1170 fstrcpy(workgroup, context->workgroup);
1172 srv = smbc_server(context, server, share, workgroup, user, password);
1174 if (!srv) {
1176 return -1; /* smbc_server sets errno */
1180 /* if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
1182 int job = smbc_stat_printjob(srv, path, NULL, NULL);
1183 if (job == -1) {
1185 return -1;
1188 if ((err = cli_printjob_del(&srv->cli, job)) != 0) {
1191 return -1;
1194 } else */
1196 if (!cli_unlink(&srv->cli, path)) {
1198 errno = smbc_errno(context, &srv->cli);
1200 if (errno == EACCES) { /* Check if the file is a directory */
1202 int saverr = errno;
1203 size_t size = 0;
1204 uint16 mode = 0;
1205 time_t m_time = 0, a_time = 0, c_time = 0;
1206 SMB_INO_T ino = 0;
1208 if (!smbc_getatr(context, srv, path, &mode, &size,
1209 &c_time, &a_time, &m_time, &ino)) {
1211 /* Hmmm, bad error ... What? */
1213 errno = smbc_errno(context, &srv->cli);
1214 return -1;
1217 else {
1219 if (IS_DOS_DIR(mode))
1220 errno = EISDIR;
1221 else
1222 errno = saverr; /* Restore this */
1227 return -1;
1231 return 0; /* Success ... */
1236 * Routine to rename() a file
1239 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1240 SMBCCTX *ncontext, const char *nname)
1242 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1243 pstring path1, path2;
1244 SMBCSRV *srv = NULL;
1246 if (!ocontext || !ncontext ||
1247 !ocontext->internal || !ncontext->internal ||
1248 !ocontext->internal->_initialized ||
1249 !ncontext->internal->_initialized) {
1251 errno = EINVAL; /* Best I can think of ... */
1252 return -1;
1256 if (!oname || !nname) {
1258 errno = EINVAL;
1259 return -1;
1263 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1265 smbc_parse_path(ocontext, oname,
1266 server1, sizeof(server1),
1267 share1, sizeof(share1),
1268 path1, sizeof(path1),
1269 user1, sizeof(user1),
1270 password1, sizeof(password1),
1271 NULL, 0);
1273 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1275 smbc_parse_path(ncontext, nname,
1276 server2, sizeof(server2),
1277 share2, sizeof(share2),
1278 path2, sizeof(path2),
1279 user2, sizeof(user2),
1280 password2, sizeof(password2),
1281 NULL, 0);
1283 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1285 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1286 strcmp(user1, user2)) {
1288 /* Can't rename across file systems, or users?? */
1290 errno = EXDEV;
1291 return -1;
1295 fstrcpy(workgroup, ocontext->workgroup);
1296 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1297 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1298 if (!srv) {
1300 return -1;
1304 if (!cli_rename(&srv->cli, path1, path2)) {
1305 int eno = smbc_errno(ocontext, &srv->cli);
1307 if (eno != EEXIST ||
1308 !cli_unlink(&srv->cli, path2) ||
1309 !cli_rename(&srv->cli, path1, path2)) {
1311 errno = eno;
1312 return -1;
1317 return 0; /* Success */
1322 * A routine to lseek() a file
1325 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1327 size_t size;
1329 if (!context || !context->internal ||
1330 !context->internal->_initialized) {
1332 errno = EINVAL;
1333 return -1;
1337 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1339 errno = EBADF;
1340 return -1;
1344 if (!file->file) {
1346 errno = EINVAL;
1347 return -1; /* Can't lseek a dir ... */
1351 switch (whence) {
1352 case SEEK_SET:
1353 file->offset = offset;
1354 break;
1356 case SEEK_CUR:
1357 file->offset += offset;
1358 break;
1360 case SEEK_END:
1361 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
1362 NULL, NULL, NULL))
1364 SMB_BIG_UINT b_size = size;
1365 if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
1366 NULL))
1368 errno = EINVAL;
1369 return -1;
1370 } else
1371 size = b_size;
1373 file->offset = size + offset;
1374 break;
1376 default:
1377 errno = EINVAL;
1378 break;
1382 return file->offset;
1387 * Generate an inode number from file name for those things that need it
1390 static
1391 ino_t smbc_inode(SMBCCTX *context, const char *name)
1394 if (!context || !context->internal ||
1395 !context->internal->_initialized) {
1397 errno = EINVAL;
1398 return -1;
1402 if (!*name) return 2; /* FIXME, why 2 ??? */
1403 return (ino_t)str_checksum(name);
1408 * Routine to put basic stat info into a stat structure ... Used by stat and
1409 * fstat below.
1412 static
1413 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname, size_t size, int mode)
1416 st->st_mode = 0;
1418 if (IS_DOS_DIR(mode)) {
1419 st->st_mode = SMBC_DIR_MODE;
1420 } else {
1421 st->st_mode = SMBC_FILE_MODE;
1424 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1425 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1426 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1427 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1429 st->st_size = size;
1430 #ifdef HAVE_STAT_ST_BLKSIZE
1431 st->st_blksize = 512;
1432 #endif
1433 #ifdef HAVE_STAT_ST_BLOCKS
1434 st->st_blocks = (size+511)/512;
1435 #endif
1436 st->st_uid = getuid();
1437 st->st_gid = getgid();
1439 if (IS_DOS_DIR(mode)) {
1440 st->st_nlink = 2;
1441 } else {
1442 st->st_nlink = 1;
1445 if (st->st_ino == 0) {
1446 st->st_ino = smbc_inode(context, fname);
1449 return True; /* FIXME: Is this needed ? */
1454 * Routine to stat a file given a name
1457 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1459 SMBCSRV *srv;
1460 fstring server, share, user, password, workgroup;
1461 pstring path;
1462 time_t m_time = 0, a_time = 0, c_time = 0;
1463 size_t size = 0;
1464 uint16 mode = 0;
1465 SMB_INO_T ino = 0;
1467 if (!context || !context->internal ||
1468 !context->internal->_initialized) {
1470 errno = EINVAL; /* Best I can think of ... */
1471 return -1;
1475 if (!fname) {
1477 errno = EINVAL;
1478 return -1;
1482 DEBUG(4, ("smbc_stat(%s)\n", fname));
1484 if (smbc_parse_path(context, fname,
1485 server, sizeof(server),
1486 share, sizeof(share),
1487 path, sizeof(path),
1488 user, sizeof(user),
1489 password, sizeof(password),
1490 NULL, 0)) {
1491 errno = EINVAL;
1492 return -1;
1495 if (user[0] == (char)0) fstrcpy(user, context->user);
1497 fstrcpy(workgroup, context->workgroup);
1499 srv = smbc_server(context, server, share, workgroup, user, password);
1501 if (!srv) {
1502 return -1; /* errno set by smbc_server */
1505 if (!smbc_getatr(context, srv, path, &mode, &size,
1506 &c_time, &a_time, &m_time, &ino)) {
1508 errno = smbc_errno(context, &srv->cli);
1509 return -1;
1513 st->st_ino = ino;
1515 smbc_setup_stat(context, st, path, size, mode);
1517 st->st_atime = a_time;
1518 st->st_ctime = c_time;
1519 st->st_mtime = m_time;
1520 st->st_dev = srv->dev;
1522 return 0;
1527 * Routine to stat a file given an fd
1530 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1532 time_t c_time, a_time, m_time;
1533 size_t size;
1534 uint16 mode;
1535 SMB_INO_T ino = 0;
1537 if (!context || !context->internal ||
1538 !context->internal->_initialized) {
1540 errno = EINVAL;
1541 return -1;
1545 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1547 errno = EBADF;
1548 return -1;
1552 if (!file->file) {
1554 return context->fstatdir(context, file, st);
1558 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
1559 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
1560 SMB_BIG_UINT b_size = size;
1561 if (!cli_getattrE(&file->srv->cli, file->cli_fd,
1562 &mode, &b_size, &c_time, &a_time, &m_time)) {
1564 errno = EINVAL;
1565 return -1;
1566 } else
1567 size = b_size;
1571 st->st_ino = ino;
1573 smbc_setup_stat(context, st, file->fname, size, mode);
1575 st->st_atime = a_time;
1576 st->st_ctime = c_time;
1577 st->st_mtime = m_time;
1578 st->st_dev = file->srv->dev;
1580 return 0;
1585 * Routine to open a directory
1586 * We accept the URL syntax explained in smbc_parse_path(), above.
1589 static void smbc_remove_dir(SMBCFILE *dir)
1591 struct smbc_dir_list *d,*f;
1593 d = dir->dir_list;
1594 while (d) {
1596 f = d; d = d->next;
1598 SAFE_FREE(f->dirent);
1599 SAFE_FREE(f);
1603 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
1607 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
1609 struct smbc_dirent *dirent;
1610 int size;
1611 char *u_name = NULL, *u_comment = NULL;
1612 size_t u_name_len = 0, u_comment_len = 0;
1614 if (name)
1615 u_name_len = push_utf8_allocate(&u_name, name);
1616 if (comment)
1617 u_comment_len = push_utf8_allocate(&u_comment, comment);
1620 * Allocate space for the dirent, which must be increased by the
1621 * size of the name and the comment and 1 for the null on the comment.
1622 * The null on the name is already accounted for.
1625 size = sizeof(struct smbc_dirent) + u_name_len + u_comment_len + 1;
1627 dirent = malloc(size);
1629 if (!dirent) {
1631 dir->dir_error = ENOMEM;
1632 return -1;
1636 ZERO_STRUCTP(dirent);
1638 if (dir->dir_list == NULL) {
1640 dir->dir_list = malloc(sizeof(struct smbc_dir_list));
1641 if (!dir->dir_list) {
1643 SAFE_FREE(dirent);
1644 dir->dir_error = ENOMEM;
1645 return -1;
1648 ZERO_STRUCTP(dir->dir_list);
1650 dir->dir_end = dir->dir_next = dir->dir_list;
1652 else {
1654 dir->dir_end->next = malloc(sizeof(struct smbc_dir_list));
1656 if (!dir->dir_end->next) {
1658 SAFE_FREE(dirent);
1659 dir->dir_error = ENOMEM;
1660 return -1;
1663 ZERO_STRUCTP(dir->dir_end->next);
1665 dir->dir_end = dir->dir_end->next;
1668 dir->dir_end->next = NULL;
1669 dir->dir_end->dirent = dirent;
1671 dirent->smbc_type = type;
1672 dirent->namelen = u_name_len;
1673 dirent->commentlen = u_comment_len;
1674 dirent->dirlen = size;
1676 strncpy(dirent->name, (u_name?u_name:""), dirent->namelen + 1);
1678 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
1679 strncpy(dirent->comment, (u_comment?u_comment:""), dirent->commentlen + 1);
1681 SAFE_FREE(u_comment);
1682 SAFE_FREE(u_name);
1684 return 0;
1688 static void
1689 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
1691 SMBCFILE *dir = (SMBCFILE *)state;
1692 struct smbc_dir_list *dir_list;
1693 struct smbc_dirent *dirent;
1694 int dirent_type;
1695 int remove = 0;
1697 dirent_type = dir->dir_type;
1699 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1701 /* An error occurred, what do we do? */
1702 /* FIXME: Add some code here */
1705 /* Point to the one just added */
1706 dirent = dir->dir_end->dirent;
1708 /* See if this was a duplicate */
1709 for (dir_list = dir->dir_list;
1710 dir_list != dir->dir_end;
1711 dir_list = dir_list->next) {
1712 if (! remove &&
1713 strcmp(dir_list->dirent->name, dirent->name) == 0) {
1714 /* Duplicate. End end of list need to be removed. */
1715 remove = 1;
1718 if (remove && dir_list->next == dir->dir_end) {
1719 /* Found the end of the list. Remove it. */
1720 dir->dir_end = dir_list;
1721 free(dir_list->next);
1722 dir_list->next = NULL;
1723 break;
1728 static void
1729 list_fn(const char *name, uint32 type, const char *comment, void *state)
1731 SMBCFILE *dir = (SMBCFILE *)state;
1732 int dirent_type;
1734 /* We need to process the type a little ... */
1736 if (dir->dir_type == SMBC_FILE_SHARE) {
1738 switch (type) {
1739 case 0: /* Directory tree */
1740 dirent_type = SMBC_FILE_SHARE;
1741 break;
1743 case 1:
1744 dirent_type = SMBC_PRINTER_SHARE;
1745 break;
1747 case 2:
1748 dirent_type = SMBC_COMMS_SHARE;
1749 break;
1751 case 3:
1752 dirent_type = SMBC_IPC_SHARE;
1753 break;
1755 default:
1756 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
1757 break;
1760 else dirent_type = dir->dir_type;
1762 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1764 /* An error occurred, what do we do? */
1765 /* FIXME: Add some code here */
1770 static void
1771 dir_list_fn(file_info *finfo, const char *mask, void *state)
1774 if (add_dirent((SMBCFILE *)state, finfo->name, "",
1775 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
1777 /* Handle an error ... */
1779 /* FIXME: Add some code ... */
1785 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
1787 fstring server, share, user, password, options;
1788 pstring workgroup;
1789 pstring path;
1790 SMBCSRV *srv = NULL;
1791 SMBCFILE *dir = NULL;
1792 struct in_addr rem_ip;
1794 if (!context || !context->internal ||
1795 !context->internal->_initialized) {
1796 DEBUG(4, ("no valid context\n"));
1797 errno = EINVAL;
1798 return NULL;
1802 if (!fname) {
1803 DEBUG(4, ("no valid fname\n"));
1804 errno = EINVAL;
1805 return NULL;
1808 if (smbc_parse_path(context, fname,
1809 server, sizeof(server),
1810 share, sizeof(share),
1811 path, sizeof(path),
1812 user, sizeof(path),
1813 password, sizeof(password),
1814 options, sizeof(options))) {
1815 DEBUG(4, ("no valid path\n"));
1816 errno = EINVAL;
1817 return NULL;
1820 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
1822 /* Ensure the options are valid */
1823 if (smbc_check_options(server, share, path, options)) {
1824 DEBUG(4, ("unacceptable options (%s)\n", options));
1825 errno = EINVAL;
1826 return NULL;
1829 if (user[0] == (char)0) fstrcpy(user, context->user);
1831 pstrcpy(workgroup, context->workgroup);
1833 dir = malloc(sizeof(*dir));
1835 if (!dir) {
1837 errno = ENOMEM;
1838 return NULL;
1842 ZERO_STRUCTP(dir);
1844 dir->cli_fd = 0;
1845 dir->fname = strdup(fname);
1846 dir->srv = NULL;
1847 dir->offset = 0;
1848 dir->file = False;
1849 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
1851 if (server[0] == (char)0 &&
1852 (! *options || strcmp(options, "mb=.any") == 0)) {
1853 struct in_addr server_ip;
1854 if (share[0] != (char)0 || path[0] != (char)0) {
1856 errno = EINVAL;
1857 if (dir) {
1858 SAFE_FREE(dir->fname);
1859 SAFE_FREE(dir);
1861 return NULL;
1865 * We have server and share and path empty ... so list the
1866 * workgroups first try to get the LMB for our workgroup, and
1867 * if that fails, try the DMB
1870 pstrcpy(workgroup, lp_workgroup());
1872 if (!find_master_ip(workgroup, &server_ip)) {
1873 struct user_auth_info u_info;
1874 struct cli_state *cli;
1876 DEBUG(4, ("Unable to find master browser for workgroup %s\n",
1877 workgroup));
1879 /* find the name of the server ... */
1880 pstrcpy(u_info.username, user);
1881 pstrcpy(u_info.password, password);
1883 if (!(cli = get_ipc_connect_master_ip_bcast(workgroup, &u_info))) {
1884 DEBUG(4, ("Unable to find master browser by "
1885 "broadcast\n"));
1886 errno = ENOENT;
1887 return NULL;
1890 fstrcpy(server, cli->desthost);
1892 cli_shutdown(cli);
1893 } else {
1895 * Do a name status query to find out the name of the
1896 * master browser. We use <01><02>__MSBROWSE__<02>#01 if
1897 * *#00 fails because a domain master browser will not
1898 * respond to a wildcard query (or, at least, an NT4
1899 * server acting as the domain master browser will not).
1901 * We might be able to use ONLY the query on MSBROWSE, but
1902 * that's not yet been tested with all Windows versions,
1903 * so until it is, leave the original wildcard query as
1904 * the first choice and fall back to MSBROWSE if the
1905 * wildcard query fails.
1907 if (!name_status_find("*", 0, 0x1d, server_ip, server) &&
1908 !name_status_find(MSBROWSE, 1, 0x1d, server_ip, server)) {
1909 errno = ENOENT;
1910 return NULL;
1914 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
1917 * Get a connection to IPC$ on the server if we do not already
1918 * have one
1921 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
1922 if (!srv) {
1924 if (dir) {
1925 SAFE_FREE(dir->fname);
1926 SAFE_FREE(dir);
1928 return NULL;
1931 dir->srv = srv;
1932 dir->dir_type = SMBC_WORKGROUP;
1934 /* Now, list the stuff ... */
1936 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_fn,
1937 (void *)dir)) {
1939 DEBUG(1, ("Could not enumerate domains using '%s'\n", workgroup));
1940 if (dir) {
1941 SAFE_FREE(dir->fname);
1942 SAFE_FREE(dir);
1944 errno = cli_errno(&srv->cli);
1946 return NULL;
1949 } else if (server[0] == (char)0 &&
1950 (! *options || strcmp(options, "mb=.all") == 0)) {
1952 int i;
1953 int count;
1954 struct ip_service *ip_list;
1955 struct ip_service server_addr;
1956 struct user_auth_info u_info;
1957 struct cli_state *cli;
1959 if (share[0] != (char)0 || path[0] != (char)0) {
1961 errno = EINVAL;
1962 if (dir) {
1963 SAFE_FREE(dir->fname);
1964 SAFE_FREE(dir);
1966 return NULL;
1969 pstrcpy(u_info.username, user);
1970 pstrcpy(u_info.password, password);
1973 * We have server and share and path empty but options
1974 * requesting that we scan all master browsers for their list
1975 * of workgroups/domains. This implies that we must first try
1976 * broadcast queries to find all master browsers, and if that
1977 * doesn't work, then try our other methods which return only
1978 * a single master browser.
1981 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
1982 if (!find_master_ip(workgroup, &server_addr.ip)) {
1984 errno = ENOENT;
1985 return NULL;
1988 ip_list = &server_addr;
1989 count = 1;
1992 for (i = 0; i < count; i++) {
1993 DEBUG(99, ("Found master browser %s\n", inet_ntoa(ip_list[i].ip)));
1995 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
1996 fstrcpy(server, cli->desthost);
1997 cli_shutdown(cli);
1999 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2002 * For each returned master browser IP address, get a
2003 * connection to IPC$ on the server if we do not
2004 * already have one, and determine the
2005 * workgroups/domains that it knows about.
2008 srv = smbc_server(context, server,
2009 "IPC$", workgroup, user, password);
2010 if (!srv) {
2012 if (dir) {
2013 SAFE_FREE(dir->fname);
2014 SAFE_FREE(dir);
2016 return NULL;
2019 dir->srv = srv;
2020 dir->dir_type = SMBC_WORKGROUP;
2022 /* Now, list the stuff ... */
2024 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2025 (void *)dir)) {
2027 if (dir) {
2028 SAFE_FREE(dir->fname);
2029 SAFE_FREE(dir);
2031 errno = cli_errno(&srv->cli);
2033 return NULL;
2037 } else {
2039 * Server not an empty string ... Check the rest and see what
2040 * gives
2042 if (share[0] == (char)0) {
2044 if (path[0] != (char)0) { /* Should not have empty share with path */
2046 errno = EINVAL;
2047 if (dir) {
2048 SAFE_FREE(dir->fname);
2049 SAFE_FREE(dir);
2051 return NULL;
2055 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2056 /* However, we check to see if <server> is an IP address first */
2058 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2059 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2060 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2061 fstring buserver;
2063 dir->dir_type = SMBC_SERVER;
2066 * Get the backup list ...
2070 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2072 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2073 errno = EPERM; /* FIXME, is this correct */
2074 return NULL;
2079 * Get a connection to IPC$ on the server if we do not already have one
2082 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2084 if (!srv) {
2085 DEBUG(0, ("got no contact to IPC$\n"));
2086 if (dir) {
2087 SAFE_FREE(dir->fname);
2088 SAFE_FREE(dir);
2090 return NULL;
2094 dir->srv = srv;
2096 /* Now, list the servers ... */
2098 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2099 (void *)dir)) {
2101 if (dir) {
2102 SAFE_FREE(dir->fname);
2103 SAFE_FREE(dir);
2105 errno = cli_errno(&srv->cli);
2106 return NULL;
2110 else {
2112 if (resolve_name(server, &rem_ip, 0x20)) {
2114 /* Now, list the shares ... */
2116 dir->dir_type = SMBC_FILE_SHARE;
2118 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2120 if (!srv) {
2122 if (dir) {
2123 SAFE_FREE(dir->fname);
2124 SAFE_FREE(dir);
2126 return NULL;
2130 dir->srv = srv;
2132 /* Now, list the servers ... */
2134 if (cli_RNetShareEnum(&srv->cli, list_fn,
2135 (void *)dir) < 0) {
2137 errno = cli_errno(&srv->cli);
2138 if (dir) {
2139 SAFE_FREE(dir->fname);
2140 SAFE_FREE(dir);
2142 return NULL;
2147 else {
2149 errno = ENODEV; /* Neither the workgroup nor server exists */
2150 if (dir) {
2151 SAFE_FREE(dir->fname);
2152 SAFE_FREE(dir);
2154 return NULL;
2161 else { /* The server and share are specified ... work from there ... */
2163 /* Well, we connect to the server and list the directory */
2165 dir->dir_type = SMBC_FILE_SHARE;
2167 srv = smbc_server(context, server, share, workgroup, user, password);
2169 if (!srv) {
2171 if (dir) {
2172 SAFE_FREE(dir->fname);
2173 SAFE_FREE(dir);
2175 return NULL;
2179 dir->srv = srv;
2181 /* Now, list the files ... */
2183 pstrcat(path, "\\*");
2185 if (cli_list(&srv->cli, path, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2186 (void *)dir) < 0) {
2188 if (dir) {
2189 SAFE_FREE(dir->fname);
2190 SAFE_FREE(dir);
2192 errno = smbc_errno(context, &srv->cli);
2193 return NULL;
2200 DLIST_ADD(context->internal->_files, dir);
2201 return dir;
2206 * Routine to close a directory
2209 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2212 if (!context || !context->internal ||
2213 !context->internal->_initialized) {
2215 errno = EINVAL;
2216 return -1;
2220 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2222 errno = EBADF;
2223 return -1;
2227 smbc_remove_dir(dir); /* Clean it up */
2229 DLIST_REMOVE(context->internal->_files, dir);
2231 if (dir) {
2233 SAFE_FREE(dir->fname);
2234 SAFE_FREE(dir); /* Free the space too */
2237 return 0;
2242 * Routine to get a directory entry
2245 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2247 struct smbc_dirent *dirp, *dirent;
2249 /* Check that all is ok first ... */
2251 if (!context || !context->internal ||
2252 !context->internal->_initialized) {
2254 errno = EINVAL;
2255 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2256 return NULL;
2260 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2262 errno = EBADF;
2263 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2264 return NULL;
2268 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2270 errno = ENOTDIR;
2271 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2272 return NULL;
2276 if (!dir->dir_next) {
2277 return NULL;
2279 else {
2281 dirent = dir->dir_next->dirent;
2282 if (!dirent) {
2284 errno = ENOENT;
2285 return NULL;
2289 /* Hmmm, do I even need to copy it? */
2291 memcpy(context->internal->_dirent, dirent, dirent->dirlen); /* Copy the dirent */
2292 dirp = (struct smbc_dirent *)context->internal->_dirent;
2293 dirp->comment = (char *)(&dirp->name + dirent->namelen + 1);
2294 dir->dir_next = dir->dir_next->next;
2296 return (struct smbc_dirent *)context->internal->_dirent;
2302 * Routine to get directory entries
2305 static int smbc_getdents_ctx(SMBCCTX *context, SMBCFILE *dir, struct smbc_dirent *dirp, int count)
2307 struct smbc_dir_list *dirlist;
2308 int rem = count, reqd;
2309 char *ndir = (char *)dirp;
2311 /* Check that all is ok first ... */
2313 if (!context || !context->internal ||
2314 !context->internal->_initialized) {
2316 errno = EINVAL;
2317 return -1;
2321 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2323 errno = EBADF;
2324 return -1;
2328 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2330 errno = ENOTDIR;
2331 return -1;
2336 * Now, retrieve the number of entries that will fit in what was passed
2337 * We have to figure out if the info is in the list, or we need to
2338 * send a request to the server to get the info.
2341 while ((dirlist = dir->dir_next)) {
2342 struct smbc_dirent *dirent;
2344 if (!dirlist->dirent) {
2346 errno = ENOENT; /* Bad error */
2347 return -1;
2351 if (rem < (reqd = (sizeof(struct smbc_dirent) + dirlist->dirent->namelen +
2352 dirlist->dirent->commentlen + 1))) {
2354 if (rem < count) { /* We managed to copy something */
2356 errno = 0;
2357 return count - rem;
2360 else { /* Nothing copied ... */
2362 errno = EINVAL; /* Not enough space ... */
2363 return -1;
2369 dirent = dirlist->dirent;
2371 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2373 ((struct smbc_dirent *)ndir)->comment =
2374 (char *)(&((struct smbc_dirent *)ndir)->name + dirent->namelen + 1);
2376 ndir += reqd;
2378 rem -= reqd;
2380 dir->dir_next = dirlist = dirlist -> next;
2383 if (rem == count)
2384 return 0;
2385 else
2386 return count - rem;
2391 * Routine to create a directory ...
2394 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2396 SMBCSRV *srv;
2397 fstring server, share, user, password, workgroup;
2398 pstring path;
2400 if (!context || !context->internal ||
2401 !context->internal->_initialized) {
2403 errno = EINVAL;
2404 return -1;
2408 if (!fname) {
2410 errno = EINVAL;
2411 return -1;
2415 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2417 if (smbc_parse_path(context, fname,
2418 server, sizeof(server),
2419 share, sizeof(share),
2420 path, sizeof(path),
2421 user, sizeof(user),
2422 password, sizeof(password),
2423 NULL, 0)) {
2424 errno = EINVAL;
2425 return -1;
2428 if (user[0] == (char)0) fstrcpy(user, context->user);
2430 fstrcpy(workgroup, context->workgroup);
2432 srv = smbc_server(context, server, share, workgroup, user, password);
2434 if (!srv) {
2436 return -1; /* errno set by smbc_server */
2440 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2442 mode = aDIR | aRONLY;
2445 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2447 if (strcmp(path, "\\") == 0) {
2449 mode = aDIR | aRONLY;
2452 else {
2454 mode = aRONLY;
2455 smbc_stat_printjob(srv, path, &size, &m_time);
2456 c_time = a_time = m_time;
2459 else { */
2461 if (!cli_mkdir(&srv->cli, path)) {
2463 errno = smbc_errno(context, &srv->cli);
2464 return -1;
2468 return 0;
2473 * Our list function simply checks to see if a directory is not empty
2476 static int smbc_rmdir_dirempty = True;
2478 static void rmdir_list_fn(file_info *finfo, const char *mask, void *state)
2481 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2482 smbc_rmdir_dirempty = False;
2487 * Routine to remove a directory
2490 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2492 SMBCSRV *srv;
2493 fstring server, share, user, password, workgroup;
2494 pstring path;
2496 if (!context || !context->internal ||
2497 !context->internal->_initialized) {
2499 errno = EINVAL;
2500 return -1;
2504 if (!fname) {
2506 errno = EINVAL;
2507 return -1;
2511 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2513 if (smbc_parse_path(context, fname,
2514 server, sizeof(server),
2515 share, sizeof(share),
2516 path, sizeof(path),
2517 user, sizeof(user),
2518 password, sizeof(password),
2519 NULL, 0))
2521 errno = EINVAL;
2522 return -1;
2525 if (user[0] == (char)0) fstrcpy(user, context->user);
2527 fstrcpy(workgroup, context->workgroup);
2529 srv = smbc_server(context, server, share, workgroup, user, password);
2531 if (!srv) {
2533 return -1; /* errno set by smbc_server */
2537 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2539 mode = aDIR | aRONLY;
2542 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2544 if (strcmp(path, "\\") == 0) {
2546 mode = aDIR | aRONLY;
2549 else {
2551 mode = aRONLY;
2552 smbc_stat_printjob(srv, path, &size, &m_time);
2553 c_time = a_time = m_time;
2556 else { */
2558 if (!cli_rmdir(&srv->cli, path)) {
2560 errno = smbc_errno(context, &srv->cli);
2562 if (errno == EACCES) { /* Check if the dir empty or not */
2564 pstring lpath; /* Local storage to avoid buffer overflows */
2566 smbc_rmdir_dirempty = True; /* Make this so ... */
2568 pstrcpy(lpath, path);
2569 pstrcat(lpath, "\\*");
2571 if (cli_list(&srv->cli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2572 NULL) < 0) {
2574 /* Fix errno to ignore latest error ... */
2576 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
2577 smbc_errno(context, &srv->cli)));
2578 errno = EACCES;
2582 if (smbc_rmdir_dirempty)
2583 errno = EACCES;
2584 else
2585 errno = ENOTEMPTY;
2589 return -1;
2593 return 0;
2598 * Routine to return the current directory position
2601 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
2603 off_t ret_val; /* Squash warnings about cast */
2605 if (!context || !context->internal ||
2606 !context->internal->_initialized) {
2608 errno = EINVAL;
2609 return -1;
2613 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2615 errno = EBADF;
2616 return -1;
2620 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2622 errno = ENOTDIR;
2623 return -1;
2628 * We return the pointer here as the offset
2630 ret_val = (int)dir->dir_next;
2631 return ret_val;
2636 * A routine to run down the list and see if the entry is OK
2639 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
2640 struct smbc_dirent *dirent)
2643 /* Run down the list looking for what we want */
2645 if (dirent) {
2647 struct smbc_dir_list *tmp = list;
2649 while (tmp) {
2651 if (tmp->dirent == dirent)
2652 return tmp;
2654 tmp = tmp->next;
2660 return NULL; /* Not found, or an error */
2666 * Routine to seek on a directory
2669 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
2671 long int l_offset = offset; /* Handle problems of size */
2672 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
2673 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
2675 if (!context || !context->internal ||
2676 !context->internal->_initialized) {
2678 errno = EINVAL;
2679 return -1;
2683 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2685 errno = ENOTDIR;
2686 return -1;
2690 /* Now, check what we were passed and see if it is OK ... */
2692 if (dirent == NULL) { /* Seek to the begining of the list */
2694 dir->dir_next = dir->dir_list;
2695 return 0;
2699 /* Now, run down the list and make sure that the entry is OK */
2700 /* This may need to be changed if we change the format of the list */
2702 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
2704 errno = EINVAL; /* Bad entry */
2705 return -1;
2709 dir->dir_next = list_ent;
2711 return 0;
2716 * Routine to fstat a dir
2719 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
2722 if (!context || !context->internal ||
2723 !context->internal->_initialized) {
2725 errno = EINVAL;
2726 return -1;
2730 /* No code yet ... */
2732 return 0;
2736 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
2738 SMBCSRV *srv;
2739 fstring server, share, user, password, workgroup;
2740 pstring path;
2741 uint16 mode;
2743 if (!context || !context->internal ||
2744 !context->internal->_initialized) {
2746 errno = EINVAL; /* Best I can think of ... */
2747 return -1;
2751 if (!fname) {
2753 errno = EINVAL;
2754 return -1;
2758 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
2760 if (smbc_parse_path(context, fname,
2761 server, sizeof(server),
2762 share, sizeof(share),
2763 path, sizeof(path),
2764 user, sizeof(user),
2765 password, sizeof(password),
2766 NULL, 0)) {
2767 errno = EINVAL;
2768 return -1;
2771 if (user[0] == (char)0) fstrcpy(user, context->user);
2773 fstrcpy(workgroup, context->workgroup);
2775 srv = smbc_server(context, server, share, workgroup, user, password);
2777 if (!srv) {
2778 return -1; /* errno set by smbc_server */
2781 mode = 0;
2783 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
2784 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
2785 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
2786 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
2788 if (!cli_setatr(&srv->cli, path, mode, 0)) {
2789 errno = smbc_errno(context, &srv->cli);
2790 return -1;
2793 return 0;
2796 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
2798 SMBCSRV *srv;
2799 fstring server, share, user, password, workgroup;
2800 pstring path;
2801 uint16 mode;
2802 time_t t = (tbuf == NULL ? time(NULL) : tbuf->tv_sec);
2804 if (!context || !context->internal ||
2805 !context->internal->_initialized) {
2807 errno = EINVAL; /* Best I can think of ... */
2808 return -1;
2812 if (!fname) {
2814 errno = EINVAL;
2815 return -1;
2819 DEBUG(4, ("smbc_utimes(%s, [%s])\n", fname, ctime(&t)));
2821 if (smbc_parse_path(context, fname,
2822 server, sizeof(server),
2823 share, sizeof(share),
2824 path, sizeof(path),
2825 user, sizeof(user),
2826 password, sizeof(password),
2827 NULL, 0)) {
2828 errno = EINVAL;
2829 return -1;
2832 if (user[0] == (char)0) fstrcpy(user, context->user);
2834 fstrcpy(workgroup, context->workgroup);
2836 srv = smbc_server(context, server, share, workgroup, user, password);
2838 if (!srv) {
2839 return -1; /* errno set by smbc_server */
2842 if (!smbc_getatr(context, srv, path,
2843 &mode, NULL,
2844 NULL, NULL, NULL,
2845 NULL)) {
2846 return -1;
2849 if (!cli_setatr(&srv->cli, path, mode, t)) {
2850 /* some servers always refuse directory changes */
2851 if (!(mode & aDIR)) {
2852 errno = smbc_errno(context, &srv->cli);
2853 return -1;
2857 return 0;
2861 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
2862 However NT4 gives a "The information may have been modified by a
2863 computer running Windows NT 5.0" if denied ACEs do not appear before
2864 allowed ACEs. */
2866 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
2868 if (sec_ace_equal(ace1, ace2))
2869 return 0;
2871 if (ace1->type != ace2->type)
2872 return ace2->type - ace1->type;
2874 if (sid_compare(&ace1->trustee, &ace2->trustee))
2875 return sid_compare(&ace1->trustee, &ace2->trustee);
2877 if (ace1->flags != ace2->flags)
2878 return ace1->flags - ace2->flags;
2880 if (ace1->info.mask != ace2->info.mask)
2881 return ace1->info.mask - ace2->info.mask;
2883 if (ace1->size != ace2->size)
2884 return ace1->size - ace2->size;
2886 return memcmp(ace1, ace2, sizeof(SEC_ACE));
2890 static void sort_acl(SEC_ACL *the_acl)
2892 uint32 i;
2893 if (!the_acl) return;
2895 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
2897 for (i=1;i<the_acl->num_aces;) {
2898 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
2899 int j;
2900 for (j=i; j<the_acl->num_aces-1; j++) {
2901 the_acl->ace[j] = the_acl->ace[j+1];
2903 the_acl->num_aces--;
2904 } else {
2905 i++;
2910 /* convert a SID to a string, either numeric or username/group */
2911 static void convert_sid_to_string(struct cli_state *ipc_cli,
2912 POLICY_HND *pol,
2913 fstring str,
2914 BOOL numeric,
2915 DOM_SID *sid)
2917 char **domains = NULL;
2918 char **names = NULL;
2919 uint32 *types = NULL;
2921 sid_to_string(str, sid);
2923 if (numeric) return; /* no lookup desired */
2925 /* Ask LSA to convert the sid to a name */
2927 if (!NT_STATUS_IS_OK(cli_lsa_lookup_sids(ipc_cli, ipc_cli->mem_ctx,
2928 pol, 1, sid, &domains,
2929 &names, &types)) ||
2930 !domains || !domains[0] || !names || !names[0]) {
2931 return;
2934 /* Converted OK */
2936 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
2937 domains[0], lp_winbind_separator(),
2938 names[0]);
2941 /* convert a string to a SID, either numeric or username/group */
2942 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
2943 POLICY_HND *pol,
2944 BOOL numeric,
2945 DOM_SID *sid,
2946 const char *str)
2948 uint32 *types = NULL;
2949 DOM_SID *sids = NULL;
2950 BOOL result = True;
2952 if (numeric) {
2953 if (strncmp(str, "S-", 2) == 0) {
2954 return string_to_sid(sid, str);
2957 result = False;
2958 goto done;
2961 if (!NT_STATUS_IS_OK(cli_lsa_lookup_names(ipc_cli, ipc_cli->mem_ctx,
2962 pol, 1, &str, &sids,
2963 &types))) {
2964 result = False;
2965 goto done;
2968 sid_copy(sid, &sids[0]);
2969 done:
2971 return result;
2975 /* parse an ACE in the same format as print_ace() */
2976 static BOOL parse_ace(struct cli_state *ipc_cli,
2977 POLICY_HND *pol,
2978 SEC_ACE *ace,
2979 BOOL numeric,
2980 char *str)
2982 char *p;
2983 const char *cp;
2984 fstring tok;
2985 unsigned atype, aflags, amask;
2986 DOM_SID sid;
2987 SEC_ACCESS mask;
2988 const struct perm_value *v;
2989 struct perm_value {
2990 const char *perm;
2991 uint32 mask;
2994 /* These values discovered by inspection */
2995 static const struct perm_value special_values[] = {
2996 { "R", 0x00120089 },
2997 { "W", 0x00120116 },
2998 { "X", 0x001200a0 },
2999 { "D", 0x00010000 },
3000 { "P", 0x00040000 },
3001 { "O", 0x00080000 },
3002 { NULL, 0 },
3005 static const struct perm_value standard_values[] = {
3006 { "READ", 0x001200a9 },
3007 { "CHANGE", 0x001301bf },
3008 { "FULL", 0x001f01ff },
3009 { NULL, 0 },
3013 ZERO_STRUCTP(ace);
3014 p = strchr_m(str,':');
3015 if (!p) return False;
3016 *p = '\0';
3017 p++;
3018 /* Try to parse numeric form */
3020 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3021 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3022 goto done;
3025 /* Try to parse text form */
3027 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3028 return False;
3031 cp = p;
3032 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3033 return False;
3036 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3037 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3038 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3039 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3040 } else {
3041 return False;
3044 /* Only numeric form accepted for flags at present */
3046 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3047 sscanf(tok, "%i", &aflags))) {
3048 return False;
3051 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3052 return False;
3055 if (strncmp(tok, "0x", 2) == 0) {
3056 if (sscanf(tok, "%i", &amask) != 1) {
3057 return False;
3059 goto done;
3062 for (v = standard_values; v->perm; v++) {
3063 if (strcmp(tok, v->perm) == 0) {
3064 amask = v->mask;
3065 goto done;
3069 p = tok;
3071 while(*p) {
3072 BOOL found = False;
3074 for (v = special_values; v->perm; v++) {
3075 if (v->perm[0] == *p) {
3076 amask |= v->mask;
3077 found = True;
3081 if (!found) return False;
3082 p++;
3085 if (*p) {
3086 return False;
3089 done:
3090 mask.mask = amask;
3091 init_sec_ace(ace, &sid, atype, mask, aflags);
3092 return True;
3095 /* add an ACE to a list of ACEs in a SEC_ACL */
3096 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3098 SEC_ACL *new;
3099 SEC_ACE *aces;
3100 if (! *the_acl) {
3101 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3102 return True;
3105 aces = calloc(1+(*the_acl)->num_aces,sizeof(SEC_ACE));
3106 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3107 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3108 new = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3109 SAFE_FREE(aces);
3110 (*the_acl) = new;
3111 return True;
3115 /* parse a ascii version of a security descriptor */
3116 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3117 struct cli_state *ipc_cli,
3118 POLICY_HND *pol,
3119 BOOL numeric,
3120 char *str)
3122 const char *p = str;
3123 fstring tok;
3124 SEC_DESC *ret;
3125 size_t sd_size;
3126 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3127 SEC_ACL *dacl=NULL;
3128 int revision=1;
3130 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3132 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3133 revision = strtol(tok+9, NULL, 16);
3134 continue;
3137 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3138 owner_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3139 if (!owner_sid ||
3140 !convert_string_to_sid(ipc_cli, pol,
3141 numeric,
3142 owner_sid, tok+6)) {
3143 DEBUG(5, ("Failed to parse owner sid\n"));
3144 return NULL;
3146 continue;
3149 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3150 owner_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3151 if (!owner_sid ||
3152 !convert_string_to_sid(ipc_cli, pol,
3153 False,
3154 owner_sid, tok+7)) {
3155 DEBUG(5, ("Failed to parse owner sid\n"));
3156 return NULL;
3158 continue;
3161 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3162 grp_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3163 if (!grp_sid ||
3164 !convert_string_to_sid(ipc_cli, pol,
3165 numeric,
3166 grp_sid, tok+6)) {
3167 DEBUG(5, ("Failed to parse group sid\n"));
3168 return NULL;
3170 continue;
3173 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3174 grp_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3175 if (!grp_sid ||
3176 !convert_string_to_sid(ipc_cli, pol,
3177 False,
3178 grp_sid, tok+6)) {
3179 DEBUG(5, ("Failed to parse group sid\n"));
3180 return NULL;
3182 continue;
3185 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3186 SEC_ACE ace;
3187 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3188 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3189 return NULL;
3191 if(!add_ace(&dacl, &ace, ctx)) {
3192 DEBUG(5, ("Failed to add ACL %s\n", tok));
3193 return NULL;
3195 continue;
3198 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3199 SEC_ACE ace;
3200 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3201 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3202 return NULL;
3204 if(!add_ace(&dacl, &ace, ctx)) {
3205 DEBUG(5, ("Failed to add ACL %s\n", tok));
3206 return NULL;
3208 continue;
3211 DEBUG(5, ("Failed to parse security descriptor\n"));
3212 return NULL;
3215 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3216 owner_sid, grp_sid, NULL, dacl, &sd_size);
3218 SAFE_FREE(grp_sid);
3219 SAFE_FREE(owner_sid);
3221 return ret;
3225 /*****************************************************
3226 retrieve the acls for a file
3227 *******************************************************/
3228 static int cacl_get(TALLOC_CTX *ctx, struct cli_state *cli,
3229 struct cli_state *ipc_cli, POLICY_HND *pol,
3230 char *filename, char *name, char *buf, int bufsize)
3232 uint32 i;
3233 int n = 0;
3234 int n_used;
3235 BOOL all;
3236 BOOL numeric = True;
3237 BOOL determine_size = (bufsize == 0);
3238 int fnum = -1;
3239 SEC_DESC *sd;
3240 fstring sidstr;
3241 char *p;
3243 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3245 if (fnum == -1) {
3246 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3247 filename, cli_errstr(cli)));
3248 errno = 0;
3249 return -1;
3252 sd = cli_query_secdesc(cli, fnum, ctx);
3254 if (!sd) {
3255 DEBUG(5, ("cacl_get Failed to query old descriptor\n"));
3256 errno = 0;
3257 return -1;
3260 cli_close(cli, fnum);
3262 all = (*name == '*');
3263 numeric = (* (name + strlen(name) - 1) != '+');
3265 n_used = 0;
3267 if (all) {
3268 if (determine_size) {
3269 p = talloc_asprintf(ctx,
3270 "REVISION:%d", sd->revision);
3271 if (!p) {
3272 errno = ENOMEM;
3273 return -1;
3275 n = strlen(p);
3276 } else {
3277 n = snprintf(buf, bufsize,
3278 "REVISION:%d", sd->revision);
3280 } else if (StrCaseCmp(name, "revision") == 0) {
3281 if (determine_size) {
3282 p = talloc_asprintf(ctx, "%d", sd->revision);
3283 if (!p) {
3284 errno = ENOMEM;
3285 return -1;
3287 n = strlen(p);
3288 } else {
3289 n = snprintf(buf, bufsize, "%d", sd->revision);
3293 if (!determine_size && n > bufsize) {
3294 errno = ERANGE;
3295 return -1;
3297 buf += n;
3298 n_used += n;
3299 bufsize -= n;
3301 /* Get owner and group sid */
3303 if (sd->owner_sid) {
3304 convert_sid_to_string(ipc_cli, pol,
3305 sidstr, numeric, sd->owner_sid);
3306 } else {
3307 fstrcpy(sidstr, "");
3310 if (all) {
3311 if (determine_size) {
3312 p = talloc_asprintf(ctx, ",OWNER:%s", sidstr);
3313 if (!p) {
3314 errno = ENOMEM;
3315 return -1;
3317 n = strlen(p);
3318 } else {
3319 n = snprintf(buf, bufsize, ",OWNER:%s", sidstr);
3321 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3322 if (determine_size) {
3323 p = talloc_asprintf(ctx, "%s", sidstr);
3324 if (!p) {
3325 errno = ENOMEM;
3326 return -1;
3328 n = strlen(p);
3329 } else {
3330 n = snprintf(buf, bufsize, "%s", sidstr);
3334 if (!determine_size && n > bufsize) {
3335 errno = ERANGE;
3336 return -1;
3338 buf += n;
3339 n_used += n;
3340 bufsize -= n;
3342 if (sd->grp_sid) {
3343 convert_sid_to_string(ipc_cli, pol,
3344 sidstr, numeric, sd->grp_sid);
3345 } else {
3346 fstrcpy(sidstr, "");
3349 if (all) {
3350 if (determine_size) {
3351 p = talloc_asprintf(ctx, ",GROUP:%s", sidstr);
3352 if (!p) {
3353 errno = ENOMEM;
3354 return -1;
3356 n = strlen(p);
3357 } else {
3358 n = snprintf(buf, bufsize, ",GROUP:%s", sidstr);
3360 } else if (StrnCaseCmp(name, "group", 5) == 0) {
3361 if (determine_size) {
3362 p = talloc_asprintf(ctx, "%s", sidstr);
3363 if (!p) {
3364 errno = ENOMEM;
3365 return -1;
3367 n = strlen(p);
3368 } else {
3369 n = snprintf(buf, bufsize, "%s", sidstr);
3373 if (!determine_size && n > bufsize) {
3374 errno = ERANGE;
3375 return -1;
3377 buf += n;
3378 n_used += n;
3379 bufsize -= n;
3381 /* Add aces to value buffer */
3382 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
3384 SEC_ACE *ace = &sd->dacl->ace[i];
3385 convert_sid_to_string(ipc_cli, pol,
3386 sidstr, numeric, &ace->trustee);
3388 if (all) {
3389 if (determine_size) {
3390 p = talloc_asprintf(ctx,
3391 ",ACL:%s:%d/%d/0x%08x",
3392 sidstr,
3393 ace->type,
3394 ace->flags,
3395 ace->info.mask);
3396 if (!p) {
3397 errno = ENOMEM;
3398 return -1;
3400 n = strlen(p);
3401 } else {
3402 n = snprintf(buf, bufsize,
3403 ",ACL:%s:%d/%d/0x%08x",
3404 sidstr,
3405 ace->type,
3406 ace->flags,
3407 ace->info.mask);
3409 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
3410 StrCaseCmp(name + 3, sidstr) == 0) ||
3411 (StrnCaseCmp(name, "acl+", 4) == 0 &&
3412 StrCaseCmp(name + 4, sidstr) == 0)) {
3413 if (determine_size) {
3414 p = talloc_asprintf(ctx,
3415 "%d/%d/0x%08x",
3416 ace->type,
3417 ace->flags,
3418 ace->info.mask);
3419 if (!p) {
3420 errno = ENOMEM;
3421 return -1;
3423 n = strlen(p);
3424 } else {
3425 n = snprintf(buf, bufsize,
3426 "%d/%d/0x%08x",
3427 ace->type, ace->flags, ace->info.mask);
3430 if (n > bufsize) {
3431 errno = ERANGE;
3432 return -1;
3434 buf += n;
3435 n_used += n;
3436 bufsize -= n;
3439 if (n_used == 0) {
3440 errno = ENOATTR;
3441 return -1;
3443 return n_used;
3447 /*****************************************************
3448 set the ACLs on a file given an ascii description
3449 *******************************************************/
3450 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
3451 struct cli_state *ipc_cli, POLICY_HND *pol,
3452 const char *filename, const char *the_acl,
3453 int mode, int flags)
3455 int fnum;
3456 int err = 0;
3457 SEC_DESC *sd = NULL, *old;
3458 SEC_ACL *dacl = NULL;
3459 DOM_SID *owner_sid = NULL;
3460 DOM_SID *grp_sid = NULL;
3461 uint32 i, j;
3462 size_t sd_size;
3463 int ret = 0;
3464 char *p;
3465 BOOL numeric = True;
3467 /* the_acl will be null for REMOVE_ALL operations */
3468 if (the_acl) {
3469 numeric = ((p = strchr(the_acl, ':')) != NULL &&
3470 p > the_acl &&
3471 p[-1] != '+');
3473 /* if this is to set the entire ACL... */
3474 if (*the_acl == '*') {
3475 /* ... then increment past the first colon */
3476 the_acl = p + 1;
3479 sd = sec_desc_parse(ctx, ipc_cli, pol,
3480 numeric, (char *) the_acl);
3482 if (!sd) {
3483 errno = EINVAL;
3484 return -1;
3488 /* The desired access below is the only one I could find that works
3489 with NT4, W2KP and Samba */
3491 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3493 if (fnum == -1) {
3494 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3495 filename, cli_errstr(cli)));
3496 errno = 0;
3497 return -1;
3500 old = cli_query_secdesc(cli, fnum, ctx);
3502 if (!old) {
3503 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
3504 errno = 0;
3505 return -1;
3508 cli_close(cli, fnum);
3510 switch (mode) {
3511 case SMBC_XATTR_MODE_REMOVE_ALL:
3512 old->dacl->num_aces = 0;
3513 SAFE_FREE(old->dacl->ace);
3514 SAFE_FREE(old->dacl);
3515 old->off_dacl = 0;
3516 dacl = old->dacl;
3517 break;
3519 case SMBC_XATTR_MODE_REMOVE:
3520 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3521 BOOL found = False;
3523 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3524 if (sec_ace_equal(&sd->dacl->ace[i],
3525 &old->dacl->ace[j])) {
3526 uint32 k;
3527 for (k=j; k<old->dacl->num_aces-1;k++) {
3528 old->dacl->ace[k] = old->dacl->ace[k+1];
3530 old->dacl->num_aces--;
3531 if (old->dacl->num_aces == 0) {
3532 SAFE_FREE(old->dacl->ace);
3533 SAFE_FREE(old->dacl);
3534 old->off_dacl = 0;
3536 found = True;
3537 dacl = old->dacl;
3538 break;
3542 if (!found) {
3543 err = ENOATTR;
3544 ret = -1;
3545 goto failed;
3548 break;
3550 case SMBC_XATTR_MODE_ADD:
3551 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3552 BOOL found = False;
3554 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3555 if (sid_equal(&sd->dacl->ace[i].trustee,
3556 &old->dacl->ace[j].trustee)) {
3557 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
3558 err = EEXIST;
3559 ret = -1;
3560 goto failed;
3562 old->dacl->ace[j] = sd->dacl->ace[i];
3563 ret = -1;
3564 found = True;
3568 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
3569 err = ENOATTR;
3570 ret = -1;
3571 goto failed;
3574 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3575 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
3578 dacl = old->dacl;
3579 break;
3581 case SMBC_XATTR_MODE_SET:
3582 old = sd;
3583 owner_sid = old->owner_sid;
3584 grp_sid = old->grp_sid;
3585 dacl = old->dacl;
3586 break;
3588 case SMBC_XATTR_MODE_CHOWN:
3589 owner_sid = sd->owner_sid;
3590 break;
3592 case SMBC_XATTR_MODE_CHGRP:
3593 grp_sid = sd->grp_sid;
3594 break;
3597 /* Denied ACE entries must come before allowed ones */
3598 sort_acl(old->dacl);
3600 /* Create new security descriptor and set it */
3601 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
3602 owner_sid, grp_sid, NULL, dacl, &sd_size);
3604 fnum = cli_nt_create(cli, filename,
3605 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
3607 if (fnum == -1) {
3608 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3609 filename, cli_errstr(cli)));
3610 errno = 0;
3611 return -1;
3614 if (!cli_set_secdesc(cli, fnum, sd)) {
3615 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
3616 ret = -1;
3619 /* Clean up */
3621 failed:
3622 cli_close(cli, fnum);
3624 if (err != 0) {
3625 errno = err;
3628 return ret;
3632 int smbc_setxattr_ctx(SMBCCTX *context,
3633 const char *fname,
3634 const char *name,
3635 const void *value,
3636 size_t size,
3637 int flags)
3639 int ret;
3640 SMBCSRV *srv;
3641 SMBCSRV *ipc_srv;
3642 fstring server, share, user, password, workgroup;
3643 pstring path;
3644 TALLOC_CTX *ctx;
3645 POLICY_HND pol;
3647 if (!context || !context->internal ||
3648 !context->internal->_initialized) {
3650 errno = EINVAL; /* Best I can think of ... */
3651 return -1;
3655 if (!fname) {
3657 errno = EINVAL;
3658 return -1;
3662 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
3663 fname, name, (int) size, (char *) value));
3665 if (smbc_parse_path(context, fname,
3666 server, sizeof(server),
3667 share, sizeof(share),
3668 path, sizeof(path),
3669 user, sizeof(user),
3670 password, sizeof(password),
3671 NULL, 0)) {
3672 errno = EINVAL;
3673 return -1;
3676 if (user[0] == (char)0) fstrcpy(user, context->user);
3678 fstrcpy(workgroup, context->workgroup);
3680 srv = smbc_server(context, server, share, workgroup, user, password);
3681 if (!srv) {
3682 return -1; /* errno set by smbc_server */
3685 ipc_srv = smbc_attr_server(context, server, share,
3686 workgroup, user, password,
3687 &pol);
3688 if (!ipc_srv) {
3689 return -1;
3692 ctx = talloc_init("smbc_setxattr");
3693 if (!ctx) {
3694 errno = ENOMEM;
3695 return -1;
3699 * Are they asking to set an access control element or to set
3700 * the entire access control list?
3702 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3703 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3704 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3705 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3706 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3708 /* Yup. */
3709 char *namevalue =
3710 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3711 if (! namevalue) {
3712 errno = ENOMEM;
3713 ret = -1;
3714 } else {
3715 ret = cacl_set(ctx, &srv->cli,
3716 &ipc_srv->cli, &pol, path,
3717 namevalue,
3718 (*namevalue == '*'
3719 ? SMBC_XATTR_MODE_SET
3720 : SMBC_XATTR_MODE_ADD),
3721 flags);
3723 talloc_destroy(ctx);
3724 return ret;
3728 * Are they asking to set the owner?
3730 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3731 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
3733 /* Yup. */
3734 char *namevalue =
3735 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3736 if (! namevalue) {
3737 errno = ENOMEM;
3738 ret = -1;
3739 } else {
3740 ret = cacl_set(ctx, &srv->cli,
3741 &ipc_srv->cli, &pol, path,
3742 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3744 talloc_destroy(ctx);
3745 return ret;
3749 * Are they asking to set the group?
3751 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3752 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
3754 /* Yup. */
3755 char *namevalue =
3756 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3757 if (! namevalue) {
3758 errno = ENOMEM;
3759 ret = -1;
3760 } else {
3761 ret = cacl_set(ctx, &srv->cli,
3762 &ipc_srv->cli, &pol, path,
3763 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3765 talloc_destroy(ctx);
3766 return ret;
3769 /* Unsupported attribute name */
3770 talloc_destroy(ctx);
3771 errno = EINVAL;
3772 return -1;
3775 int smbc_getxattr_ctx(SMBCCTX *context,
3776 const char *fname,
3777 const char *name,
3778 const void *value,
3779 size_t size)
3781 int ret;
3782 SMBCSRV *srv;
3783 SMBCSRV *ipc_srv;
3784 fstring server, share, user, password, workgroup;
3785 pstring path;
3786 TALLOC_CTX *ctx;
3787 POLICY_HND pol;
3789 if (!context || !context->internal ||
3790 !context->internal->_initialized) {
3792 errno = EINVAL; /* Best I can think of ... */
3793 return -1;
3797 if (!fname) {
3799 errno = EINVAL;
3800 return -1;
3804 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
3806 if (smbc_parse_path(context, fname,
3807 server, sizeof(server),
3808 share, sizeof(share),
3809 path, sizeof(path),
3810 user, sizeof(user),
3811 password, sizeof(password),
3812 NULL, 0)) {
3813 errno = EINVAL;
3814 return -1;
3817 if (user[0] == (char)0) fstrcpy(user, context->user);
3819 fstrcpy(workgroup, context->workgroup);
3821 srv = smbc_server(context, server, share, workgroup, user, password);
3822 if (!srv) {
3823 return -1; /* errno set by smbc_server */
3826 ipc_srv = smbc_attr_server(context, server, share,
3827 workgroup, user, password,
3828 &pol);
3829 if (!ipc_srv) {
3830 return -1;
3833 ctx = talloc_init("smbc:getxattr");
3834 if (!ctx) {
3835 errno = ENOMEM;
3836 return -1;
3839 /* Are they requesting a supported attribute? */
3840 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3841 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3842 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3843 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3844 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3845 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3846 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3847 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3848 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3850 /* Yup. */
3851 ret = cacl_get(ctx, &srv->cli,
3852 &ipc_srv->cli, &pol,
3853 (char *) path, (char *) name + 19,
3854 (char *) value, size);
3855 if (ret < 0 && errno == 0) {
3856 errno = smbc_errno(context, &srv->cli);
3858 talloc_destroy(ctx);
3859 return ret;
3862 /* Unsupported attribute name */
3863 talloc_destroy(ctx);
3864 errno = EINVAL;
3865 return -1;
3869 int smbc_removexattr_ctx(SMBCCTX *context,
3870 const char *fname,
3871 const char *name)
3873 int ret;
3874 SMBCSRV *srv;
3875 SMBCSRV *ipc_srv;
3876 fstring server, share, user, password, workgroup;
3877 pstring path;
3878 TALLOC_CTX *ctx;
3879 POLICY_HND pol;
3881 if (!context || !context->internal ||
3882 !context->internal->_initialized) {
3884 errno = EINVAL; /* Best I can think of ... */
3885 return -1;
3889 if (!fname) {
3891 errno = EINVAL;
3892 return -1;
3896 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
3898 if (smbc_parse_path(context, fname,
3899 server, sizeof(server),
3900 share, sizeof(share),
3901 path, sizeof(path),
3902 user, sizeof(user),
3903 password, sizeof(password),
3904 NULL, 0)) {
3905 errno = EINVAL;
3906 return -1;
3909 if (user[0] == (char)0) fstrcpy(user, context->user);
3911 fstrcpy(workgroup, context->workgroup);
3913 srv = smbc_server(context, server, share, workgroup, user, password);
3914 if (!srv) {
3915 return -1; /* errno set by smbc_server */
3918 ipc_srv = smbc_attr_server(context, server, share,
3919 workgroup, user, password,
3920 &pol);
3921 if (!ipc_srv) {
3922 return -1;
3925 ipc_srv = smbc_attr_server(context, server, share,
3926 workgroup, user, password,
3927 &pol);
3928 if (!ipc_srv) {
3929 return -1;
3932 ctx = talloc_init("smbc_removexattr");
3933 if (!ctx) {
3934 errno = ENOMEM;
3935 return -1;
3938 /* Are they asking to set the entire ACL? */
3939 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3940 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
3942 /* Yup. */
3943 ret = cacl_set(ctx, &srv->cli,
3944 &ipc_srv->cli, &pol, path,
3945 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
3946 talloc_destroy(ctx);
3947 return ret;
3951 * Are they asking to remove one or more spceific security descriptor
3952 * attributes?
3954 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3955 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3956 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3957 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3958 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3959 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3960 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3962 /* Yup. */
3963 ret = cacl_set(ctx, &srv->cli,
3964 &ipc_srv->cli, &pol, path,
3965 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
3966 talloc_destroy(ctx);
3967 return ret;
3970 /* Unsupported attribute name */
3971 talloc_destroy(ctx);
3972 errno = EINVAL;
3973 return -1;
3976 int smbc_listxattr_ctx(SMBCCTX *context,
3977 const char *fname,
3978 char *list,
3979 size_t size)
3982 * This isn't quite what listxattr() is supposed to do. This returns
3983 * the complete set of attributes, always, rather than only those
3984 * attribute names which actually exist for a file. Hmmm...
3986 const char supported[] =
3987 "system.nt_sec_desc.revision\0"
3988 "system.nt_sec_desc.owner\0"
3989 "system.nt_sec_desc.owner+\0"
3990 "system.nt_sec_desc.group\0"
3991 "system.nt_sec_desc.group+\0"
3992 "system.nt_sec_desc.acl\0"
3993 "system.nt_sec_desc.acl+\0"
3994 "system.nt_sec_desc.*\0"
3995 "system.nt_sec_desc.*+\0"
3998 if (size == 0) {
3999 return sizeof(supported);
4002 if (sizeof(supported) > size) {
4003 errno = ERANGE;
4004 return -1;
4007 /* this can't be strcpy() because there are embedded null characters */
4008 memcpy(list, supported, sizeof(supported));
4009 return sizeof(supported);
4014 * Open a print file to be written to by other calls
4017 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
4019 fstring server, share, user, password;
4020 pstring path;
4022 if (!context || !context->internal ||
4023 !context->internal->_initialized) {
4025 errno = EINVAL;
4026 return NULL;
4030 if (!fname) {
4032 errno = EINVAL;
4033 return NULL;
4037 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
4039 if (smbc_parse_path(context, fname,
4040 server, sizeof(server),
4041 share, sizeof(share),
4042 path, sizeof(path),
4043 user, sizeof(user),
4044 password, sizeof(password),
4045 NULL, 0)) {
4046 errno = EINVAL;
4047 return NULL;
4050 /* What if the path is empty, or the file exists? */
4052 return context->open(context, fname, O_WRONLY, 666);
4057 * Routine to print a file on a remote server ...
4059 * We open the file, which we assume to be on a remote server, and then
4060 * copy it to a print file on the share specified by printq.
4063 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
4065 SMBCFILE *fid1, *fid2;
4066 int bytes, saverr, tot_bytes = 0;
4067 char buf[4096];
4069 if (!c_file || !c_file->internal->_initialized || !c_print ||
4070 !c_print->internal->_initialized) {
4072 errno = EINVAL;
4073 return -1;
4077 if (!fname && !printq) {
4079 errno = EINVAL;
4080 return -1;
4084 /* Try to open the file for reading ... */
4086 if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
4088 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
4089 return -1; /* smbc_open sets errno */
4093 /* Now, try to open the printer file for writing */
4095 if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
4097 saverr = errno; /* Save errno */
4098 c_file->close(c_file, fid1);
4099 errno = saverr;
4100 return -1;
4104 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
4106 tot_bytes += bytes;
4108 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
4110 saverr = errno;
4111 c_file->close(c_file, fid1);
4112 c_print->close(c_print, fid2);
4113 errno = saverr;
4119 saverr = errno;
4121 c_file->close(c_file, fid1); /* We have to close these anyway */
4122 c_print->close(c_print, fid2);
4124 if (bytes < 0) {
4126 errno = saverr;
4127 return -1;
4131 return tot_bytes;
4136 * Routine to list print jobs on a printer share ...
4139 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
4141 SMBCSRV *srv;
4142 fstring server, share, user, password, workgroup;
4143 pstring path;
4145 if (!context || !context->internal ||
4146 !context->internal->_initialized) {
4148 errno = EINVAL;
4149 return -1;
4153 if (!fname) {
4155 errno = EINVAL;
4156 return -1;
4160 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
4162 if (smbc_parse_path(context, fname,
4163 server, sizeof(server),
4164 share, sizeof(share),
4165 path, sizeof(path),
4166 user, sizeof(user),
4167 password, sizeof(password),
4168 NULL, 0)) {
4169 errno = EINVAL;
4170 return -1;
4173 if (user[0] == (char)0) fstrcpy(user, context->user);
4175 fstrcpy(workgroup, context->workgroup);
4177 srv = smbc_server(context, server, share, workgroup, user, password);
4179 if (!srv) {
4181 return -1; /* errno set by smbc_server */
4185 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
4187 errno = smbc_errno(context, &srv->cli);
4188 return -1;
4192 return 0;
4197 * Delete a print job from a remote printer share
4200 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
4202 SMBCSRV *srv;
4203 fstring server, share, user, password, workgroup;
4204 pstring path;
4205 int err;
4207 if (!context || !context->internal ||
4208 !context->internal->_initialized) {
4210 errno = EINVAL;
4211 return -1;
4215 if (!fname) {
4217 errno = EINVAL;
4218 return -1;
4222 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
4224 if (smbc_parse_path(context, fname,
4225 server, sizeof(server),
4226 share, sizeof(share),
4227 path, sizeof(path),
4228 user, sizeof(user),
4229 password, sizeof(password),
4230 NULL, 0)) {
4231 errno = EINVAL;
4232 return -1;
4235 if (user[0] == (char)0) fstrcpy(user, context->user);
4237 fstrcpy(workgroup, context->workgroup);
4239 srv = smbc_server(context, server, share, workgroup, user, password);
4241 if (!srv) {
4243 return -1; /* errno set by smbc_server */
4247 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
4249 if (err < 0)
4250 errno = smbc_errno(context, &srv->cli);
4251 else if (err == ERRnosuchprintjob)
4252 errno = EINVAL;
4253 return -1;
4257 return 0;
4262 * Get a new empty handle to fill in with your own info
4264 SMBCCTX * smbc_new_context(void)
4266 SMBCCTX * context;
4268 context = malloc(sizeof(SMBCCTX));
4269 if (!context) {
4270 errno = ENOMEM;
4271 return NULL;
4274 ZERO_STRUCTP(context);
4276 context->internal = malloc(sizeof(struct smbc_internal_data));
4277 if (!context->internal) {
4278 errno = ENOMEM;
4279 return NULL;
4282 ZERO_STRUCTP(context->internal);
4285 /* ADD REASONABLE DEFAULTS */
4286 context->debug = 0;
4287 context->timeout = 20000; /* 20 seconds */
4289 context->open = smbc_open_ctx;
4290 context->creat = smbc_creat_ctx;
4291 context->read = smbc_read_ctx;
4292 context->write = smbc_write_ctx;
4293 context->close = smbc_close_ctx;
4294 context->unlink = smbc_unlink_ctx;
4295 context->rename = smbc_rename_ctx;
4296 context->lseek = smbc_lseek_ctx;
4297 context->stat = smbc_stat_ctx;
4298 context->fstat = smbc_fstat_ctx;
4299 context->opendir = smbc_opendir_ctx;
4300 context->closedir = smbc_closedir_ctx;
4301 context->readdir = smbc_readdir_ctx;
4302 context->getdents = smbc_getdents_ctx;
4303 context->mkdir = smbc_mkdir_ctx;
4304 context->rmdir = smbc_rmdir_ctx;
4305 context->telldir = smbc_telldir_ctx;
4306 context->lseekdir = smbc_lseekdir_ctx;
4307 context->fstatdir = smbc_fstatdir_ctx;
4308 context->chmod = smbc_chmod_ctx;
4309 context->utimes = smbc_utimes_ctx;
4310 context->setxattr = smbc_setxattr_ctx;
4311 context->getxattr = smbc_getxattr_ctx;
4312 context->removexattr = smbc_removexattr_ctx;
4313 context->listxattr = smbc_listxattr_ctx;
4314 context->open_print_job = smbc_open_print_job_ctx;
4315 context->print_file = smbc_print_file_ctx;
4316 context->list_print_jobs = smbc_list_print_jobs_ctx;
4317 context->unlink_print_job = smbc_unlink_print_job_ctx;
4319 context->callbacks.check_server_fn = smbc_check_server;
4320 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
4322 smbc_default_cache_functions(context);
4324 return context;
4328 * Free a context
4330 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
4331 * and thus you'll be leaking memory if not handled properly.
4334 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
4336 if (!context) {
4337 errno = EBADF;
4338 return 1;
4341 if (shutdown_ctx) {
4342 SMBCFILE * f;
4343 DEBUG(1,("Performing aggressive shutdown.\n"));
4345 f = context->internal->_files;
4346 while (f) {
4347 context->close(context, f);
4348 f = f->next;
4350 context->internal->_files = NULL;
4352 /* First try to remove the servers the nice way. */
4353 if (context->callbacks.purge_cached_fn(context)) {
4354 SMBCSRV * s;
4355 SMBCSRV * next;
4356 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
4357 s = context->internal->_servers;
4358 while (s) {
4359 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
4360 cli_shutdown(&s->cli);
4361 context->callbacks.remove_cached_srv_fn(context, s);
4362 next = s->next;
4363 DLIST_REMOVE(context->internal->_servers, s);
4364 SAFE_FREE(s);
4365 s = next;
4367 context->internal->_servers = NULL;
4370 else {
4371 /* This is the polite way */
4372 if (context->callbacks.purge_cached_fn(context)) {
4373 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
4374 errno = EBUSY;
4375 return 1;
4377 if (context->internal->_servers) {
4378 DEBUG(1, ("Active servers in context, free_context failed.\n"));
4379 errno = EBUSY;
4380 return 1;
4382 if (context->internal->_files) {
4383 DEBUG(1, ("Active files in context, free_context failed.\n"));
4384 errno = EBUSY;
4385 return 1;
4389 /* Things we have to clean up */
4390 SAFE_FREE(context->workgroup);
4391 SAFE_FREE(context->netbios_name);
4392 SAFE_FREE(context->user);
4394 DEBUG(3, ("Context %p succesfully freed\n", context));
4395 SAFE_FREE(context->internal);
4396 SAFE_FREE(context);
4397 return 0;
4402 * Initialise the library etc
4404 * We accept a struct containing handle information.
4405 * valid values for info->debug from 0 to 100,
4406 * and insist that info->fn must be non-null.
4408 SMBCCTX * smbc_init_context(SMBCCTX * context)
4410 pstring conf;
4411 int pid;
4412 char *user = NULL, *home = NULL;
4414 if (!context || !context->internal) {
4415 errno = EBADF;
4416 return NULL;
4419 /* Do not initialise the same client twice */
4420 if (context->internal->_initialized) {
4421 return 0;
4424 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
4426 errno = EINVAL;
4427 return NULL;
4431 if (!smbc_initialized) {
4432 /* Do some library wide intialisations the first time we get called */
4434 /* Set this to what the user wants */
4435 DEBUGLEVEL = context->debug;
4437 setup_logging( "libsmbclient", True);
4439 /* Here we would open the smb.conf file if needed ... */
4441 home = getenv("HOME");
4443 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
4445 load_interfaces(); /* Load the list of interfaces ... */
4447 in_client = True; /* FIXME, make a param */
4449 if (!lp_load(conf, True, False, False)) {
4452 * Well, if that failed, try the dyn_CONFIGFILE
4453 * Which points to the standard locn, and if that
4454 * fails, silently ignore it and use the internal
4455 * defaults ...
4458 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
4459 DEBUG(5, ("Could not load either config file: %s or %s\n",
4460 conf, dyn_CONFIGFILE));
4464 reopen_logs(); /* Get logging working ... */
4467 * Block SIGPIPE (from lib/util_sock.c: write())
4468 * It is not needed and should not stop execution
4470 BlockSignals(True, SIGPIPE);
4472 /* Done with one-time initialisation */
4473 smbc_initialized = 1;
4477 if (!context->user) {
4479 * FIXME: Is this the best way to get the user info?
4481 user = getenv("USER");
4482 /* walk around as "guest" if no username can be found */
4483 if (!user) context->user = strdup("guest");
4484 else context->user = strdup(user);
4487 if (!context->netbios_name) {
4489 * We try to get our netbios name from the config. If that fails we fall
4490 * back on constructing our netbios name from our hostname etc
4492 if (global_myname()) {
4493 context->netbios_name = strdup(global_myname());
4495 else {
4497 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
4499 pid = sys_getpid();
4500 context->netbios_name = malloc(17);
4501 if (!context->netbios_name) {
4502 errno = ENOMEM;
4503 return NULL;
4505 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
4509 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
4511 if (!context->workgroup) {
4512 if (lp_workgroup()) {
4513 context->workgroup = strdup(lp_workgroup());
4515 else {
4516 /* TODO: Think about a decent default workgroup */
4517 context->workgroup = strdup("samba");
4521 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
4523 /* shortest timeout is 1 second */
4524 if (context->timeout > 0 && context->timeout < 1000)
4525 context->timeout = 1000;
4528 * FIXME: Should we check the function pointers here?
4531 context->internal->_initialized = 1;
4533 return context;