r7168: Updating file times from libsmbclient was not working for win98. Although
[Samba/gebeck_regimport.git] / source3 / libsmb / libsmbclient.c
blob296dbc7f5bb7c5180766b6f33538b15078ff42a5
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, 2004
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"
31 * DOS Attribute values (used internally)
33 typedef struct DOS_ATTR_DESC
35 int mode;
36 unsigned long long size;
37 time_t a_time;
38 time_t c_time;
39 time_t m_time;
40 unsigned long long inode;
41 } DOS_ATTR_DESC;
45 * Internal flags for extended attributes
48 /* internal mode values */
49 #define SMBC_XATTR_MODE_ADD 1
50 #define SMBC_XATTR_MODE_REMOVE 2
51 #define SMBC_XATTR_MODE_REMOVE_ALL 3
52 #define SMBC_XATTR_MODE_SET 4
53 #define SMBC_XATTR_MODE_CHOWN 5
54 #define SMBC_XATTR_MODE_CHGRP 6
56 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
58 /*We should test for this in configure ... */
59 #ifndef ENOTSUP
60 #define ENOTSUP EOPNOTSUPP
61 #endif
64 * Functions exported by libsmb_cache.c that we need here
66 int smbc_default_cache_functions(SMBCCTX *context);
68 /*
69 * check if an element is part of the list.
70 * FIXME: Does not belong here !
71 * Can anyone put this in a macro in dlinklist.h ?
72 * -- Tom
74 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
75 if (!p || !list) return False;
76 do {
77 if (p == list) return True;
78 list = list->next;
79 } while (list);
80 return False;
83 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file);
84 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence);
86 extern BOOL in_client;
89 * Is the logging working / configfile read ?
91 static int smbc_initialized = 0;
93 static int
94 hex2int( unsigned int _char )
96 if ( _char >= 'A' && _char <='F')
97 return _char - 'A' + 10;
98 if ( _char >= 'a' && _char <='f')
99 return _char - 'a' + 10;
100 if ( _char >= '0' && _char <='9')
101 return _char - '0';
102 return -1;
106 * smbc_urldecode()
108 * Convert strings of %xx to their single character equivalent. Each 'x' must
109 * be a valid hexadecimal digit, or that % sequence is left undecoded.
111 * dest may, but need not be, the same pointer as src.
113 * Returns the number of % sequences which could not be converted due to lack
114 * of two following hexadecimal digits.
117 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
119 int old_length = strlen(src);
120 int i = 0;
121 int err_count = 0;
122 pstring temp;
123 char * p;
125 if ( old_length == 0 ) {
126 return 0;
129 p = temp;
130 while ( i < old_length ) {
131 unsigned char character = src[ i++ ];
133 if (character == '%') {
134 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
135 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
137 /* Replace valid sequence */
138 if (a != -1 && b != -1) {
140 /* Replace valid %xx sequence with %dd */
141 character = (a * 16) + b;
143 if (character == '\0') {
144 break; /* Stop at %00 */
147 i += 2;
148 } else {
150 err_count++;
154 *p++ = character;
157 *p = '\0';
159 strncpy(dest, temp, max_dest_len);
161 return err_count;
165 * smbc_urlencode()
167 * Convert any characters not specifically allowed in a URL into their %xx
168 * equivalent.
170 * Returns the remaining buffer length.
173 smbc_urlencode(char * dest, char * src, int max_dest_len)
175 char hex[] = "0123456789ABCDEF";
177 for (; *src != '\0' && max_dest_len >= 3; src++) {
179 if ((*src < '0' &&
180 *src != '-' &&
181 *src != '.') ||
182 (*src > '9' &&
183 *src < 'A') ||
184 (*src > 'Z' &&
185 *src < 'a' &&
186 *src != '_') ||
187 (*src > 'z')) {
188 *dest++ = '%';
189 *dest++ = hex[(*src >> 4) & 0x0f];
190 *dest++ = hex[*src & 0x0f];
191 max_dest_len -= 3;
192 } else {
193 *dest++ = *src;
194 max_dest_len--;
198 *dest++ = '\0';
199 max_dest_len--;
201 return max_dest_len;
205 * Function to parse a path and turn it into components
207 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
208 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
209 * general format ("smb:" only; we do not look for "cifs:").
212 * We accept:
213 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
215 * Meaning of URLs:
217 * smb:// Show all workgroups.
219 * The method of locating the list of workgroups varies
220 * depending upon the setting of the context variable
221 * context->options.browse_max_lmb_count. This value
222 * determine the maximum number of local master browsers to
223 * query for the list of workgroups. In order to ensure that
224 * a complete list of workgroups is obtained, all master
225 * browsers must be queried, but if there are many
226 * workgroups, the time spent querying can begin to add up.
227 * For small networks (not many workgroups), it is suggested
228 * that this variable be set to 0, indicating query all local
229 * master browsers. When the network has many workgroups, a
230 * reasonable setting for this variable might be around 3.
232 * smb://name/ if name<1D> or name<1B> exists, list servers in
233 * workgroup, else, if name<20> exists, list all shares
234 * for server ...
236 * If "options" are provided, this function returns the entire option list as a
237 * string, for later parsing by the caller. Note that currently, no options
238 * are supported.
241 static const char *smbc_prefix = "smb:";
243 static int
244 smbc_parse_path(SMBCCTX *context,
245 const char *fname,
246 char *server, int server_len,
247 char *share, int share_len,
248 char *path, int path_len,
249 char *user, int user_len,
250 char *password, int password_len,
251 char *options, int options_len)
253 static pstring s;
254 pstring userinfo;
255 const char *p;
256 char *q, *r;
257 int len;
259 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
260 if (options != NULL && options_len > 0) {
261 options[0] = (char)0;
263 pstrcpy(s, fname);
265 /* see if it has the right prefix */
266 len = strlen(smbc_prefix);
267 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
268 return -1; /* What about no smb: ? */
271 p = s + len;
273 /* Watch the test below, we are testing to see if we should exit */
275 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
277 DEBUG(1, ("Invalid path (does not begin with smb://"));
278 return -1;
282 p += 2; /* Skip the double slash */
284 /* See if any options were specified */
285 if ((q = strrchr(p, '?')) != NULL ) {
286 /* There are options. Null terminate here and point to them */
287 *q++ = '\0';
289 DEBUG(4, ("Found options '%s'", q));
291 /* Copy the options */
292 if (options != NULL && options_len > 0) {
293 safe_strcpy(options, q, options_len - 1);
297 if (*p == (char)0)
298 goto decoding;
300 if (*p == '/') {
302 strncpy(server, context->workgroup,
303 (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
304 return 0;
309 * ok, its for us. Now parse out the server, share etc.
311 * However, we want to parse out [[domain;]user[:password]@] if it
312 * exists ...
315 /* check that '@' occurs before '/', if '/' exists at all */
316 q = strchr_m(p, '@');
317 r = strchr_m(p, '/');
318 if (q && (!r || q < r)) {
319 pstring username, passwd, domain;
320 const char *u = userinfo;
322 next_token(&p, userinfo, "@", sizeof(fstring));
324 username[0] = passwd[0] = domain[0] = 0;
326 if (strchr_m(u, ';')) {
328 next_token(&u, domain, ";", sizeof(fstring));
332 if (strchr_m(u, ':')) {
334 next_token(&u, username, ":", sizeof(fstring));
336 pstrcpy(passwd, u);
339 else {
341 pstrcpy(username, u);
345 if (username[0])
346 strncpy(user, username, user_len); /* FIXME, domain */
348 if (passwd[0])
349 strncpy(password, passwd, password_len);
353 if (!next_token(&p, server, "/", sizeof(fstring))) {
355 return -1;
359 if (*p == (char)0) goto decoding; /* That's it ... */
361 if (!next_token(&p, share, "/", sizeof(fstring))) {
363 return -1;
367 safe_strcpy(path, p, path_len - 1);
369 all_string_sub(path, "/", "\\", 0);
371 decoding:
372 (void) smbc_urldecode(path, path, path_len);
373 (void) smbc_urldecode(server, server, server_len);
374 (void) smbc_urldecode(share, share, share_len);
375 (void) smbc_urldecode(user, user, user_len);
376 (void) smbc_urldecode(password, password, password_len);
378 return 0;
382 * Verify that the options specified in a URL are valid
384 static int smbc_check_options(char *server, char *share, char *path, char *options)
386 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' path='%s' options='%s'\n", server, share, path, options));
388 /* No options at all is always ok */
389 if (! *options) return 0;
391 /* Currently, we don't support any options. */
392 return -1;
396 * Convert an SMB error into a UNIX error ...
398 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
400 int ret = cli_errno(c);
402 if (cli_is_dos_error(c)) {
403 uint8 eclass;
404 uint32 ecode;
406 cli_dos_error(c, &eclass, &ecode);
408 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
409 (int)eclass, (int)ecode, (int)ecode, ret));
410 } else {
411 NTSTATUS status;
413 status = cli_nt_error(c);
415 DEBUG(3,("smbc errno %s -> %d\n",
416 nt_errstr(status), ret));
419 return ret;
423 * Check a server_fd.
424 * returns 0 if the server is in shape. Returns 1 on error
426 * Also useable outside libsmbclient to enable external cache
427 * to do some checks too.
429 int smbc_check_server(SMBCCTX * context, SMBCSRV * server)
431 if ( send_keepalive(server->cli.fd) == False )
432 return 1;
434 /* connection is ok */
435 return 0;
439 * Remove a server from the cached server list it's unused.
440 * On success, 0 is returned. 1 is returned if the server could not be removed.
442 * Also useable outside libsmbclient
444 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
446 SMBCFILE * file;
448 /* are we being fooled ? */
449 if (!context || !context->internal ||
450 !context->internal->_initialized || !srv) return 1;
453 /* Check all open files/directories for a relation with this server */
454 for (file = context->internal->_files; file; file=file->next) {
455 if (file->srv == srv) {
456 /* Still used */
457 DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n",
458 srv, file));
459 return 1;
463 DLIST_REMOVE(context->internal->_servers, srv);
465 cli_shutdown(&srv->cli);
467 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
469 context->callbacks.remove_cached_srv_fn(context, srv);
471 return 0;
474 SMBCSRV *find_server(SMBCCTX *context,
475 const char *server,
476 const char *share,
477 fstring workgroup,
478 fstring username,
479 fstring password)
481 SMBCSRV *srv;
482 int auth_called = 0;
484 check_server_cache:
486 srv = context->callbacks.get_cached_srv_fn(context, server, share,
487 workgroup, username);
489 if (!auth_called && !srv && (!username[0] || !password[0])) {
490 context->callbacks.auth_fn(server, share,
491 workgroup, sizeof(fstring),
492 username, sizeof(fstring),
493 password, sizeof(fstring));
495 * However, smbc_auth_fn may have picked up info relating to
496 * an existing connection, so try for an existing connection
497 * again ...
499 auth_called = 1;
500 goto check_server_cache;
504 if (srv) {
505 if (context->callbacks.check_server_fn(context, srv)) {
507 * This server is no good anymore
508 * Try to remove it and check for more possible
509 * servers in the cache
511 if (context->callbacks.remove_unused_server_fn(context,
512 srv)) {
514 * We could not remove the server completely,
515 * remove it from the cache so we will not get
516 * it again. It will be removed when the last
517 * file/dir is closed.
519 context->callbacks.remove_cached_srv_fn(context,
520 srv);
524 * Maybe there are more cached connections to this
525 * server
527 goto check_server_cache;
530 return srv;
533 return NULL;
537 * Connect to a server, possibly on an existing connection
539 * Here, what we want to do is: If the server and username
540 * match an existing connection, reuse that, otherwise, establish a
541 * new connection.
543 * If we have to create a new connection, call the auth_fn to get the
544 * info we need, unless the username and password were passed in.
547 SMBCSRV *smbc_server(SMBCCTX *context,
548 const char *server, const char *share,
549 fstring workgroup, fstring username,
550 fstring password)
552 SMBCSRV *srv=NULL;
553 struct cli_state c;
554 struct nmb_name called, calling;
555 const char *server_n = server;
556 pstring ipenv;
557 struct in_addr ip;
558 int tried_reverse = 0;
559 int port_try_first;
560 int port_try_next;
561 const char *username_used;
563 zero_ip(&ip);
564 ZERO_STRUCT(c);
566 if (server[0] == 0) {
567 errno = EPERM;
568 return NULL;
571 srv = find_server(context, server, share,
572 workgroup, username, password);
575 * If we found a connection and we're only allowed one share per
576 * server...
578 if (srv && *share != '\0' && context->options.one_share_per_server) {
581 * ... then if there's no current connection to the share,
582 * connect to it. find_server(), or rather the function
583 * pointed to by context->callbacks.get_cached_srv_fn which
584 * was called by find_server(), will have issued a tree
585 * disconnect if the requested share is not the same as the
586 * one that was already connected.
588 if (srv->cli.cnum == (uint16) -1) {
589 /* Ensure we have accurate auth info */
590 context->callbacks.auth_fn(server, share,
591 workgroup, sizeof(fstring),
592 username, sizeof(fstring),
593 password, sizeof(fstring));
595 if (! cli_send_tconX(&srv->cli, share, "?????",
596 password, strlen(password)+1)) {
598 errno = smbc_errno(context, &srv->cli);
599 cli_shutdown(&srv->cli);
600 context->callbacks.remove_cached_srv_fn(context, srv);
601 srv = NULL;
604 /* Regenerate the dev value since it's based on both server and share */
605 if (srv) {
606 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
611 /* If we have a connection... */
612 if (srv) {
614 /* ... then we're done here. Give 'em what they came for. */
615 return srv;
618 make_nmb_name(&calling, context->netbios_name, 0x0);
619 make_nmb_name(&called , server, 0x20);
621 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
623 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
625 again:
626 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
628 zero_ip(&ip);
630 /* have to open a new connection */
631 if (!cli_initialise(&c)) {
632 errno = ENOMEM;
633 return NULL;
636 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
637 c.use_kerberos = True;
639 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
640 c.fallback_after_kerberos = True;
643 c.timeout = context->timeout;
646 * Force use of port 139 for first try if share is $IPC, empty, or
647 * null, so browse lists can work
649 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
650 port_try_first = 139;
651 port_try_next = 445;
652 } else {
653 port_try_first = 445;
654 port_try_next = 139;
657 c.port = port_try_first;
659 if (!cli_connect(&c, server_n, &ip)) {
661 /* First connection attempt failed. Try alternate port. */
662 c.port = port_try_next;
664 if (!cli_connect(&c, server_n, &ip)) {
665 cli_shutdown(&c);
666 errno = ETIMEDOUT;
667 return NULL;
671 if (!cli_session_request(&c, &calling, &called)) {
672 cli_shutdown(&c);
673 if (strcmp(called.name, "*SMBSERVER")) {
674 make_nmb_name(&called , "*SMBSERVER", 0x20);
675 goto again;
677 else { /* Try one more time, but ensure we don't loop */
679 /* Only try this if server is an IP address ... */
681 if (is_ipaddress(server) && !tried_reverse) {
682 fstring remote_name;
683 struct in_addr rem_ip;
685 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
686 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
687 errno = ETIMEDOUT;
688 return NULL;
691 tried_reverse++; /* Yuck */
693 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
694 make_nmb_name(&called, remote_name, 0x20);
695 goto again;
701 errno = ETIMEDOUT;
702 return NULL;
705 DEBUG(4,(" session request ok\n"));
707 if (!cli_negprot(&c)) {
708 cli_shutdown(&c);
709 errno = ETIMEDOUT;
710 return NULL;
713 username_used = username;
715 if (!cli_session_setup(&c, username_used,
716 password, strlen(password),
717 password, strlen(password),
718 workgroup)) {
720 /* Failed. Try an anonymous login, if allowed by flags. */
721 username_used = "";
723 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
724 !cli_session_setup(&c, username_used,
725 password, 1,
726 password, 0,
727 workgroup)) {
729 cli_shutdown(&c);
730 errno = EPERM;
731 return NULL;
735 DEBUG(4,(" session setup ok\n"));
737 if (!cli_send_tconX(&c, share, "?????",
738 password, strlen(password)+1)) {
739 errno = smbc_errno(context, &c);
740 cli_shutdown(&c);
741 return NULL;
744 DEBUG(4,(" tconx ok\n"));
747 * Ok, we have got a nice connection
748 * Let's find a free server_fd
751 srv = SMB_MALLOC_P(SMBCSRV);
752 if (!srv) {
753 errno = ENOMEM;
754 goto failed;
757 ZERO_STRUCTP(srv);
758 srv->cli = c;
759 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
761 /* now add it to the cache (internal or external) */
762 /* Let the cache function set errno if it wants to */
763 errno = 0;
764 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username_used)) {
765 int saved_errno = errno;
766 DEBUG(3, (" Failed to add server to cache\n"));
767 errno = saved_errno;
768 if (errno == 0) {
769 errno = ENOMEM;
771 goto failed;
774 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
775 server, share, srv));
777 DLIST_ADD(context->internal->_servers, srv);
778 return srv;
780 failed:
781 cli_shutdown(&c);
782 if (!srv) return NULL;
784 SAFE_FREE(srv);
785 return NULL;
789 * Connect to a server for getting/setting attributes, possibly on an existing
790 * connection. This works similarly to smbc_server().
792 SMBCSRV *smbc_attr_server(SMBCCTX *context,
793 const char *server, const char *share,
794 fstring workgroup,
795 fstring username, fstring password,
796 POLICY_HND *pol)
798 struct in_addr ip;
799 struct cli_state *ipc_cli;
800 NTSTATUS nt_status;
801 SMBCSRV *ipc_srv=NULL;
804 * See if we've already created this special connection. Reference our
805 * "special" share name '*IPC$', which is an impossible real share name
806 * due to the leading asterisk.
808 ipc_srv = find_server(context, server, "*IPC$",
809 workgroup, username, password);
810 if (!ipc_srv) {
812 /* We didn't find a cached connection. Get the password */
813 if (*password == '\0') {
814 /* ... then retrieve it now. */
815 context->callbacks.auth_fn(server, share,
816 workgroup, sizeof(fstring),
817 username, sizeof(fstring),
818 password, sizeof(fstring));
821 zero_ip(&ip);
822 nt_status = cli_full_connection(&ipc_cli,
823 global_myname(), server,
824 &ip, 0, "IPC$", "?????",
825 username, workgroup,
826 password, 0,
827 Undefined, NULL);
828 if (! NT_STATUS_IS_OK(nt_status)) {
829 DEBUG(1,("cli_full_connection failed! (%s)\n",
830 nt_errstr(nt_status)));
831 errno = ENOTSUP;
832 return NULL;
835 if (!cli_nt_session_open(ipc_cli, PI_LSARPC)) {
836 DEBUG(1, ("cli_nt_session_open fail!\n"));
837 errno = ENOTSUP;
838 cli_shutdown(ipc_cli);
839 return NULL;
842 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
843 but NT sends 0x2000000 so we might as well do it too. */
845 nt_status = cli_lsa_open_policy(ipc_cli,
846 ipc_cli->mem_ctx,
847 True,
848 GENERIC_EXECUTE_ACCESS,
849 pol);
851 if (!NT_STATUS_IS_OK(nt_status)) {
852 errno = smbc_errno(context, ipc_cli);
853 cli_shutdown(ipc_cli);
854 return NULL;
857 ipc_srv = SMB_MALLOC_P(SMBCSRV);
858 if (!ipc_srv) {
859 errno = ENOMEM;
860 cli_shutdown(ipc_cli);
861 return NULL;
864 ZERO_STRUCTP(ipc_srv);
865 ipc_srv->cli = *ipc_cli;
867 free(ipc_cli);
869 /* now add it to the cache (internal or external) */
871 errno = 0; /* let cache function set errno if it likes */
872 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
873 server,
874 "*IPC$",
875 workgroup,
876 username)) {
877 DEBUG(3, (" Failed to add server to cache\n"));
878 if (errno == 0) {
879 errno = ENOMEM;
881 cli_shutdown(&ipc_srv->cli);
882 free(ipc_srv);
883 return NULL;
886 DLIST_ADD(context->internal->_servers, ipc_srv);
889 return ipc_srv;
893 * Routine to open() a file ...
896 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
898 fstring server, share, user, password, workgroup;
899 pstring path;
900 SMBCSRV *srv = NULL;
901 SMBCFILE *file = NULL;
902 int fd;
904 if (!context || !context->internal ||
905 !context->internal->_initialized) {
907 errno = EINVAL; /* Best I can think of ... */
908 return NULL;
912 if (!fname) {
914 errno = EINVAL;
915 return NULL;
919 if (smbc_parse_path(context, fname,
920 server, sizeof(server),
921 share, sizeof(share),
922 path, sizeof(path),
923 user, sizeof(user),
924 password, sizeof(password),
925 NULL, 0)) {
926 errno = EINVAL;
927 return NULL;
930 if (user[0] == (char)0) fstrcpy(user, context->user);
932 fstrcpy(workgroup, context->workgroup);
934 srv = smbc_server(context, server, share, workgroup, user, password);
936 if (!srv) {
938 if (errno == EPERM) errno = EACCES;
939 return NULL; /* smbc_server sets errno */
943 /* Hmmm, the test for a directory is suspect here ... FIXME */
945 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
947 fd = -1;
950 else {
952 file = SMB_MALLOC_P(SMBCFILE);
954 if (!file) {
956 errno = ENOMEM;
957 return NULL;
961 ZERO_STRUCTP(file);
963 if ((fd = cli_open(&srv->cli, path, flags, DENY_NONE)) < 0) {
965 /* Handle the error ... */
967 SAFE_FREE(file);
968 errno = smbc_errno(context, &srv->cli);
969 return NULL;
973 /* Fill in file struct */
975 file->cli_fd = fd;
976 file->fname = SMB_STRDUP(fname);
977 file->srv = srv;
978 file->offset = 0;
979 file->file = True;
981 DLIST_ADD(context->internal->_files, file);
984 * If the file was opened in O_APPEND mode, all write
985 * operations should be appended to the file. To do that,
986 * though, using this protocol, would require a getattrE()
987 * call for each and every write, to determine where the end
988 * of the file is. (There does not appear to be an append flag
989 * in the protocol.) Rather than add all of that overhead of
990 * retrieving the current end-of-file offset prior to each
991 * write operation, we'll assume that most append operations
992 * will continuously write, so we'll just set the offset to
993 * the end of the file now and hope that's adequate.
995 * Note to self: If this proves inadequate, and O_APPEND
996 * should, in some cases, be forced for each write, add a
997 * field in the context options structure, for
998 * "strict_append_mode" which would select between the current
999 * behavior (if FALSE) or issuing a getattrE() prior to each
1000 * write and forcing the write to the end of the file (if
1001 * TRUE). Adding that capability will likely require adding
1002 * an "append" flag into the _SMBCFILE structure to track
1003 * whether a file was opened in O_APPEND mode. -- djl
1005 if (flags & O_APPEND) {
1006 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1007 (void) smbc_close_ctx(context, file);
1008 errno = ENXIO;
1009 return NULL;
1013 return file;
1017 /* Check if opendir needed ... */
1019 if (fd == -1) {
1020 int eno = 0;
1022 eno = smbc_errno(context, &srv->cli);
1023 file = context->opendir(context, fname);
1024 if (!file) errno = eno;
1025 return file;
1029 errno = EINVAL; /* FIXME, correct errno ? */
1030 return NULL;
1035 * Routine to create a file
1038 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1040 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
1043 if (!context || !context->internal ||
1044 !context->internal->_initialized) {
1046 errno = EINVAL;
1047 return NULL;
1051 return smbc_open_ctx(context, path, creat_bits, mode);
1055 * Routine to read() a file ...
1058 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1060 int ret;
1063 * offset:
1065 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1066 * appears to pass file->offset (which is type off_t) differently than
1067 * a local variable of type off_t. Using local variable "offset" in
1068 * the call to cli_read() instead of file->offset fixes a problem
1069 * retrieving data at an offset greater than 4GB.
1071 off_t offset = file->offset;
1073 if (!context || !context->internal ||
1074 !context->internal->_initialized) {
1076 errno = EINVAL;
1077 return -1;
1081 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1083 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1085 errno = EBADF;
1086 return -1;
1090 /* Check that the buffer exists ... */
1092 if (buf == NULL) {
1094 errno = EINVAL;
1095 return -1;
1099 ret = cli_read(&file->srv->cli, file->cli_fd, buf, offset, count);
1101 if (ret < 0) {
1103 errno = smbc_errno(context, &file->srv->cli);
1104 return -1;
1108 file->offset += ret;
1110 DEBUG(4, (" --> %d\n", ret));
1112 return ret; /* Success, ret bytes of data ... */
1117 * Routine to write() a file ...
1120 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1122 int ret;
1123 off_t offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1125 if (!context || !context->internal ||
1126 !context->internal->_initialized) {
1128 errno = EINVAL;
1129 return -1;
1133 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1135 errno = EBADF;
1136 return -1;
1140 /* Check that the buffer exists ... */
1142 if (buf == NULL) {
1144 errno = EINVAL;
1145 return -1;
1149 ret = cli_write(&file->srv->cli, file->cli_fd, 0, buf, offset, count);
1151 if (ret <= 0) {
1153 errno = smbc_errno(context, &file->srv->cli);
1154 return -1;
1158 file->offset += ret;
1160 return ret; /* Success, 0 bytes of data ... */
1164 * Routine to close() a file ...
1167 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1169 SMBCSRV *srv;
1171 if (!context || !context->internal ||
1172 !context->internal->_initialized) {
1174 errno = EINVAL;
1175 return -1;
1179 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1181 errno = EBADF;
1182 return -1;
1186 /* IS a dir ... */
1187 if (!file->file) {
1189 return context->closedir(context, file);
1193 if (!cli_close(&file->srv->cli, file->cli_fd)) {
1195 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1196 file->fname));
1197 /* Deallocate slot and remove the server
1198 * from the server cache if unused */
1199 errno = smbc_errno(context, &file->srv->cli);
1200 srv = file->srv;
1201 DLIST_REMOVE(context->internal->_files, file);
1202 SAFE_FREE(file->fname);
1203 SAFE_FREE(file);
1204 context->callbacks.remove_unused_server_fn(context, srv);
1206 return -1;
1210 DLIST_REMOVE(context->internal->_files, file);
1211 SAFE_FREE(file->fname);
1212 SAFE_FREE(file);
1214 return 0;
1218 * Get info from an SMB server on a file. Use a qpathinfo call first
1219 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1221 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1222 uint16 *mode, SMB_OFF_T *size,
1223 time_t *c_time, time_t *a_time, time_t *m_time,
1224 SMB_INO_T *ino)
1227 if (!context || !context->internal ||
1228 !context->internal->_initialized) {
1230 errno = EINVAL;
1231 return -1;
1235 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1237 if (!srv->no_pathinfo2 &&
1238 cli_qpathinfo2(&srv->cli, path, c_time, a_time, m_time, NULL,
1239 size, mode, ino)) return True;
1241 /* if this is NT then don't bother with the getatr */
1242 if (srv->cli.capabilities & CAP_NT_SMBS) {
1243 errno = EPERM;
1244 return False;
1247 if (cli_getatr(&srv->cli, path, mode, size, m_time)) {
1248 if (m_time != NULL) {
1249 if (a_time != NULL) *a_time = *m_time;
1250 if (c_time != NULL) *c_time = *m_time;
1252 srv->no_pathinfo2 = True;
1253 return True;
1256 errno = EPERM;
1257 return False;
1262 * Routine to unlink() a file
1265 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1267 fstring server, share, user, password, workgroup;
1268 pstring path;
1269 SMBCSRV *srv = NULL;
1271 if (!context || !context->internal ||
1272 !context->internal->_initialized) {
1274 errno = EINVAL; /* Best I can think of ... */
1275 return -1;
1279 if (!fname) {
1281 errno = EINVAL;
1282 return -1;
1286 if (smbc_parse_path(context, fname,
1287 server, sizeof(server),
1288 share, sizeof(share),
1289 path, sizeof(path),
1290 user, sizeof(user),
1291 password, sizeof(password),
1292 NULL, 0)) {
1293 errno = EINVAL;
1294 return -1;
1297 if (user[0] == (char)0) fstrcpy(user, context->user);
1299 fstrcpy(workgroup, context->workgroup);
1301 srv = smbc_server(context, server, share, workgroup, user, password);
1303 if (!srv) {
1305 return -1; /* smbc_server sets errno */
1309 if (!cli_unlink(&srv->cli, path)) {
1311 errno = smbc_errno(context, &srv->cli);
1313 if (errno == EACCES) { /* Check if the file is a directory */
1315 int saverr = errno;
1316 SMB_OFF_T size = 0;
1317 uint16 mode = 0;
1318 time_t m_time = 0, a_time = 0, c_time = 0;
1319 SMB_INO_T ino = 0;
1321 if (!smbc_getatr(context, srv, path, &mode, &size,
1322 &c_time, &a_time, &m_time, &ino)) {
1324 /* Hmmm, bad error ... What? */
1326 errno = smbc_errno(context, &srv->cli);
1327 return -1;
1330 else {
1332 if (IS_DOS_DIR(mode))
1333 errno = EISDIR;
1334 else
1335 errno = saverr; /* Restore this */
1340 return -1;
1344 return 0; /* Success ... */
1349 * Routine to rename() a file
1352 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1353 SMBCCTX *ncontext, const char *nname)
1355 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1356 pstring path1, path2;
1357 SMBCSRV *srv = NULL;
1359 if (!ocontext || !ncontext ||
1360 !ocontext->internal || !ncontext->internal ||
1361 !ocontext->internal->_initialized ||
1362 !ncontext->internal->_initialized) {
1364 errno = EINVAL; /* Best I can think of ... */
1365 return -1;
1369 if (!oname || !nname) {
1371 errno = EINVAL;
1372 return -1;
1376 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1378 smbc_parse_path(ocontext, oname,
1379 server1, sizeof(server1),
1380 share1, sizeof(share1),
1381 path1, sizeof(path1),
1382 user1, sizeof(user1),
1383 password1, sizeof(password1),
1384 NULL, 0);
1386 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1388 smbc_parse_path(ncontext, nname,
1389 server2, sizeof(server2),
1390 share2, sizeof(share2),
1391 path2, sizeof(path2),
1392 user2, sizeof(user2),
1393 password2, sizeof(password2),
1394 NULL, 0);
1396 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1398 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1399 strcmp(user1, user2)) {
1401 /* Can't rename across file systems, or users?? */
1403 errno = EXDEV;
1404 return -1;
1408 fstrcpy(workgroup, ocontext->workgroup);
1409 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1410 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1411 if (!srv) {
1413 return -1;
1417 if (!cli_rename(&srv->cli, path1, path2)) {
1418 int eno = smbc_errno(ocontext, &srv->cli);
1420 if (eno != EEXIST ||
1421 !cli_unlink(&srv->cli, path2) ||
1422 !cli_rename(&srv->cli, path1, path2)) {
1424 errno = eno;
1425 return -1;
1430 return 0; /* Success */
1435 * A routine to lseek() a file
1438 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1440 SMB_OFF_T size;
1442 if (!context || !context->internal ||
1443 !context->internal->_initialized) {
1445 errno = EINVAL;
1446 return -1;
1450 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1452 errno = EBADF;
1453 return -1;
1457 if (!file->file) {
1459 errno = EINVAL;
1460 return -1; /* Can't lseek a dir ... */
1464 switch (whence) {
1465 case SEEK_SET:
1466 file->offset = offset;
1467 break;
1469 case SEEK_CUR:
1470 file->offset += offset;
1471 break;
1473 case SEEK_END:
1474 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
1475 NULL, NULL, NULL))
1477 SMB_BIG_UINT b_size = size;
1478 if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
1479 NULL))
1481 errno = EINVAL;
1482 return -1;
1483 } else
1484 size = b_size;
1486 file->offset = size + offset;
1487 break;
1489 default:
1490 errno = EINVAL;
1491 break;
1495 return file->offset;
1500 * Generate an inode number from file name for those things that need it
1503 static
1504 ino_t smbc_inode(SMBCCTX *context, const char *name)
1507 if (!context || !context->internal ||
1508 !context->internal->_initialized) {
1510 errno = EINVAL;
1511 return -1;
1515 if (!*name) return 2; /* FIXME, why 2 ??? */
1516 return (ino_t)str_checksum(name);
1521 * Routine to put basic stat info into a stat structure ... Used by stat and
1522 * fstat below.
1525 static
1526 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname,
1527 SMB_OFF_T size, int mode)
1530 st->st_mode = 0;
1532 if (IS_DOS_DIR(mode)) {
1533 st->st_mode = SMBC_DIR_MODE;
1534 } else {
1535 st->st_mode = SMBC_FILE_MODE;
1538 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1539 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1540 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1541 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1543 st->st_size = size;
1544 #ifdef HAVE_STAT_ST_BLKSIZE
1545 st->st_blksize = 512;
1546 #endif
1547 #ifdef HAVE_STAT_ST_BLOCKS
1548 st->st_blocks = (size+511)/512;
1549 #endif
1550 st->st_uid = getuid();
1551 st->st_gid = getgid();
1553 if (IS_DOS_DIR(mode)) {
1554 st->st_nlink = 2;
1555 } else {
1556 st->st_nlink = 1;
1559 if (st->st_ino == 0) {
1560 st->st_ino = smbc_inode(context, fname);
1563 return True; /* FIXME: Is this needed ? */
1568 * Routine to stat a file given a name
1571 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1573 SMBCSRV *srv;
1574 fstring server, share, user, password, workgroup;
1575 pstring path;
1576 time_t m_time = 0, a_time = 0, c_time = 0;
1577 SMB_OFF_T size = 0;
1578 uint16 mode = 0;
1579 SMB_INO_T ino = 0;
1581 if (!context || !context->internal ||
1582 !context->internal->_initialized) {
1584 errno = EINVAL; /* Best I can think of ... */
1585 return -1;
1589 if (!fname) {
1591 errno = EINVAL;
1592 return -1;
1596 DEBUG(4, ("smbc_stat(%s)\n", fname));
1598 if (smbc_parse_path(context, fname,
1599 server, sizeof(server),
1600 share, sizeof(share),
1601 path, sizeof(path),
1602 user, sizeof(user),
1603 password, sizeof(password),
1604 NULL, 0)) {
1605 errno = EINVAL;
1606 return -1;
1609 if (user[0] == (char)0) fstrcpy(user, context->user);
1611 fstrcpy(workgroup, context->workgroup);
1613 srv = smbc_server(context, server, share, workgroup, user, password);
1615 if (!srv) {
1616 return -1; /* errno set by smbc_server */
1619 if (!smbc_getatr(context, srv, path, &mode, &size,
1620 &c_time, &a_time, &m_time, &ino)) {
1622 errno = smbc_errno(context, &srv->cli);
1623 return -1;
1627 st->st_ino = ino;
1629 smbc_setup_stat(context, st, path, size, mode);
1631 st->st_atime = a_time;
1632 st->st_ctime = c_time;
1633 st->st_mtime = m_time;
1634 st->st_dev = srv->dev;
1636 return 0;
1641 * Routine to stat a file given an fd
1644 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1646 time_t c_time, a_time, m_time;
1647 SMB_OFF_T size;
1648 uint16 mode;
1649 SMB_INO_T ino = 0;
1651 if (!context || !context->internal ||
1652 !context->internal->_initialized) {
1654 errno = EINVAL;
1655 return -1;
1659 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1661 errno = EBADF;
1662 return -1;
1666 if (!file->file) {
1668 return context->fstatdir(context, file, st);
1672 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
1673 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
1674 if (!cli_getattrE(&file->srv->cli, file->cli_fd,
1675 &mode, &size, &c_time, &a_time, &m_time)) {
1677 errno = EINVAL;
1678 return -1;
1682 st->st_ino = ino;
1684 smbc_setup_stat(context, st, file->fname, size, mode);
1686 st->st_atime = a_time;
1687 st->st_ctime = c_time;
1688 st->st_mtime = m_time;
1689 st->st_dev = file->srv->dev;
1691 return 0;
1696 * Routine to open a directory
1697 * We accept the URL syntax explained in smbc_parse_path(), above.
1700 static void smbc_remove_dir(SMBCFILE *dir)
1702 struct smbc_dir_list *d,*f;
1704 d = dir->dir_list;
1705 while (d) {
1707 f = d; d = d->next;
1709 SAFE_FREE(f->dirent);
1710 SAFE_FREE(f);
1714 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
1718 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
1720 struct smbc_dirent *dirent;
1721 int size;
1722 int name_length = (name == NULL ? 0 : strlen(name));
1723 int comment_len = (comment == NULL ? 0 : strlen(comment));
1726 * Allocate space for the dirent, which must be increased by the
1727 * size of the name and the comment and 1 each for the null terminator.
1730 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
1732 dirent = SMB_MALLOC(size);
1734 if (!dirent) {
1736 dir->dir_error = ENOMEM;
1737 return -1;
1741 ZERO_STRUCTP(dirent);
1743 if (dir->dir_list == NULL) {
1745 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
1746 if (!dir->dir_list) {
1748 SAFE_FREE(dirent);
1749 dir->dir_error = ENOMEM;
1750 return -1;
1753 ZERO_STRUCTP(dir->dir_list);
1755 dir->dir_end = dir->dir_next = dir->dir_list;
1757 else {
1759 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
1761 if (!dir->dir_end->next) {
1763 SAFE_FREE(dirent);
1764 dir->dir_error = ENOMEM;
1765 return -1;
1768 ZERO_STRUCTP(dir->dir_end->next);
1770 dir->dir_end = dir->dir_end->next;
1773 dir->dir_end->next = NULL;
1774 dir->dir_end->dirent = dirent;
1776 dirent->smbc_type = type;
1777 dirent->namelen = name_length;
1778 dirent->commentlen = comment_len;
1779 dirent->dirlen = size;
1781 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
1783 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
1784 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
1786 return 0;
1790 static void
1791 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
1793 SMBCFILE *dir = (SMBCFILE *)state;
1794 struct smbc_dir_list *dir_list;
1795 struct smbc_dirent *dirent;
1796 int dirent_type;
1797 int do_remove = 0;
1799 dirent_type = dir->dir_type;
1801 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1803 /* An error occurred, what do we do? */
1804 /* FIXME: Add some code here */
1807 /* Point to the one just added */
1808 dirent = dir->dir_end->dirent;
1810 /* See if this was a duplicate */
1811 for (dir_list = dir->dir_list;
1812 dir_list != dir->dir_end;
1813 dir_list = dir_list->next) {
1814 if (! do_remove &&
1815 strcmp(dir_list->dirent->name, dirent->name) == 0) {
1816 /* Duplicate. End end of list need to be removed. */
1817 do_remove = 1;
1820 if (do_remove && dir_list->next == dir->dir_end) {
1821 /* Found the end of the list. Remove it. */
1822 dir->dir_end = dir_list;
1823 free(dir_list->next);
1824 dir_list->next = NULL;
1825 break;
1830 static void
1831 list_fn(const char *name, uint32 type, const char *comment, void *state)
1833 SMBCFILE *dir = (SMBCFILE *)state;
1834 int dirent_type;
1836 /* We need to process the type a little ... */
1838 if (dir->dir_type == SMBC_FILE_SHARE) {
1840 switch (type) {
1841 case 0: /* Directory tree */
1842 dirent_type = SMBC_FILE_SHARE;
1843 break;
1845 case 1:
1846 dirent_type = SMBC_PRINTER_SHARE;
1847 break;
1849 case 2:
1850 dirent_type = SMBC_COMMS_SHARE;
1851 break;
1853 case 3:
1854 dirent_type = SMBC_IPC_SHARE;
1855 break;
1857 default:
1858 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
1859 break;
1862 else dirent_type = dir->dir_type;
1864 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1866 /* An error occurred, what do we do? */
1867 /* FIXME: Add some code here */
1872 static void
1873 dir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
1876 if (add_dirent((SMBCFILE *)state, finfo->name, "",
1877 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
1879 /* Handle an error ... */
1881 /* FIXME: Add some code ... */
1887 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
1889 fstring server, share, user, password, options;
1890 pstring workgroup;
1891 pstring path;
1892 uint16 mode;
1893 char *p;
1894 SMBCSRV *srv = NULL;
1895 SMBCFILE *dir = NULL;
1896 struct in_addr rem_ip;
1898 if (!context || !context->internal ||
1899 !context->internal->_initialized) {
1900 DEBUG(4, ("no valid context\n"));
1901 errno = EINVAL + 8192;
1902 return NULL;
1906 if (!fname) {
1907 DEBUG(4, ("no valid fname\n"));
1908 errno = EINVAL + 8193;
1909 return NULL;
1912 if (smbc_parse_path(context, fname,
1913 server, sizeof(server),
1914 share, sizeof(share),
1915 path, sizeof(path),
1916 user, sizeof(user),
1917 password, sizeof(password),
1918 options, sizeof(options))) {
1919 DEBUG(4, ("no valid path\n"));
1920 errno = EINVAL + 8194;
1921 return NULL;
1924 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
1926 /* Ensure the options are valid */
1927 if (smbc_check_options(server, share, path, options)) {
1928 DEBUG(4, ("unacceptable options (%s)\n", options));
1929 errno = EINVAL + 8195;
1930 return NULL;
1933 if (user[0] == (char)0) fstrcpy(user, context->user);
1935 pstrcpy(workgroup, context->workgroup);
1937 dir = SMB_MALLOC_P(SMBCFILE);
1939 if (!dir) {
1941 errno = ENOMEM;
1942 return NULL;
1946 ZERO_STRUCTP(dir);
1948 dir->cli_fd = 0;
1949 dir->fname = SMB_STRDUP(fname);
1950 dir->srv = NULL;
1951 dir->offset = 0;
1952 dir->file = False;
1953 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
1955 if (server[0] == (char)0) {
1957 int i;
1958 int count;
1959 int max_lmb_count;
1960 struct ip_service *ip_list;
1961 struct ip_service server_addr;
1962 struct user_auth_info u_info;
1963 struct cli_state *cli;
1965 if (share[0] != (char)0 || path[0] != (char)0) {
1967 errno = EINVAL + 8196;
1968 if (dir) {
1969 SAFE_FREE(dir->fname);
1970 SAFE_FREE(dir);
1972 return NULL;
1975 /* Determine how many local master browsers to query */
1976 max_lmb_count = (context->options.browse_max_lmb_count == 0
1977 ? INT_MAX
1978 : context->options.browse_max_lmb_count);
1980 pstrcpy(u_info.username, user);
1981 pstrcpy(u_info.password, password);
1984 * We have server and share and path empty but options
1985 * requesting that we scan all master browsers for their list
1986 * of workgroups/domains. This implies that we must first try
1987 * broadcast queries to find all master browsers, and if that
1988 * doesn't work, then try our other methods which return only
1989 * a single master browser.
1992 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
1993 if (!find_master_ip(workgroup, &server_addr.ip)) {
1995 errno = ENOENT;
1996 return NULL;
1999 ip_list = &server_addr;
2000 count = 1;
2003 for (i = 0; i < count && i < max_lmb_count; i++) {
2004 DEBUG(99, ("Found master browser %d of %d: %s\n", i+1, MAX(count, max_lmb_count), inet_ntoa(ip_list[i].ip)));
2006 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2007 /* cli == NULL is the master browser refused to talk or
2008 could not be found */
2009 if ( !cli )
2010 continue;
2012 fstrcpy(server, cli->desthost);
2013 cli_shutdown(cli);
2015 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2018 * For each returned master browser IP address, get a
2019 * connection to IPC$ on the server if we do not
2020 * already have one, and determine the
2021 * workgroups/domains that it knows about.
2024 srv = smbc_server(context, server,
2025 "IPC$", workgroup, user, password);
2026 if (!srv) {
2027 continue;
2030 dir->srv = srv;
2031 dir->dir_type = SMBC_WORKGROUP;
2033 /* Now, list the stuff ... */
2035 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2036 (void *)dir)) {
2038 continue;
2041 } else {
2043 * Server not an empty string ... Check the rest and see what
2044 * gives
2046 if (share[0] == (char)0) {
2048 if (path[0] != (char)0) { /* Should not have empty share with path */
2050 errno = EINVAL + 8197;
2051 if (dir) {
2052 SAFE_FREE(dir->fname);
2053 SAFE_FREE(dir);
2055 return NULL;
2059 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2060 /* However, we check to see if <server> is an IP address first */
2062 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2063 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2064 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2065 fstring buserver;
2067 dir->dir_type = SMBC_SERVER;
2070 * Get the backup list ...
2074 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2076 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2077 errno = EPERM; /* FIXME, is this correct */
2078 return NULL;
2083 * Get a connection to IPC$ on the server if we do not already have one
2086 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2088 if (!srv) {
2089 DEBUG(0, ("got no contact to IPC$\n"));
2090 if (dir) {
2091 SAFE_FREE(dir->fname);
2092 SAFE_FREE(dir);
2094 return NULL;
2098 dir->srv = srv;
2100 /* Now, list the servers ... */
2102 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2103 (void *)dir)) {
2105 if (dir) {
2106 SAFE_FREE(dir->fname);
2107 SAFE_FREE(dir);
2109 return NULL;
2113 else {
2115 if (resolve_name(server, &rem_ip, 0x20)) {
2117 /* Now, list the shares ... */
2119 dir->dir_type = SMBC_FILE_SHARE;
2121 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2123 if (!srv) {
2125 if (dir) {
2126 SAFE_FREE(dir->fname);
2127 SAFE_FREE(dir);
2129 return NULL;
2133 dir->srv = srv;
2135 /* Now, list the servers ... */
2137 if (cli_RNetShareEnum(&srv->cli, list_fn,
2138 (void *)dir) < 0) {
2140 errno = cli_errno(&srv->cli);
2141 if (dir) {
2142 SAFE_FREE(dir->fname);
2143 SAFE_FREE(dir);
2145 return NULL;
2150 else {
2152 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2153 if (dir) {
2154 SAFE_FREE(dir->fname);
2155 SAFE_FREE(dir);
2157 return NULL;
2164 else { /* The server and share are specified ... work from there ... */
2166 /* Well, we connect to the server and list the directory */
2168 dir->dir_type = SMBC_FILE_SHARE;
2170 srv = smbc_server(context, server, share, workgroup, user, password);
2172 if (!srv) {
2174 if (dir) {
2175 SAFE_FREE(dir->fname);
2176 SAFE_FREE(dir);
2178 return NULL;
2182 dir->srv = srv;
2184 /* Now, list the files ... */
2186 p = path + strlen(path);
2187 pstrcat(path, "\\*");
2189 if (cli_list(&srv->cli, path, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2190 (void *)dir) < 0) {
2192 if (dir) {
2193 SAFE_FREE(dir->fname);
2194 SAFE_FREE(dir);
2196 errno = smbc_errno(context, &srv->cli);
2198 if (errno == EINVAL) {
2200 * See if they asked to opendir something
2201 * other than a directory. If so, the
2202 * converted error value we got would have
2203 * been EINVAL rather than ENOTDIR.
2205 *p = '\0'; /* restore original path */
2207 if (smbc_getatr(context, srv, path,
2208 &mode, NULL,
2209 NULL, NULL, NULL,
2210 NULL) &&
2211 ! IS_DOS_DIR(mode)) {
2213 /* It is. Correct the error value */
2214 errno = ENOTDIR;
2218 return NULL;
2225 DLIST_ADD(context->internal->_files, dir);
2226 return dir;
2231 * Routine to close a directory
2234 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2237 if (!context || !context->internal ||
2238 !context->internal->_initialized) {
2240 errno = EINVAL;
2241 return -1;
2245 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2247 errno = EBADF;
2248 return -1;
2252 smbc_remove_dir(dir); /* Clean it up */
2254 DLIST_REMOVE(context->internal->_files, dir);
2256 if (dir) {
2258 SAFE_FREE(dir->fname);
2259 SAFE_FREE(dir); /* Free the space too */
2262 return 0;
2266 static void smbc_readdir_internal(SMBCCTX * context,
2267 struct smbc_dirent *dest,
2268 struct smbc_dirent *src,
2269 int max_namebuf_len)
2271 if (context->options.urlencode_readdir_entries) {
2273 /* url-encode the name. get back remaining buffer space */
2274 max_namebuf_len =
2275 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2277 /* We now know the name length */
2278 dest->namelen = strlen(dest->name);
2280 /* Save the pointer to the beginning of the comment */
2281 dest->comment = dest->name + dest->namelen + 1;
2283 /* Copy the comment */
2284 strncpy(dest->comment, src->comment, max_namebuf_len);
2286 /* Ensure the comment is null terminated */
2287 if (max_namebuf_len > src->commentlen) {
2288 dest->comment[src->commentlen] = '\0';
2289 } else {
2290 dest->comment[max_namebuf_len - 1] = '\0';
2293 /* Save other fields */
2294 dest->smbc_type = src->smbc_type;
2295 dest->commentlen = strlen(dest->comment);
2296 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2297 (char *) dest);
2298 } else {
2300 /* No encoding. Just copy the entry as is. */
2301 memcpy(dest, src, src->dirlen);
2302 dest->comment = (char *)(&dest->name + src->namelen + 1);
2308 * Routine to get a directory entry
2311 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2313 int maxlen;
2314 struct smbc_dirent *dirp, *dirent;
2316 /* Check that all is ok first ... */
2318 if (!context || !context->internal ||
2319 !context->internal->_initialized) {
2321 errno = EINVAL;
2322 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2323 return NULL;
2327 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2329 errno = EBADF;
2330 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2331 return NULL;
2335 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2337 errno = ENOTDIR;
2338 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2339 return NULL;
2343 if (!dir->dir_next) {
2344 return NULL;
2347 dirent = dir->dir_next->dirent;
2348 if (!dirent) {
2350 errno = ENOENT;
2351 return NULL;
2355 dirp = (struct smbc_dirent *)context->internal->_dirent;
2356 maxlen = (sizeof(context->internal->_dirent) -
2357 sizeof(struct smbc_dirent));
2359 smbc_readdir_internal(context, dirp, dirent, maxlen);
2361 dir->dir_next = dir->dir_next->next;
2363 return dirp;
2367 * Routine to get directory entries
2370 static int smbc_getdents_ctx(SMBCCTX *context,
2371 SMBCFILE *dir,
2372 struct smbc_dirent *dirp,
2373 int count)
2375 int rem = count;
2376 int reqd;
2377 int maxlen;
2378 char *ndir = (char *)dirp;
2379 struct smbc_dir_list *dirlist;
2381 /* Check that all is ok first ... */
2383 if (!context || !context->internal ||
2384 !context->internal->_initialized) {
2386 errno = EINVAL;
2387 return -1;
2391 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2393 errno = EBADF;
2394 return -1;
2398 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2400 errno = ENOTDIR;
2401 return -1;
2406 * Now, retrieve the number of entries that will fit in what was passed
2407 * We have to figure out if the info is in the list, or we need to
2408 * send a request to the server to get the info.
2411 while ((dirlist = dir->dir_next)) {
2412 struct smbc_dirent *dirent;
2414 if (!dirlist->dirent) {
2416 errno = ENOENT; /* Bad error */
2417 return -1;
2421 /* Do urlencoding of next entry, if so selected */
2422 dirent = (struct smbc_dirent *)context->internal->_dirent;
2423 maxlen = (sizeof(context->internal->_dirent) -
2424 sizeof(struct smbc_dirent));
2425 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
2427 reqd = dirent->dirlen;
2429 if (rem < reqd) {
2431 if (rem < count) { /* We managed to copy something */
2433 errno = 0;
2434 return count - rem;
2437 else { /* Nothing copied ... */
2439 errno = EINVAL; /* Not enough space ... */
2440 return -1;
2446 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2448 ((struct smbc_dirent *)ndir)->comment =
2449 (char *)(&((struct smbc_dirent *)ndir)->name +
2450 dirent->namelen +
2453 ndir += reqd;
2455 rem -= reqd;
2457 dir->dir_next = dirlist = dirlist -> next;
2460 if (rem == count)
2461 return 0;
2462 else
2463 return count - rem;
2468 * Routine to create a directory ...
2471 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2473 SMBCSRV *srv;
2474 fstring server, share, user, password, workgroup;
2475 pstring path;
2477 if (!context || !context->internal ||
2478 !context->internal->_initialized) {
2480 errno = EINVAL;
2481 return -1;
2485 if (!fname) {
2487 errno = EINVAL;
2488 return -1;
2492 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2494 if (smbc_parse_path(context, fname,
2495 server, sizeof(server),
2496 share, sizeof(share),
2497 path, sizeof(path),
2498 user, sizeof(user),
2499 password, sizeof(password),
2500 NULL, 0)) {
2501 errno = EINVAL;
2502 return -1;
2505 if (user[0] == (char)0) fstrcpy(user, context->user);
2507 fstrcpy(workgroup, context->workgroup);
2509 srv = smbc_server(context, server, share, workgroup, user, password);
2511 if (!srv) {
2513 return -1; /* errno set by smbc_server */
2517 if (!cli_mkdir(&srv->cli, path)) {
2519 errno = smbc_errno(context, &srv->cli);
2520 return -1;
2524 return 0;
2529 * Our list function simply checks to see if a directory is not empty
2532 static int smbc_rmdir_dirempty = True;
2534 static void rmdir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2537 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2538 smbc_rmdir_dirempty = False;
2543 * Routine to remove a directory
2546 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2548 SMBCSRV *srv;
2549 fstring server, share, user, password, workgroup;
2550 pstring path;
2552 if (!context || !context->internal ||
2553 !context->internal->_initialized) {
2555 errno = EINVAL;
2556 return -1;
2560 if (!fname) {
2562 errno = EINVAL;
2563 return -1;
2567 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2569 if (smbc_parse_path(context, fname,
2570 server, sizeof(server),
2571 share, sizeof(share),
2572 path, sizeof(path),
2573 user, sizeof(user),
2574 password, sizeof(password),
2575 NULL, 0))
2577 errno = EINVAL;
2578 return -1;
2581 if (user[0] == (char)0) fstrcpy(user, context->user);
2583 fstrcpy(workgroup, context->workgroup);
2585 srv = smbc_server(context, server, share, workgroup, user, password);
2587 if (!srv) {
2589 return -1; /* errno set by smbc_server */
2593 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2595 mode = aDIR | aRONLY;
2598 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2600 if (strcmp(path, "\\") == 0) {
2602 mode = aDIR | aRONLY;
2605 else {
2607 mode = aRONLY;
2608 smbc_stat_printjob(srv, path, &size, &m_time);
2609 c_time = a_time = m_time;
2612 else { */
2614 if (!cli_rmdir(&srv->cli, path)) {
2616 errno = smbc_errno(context, &srv->cli);
2618 if (errno == EACCES) { /* Check if the dir empty or not */
2620 pstring lpath; /* Local storage to avoid buffer overflows */
2622 smbc_rmdir_dirempty = True; /* Make this so ... */
2624 pstrcpy(lpath, path);
2625 pstrcat(lpath, "\\*");
2627 if (cli_list(&srv->cli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2628 NULL) < 0) {
2630 /* Fix errno to ignore latest error ... */
2632 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
2633 smbc_errno(context, &srv->cli)));
2634 errno = EACCES;
2638 if (smbc_rmdir_dirempty)
2639 errno = EACCES;
2640 else
2641 errno = ENOTEMPTY;
2645 return -1;
2649 return 0;
2654 * Routine to return the current directory position
2657 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
2659 off_t ret_val; /* Squash warnings about cast */
2661 if (!context || !context->internal ||
2662 !context->internal->_initialized) {
2664 errno = EINVAL;
2665 return -1;
2669 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2671 errno = EBADF;
2672 return -1;
2676 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2678 errno = ENOTDIR;
2679 return -1;
2684 * We return the pointer here as the offset
2686 ret_val = (int)dir->dir_next;
2687 return ret_val;
2692 * A routine to run down the list and see if the entry is OK
2695 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
2696 struct smbc_dirent *dirent)
2699 /* Run down the list looking for what we want */
2701 if (dirent) {
2703 struct smbc_dir_list *tmp = list;
2705 while (tmp) {
2707 if (tmp->dirent == dirent)
2708 return tmp;
2710 tmp = tmp->next;
2716 return NULL; /* Not found, or an error */
2722 * Routine to seek on a directory
2725 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
2727 long int l_offset = offset; /* Handle problems of size */
2728 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
2729 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
2731 if (!context || !context->internal ||
2732 !context->internal->_initialized) {
2734 errno = EINVAL;
2735 return -1;
2739 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2741 errno = ENOTDIR;
2742 return -1;
2746 /* Now, check what we were passed and see if it is OK ... */
2748 if (dirent == NULL) { /* Seek to the begining of the list */
2750 dir->dir_next = dir->dir_list;
2751 return 0;
2755 /* Now, run down the list and make sure that the entry is OK */
2756 /* This may need to be changed if we change the format of the list */
2758 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
2760 errno = EINVAL; /* Bad entry */
2761 return -1;
2765 dir->dir_next = list_ent;
2767 return 0;
2772 * Routine to fstat a dir
2775 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
2778 if (!context || !context->internal ||
2779 !context->internal->_initialized) {
2781 errno = EINVAL;
2782 return -1;
2786 /* No code yet ... */
2788 return 0;
2792 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
2794 SMBCSRV *srv;
2795 fstring server, share, user, password, workgroup;
2796 pstring path;
2797 uint16 mode;
2799 if (!context || !context->internal ||
2800 !context->internal->_initialized) {
2802 errno = EINVAL; /* Best I can think of ... */
2803 return -1;
2807 if (!fname) {
2809 errno = EINVAL;
2810 return -1;
2814 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
2816 if (smbc_parse_path(context, fname,
2817 server, sizeof(server),
2818 share, sizeof(share),
2819 path, sizeof(path),
2820 user, sizeof(user),
2821 password, sizeof(password),
2822 NULL, 0)) {
2823 errno = EINVAL;
2824 return -1;
2827 if (user[0] == (char)0) fstrcpy(user, context->user);
2829 fstrcpy(workgroup, context->workgroup);
2831 srv = smbc_server(context, server, share, workgroup, user, password);
2833 if (!srv) {
2834 return -1; /* errno set by smbc_server */
2837 mode = 0;
2839 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
2840 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
2841 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
2842 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
2844 if (!cli_setatr(&srv->cli, path, mode, 0)) {
2845 errno = smbc_errno(context, &srv->cli);
2846 return -1;
2849 return 0;
2852 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
2854 int fd;
2855 int ret;
2856 SMBCSRV *srv;
2857 fstring server, share, user, password, workgroup;
2858 pstring path;
2859 time_t c_time;
2860 time_t a_time;
2861 time_t m_time;
2863 if (!context || !context->internal ||
2864 !context->internal->_initialized) {
2866 errno = EINVAL; /* Best I can think of ... */
2867 return -1;
2871 if (!fname) {
2873 errno = EINVAL;
2874 return -1;
2878 if (tbuf == NULL) {
2879 a_time = m_time = time(NULL);
2880 } else {
2881 a_time = tbuf[0].tv_sec;
2882 m_time = tbuf[1].tv_sec;
2886 char atimebuf[32];
2887 char mtimebuf[32];
2889 DEBUG(4, ("smbc_utimes(%s, atime = %s mtime = %s)\n",
2890 fname,
2891 ctime_r(&a_time, atimebuf),
2892 ctime_r(&m_time, mtimebuf)));
2895 if (smbc_parse_path(context, fname,
2896 server, sizeof(server),
2897 share, sizeof(share),
2898 path, sizeof(path),
2899 user, sizeof(user),
2900 password, sizeof(password),
2901 NULL, 0)) {
2902 errno = EINVAL;
2903 return -1;
2906 if (user[0] == (char)0) fstrcpy(user, context->user);
2908 fstrcpy(workgroup, context->workgroup);
2910 srv = smbc_server(context, server, share, workgroup, user, password);
2912 if (!srv) {
2913 return -1; /* errno set by smbc_server */
2917 * cli_setatr() does not work on win98, and it also doesn't support
2918 * setting the access time (only the modification time), so in all
2919 * cases, we open the specified file and use cli_setattrE() which
2920 * should work on all OS versions, and supports both times.
2922 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
2924 errno = smbc_errno(context, &srv->cli);
2925 return -1;
2929 /* Get the creat time of the file; we'll need it in the set call */
2930 ret = cli_getattrE(&srv->cli, fd, NULL, NULL, &c_time, NULL, NULL);
2932 /* Some OS versions don't support create time */
2933 if (c_time == 0) {
2934 c_time = time(NULL);
2938 * For sanity sake, since there is no POSIX function to set the create
2939 * time of a file, if the existing create time is greater than either
2940 * of access time or modification time, set create time to the
2941 * smallest of those. This ensure that the create time of a file is
2942 * never greater than its last access or modification time.
2944 if (c_time > a_time) c_time = a_time;
2945 if (c_time > m_time) c_time = m_time;
2947 /* If we sucessfully retrieved the create time... */
2948 if (ret) {
2949 /* ... then set the new attributes */
2950 ret = cli_setattrE(&srv->cli, fd, c_time, a_time, m_time);
2953 cli_close(&srv->cli, fd);
2955 return ret;
2959 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
2960 However NT4 gives a "The information may have been modified by a
2961 computer running Windows NT 5.0" if denied ACEs do not appear before
2962 allowed ACEs. */
2964 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
2966 if (sec_ace_equal(ace1, ace2))
2967 return 0;
2969 if (ace1->type != ace2->type)
2970 return ace2->type - ace1->type;
2972 if (sid_compare(&ace1->trustee, &ace2->trustee))
2973 return sid_compare(&ace1->trustee, &ace2->trustee);
2975 if (ace1->flags != ace2->flags)
2976 return ace1->flags - ace2->flags;
2978 if (ace1->info.mask != ace2->info.mask)
2979 return ace1->info.mask - ace2->info.mask;
2981 if (ace1->size != ace2->size)
2982 return ace1->size - ace2->size;
2984 return memcmp(ace1, ace2, sizeof(SEC_ACE));
2988 static void sort_acl(SEC_ACL *the_acl)
2990 uint32 i;
2991 if (!the_acl) return;
2993 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
2995 for (i=1;i<the_acl->num_aces;) {
2996 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
2997 int j;
2998 for (j=i; j<the_acl->num_aces-1; j++) {
2999 the_acl->ace[j] = the_acl->ace[j+1];
3001 the_acl->num_aces--;
3002 } else {
3003 i++;
3008 /* convert a SID to a string, either numeric or username/group */
3009 static void convert_sid_to_string(struct cli_state *ipc_cli,
3010 POLICY_HND *pol,
3011 fstring str,
3012 BOOL numeric,
3013 DOM_SID *sid)
3015 char **domains = NULL;
3016 char **names = NULL;
3017 uint32 *types = NULL;
3019 sid_to_string(str, sid);
3021 if (numeric) return; /* no lookup desired */
3023 /* Ask LSA to convert the sid to a name */
3025 if (!NT_STATUS_IS_OK(cli_lsa_lookup_sids(ipc_cli, ipc_cli->mem_ctx,
3026 pol, 1, sid, &domains,
3027 &names, &types)) ||
3028 !domains || !domains[0] || !names || !names[0]) {
3029 return;
3032 /* Converted OK */
3034 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3035 domains[0], lp_winbind_separator(),
3036 names[0]);
3039 /* convert a string to a SID, either numeric or username/group */
3040 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
3041 POLICY_HND *pol,
3042 BOOL numeric,
3043 DOM_SID *sid,
3044 const char *str)
3046 uint32 *types = NULL;
3047 DOM_SID *sids = NULL;
3048 BOOL result = True;
3050 if (numeric) {
3051 if (strncmp(str, "S-", 2) == 0) {
3052 return string_to_sid(sid, str);
3055 result = False;
3056 goto done;
3059 if (!NT_STATUS_IS_OK(cli_lsa_lookup_names(ipc_cli, ipc_cli->mem_ctx,
3060 pol, 1, &str, &sids,
3061 &types))) {
3062 result = False;
3063 goto done;
3066 sid_copy(sid, &sids[0]);
3067 done:
3069 return result;
3073 /* parse an ACE in the same format as print_ace() */
3074 static BOOL parse_ace(struct cli_state *ipc_cli,
3075 POLICY_HND *pol,
3076 SEC_ACE *ace,
3077 BOOL numeric,
3078 char *str)
3080 char *p;
3081 const char *cp;
3082 fstring tok;
3083 unsigned atype, aflags, amask;
3084 DOM_SID sid;
3085 SEC_ACCESS mask;
3086 const struct perm_value *v;
3087 struct perm_value {
3088 const char *perm;
3089 uint32 mask;
3092 /* These values discovered by inspection */
3093 static const struct perm_value special_values[] = {
3094 { "R", 0x00120089 },
3095 { "W", 0x00120116 },
3096 { "X", 0x001200a0 },
3097 { "D", 0x00010000 },
3098 { "P", 0x00040000 },
3099 { "O", 0x00080000 },
3100 { NULL, 0 },
3103 static const struct perm_value standard_values[] = {
3104 { "READ", 0x001200a9 },
3105 { "CHANGE", 0x001301bf },
3106 { "FULL", 0x001f01ff },
3107 { NULL, 0 },
3111 ZERO_STRUCTP(ace);
3112 p = strchr_m(str,':');
3113 if (!p) return False;
3114 *p = '\0';
3115 p++;
3116 /* Try to parse numeric form */
3118 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3119 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3120 goto done;
3123 /* Try to parse text form */
3125 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3126 return False;
3129 cp = p;
3130 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3131 return False;
3134 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3135 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3136 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3137 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3138 } else {
3139 return False;
3142 /* Only numeric form accepted for flags at present */
3144 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3145 sscanf(tok, "%i", &aflags))) {
3146 return False;
3149 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3150 return False;
3153 if (strncmp(tok, "0x", 2) == 0) {
3154 if (sscanf(tok, "%i", &amask) != 1) {
3155 return False;
3157 goto done;
3160 for (v = standard_values; v->perm; v++) {
3161 if (strcmp(tok, v->perm) == 0) {
3162 amask = v->mask;
3163 goto done;
3167 p = tok;
3169 while(*p) {
3170 BOOL found = False;
3172 for (v = special_values; v->perm; v++) {
3173 if (v->perm[0] == *p) {
3174 amask |= v->mask;
3175 found = True;
3179 if (!found) return False;
3180 p++;
3183 if (*p) {
3184 return False;
3187 done:
3188 mask.mask = amask;
3189 init_sec_ace(ace, &sid, atype, mask, aflags);
3190 return True;
3193 /* add an ACE to a list of ACEs in a SEC_ACL */
3194 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3196 SEC_ACL *new;
3197 SEC_ACE *aces;
3198 if (! *the_acl) {
3199 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3200 return True;
3203 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3204 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3205 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3206 new = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3207 SAFE_FREE(aces);
3208 (*the_acl) = new;
3209 return True;
3213 /* parse a ascii version of a security descriptor */
3214 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3215 struct cli_state *ipc_cli,
3216 POLICY_HND *pol,
3217 BOOL numeric,
3218 char *str)
3220 const char *p = str;
3221 fstring tok;
3222 SEC_DESC *ret;
3223 size_t sd_size;
3224 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3225 SEC_ACL *dacl=NULL;
3226 int revision=1;
3228 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3230 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3231 revision = strtol(tok+9, NULL, 16);
3232 continue;
3235 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3236 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3237 if (!owner_sid ||
3238 !convert_string_to_sid(ipc_cli, pol,
3239 numeric,
3240 owner_sid, tok+6)) {
3241 DEBUG(5, ("Failed to parse owner sid\n"));
3242 return NULL;
3244 continue;
3247 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3248 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3249 if (!owner_sid ||
3250 !convert_string_to_sid(ipc_cli, pol,
3251 False,
3252 owner_sid, tok+7)) {
3253 DEBUG(5, ("Failed to parse owner sid\n"));
3254 return NULL;
3256 continue;
3259 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3260 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3261 if (!grp_sid ||
3262 !convert_string_to_sid(ipc_cli, pol,
3263 numeric,
3264 grp_sid, tok+6)) {
3265 DEBUG(5, ("Failed to parse group sid\n"));
3266 return NULL;
3268 continue;
3271 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3272 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3273 if (!grp_sid ||
3274 !convert_string_to_sid(ipc_cli, pol,
3275 False,
3276 grp_sid, tok+6)) {
3277 DEBUG(5, ("Failed to parse group sid\n"));
3278 return NULL;
3280 continue;
3283 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3284 SEC_ACE ace;
3285 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3286 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3287 return NULL;
3289 if(!add_ace(&dacl, &ace, ctx)) {
3290 DEBUG(5, ("Failed to add ACL %s\n", tok));
3291 return NULL;
3293 continue;
3296 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3297 SEC_ACE ace;
3298 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3299 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3300 return NULL;
3302 if(!add_ace(&dacl, &ace, ctx)) {
3303 DEBUG(5, ("Failed to add ACL %s\n", tok));
3304 return NULL;
3306 continue;
3309 DEBUG(5, ("Failed to parse security descriptor\n"));
3310 return NULL;
3313 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3314 owner_sid, grp_sid, NULL, dacl, &sd_size);
3316 SAFE_FREE(grp_sid);
3317 SAFE_FREE(owner_sid);
3319 return ret;
3323 /* Obtain the current dos attributes */
3324 static DOS_ATTR_DESC *dos_attr_query(SMBCCTX *context,
3325 TALLOC_CTX *ctx,
3326 const char *filename,
3327 SMBCSRV *srv)
3329 time_t m_time = 0, a_time = 0, c_time = 0;
3330 SMB_OFF_T size = 0;
3331 uint16 mode = 0;
3332 SMB_INO_T inode = 0;
3333 DOS_ATTR_DESC *ret;
3335 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
3336 if (!ret) {
3337 errno = ENOMEM;
3338 return NULL;
3341 /* Obtain the DOS attributes */
3342 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
3343 &mode, &size,
3344 &c_time, &a_time, &m_time, &inode)) {
3346 errno = smbc_errno(context, &srv->cli);
3347 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
3348 return NULL;
3352 ret->mode = mode;
3353 ret->size = size;
3354 ret->a_time = a_time;
3355 ret->c_time = c_time;
3356 ret->m_time = m_time;
3357 ret->inode = inode;
3359 return ret;
3363 /* parse a ascii version of a security descriptor */
3364 static void dos_attr_parse(SMBCCTX *context,
3365 DOS_ATTR_DESC *dad,
3366 SMBCSRV *srv,
3367 char *str)
3369 const char *p = str;
3370 fstring tok;
3372 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3374 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
3375 dad->mode = strtol(tok+5, NULL, 16);
3376 continue;
3379 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
3380 dad->size = strtoll(tok+5, NULL, 10);
3381 continue;
3384 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
3385 dad->a_time = strtoll(tok+7, NULL, 10);
3386 continue;
3389 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
3390 dad->c_time = strtoll(tok+7, NULL, 10);
3391 continue;
3394 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
3395 dad->m_time = strtoll(tok+7, NULL, 10);
3396 continue;
3399 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
3400 dad->inode = strtoll(tok+6, NULL, 10);
3401 continue;
3407 /*****************************************************
3408 retrieve the acls for a file
3409 *******************************************************/
3410 static int cacl_get(SMBCCTX *context, TALLOC_CTX *ctx, SMBCSRV *srv,
3411 struct cli_state *ipc_cli, POLICY_HND *pol,
3412 char *filename, char *attr_name, char *buf, int bufsize)
3414 uint32 i;
3415 int n = 0;
3416 int n_used;
3417 BOOL all;
3418 BOOL all_nt;
3419 BOOL all_nt_acls;
3420 BOOL all_dos;
3421 BOOL some_nt;
3422 BOOL some_dos;
3423 BOOL exclude_nt_revision = False;
3424 BOOL exclude_nt_owner = False;
3425 BOOL exclude_nt_group = False;
3426 BOOL exclude_nt_acl = False;
3427 BOOL exclude_dos_mode = False;
3428 BOOL exclude_dos_size = False;
3429 BOOL exclude_dos_ctime = False;
3430 BOOL exclude_dos_atime = False;
3431 BOOL exclude_dos_mtime = False;
3432 BOOL exclude_dos_inode = False;
3433 BOOL numeric = True;
3434 BOOL determine_size = (bufsize == 0);
3435 int fnum = -1;
3436 SEC_DESC *sd;
3437 fstring sidstr;
3438 fstring name_sandbox;
3439 char *name;
3440 char *pExclude;
3441 char *p;
3442 time_t m_time = 0, a_time = 0, c_time = 0;
3443 SMB_OFF_T size = 0;
3444 uint16 mode = 0;
3445 SMB_INO_T ino = 0;
3446 struct cli_state *cli = &srv->cli;
3448 /* Copy name so we can strip off exclusions (if any are specified) */
3449 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
3451 /* Ensure name is null terminated */
3452 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
3454 /* Play in the sandbox */
3455 name = name_sandbox;
3457 /* If there are any exclusions, point to them and mask them from name */
3458 if ((pExclude = strchr(name, '!')) != NULL)
3460 *pExclude++ = '\0';
3463 all = (StrnCaseCmp(name, "system.*", 8) == 0);
3464 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
3465 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
3466 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
3467 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
3468 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
3469 numeric = (* (name + strlen(name) - 1) != '+');
3471 /* Look for exclusions from "all" requests */
3472 if (all || all_nt || all_dos) {
3474 /* Exclusions are delimited by '!' */
3475 for (; pExclude != NULL; pExclude = (p == NULL ? NULL : p + 1)) {
3477 /* Find end of this exclusion name */
3478 if ((p = strchr(pExclude, '!')) != NULL)
3480 *p = '\0';
3483 /* Which exclusion name is this? */
3484 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
3485 exclude_nt_revision = True;
3487 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
3488 exclude_nt_owner = True;
3490 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
3491 exclude_nt_group = True;
3493 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
3494 exclude_nt_acl = True;
3496 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
3497 exclude_dos_mode = True;
3499 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
3500 exclude_dos_size = True;
3502 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
3503 exclude_dos_ctime = True;
3505 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
3506 exclude_dos_atime = True;
3508 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
3509 exclude_dos_mtime = True;
3511 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
3512 exclude_dos_inode = True;
3514 else {
3515 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
3516 pExclude));
3517 errno = ENOATTR;
3518 return -1;
3523 n_used = 0;
3526 * If we are (possibly) talking to an NT or new system and some NT
3527 * attributes have been requested...
3529 if (ipc_cli && (all || some_nt || all_nt_acls)) {
3530 /* Point to the portion after "system.nt_sec_desc." */
3531 name += 19; /* if (all) this will be invalid but unused */
3533 /* ... then obtain any NT attributes which were requested */
3534 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3536 if (fnum == -1) {
3537 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3538 filename, cli_errstr(cli)));
3539 errno = 0;
3540 return -1;
3543 sd = cli_query_secdesc(cli, fnum, ctx);
3545 if (!sd) {
3546 DEBUG(5,
3547 ("cacl_get Failed to query old descriptor\n"));
3548 errno = 0;
3549 return -1;
3552 cli_close(cli, fnum);
3554 if (! exclude_nt_revision) {
3555 if (all || all_nt) {
3556 if (determine_size) {
3557 p = talloc_asprintf(ctx,
3558 "REVISION:%d",
3559 sd->revision);
3560 if (!p) {
3561 errno = ENOMEM;
3562 return -1;
3564 n = strlen(p);
3565 } else {
3566 n = snprintf(buf, bufsize,
3567 "REVISION:%d", sd->revision);
3569 } else if (StrCaseCmp(name, "revision") == 0) {
3570 if (determine_size) {
3571 p = talloc_asprintf(ctx, "%d",
3572 sd->revision);
3573 if (!p) {
3574 errno = ENOMEM;
3575 return -1;
3577 n = strlen(p);
3578 } else {
3579 n = snprintf(buf, bufsize, "%d",
3580 sd->revision);
3584 if (!determine_size && n > bufsize) {
3585 errno = ERANGE;
3586 return -1;
3588 buf += n;
3589 n_used += n;
3590 bufsize -= n;
3593 if (! exclude_nt_owner) {
3594 /* Get owner and group sid */
3595 if (sd->owner_sid) {
3596 convert_sid_to_string(ipc_cli, pol,
3597 sidstr,
3598 numeric,
3599 sd->owner_sid);
3600 } else {
3601 fstrcpy(sidstr, "");
3604 if (all || all_nt) {
3605 if (determine_size) {
3606 p = talloc_asprintf(ctx, ",OWNER:%s",
3607 sidstr);
3608 if (!p) {
3609 errno = ENOMEM;
3610 return -1;
3612 n = strlen(p);
3613 } else {
3614 n = snprintf(buf, bufsize,
3615 ",OWNER:%s", sidstr);
3617 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3618 if (determine_size) {
3619 p = talloc_asprintf(ctx, "%s", sidstr);
3620 if (!p) {
3621 errno = ENOMEM;
3622 return -1;
3624 n = strlen(p);
3625 } else {
3626 n = snprintf(buf, bufsize, "%s",
3627 sidstr);
3631 if (!determine_size && n > bufsize) {
3632 errno = ERANGE;
3633 return -1;
3635 buf += n;
3636 n_used += n;
3637 bufsize -= n;
3640 if (! exclude_nt_group) {
3641 if (sd->grp_sid) {
3642 convert_sid_to_string(ipc_cli, pol,
3643 sidstr, numeric,
3644 sd->grp_sid);
3645 } else {
3646 fstrcpy(sidstr, "");
3649 if (all || all_nt) {
3650 if (determine_size) {
3651 p = talloc_asprintf(ctx, ",GROUP:%s",
3652 sidstr);
3653 if (!p) {
3654 errno = ENOMEM;
3655 return -1;
3657 n = strlen(p);
3658 } else {
3659 n = snprintf(buf, bufsize,
3660 ",GROUP:%s", sidstr);
3662 } else if (StrnCaseCmp(name, "group", 5) == 0) {
3663 if (determine_size) {
3664 p = talloc_asprintf(ctx, "%s", sidstr);
3665 if (!p) {
3666 errno = ENOMEM;
3667 return -1;
3669 n = strlen(p);
3670 } else {
3671 n = snprintf(buf, bufsize, "%s", sidstr);
3675 if (!determine_size && n > bufsize) {
3676 errno = ERANGE;
3677 return -1;
3679 buf += n;
3680 n_used += n;
3681 bufsize -= n;
3684 if (! exclude_nt_acl) {
3685 /* Add aces to value buffer */
3686 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
3688 SEC_ACE *ace = &sd->dacl->ace[i];
3689 convert_sid_to_string(ipc_cli, pol,
3690 sidstr, numeric,
3691 &ace->trustee);
3693 if (all || all_nt) {
3694 if (determine_size) {
3695 p = talloc_asprintf(
3696 ctx,
3697 ",ACL:"
3698 "%s:%d/%d/0x%08x",
3699 sidstr,
3700 ace->type,
3701 ace->flags,
3702 ace->info.mask);
3703 if (!p) {
3704 errno = ENOMEM;
3705 return -1;
3707 n = strlen(p);
3708 } else {
3709 n = snprintf(
3710 buf, bufsize,
3711 ",ACL:%s:%d/%d/0x%08x",
3712 sidstr,
3713 ace->type,
3714 ace->flags,
3715 ace->info.mask);
3717 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
3718 StrCaseCmp(name + 3, sidstr) == 0) ||
3719 (StrnCaseCmp(name, "acl+", 4) == 0 &&
3720 StrCaseCmp(name + 4, sidstr) == 0)) {
3721 if (determine_size) {
3722 p = talloc_asprintf(
3723 ctx,
3724 "%d/%d/0x%08x",
3725 ace->type,
3726 ace->flags,
3727 ace->info.mask);
3728 if (!p) {
3729 errno = ENOMEM;
3730 return -1;
3732 n = strlen(p);
3733 } else {
3734 n = snprintf(buf, bufsize,
3735 "%d/%d/0x%08x",
3736 ace->type,
3737 ace->flags,
3738 ace->info.mask);
3740 } else if (all_nt_acls) {
3741 if (determine_size) {
3742 p = talloc_asprintf(
3743 ctx,
3744 "%s%s:%d/%d/0x%08x",
3745 i ? "," : "",
3746 sidstr,
3747 ace->type,
3748 ace->flags,
3749 ace->info.mask);
3750 if (!p) {
3751 errno = ENOMEM;
3752 return -1;
3754 n = strlen(p);
3755 } else {
3756 n = snprintf(buf, bufsize,
3757 "%s%s:%d/%d/0x%08x",
3758 i ? "," : "",
3759 sidstr,
3760 ace->type,
3761 ace->flags,
3762 ace->info.mask);
3765 if (n > bufsize) {
3766 errno = ERANGE;
3767 return -1;
3769 buf += n;
3770 n_used += n;
3771 bufsize -= n;
3775 /* Restore name pointer to its original value */
3776 name -= 19;
3779 if (all || some_dos) {
3780 /* Point to the portion after "system.dos_attr." */
3781 name += 16; /* if (all) this will be invalid but unused */
3783 /* Obtain the DOS attributes */
3784 if (!smbc_getatr(context, srv, filename, &mode, &size,
3785 &c_time, &a_time, &m_time, &ino)) {
3787 errno = smbc_errno(context, &srv->cli);
3788 return -1;
3792 if (! exclude_dos_mode) {
3793 if (all || all_dos) {
3794 if (determine_size) {
3795 p = talloc_asprintf(ctx,
3796 "%sMODE:0x%x",
3797 (ipc_cli &&
3798 (all || some_nt)
3799 ? ","
3800 : ""),
3801 mode);
3802 if (!p) {
3803 errno = ENOMEM;
3804 return -1;
3806 n = strlen(p);
3807 } else {
3808 n = snprintf(buf, bufsize,
3809 "%sMODE:0x%x",
3810 (ipc_cli &&
3811 (all || some_nt)
3812 ? ","
3813 : ""),
3814 mode);
3816 } else if (StrCaseCmp(name, "mode") == 0) {
3817 if (determine_size) {
3818 p = talloc_asprintf(ctx, "0x%x", mode);
3819 if (!p) {
3820 errno = ENOMEM;
3821 return -1;
3823 n = strlen(p);
3824 } else {
3825 n = snprintf(buf, bufsize, "0x%x", mode);
3829 if (!determine_size && n > bufsize) {
3830 errno = ERANGE;
3831 return -1;
3833 buf += n;
3834 n_used += n;
3835 bufsize -= n;
3838 if (! exclude_dos_size) {
3839 if (all || all_dos) {
3840 if (determine_size) {
3841 p = talloc_asprintf(
3842 ctx,
3843 ",SIZE:%llu",
3844 (unsigned long long) size);
3845 if (!p) {
3846 errno = ENOMEM;
3847 return -1;
3849 n = strlen(p);
3850 } else {
3851 n = snprintf(buf, bufsize,
3852 ",SIZE:%llu",
3853 (unsigned long long) size);
3855 } else if (StrCaseCmp(name, "size") == 0) {
3856 if (determine_size) {
3857 p = talloc_asprintf(
3858 ctx,
3859 "%llu",
3860 (unsigned long long) size);
3861 if (!p) {
3862 errno = ENOMEM;
3863 return -1;
3865 n = strlen(p);
3866 } else {
3867 n = snprintf(buf, bufsize,
3868 "%llu",
3869 (unsigned long long) size);
3873 if (!determine_size && n > bufsize) {
3874 errno = ERANGE;
3875 return -1;
3877 buf += n;
3878 n_used += n;
3879 bufsize -= n;
3882 if (! exclude_dos_ctime) {
3883 if (all || all_dos) {
3884 if (determine_size) {
3885 p = talloc_asprintf(ctx,
3886 ",C_TIME:%lu",
3887 c_time);
3888 if (!p) {
3889 errno = ENOMEM;
3890 return -1;
3892 n = strlen(p);
3893 } else {
3894 n = snprintf(buf, bufsize,
3895 ",C_TIME:%lu", c_time);
3897 } else if (StrCaseCmp(name, "c_time") == 0) {
3898 if (determine_size) {
3899 p = talloc_asprintf(ctx, "%lu", c_time);
3900 if (!p) {
3901 errno = ENOMEM;
3902 return -1;
3904 n = strlen(p);
3905 } else {
3906 n = snprintf(buf, bufsize, "%lu", c_time);
3910 if (!determine_size && n > bufsize) {
3911 errno = ERANGE;
3912 return -1;
3914 buf += n;
3915 n_used += n;
3916 bufsize -= n;
3919 if (! exclude_dos_atime) {
3920 if (all || all_dos) {
3921 if (determine_size) {
3922 p = talloc_asprintf(ctx,
3923 ",A_TIME:%lu",
3924 a_time);
3925 if (!p) {
3926 errno = ENOMEM;
3927 return -1;
3929 n = strlen(p);
3930 } else {
3931 n = snprintf(buf, bufsize,
3932 ",A_TIME:%lu", a_time);
3934 } else if (StrCaseCmp(name, "a_time") == 0) {
3935 if (determine_size) {
3936 p = talloc_asprintf(ctx, "%lu", a_time);
3937 if (!p) {
3938 errno = ENOMEM;
3939 return -1;
3941 n = strlen(p);
3942 } else {
3943 n = snprintf(buf, bufsize, "%lu", a_time);
3947 if (!determine_size && n > bufsize) {
3948 errno = ERANGE;
3949 return -1;
3951 buf += n;
3952 n_used += n;
3953 bufsize -= n;
3956 if (! exclude_dos_mtime) {
3957 if (all || all_dos) {
3958 if (determine_size) {
3959 p = talloc_asprintf(ctx,
3960 ",M_TIME:%lu",
3961 m_time);
3962 if (!p) {
3963 errno = ENOMEM;
3964 return -1;
3966 n = strlen(p);
3967 } else {
3968 n = snprintf(buf, bufsize,
3969 ",M_TIME:%lu", m_time);
3971 } else if (StrCaseCmp(name, "m_time") == 0) {
3972 if (determine_size) {
3973 p = talloc_asprintf(ctx, "%lu", m_time);
3974 if (!p) {
3975 errno = ENOMEM;
3976 return -1;
3978 n = strlen(p);
3979 } else {
3980 n = snprintf(buf, bufsize, "%lu", m_time);
3984 if (!determine_size && n > bufsize) {
3985 errno = ERANGE;
3986 return -1;
3988 buf += n;
3989 n_used += n;
3990 bufsize -= n;
3993 if (! exclude_dos_inode) {
3994 if (all || all_dos) {
3995 if (determine_size) {
3996 p = talloc_asprintf(
3997 ctx,
3998 ",INODE:%llu",
3999 (unsigned long long) ino);
4000 if (!p) {
4001 errno = ENOMEM;
4002 return -1;
4004 n = strlen(p);
4005 } else {
4006 n = snprintf(buf, bufsize,
4007 ",INODE:%llu",
4008 (unsigned long long) ino);
4010 } else if (StrCaseCmp(name, "inode") == 0) {
4011 if (determine_size) {
4012 p = talloc_asprintf(
4013 ctx,
4014 "%llu",
4015 (unsigned long long) ino);
4016 if (!p) {
4017 errno = ENOMEM;
4018 return -1;
4020 n = strlen(p);
4021 } else {
4022 n = snprintf(buf, bufsize,
4023 "%llu",
4024 (unsigned long long) ino);
4028 if (!determine_size && n > bufsize) {
4029 errno = ERANGE;
4030 return -1;
4032 buf += n;
4033 n_used += n;
4034 bufsize -= n;
4037 /* Restore name pointer to its original value */
4038 name -= 16;
4041 if (n_used == 0) {
4042 errno = ENOATTR;
4043 return -1;
4046 return n_used;
4050 /*****************************************************
4051 set the ACLs on a file given an ascii description
4052 *******************************************************/
4053 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
4054 struct cli_state *ipc_cli, POLICY_HND *pol,
4055 const char *filename, const char *the_acl,
4056 int mode, int flags)
4058 int fnum;
4059 int err = 0;
4060 SEC_DESC *sd = NULL, *old;
4061 SEC_ACL *dacl = NULL;
4062 DOM_SID *owner_sid = NULL;
4063 DOM_SID *grp_sid = NULL;
4064 uint32 i, j;
4065 size_t sd_size;
4066 int ret = 0;
4067 char *p;
4068 BOOL numeric = True;
4070 /* the_acl will be null for REMOVE_ALL operations */
4071 if (the_acl) {
4072 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4073 p > the_acl &&
4074 p[-1] != '+');
4076 /* if this is to set the entire ACL... */
4077 if (*the_acl == '*') {
4078 /* ... then increment past the first colon */
4079 the_acl = p + 1;
4082 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4083 CONST_DISCARD(char *, the_acl));
4085 if (!sd) {
4086 errno = EINVAL;
4087 return -1;
4091 /* The desired access below is the only one I could find that works
4092 with NT4, W2KP and Samba */
4094 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4096 if (fnum == -1) {
4097 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4098 filename, cli_errstr(cli)));
4099 errno = 0;
4100 return -1;
4103 old = cli_query_secdesc(cli, fnum, ctx);
4105 if (!old) {
4106 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4107 errno = 0;
4108 return -1;
4111 cli_close(cli, fnum);
4113 switch (mode) {
4114 case SMBC_XATTR_MODE_REMOVE_ALL:
4115 old->dacl->num_aces = 0;
4116 SAFE_FREE(old->dacl->ace);
4117 SAFE_FREE(old->dacl);
4118 old->off_dacl = 0;
4119 dacl = old->dacl;
4120 break;
4122 case SMBC_XATTR_MODE_REMOVE:
4123 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4124 BOOL found = False;
4126 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4127 if (sec_ace_equal(&sd->dacl->ace[i],
4128 &old->dacl->ace[j])) {
4129 uint32 k;
4130 for (k=j; k<old->dacl->num_aces-1;k++) {
4131 old->dacl->ace[k] = old->dacl->ace[k+1];
4133 old->dacl->num_aces--;
4134 if (old->dacl->num_aces == 0) {
4135 SAFE_FREE(old->dacl->ace);
4136 SAFE_FREE(old->dacl);
4137 old->off_dacl = 0;
4139 found = True;
4140 dacl = old->dacl;
4141 break;
4145 if (!found) {
4146 err = ENOATTR;
4147 ret = -1;
4148 goto failed;
4151 break;
4153 case SMBC_XATTR_MODE_ADD:
4154 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4155 BOOL found = False;
4157 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4158 if (sid_equal(&sd->dacl->ace[i].trustee,
4159 &old->dacl->ace[j].trustee)) {
4160 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4161 err = EEXIST;
4162 ret = -1;
4163 goto failed;
4165 old->dacl->ace[j] = sd->dacl->ace[i];
4166 ret = -1;
4167 found = True;
4171 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4172 err = ENOATTR;
4173 ret = -1;
4174 goto failed;
4177 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4178 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4181 dacl = old->dacl;
4182 break;
4184 case SMBC_XATTR_MODE_SET:
4185 old = sd;
4186 owner_sid = old->owner_sid;
4187 grp_sid = old->grp_sid;
4188 dacl = old->dacl;
4189 break;
4191 case SMBC_XATTR_MODE_CHOWN:
4192 owner_sid = sd->owner_sid;
4193 break;
4195 case SMBC_XATTR_MODE_CHGRP:
4196 grp_sid = sd->grp_sid;
4197 break;
4200 /* Denied ACE entries must come before allowed ones */
4201 sort_acl(old->dacl);
4203 /* Create new security descriptor and set it */
4204 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4205 owner_sid, grp_sid, NULL, dacl, &sd_size);
4207 fnum = cli_nt_create(cli, filename,
4208 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4210 if (fnum == -1) {
4211 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4212 filename, cli_errstr(cli)));
4213 errno = 0;
4214 return -1;
4217 if (!cli_set_secdesc(cli, fnum, sd)) {
4218 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4219 ret = -1;
4222 /* Clean up */
4224 failed:
4225 cli_close(cli, fnum);
4227 if (err != 0) {
4228 errno = err;
4231 return ret;
4235 int smbc_setxattr_ctx(SMBCCTX *context,
4236 const char *fname,
4237 const char *name,
4238 const void *value,
4239 size_t size,
4240 int flags)
4242 int ret;
4243 int ret2;
4244 SMBCSRV *srv;
4245 SMBCSRV *ipc_srv;
4246 fstring server, share, user, password, workgroup;
4247 pstring path;
4248 TALLOC_CTX *ctx;
4249 POLICY_HND pol;
4250 DOS_ATTR_DESC *dad;
4252 if (!context || !context->internal ||
4253 !context->internal->_initialized) {
4255 errno = EINVAL; /* Best I can think of ... */
4256 return -1;
4260 if (!fname) {
4262 errno = EINVAL;
4263 return -1;
4267 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n", fname, name, (int) size, (const char*)value));
4269 if (smbc_parse_path(context, fname,
4270 server, sizeof(server),
4271 share, sizeof(share),
4272 path, sizeof(path),
4273 user, sizeof(user),
4274 password, sizeof(password),
4275 NULL, 0)) {
4276 errno = EINVAL;
4277 return -1;
4280 if (user[0] == (char)0) fstrcpy(user, context->user);
4282 fstrcpy(workgroup, context->workgroup);
4284 srv = smbc_server(context, server, share, workgroup, user, password);
4285 if (!srv) {
4286 return -1; /* errno set by smbc_server */
4289 if (! srv->no_nt_session) {
4290 ipc_srv = smbc_attr_server(context, server, share,
4291 workgroup, user, password,
4292 &pol);
4293 srv->no_nt_session = True;
4294 } else {
4295 ipc_srv = NULL;
4298 ctx = talloc_init("smbc_setxattr");
4299 if (!ctx) {
4300 errno = ENOMEM;
4301 return -1;
4305 * Are they asking to set the entire set of known attributes?
4307 if (StrCaseCmp(name, "system.*") == 0 ||
4308 StrCaseCmp(name, "system.*+") == 0) {
4309 /* Yup. */
4310 char *namevalue =
4311 talloc_asprintf(ctx, "%s:%s", name+7, (const char *) value);
4312 if (! namevalue) {
4313 errno = ENOMEM;
4314 ret = -1;
4315 return -1;
4318 if (ipc_srv) {
4319 ret = cacl_set(ctx, &srv->cli,
4320 &ipc_srv->cli, &pol, path,
4321 namevalue,
4322 (*namevalue == '*'
4323 ? SMBC_XATTR_MODE_SET
4324 : SMBC_XATTR_MODE_ADD),
4325 flags);
4326 } else {
4327 ret = 0;
4330 /* get a DOS Attribute Descriptor with current attributes */
4331 dad = dos_attr_query(context, ctx, path, srv);
4332 if (dad) {
4333 /* Overwrite old with new, using what was provided */
4334 dos_attr_parse(context, dad, srv, namevalue);
4336 /* Set the new DOS attributes */
4337 #if 0 /* not yet implemented */
4338 if (! cli_setpathinfo(&srv->cli, path,
4339 dad->c_time,
4340 dad->a_time,
4341 dad->m_time,
4342 dad->mode)) {
4343 if (!cli_setatr(&srv->cli, path,
4344 dad->mode, dad->m_time)) {
4345 errno = smbc_errno(context, &srv->cli);
4348 #else
4349 if (!cli_setatr(&srv->cli, path,
4350 dad->mode, dad->m_time)) {
4351 errno = smbc_errno(context, &srv->cli);
4353 #endif
4356 /* we only fail if both NT and DOS sets failed */
4357 if (ret < 0 && ! dad) {
4358 ret = -1; /* in case dad was null */
4360 else {
4361 ret = 0;
4364 talloc_destroy(ctx);
4365 return ret;
4369 * Are they asking to set an access control element or to set
4370 * the entire access control list?
4372 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4373 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4374 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4375 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4376 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4378 /* Yup. */
4379 char *namevalue =
4380 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4382 if (! ipc_srv) {
4383 ret = -1; /* errno set by smbc_server() */
4385 else if (! namevalue) {
4386 errno = ENOMEM;
4387 ret = -1;
4388 } else {
4389 ret = cacl_set(ctx, &srv->cli,
4390 &ipc_srv->cli, &pol, path,
4391 namevalue,
4392 (*namevalue == '*'
4393 ? SMBC_XATTR_MODE_SET
4394 : SMBC_XATTR_MODE_ADD),
4395 flags);
4397 talloc_destroy(ctx);
4398 return ret;
4402 * Are they asking to set the owner?
4404 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4405 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
4407 /* Yup. */
4408 char *namevalue =
4409 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4411 if (! ipc_srv) {
4413 ret = -1; /* errno set by smbc_server() */
4415 else if (! namevalue) {
4416 errno = ENOMEM;
4417 ret = -1;
4418 } else {
4419 ret = cacl_set(ctx, &srv->cli,
4420 &ipc_srv->cli, &pol, path,
4421 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4423 talloc_destroy(ctx);
4424 return ret;
4428 * Are they asking to set the group?
4430 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4431 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
4433 /* Yup. */
4434 char *namevalue =
4435 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4437 if (! ipc_srv) {
4438 /* errno set by smbc_server() */
4439 ret = -1;
4441 else if (! namevalue) {
4442 errno = ENOMEM;
4443 ret = -1;
4444 } else {
4445 ret = cacl_set(ctx, &srv->cli,
4446 &ipc_srv->cli, &pol, path,
4447 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4449 talloc_destroy(ctx);
4450 return ret;
4454 * Are they asking to set a DOS attribute?
4456 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4457 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4458 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4459 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4460 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
4462 /* get a DOS Attribute Descriptor with current attributes */
4463 dad = dos_attr_query(context, ctx, path, srv);
4464 if (dad) {
4465 char *namevalue =
4466 talloc_asprintf(ctx, "%s:%s", name+16, (const char *) value);
4467 if (! namevalue) {
4468 errno = ENOMEM;
4469 ret = -1;
4470 } else {
4471 /* Overwrite old with provided new params */
4472 dos_attr_parse(context, dad, srv, namevalue);
4474 /* Set the new DOS attributes */
4475 #if 0 /* not yet implemented */
4476 ret2 = cli_setpathinfo(&srv->cli, path,
4477 dad->c_time,
4478 dad->a_time,
4479 dad->m_time,
4480 dad->mode);
4481 if (! ret2) {
4482 ret2 = cli_setatr(&srv->cli, path,
4483 dad->mode,
4484 dad->m_time);
4485 if (! ret2) {
4486 errno = smbc_errno(context,
4487 &srv->cli);
4490 #else
4491 ret2 = cli_setatr(&srv->cli, path,
4492 dad->mode, dad->m_time);
4493 if (! ret2) {
4494 errno = smbc_errno(context, &srv->cli);
4496 #endif
4498 /* ret2 has True (success) / False (failure) */
4499 if (ret2) {
4500 ret = 0;
4501 } else {
4502 ret = -1;
4505 } else {
4506 ret = -1;
4509 talloc_destroy(ctx);
4510 return ret;
4513 /* Unsupported attribute name */
4514 talloc_destroy(ctx);
4515 errno = EINVAL;
4516 return -1;
4519 int smbc_getxattr_ctx(SMBCCTX *context,
4520 const char *fname,
4521 const char *name,
4522 const void *value,
4523 size_t size)
4525 int ret;
4526 SMBCSRV *srv;
4527 SMBCSRV *ipc_srv;
4528 fstring server, share, user, password, workgroup;
4529 pstring path;
4530 TALLOC_CTX *ctx;
4531 POLICY_HND pol;
4534 if (!context || !context->internal ||
4535 !context->internal->_initialized) {
4537 errno = EINVAL; /* Best I can think of ... */
4538 return -1;
4542 if (!fname) {
4544 errno = EINVAL;
4545 return -1;
4549 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
4551 if (smbc_parse_path(context, fname,
4552 server, sizeof(server),
4553 share, sizeof(share),
4554 path, sizeof(path),
4555 user, sizeof(user),
4556 password, sizeof(password),
4557 NULL, 0)) {
4558 errno = EINVAL;
4559 return -1;
4562 if (user[0] == (char)0) fstrcpy(user, context->user);
4564 fstrcpy(workgroup, context->workgroup);
4566 srv = smbc_server(context, server, share, workgroup, user, password);
4567 if (!srv) {
4568 return -1; /* errno set by smbc_server */
4571 if (! srv->no_nt_session) {
4572 ipc_srv = smbc_attr_server(context, server, share,
4573 workgroup, user, password,
4574 &pol);
4575 if (! ipc_srv) {
4576 srv->no_nt_session = True;
4578 } else {
4579 ipc_srv = NULL;
4582 ctx = talloc_init("smbc:getxattr");
4583 if (!ctx) {
4584 errno = ENOMEM;
4585 return -1;
4588 /* Are they requesting a supported attribute? */
4589 if (StrCaseCmp(name, "system.*") == 0 ||
4590 StrnCaseCmp(name, "system.*!", 9) == 0 ||
4591 StrCaseCmp(name, "system.*+") == 0 ||
4592 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
4593 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4594 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
4595 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4596 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
4597 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4598 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4599 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
4600 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4601 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
4602 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4603 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
4604 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4605 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
4606 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4607 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
4608 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4609 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4610 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
4611 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
4613 /* Yup. */
4614 ret = cacl_get(context, ctx, srv,
4615 ipc_srv == NULL ? NULL : &ipc_srv->cli,
4616 &pol, path,
4617 CONST_DISCARD(char *, name),
4618 CONST_DISCARD(char *, value), size);
4619 if (ret < 0 && errno == 0) {
4620 errno = smbc_errno(context, &srv->cli);
4622 talloc_destroy(ctx);
4623 return ret;
4626 /* Unsupported attribute name */
4627 talloc_destroy(ctx);
4628 errno = EINVAL;
4629 return -1;
4633 int smbc_removexattr_ctx(SMBCCTX *context,
4634 const char *fname,
4635 const char *name)
4637 int ret;
4638 SMBCSRV *srv;
4639 SMBCSRV *ipc_srv;
4640 fstring server, share, user, password, workgroup;
4641 pstring path;
4642 TALLOC_CTX *ctx;
4643 POLICY_HND pol;
4645 if (!context || !context->internal ||
4646 !context->internal->_initialized) {
4648 errno = EINVAL; /* Best I can think of ... */
4649 return -1;
4653 if (!fname) {
4655 errno = EINVAL;
4656 return -1;
4660 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
4662 if (smbc_parse_path(context, fname,
4663 server, sizeof(server),
4664 share, sizeof(share),
4665 path, sizeof(path),
4666 user, sizeof(user),
4667 password, sizeof(password),
4668 NULL, 0)) {
4669 errno = EINVAL;
4670 return -1;
4673 if (user[0] == (char)0) fstrcpy(user, context->user);
4675 fstrcpy(workgroup, context->workgroup);
4677 srv = smbc_server(context, server, share, workgroup, user, password);
4678 if (!srv) {
4679 return -1; /* errno set by smbc_server */
4682 if (! srv->no_nt_session) {
4683 ipc_srv = smbc_attr_server(context, server, share,
4684 workgroup, user, password,
4685 &pol);
4686 srv->no_nt_session = True;
4687 } else {
4688 ipc_srv = NULL;
4691 if (! ipc_srv) {
4692 return -1; /* errno set by smbc_attr_server */
4695 ctx = talloc_init("smbc_removexattr");
4696 if (!ctx) {
4697 errno = ENOMEM;
4698 return -1;
4701 /* Are they asking to set the entire ACL? */
4702 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4703 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
4705 /* Yup. */
4706 ret = cacl_set(ctx, &srv->cli,
4707 &ipc_srv->cli, &pol, path,
4708 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
4709 talloc_destroy(ctx);
4710 return ret;
4714 * Are they asking to remove one or more spceific security descriptor
4715 * attributes?
4717 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4718 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4719 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
4720 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4721 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
4722 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4723 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4725 /* Yup. */
4726 ret = cacl_set(ctx, &srv->cli,
4727 &ipc_srv->cli, &pol, path,
4728 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
4729 talloc_destroy(ctx);
4730 return ret;
4733 /* Unsupported attribute name */
4734 talloc_destroy(ctx);
4735 errno = EINVAL;
4736 return -1;
4739 int smbc_listxattr_ctx(SMBCCTX *context,
4740 const char *fname,
4741 char *list,
4742 size_t size)
4745 * This isn't quite what listxattr() is supposed to do. This returns
4746 * the complete set of attribute names, always, rather than only those
4747 * attribute names which actually exist for a file. Hmmm...
4749 const char supported[] =
4750 "system.*\0"
4751 "system.*+\0"
4752 "system.nt_sec_desc.revision\0"
4753 "system.nt_sec_desc.owner\0"
4754 "system.nt_sec_desc.owner+\0"
4755 "system.nt_sec_desc.group\0"
4756 "system.nt_sec_desc.group+\0"
4757 "system.nt_sec_desc.acl.*\0"
4758 "system.nt_sec_desc.acl\0"
4759 "system.nt_sec_desc.acl+\0"
4760 "system.nt_sec_desc.*\0"
4761 "system.nt_sec_desc.*+\0"
4762 "system.dos_attr.*\0"
4763 "system.dos_attr.mode\0"
4764 "system.dos_attr.c_time\0"
4765 "system.dos_attr.a_time\0"
4766 "system.dos_attr.m_time\0"
4769 if (size == 0) {
4770 return sizeof(supported);
4773 if (sizeof(supported) > size) {
4774 errno = ERANGE;
4775 return -1;
4778 /* this can't be strcpy() because there are embedded null characters */
4779 memcpy(list, supported, sizeof(supported));
4780 return sizeof(supported);
4785 * Open a print file to be written to by other calls
4788 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
4790 fstring server, share, user, password;
4791 pstring path;
4793 if (!context || !context->internal ||
4794 !context->internal->_initialized) {
4796 errno = EINVAL;
4797 return NULL;
4801 if (!fname) {
4803 errno = EINVAL;
4804 return NULL;
4808 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
4810 if (smbc_parse_path(context, fname,
4811 server, sizeof(server),
4812 share, sizeof(share),
4813 path, sizeof(path),
4814 user, sizeof(user),
4815 password, sizeof(password),
4816 NULL, 0)) {
4817 errno = EINVAL;
4818 return NULL;
4821 /* What if the path is empty, or the file exists? */
4823 return context->open(context, fname, O_WRONLY, 666);
4828 * Routine to print a file on a remote server ...
4830 * We open the file, which we assume to be on a remote server, and then
4831 * copy it to a print file on the share specified by printq.
4834 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
4836 SMBCFILE *fid1, *fid2;
4837 int bytes, saverr, tot_bytes = 0;
4838 char buf[4096];
4840 if (!c_file || !c_file->internal->_initialized || !c_print ||
4841 !c_print->internal->_initialized) {
4843 errno = EINVAL;
4844 return -1;
4848 if (!fname && !printq) {
4850 errno = EINVAL;
4851 return -1;
4855 /* Try to open the file for reading ... */
4857 if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
4859 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
4860 return -1; /* smbc_open sets errno */
4864 /* Now, try to open the printer file for writing */
4866 if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
4868 saverr = errno; /* Save errno */
4869 c_file->close(c_file, fid1);
4870 errno = saverr;
4871 return -1;
4875 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
4877 tot_bytes += bytes;
4879 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
4881 saverr = errno;
4882 c_file->close(c_file, fid1);
4883 c_print->close(c_print, fid2);
4884 errno = saverr;
4890 saverr = errno;
4892 c_file->close(c_file, fid1); /* We have to close these anyway */
4893 c_print->close(c_print, fid2);
4895 if (bytes < 0) {
4897 errno = saverr;
4898 return -1;
4902 return tot_bytes;
4907 * Routine to list print jobs on a printer share ...
4910 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
4912 SMBCSRV *srv;
4913 fstring server, share, user, password, workgroup;
4914 pstring path;
4916 if (!context || !context->internal ||
4917 !context->internal->_initialized) {
4919 errno = EINVAL;
4920 return -1;
4924 if (!fname) {
4926 errno = EINVAL;
4927 return -1;
4931 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
4933 if (smbc_parse_path(context, fname,
4934 server, sizeof(server),
4935 share, sizeof(share),
4936 path, sizeof(path),
4937 user, sizeof(user),
4938 password, sizeof(password),
4939 NULL, 0)) {
4940 errno = EINVAL;
4941 return -1;
4944 if (user[0] == (char)0) fstrcpy(user, context->user);
4946 fstrcpy(workgroup, context->workgroup);
4948 srv = smbc_server(context, server, share, workgroup, user, password);
4950 if (!srv) {
4952 return -1; /* errno set by smbc_server */
4956 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
4958 errno = smbc_errno(context, &srv->cli);
4959 return -1;
4963 return 0;
4968 * Delete a print job from a remote printer share
4971 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
4973 SMBCSRV *srv;
4974 fstring server, share, user, password, workgroup;
4975 pstring path;
4976 int err;
4978 if (!context || !context->internal ||
4979 !context->internal->_initialized) {
4981 errno = EINVAL;
4982 return -1;
4986 if (!fname) {
4988 errno = EINVAL;
4989 return -1;
4993 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
4995 if (smbc_parse_path(context, fname,
4996 server, sizeof(server),
4997 share, sizeof(share),
4998 path, sizeof(path),
4999 user, sizeof(user),
5000 password, sizeof(password),
5001 NULL, 0)) {
5002 errno = EINVAL;
5003 return -1;
5006 if (user[0] == (char)0) fstrcpy(user, context->user);
5008 fstrcpy(workgroup, context->workgroup);
5010 srv = smbc_server(context, server, share, workgroup, user, password);
5012 if (!srv) {
5014 return -1; /* errno set by smbc_server */
5018 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5020 if (err < 0)
5021 errno = smbc_errno(context, &srv->cli);
5022 else if (err == ERRnosuchprintjob)
5023 errno = EINVAL;
5024 return -1;
5028 return 0;
5033 * Get a new empty handle to fill in with your own info
5035 SMBCCTX * smbc_new_context(void)
5037 SMBCCTX * context;
5039 context = SMB_MALLOC_P(SMBCCTX);
5040 if (!context) {
5041 errno = ENOMEM;
5042 return NULL;
5045 ZERO_STRUCTP(context);
5047 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5048 if (!context->internal) {
5049 errno = ENOMEM;
5050 return NULL;
5053 ZERO_STRUCTP(context->internal);
5056 /* ADD REASONABLE DEFAULTS */
5057 context->debug = 0;
5058 context->timeout = 20000; /* 20 seconds */
5060 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5061 context->options.urlencode_readdir_entries = False;/* backward compat */
5062 context->options.one_share_per_server = False;/* backward compat */
5064 context->open = smbc_open_ctx;
5065 context->creat = smbc_creat_ctx;
5066 context->read = smbc_read_ctx;
5067 context->write = smbc_write_ctx;
5068 context->close = smbc_close_ctx;
5069 context->unlink = smbc_unlink_ctx;
5070 context->rename = smbc_rename_ctx;
5071 context->lseek = smbc_lseek_ctx;
5072 context->stat = smbc_stat_ctx;
5073 context->fstat = smbc_fstat_ctx;
5074 context->opendir = smbc_opendir_ctx;
5075 context->closedir = smbc_closedir_ctx;
5076 context->readdir = smbc_readdir_ctx;
5077 context->getdents = smbc_getdents_ctx;
5078 context->mkdir = smbc_mkdir_ctx;
5079 context->rmdir = smbc_rmdir_ctx;
5080 context->telldir = smbc_telldir_ctx;
5081 context->lseekdir = smbc_lseekdir_ctx;
5082 context->fstatdir = smbc_fstatdir_ctx;
5083 context->chmod = smbc_chmod_ctx;
5084 context->utimes = smbc_utimes_ctx;
5085 context->setxattr = smbc_setxattr_ctx;
5086 context->getxattr = smbc_getxattr_ctx;
5087 context->removexattr = smbc_removexattr_ctx;
5088 context->listxattr = smbc_listxattr_ctx;
5089 context->open_print_job = smbc_open_print_job_ctx;
5090 context->print_file = smbc_print_file_ctx;
5091 context->list_print_jobs = smbc_list_print_jobs_ctx;
5092 context->unlink_print_job = smbc_unlink_print_job_ctx;
5094 context->callbacks.check_server_fn = smbc_check_server;
5095 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5097 smbc_default_cache_functions(context);
5099 return context;
5103 * Free a context
5105 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5106 * and thus you'll be leaking memory if not handled properly.
5109 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
5111 if (!context) {
5112 errno = EBADF;
5113 return 1;
5116 if (shutdown_ctx) {
5117 SMBCFILE * f;
5118 DEBUG(1,("Performing aggressive shutdown.\n"));
5120 f = context->internal->_files;
5121 while (f) {
5122 context->close(context, f);
5123 f = f->next;
5125 context->internal->_files = NULL;
5127 /* First try to remove the servers the nice way. */
5128 if (context->callbacks.purge_cached_fn(context)) {
5129 SMBCSRV * s;
5130 SMBCSRV * next;
5131 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
5132 s = context->internal->_servers;
5133 while (s) {
5134 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
5135 cli_shutdown(&s->cli);
5136 context->callbacks.remove_cached_srv_fn(context, s);
5137 next = s->next;
5138 DLIST_REMOVE(context->internal->_servers, s);
5139 SAFE_FREE(s);
5140 s = next;
5142 context->internal->_servers = NULL;
5145 else {
5146 /* This is the polite way */
5147 if (context->callbacks.purge_cached_fn(context)) {
5148 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
5149 errno = EBUSY;
5150 return 1;
5152 if (context->internal->_servers) {
5153 DEBUG(1, ("Active servers in context, free_context failed.\n"));
5154 errno = EBUSY;
5155 return 1;
5157 if (context->internal->_files) {
5158 DEBUG(1, ("Active files in context, free_context failed.\n"));
5159 errno = EBUSY;
5160 return 1;
5164 /* Things we have to clean up */
5165 SAFE_FREE(context->workgroup);
5166 SAFE_FREE(context->netbios_name);
5167 SAFE_FREE(context->user);
5169 DEBUG(3, ("Context %p succesfully freed\n", context));
5170 SAFE_FREE(context->internal);
5171 SAFE_FREE(context);
5172 return 0;
5177 * Initialise the library etc
5179 * We accept a struct containing handle information.
5180 * valid values for info->debug from 0 to 100,
5181 * and insist that info->fn must be non-null.
5183 SMBCCTX * smbc_init_context(SMBCCTX * context)
5185 pstring conf;
5186 int pid;
5187 char *user = NULL, *home = NULL;
5189 if (!context || !context->internal) {
5190 errno = EBADF;
5191 return NULL;
5194 /* Do not initialise the same client twice */
5195 if (context->internal->_initialized) {
5196 return 0;
5199 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
5201 errno = EINVAL;
5202 return NULL;
5206 if (!smbc_initialized) {
5207 /* Do some library wide intialisations the first time we get called */
5209 /* Set this to what the user wants */
5210 DEBUGLEVEL = context->debug;
5212 setup_logging( "libsmbclient", True);
5214 /* Here we would open the smb.conf file if needed ... */
5216 home = getenv("HOME");
5218 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5220 load_interfaces(); /* Load the list of interfaces ... */
5222 in_client = True; /* FIXME, make a param */
5224 if (!lp_load(conf, True, False, False)) {
5227 * Well, if that failed, try the dyn_CONFIGFILE
5228 * Which points to the standard locn, and if that
5229 * fails, silently ignore it and use the internal
5230 * defaults ...
5233 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
5234 DEBUG(5, ("Could not load either config file: "
5235 "%s or %s\n",
5236 conf, dyn_CONFIGFILE));
5237 } else {
5239 * We loaded the global config file. Now lets
5240 * load user-specific modifications to the
5241 * global config.
5243 slprintf(conf, sizeof(conf),
5244 "%s/.smb/smb.conf.append", home);
5245 if (!lp_load(conf, True, False, False)) {
5246 DEBUG(10,
5247 ("Could not append config file: "
5248 "%s\n",
5249 conf));
5254 reopen_logs(); /* Get logging working ... */
5257 * Block SIGPIPE (from lib/util_sock.c: write())
5258 * It is not needed and should not stop execution
5260 BlockSignals(True, SIGPIPE);
5262 /* Done with one-time initialisation */
5263 smbc_initialized = 1;
5267 if (!context->user) {
5269 * FIXME: Is this the best way to get the user info?
5271 user = getenv("USER");
5272 /* walk around as "guest" if no username can be found */
5273 if (!user) context->user = SMB_STRDUP("guest");
5274 else context->user = SMB_STRDUP(user);
5277 if (!context->netbios_name) {
5279 * We try to get our netbios name from the config. If that fails we fall
5280 * back on constructing our netbios name from our hostname etc
5282 if (global_myname()) {
5283 context->netbios_name = SMB_STRDUP(global_myname());
5285 else {
5287 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
5289 pid = sys_getpid();
5290 context->netbios_name = SMB_MALLOC(17);
5291 if (!context->netbios_name) {
5292 errno = ENOMEM;
5293 return NULL;
5295 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
5299 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
5301 if (!context->workgroup) {
5302 if (lp_workgroup()) {
5303 context->workgroup = SMB_STRDUP(lp_workgroup());
5305 else {
5306 /* TODO: Think about a decent default workgroup */
5307 context->workgroup = SMB_STRDUP("samba");
5311 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
5313 /* shortest timeout is 1 second */
5314 if (context->timeout > 0 && context->timeout < 1000)
5315 context->timeout = 1000;
5318 * FIXME: Should we check the function pointers here?
5321 context->internal->_initialized = 1;
5323 return context;
5327 /* Return the verion of samba, and thus libsmbclient */
5328 const char *
5329 smbc_version(void)
5331 return samba_version_string();