r7172: This is the proper fix for setting file times from libsmbclient. We now
[Samba.git] / source / libsmb / libsmbclient.c
blob404d9def69698f16b0e0d5f516624981ef534918
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 for being alive and well.
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 allocate a server structure.
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));
760 srv->no_pathinfo = False;
761 srv->no_pathinfo2 = False;
762 srv->no_nt_session = False;
764 /* now add it to the cache (internal or external) */
765 /* Let the cache function set errno if it wants to */
766 errno = 0;
767 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username_used)) {
768 int saved_errno = errno;
769 DEBUG(3, (" Failed to add server to cache\n"));
770 errno = saved_errno;
771 if (errno == 0) {
772 errno = ENOMEM;
774 goto failed;
777 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
778 server, share, srv));
780 DLIST_ADD(context->internal->_servers, srv);
781 return srv;
783 failed:
784 cli_shutdown(&c);
785 if (!srv) return NULL;
787 SAFE_FREE(srv);
788 return NULL;
792 * Connect to a server for getting/setting attributes, possibly on an existing
793 * connection. This works similarly to smbc_server().
795 SMBCSRV *smbc_attr_server(SMBCCTX *context,
796 const char *server, const char *share,
797 fstring workgroup,
798 fstring username, fstring password,
799 POLICY_HND *pol)
801 struct in_addr ip;
802 struct cli_state *ipc_cli;
803 NTSTATUS nt_status;
804 SMBCSRV *ipc_srv=NULL;
807 * See if we've already created this special connection. Reference our
808 * "special" share name '*IPC$', which is an impossible real share name
809 * due to the leading asterisk.
811 ipc_srv = find_server(context, server, "*IPC$",
812 workgroup, username, password);
813 if (!ipc_srv) {
815 /* We didn't find a cached connection. Get the password */
816 if (*password == '\0') {
817 /* ... then retrieve it now. */
818 context->callbacks.auth_fn(server, share,
819 workgroup, sizeof(fstring),
820 username, sizeof(fstring),
821 password, sizeof(fstring));
824 zero_ip(&ip);
825 nt_status = cli_full_connection(&ipc_cli,
826 global_myname(), server,
827 &ip, 0, "IPC$", "?????",
828 username, workgroup,
829 password, 0,
830 Undefined, NULL);
831 if (! NT_STATUS_IS_OK(nt_status)) {
832 DEBUG(1,("cli_full_connection failed! (%s)\n",
833 nt_errstr(nt_status)));
834 errno = ENOTSUP;
835 return NULL;
838 if (!cli_nt_session_open(ipc_cli, PI_LSARPC)) {
839 DEBUG(1, ("cli_nt_session_open fail!\n"));
840 errno = ENOTSUP;
841 cli_shutdown(ipc_cli);
842 return NULL;
845 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
846 but NT sends 0x2000000 so we might as well do it too. */
848 nt_status = cli_lsa_open_policy(ipc_cli,
849 ipc_cli->mem_ctx,
850 True,
851 GENERIC_EXECUTE_ACCESS,
852 pol);
854 if (!NT_STATUS_IS_OK(nt_status)) {
855 errno = smbc_errno(context, ipc_cli);
856 cli_shutdown(ipc_cli);
857 return NULL;
860 ipc_srv = SMB_MALLOC_P(SMBCSRV);
861 if (!ipc_srv) {
862 errno = ENOMEM;
863 cli_shutdown(ipc_cli);
864 return NULL;
867 ZERO_STRUCTP(ipc_srv);
868 ipc_srv->cli = *ipc_cli;
870 free(ipc_cli);
872 /* now add it to the cache (internal or external) */
874 errno = 0; /* let cache function set errno if it likes */
875 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
876 server,
877 "*IPC$",
878 workgroup,
879 username)) {
880 DEBUG(3, (" Failed to add server to cache\n"));
881 if (errno == 0) {
882 errno = ENOMEM;
884 cli_shutdown(&ipc_srv->cli);
885 free(ipc_srv);
886 return NULL;
889 DLIST_ADD(context->internal->_servers, ipc_srv);
892 return ipc_srv;
896 * Routine to open() a file ...
899 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
901 fstring server, share, user, password, workgroup;
902 pstring path;
903 SMBCSRV *srv = NULL;
904 SMBCFILE *file = NULL;
905 int fd;
907 if (!context || !context->internal ||
908 !context->internal->_initialized) {
910 errno = EINVAL; /* Best I can think of ... */
911 return NULL;
915 if (!fname) {
917 errno = EINVAL;
918 return NULL;
922 if (smbc_parse_path(context, fname,
923 server, sizeof(server),
924 share, sizeof(share),
925 path, sizeof(path),
926 user, sizeof(user),
927 password, sizeof(password),
928 NULL, 0)) {
929 errno = EINVAL;
930 return NULL;
933 if (user[0] == (char)0) fstrcpy(user, context->user);
935 fstrcpy(workgroup, context->workgroup);
937 srv = smbc_server(context, server, share, workgroup, user, password);
939 if (!srv) {
941 if (errno == EPERM) errno = EACCES;
942 return NULL; /* smbc_server sets errno */
946 /* Hmmm, the test for a directory is suspect here ... FIXME */
948 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
950 fd = -1;
953 else {
955 file = SMB_MALLOC_P(SMBCFILE);
957 if (!file) {
959 errno = ENOMEM;
960 return NULL;
964 ZERO_STRUCTP(file);
966 if ((fd = cli_open(&srv->cli, path, flags, DENY_NONE)) < 0) {
968 /* Handle the error ... */
970 SAFE_FREE(file);
971 errno = smbc_errno(context, &srv->cli);
972 return NULL;
976 /* Fill in file struct */
978 file->cli_fd = fd;
979 file->fname = SMB_STRDUP(fname);
980 file->srv = srv;
981 file->offset = 0;
982 file->file = True;
984 DLIST_ADD(context->internal->_files, file);
987 * If the file was opened in O_APPEND mode, all write
988 * operations should be appended to the file. To do that,
989 * though, using this protocol, would require a getattrE()
990 * call for each and every write, to determine where the end
991 * of the file is. (There does not appear to be an append flag
992 * in the protocol.) Rather than add all of that overhead of
993 * retrieving the current end-of-file offset prior to each
994 * write operation, we'll assume that most append operations
995 * will continuously write, so we'll just set the offset to
996 * the end of the file now and hope that's adequate.
998 * Note to self: If this proves inadequate, and O_APPEND
999 * should, in some cases, be forced for each write, add a
1000 * field in the context options structure, for
1001 * "strict_append_mode" which would select between the current
1002 * behavior (if FALSE) or issuing a getattrE() prior to each
1003 * write and forcing the write to the end of the file (if
1004 * TRUE). Adding that capability will likely require adding
1005 * an "append" flag into the _SMBCFILE structure to track
1006 * whether a file was opened in O_APPEND mode. -- djl
1008 if (flags & O_APPEND) {
1009 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1010 (void) smbc_close_ctx(context, file);
1011 errno = ENXIO;
1012 return NULL;
1016 return file;
1020 /* Check if opendir needed ... */
1022 if (fd == -1) {
1023 int eno = 0;
1025 eno = smbc_errno(context, &srv->cli);
1026 file = context->opendir(context, fname);
1027 if (!file) errno = eno;
1028 return file;
1032 errno = EINVAL; /* FIXME, correct errno ? */
1033 return NULL;
1038 * Routine to create a file
1041 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1043 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
1046 if (!context || !context->internal ||
1047 !context->internal->_initialized) {
1049 errno = EINVAL;
1050 return NULL;
1054 return smbc_open_ctx(context, path, creat_bits, mode);
1058 * Routine to read() a file ...
1061 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1063 int ret;
1066 * offset:
1068 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1069 * appears to pass file->offset (which is type off_t) differently than
1070 * a local variable of type off_t. Using local variable "offset" in
1071 * the call to cli_read() instead of file->offset fixes a problem
1072 * retrieving data at an offset greater than 4GB.
1074 off_t offset = file->offset;
1076 if (!context || !context->internal ||
1077 !context->internal->_initialized) {
1079 errno = EINVAL;
1080 return -1;
1084 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1086 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1088 errno = EBADF;
1089 return -1;
1093 /* Check that the buffer exists ... */
1095 if (buf == NULL) {
1097 errno = EINVAL;
1098 return -1;
1102 ret = cli_read(&file->srv->cli, file->cli_fd, buf, offset, count);
1104 if (ret < 0) {
1106 errno = smbc_errno(context, &file->srv->cli);
1107 return -1;
1111 file->offset += ret;
1113 DEBUG(4, (" --> %d\n", ret));
1115 return ret; /* Success, ret bytes of data ... */
1120 * Routine to write() a file ...
1123 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1125 int ret;
1126 off_t offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1128 if (!context || !context->internal ||
1129 !context->internal->_initialized) {
1131 errno = EINVAL;
1132 return -1;
1136 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1138 errno = EBADF;
1139 return -1;
1143 /* Check that the buffer exists ... */
1145 if (buf == NULL) {
1147 errno = EINVAL;
1148 return -1;
1152 ret = cli_write(&file->srv->cli, file->cli_fd, 0, buf, offset, count);
1154 if (ret <= 0) {
1156 errno = smbc_errno(context, &file->srv->cli);
1157 return -1;
1161 file->offset += ret;
1163 return ret; /* Success, 0 bytes of data ... */
1167 * Routine to close() a file ...
1170 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1172 SMBCSRV *srv;
1174 if (!context || !context->internal ||
1175 !context->internal->_initialized) {
1177 errno = EINVAL;
1178 return -1;
1182 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1184 errno = EBADF;
1185 return -1;
1189 /* IS a dir ... */
1190 if (!file->file) {
1192 return context->closedir(context, file);
1196 if (!cli_close(&file->srv->cli, file->cli_fd)) {
1198 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1199 file->fname));
1200 /* Deallocate slot and remove the server
1201 * from the server cache if unused */
1202 errno = smbc_errno(context, &file->srv->cli);
1203 srv = file->srv;
1204 DLIST_REMOVE(context->internal->_files, file);
1205 SAFE_FREE(file->fname);
1206 SAFE_FREE(file);
1207 context->callbacks.remove_unused_server_fn(context, srv);
1209 return -1;
1213 DLIST_REMOVE(context->internal->_files, file);
1214 SAFE_FREE(file->fname);
1215 SAFE_FREE(file);
1217 return 0;
1221 * Get info from an SMB server on a file. Use a qpathinfo call first
1222 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1224 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1225 uint16 *mode, SMB_OFF_T *size,
1226 time_t *c_time, time_t *a_time, time_t *m_time,
1227 SMB_INO_T *ino)
1230 if (!context || !context->internal ||
1231 !context->internal->_initialized) {
1233 errno = EINVAL;
1234 return -1;
1238 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1240 if (!srv->no_pathinfo2 &&
1241 cli_qpathinfo2(&srv->cli, path, c_time, a_time, m_time, NULL,
1242 size, mode, ino)) return True;
1244 /* if this is NT then don't bother with the getatr */
1245 if (srv->cli.capabilities & CAP_NT_SMBS) {
1246 errno = EPERM;
1247 return False;
1250 if (cli_getatr(&srv->cli, path, mode, size, m_time)) {
1251 if (m_time != NULL) {
1252 if (a_time != NULL) *a_time = *m_time;
1253 if (c_time != NULL) *c_time = *m_time;
1255 srv->no_pathinfo2 = True;
1256 return True;
1259 errno = EPERM;
1260 return False;
1265 * Set file info on an SMB server. Use setpathinfo call first. If that
1266 * fails, use setattrE..
1268 * Time parameters are always used and must be provided.
1269 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1271 static BOOL smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1272 time_t c_time, time_t a_time, time_t m_time,
1273 uint16 mode)
1275 int fd;
1276 int ret;
1279 * Get the create time of the file (if not provided); we'll need it in
1280 * the set call.
1282 if (! srv->no_pathinfo && c_time != 0) {
1283 if (! cli_qpathinfo(&srv->cli, path,
1284 &c_time, NULL, NULL, NULL, NULL)) {
1285 /* qpathinfo not available */
1286 srv->no_pathinfo = True;
1287 } else {
1289 * We got a creation time. For sanity sake, since
1290 * there is no POSIX function to set the create time
1291 * of a file, if the existing create time is greater
1292 * than either of access time or modification time,
1293 * set create time to the smallest of those. This
1294 * ensure that the create time of a file is never
1295 * greater than its last access or modification time.
1297 if (c_time > a_time) c_time = a_time;
1298 if (c_time > m_time) c_time = m_time;
1303 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1304 * modern function for "new code" to be using, and it works given a
1305 * filename rather than requiring that the file be opened to have its
1306 * attributes manipulated.
1308 if (srv->no_pathinfo ||
1309 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1312 * setpathinfo is not supported; go to plan B.
1314 * cli_setatr() does not work on win98, and it also doesn't
1315 * support setting the access time (only the modification
1316 * time), so in all cases, we open the specified file and use
1317 * cli_setattrE() which should work on all OS versions, and
1318 * supports both times.
1321 /* Don't try {q,set}pathinfo() again, with this server */
1322 srv->no_pathinfo = True;
1324 /* Open the file */
1325 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1327 errno = smbc_errno(context, &srv->cli);
1328 return -1;
1332 * Get the creat time of the file (if it wasn't provided).
1333 * We'll need it in the set call
1335 if (c_time == 0) {
1336 ret = cli_getattrE(&srv->cli, fd,
1337 NULL, NULL,
1338 &c_time, NULL, NULL);
1339 } else {
1340 ret = True;
1343 /* If we got create time, set times */
1344 if (ret) {
1345 /* Some OS versions don't support create time */
1346 if (c_time == 0) {
1347 c_time = time(NULL);
1351 * For sanity sake, since there is no POSIX function
1352 * to set the create time of a file, if the existing
1353 * create time is greater than either of access time
1354 * or modification time, set create time to the
1355 * smallest of those. This ensure that the create
1356 * time of a file is never greater than its last
1357 * access or modification time.
1359 if (c_time > a_time) c_time = a_time;
1360 if (c_time > m_time) c_time = m_time;
1362 /* Set the new attributes */
1363 ret = cli_setattrE(&srv->cli, fd,
1364 c_time, a_time, m_time);
1365 cli_close(&srv->cli, fd);
1369 * Unfortunately, setattrE() doesn't have a provision for
1370 * setting the access mode (attributes). We'll have to try
1371 * cli_setatr() for that, and with only this parameter, it
1372 * seems to work on win98.
1374 if (ret && mode != (uint16) -1) {
1375 ret = cli_setatr(&srv->cli, path, mode, 0);
1378 if (! ret) {
1379 errno = smbc_errno(context, &srv->cli);
1380 return False;
1384 return True;
1388 * Routine to unlink() a file
1391 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1393 fstring server, share, user, password, workgroup;
1394 pstring path;
1395 SMBCSRV *srv = NULL;
1397 if (!context || !context->internal ||
1398 !context->internal->_initialized) {
1400 errno = EINVAL; /* Best I can think of ... */
1401 return -1;
1405 if (!fname) {
1407 errno = EINVAL;
1408 return -1;
1412 if (smbc_parse_path(context, fname,
1413 server, sizeof(server),
1414 share, sizeof(share),
1415 path, sizeof(path),
1416 user, sizeof(user),
1417 password, sizeof(password),
1418 NULL, 0)) {
1419 errno = EINVAL;
1420 return -1;
1423 if (user[0] == (char)0) fstrcpy(user, context->user);
1425 fstrcpy(workgroup, context->workgroup);
1427 srv = smbc_server(context, server, share, workgroup, user, password);
1429 if (!srv) {
1431 return -1; /* smbc_server sets errno */
1435 if (!cli_unlink(&srv->cli, path)) {
1437 errno = smbc_errno(context, &srv->cli);
1439 if (errno == EACCES) { /* Check if the file is a directory */
1441 int saverr = errno;
1442 SMB_OFF_T size = 0;
1443 uint16 mode = 0;
1444 time_t m_time = 0, a_time = 0, c_time = 0;
1445 SMB_INO_T ino = 0;
1447 if (!smbc_getatr(context, srv, path, &mode, &size,
1448 &c_time, &a_time, &m_time, &ino)) {
1450 /* Hmmm, bad error ... What? */
1452 errno = smbc_errno(context, &srv->cli);
1453 return -1;
1456 else {
1458 if (IS_DOS_DIR(mode))
1459 errno = EISDIR;
1460 else
1461 errno = saverr; /* Restore this */
1466 return -1;
1470 return 0; /* Success ... */
1475 * Routine to rename() a file
1478 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1479 SMBCCTX *ncontext, const char *nname)
1481 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1482 pstring path1, path2;
1483 SMBCSRV *srv = NULL;
1485 if (!ocontext || !ncontext ||
1486 !ocontext->internal || !ncontext->internal ||
1487 !ocontext->internal->_initialized ||
1488 !ncontext->internal->_initialized) {
1490 errno = EINVAL; /* Best I can think of ... */
1491 return -1;
1495 if (!oname || !nname) {
1497 errno = EINVAL;
1498 return -1;
1502 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1504 smbc_parse_path(ocontext, oname,
1505 server1, sizeof(server1),
1506 share1, sizeof(share1),
1507 path1, sizeof(path1),
1508 user1, sizeof(user1),
1509 password1, sizeof(password1),
1510 NULL, 0);
1512 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1514 smbc_parse_path(ncontext, nname,
1515 server2, sizeof(server2),
1516 share2, sizeof(share2),
1517 path2, sizeof(path2),
1518 user2, sizeof(user2),
1519 password2, sizeof(password2),
1520 NULL, 0);
1522 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1524 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1525 strcmp(user1, user2)) {
1527 /* Can't rename across file systems, or users?? */
1529 errno = EXDEV;
1530 return -1;
1534 fstrcpy(workgroup, ocontext->workgroup);
1535 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1536 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1537 if (!srv) {
1539 return -1;
1543 if (!cli_rename(&srv->cli, path1, path2)) {
1544 int eno = smbc_errno(ocontext, &srv->cli);
1546 if (eno != EEXIST ||
1547 !cli_unlink(&srv->cli, path2) ||
1548 !cli_rename(&srv->cli, path1, path2)) {
1550 errno = eno;
1551 return -1;
1556 return 0; /* Success */
1561 * A routine to lseek() a file
1564 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1566 SMB_OFF_T size;
1568 if (!context || !context->internal ||
1569 !context->internal->_initialized) {
1571 errno = EINVAL;
1572 return -1;
1576 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1578 errno = EBADF;
1579 return -1;
1583 if (!file->file) {
1585 errno = EINVAL;
1586 return -1; /* Can't lseek a dir ... */
1590 switch (whence) {
1591 case SEEK_SET:
1592 file->offset = offset;
1593 break;
1595 case SEEK_CUR:
1596 file->offset += offset;
1597 break;
1599 case SEEK_END:
1600 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
1601 NULL, NULL, NULL))
1603 SMB_BIG_UINT b_size = size;
1604 if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
1605 NULL))
1607 errno = EINVAL;
1608 return -1;
1609 } else
1610 size = b_size;
1612 file->offset = size + offset;
1613 break;
1615 default:
1616 errno = EINVAL;
1617 break;
1621 return file->offset;
1626 * Generate an inode number from file name for those things that need it
1629 static
1630 ino_t smbc_inode(SMBCCTX *context, const char *name)
1633 if (!context || !context->internal ||
1634 !context->internal->_initialized) {
1636 errno = EINVAL;
1637 return -1;
1641 if (!*name) return 2; /* FIXME, why 2 ??? */
1642 return (ino_t)str_checksum(name);
1647 * Routine to put basic stat info into a stat structure ... Used by stat and
1648 * fstat below.
1651 static
1652 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname,
1653 SMB_OFF_T size, int mode)
1656 st->st_mode = 0;
1658 if (IS_DOS_DIR(mode)) {
1659 st->st_mode = SMBC_DIR_MODE;
1660 } else {
1661 st->st_mode = SMBC_FILE_MODE;
1664 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1665 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1666 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1667 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1669 st->st_size = size;
1670 #ifdef HAVE_STAT_ST_BLKSIZE
1671 st->st_blksize = 512;
1672 #endif
1673 #ifdef HAVE_STAT_ST_BLOCKS
1674 st->st_blocks = (size+511)/512;
1675 #endif
1676 st->st_uid = getuid();
1677 st->st_gid = getgid();
1679 if (IS_DOS_DIR(mode)) {
1680 st->st_nlink = 2;
1681 } else {
1682 st->st_nlink = 1;
1685 if (st->st_ino == 0) {
1686 st->st_ino = smbc_inode(context, fname);
1689 return True; /* FIXME: Is this needed ? */
1694 * Routine to stat a file given a name
1697 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1699 SMBCSRV *srv;
1700 fstring server, share, user, password, workgroup;
1701 pstring path;
1702 time_t m_time = 0, a_time = 0, c_time = 0;
1703 SMB_OFF_T size = 0;
1704 uint16 mode = 0;
1705 SMB_INO_T ino = 0;
1707 if (!context || !context->internal ||
1708 !context->internal->_initialized) {
1710 errno = EINVAL; /* Best I can think of ... */
1711 return -1;
1715 if (!fname) {
1717 errno = EINVAL;
1718 return -1;
1722 DEBUG(4, ("smbc_stat(%s)\n", fname));
1724 if (smbc_parse_path(context, fname,
1725 server, sizeof(server),
1726 share, sizeof(share),
1727 path, sizeof(path),
1728 user, sizeof(user),
1729 password, sizeof(password),
1730 NULL, 0)) {
1731 errno = EINVAL;
1732 return -1;
1735 if (user[0] == (char)0) fstrcpy(user, context->user);
1737 fstrcpy(workgroup, context->workgroup);
1739 srv = smbc_server(context, server, share, workgroup, user, password);
1741 if (!srv) {
1742 return -1; /* errno set by smbc_server */
1745 if (!smbc_getatr(context, srv, path, &mode, &size,
1746 &c_time, &a_time, &m_time, &ino)) {
1748 errno = smbc_errno(context, &srv->cli);
1749 return -1;
1753 st->st_ino = ino;
1755 smbc_setup_stat(context, st, path, size, mode);
1757 st->st_atime = a_time;
1758 st->st_ctime = c_time;
1759 st->st_mtime = m_time;
1760 st->st_dev = srv->dev;
1762 return 0;
1767 * Routine to stat a file given an fd
1770 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1772 time_t c_time, a_time, m_time;
1773 SMB_OFF_T size;
1774 uint16 mode;
1775 SMB_INO_T ino = 0;
1777 if (!context || !context->internal ||
1778 !context->internal->_initialized) {
1780 errno = EINVAL;
1781 return -1;
1785 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1787 errno = EBADF;
1788 return -1;
1792 if (!file->file) {
1794 return context->fstatdir(context, file, st);
1798 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
1799 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
1800 if (!cli_getattrE(&file->srv->cli, file->cli_fd,
1801 &mode, &size, &c_time, &a_time, &m_time)) {
1803 errno = EINVAL;
1804 return -1;
1808 st->st_ino = ino;
1810 smbc_setup_stat(context, st, file->fname, size, mode);
1812 st->st_atime = a_time;
1813 st->st_ctime = c_time;
1814 st->st_mtime = m_time;
1815 st->st_dev = file->srv->dev;
1817 return 0;
1822 * Routine to open a directory
1823 * We accept the URL syntax explained in smbc_parse_path(), above.
1826 static void smbc_remove_dir(SMBCFILE *dir)
1828 struct smbc_dir_list *d,*f;
1830 d = dir->dir_list;
1831 while (d) {
1833 f = d; d = d->next;
1835 SAFE_FREE(f->dirent);
1836 SAFE_FREE(f);
1840 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
1844 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
1846 struct smbc_dirent *dirent;
1847 int size;
1848 int name_length = (name == NULL ? 0 : strlen(name));
1849 int comment_len = (comment == NULL ? 0 : strlen(comment));
1852 * Allocate space for the dirent, which must be increased by the
1853 * size of the name and the comment and 1 each for the null terminator.
1856 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
1858 dirent = SMB_MALLOC(size);
1860 if (!dirent) {
1862 dir->dir_error = ENOMEM;
1863 return -1;
1867 ZERO_STRUCTP(dirent);
1869 if (dir->dir_list == NULL) {
1871 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
1872 if (!dir->dir_list) {
1874 SAFE_FREE(dirent);
1875 dir->dir_error = ENOMEM;
1876 return -1;
1879 ZERO_STRUCTP(dir->dir_list);
1881 dir->dir_end = dir->dir_next = dir->dir_list;
1883 else {
1885 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
1887 if (!dir->dir_end->next) {
1889 SAFE_FREE(dirent);
1890 dir->dir_error = ENOMEM;
1891 return -1;
1894 ZERO_STRUCTP(dir->dir_end->next);
1896 dir->dir_end = dir->dir_end->next;
1899 dir->dir_end->next = NULL;
1900 dir->dir_end->dirent = dirent;
1902 dirent->smbc_type = type;
1903 dirent->namelen = name_length;
1904 dirent->commentlen = comment_len;
1905 dirent->dirlen = size;
1907 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
1909 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
1910 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
1912 return 0;
1916 static void
1917 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
1919 SMBCFILE *dir = (SMBCFILE *)state;
1920 struct smbc_dir_list *dir_list;
1921 struct smbc_dirent *dirent;
1922 int dirent_type;
1923 int do_remove = 0;
1925 dirent_type = dir->dir_type;
1927 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1929 /* An error occurred, what do we do? */
1930 /* FIXME: Add some code here */
1933 /* Point to the one just added */
1934 dirent = dir->dir_end->dirent;
1936 /* See if this was a duplicate */
1937 for (dir_list = dir->dir_list;
1938 dir_list != dir->dir_end;
1939 dir_list = dir_list->next) {
1940 if (! do_remove &&
1941 strcmp(dir_list->dirent->name, dirent->name) == 0) {
1942 /* Duplicate. End end of list need to be removed. */
1943 do_remove = 1;
1946 if (do_remove && dir_list->next == dir->dir_end) {
1947 /* Found the end of the list. Remove it. */
1948 dir->dir_end = dir_list;
1949 free(dir_list->next);
1950 dir_list->next = NULL;
1951 break;
1956 static void
1957 list_fn(const char *name, uint32 type, const char *comment, void *state)
1959 SMBCFILE *dir = (SMBCFILE *)state;
1960 int dirent_type;
1962 /* We need to process the type a little ... */
1964 if (dir->dir_type == SMBC_FILE_SHARE) {
1966 switch (type) {
1967 case 0: /* Directory tree */
1968 dirent_type = SMBC_FILE_SHARE;
1969 break;
1971 case 1:
1972 dirent_type = SMBC_PRINTER_SHARE;
1973 break;
1975 case 2:
1976 dirent_type = SMBC_COMMS_SHARE;
1977 break;
1979 case 3:
1980 dirent_type = SMBC_IPC_SHARE;
1981 break;
1983 default:
1984 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
1985 break;
1988 else dirent_type = dir->dir_type;
1990 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1992 /* An error occurred, what do we do? */
1993 /* FIXME: Add some code here */
1998 static void
1999 dir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2002 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2003 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2005 /* Handle an error ... */
2007 /* FIXME: Add some code ... */
2013 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
2015 fstring server, share, user, password, options;
2016 pstring workgroup;
2017 pstring path;
2018 uint16 mode;
2019 char *p;
2020 SMBCSRV *srv = NULL;
2021 SMBCFILE *dir = NULL;
2022 struct in_addr rem_ip;
2024 if (!context || !context->internal ||
2025 !context->internal->_initialized) {
2026 DEBUG(4, ("no valid context\n"));
2027 errno = EINVAL + 8192;
2028 return NULL;
2032 if (!fname) {
2033 DEBUG(4, ("no valid fname\n"));
2034 errno = EINVAL + 8193;
2035 return NULL;
2038 if (smbc_parse_path(context, fname,
2039 server, sizeof(server),
2040 share, sizeof(share),
2041 path, sizeof(path),
2042 user, sizeof(user),
2043 password, sizeof(password),
2044 options, sizeof(options))) {
2045 DEBUG(4, ("no valid path\n"));
2046 errno = EINVAL + 8194;
2047 return NULL;
2050 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
2052 /* Ensure the options are valid */
2053 if (smbc_check_options(server, share, path, options)) {
2054 DEBUG(4, ("unacceptable options (%s)\n", options));
2055 errno = EINVAL + 8195;
2056 return NULL;
2059 if (user[0] == (char)0) fstrcpy(user, context->user);
2061 pstrcpy(workgroup, context->workgroup);
2063 dir = SMB_MALLOC_P(SMBCFILE);
2065 if (!dir) {
2067 errno = ENOMEM;
2068 return NULL;
2072 ZERO_STRUCTP(dir);
2074 dir->cli_fd = 0;
2075 dir->fname = SMB_STRDUP(fname);
2076 dir->srv = NULL;
2077 dir->offset = 0;
2078 dir->file = False;
2079 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2081 if (server[0] == (char)0) {
2083 int i;
2084 int count;
2085 int max_lmb_count;
2086 struct ip_service *ip_list;
2087 struct ip_service server_addr;
2088 struct user_auth_info u_info;
2089 struct cli_state *cli;
2091 if (share[0] != (char)0 || path[0] != (char)0) {
2093 errno = EINVAL + 8196;
2094 if (dir) {
2095 SAFE_FREE(dir->fname);
2096 SAFE_FREE(dir);
2098 return NULL;
2101 /* Determine how many local master browsers to query */
2102 max_lmb_count = (context->options.browse_max_lmb_count == 0
2103 ? INT_MAX
2104 : context->options.browse_max_lmb_count);
2106 pstrcpy(u_info.username, user);
2107 pstrcpy(u_info.password, password);
2110 * We have server and share and path empty but options
2111 * requesting that we scan all master browsers for their list
2112 * of workgroups/domains. This implies that we must first try
2113 * broadcast queries to find all master browsers, and if that
2114 * doesn't work, then try our other methods which return only
2115 * a single master browser.
2118 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2119 if (!find_master_ip(workgroup, &server_addr.ip)) {
2121 errno = ENOENT;
2122 return NULL;
2125 ip_list = &server_addr;
2126 count = 1;
2129 for (i = 0; i < count && i < max_lmb_count; i++) {
2130 DEBUG(99, ("Found master browser %d of %d: %s\n", i+1, MAX(count, max_lmb_count), inet_ntoa(ip_list[i].ip)));
2132 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2133 /* cli == NULL is the master browser refused to talk or
2134 could not be found */
2135 if ( !cli )
2136 continue;
2138 fstrcpy(server, cli->desthost);
2139 cli_shutdown(cli);
2141 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2144 * For each returned master browser IP address, get a
2145 * connection to IPC$ on the server if we do not
2146 * already have one, and determine the
2147 * workgroups/domains that it knows about.
2150 srv = smbc_server(context, server,
2151 "IPC$", workgroup, user, password);
2152 if (!srv) {
2153 continue;
2156 dir->srv = srv;
2157 dir->dir_type = SMBC_WORKGROUP;
2159 /* Now, list the stuff ... */
2161 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2162 (void *)dir)) {
2164 continue;
2167 } else {
2169 * Server not an empty string ... Check the rest and see what
2170 * gives
2172 if (share[0] == (char)0) {
2174 if (path[0] != (char)0) { /* Should not have empty share with path */
2176 errno = EINVAL + 8197;
2177 if (dir) {
2178 SAFE_FREE(dir->fname);
2179 SAFE_FREE(dir);
2181 return NULL;
2185 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2186 /* However, we check to see if <server> is an IP address first */
2188 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2189 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2190 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2191 fstring buserver;
2193 dir->dir_type = SMBC_SERVER;
2196 * Get the backup list ...
2200 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2202 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2203 errno = EPERM; /* FIXME, is this correct */
2204 return NULL;
2209 * Get a connection to IPC$ on the server if we do not already have one
2212 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2214 if (!srv) {
2215 DEBUG(0, ("got no contact to IPC$\n"));
2216 if (dir) {
2217 SAFE_FREE(dir->fname);
2218 SAFE_FREE(dir);
2220 return NULL;
2224 dir->srv = srv;
2226 /* Now, list the servers ... */
2228 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2229 (void *)dir)) {
2231 if (dir) {
2232 SAFE_FREE(dir->fname);
2233 SAFE_FREE(dir);
2235 return NULL;
2239 else {
2241 if (resolve_name(server, &rem_ip, 0x20)) {
2243 /* Now, list the shares ... */
2245 dir->dir_type = SMBC_FILE_SHARE;
2247 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2249 if (!srv) {
2251 if (dir) {
2252 SAFE_FREE(dir->fname);
2253 SAFE_FREE(dir);
2255 return NULL;
2259 dir->srv = srv;
2261 /* Now, list the servers ... */
2263 if (cli_RNetShareEnum(&srv->cli, list_fn,
2264 (void *)dir) < 0) {
2266 errno = cli_errno(&srv->cli);
2267 if (dir) {
2268 SAFE_FREE(dir->fname);
2269 SAFE_FREE(dir);
2271 return NULL;
2276 else {
2278 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2279 if (dir) {
2280 SAFE_FREE(dir->fname);
2281 SAFE_FREE(dir);
2283 return NULL;
2290 else { /* The server and share are specified ... work from there ... */
2292 /* Well, we connect to the server and list the directory */
2294 dir->dir_type = SMBC_FILE_SHARE;
2296 srv = smbc_server(context, server, share, workgroup, user, password);
2298 if (!srv) {
2300 if (dir) {
2301 SAFE_FREE(dir->fname);
2302 SAFE_FREE(dir);
2304 return NULL;
2308 dir->srv = srv;
2310 /* Now, list the files ... */
2312 p = path + strlen(path);
2313 pstrcat(path, "\\*");
2315 if (cli_list(&srv->cli, path, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2316 (void *)dir) < 0) {
2318 if (dir) {
2319 SAFE_FREE(dir->fname);
2320 SAFE_FREE(dir);
2322 errno = smbc_errno(context, &srv->cli);
2324 if (errno == EINVAL) {
2326 * See if they asked to opendir something
2327 * other than a directory. If so, the
2328 * converted error value we got would have
2329 * been EINVAL rather than ENOTDIR.
2331 *p = '\0'; /* restore original path */
2333 if (smbc_getatr(context, srv, path,
2334 &mode, NULL,
2335 NULL, NULL, NULL,
2336 NULL) &&
2337 ! IS_DOS_DIR(mode)) {
2339 /* It is. Correct the error value */
2340 errno = ENOTDIR;
2344 return NULL;
2351 DLIST_ADD(context->internal->_files, dir);
2352 return dir;
2357 * Routine to close a directory
2360 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2363 if (!context || !context->internal ||
2364 !context->internal->_initialized) {
2366 errno = EINVAL;
2367 return -1;
2371 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2373 errno = EBADF;
2374 return -1;
2378 smbc_remove_dir(dir); /* Clean it up */
2380 DLIST_REMOVE(context->internal->_files, dir);
2382 if (dir) {
2384 SAFE_FREE(dir->fname);
2385 SAFE_FREE(dir); /* Free the space too */
2388 return 0;
2392 static void smbc_readdir_internal(SMBCCTX * context,
2393 struct smbc_dirent *dest,
2394 struct smbc_dirent *src,
2395 int max_namebuf_len)
2397 if (context->options.urlencode_readdir_entries) {
2399 /* url-encode the name. get back remaining buffer space */
2400 max_namebuf_len =
2401 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2403 /* We now know the name length */
2404 dest->namelen = strlen(dest->name);
2406 /* Save the pointer to the beginning of the comment */
2407 dest->comment = dest->name + dest->namelen + 1;
2409 /* Copy the comment */
2410 strncpy(dest->comment, src->comment, max_namebuf_len);
2412 /* Ensure the comment is null terminated */
2413 if (max_namebuf_len > src->commentlen) {
2414 dest->comment[src->commentlen] = '\0';
2415 } else {
2416 dest->comment[max_namebuf_len - 1] = '\0';
2419 /* Save other fields */
2420 dest->smbc_type = src->smbc_type;
2421 dest->commentlen = strlen(dest->comment);
2422 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2423 (char *) dest);
2424 } else {
2426 /* No encoding. Just copy the entry as is. */
2427 memcpy(dest, src, src->dirlen);
2428 dest->comment = (char *)(&dest->name + src->namelen + 1);
2434 * Routine to get a directory entry
2437 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2439 int maxlen;
2440 struct smbc_dirent *dirp, *dirent;
2442 /* Check that all is ok first ... */
2444 if (!context || !context->internal ||
2445 !context->internal->_initialized) {
2447 errno = EINVAL;
2448 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2449 return NULL;
2453 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2455 errno = EBADF;
2456 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2457 return NULL;
2461 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2463 errno = ENOTDIR;
2464 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2465 return NULL;
2469 if (!dir->dir_next) {
2470 return NULL;
2473 dirent = dir->dir_next->dirent;
2474 if (!dirent) {
2476 errno = ENOENT;
2477 return NULL;
2481 dirp = (struct smbc_dirent *)context->internal->_dirent;
2482 maxlen = (sizeof(context->internal->_dirent) -
2483 sizeof(struct smbc_dirent));
2485 smbc_readdir_internal(context, dirp, dirent, maxlen);
2487 dir->dir_next = dir->dir_next->next;
2489 return dirp;
2493 * Routine to get directory entries
2496 static int smbc_getdents_ctx(SMBCCTX *context,
2497 SMBCFILE *dir,
2498 struct smbc_dirent *dirp,
2499 int count)
2501 int rem = count;
2502 int reqd;
2503 int maxlen;
2504 char *ndir = (char *)dirp;
2505 struct smbc_dir_list *dirlist;
2507 /* Check that all is ok first ... */
2509 if (!context || !context->internal ||
2510 !context->internal->_initialized) {
2512 errno = EINVAL;
2513 return -1;
2517 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2519 errno = EBADF;
2520 return -1;
2524 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2526 errno = ENOTDIR;
2527 return -1;
2532 * Now, retrieve the number of entries that will fit in what was passed
2533 * We have to figure out if the info is in the list, or we need to
2534 * send a request to the server to get the info.
2537 while ((dirlist = dir->dir_next)) {
2538 struct smbc_dirent *dirent;
2540 if (!dirlist->dirent) {
2542 errno = ENOENT; /* Bad error */
2543 return -1;
2547 /* Do urlencoding of next entry, if so selected */
2548 dirent = (struct smbc_dirent *)context->internal->_dirent;
2549 maxlen = (sizeof(context->internal->_dirent) -
2550 sizeof(struct smbc_dirent));
2551 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
2553 reqd = dirent->dirlen;
2555 if (rem < reqd) {
2557 if (rem < count) { /* We managed to copy something */
2559 errno = 0;
2560 return count - rem;
2563 else { /* Nothing copied ... */
2565 errno = EINVAL; /* Not enough space ... */
2566 return -1;
2572 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2574 ((struct smbc_dirent *)ndir)->comment =
2575 (char *)(&((struct smbc_dirent *)ndir)->name +
2576 dirent->namelen +
2579 ndir += reqd;
2581 rem -= reqd;
2583 dir->dir_next = dirlist = dirlist -> next;
2586 if (rem == count)
2587 return 0;
2588 else
2589 return count - rem;
2594 * Routine to create a directory ...
2597 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2599 SMBCSRV *srv;
2600 fstring server, share, user, password, workgroup;
2601 pstring path;
2603 if (!context || !context->internal ||
2604 !context->internal->_initialized) {
2606 errno = EINVAL;
2607 return -1;
2611 if (!fname) {
2613 errno = EINVAL;
2614 return -1;
2618 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2620 if (smbc_parse_path(context, fname,
2621 server, sizeof(server),
2622 share, sizeof(share),
2623 path, sizeof(path),
2624 user, sizeof(user),
2625 password, sizeof(password),
2626 NULL, 0)) {
2627 errno = EINVAL;
2628 return -1;
2631 if (user[0] == (char)0) fstrcpy(user, context->user);
2633 fstrcpy(workgroup, context->workgroup);
2635 srv = smbc_server(context, server, share, workgroup, user, password);
2637 if (!srv) {
2639 return -1; /* errno set by smbc_server */
2643 if (!cli_mkdir(&srv->cli, path)) {
2645 errno = smbc_errno(context, &srv->cli);
2646 return -1;
2650 return 0;
2655 * Our list function simply checks to see if a directory is not empty
2658 static int smbc_rmdir_dirempty = True;
2660 static void rmdir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2663 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2664 smbc_rmdir_dirempty = False;
2669 * Routine to remove a directory
2672 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2674 SMBCSRV *srv;
2675 fstring server, share, user, password, workgroup;
2676 pstring path;
2678 if (!context || !context->internal ||
2679 !context->internal->_initialized) {
2681 errno = EINVAL;
2682 return -1;
2686 if (!fname) {
2688 errno = EINVAL;
2689 return -1;
2693 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2695 if (smbc_parse_path(context, fname,
2696 server, sizeof(server),
2697 share, sizeof(share),
2698 path, sizeof(path),
2699 user, sizeof(user),
2700 password, sizeof(password),
2701 NULL, 0))
2703 errno = EINVAL;
2704 return -1;
2707 if (user[0] == (char)0) fstrcpy(user, context->user);
2709 fstrcpy(workgroup, context->workgroup);
2711 srv = smbc_server(context, server, share, workgroup, user, password);
2713 if (!srv) {
2715 return -1; /* errno set by smbc_server */
2719 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2721 mode = aDIR | aRONLY;
2724 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2726 if (strcmp(path, "\\") == 0) {
2728 mode = aDIR | aRONLY;
2731 else {
2733 mode = aRONLY;
2734 smbc_stat_printjob(srv, path, &size, &m_time);
2735 c_time = a_time = m_time;
2738 else { */
2740 if (!cli_rmdir(&srv->cli, path)) {
2742 errno = smbc_errno(context, &srv->cli);
2744 if (errno == EACCES) { /* Check if the dir empty or not */
2746 pstring lpath; /* Local storage to avoid buffer overflows */
2748 smbc_rmdir_dirempty = True; /* Make this so ... */
2750 pstrcpy(lpath, path);
2751 pstrcat(lpath, "\\*");
2753 if (cli_list(&srv->cli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2754 NULL) < 0) {
2756 /* Fix errno to ignore latest error ... */
2758 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
2759 smbc_errno(context, &srv->cli)));
2760 errno = EACCES;
2764 if (smbc_rmdir_dirempty)
2765 errno = EACCES;
2766 else
2767 errno = ENOTEMPTY;
2771 return -1;
2775 return 0;
2780 * Routine to return the current directory position
2783 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
2785 off_t ret_val; /* Squash warnings about cast */
2787 if (!context || !context->internal ||
2788 !context->internal->_initialized) {
2790 errno = EINVAL;
2791 return -1;
2795 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2797 errno = EBADF;
2798 return -1;
2802 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2804 errno = ENOTDIR;
2805 return -1;
2810 * We return the pointer here as the offset
2812 ret_val = (int)dir->dir_next;
2813 return ret_val;
2818 * A routine to run down the list and see if the entry is OK
2821 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
2822 struct smbc_dirent *dirent)
2825 /* Run down the list looking for what we want */
2827 if (dirent) {
2829 struct smbc_dir_list *tmp = list;
2831 while (tmp) {
2833 if (tmp->dirent == dirent)
2834 return tmp;
2836 tmp = tmp->next;
2842 return NULL; /* Not found, or an error */
2848 * Routine to seek on a directory
2851 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
2853 long int l_offset = offset; /* Handle problems of size */
2854 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
2855 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
2857 if (!context || !context->internal ||
2858 !context->internal->_initialized) {
2860 errno = EINVAL;
2861 return -1;
2865 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2867 errno = ENOTDIR;
2868 return -1;
2872 /* Now, check what we were passed and see if it is OK ... */
2874 if (dirent == NULL) { /* Seek to the begining of the list */
2876 dir->dir_next = dir->dir_list;
2877 return 0;
2881 /* Now, run down the list and make sure that the entry is OK */
2882 /* This may need to be changed if we change the format of the list */
2884 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
2886 errno = EINVAL; /* Bad entry */
2887 return -1;
2891 dir->dir_next = list_ent;
2893 return 0;
2898 * Routine to fstat a dir
2901 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
2904 if (!context || !context->internal ||
2905 !context->internal->_initialized) {
2907 errno = EINVAL;
2908 return -1;
2912 /* No code yet ... */
2914 return 0;
2918 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
2920 SMBCSRV *srv;
2921 fstring server, share, user, password, workgroup;
2922 pstring path;
2923 uint16 mode;
2925 if (!context || !context->internal ||
2926 !context->internal->_initialized) {
2928 errno = EINVAL; /* Best I can think of ... */
2929 return -1;
2933 if (!fname) {
2935 errno = EINVAL;
2936 return -1;
2940 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
2942 if (smbc_parse_path(context, fname,
2943 server, sizeof(server),
2944 share, sizeof(share),
2945 path, sizeof(path),
2946 user, sizeof(user),
2947 password, sizeof(password),
2948 NULL, 0)) {
2949 errno = EINVAL;
2950 return -1;
2953 if (user[0] == (char)0) fstrcpy(user, context->user);
2955 fstrcpy(workgroup, context->workgroup);
2957 srv = smbc_server(context, server, share, workgroup, user, password);
2959 if (!srv) {
2960 return -1; /* errno set by smbc_server */
2963 mode = 0;
2965 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
2966 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
2967 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
2968 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
2970 if (!cli_setatr(&srv->cli, path, mode, 0)) {
2971 errno = smbc_errno(context, &srv->cli);
2972 return -1;
2975 return 0;
2978 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
2980 SMBCSRV *srv;
2981 fstring server, share, user, password, workgroup;
2982 pstring path;
2983 time_t a_time;
2984 time_t m_time;
2986 if (!context || !context->internal ||
2987 !context->internal->_initialized) {
2989 errno = EINVAL; /* Best I can think of ... */
2990 return -1;
2994 if (!fname) {
2996 errno = EINVAL;
2997 return -1;
3001 if (tbuf == NULL) {
3002 a_time = m_time = time(NULL);
3003 } else {
3004 a_time = tbuf[0].tv_sec;
3005 m_time = tbuf[1].tv_sec;
3009 char atimebuf[32];
3010 char mtimebuf[32];
3012 DEBUG(4, ("smbc_utimes(%s, atime = %s mtime = %s)\n",
3013 fname,
3014 ctime_r(&a_time, atimebuf),
3015 ctime_r(&m_time, mtimebuf)));
3018 if (smbc_parse_path(context, fname,
3019 server, sizeof(server),
3020 share, sizeof(share),
3021 path, sizeof(path),
3022 user, sizeof(user),
3023 password, sizeof(password),
3024 NULL, 0)) {
3025 errno = EINVAL;
3026 return -1;
3029 if (user[0] == (char)0) fstrcpy(user, context->user);
3031 fstrcpy(workgroup, context->workgroup);
3033 srv = smbc_server(context, server, share, workgroup, user, password);
3035 if (!srv) {
3036 return -1; /* errno set by smbc_server */
3039 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3040 return -1; /* errno set by smbc_setatr */
3043 return 0;
3047 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3048 However NT4 gives a "The information may have been modified by a
3049 computer running Windows NT 5.0" if denied ACEs do not appear before
3050 allowed ACEs. */
3052 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
3054 if (sec_ace_equal(ace1, ace2))
3055 return 0;
3057 if (ace1->type != ace2->type)
3058 return ace2->type - ace1->type;
3060 if (sid_compare(&ace1->trustee, &ace2->trustee))
3061 return sid_compare(&ace1->trustee, &ace2->trustee);
3063 if (ace1->flags != ace2->flags)
3064 return ace1->flags - ace2->flags;
3066 if (ace1->info.mask != ace2->info.mask)
3067 return ace1->info.mask - ace2->info.mask;
3069 if (ace1->size != ace2->size)
3070 return ace1->size - ace2->size;
3072 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3076 static void sort_acl(SEC_ACL *the_acl)
3078 uint32 i;
3079 if (!the_acl) return;
3081 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
3083 for (i=1;i<the_acl->num_aces;) {
3084 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3085 int j;
3086 for (j=i; j<the_acl->num_aces-1; j++) {
3087 the_acl->ace[j] = the_acl->ace[j+1];
3089 the_acl->num_aces--;
3090 } else {
3091 i++;
3096 /* convert a SID to a string, either numeric or username/group */
3097 static void convert_sid_to_string(struct cli_state *ipc_cli,
3098 POLICY_HND *pol,
3099 fstring str,
3100 BOOL numeric,
3101 DOM_SID *sid)
3103 char **domains = NULL;
3104 char **names = NULL;
3105 uint32 *types = NULL;
3107 sid_to_string(str, sid);
3109 if (numeric) return; /* no lookup desired */
3111 /* Ask LSA to convert the sid to a name */
3113 if (!NT_STATUS_IS_OK(cli_lsa_lookup_sids(ipc_cli, ipc_cli->mem_ctx,
3114 pol, 1, sid, &domains,
3115 &names, &types)) ||
3116 !domains || !domains[0] || !names || !names[0]) {
3117 return;
3120 /* Converted OK */
3122 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3123 domains[0], lp_winbind_separator(),
3124 names[0]);
3127 /* convert a string to a SID, either numeric or username/group */
3128 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
3129 POLICY_HND *pol,
3130 BOOL numeric,
3131 DOM_SID *sid,
3132 const char *str)
3134 uint32 *types = NULL;
3135 DOM_SID *sids = NULL;
3136 BOOL result = True;
3138 if (numeric) {
3139 if (strncmp(str, "S-", 2) == 0) {
3140 return string_to_sid(sid, str);
3143 result = False;
3144 goto done;
3147 if (!NT_STATUS_IS_OK(cli_lsa_lookup_names(ipc_cli, ipc_cli->mem_ctx,
3148 pol, 1, &str, &sids,
3149 &types))) {
3150 result = False;
3151 goto done;
3154 sid_copy(sid, &sids[0]);
3155 done:
3157 return result;
3161 /* parse an ACE in the same format as print_ace() */
3162 static BOOL parse_ace(struct cli_state *ipc_cli,
3163 POLICY_HND *pol,
3164 SEC_ACE *ace,
3165 BOOL numeric,
3166 char *str)
3168 char *p;
3169 const char *cp;
3170 fstring tok;
3171 unsigned atype, aflags, amask;
3172 DOM_SID sid;
3173 SEC_ACCESS mask;
3174 const struct perm_value *v;
3175 struct perm_value {
3176 const char *perm;
3177 uint32 mask;
3180 /* These values discovered by inspection */
3181 static const struct perm_value special_values[] = {
3182 { "R", 0x00120089 },
3183 { "W", 0x00120116 },
3184 { "X", 0x001200a0 },
3185 { "D", 0x00010000 },
3186 { "P", 0x00040000 },
3187 { "O", 0x00080000 },
3188 { NULL, 0 },
3191 static const struct perm_value standard_values[] = {
3192 { "READ", 0x001200a9 },
3193 { "CHANGE", 0x001301bf },
3194 { "FULL", 0x001f01ff },
3195 { NULL, 0 },
3199 ZERO_STRUCTP(ace);
3200 p = strchr_m(str,':');
3201 if (!p) return False;
3202 *p = '\0';
3203 p++;
3204 /* Try to parse numeric form */
3206 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3207 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3208 goto done;
3211 /* Try to parse text form */
3213 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3214 return False;
3217 cp = p;
3218 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3219 return False;
3222 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3223 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3224 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3225 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3226 } else {
3227 return False;
3230 /* Only numeric form accepted for flags at present */
3232 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3233 sscanf(tok, "%i", &aflags))) {
3234 return False;
3237 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3238 return False;
3241 if (strncmp(tok, "0x", 2) == 0) {
3242 if (sscanf(tok, "%i", &amask) != 1) {
3243 return False;
3245 goto done;
3248 for (v = standard_values; v->perm; v++) {
3249 if (strcmp(tok, v->perm) == 0) {
3250 amask = v->mask;
3251 goto done;
3255 p = tok;
3257 while(*p) {
3258 BOOL found = False;
3260 for (v = special_values; v->perm; v++) {
3261 if (v->perm[0] == *p) {
3262 amask |= v->mask;
3263 found = True;
3267 if (!found) return False;
3268 p++;
3271 if (*p) {
3272 return False;
3275 done:
3276 mask.mask = amask;
3277 init_sec_ace(ace, &sid, atype, mask, aflags);
3278 return True;
3281 /* add an ACE to a list of ACEs in a SEC_ACL */
3282 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3284 SEC_ACL *new;
3285 SEC_ACE *aces;
3286 if (! *the_acl) {
3287 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3288 return True;
3291 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3292 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3293 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3294 new = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3295 SAFE_FREE(aces);
3296 (*the_acl) = new;
3297 return True;
3301 /* parse a ascii version of a security descriptor */
3302 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3303 struct cli_state *ipc_cli,
3304 POLICY_HND *pol,
3305 BOOL numeric,
3306 char *str)
3308 const char *p = str;
3309 fstring tok;
3310 SEC_DESC *ret;
3311 size_t sd_size;
3312 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3313 SEC_ACL *dacl=NULL;
3314 int revision=1;
3316 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3318 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3319 revision = strtol(tok+9, NULL, 16);
3320 continue;
3323 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3324 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3325 if (!owner_sid ||
3326 !convert_string_to_sid(ipc_cli, pol,
3327 numeric,
3328 owner_sid, tok+6)) {
3329 DEBUG(5, ("Failed to parse owner sid\n"));
3330 return NULL;
3332 continue;
3335 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3336 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3337 if (!owner_sid ||
3338 !convert_string_to_sid(ipc_cli, pol,
3339 False,
3340 owner_sid, tok+7)) {
3341 DEBUG(5, ("Failed to parse owner sid\n"));
3342 return NULL;
3344 continue;
3347 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3348 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3349 if (!grp_sid ||
3350 !convert_string_to_sid(ipc_cli, pol,
3351 numeric,
3352 grp_sid, tok+6)) {
3353 DEBUG(5, ("Failed to parse group sid\n"));
3354 return NULL;
3356 continue;
3359 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3360 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3361 if (!grp_sid ||
3362 !convert_string_to_sid(ipc_cli, pol,
3363 False,
3364 grp_sid, tok+6)) {
3365 DEBUG(5, ("Failed to parse group sid\n"));
3366 return NULL;
3368 continue;
3371 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3372 SEC_ACE ace;
3373 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3374 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3375 return NULL;
3377 if(!add_ace(&dacl, &ace, ctx)) {
3378 DEBUG(5, ("Failed to add ACL %s\n", tok));
3379 return NULL;
3381 continue;
3384 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3385 SEC_ACE ace;
3386 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3387 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3388 return NULL;
3390 if(!add_ace(&dacl, &ace, ctx)) {
3391 DEBUG(5, ("Failed to add ACL %s\n", tok));
3392 return NULL;
3394 continue;
3397 DEBUG(5, ("Failed to parse security descriptor\n"));
3398 return NULL;
3401 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3402 owner_sid, grp_sid, NULL, dacl, &sd_size);
3404 SAFE_FREE(grp_sid);
3405 SAFE_FREE(owner_sid);
3407 return ret;
3411 /* Obtain the current dos attributes */
3412 static DOS_ATTR_DESC *dos_attr_query(SMBCCTX *context,
3413 TALLOC_CTX *ctx,
3414 const char *filename,
3415 SMBCSRV *srv)
3417 time_t m_time = 0, a_time = 0, c_time = 0;
3418 SMB_OFF_T size = 0;
3419 uint16 mode = 0;
3420 SMB_INO_T inode = 0;
3421 DOS_ATTR_DESC *ret;
3423 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
3424 if (!ret) {
3425 errno = ENOMEM;
3426 return NULL;
3429 /* Obtain the DOS attributes */
3430 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
3431 &mode, &size,
3432 &c_time, &a_time, &m_time, &inode)) {
3434 errno = smbc_errno(context, &srv->cli);
3435 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
3436 return NULL;
3440 ret->mode = mode;
3441 ret->size = size;
3442 ret->a_time = a_time;
3443 ret->c_time = c_time;
3444 ret->m_time = m_time;
3445 ret->inode = inode;
3447 return ret;
3451 /* parse a ascii version of a security descriptor */
3452 static void dos_attr_parse(SMBCCTX *context,
3453 DOS_ATTR_DESC *dad,
3454 SMBCSRV *srv,
3455 char *str)
3457 const char *p = str;
3458 fstring tok;
3460 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3462 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
3463 dad->mode = strtol(tok+5, NULL, 16);
3464 continue;
3467 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
3468 dad->size = strtoll(tok+5, NULL, 10);
3469 continue;
3472 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
3473 dad->a_time = strtoll(tok+7, NULL, 10);
3474 continue;
3477 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
3478 dad->c_time = strtoll(tok+7, NULL, 10);
3479 continue;
3482 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
3483 dad->m_time = strtoll(tok+7, NULL, 10);
3484 continue;
3487 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
3488 dad->inode = strtoll(tok+6, NULL, 10);
3489 continue;
3495 /*****************************************************
3496 retrieve the acls for a file
3497 *******************************************************/
3498 static int cacl_get(SMBCCTX *context, TALLOC_CTX *ctx, SMBCSRV *srv,
3499 struct cli_state *ipc_cli, POLICY_HND *pol,
3500 char *filename, char *attr_name, char *buf, int bufsize)
3502 uint32 i;
3503 int n = 0;
3504 int n_used;
3505 BOOL all;
3506 BOOL all_nt;
3507 BOOL all_nt_acls;
3508 BOOL all_dos;
3509 BOOL some_nt;
3510 BOOL some_dos;
3511 BOOL exclude_nt_revision = False;
3512 BOOL exclude_nt_owner = False;
3513 BOOL exclude_nt_group = False;
3514 BOOL exclude_nt_acl = False;
3515 BOOL exclude_dos_mode = False;
3516 BOOL exclude_dos_size = False;
3517 BOOL exclude_dos_ctime = False;
3518 BOOL exclude_dos_atime = False;
3519 BOOL exclude_dos_mtime = False;
3520 BOOL exclude_dos_inode = False;
3521 BOOL numeric = True;
3522 BOOL determine_size = (bufsize == 0);
3523 int fnum = -1;
3524 SEC_DESC *sd;
3525 fstring sidstr;
3526 fstring name_sandbox;
3527 char *name;
3528 char *pExclude;
3529 char *p;
3530 time_t m_time = 0, a_time = 0, c_time = 0;
3531 SMB_OFF_T size = 0;
3532 uint16 mode = 0;
3533 SMB_INO_T ino = 0;
3534 struct cli_state *cli = &srv->cli;
3536 /* Copy name so we can strip off exclusions (if any are specified) */
3537 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
3539 /* Ensure name is null terminated */
3540 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
3542 /* Play in the sandbox */
3543 name = name_sandbox;
3545 /* If there are any exclusions, point to them and mask them from name */
3546 if ((pExclude = strchr(name, '!')) != NULL)
3548 *pExclude++ = '\0';
3551 all = (StrnCaseCmp(name, "system.*", 8) == 0);
3552 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
3553 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
3554 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
3555 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
3556 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
3557 numeric = (* (name + strlen(name) - 1) != '+');
3559 /* Look for exclusions from "all" requests */
3560 if (all || all_nt || all_dos) {
3562 /* Exclusions are delimited by '!' */
3563 for (; pExclude != NULL; pExclude = (p == NULL ? NULL : p + 1)) {
3565 /* Find end of this exclusion name */
3566 if ((p = strchr(pExclude, '!')) != NULL)
3568 *p = '\0';
3571 /* Which exclusion name is this? */
3572 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
3573 exclude_nt_revision = True;
3575 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
3576 exclude_nt_owner = True;
3578 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
3579 exclude_nt_group = True;
3581 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
3582 exclude_nt_acl = True;
3584 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
3585 exclude_dos_mode = True;
3587 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
3588 exclude_dos_size = True;
3590 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
3591 exclude_dos_ctime = True;
3593 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
3594 exclude_dos_atime = True;
3596 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
3597 exclude_dos_mtime = True;
3599 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
3600 exclude_dos_inode = True;
3602 else {
3603 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
3604 pExclude));
3605 errno = ENOATTR;
3606 return -1;
3611 n_used = 0;
3614 * If we are (possibly) talking to an NT or new system and some NT
3615 * attributes have been requested...
3617 if (ipc_cli && (all || some_nt || all_nt_acls)) {
3618 /* Point to the portion after "system.nt_sec_desc." */
3619 name += 19; /* if (all) this will be invalid but unused */
3621 /* ... then obtain any NT attributes which were requested */
3622 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3624 if (fnum == -1) {
3625 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3626 filename, cli_errstr(cli)));
3627 errno = 0;
3628 return -1;
3631 sd = cli_query_secdesc(cli, fnum, ctx);
3633 if (!sd) {
3634 DEBUG(5,
3635 ("cacl_get Failed to query old descriptor\n"));
3636 errno = 0;
3637 return -1;
3640 cli_close(cli, fnum);
3642 if (! exclude_nt_revision) {
3643 if (all || all_nt) {
3644 if (determine_size) {
3645 p = talloc_asprintf(ctx,
3646 "REVISION:%d",
3647 sd->revision);
3648 if (!p) {
3649 errno = ENOMEM;
3650 return -1;
3652 n = strlen(p);
3653 } else {
3654 n = snprintf(buf, bufsize,
3655 "REVISION:%d", sd->revision);
3657 } else if (StrCaseCmp(name, "revision") == 0) {
3658 if (determine_size) {
3659 p = talloc_asprintf(ctx, "%d",
3660 sd->revision);
3661 if (!p) {
3662 errno = ENOMEM;
3663 return -1;
3665 n = strlen(p);
3666 } else {
3667 n = snprintf(buf, bufsize, "%d",
3668 sd->revision);
3672 if (!determine_size && n > bufsize) {
3673 errno = ERANGE;
3674 return -1;
3676 buf += n;
3677 n_used += n;
3678 bufsize -= n;
3681 if (! exclude_nt_owner) {
3682 /* Get owner and group sid */
3683 if (sd->owner_sid) {
3684 convert_sid_to_string(ipc_cli, pol,
3685 sidstr,
3686 numeric,
3687 sd->owner_sid);
3688 } else {
3689 fstrcpy(sidstr, "");
3692 if (all || all_nt) {
3693 if (determine_size) {
3694 p = talloc_asprintf(ctx, ",OWNER:%s",
3695 sidstr);
3696 if (!p) {
3697 errno = ENOMEM;
3698 return -1;
3700 n = strlen(p);
3701 } else {
3702 n = snprintf(buf, bufsize,
3703 ",OWNER:%s", sidstr);
3705 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3706 if (determine_size) {
3707 p = talloc_asprintf(ctx, "%s", sidstr);
3708 if (!p) {
3709 errno = ENOMEM;
3710 return -1;
3712 n = strlen(p);
3713 } else {
3714 n = snprintf(buf, bufsize, "%s",
3715 sidstr);
3719 if (!determine_size && n > bufsize) {
3720 errno = ERANGE;
3721 return -1;
3723 buf += n;
3724 n_used += n;
3725 bufsize -= n;
3728 if (! exclude_nt_group) {
3729 if (sd->grp_sid) {
3730 convert_sid_to_string(ipc_cli, pol,
3731 sidstr, numeric,
3732 sd->grp_sid);
3733 } else {
3734 fstrcpy(sidstr, "");
3737 if (all || all_nt) {
3738 if (determine_size) {
3739 p = talloc_asprintf(ctx, ",GROUP:%s",
3740 sidstr);
3741 if (!p) {
3742 errno = ENOMEM;
3743 return -1;
3745 n = strlen(p);
3746 } else {
3747 n = snprintf(buf, bufsize,
3748 ",GROUP:%s", sidstr);
3750 } else if (StrnCaseCmp(name, "group", 5) == 0) {
3751 if (determine_size) {
3752 p = talloc_asprintf(ctx, "%s", sidstr);
3753 if (!p) {
3754 errno = ENOMEM;
3755 return -1;
3757 n = strlen(p);
3758 } else {
3759 n = snprintf(buf, bufsize, "%s", sidstr);
3763 if (!determine_size && n > bufsize) {
3764 errno = ERANGE;
3765 return -1;
3767 buf += n;
3768 n_used += n;
3769 bufsize -= n;
3772 if (! exclude_nt_acl) {
3773 /* Add aces to value buffer */
3774 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
3776 SEC_ACE *ace = &sd->dacl->ace[i];
3777 convert_sid_to_string(ipc_cli, pol,
3778 sidstr, numeric,
3779 &ace->trustee);
3781 if (all || all_nt) {
3782 if (determine_size) {
3783 p = talloc_asprintf(
3784 ctx,
3785 ",ACL:"
3786 "%s:%d/%d/0x%08x",
3787 sidstr,
3788 ace->type,
3789 ace->flags,
3790 ace->info.mask);
3791 if (!p) {
3792 errno = ENOMEM;
3793 return -1;
3795 n = strlen(p);
3796 } else {
3797 n = snprintf(
3798 buf, bufsize,
3799 ",ACL:%s:%d/%d/0x%08x",
3800 sidstr,
3801 ace->type,
3802 ace->flags,
3803 ace->info.mask);
3805 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
3806 StrCaseCmp(name + 3, sidstr) == 0) ||
3807 (StrnCaseCmp(name, "acl+", 4) == 0 &&
3808 StrCaseCmp(name + 4, sidstr) == 0)) {
3809 if (determine_size) {
3810 p = talloc_asprintf(
3811 ctx,
3812 "%d/%d/0x%08x",
3813 ace->type,
3814 ace->flags,
3815 ace->info.mask);
3816 if (!p) {
3817 errno = ENOMEM;
3818 return -1;
3820 n = strlen(p);
3821 } else {
3822 n = snprintf(buf, bufsize,
3823 "%d/%d/0x%08x",
3824 ace->type,
3825 ace->flags,
3826 ace->info.mask);
3828 } else if (all_nt_acls) {
3829 if (determine_size) {
3830 p = talloc_asprintf(
3831 ctx,
3832 "%s%s:%d/%d/0x%08x",
3833 i ? "," : "",
3834 sidstr,
3835 ace->type,
3836 ace->flags,
3837 ace->info.mask);
3838 if (!p) {
3839 errno = ENOMEM;
3840 return -1;
3842 n = strlen(p);
3843 } else {
3844 n = snprintf(buf, bufsize,
3845 "%s%s:%d/%d/0x%08x",
3846 i ? "," : "",
3847 sidstr,
3848 ace->type,
3849 ace->flags,
3850 ace->info.mask);
3853 if (n > bufsize) {
3854 errno = ERANGE;
3855 return -1;
3857 buf += n;
3858 n_used += n;
3859 bufsize -= n;
3863 /* Restore name pointer to its original value */
3864 name -= 19;
3867 if (all || some_dos) {
3868 /* Point to the portion after "system.dos_attr." */
3869 name += 16; /* if (all) this will be invalid but unused */
3871 /* Obtain the DOS attributes */
3872 if (!smbc_getatr(context, srv, filename, &mode, &size,
3873 &c_time, &a_time, &m_time, &ino)) {
3875 errno = smbc_errno(context, &srv->cli);
3876 return -1;
3880 if (! exclude_dos_mode) {
3881 if (all || all_dos) {
3882 if (determine_size) {
3883 p = talloc_asprintf(ctx,
3884 "%sMODE:0x%x",
3885 (ipc_cli &&
3886 (all || some_nt)
3887 ? ","
3888 : ""),
3889 mode);
3890 if (!p) {
3891 errno = ENOMEM;
3892 return -1;
3894 n = strlen(p);
3895 } else {
3896 n = snprintf(buf, bufsize,
3897 "%sMODE:0x%x",
3898 (ipc_cli &&
3899 (all || some_nt)
3900 ? ","
3901 : ""),
3902 mode);
3904 } else if (StrCaseCmp(name, "mode") == 0) {
3905 if (determine_size) {
3906 p = talloc_asprintf(ctx, "0x%x", mode);
3907 if (!p) {
3908 errno = ENOMEM;
3909 return -1;
3911 n = strlen(p);
3912 } else {
3913 n = snprintf(buf, bufsize, "0x%x", mode);
3917 if (!determine_size && n > bufsize) {
3918 errno = ERANGE;
3919 return -1;
3921 buf += n;
3922 n_used += n;
3923 bufsize -= n;
3926 if (! exclude_dos_size) {
3927 if (all || all_dos) {
3928 if (determine_size) {
3929 p = talloc_asprintf(
3930 ctx,
3931 ",SIZE:%llu",
3932 (unsigned long long) size);
3933 if (!p) {
3934 errno = ENOMEM;
3935 return -1;
3937 n = strlen(p);
3938 } else {
3939 n = snprintf(buf, bufsize,
3940 ",SIZE:%llu",
3941 (unsigned long long) size);
3943 } else if (StrCaseCmp(name, "size") == 0) {
3944 if (determine_size) {
3945 p = talloc_asprintf(
3946 ctx,
3947 "%llu",
3948 (unsigned long long) size);
3949 if (!p) {
3950 errno = ENOMEM;
3951 return -1;
3953 n = strlen(p);
3954 } else {
3955 n = snprintf(buf, bufsize,
3956 "%llu",
3957 (unsigned long long) size);
3961 if (!determine_size && n > bufsize) {
3962 errno = ERANGE;
3963 return -1;
3965 buf += n;
3966 n_used += n;
3967 bufsize -= n;
3970 if (! exclude_dos_ctime) {
3971 if (all || all_dos) {
3972 if (determine_size) {
3973 p = talloc_asprintf(ctx,
3974 ",C_TIME:%lu",
3975 c_time);
3976 if (!p) {
3977 errno = ENOMEM;
3978 return -1;
3980 n = strlen(p);
3981 } else {
3982 n = snprintf(buf, bufsize,
3983 ",C_TIME:%lu", c_time);
3985 } else if (StrCaseCmp(name, "c_time") == 0) {
3986 if (determine_size) {
3987 p = talloc_asprintf(ctx, "%lu", c_time);
3988 if (!p) {
3989 errno = ENOMEM;
3990 return -1;
3992 n = strlen(p);
3993 } else {
3994 n = snprintf(buf, bufsize, "%lu", c_time);
3998 if (!determine_size && n > bufsize) {
3999 errno = ERANGE;
4000 return -1;
4002 buf += n;
4003 n_used += n;
4004 bufsize -= n;
4007 if (! exclude_dos_atime) {
4008 if (all || all_dos) {
4009 if (determine_size) {
4010 p = talloc_asprintf(ctx,
4011 ",A_TIME:%lu",
4012 a_time);
4013 if (!p) {
4014 errno = ENOMEM;
4015 return -1;
4017 n = strlen(p);
4018 } else {
4019 n = snprintf(buf, bufsize,
4020 ",A_TIME:%lu", a_time);
4022 } else if (StrCaseCmp(name, "a_time") == 0) {
4023 if (determine_size) {
4024 p = talloc_asprintf(ctx, "%lu", a_time);
4025 if (!p) {
4026 errno = ENOMEM;
4027 return -1;
4029 n = strlen(p);
4030 } else {
4031 n = snprintf(buf, bufsize, "%lu", a_time);
4035 if (!determine_size && n > bufsize) {
4036 errno = ERANGE;
4037 return -1;
4039 buf += n;
4040 n_used += n;
4041 bufsize -= n;
4044 if (! exclude_dos_mtime) {
4045 if (all || all_dos) {
4046 if (determine_size) {
4047 p = talloc_asprintf(ctx,
4048 ",M_TIME:%lu",
4049 m_time);
4050 if (!p) {
4051 errno = ENOMEM;
4052 return -1;
4054 n = strlen(p);
4055 } else {
4056 n = snprintf(buf, bufsize,
4057 ",M_TIME:%lu", m_time);
4059 } else if (StrCaseCmp(name, "m_time") == 0) {
4060 if (determine_size) {
4061 p = talloc_asprintf(ctx, "%lu", m_time);
4062 if (!p) {
4063 errno = ENOMEM;
4064 return -1;
4066 n = strlen(p);
4067 } else {
4068 n = snprintf(buf, bufsize, "%lu", m_time);
4072 if (!determine_size && n > bufsize) {
4073 errno = ERANGE;
4074 return -1;
4076 buf += n;
4077 n_used += n;
4078 bufsize -= n;
4081 if (! exclude_dos_inode) {
4082 if (all || all_dos) {
4083 if (determine_size) {
4084 p = talloc_asprintf(
4085 ctx,
4086 ",INODE:%llu",
4087 (unsigned long long) ino);
4088 if (!p) {
4089 errno = ENOMEM;
4090 return -1;
4092 n = strlen(p);
4093 } else {
4094 n = snprintf(buf, bufsize,
4095 ",INODE:%llu",
4096 (unsigned long long) ino);
4098 } else if (StrCaseCmp(name, "inode") == 0) {
4099 if (determine_size) {
4100 p = talloc_asprintf(
4101 ctx,
4102 "%llu",
4103 (unsigned long long) ino);
4104 if (!p) {
4105 errno = ENOMEM;
4106 return -1;
4108 n = strlen(p);
4109 } else {
4110 n = snprintf(buf, bufsize,
4111 "%llu",
4112 (unsigned long long) ino);
4116 if (!determine_size && n > bufsize) {
4117 errno = ERANGE;
4118 return -1;
4120 buf += n;
4121 n_used += n;
4122 bufsize -= n;
4125 /* Restore name pointer to its original value */
4126 name -= 16;
4129 if (n_used == 0) {
4130 errno = ENOATTR;
4131 return -1;
4134 return n_used;
4138 /*****************************************************
4139 set the ACLs on a file given an ascii description
4140 *******************************************************/
4141 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
4142 struct cli_state *ipc_cli, POLICY_HND *pol,
4143 const char *filename, const char *the_acl,
4144 int mode, int flags)
4146 int fnum;
4147 int err = 0;
4148 SEC_DESC *sd = NULL, *old;
4149 SEC_ACL *dacl = NULL;
4150 DOM_SID *owner_sid = NULL;
4151 DOM_SID *grp_sid = NULL;
4152 uint32 i, j;
4153 size_t sd_size;
4154 int ret = 0;
4155 char *p;
4156 BOOL numeric = True;
4158 /* the_acl will be null for REMOVE_ALL operations */
4159 if (the_acl) {
4160 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4161 p > the_acl &&
4162 p[-1] != '+');
4164 /* if this is to set the entire ACL... */
4165 if (*the_acl == '*') {
4166 /* ... then increment past the first colon */
4167 the_acl = p + 1;
4170 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4171 CONST_DISCARD(char *, the_acl));
4173 if (!sd) {
4174 errno = EINVAL;
4175 return -1;
4179 /* The desired access below is the only one I could find that works
4180 with NT4, W2KP and Samba */
4182 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4184 if (fnum == -1) {
4185 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4186 filename, cli_errstr(cli)));
4187 errno = 0;
4188 return -1;
4191 old = cli_query_secdesc(cli, fnum, ctx);
4193 if (!old) {
4194 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4195 errno = 0;
4196 return -1;
4199 cli_close(cli, fnum);
4201 switch (mode) {
4202 case SMBC_XATTR_MODE_REMOVE_ALL:
4203 old->dacl->num_aces = 0;
4204 SAFE_FREE(old->dacl->ace);
4205 SAFE_FREE(old->dacl);
4206 old->off_dacl = 0;
4207 dacl = old->dacl;
4208 break;
4210 case SMBC_XATTR_MODE_REMOVE:
4211 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4212 BOOL found = False;
4214 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4215 if (sec_ace_equal(&sd->dacl->ace[i],
4216 &old->dacl->ace[j])) {
4217 uint32 k;
4218 for (k=j; k<old->dacl->num_aces-1;k++) {
4219 old->dacl->ace[k] = old->dacl->ace[k+1];
4221 old->dacl->num_aces--;
4222 if (old->dacl->num_aces == 0) {
4223 SAFE_FREE(old->dacl->ace);
4224 SAFE_FREE(old->dacl);
4225 old->off_dacl = 0;
4227 found = True;
4228 dacl = old->dacl;
4229 break;
4233 if (!found) {
4234 err = ENOATTR;
4235 ret = -1;
4236 goto failed;
4239 break;
4241 case SMBC_XATTR_MODE_ADD:
4242 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4243 BOOL found = False;
4245 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4246 if (sid_equal(&sd->dacl->ace[i].trustee,
4247 &old->dacl->ace[j].trustee)) {
4248 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4249 err = EEXIST;
4250 ret = -1;
4251 goto failed;
4253 old->dacl->ace[j] = sd->dacl->ace[i];
4254 ret = -1;
4255 found = True;
4259 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4260 err = ENOATTR;
4261 ret = -1;
4262 goto failed;
4265 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4266 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4269 dacl = old->dacl;
4270 break;
4272 case SMBC_XATTR_MODE_SET:
4273 old = sd;
4274 owner_sid = old->owner_sid;
4275 grp_sid = old->grp_sid;
4276 dacl = old->dacl;
4277 break;
4279 case SMBC_XATTR_MODE_CHOWN:
4280 owner_sid = sd->owner_sid;
4281 break;
4283 case SMBC_XATTR_MODE_CHGRP:
4284 grp_sid = sd->grp_sid;
4285 break;
4288 /* Denied ACE entries must come before allowed ones */
4289 sort_acl(old->dacl);
4291 /* Create new security descriptor and set it */
4292 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4293 owner_sid, grp_sid, NULL, dacl, &sd_size);
4295 fnum = cli_nt_create(cli, filename,
4296 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4298 if (fnum == -1) {
4299 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4300 filename, cli_errstr(cli)));
4301 errno = 0;
4302 return -1;
4305 if (!cli_set_secdesc(cli, fnum, sd)) {
4306 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4307 ret = -1;
4310 /* Clean up */
4312 failed:
4313 cli_close(cli, fnum);
4315 if (err != 0) {
4316 errno = err;
4319 return ret;
4323 int smbc_setxattr_ctx(SMBCCTX *context,
4324 const char *fname,
4325 const char *name,
4326 const void *value,
4327 size_t size,
4328 int flags)
4330 int ret;
4331 int ret2;
4332 SMBCSRV *srv;
4333 SMBCSRV *ipc_srv;
4334 fstring server, share, user, password, workgroup;
4335 pstring path;
4336 TALLOC_CTX *ctx;
4337 POLICY_HND pol;
4338 DOS_ATTR_DESC *dad;
4340 if (!context || !context->internal ||
4341 !context->internal->_initialized) {
4343 errno = EINVAL; /* Best I can think of ... */
4344 return -1;
4348 if (!fname) {
4350 errno = EINVAL;
4351 return -1;
4355 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n", fname, name, (int) size, (const char*)value));
4357 if (smbc_parse_path(context, fname,
4358 server, sizeof(server),
4359 share, sizeof(share),
4360 path, sizeof(path),
4361 user, sizeof(user),
4362 password, sizeof(password),
4363 NULL, 0)) {
4364 errno = EINVAL;
4365 return -1;
4368 if (user[0] == (char)0) fstrcpy(user, context->user);
4370 fstrcpy(workgroup, context->workgroup);
4372 srv = smbc_server(context, server, share, workgroup, user, password);
4373 if (!srv) {
4374 return -1; /* errno set by smbc_server */
4377 if (! srv->no_nt_session) {
4378 ipc_srv = smbc_attr_server(context, server, share,
4379 workgroup, user, password,
4380 &pol);
4381 srv->no_nt_session = True;
4382 } else {
4383 ipc_srv = NULL;
4386 ctx = talloc_init("smbc_setxattr");
4387 if (!ctx) {
4388 errno = ENOMEM;
4389 return -1;
4393 * Are they asking to set the entire set of known attributes?
4395 if (StrCaseCmp(name, "system.*") == 0 ||
4396 StrCaseCmp(name, "system.*+") == 0) {
4397 /* Yup. */
4398 char *namevalue =
4399 talloc_asprintf(ctx, "%s:%s", name+7, (const char *) value);
4400 if (! namevalue) {
4401 errno = ENOMEM;
4402 ret = -1;
4403 return -1;
4406 if (ipc_srv) {
4407 ret = cacl_set(ctx, &srv->cli,
4408 &ipc_srv->cli, &pol, path,
4409 namevalue,
4410 (*namevalue == '*'
4411 ? SMBC_XATTR_MODE_SET
4412 : SMBC_XATTR_MODE_ADD),
4413 flags);
4414 } else {
4415 ret = 0;
4418 /* get a DOS Attribute Descriptor with current attributes */
4419 dad = dos_attr_query(context, ctx, path, srv);
4420 if (dad) {
4421 /* Overwrite old with new, using what was provided */
4422 dos_attr_parse(context, dad, srv, namevalue);
4424 /* Set the new DOS attributes */
4425 if (! smbc_setatr(context, srv, path,
4426 dad->c_time,
4427 dad->a_time,
4428 dad->m_time,
4429 dad->mode)) {
4431 /* cause failure if NT failed too */
4432 dad = NULL;
4436 /* we only fail if both NT and DOS sets failed */
4437 if (ret < 0 && ! dad) {
4438 ret = -1; /* in case dad was null */
4440 else {
4441 ret = 0;
4444 talloc_destroy(ctx);
4445 return ret;
4449 * Are they asking to set an access control element or to set
4450 * the entire access control list?
4452 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4453 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4454 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4455 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4456 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4458 /* Yup. */
4459 char *namevalue =
4460 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4462 if (! ipc_srv) {
4463 ret = -1; /* errno set by smbc_server() */
4465 else if (! namevalue) {
4466 errno = ENOMEM;
4467 ret = -1;
4468 } else {
4469 ret = cacl_set(ctx, &srv->cli,
4470 &ipc_srv->cli, &pol, path,
4471 namevalue,
4472 (*namevalue == '*'
4473 ? SMBC_XATTR_MODE_SET
4474 : SMBC_XATTR_MODE_ADD),
4475 flags);
4477 talloc_destroy(ctx);
4478 return ret;
4482 * Are they asking to set the owner?
4484 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4485 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
4487 /* Yup. */
4488 char *namevalue =
4489 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4491 if (! ipc_srv) {
4493 ret = -1; /* errno set by smbc_server() */
4495 else if (! namevalue) {
4496 errno = ENOMEM;
4497 ret = -1;
4498 } else {
4499 ret = cacl_set(ctx, &srv->cli,
4500 &ipc_srv->cli, &pol, path,
4501 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4503 talloc_destroy(ctx);
4504 return ret;
4508 * Are they asking to set the group?
4510 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4511 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
4513 /* Yup. */
4514 char *namevalue =
4515 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4517 if (! ipc_srv) {
4518 /* errno set by smbc_server() */
4519 ret = -1;
4521 else if (! namevalue) {
4522 errno = ENOMEM;
4523 ret = -1;
4524 } else {
4525 ret = cacl_set(ctx, &srv->cli,
4526 &ipc_srv->cli, &pol, path,
4527 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4529 talloc_destroy(ctx);
4530 return ret;
4534 * Are they asking to set a DOS attribute?
4536 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4537 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4538 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4539 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4540 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
4542 /* get a DOS Attribute Descriptor with current attributes */
4543 dad = dos_attr_query(context, ctx, path, srv);
4544 if (dad) {
4545 char *namevalue =
4546 talloc_asprintf(ctx, "%s:%s", name+16, (const char *) value);
4547 if (! namevalue) {
4548 errno = ENOMEM;
4549 ret = -1;
4550 } else {
4551 /* Overwrite old with provided new params */
4552 dos_attr_parse(context, dad, srv, namevalue);
4554 /* Set the new DOS attributes */
4555 ret2 = smbc_setatr(context, srv, path,
4556 dad->c_time,
4557 dad->a_time,
4558 dad->m_time,
4559 dad->mode);
4561 /* ret2 has True (success) / False (failure) */
4562 if (ret2) {
4563 ret = 0;
4564 } else {
4565 ret = -1;
4568 } else {
4569 ret = -1;
4572 talloc_destroy(ctx);
4573 return ret;
4576 /* Unsupported attribute name */
4577 talloc_destroy(ctx);
4578 errno = EINVAL;
4579 return -1;
4582 int smbc_getxattr_ctx(SMBCCTX *context,
4583 const char *fname,
4584 const char *name,
4585 const void *value,
4586 size_t size)
4588 int ret;
4589 SMBCSRV *srv;
4590 SMBCSRV *ipc_srv;
4591 fstring server, share, user, password, workgroup;
4592 pstring path;
4593 TALLOC_CTX *ctx;
4594 POLICY_HND pol;
4597 if (!context || !context->internal ||
4598 !context->internal->_initialized) {
4600 errno = EINVAL; /* Best I can think of ... */
4601 return -1;
4605 if (!fname) {
4607 errno = EINVAL;
4608 return -1;
4612 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
4614 if (smbc_parse_path(context, fname,
4615 server, sizeof(server),
4616 share, sizeof(share),
4617 path, sizeof(path),
4618 user, sizeof(user),
4619 password, sizeof(password),
4620 NULL, 0)) {
4621 errno = EINVAL;
4622 return -1;
4625 if (user[0] == (char)0) fstrcpy(user, context->user);
4627 fstrcpy(workgroup, context->workgroup);
4629 srv = smbc_server(context, server, share, workgroup, user, password);
4630 if (!srv) {
4631 return -1; /* errno set by smbc_server */
4634 if (! srv->no_nt_session) {
4635 ipc_srv = smbc_attr_server(context, server, share,
4636 workgroup, user, password,
4637 &pol);
4638 if (! ipc_srv) {
4639 srv->no_nt_session = True;
4641 } else {
4642 ipc_srv = NULL;
4645 ctx = talloc_init("smbc:getxattr");
4646 if (!ctx) {
4647 errno = ENOMEM;
4648 return -1;
4651 /* Are they requesting a supported attribute? */
4652 if (StrCaseCmp(name, "system.*") == 0 ||
4653 StrnCaseCmp(name, "system.*!", 9) == 0 ||
4654 StrCaseCmp(name, "system.*+") == 0 ||
4655 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
4656 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4657 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
4658 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4659 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
4660 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4661 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4662 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
4663 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4664 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
4665 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4666 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
4667 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4668 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
4669 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4670 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
4671 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4672 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4673 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
4674 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
4676 /* Yup. */
4677 ret = cacl_get(context, ctx, srv,
4678 ipc_srv == NULL ? NULL : &ipc_srv->cli,
4679 &pol, path,
4680 CONST_DISCARD(char *, name),
4681 CONST_DISCARD(char *, value), size);
4682 if (ret < 0 && errno == 0) {
4683 errno = smbc_errno(context, &srv->cli);
4685 talloc_destroy(ctx);
4686 return ret;
4689 /* Unsupported attribute name */
4690 talloc_destroy(ctx);
4691 errno = EINVAL;
4692 return -1;
4696 int smbc_removexattr_ctx(SMBCCTX *context,
4697 const char *fname,
4698 const char *name)
4700 int ret;
4701 SMBCSRV *srv;
4702 SMBCSRV *ipc_srv;
4703 fstring server, share, user, password, workgroup;
4704 pstring path;
4705 TALLOC_CTX *ctx;
4706 POLICY_HND pol;
4708 if (!context || !context->internal ||
4709 !context->internal->_initialized) {
4711 errno = EINVAL; /* Best I can think of ... */
4712 return -1;
4716 if (!fname) {
4718 errno = EINVAL;
4719 return -1;
4723 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
4725 if (smbc_parse_path(context, fname,
4726 server, sizeof(server),
4727 share, sizeof(share),
4728 path, sizeof(path),
4729 user, sizeof(user),
4730 password, sizeof(password),
4731 NULL, 0)) {
4732 errno = EINVAL;
4733 return -1;
4736 if (user[0] == (char)0) fstrcpy(user, context->user);
4738 fstrcpy(workgroup, context->workgroup);
4740 srv = smbc_server(context, server, share, workgroup, user, password);
4741 if (!srv) {
4742 return -1; /* errno set by smbc_server */
4745 if (! srv->no_nt_session) {
4746 ipc_srv = smbc_attr_server(context, server, share,
4747 workgroup, user, password,
4748 &pol);
4749 srv->no_nt_session = True;
4750 } else {
4751 ipc_srv = NULL;
4754 if (! ipc_srv) {
4755 return -1; /* errno set by smbc_attr_server */
4758 ctx = talloc_init("smbc_removexattr");
4759 if (!ctx) {
4760 errno = ENOMEM;
4761 return -1;
4764 /* Are they asking to set the entire ACL? */
4765 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4766 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
4768 /* Yup. */
4769 ret = cacl_set(ctx, &srv->cli,
4770 &ipc_srv->cli, &pol, path,
4771 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
4772 talloc_destroy(ctx);
4773 return ret;
4777 * Are they asking to remove one or more spceific security descriptor
4778 * attributes?
4780 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4781 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4782 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
4783 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4784 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
4785 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4786 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4788 /* Yup. */
4789 ret = cacl_set(ctx, &srv->cli,
4790 &ipc_srv->cli, &pol, path,
4791 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
4792 talloc_destroy(ctx);
4793 return ret;
4796 /* Unsupported attribute name */
4797 talloc_destroy(ctx);
4798 errno = EINVAL;
4799 return -1;
4802 int smbc_listxattr_ctx(SMBCCTX *context,
4803 const char *fname,
4804 char *list,
4805 size_t size)
4808 * This isn't quite what listxattr() is supposed to do. This returns
4809 * the complete set of attribute names, always, rather than only those
4810 * attribute names which actually exist for a file. Hmmm...
4812 const char supported[] =
4813 "system.*\0"
4814 "system.*+\0"
4815 "system.nt_sec_desc.revision\0"
4816 "system.nt_sec_desc.owner\0"
4817 "system.nt_sec_desc.owner+\0"
4818 "system.nt_sec_desc.group\0"
4819 "system.nt_sec_desc.group+\0"
4820 "system.nt_sec_desc.acl.*\0"
4821 "system.nt_sec_desc.acl\0"
4822 "system.nt_sec_desc.acl+\0"
4823 "system.nt_sec_desc.*\0"
4824 "system.nt_sec_desc.*+\0"
4825 "system.dos_attr.*\0"
4826 "system.dos_attr.mode\0"
4827 "system.dos_attr.c_time\0"
4828 "system.dos_attr.a_time\0"
4829 "system.dos_attr.m_time\0"
4832 if (size == 0) {
4833 return sizeof(supported);
4836 if (sizeof(supported) > size) {
4837 errno = ERANGE;
4838 return -1;
4841 /* this can't be strcpy() because there are embedded null characters */
4842 memcpy(list, supported, sizeof(supported));
4843 return sizeof(supported);
4848 * Open a print file to be written to by other calls
4851 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
4853 fstring server, share, user, password;
4854 pstring path;
4856 if (!context || !context->internal ||
4857 !context->internal->_initialized) {
4859 errno = EINVAL;
4860 return NULL;
4864 if (!fname) {
4866 errno = EINVAL;
4867 return NULL;
4871 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
4873 if (smbc_parse_path(context, fname,
4874 server, sizeof(server),
4875 share, sizeof(share),
4876 path, sizeof(path),
4877 user, sizeof(user),
4878 password, sizeof(password),
4879 NULL, 0)) {
4880 errno = EINVAL;
4881 return NULL;
4884 /* What if the path is empty, or the file exists? */
4886 return context->open(context, fname, O_WRONLY, 666);
4891 * Routine to print a file on a remote server ...
4893 * We open the file, which we assume to be on a remote server, and then
4894 * copy it to a print file on the share specified by printq.
4897 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
4899 SMBCFILE *fid1, *fid2;
4900 int bytes, saverr, tot_bytes = 0;
4901 char buf[4096];
4903 if (!c_file || !c_file->internal->_initialized || !c_print ||
4904 !c_print->internal->_initialized) {
4906 errno = EINVAL;
4907 return -1;
4911 if (!fname && !printq) {
4913 errno = EINVAL;
4914 return -1;
4918 /* Try to open the file for reading ... */
4920 if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
4922 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
4923 return -1; /* smbc_open sets errno */
4927 /* Now, try to open the printer file for writing */
4929 if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
4931 saverr = errno; /* Save errno */
4932 c_file->close(c_file, fid1);
4933 errno = saverr;
4934 return -1;
4938 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
4940 tot_bytes += bytes;
4942 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
4944 saverr = errno;
4945 c_file->close(c_file, fid1);
4946 c_print->close(c_print, fid2);
4947 errno = saverr;
4953 saverr = errno;
4955 c_file->close(c_file, fid1); /* We have to close these anyway */
4956 c_print->close(c_print, fid2);
4958 if (bytes < 0) {
4960 errno = saverr;
4961 return -1;
4965 return tot_bytes;
4970 * Routine to list print jobs on a printer share ...
4973 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
4975 SMBCSRV *srv;
4976 fstring server, share, user, password, workgroup;
4977 pstring path;
4979 if (!context || !context->internal ||
4980 !context->internal->_initialized) {
4982 errno = EINVAL;
4983 return -1;
4987 if (!fname) {
4989 errno = EINVAL;
4990 return -1;
4994 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
4996 if (smbc_parse_path(context, fname,
4997 server, sizeof(server),
4998 share, sizeof(share),
4999 path, sizeof(path),
5000 user, sizeof(user),
5001 password, sizeof(password),
5002 NULL, 0)) {
5003 errno = EINVAL;
5004 return -1;
5007 if (user[0] == (char)0) fstrcpy(user, context->user);
5009 fstrcpy(workgroup, context->workgroup);
5011 srv = smbc_server(context, server, share, workgroup, user, password);
5013 if (!srv) {
5015 return -1; /* errno set by smbc_server */
5019 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
5021 errno = smbc_errno(context, &srv->cli);
5022 return -1;
5026 return 0;
5031 * Delete a print job from a remote printer share
5034 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
5036 SMBCSRV *srv;
5037 fstring server, share, user, password, workgroup;
5038 pstring path;
5039 int err;
5041 if (!context || !context->internal ||
5042 !context->internal->_initialized) {
5044 errno = EINVAL;
5045 return -1;
5049 if (!fname) {
5051 errno = EINVAL;
5052 return -1;
5056 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5058 if (smbc_parse_path(context, fname,
5059 server, sizeof(server),
5060 share, sizeof(share),
5061 path, sizeof(path),
5062 user, sizeof(user),
5063 password, sizeof(password),
5064 NULL, 0)) {
5065 errno = EINVAL;
5066 return -1;
5069 if (user[0] == (char)0) fstrcpy(user, context->user);
5071 fstrcpy(workgroup, context->workgroup);
5073 srv = smbc_server(context, server, share, workgroup, user, password);
5075 if (!srv) {
5077 return -1; /* errno set by smbc_server */
5081 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5083 if (err < 0)
5084 errno = smbc_errno(context, &srv->cli);
5085 else if (err == ERRnosuchprintjob)
5086 errno = EINVAL;
5087 return -1;
5091 return 0;
5096 * Get a new empty handle to fill in with your own info
5098 SMBCCTX * smbc_new_context(void)
5100 SMBCCTX * context;
5102 context = SMB_MALLOC_P(SMBCCTX);
5103 if (!context) {
5104 errno = ENOMEM;
5105 return NULL;
5108 ZERO_STRUCTP(context);
5110 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5111 if (!context->internal) {
5112 errno = ENOMEM;
5113 return NULL;
5116 ZERO_STRUCTP(context->internal);
5119 /* ADD REASONABLE DEFAULTS */
5120 context->debug = 0;
5121 context->timeout = 20000; /* 20 seconds */
5123 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5124 context->options.urlencode_readdir_entries = False;/* backward compat */
5125 context->options.one_share_per_server = False;/* backward compat */
5127 context->open = smbc_open_ctx;
5128 context->creat = smbc_creat_ctx;
5129 context->read = smbc_read_ctx;
5130 context->write = smbc_write_ctx;
5131 context->close = smbc_close_ctx;
5132 context->unlink = smbc_unlink_ctx;
5133 context->rename = smbc_rename_ctx;
5134 context->lseek = smbc_lseek_ctx;
5135 context->stat = smbc_stat_ctx;
5136 context->fstat = smbc_fstat_ctx;
5137 context->opendir = smbc_opendir_ctx;
5138 context->closedir = smbc_closedir_ctx;
5139 context->readdir = smbc_readdir_ctx;
5140 context->getdents = smbc_getdents_ctx;
5141 context->mkdir = smbc_mkdir_ctx;
5142 context->rmdir = smbc_rmdir_ctx;
5143 context->telldir = smbc_telldir_ctx;
5144 context->lseekdir = smbc_lseekdir_ctx;
5145 context->fstatdir = smbc_fstatdir_ctx;
5146 context->chmod = smbc_chmod_ctx;
5147 context->utimes = smbc_utimes_ctx;
5148 context->setxattr = smbc_setxattr_ctx;
5149 context->getxattr = smbc_getxattr_ctx;
5150 context->removexattr = smbc_removexattr_ctx;
5151 context->listxattr = smbc_listxattr_ctx;
5152 context->open_print_job = smbc_open_print_job_ctx;
5153 context->print_file = smbc_print_file_ctx;
5154 context->list_print_jobs = smbc_list_print_jobs_ctx;
5155 context->unlink_print_job = smbc_unlink_print_job_ctx;
5157 context->callbacks.check_server_fn = smbc_check_server;
5158 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5160 smbc_default_cache_functions(context);
5162 return context;
5166 * Free a context
5168 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5169 * and thus you'll be leaking memory if not handled properly.
5172 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
5174 if (!context) {
5175 errno = EBADF;
5176 return 1;
5179 if (shutdown_ctx) {
5180 SMBCFILE * f;
5181 DEBUG(1,("Performing aggressive shutdown.\n"));
5183 f = context->internal->_files;
5184 while (f) {
5185 context->close(context, f);
5186 f = f->next;
5188 context->internal->_files = NULL;
5190 /* First try to remove the servers the nice way. */
5191 if (context->callbacks.purge_cached_fn(context)) {
5192 SMBCSRV * s;
5193 SMBCSRV * next;
5194 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
5195 s = context->internal->_servers;
5196 while (s) {
5197 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
5198 cli_shutdown(&s->cli);
5199 context->callbacks.remove_cached_srv_fn(context, s);
5200 next = s->next;
5201 DLIST_REMOVE(context->internal->_servers, s);
5202 SAFE_FREE(s);
5203 s = next;
5205 context->internal->_servers = NULL;
5208 else {
5209 /* This is the polite way */
5210 if (context->callbacks.purge_cached_fn(context)) {
5211 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
5212 errno = EBUSY;
5213 return 1;
5215 if (context->internal->_servers) {
5216 DEBUG(1, ("Active servers in context, free_context failed.\n"));
5217 errno = EBUSY;
5218 return 1;
5220 if (context->internal->_files) {
5221 DEBUG(1, ("Active files in context, free_context failed.\n"));
5222 errno = EBUSY;
5223 return 1;
5227 /* Things we have to clean up */
5228 SAFE_FREE(context->workgroup);
5229 SAFE_FREE(context->netbios_name);
5230 SAFE_FREE(context->user);
5232 DEBUG(3, ("Context %p succesfully freed\n", context));
5233 SAFE_FREE(context->internal);
5234 SAFE_FREE(context);
5235 return 0;
5240 * Initialise the library etc
5242 * We accept a struct containing handle information.
5243 * valid values for info->debug from 0 to 100,
5244 * and insist that info->fn must be non-null.
5246 SMBCCTX * smbc_init_context(SMBCCTX * context)
5248 pstring conf;
5249 int pid;
5250 char *user = NULL, *home = NULL;
5252 if (!context || !context->internal) {
5253 errno = EBADF;
5254 return NULL;
5257 /* Do not initialise the same client twice */
5258 if (context->internal->_initialized) {
5259 return 0;
5262 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
5264 errno = EINVAL;
5265 return NULL;
5269 if (!smbc_initialized) {
5270 /* Do some library wide intialisations the first time we get called */
5272 /* Set this to what the user wants */
5273 DEBUGLEVEL = context->debug;
5275 setup_logging( "libsmbclient", True);
5277 /* Here we would open the smb.conf file if needed ... */
5279 home = getenv("HOME");
5281 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5283 load_interfaces(); /* Load the list of interfaces ... */
5285 in_client = True; /* FIXME, make a param */
5287 if (!lp_load(conf, True, False, False)) {
5290 * Well, if that failed, try the dyn_CONFIGFILE
5291 * Which points to the standard locn, and if that
5292 * fails, silently ignore it and use the internal
5293 * defaults ...
5296 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
5297 DEBUG(5, ("Could not load either config file: "
5298 "%s or %s\n",
5299 conf, dyn_CONFIGFILE));
5300 } else {
5302 * We loaded the global config file. Now lets
5303 * load user-specific modifications to the
5304 * global config.
5306 slprintf(conf, sizeof(conf),
5307 "%s/.smb/smb.conf.append", home);
5308 if (!lp_load(conf, True, False, False)) {
5309 DEBUG(10,
5310 ("Could not append config file: "
5311 "%s\n",
5312 conf));
5317 reopen_logs(); /* Get logging working ... */
5320 * Block SIGPIPE (from lib/util_sock.c: write())
5321 * It is not needed and should not stop execution
5323 BlockSignals(True, SIGPIPE);
5325 /* Done with one-time initialisation */
5326 smbc_initialized = 1;
5330 if (!context->user) {
5332 * FIXME: Is this the best way to get the user info?
5334 user = getenv("USER");
5335 /* walk around as "guest" if no username can be found */
5336 if (!user) context->user = SMB_STRDUP("guest");
5337 else context->user = SMB_STRDUP(user);
5340 if (!context->netbios_name) {
5342 * We try to get our netbios name from the config. If that fails we fall
5343 * back on constructing our netbios name from our hostname etc
5345 if (global_myname()) {
5346 context->netbios_name = SMB_STRDUP(global_myname());
5348 else {
5350 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
5352 pid = sys_getpid();
5353 context->netbios_name = SMB_MALLOC(17);
5354 if (!context->netbios_name) {
5355 errno = ENOMEM;
5356 return NULL;
5358 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
5362 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
5364 if (!context->workgroup) {
5365 if (lp_workgroup()) {
5366 context->workgroup = SMB_STRDUP(lp_workgroup());
5368 else {
5369 /* TODO: Think about a decent default workgroup */
5370 context->workgroup = SMB_STRDUP("samba");
5374 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
5376 /* shortest timeout is 1 second */
5377 if (context->timeout > 0 && context->timeout < 1000)
5378 context->timeout = 1000;
5381 * FIXME: Should we check the function pointers here?
5384 context->internal->_initialized = 1;
5386 return context;
5390 /* Return the verion of samba, and thus libsmbclient */
5391 const char *
5392 smbc_version(void)
5394 return samba_version_string();