r6369: update release notes
[Samba.git] / source / libsmb / libsmbclient.c
blob3e8e604ab11488380f78c07e12aa8e66e7bd970e
1 /*
2 Unix SMB/Netbios implementation.
3 SMB client library implementation
4 Copyright (C) Andrew Tridgell 1998
5 Copyright (C) Richard Sharpe 2000, 2002
6 Copyright (C) John Terpstra 2000
7 Copyright (C) Tom Jansen (Ninja ISD) 2002
8 Copyright (C) Derrell Lipman 2003, 2004
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 #include "includes.h"
27 #include "include/libsmb_internal.h"
31 * DOS Attribute values (used internally)
33 typedef struct DOS_ATTR_DESC
35 int mode;
36 unsigned long long size;
37 time_t a_time;
38 time_t c_time;
39 time_t m_time;
40 unsigned long long inode;
41 } DOS_ATTR_DESC;
45 * Internal flags for extended attributes
48 /* internal mode values */
49 #define SMBC_XATTR_MODE_ADD 1
50 #define SMBC_XATTR_MODE_REMOVE 2
51 #define SMBC_XATTR_MODE_REMOVE_ALL 3
52 #define SMBC_XATTR_MODE_SET 4
53 #define SMBC_XATTR_MODE_CHOWN 5
54 #define SMBC_XATTR_MODE_CHGRP 6
56 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
58 /*We should test for this in configure ... */
59 #ifndef ENOTSUP
60 #define ENOTSUP EOPNOTSUPP
61 #endif
64 * Functions exported by libsmb_cache.c that we need here
66 int smbc_default_cache_functions(SMBCCTX *context);
68 /*
69 * check if an element is part of the list.
70 * FIXME: Does not belong here !
71 * Can anyone put this in a macro in dlinklist.h ?
72 * -- Tom
74 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
75 if (!p || !list) return False;
76 do {
77 if (p == list) return True;
78 list = list->next;
79 } while (list);
80 return False;
83 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file);
84 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence);
86 extern BOOL in_client;
89 * Is the logging working / configfile read ?
91 static int smbc_initialized = 0;
93 static int
94 hex2int( unsigned int _char )
96 if ( _char >= 'A' && _char <='F')
97 return _char - 'A' + 10;
98 if ( _char >= 'a' && _char <='f')
99 return _char - 'a' + 10;
100 if ( _char >= '0' && _char <='9')
101 return _char - '0';
102 return -1;
106 * smbc_urldecode()
108 * Convert strings of %xx to their single character equivalent. Each 'x' must
109 * be a valid hexadecimal digit, or that % sequence is left undecoded.
111 * dest may, but need not be, the same pointer as src.
113 * Returns the number of % sequences which could not be converted due to lack
114 * of two following hexadecimal digits.
117 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
119 int old_length = strlen(src);
120 int i = 0;
121 int err_count = 0;
122 pstring temp;
123 char * p;
125 if ( old_length == 0 ) {
126 return 0;
129 p = temp;
130 while ( i < old_length ) {
131 unsigned char character = src[ i++ ];
133 if (character == '%') {
134 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
135 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
137 /* Replace valid sequence */
138 if (a != -1 && b != -1) {
140 /* Replace valid %xx sequence with %dd */
141 character = (a * 16) + b;
143 if (character == '\0') {
144 break; /* Stop at %00 */
147 i += 2;
148 } else {
150 err_count++;
154 *p++ = character;
157 *p = '\0';
159 strncpy(dest, temp, max_dest_len);
161 return err_count;
165 * smbc_urlencode()
167 * Convert any characters not specifically allowed in a URL into their %xx
168 * equivalent.
170 * Returns the remaining buffer length.
173 smbc_urlencode(char * dest, char * src, int max_dest_len)
175 char hex[] = "0123456789ABCDEF";
177 for (; *src != '\0' && max_dest_len >= 3; src++) {
179 if ((*src < '0' &&
180 *src != '-' &&
181 *src != '.') ||
182 (*src > '9' &&
183 *src < 'A') ||
184 (*src > 'Z' &&
185 *src < 'a' &&
186 *src != '_') ||
187 (*src > 'z')) {
188 *dest++ = '%';
189 *dest++ = hex[(*src >> 4) & 0x0f];
190 *dest++ = hex[*src & 0x0f];
191 max_dest_len -= 3;
192 } else {
193 *dest++ = *src;
194 max_dest_len--;
198 *dest++ = '\0';
199 max_dest_len--;
201 return max_dest_len;
205 * Function to parse a path and turn it into components
207 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
208 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
209 * general format ("smb:" only; we do not look for "cifs:").
212 * We accept:
213 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
215 * Meaning of URLs:
217 * smb:// Show all workgroups.
219 * The method of locating the list of workgroups varies
220 * depending upon the setting of the context variable
221 * context->options.browse_max_lmb_count. This value
222 * determine the maximum number of local master browsers to
223 * query for the list of workgroups. In order to ensure that
224 * a complete list of workgroups is obtained, all master
225 * browsers must be queried, but if there are many
226 * workgroups, the time spent querying can begin to add up.
227 * For small networks (not many workgroups), it is suggested
228 * that this variable be set to 0, indicating query all local
229 * master browsers. When the network has many workgroups, a
230 * reasonable setting for this variable might be around 3.
232 * smb://name/ if name<1D> or name<1B> exists, list servers in
233 * workgroup, else, if name<20> exists, list all shares
234 * for server ...
236 * If "options" are provided, this function returns the entire option list as a
237 * string, for later parsing by the caller. Note that currently, no options
238 * are supported.
241 static const char *smbc_prefix = "smb:";
243 static int
244 smbc_parse_path(SMBCCTX *context,
245 const char *fname,
246 char *server, int server_len,
247 char *share, int share_len,
248 char *path, int path_len,
249 char *user, int user_len,
250 char *password, int password_len,
251 char *options, int options_len)
253 static pstring s;
254 pstring userinfo;
255 const char *p;
256 char *q, *r;
257 int len;
259 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
260 if (options != NULL && options_len > 0) {
261 options[0] = (char)0;
263 pstrcpy(s, fname);
265 /* see if it has the right prefix */
266 len = strlen(smbc_prefix);
267 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
268 return -1; /* What about no smb: ? */
271 p = s + len;
273 /* Watch the test below, we are testing to see if we should exit */
275 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
277 DEBUG(1, ("Invalid path (does not begin with smb://"));
278 return -1;
282 p += 2; /* Skip the double slash */
284 /* See if any options were specified */
285 if ((q = strrchr(p, '?')) != NULL ) {
286 /* There are options. Null terminate here and point to them */
287 *q++ = '\0';
289 DEBUG(4, ("Found options '%s'", q));
291 /* Copy the options */
292 if (options != NULL && options_len > 0) {
293 safe_strcpy(options, q, options_len - 1);
297 if (*p == (char)0)
298 goto decoding;
300 if (*p == '/') {
302 strncpy(server, context->workgroup,
303 (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
304 return 0;
309 * ok, its for us. Now parse out the server, share etc.
311 * However, we want to parse out [[domain;]user[:password]@] if it
312 * exists ...
315 /* check that '@' occurs before '/', if '/' exists at all */
316 q = strchr_m(p, '@');
317 r = strchr_m(p, '/');
318 if (q && (!r || q < r)) {
319 pstring username, passwd, domain;
320 const char *u = userinfo;
322 next_token(&p, userinfo, "@", sizeof(fstring));
324 username[0] = passwd[0] = domain[0] = 0;
326 if (strchr_m(u, ';')) {
328 next_token(&u, domain, ";", sizeof(fstring));
332 if (strchr_m(u, ':')) {
334 next_token(&u, username, ":", sizeof(fstring));
336 pstrcpy(passwd, u);
339 else {
341 pstrcpy(username, u);
345 if (username[0])
346 strncpy(user, username, user_len); /* FIXME, domain */
348 if (passwd[0])
349 strncpy(password, passwd, password_len);
353 if (!next_token(&p, server, "/", sizeof(fstring))) {
355 return -1;
359 if (*p == (char)0) goto decoding; /* That's it ... */
361 if (!next_token(&p, share, "/", sizeof(fstring))) {
363 return -1;
367 safe_strcpy(path, p, path_len - 1);
369 all_string_sub(path, "/", "\\", 0);
371 decoding:
372 (void) smbc_urldecode(path, path, path_len);
373 (void) smbc_urldecode(server, server, server_len);
374 (void) smbc_urldecode(share, share, share_len);
375 (void) smbc_urldecode(user, user, user_len);
376 (void) smbc_urldecode(password, password, password_len);
378 return 0;
382 * Verify that the options specified in a URL are valid
384 static int smbc_check_options(char *server, char *share, char *path, char *options)
386 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' path='%s' options='%s'\n", server, share, path, options));
388 /* No options at all is always ok */
389 if (! *options) return 0;
391 /* Currently, we don't support any options. */
392 return -1;
396 * Convert an SMB error into a UNIX error ...
398 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
400 int ret = cli_errno(c);
402 if (cli_is_dos_error(c)) {
403 uint8 eclass;
404 uint32 ecode;
406 cli_dos_error(c, &eclass, &ecode);
408 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
409 (int)eclass, (int)ecode, (int)ecode, ret));
410 } else {
411 NTSTATUS status;
413 status = cli_nt_error(c);
415 DEBUG(3,("smbc errno %s -> %d\n",
416 nt_errstr(status), ret));
419 return ret;
423 * Check a server_fd.
424 * returns 0 if the server is in shape. Returns 1 on error
426 * Also useable outside libsmbclient to enable external cache
427 * to do some checks too.
429 int smbc_check_server(SMBCCTX * context, SMBCSRV * server)
431 if ( send_keepalive(server->cli.fd) == False )
432 return 1;
434 /* connection is ok */
435 return 0;
439 * Remove a server from the cached server list it's unused.
440 * On success, 0 is returned. 1 is returned if the server could not be removed.
442 * Also useable outside libsmbclient
444 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
446 SMBCFILE * file;
448 /* are we being fooled ? */
449 if (!context || !context->internal ||
450 !context->internal->_initialized || !srv) return 1;
453 /* Check all open files/directories for a relation with this server */
454 for (file = context->internal->_files; file; file=file->next) {
455 if (file->srv == srv) {
456 /* Still used */
457 DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n",
458 srv, file));
459 return 1;
463 DLIST_REMOVE(context->internal->_servers, srv);
465 cli_shutdown(&srv->cli);
467 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
469 context->callbacks.remove_cached_srv_fn(context, srv);
471 return 0;
474 SMBCSRV *find_server(SMBCCTX *context,
475 const char *server,
476 const char *share,
477 fstring workgroup,
478 fstring username,
479 fstring password)
481 SMBCSRV *srv;
482 int auth_called = 0;
484 check_server_cache:
486 srv = context->callbacks.get_cached_srv_fn(context, server, share,
487 workgroup, username);
489 if (!auth_called && !srv && (!username[0] || !password[0])) {
490 context->callbacks.auth_fn(server, share,
491 workgroup, sizeof(fstring),
492 username, sizeof(fstring),
493 password, sizeof(fstring));
495 * However, smbc_auth_fn may have picked up info relating to
496 * an existing connection, so try for an existing connection
497 * again ...
499 auth_called = 1;
500 goto check_server_cache;
504 if (srv) {
505 if (context->callbacks.check_server_fn(context, srv)) {
507 * This server is no good anymore
508 * Try to remove it and check for more possible
509 * servers in the cache
511 if (context->callbacks.remove_unused_server_fn(context,
512 srv)) {
514 * We could not remove the server completely,
515 * remove it from the cache so we will not get
516 * it again. It will be removed when the last
517 * file/dir is closed.
519 context->callbacks.remove_cached_srv_fn(context,
520 srv);
524 * Maybe there are more cached connections to this
525 * server
527 goto check_server_cache;
530 return srv;
533 return NULL;
537 * Connect to a server, possibly on an existing connection
539 * Here, what we want to do is: If the server and username
540 * match an existing connection, reuse that, otherwise, establish a
541 * new connection.
543 * If we have to create a new connection, call the auth_fn to get the
544 * info we need, unless the username and password were passed in.
547 SMBCSRV *smbc_server(SMBCCTX *context,
548 const char *server, const char *share,
549 fstring workgroup, fstring username,
550 fstring password)
552 SMBCSRV *srv=NULL;
553 struct cli_state c;
554 struct nmb_name called, calling;
555 const char *server_n = server;
556 pstring ipenv;
557 struct in_addr ip;
558 int tried_reverse = 0;
559 int port_try_first;
560 int port_try_next;
561 const char *username_used;
563 zero_ip(&ip);
564 ZERO_STRUCT(c);
566 if (server[0] == 0) {
567 errno = EPERM;
568 return NULL;
571 srv = find_server(context, server, share,
572 workgroup, username, password);
575 * If we found a connection and we're only allowed one share per
576 * server...
578 if (srv && *share != '\0' && context->options.one_share_per_server) {
581 * ... then if there's no current connection to the share,
582 * connect to it. find_server(), or rather the function
583 * pointed to by context->callbacks.get_cached_srv_fn which
584 * was called by find_server(), will have issued a tree
585 * disconnect if the requested share is not the same as the
586 * one that was already connected.
588 if (srv->cli.cnum == (uint16) -1) {
589 /* Ensure we have accurate auth info */
590 context->callbacks.auth_fn(server, share,
591 workgroup, sizeof(fstring),
592 username, sizeof(fstring),
593 password, sizeof(fstring));
595 if (! cli_send_tconX(&srv->cli, share, "?????",
596 password, strlen(password)+1)) {
598 errno = smbc_errno(context, &srv->cli);
599 cli_shutdown(&srv->cli);
600 context->callbacks.remove_cached_srv_fn(context, srv);
601 srv = NULL;
604 /* Regenerate the dev value since it's based on both server and share */
605 if (srv) {
606 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
611 /* If we have a connection... */
612 if (srv) {
614 /* ... then we're done here. Give 'em what they came for. */
615 return srv;
618 make_nmb_name(&calling, context->netbios_name, 0x0);
619 make_nmb_name(&called , server, 0x20);
621 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
623 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
625 again:
626 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
628 zero_ip(&ip);
630 /* have to open a new connection */
631 if (!cli_initialise(&c)) {
632 errno = ENOMEM;
633 return NULL;
636 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
637 c.use_kerberos = True;
639 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
640 c.fallback_after_kerberos = True;
643 c.timeout = context->timeout;
646 * Force use of port 139 for first try if share is $IPC, empty, or
647 * null, so browse lists can work
649 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0)
651 port_try_first = 139;
652 port_try_next = 445;
654 else
656 port_try_first = 445;
657 port_try_next = 139;
660 c.port = port_try_first;
662 if (!cli_connect(&c, server_n, &ip)) {
664 /* First connection attempt failed. Try alternate port. */
665 c.port = port_try_next;
667 if (!cli_connect(&c, server_n, &ip)) {
668 cli_shutdown(&c);
669 errno = ETIMEDOUT;
670 return NULL;
674 if (!cli_session_request(&c, &calling, &called)) {
675 cli_shutdown(&c);
676 if (strcmp(called.name, "*SMBSERVER")) {
677 make_nmb_name(&called , "*SMBSERVER", 0x20);
678 goto again;
680 else { /* Try one more time, but ensure we don't loop */
682 /* Only try this if server is an IP address ... */
684 if (is_ipaddress(server) && !tried_reverse) {
685 fstring remote_name;
686 struct in_addr rem_ip;
688 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
689 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
690 errno = ETIMEDOUT;
691 return NULL;
694 tried_reverse++; /* Yuck */
696 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
697 make_nmb_name(&called, remote_name, 0x20);
698 goto again;
704 errno = ETIMEDOUT;
705 return NULL;
708 DEBUG(4,(" session request ok\n"));
710 if (!cli_negprot(&c)) {
711 cli_shutdown(&c);
712 errno = ETIMEDOUT;
713 return NULL;
716 username_used = username;
718 if (!cli_session_setup(&c, username_used,
719 password, strlen(password),
720 password, strlen(password),
721 workgroup)) {
723 /* Failed. Try an anonymous login, if allowed by flags. */
724 username_used = "";
726 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
727 !cli_session_setup(&c, username_used,
728 password, 1,
729 password, 0,
730 workgroup)) {
732 cli_shutdown(&c);
733 errno = EPERM;
734 return NULL;
738 DEBUG(4,(" session setup ok\n"));
740 if (!cli_send_tconX(&c, share, "?????",
741 password, strlen(password)+1)) {
742 errno = smbc_errno(context, &c);
743 cli_shutdown(&c);
744 return NULL;
747 DEBUG(4,(" tconx ok\n"));
750 * Ok, we have got a nice connection
751 * Let's find a free server_fd
754 srv = SMB_MALLOC_P(SMBCSRV);
755 if (!srv) {
756 errno = ENOMEM;
757 goto failed;
760 ZERO_STRUCTP(srv);
761 srv->cli = c;
762 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
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 a_time = c_time = m_time;
1252 srv->no_pathinfo2 = True;
1253 return True;
1256 errno = EPERM;
1257 return False;
1262 * Routine to unlink() a file
1265 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1267 fstring server, share, user, password, workgroup;
1268 pstring path;
1269 SMBCSRV *srv = NULL;
1271 if (!context || !context->internal ||
1272 !context->internal->_initialized) {
1274 errno = EINVAL; /* Best I can think of ... */
1275 return -1;
1279 if (!fname) {
1281 errno = EINVAL;
1282 return -1;
1286 if (smbc_parse_path(context, fname,
1287 server, sizeof(server),
1288 share, sizeof(share),
1289 path, sizeof(path),
1290 user, sizeof(user),
1291 password, sizeof(password),
1292 NULL, 0)) {
1293 errno = EINVAL;
1294 return -1;
1297 if (user[0] == (char)0) fstrcpy(user, context->user);
1299 fstrcpy(workgroup, context->workgroup);
1301 srv = smbc_server(context, server, share, workgroup, user, password);
1303 if (!srv) {
1305 return -1; /* smbc_server sets errno */
1309 /* if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
1311 int job = smbc_stat_printjob(srv, path, NULL, NULL);
1312 if (job == -1) {
1314 return -1;
1317 if ((err = cli_printjob_del(&srv->cli, job)) != 0) {
1320 return -1;
1323 } else */
1325 if (!cli_unlink(&srv->cli, path)) {
1327 errno = smbc_errno(context, &srv->cli);
1329 if (errno == EACCES) { /* Check if the file is a directory */
1331 int saverr = errno;
1332 SMB_OFF_T size = 0;
1333 uint16 mode = 0;
1334 time_t m_time = 0, a_time = 0, c_time = 0;
1335 SMB_INO_T ino = 0;
1337 if (!smbc_getatr(context, srv, path, &mode, &size,
1338 &c_time, &a_time, &m_time, &ino)) {
1340 /* Hmmm, bad error ... What? */
1342 errno = smbc_errno(context, &srv->cli);
1343 return -1;
1346 else {
1348 if (IS_DOS_DIR(mode))
1349 errno = EISDIR;
1350 else
1351 errno = saverr; /* Restore this */
1356 return -1;
1360 return 0; /* Success ... */
1365 * Routine to rename() a file
1368 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1369 SMBCCTX *ncontext, const char *nname)
1371 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1372 pstring path1, path2;
1373 SMBCSRV *srv = NULL;
1375 if (!ocontext || !ncontext ||
1376 !ocontext->internal || !ncontext->internal ||
1377 !ocontext->internal->_initialized ||
1378 !ncontext->internal->_initialized) {
1380 errno = EINVAL; /* Best I can think of ... */
1381 return -1;
1385 if (!oname || !nname) {
1387 errno = EINVAL;
1388 return -1;
1392 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1394 smbc_parse_path(ocontext, oname,
1395 server1, sizeof(server1),
1396 share1, sizeof(share1),
1397 path1, sizeof(path1),
1398 user1, sizeof(user1),
1399 password1, sizeof(password1),
1400 NULL, 0);
1402 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1404 smbc_parse_path(ncontext, nname,
1405 server2, sizeof(server2),
1406 share2, sizeof(share2),
1407 path2, sizeof(path2),
1408 user2, sizeof(user2),
1409 password2, sizeof(password2),
1410 NULL, 0);
1412 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1414 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1415 strcmp(user1, user2)) {
1417 /* Can't rename across file systems, or users?? */
1419 errno = EXDEV;
1420 return -1;
1424 fstrcpy(workgroup, ocontext->workgroup);
1425 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1426 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1427 if (!srv) {
1429 return -1;
1433 if (!cli_rename(&srv->cli, path1, path2)) {
1434 int eno = smbc_errno(ocontext, &srv->cli);
1436 if (eno != EEXIST ||
1437 !cli_unlink(&srv->cli, path2) ||
1438 !cli_rename(&srv->cli, path1, path2)) {
1440 errno = eno;
1441 return -1;
1446 return 0; /* Success */
1451 * A routine to lseek() a file
1454 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1456 SMB_OFF_T size;
1458 if (!context || !context->internal ||
1459 !context->internal->_initialized) {
1461 errno = EINVAL;
1462 return -1;
1466 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1468 errno = EBADF;
1469 return -1;
1473 if (!file->file) {
1475 errno = EINVAL;
1476 return -1; /* Can't lseek a dir ... */
1480 switch (whence) {
1481 case SEEK_SET:
1482 file->offset = offset;
1483 break;
1485 case SEEK_CUR:
1486 file->offset += offset;
1487 break;
1489 case SEEK_END:
1490 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
1491 NULL, NULL, NULL))
1493 SMB_BIG_UINT b_size = size;
1494 if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
1495 NULL))
1497 errno = EINVAL;
1498 return -1;
1499 } else
1500 size = b_size;
1502 file->offset = size + offset;
1503 break;
1505 default:
1506 errno = EINVAL;
1507 break;
1511 return file->offset;
1516 * Generate an inode number from file name for those things that need it
1519 static
1520 ino_t smbc_inode(SMBCCTX *context, const char *name)
1523 if (!context || !context->internal ||
1524 !context->internal->_initialized) {
1526 errno = EINVAL;
1527 return -1;
1531 if (!*name) return 2; /* FIXME, why 2 ??? */
1532 return (ino_t)str_checksum(name);
1537 * Routine to put basic stat info into a stat structure ... Used by stat and
1538 * fstat below.
1541 static
1542 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname,
1543 SMB_OFF_T size, int mode)
1546 st->st_mode = 0;
1548 if (IS_DOS_DIR(mode)) {
1549 st->st_mode = SMBC_DIR_MODE;
1550 } else {
1551 st->st_mode = SMBC_FILE_MODE;
1554 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1555 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1556 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1557 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1559 st->st_size = size;
1560 #ifdef HAVE_STAT_ST_BLKSIZE
1561 st->st_blksize = 512;
1562 #endif
1563 #ifdef HAVE_STAT_ST_BLOCKS
1564 st->st_blocks = (size+511)/512;
1565 #endif
1566 st->st_uid = getuid();
1567 st->st_gid = getgid();
1569 if (IS_DOS_DIR(mode)) {
1570 st->st_nlink = 2;
1571 } else {
1572 st->st_nlink = 1;
1575 if (st->st_ino == 0) {
1576 st->st_ino = smbc_inode(context, fname);
1579 return True; /* FIXME: Is this needed ? */
1584 * Routine to stat a file given a name
1587 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1589 SMBCSRV *srv;
1590 fstring server, share, user, password, workgroup;
1591 pstring path;
1592 time_t m_time = 0, a_time = 0, c_time = 0;
1593 SMB_OFF_T size = 0;
1594 uint16 mode = 0;
1595 SMB_INO_T ino = 0;
1597 if (!context || !context->internal ||
1598 !context->internal->_initialized) {
1600 errno = EINVAL; /* Best I can think of ... */
1601 return -1;
1605 if (!fname) {
1607 errno = EINVAL;
1608 return -1;
1612 DEBUG(4, ("smbc_stat(%s)\n", fname));
1614 if (smbc_parse_path(context, fname,
1615 server, sizeof(server),
1616 share, sizeof(share),
1617 path, sizeof(path),
1618 user, sizeof(user),
1619 password, sizeof(password),
1620 NULL, 0)) {
1621 errno = EINVAL;
1622 return -1;
1625 if (user[0] == (char)0) fstrcpy(user, context->user);
1627 fstrcpy(workgroup, context->workgroup);
1629 srv = smbc_server(context, server, share, workgroup, user, password);
1631 if (!srv) {
1632 return -1; /* errno set by smbc_server */
1635 if (!smbc_getatr(context, srv, path, &mode, &size,
1636 &c_time, &a_time, &m_time, &ino)) {
1638 errno = smbc_errno(context, &srv->cli);
1639 return -1;
1643 st->st_ino = ino;
1645 smbc_setup_stat(context, st, path, size, mode);
1647 st->st_atime = a_time;
1648 st->st_ctime = c_time;
1649 st->st_mtime = m_time;
1650 st->st_dev = srv->dev;
1652 return 0;
1657 * Routine to stat a file given an fd
1660 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1662 time_t c_time, a_time, m_time;
1663 SMB_OFF_T size;
1664 uint16 mode;
1665 SMB_INO_T ino = 0;
1667 if (!context || !context->internal ||
1668 !context->internal->_initialized) {
1670 errno = EINVAL;
1671 return -1;
1675 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1677 errno = EBADF;
1678 return -1;
1682 if (!file->file) {
1684 return context->fstatdir(context, file, st);
1688 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
1689 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
1690 if (!cli_getattrE(&file->srv->cli, file->cli_fd,
1691 &mode, &size, &c_time, &a_time, &m_time)) {
1693 errno = EINVAL;
1694 return -1;
1698 st->st_ino = ino;
1700 smbc_setup_stat(context, st, file->fname, size, mode);
1702 st->st_atime = a_time;
1703 st->st_ctime = c_time;
1704 st->st_mtime = m_time;
1705 st->st_dev = file->srv->dev;
1707 return 0;
1712 * Routine to open a directory
1713 * We accept the URL syntax explained in smbc_parse_path(), above.
1716 static void smbc_remove_dir(SMBCFILE *dir)
1718 struct smbc_dir_list *d,*f;
1720 d = dir->dir_list;
1721 while (d) {
1723 f = d; d = d->next;
1725 SAFE_FREE(f->dirent);
1726 SAFE_FREE(f);
1730 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
1734 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
1736 struct smbc_dirent *dirent;
1737 int size;
1738 int name_length = (name == NULL ? 0 : strlen(name));
1739 int comment_len = (comment == NULL ? 0 : strlen(comment));
1742 * Allocate space for the dirent, which must be increased by the
1743 * size of the name and the comment and 1 each for the null terminator.
1746 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
1748 dirent = SMB_MALLOC(size);
1750 if (!dirent) {
1752 dir->dir_error = ENOMEM;
1753 return -1;
1757 ZERO_STRUCTP(dirent);
1759 if (dir->dir_list == NULL) {
1761 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
1762 if (!dir->dir_list) {
1764 SAFE_FREE(dirent);
1765 dir->dir_error = ENOMEM;
1766 return -1;
1769 ZERO_STRUCTP(dir->dir_list);
1771 dir->dir_end = dir->dir_next = dir->dir_list;
1773 else {
1775 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
1777 if (!dir->dir_end->next) {
1779 SAFE_FREE(dirent);
1780 dir->dir_error = ENOMEM;
1781 return -1;
1784 ZERO_STRUCTP(dir->dir_end->next);
1786 dir->dir_end = dir->dir_end->next;
1789 dir->dir_end->next = NULL;
1790 dir->dir_end->dirent = dirent;
1792 dirent->smbc_type = type;
1793 dirent->namelen = name_length;
1794 dirent->commentlen = comment_len;
1795 dirent->dirlen = size;
1797 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
1799 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
1800 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
1802 return 0;
1806 static void
1807 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
1809 SMBCFILE *dir = (SMBCFILE *)state;
1810 struct smbc_dir_list *dir_list;
1811 struct smbc_dirent *dirent;
1812 int dirent_type;
1813 int do_remove = 0;
1815 dirent_type = dir->dir_type;
1817 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1819 /* An error occurred, what do we do? */
1820 /* FIXME: Add some code here */
1823 /* Point to the one just added */
1824 dirent = dir->dir_end->dirent;
1826 /* See if this was a duplicate */
1827 for (dir_list = dir->dir_list;
1828 dir_list != dir->dir_end;
1829 dir_list = dir_list->next) {
1830 if (! do_remove &&
1831 strcmp(dir_list->dirent->name, dirent->name) == 0) {
1832 /* Duplicate. End end of list need to be removed. */
1833 do_remove = 1;
1836 if (do_remove && dir_list->next == dir->dir_end) {
1837 /* Found the end of the list. Remove it. */
1838 dir->dir_end = dir_list;
1839 free(dir_list->next);
1840 dir_list->next = NULL;
1841 break;
1846 static void
1847 list_fn(const char *name, uint32 type, const char *comment, void *state)
1849 SMBCFILE *dir = (SMBCFILE *)state;
1850 int dirent_type;
1852 /* We need to process the type a little ... */
1854 if (dir->dir_type == SMBC_FILE_SHARE) {
1856 switch (type) {
1857 case 0: /* Directory tree */
1858 dirent_type = SMBC_FILE_SHARE;
1859 break;
1861 case 1:
1862 dirent_type = SMBC_PRINTER_SHARE;
1863 break;
1865 case 2:
1866 dirent_type = SMBC_COMMS_SHARE;
1867 break;
1869 case 3:
1870 dirent_type = SMBC_IPC_SHARE;
1871 break;
1873 default:
1874 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
1875 break;
1878 else dirent_type = dir->dir_type;
1880 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1882 /* An error occurred, what do we do? */
1883 /* FIXME: Add some code here */
1888 static void
1889 dir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
1892 if (add_dirent((SMBCFILE *)state, finfo->name, "",
1893 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
1895 /* Handle an error ... */
1897 /* FIXME: Add some code ... */
1903 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
1905 fstring server, share, user, password, options;
1906 pstring workgroup;
1907 pstring path;
1908 SMBCSRV *srv = NULL;
1909 SMBCFILE *dir = NULL;
1910 struct in_addr rem_ip;
1912 if (!context || !context->internal ||
1913 !context->internal->_initialized) {
1914 DEBUG(4, ("no valid context\n"));
1915 errno = EINVAL + 8192;
1916 return NULL;
1920 if (!fname) {
1921 DEBUG(4, ("no valid fname\n"));
1922 errno = EINVAL + 8193;
1923 return NULL;
1926 if (smbc_parse_path(context, fname,
1927 server, sizeof(server),
1928 share, sizeof(share),
1929 path, sizeof(path),
1930 user, sizeof(user),
1931 password, sizeof(password),
1932 options, sizeof(options))) {
1933 DEBUG(4, ("no valid path\n"));
1934 errno = EINVAL + 8194;
1935 return NULL;
1938 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
1940 /* Ensure the options are valid */
1941 if (smbc_check_options(server, share, path, options)) {
1942 DEBUG(4, ("unacceptable options (%s)\n", options));
1943 errno = EINVAL + 8195;
1944 return NULL;
1947 if (user[0] == (char)0) fstrcpy(user, context->user);
1949 pstrcpy(workgroup, context->workgroup);
1951 dir = SMB_MALLOC_P(SMBCFILE);
1953 if (!dir) {
1955 errno = ENOMEM;
1956 return NULL;
1960 ZERO_STRUCTP(dir);
1962 dir->cli_fd = 0;
1963 dir->fname = SMB_STRDUP(fname);
1964 dir->srv = NULL;
1965 dir->offset = 0;
1966 dir->file = False;
1967 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
1969 if (server[0] == (char)0) {
1971 int i;
1972 int count;
1973 int max_lmb_count;
1974 struct ip_service *ip_list;
1975 struct ip_service server_addr;
1976 struct user_auth_info u_info;
1977 struct cli_state *cli;
1979 if (share[0] != (char)0 || path[0] != (char)0) {
1981 errno = EINVAL + 8196;
1982 if (dir) {
1983 SAFE_FREE(dir->fname);
1984 SAFE_FREE(dir);
1986 return NULL;
1989 /* Determine how many local master browsers to query */
1990 max_lmb_count = (context->options.browse_max_lmb_count == 0
1991 ? INT_MAX
1992 : context->options.browse_max_lmb_count);
1994 pstrcpy(u_info.username, user);
1995 pstrcpy(u_info.password, password);
1998 * We have server and share and path empty but options
1999 * requesting that we scan all master browsers for their list
2000 * of workgroups/domains. This implies that we must first try
2001 * broadcast queries to find all master browsers, and if that
2002 * doesn't work, then try our other methods which return only
2003 * a single master browser.
2006 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2007 if (!find_master_ip(workgroup, &server_addr.ip)) {
2009 errno = ENOENT;
2010 return NULL;
2013 ip_list = &server_addr;
2014 count = 1;
2017 for (i = 0; i < count && i < max_lmb_count; i++) {
2018 DEBUG(99, ("Found master browser %d of %d: %s\n", i+1, MAX(count, max_lmb_count), inet_ntoa(ip_list[i].ip)));
2020 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2021 /* cli == NULL is the master browser refused to talk or
2022 could not be found */
2023 if ( !cli )
2024 continue;
2026 fstrcpy(server, cli->desthost);
2027 cli_shutdown(cli);
2029 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2032 * For each returned master browser IP address, get a
2033 * connection to IPC$ on the server if we do not
2034 * already have one, and determine the
2035 * workgroups/domains that it knows about.
2038 srv = smbc_server(context, server,
2039 "IPC$", workgroup, user, password);
2040 if (!srv) {
2041 continue;
2044 dir->srv = srv;
2045 dir->dir_type = SMBC_WORKGROUP;
2047 /* Now, list the stuff ... */
2049 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2050 (void *)dir)) {
2052 continue;
2055 } else {
2057 * Server not an empty string ... Check the rest and see what
2058 * gives
2060 if (share[0] == (char)0) {
2062 if (path[0] != (char)0) { /* Should not have empty share with path */
2064 errno = EINVAL + 8197;
2065 if (dir) {
2066 SAFE_FREE(dir->fname);
2067 SAFE_FREE(dir);
2069 return NULL;
2073 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2074 /* However, we check to see if <server> is an IP address first */
2076 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2077 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2078 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2079 fstring buserver;
2081 dir->dir_type = SMBC_SERVER;
2084 * Get the backup list ...
2088 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2090 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2091 errno = EPERM; /* FIXME, is this correct */
2092 return NULL;
2097 * Get a connection to IPC$ on the server if we do not already have one
2100 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2102 if (!srv) {
2103 DEBUG(0, ("got no contact to IPC$\n"));
2104 if (dir) {
2105 SAFE_FREE(dir->fname);
2106 SAFE_FREE(dir);
2108 return NULL;
2112 dir->srv = srv;
2114 /* Now, list the servers ... */
2116 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2117 (void *)dir)) {
2119 if (dir) {
2120 SAFE_FREE(dir->fname);
2121 SAFE_FREE(dir);
2123 return NULL;
2127 else {
2129 if (resolve_name(server, &rem_ip, 0x20)) {
2131 /* Now, list the shares ... */
2133 dir->dir_type = SMBC_FILE_SHARE;
2135 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2137 if (!srv) {
2139 if (dir) {
2140 SAFE_FREE(dir->fname);
2141 SAFE_FREE(dir);
2143 return NULL;
2147 dir->srv = srv;
2149 /* Now, list the servers ... */
2151 if (cli_RNetShareEnum(&srv->cli, list_fn,
2152 (void *)dir) < 0) {
2154 errno = cli_errno(&srv->cli);
2155 if (dir) {
2156 SAFE_FREE(dir->fname);
2157 SAFE_FREE(dir);
2159 return NULL;
2164 else {
2166 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2167 if (dir) {
2168 SAFE_FREE(dir->fname);
2169 SAFE_FREE(dir);
2171 return NULL;
2178 else { /* The server and share are specified ... work from there ... */
2180 /* Well, we connect to the server and list the directory */
2182 dir->dir_type = SMBC_FILE_SHARE;
2184 srv = smbc_server(context, server, share, workgroup, user, password);
2186 if (!srv) {
2188 if (dir) {
2189 SAFE_FREE(dir->fname);
2190 SAFE_FREE(dir);
2192 return NULL;
2196 dir->srv = srv;
2198 /* Now, list the files ... */
2200 pstrcat(path, "\\*");
2202 if (cli_list(&srv->cli, path, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2203 (void *)dir) < 0) {
2205 if (dir) {
2206 SAFE_FREE(dir->fname);
2207 SAFE_FREE(dir);
2209 errno = smbc_errno(context, &srv->cli);
2210 return NULL;
2217 DLIST_ADD(context->internal->_files, dir);
2218 return dir;
2223 * Routine to close a directory
2226 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2229 if (!context || !context->internal ||
2230 !context->internal->_initialized) {
2232 errno = EINVAL;
2233 return -1;
2237 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2239 errno = EBADF;
2240 return -1;
2244 smbc_remove_dir(dir); /* Clean it up */
2246 DLIST_REMOVE(context->internal->_files, dir);
2248 if (dir) {
2250 SAFE_FREE(dir->fname);
2251 SAFE_FREE(dir); /* Free the space too */
2254 return 0;
2258 static void smbc_readdir_internal(SMBCCTX * context,
2259 struct smbc_dirent *dest,
2260 struct smbc_dirent *src,
2261 int max_namebuf_len)
2263 if (context->options.urlencode_readdir_entries) {
2265 /* url-encode the name. get back remaining buffer space */
2266 max_namebuf_len =
2267 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2269 /* We now know the name length */
2270 dest->namelen = strlen(dest->name);
2272 /* Save the pointer to the beginning of the comment */
2273 dest->comment = dest->name + dest->namelen + 1;
2275 /* Copy the comment */
2276 strncpy(dest->comment, src->comment, max_namebuf_len);
2278 /* Ensure the comment is null terminated */
2279 if (max_namebuf_len > src->commentlen) {
2280 dest->comment[src->commentlen] = '\0';
2281 } else {
2282 dest->comment[max_namebuf_len - 1] = '\0';
2285 /* Save other fields */
2286 dest->smbc_type = src->smbc_type;
2287 dest->commentlen = strlen(dest->comment);
2288 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2289 (char *) dest);
2290 } else {
2292 /* No encoding. Just copy the entry as is. */
2293 memcpy(dest, src, src->dirlen);
2294 dest->comment = (char *)(&dest->name + src->namelen + 1);
2300 * Routine to get a directory entry
2303 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2305 int maxlen;
2306 struct smbc_dirent *dirp, *dirent;
2308 /* Check that all is ok first ... */
2310 if (!context || !context->internal ||
2311 !context->internal->_initialized) {
2313 errno = EINVAL;
2314 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2315 return NULL;
2319 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2321 errno = EBADF;
2322 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2323 return NULL;
2327 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2329 errno = ENOTDIR;
2330 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2331 return NULL;
2335 if (!dir->dir_next) {
2336 return NULL;
2339 dirent = dir->dir_next->dirent;
2340 if (!dirent) {
2342 errno = ENOENT;
2343 return NULL;
2347 dirp = (struct smbc_dirent *)context->internal->_dirent;
2348 maxlen = (sizeof(context->internal->_dirent) -
2349 sizeof(struct smbc_dirent));
2351 smbc_readdir_internal(context, dirp, dirent, maxlen);
2353 dir->dir_next = dir->dir_next->next;
2355 return dirp;
2359 * Routine to get directory entries
2362 static int smbc_getdents_ctx(SMBCCTX *context,
2363 SMBCFILE *dir,
2364 struct smbc_dirent *dirp,
2365 int count)
2367 int rem = count;
2368 int reqd;
2369 int maxlen;
2370 char *ndir = (char *)dirp;
2371 struct smbc_dir_list *dirlist;
2373 /* Check that all is ok first ... */
2375 if (!context || !context->internal ||
2376 !context->internal->_initialized) {
2378 errno = EINVAL;
2379 return -1;
2383 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2385 errno = EBADF;
2386 return -1;
2390 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2392 errno = ENOTDIR;
2393 return -1;
2398 * Now, retrieve the number of entries that will fit in what was passed
2399 * We have to figure out if the info is in the list, or we need to
2400 * send a request to the server to get the info.
2403 while ((dirlist = dir->dir_next)) {
2404 struct smbc_dirent *dirent;
2406 if (!dirlist->dirent) {
2408 errno = ENOENT; /* Bad error */
2409 return -1;
2413 /* Do urlencoding of next entry, if so selected */
2414 dirent = (struct smbc_dirent *)context->internal->_dirent;
2415 maxlen = (sizeof(context->internal->_dirent) -
2416 sizeof(struct smbc_dirent));
2417 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
2419 reqd = dirent->dirlen;
2421 if (rem < reqd) {
2423 if (rem < count) { /* We managed to copy something */
2425 errno = 0;
2426 return count - rem;
2429 else { /* Nothing copied ... */
2431 errno = EINVAL; /* Not enough space ... */
2432 return -1;
2438 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2440 ((struct smbc_dirent *)ndir)->comment =
2441 (char *)(&((struct smbc_dirent *)ndir)->name +
2442 dirent->namelen +
2445 ndir += reqd;
2447 rem -= reqd;
2449 dir->dir_next = dirlist = dirlist -> next;
2452 if (rem == count)
2453 return 0;
2454 else
2455 return count - rem;
2460 * Routine to create a directory ...
2463 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2465 SMBCSRV *srv;
2466 fstring server, share, user, password, workgroup;
2467 pstring path;
2469 if (!context || !context->internal ||
2470 !context->internal->_initialized) {
2472 errno = EINVAL;
2473 return -1;
2477 if (!fname) {
2479 errno = EINVAL;
2480 return -1;
2484 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2486 if (smbc_parse_path(context, fname,
2487 server, sizeof(server),
2488 share, sizeof(share),
2489 path, sizeof(path),
2490 user, sizeof(user),
2491 password, sizeof(password),
2492 NULL, 0)) {
2493 errno = EINVAL;
2494 return -1;
2497 if (user[0] == (char)0) fstrcpy(user, context->user);
2499 fstrcpy(workgroup, context->workgroup);
2501 srv = smbc_server(context, server, share, workgroup, user, password);
2503 if (!srv) {
2505 return -1; /* errno set by smbc_server */
2509 if (!cli_mkdir(&srv->cli, path)) {
2511 errno = smbc_errno(context, &srv->cli);
2512 return -1;
2516 return 0;
2521 * Our list function simply checks to see if a directory is not empty
2524 static int smbc_rmdir_dirempty = True;
2526 static void rmdir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2529 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2530 smbc_rmdir_dirempty = False;
2535 * Routine to remove a directory
2538 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2540 SMBCSRV *srv;
2541 fstring server, share, user, password, workgroup;
2542 pstring path;
2544 if (!context || !context->internal ||
2545 !context->internal->_initialized) {
2547 errno = EINVAL;
2548 return -1;
2552 if (!fname) {
2554 errno = EINVAL;
2555 return -1;
2559 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2561 if (smbc_parse_path(context, fname,
2562 server, sizeof(server),
2563 share, sizeof(share),
2564 path, sizeof(path),
2565 user, sizeof(user),
2566 password, sizeof(password),
2567 NULL, 0))
2569 errno = EINVAL;
2570 return -1;
2573 if (user[0] == (char)0) fstrcpy(user, context->user);
2575 fstrcpy(workgroup, context->workgroup);
2577 srv = smbc_server(context, server, share, workgroup, user, password);
2579 if (!srv) {
2581 return -1; /* errno set by smbc_server */
2585 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2587 mode = aDIR | aRONLY;
2590 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2592 if (strcmp(path, "\\") == 0) {
2594 mode = aDIR | aRONLY;
2597 else {
2599 mode = aRONLY;
2600 smbc_stat_printjob(srv, path, &size, &m_time);
2601 c_time = a_time = m_time;
2604 else { */
2606 if (!cli_rmdir(&srv->cli, path)) {
2608 errno = smbc_errno(context, &srv->cli);
2610 if (errno == EACCES) { /* Check if the dir empty or not */
2612 pstring lpath; /* Local storage to avoid buffer overflows */
2614 smbc_rmdir_dirempty = True; /* Make this so ... */
2616 pstrcpy(lpath, path);
2617 pstrcat(lpath, "\\*");
2619 if (cli_list(&srv->cli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2620 NULL) < 0) {
2622 /* Fix errno to ignore latest error ... */
2624 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
2625 smbc_errno(context, &srv->cli)));
2626 errno = EACCES;
2630 if (smbc_rmdir_dirempty)
2631 errno = EACCES;
2632 else
2633 errno = ENOTEMPTY;
2637 return -1;
2641 return 0;
2646 * Routine to return the current directory position
2649 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
2651 off_t ret_val; /* Squash warnings about cast */
2653 if (!context || !context->internal ||
2654 !context->internal->_initialized) {
2656 errno = EINVAL;
2657 return -1;
2661 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2663 errno = EBADF;
2664 return -1;
2668 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2670 errno = ENOTDIR;
2671 return -1;
2676 * We return the pointer here as the offset
2678 ret_val = (int)dir->dir_next;
2679 return ret_val;
2684 * A routine to run down the list and see if the entry is OK
2687 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
2688 struct smbc_dirent *dirent)
2691 /* Run down the list looking for what we want */
2693 if (dirent) {
2695 struct smbc_dir_list *tmp = list;
2697 while (tmp) {
2699 if (tmp->dirent == dirent)
2700 return tmp;
2702 tmp = tmp->next;
2708 return NULL; /* Not found, or an error */
2714 * Routine to seek on a directory
2717 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
2719 long int l_offset = offset; /* Handle problems of size */
2720 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
2721 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
2723 if (!context || !context->internal ||
2724 !context->internal->_initialized) {
2726 errno = EINVAL;
2727 return -1;
2731 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2733 errno = ENOTDIR;
2734 return -1;
2738 /* Now, check what we were passed and see if it is OK ... */
2740 if (dirent == NULL) { /* Seek to the begining of the list */
2742 dir->dir_next = dir->dir_list;
2743 return 0;
2747 /* Now, run down the list and make sure that the entry is OK */
2748 /* This may need to be changed if we change the format of the list */
2750 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
2752 errno = EINVAL; /* Bad entry */
2753 return -1;
2757 dir->dir_next = list_ent;
2759 return 0;
2764 * Routine to fstat a dir
2767 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
2770 if (!context || !context->internal ||
2771 !context->internal->_initialized) {
2773 errno = EINVAL;
2774 return -1;
2778 /* No code yet ... */
2780 return 0;
2784 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
2786 SMBCSRV *srv;
2787 fstring server, share, user, password, workgroup;
2788 pstring path;
2789 uint16 mode;
2791 if (!context || !context->internal ||
2792 !context->internal->_initialized) {
2794 errno = EINVAL; /* Best I can think of ... */
2795 return -1;
2799 if (!fname) {
2801 errno = EINVAL;
2802 return -1;
2806 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
2808 if (smbc_parse_path(context, fname,
2809 server, sizeof(server),
2810 share, sizeof(share),
2811 path, sizeof(path),
2812 user, sizeof(user),
2813 password, sizeof(password),
2814 NULL, 0)) {
2815 errno = EINVAL;
2816 return -1;
2819 if (user[0] == (char)0) fstrcpy(user, context->user);
2821 fstrcpy(workgroup, context->workgroup);
2823 srv = smbc_server(context, server, share, workgroup, user, password);
2825 if (!srv) {
2826 return -1; /* errno set by smbc_server */
2829 mode = 0;
2831 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
2832 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
2833 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
2834 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
2836 if (!cli_setatr(&srv->cli, path, mode, 0)) {
2837 errno = smbc_errno(context, &srv->cli);
2838 return -1;
2841 return 0;
2844 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
2846 SMBCSRV *srv;
2847 fstring server, share, user, password, workgroup;
2848 pstring path;
2849 uint16 mode;
2850 time_t t = (tbuf == NULL ? time(NULL) : tbuf->tv_sec);
2852 if (!context || !context->internal ||
2853 !context->internal->_initialized) {
2855 errno = EINVAL; /* Best I can think of ... */
2856 return -1;
2860 if (!fname) {
2862 errno = EINVAL;
2863 return -1;
2867 DEBUG(4, ("smbc_utimes(%s, [%s])\n", fname, ctime(&t)));
2869 if (smbc_parse_path(context, fname,
2870 server, sizeof(server),
2871 share, sizeof(share),
2872 path, sizeof(path),
2873 user, sizeof(user),
2874 password, sizeof(password),
2875 NULL, 0)) {
2876 errno = EINVAL;
2877 return -1;
2880 if (user[0] == (char)0) fstrcpy(user, context->user);
2882 fstrcpy(workgroup, context->workgroup);
2884 srv = smbc_server(context, server, share, workgroup, user, password);
2886 if (!srv) {
2887 return -1; /* errno set by smbc_server */
2890 if (!smbc_getatr(context, srv, path,
2891 &mode, NULL,
2892 NULL, NULL, NULL,
2893 NULL)) {
2894 return -1;
2897 if (!cli_setatr(&srv->cli, path, mode, t)) {
2898 /* some servers always refuse directory changes */
2899 if (!(mode & aDIR)) {
2900 errno = smbc_errno(context, &srv->cli);
2901 return -1;
2905 return 0;
2909 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
2910 However NT4 gives a "The information may have been modified by a
2911 computer running Windows NT 5.0" if denied ACEs do not appear before
2912 allowed ACEs. */
2914 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
2916 if (sec_ace_equal(ace1, ace2))
2917 return 0;
2919 if (ace1->type != ace2->type)
2920 return ace2->type - ace1->type;
2922 if (sid_compare(&ace1->trustee, &ace2->trustee))
2923 return sid_compare(&ace1->trustee, &ace2->trustee);
2925 if (ace1->flags != ace2->flags)
2926 return ace1->flags - ace2->flags;
2928 if (ace1->info.mask != ace2->info.mask)
2929 return ace1->info.mask - ace2->info.mask;
2931 if (ace1->size != ace2->size)
2932 return ace1->size - ace2->size;
2934 return memcmp(ace1, ace2, sizeof(SEC_ACE));
2938 static void sort_acl(SEC_ACL *the_acl)
2940 uint32 i;
2941 if (!the_acl) return;
2943 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
2945 for (i=1;i<the_acl->num_aces;) {
2946 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
2947 int j;
2948 for (j=i; j<the_acl->num_aces-1; j++) {
2949 the_acl->ace[j] = the_acl->ace[j+1];
2951 the_acl->num_aces--;
2952 } else {
2953 i++;
2958 /* convert a SID to a string, either numeric or username/group */
2959 static void convert_sid_to_string(struct cli_state *ipc_cli,
2960 POLICY_HND *pol,
2961 fstring str,
2962 BOOL numeric,
2963 DOM_SID *sid)
2965 char **domains = NULL;
2966 char **names = NULL;
2967 uint32 *types = NULL;
2969 sid_to_string(str, sid);
2971 if (numeric) return; /* no lookup desired */
2973 /* Ask LSA to convert the sid to a name */
2975 if (!NT_STATUS_IS_OK(cli_lsa_lookup_sids(ipc_cli, ipc_cli->mem_ctx,
2976 pol, 1, sid, &domains,
2977 &names, &types)) ||
2978 !domains || !domains[0] || !names || !names[0]) {
2979 return;
2982 /* Converted OK */
2984 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
2985 domains[0], lp_winbind_separator(),
2986 names[0]);
2989 /* convert a string to a SID, either numeric or username/group */
2990 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
2991 POLICY_HND *pol,
2992 BOOL numeric,
2993 DOM_SID *sid,
2994 const char *str)
2996 uint32 *types = NULL;
2997 DOM_SID *sids = NULL;
2998 BOOL result = True;
3000 if (numeric) {
3001 if (strncmp(str, "S-", 2) == 0) {
3002 return string_to_sid(sid, str);
3005 result = False;
3006 goto done;
3009 if (!NT_STATUS_IS_OK(cli_lsa_lookup_names(ipc_cli, ipc_cli->mem_ctx,
3010 pol, 1, &str, &sids,
3011 &types))) {
3012 result = False;
3013 goto done;
3016 sid_copy(sid, &sids[0]);
3017 done:
3019 return result;
3023 /* parse an ACE in the same format as print_ace() */
3024 static BOOL parse_ace(struct cli_state *ipc_cli,
3025 POLICY_HND *pol,
3026 SEC_ACE *ace,
3027 BOOL numeric,
3028 char *str)
3030 char *p;
3031 const char *cp;
3032 fstring tok;
3033 unsigned atype, aflags, amask;
3034 DOM_SID sid;
3035 SEC_ACCESS mask;
3036 const struct perm_value *v;
3037 struct perm_value {
3038 const char *perm;
3039 uint32 mask;
3042 /* These values discovered by inspection */
3043 static const struct perm_value special_values[] = {
3044 { "R", 0x00120089 },
3045 { "W", 0x00120116 },
3046 { "X", 0x001200a0 },
3047 { "D", 0x00010000 },
3048 { "P", 0x00040000 },
3049 { "O", 0x00080000 },
3050 { NULL, 0 },
3053 static const struct perm_value standard_values[] = {
3054 { "READ", 0x001200a9 },
3055 { "CHANGE", 0x001301bf },
3056 { "FULL", 0x001f01ff },
3057 { NULL, 0 },
3061 ZERO_STRUCTP(ace);
3062 p = strchr_m(str,':');
3063 if (!p) return False;
3064 *p = '\0';
3065 p++;
3066 /* Try to parse numeric form */
3068 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3069 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3070 goto done;
3073 /* Try to parse text form */
3075 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3076 return False;
3079 cp = p;
3080 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3081 return False;
3084 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3085 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3086 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3087 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3088 } else {
3089 return False;
3092 /* Only numeric form accepted for flags at present */
3094 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3095 sscanf(tok, "%i", &aflags))) {
3096 return False;
3099 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3100 return False;
3103 if (strncmp(tok, "0x", 2) == 0) {
3104 if (sscanf(tok, "%i", &amask) != 1) {
3105 return False;
3107 goto done;
3110 for (v = standard_values; v->perm; v++) {
3111 if (strcmp(tok, v->perm) == 0) {
3112 amask = v->mask;
3113 goto done;
3117 p = tok;
3119 while(*p) {
3120 BOOL found = False;
3122 for (v = special_values; v->perm; v++) {
3123 if (v->perm[0] == *p) {
3124 amask |= v->mask;
3125 found = True;
3129 if (!found) return False;
3130 p++;
3133 if (*p) {
3134 return False;
3137 done:
3138 mask.mask = amask;
3139 init_sec_ace(ace, &sid, atype, mask, aflags);
3140 return True;
3143 /* add an ACE to a list of ACEs in a SEC_ACL */
3144 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3146 SEC_ACL *new;
3147 SEC_ACE *aces;
3148 if (! *the_acl) {
3149 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3150 return True;
3153 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3154 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3155 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3156 new = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3157 SAFE_FREE(aces);
3158 (*the_acl) = new;
3159 return True;
3163 /* parse a ascii version of a security descriptor */
3164 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3165 struct cli_state *ipc_cli,
3166 POLICY_HND *pol,
3167 BOOL numeric,
3168 char *str)
3170 const char *p = str;
3171 fstring tok;
3172 SEC_DESC *ret;
3173 size_t sd_size;
3174 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3175 SEC_ACL *dacl=NULL;
3176 int revision=1;
3178 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3180 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3181 revision = strtol(tok+9, NULL, 16);
3182 continue;
3185 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3186 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3187 if (!owner_sid ||
3188 !convert_string_to_sid(ipc_cli, pol,
3189 numeric,
3190 owner_sid, tok+6)) {
3191 DEBUG(5, ("Failed to parse owner sid\n"));
3192 return NULL;
3194 continue;
3197 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3198 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3199 if (!owner_sid ||
3200 !convert_string_to_sid(ipc_cli, pol,
3201 False,
3202 owner_sid, tok+7)) {
3203 DEBUG(5, ("Failed to parse owner sid\n"));
3204 return NULL;
3206 continue;
3209 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3210 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3211 if (!grp_sid ||
3212 !convert_string_to_sid(ipc_cli, pol,
3213 numeric,
3214 grp_sid, tok+6)) {
3215 DEBUG(5, ("Failed to parse group sid\n"));
3216 return NULL;
3218 continue;
3221 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3222 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3223 if (!grp_sid ||
3224 !convert_string_to_sid(ipc_cli, pol,
3225 False,
3226 grp_sid, tok+6)) {
3227 DEBUG(5, ("Failed to parse group sid\n"));
3228 return NULL;
3230 continue;
3233 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3234 SEC_ACE ace;
3235 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3236 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3237 return NULL;
3239 if(!add_ace(&dacl, &ace, ctx)) {
3240 DEBUG(5, ("Failed to add ACL %s\n", tok));
3241 return NULL;
3243 continue;
3246 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3247 SEC_ACE ace;
3248 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3249 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3250 return NULL;
3252 if(!add_ace(&dacl, &ace, ctx)) {
3253 DEBUG(5, ("Failed to add ACL %s\n", tok));
3254 return NULL;
3256 continue;
3259 DEBUG(5, ("Failed to parse security descriptor\n"));
3260 return NULL;
3263 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3264 owner_sid, grp_sid, NULL, dacl, &sd_size);
3266 SAFE_FREE(grp_sid);
3267 SAFE_FREE(owner_sid);
3269 return ret;
3273 /* Obtain the current dos attributes */
3274 static DOS_ATTR_DESC *dos_attr_query(SMBCCTX *context,
3275 TALLOC_CTX *ctx,
3276 const char *filename,
3277 SMBCSRV *srv)
3279 time_t m_time = 0, a_time = 0, c_time = 0;
3280 SMB_OFF_T size = 0;
3281 uint16 mode = 0;
3282 SMB_INO_T inode = 0;
3283 DOS_ATTR_DESC *ret;
3285 ret = talloc(ctx, sizeof(DOS_ATTR_DESC));
3286 if (!ret) {
3287 errno = ENOMEM;
3288 return NULL;
3291 /* Obtain the DOS attributes */
3292 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
3293 &mode, &size,
3294 &c_time, &a_time, &m_time, &inode)) {
3296 errno = smbc_errno(context, &srv->cli);
3297 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
3298 return NULL;
3302 ret->mode = mode;
3303 ret->size = size;
3304 ret->a_time = a_time;
3305 ret->c_time = c_time;
3306 ret->m_time = m_time;
3307 ret->inode = inode;
3309 return ret;
3313 /* parse a ascii version of a security descriptor */
3314 static void dos_attr_parse(SMBCCTX *context,
3315 DOS_ATTR_DESC *dad,
3316 SMBCSRV *srv,
3317 char *str)
3319 const char *p = str;
3320 fstring tok;
3322 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3324 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
3325 dad->mode = strtol(tok+5, NULL, 16);
3326 continue;
3329 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
3330 dad->size = strtoll(tok+5, NULL, 10);
3331 continue;
3334 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
3335 dad->a_time = strtoll(tok+7, NULL, 10);
3336 continue;
3339 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
3340 dad->c_time = strtoll(tok+7, NULL, 10);
3341 continue;
3344 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
3345 dad->m_time = strtoll(tok+7, NULL, 10);
3346 continue;
3349 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
3350 dad->inode = strtoll(tok+6, NULL, 10);
3351 continue;
3357 /*****************************************************
3358 retrieve the acls for a file
3359 *******************************************************/
3360 static int cacl_get(SMBCCTX *context, TALLOC_CTX *ctx, SMBCSRV *srv,
3361 struct cli_state *ipc_cli, POLICY_HND *pol,
3362 char *filename, char *attr_name, char *buf, int bufsize)
3364 uint32 i;
3365 int n = 0;
3366 int n_used;
3367 BOOL all;
3368 BOOL all_nt;
3369 BOOL all_nt_acls;
3370 BOOL all_dos;
3371 BOOL some_nt;
3372 BOOL some_dos;
3373 BOOL exclude_nt_revision = False;
3374 BOOL exclude_nt_owner = False;
3375 BOOL exclude_nt_group = False;
3376 BOOL exclude_nt_acl = False;
3377 BOOL exclude_dos_mode = False;
3378 BOOL exclude_dos_size = False;
3379 BOOL exclude_dos_ctime = False;
3380 BOOL exclude_dos_atime = False;
3381 BOOL exclude_dos_mtime = False;
3382 BOOL exclude_dos_inode = False;
3383 BOOL numeric = True;
3384 BOOL determine_size = (bufsize == 0);
3385 int fnum = -1;
3386 SEC_DESC *sd;
3387 fstring sidstr;
3388 fstring name_sandbox;
3389 char *name;
3390 char *pExclude;
3391 char *p;
3392 time_t m_time = 0, a_time = 0, c_time = 0;
3393 SMB_OFF_T size = 0;
3394 uint16 mode = 0;
3395 SMB_INO_T ino = 0;
3396 struct cli_state *cli = &srv->cli;
3398 /* Copy name so we can strip off exclusions (if any are specified) */
3399 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
3401 /* Ensure name is null terminated */
3402 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
3404 /* Play in the sandbox */
3405 name = name_sandbox;
3407 /* If there are any exclusions, point to them and mask them from name */
3408 if ((pExclude = strchr(name, '!')) != NULL)
3410 *pExclude++ = '\0';
3413 all = (StrnCaseCmp(name, "system.*", 8) == 0);
3414 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
3415 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
3416 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
3417 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
3418 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
3419 numeric = (* (name + strlen(name) - 1) != '+');
3421 /* Look for exclusions from "all" requests */
3422 if (all || all_nt || all_dos) {
3424 /* Exclusions are delimited by '!' */
3425 for (; pExclude != NULL; pExclude = (p == NULL ? NULL : p + 1)) {
3427 /* Find end of this exclusion name */
3428 if ((p = strchr(pExclude, '!')) != NULL)
3430 *p = '\0';
3433 /* Which exclusion name is this? */
3434 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
3435 exclude_nt_revision = True;
3437 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
3438 exclude_nt_owner = True;
3440 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
3441 exclude_nt_group = True;
3443 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
3444 exclude_nt_acl = True;
3446 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
3447 exclude_dos_mode = True;
3449 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
3450 exclude_dos_size = True;
3452 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
3453 exclude_dos_ctime = True;
3455 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
3456 exclude_dos_atime = True;
3458 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
3459 exclude_dos_mtime = True;
3461 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
3462 exclude_dos_inode = True;
3464 else {
3465 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
3466 pExclude));
3467 errno = ENOATTR;
3468 return -1;
3473 n_used = 0;
3476 * If we are (possibly) talking to an NT or new system and some NT
3477 * attributes have been requested...
3479 if (ipc_cli && (all || some_nt || all_nt_acls)) {
3480 /* Point to the portion after "system.nt_sec_desc." */
3481 name += 19; /* if (all) this will be invalid but unused */
3483 /* ... then obtain any NT attributes which were requested */
3484 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3486 if (fnum == -1) {
3487 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3488 filename, cli_errstr(cli)));
3489 errno = 0;
3490 return -1;
3493 sd = cli_query_secdesc(cli, fnum, ctx);
3495 if (!sd) {
3496 DEBUG(5,
3497 ("cacl_get Failed to query old descriptor\n"));
3498 errno = 0;
3499 return -1;
3502 cli_close(cli, fnum);
3504 if (! exclude_nt_revision) {
3505 if (all || all_nt) {
3506 if (determine_size) {
3507 p = talloc_asprintf(ctx,
3508 "REVISION:%d",
3509 sd->revision);
3510 if (!p) {
3511 errno = ENOMEM;
3512 return -1;
3514 n = strlen(p);
3515 } else {
3516 n = snprintf(buf, bufsize,
3517 "REVISION:%d", sd->revision);
3519 } else if (StrCaseCmp(name, "revision") == 0) {
3520 if (determine_size) {
3521 p = talloc_asprintf(ctx, "%d",
3522 sd->revision);
3523 if (!p) {
3524 errno = ENOMEM;
3525 return -1;
3527 n = strlen(p);
3528 } else {
3529 n = snprintf(buf, bufsize, "%d",
3530 sd->revision);
3534 if (!determine_size && n > bufsize) {
3535 errno = ERANGE;
3536 return -1;
3538 buf += n;
3539 n_used += n;
3540 bufsize -= n;
3543 if (! exclude_nt_owner) {
3544 /* Get owner and group sid */
3545 if (sd->owner_sid) {
3546 convert_sid_to_string(ipc_cli, pol,
3547 sidstr,
3548 numeric,
3549 sd->owner_sid);
3550 } else {
3551 fstrcpy(sidstr, "");
3554 if (all || all_nt) {
3555 if (determine_size) {
3556 p = talloc_asprintf(ctx, ",OWNER:%s",
3557 sidstr);
3558 if (!p) {
3559 errno = ENOMEM;
3560 return -1;
3562 n = strlen(p);
3563 } else {
3564 n = snprintf(buf, bufsize,
3565 ",OWNER:%s", sidstr);
3567 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3568 if (determine_size) {
3569 p = talloc_asprintf(ctx, "%s", sidstr);
3570 if (!p) {
3571 errno = ENOMEM;
3572 return -1;
3574 n = strlen(p);
3575 } else {
3576 n = snprintf(buf, bufsize, "%s",
3577 sidstr);
3581 if (!determine_size && n > bufsize) {
3582 errno = ERANGE;
3583 return -1;
3585 buf += n;
3586 n_used += n;
3587 bufsize -= n;
3590 if (! exclude_nt_group) {
3591 if (sd->grp_sid) {
3592 convert_sid_to_string(ipc_cli, pol,
3593 sidstr, numeric,
3594 sd->grp_sid);
3595 } else {
3596 fstrcpy(sidstr, "");
3599 if (all || all_nt) {
3600 if (determine_size) {
3601 p = talloc_asprintf(ctx, ",GROUP:%s",
3602 sidstr);
3603 if (!p) {
3604 errno = ENOMEM;
3605 return -1;
3607 n = strlen(p);
3608 } else {
3609 n = snprintf(buf, bufsize,
3610 ",GROUP:%s", sidstr);
3612 } else if (StrnCaseCmp(name, "group", 5) == 0) {
3613 if (determine_size) {
3614 p = talloc_asprintf(ctx, "%s", sidstr);
3615 if (!p) {
3616 errno = ENOMEM;
3617 return -1;
3619 n = strlen(p);
3620 } else {
3621 n = snprintf(buf, bufsize, "%s", sidstr);
3625 if (!determine_size && n > bufsize) {
3626 errno = ERANGE;
3627 return -1;
3629 buf += n;
3630 n_used += n;
3631 bufsize -= n;
3634 if (! exclude_nt_acl) {
3635 /* Add aces to value buffer */
3636 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
3638 SEC_ACE *ace = &sd->dacl->ace[i];
3639 convert_sid_to_string(ipc_cli, pol,
3640 sidstr, numeric,
3641 &ace->trustee);
3643 if (all || all_nt) {
3644 if (determine_size) {
3645 p = talloc_asprintf(
3646 ctx,
3647 ",ACL:"
3648 "%s:%d/%d/0x%08x",
3649 sidstr,
3650 ace->type,
3651 ace->flags,
3652 ace->info.mask);
3653 if (!p) {
3654 errno = ENOMEM;
3655 return -1;
3657 n = strlen(p);
3658 } else {
3659 n = snprintf(
3660 buf, bufsize,
3661 ",ACL:%s:%d/%d/0x%08x",
3662 sidstr,
3663 ace->type,
3664 ace->flags,
3665 ace->info.mask);
3667 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
3668 StrCaseCmp(name + 3, sidstr) == 0) ||
3669 (StrnCaseCmp(name, "acl+", 4) == 0 &&
3670 StrCaseCmp(name + 4, sidstr) == 0)) {
3671 if (determine_size) {
3672 p = talloc_asprintf(
3673 ctx,
3674 "%d/%d/0x%08x",
3675 ace->type,
3676 ace->flags,
3677 ace->info.mask);
3678 if (!p) {
3679 errno = ENOMEM;
3680 return -1;
3682 n = strlen(p);
3683 } else {
3684 n = snprintf(buf, bufsize,
3685 "%d/%d/0x%08x",
3686 ace->type,
3687 ace->flags,
3688 ace->info.mask);
3690 } else if (all_nt_acls) {
3691 if (determine_size) {
3692 p = talloc_asprintf(
3693 ctx,
3694 "%s%s:%d/%d/0x%08x",
3695 i ? "," : "",
3696 sidstr,
3697 ace->type,
3698 ace->flags,
3699 ace->info.mask);
3700 if (!p) {
3701 errno = ENOMEM;
3702 return -1;
3704 n = strlen(p);
3705 } else {
3706 n = snprintf(buf, bufsize,
3707 "%s%s:%d/%d/0x%08x",
3708 i ? "," : "",
3709 sidstr,
3710 ace->type,
3711 ace->flags,
3712 ace->info.mask);
3715 if (n > bufsize) {
3716 errno = ERANGE;
3717 return -1;
3719 buf += n;
3720 n_used += n;
3721 bufsize -= n;
3725 /* Restore name pointer to its original value */
3726 name -= 19;
3729 if (all || some_dos) {
3730 /* Point to the portion after "system.dos_attr." */
3731 name += 16; /* if (all) this will be invalid but unused */
3733 /* Obtain the DOS attributes */
3734 if (!smbc_getatr(context, srv, filename, &mode, &size,
3735 &c_time, &a_time, &m_time, &ino)) {
3737 errno = smbc_errno(context, &srv->cli);
3738 return -1;
3742 if (! exclude_dos_mode) {
3743 if (all || all_dos) {
3744 if (determine_size) {
3745 p = talloc_asprintf(ctx,
3746 "%sMODE:0x%x",
3747 (ipc_cli &&
3748 (all || some_nt)
3749 ? ","
3750 : ""),
3751 mode);
3752 if (!p) {
3753 errno = ENOMEM;
3754 return -1;
3756 n = strlen(p);
3757 } else {
3758 n = snprintf(buf, bufsize,
3759 "%sMODE:0x%x",
3760 (ipc_cli &&
3761 (all || some_nt)
3762 ? ","
3763 : ""),
3764 mode);
3766 } else if (StrCaseCmp(name, "mode") == 0) {
3767 if (determine_size) {
3768 p = talloc_asprintf(ctx, "0x%x", mode);
3769 if (!p) {
3770 errno = ENOMEM;
3771 return -1;
3773 n = strlen(p);
3774 } else {
3775 n = snprintf(buf, bufsize, "0x%x", mode);
3779 if (!determine_size && n > bufsize) {
3780 errno = ERANGE;
3781 return -1;
3783 buf += n;
3784 n_used += n;
3785 bufsize -= n;
3788 if (! exclude_dos_size) {
3789 if (all || all_dos) {
3790 if (determine_size) {
3791 p = talloc_asprintf(
3792 ctx,
3793 ",SIZE:%llu",
3794 (unsigned long long) size);
3795 if (!p) {
3796 errno = ENOMEM;
3797 return -1;
3799 n = strlen(p);
3800 } else {
3801 n = snprintf(buf, bufsize,
3802 ",SIZE:%llu",
3803 (unsigned long long) size);
3805 } else if (StrCaseCmp(name, "size") == 0) {
3806 if (determine_size) {
3807 p = talloc_asprintf(
3808 ctx,
3809 "%llu",
3810 (unsigned long long) size);
3811 if (!p) {
3812 errno = ENOMEM;
3813 return -1;
3815 n = strlen(p);
3816 } else {
3817 n = snprintf(buf, bufsize,
3818 "%llu",
3819 (unsigned long long) size);
3823 if (!determine_size && n > bufsize) {
3824 errno = ERANGE;
3825 return -1;
3827 buf += n;
3828 n_used += n;
3829 bufsize -= n;
3832 if (! exclude_dos_ctime) {
3833 if (all || all_dos) {
3834 if (determine_size) {
3835 p = talloc_asprintf(ctx,
3836 ",C_TIME:%lu",
3837 c_time);
3838 if (!p) {
3839 errno = ENOMEM;
3840 return -1;
3842 n = strlen(p);
3843 } else {
3844 n = snprintf(buf, bufsize,
3845 ",C_TIME:%lu", c_time);
3847 } else if (StrCaseCmp(name, "c_time") == 0) {
3848 if (determine_size) {
3849 p = talloc_asprintf(ctx, "%lu", c_time);
3850 if (!p) {
3851 errno = ENOMEM;
3852 return -1;
3854 n = strlen(p);
3855 } else {
3856 n = snprintf(buf, bufsize, "%lu", c_time);
3860 if (!determine_size && n > bufsize) {
3861 errno = ERANGE;
3862 return -1;
3864 buf += n;
3865 n_used += n;
3866 bufsize -= n;
3869 if (! exclude_dos_atime) {
3870 if (all || all_dos) {
3871 if (determine_size) {
3872 p = talloc_asprintf(ctx,
3873 ",A_TIME:%lu",
3874 a_time);
3875 if (!p) {
3876 errno = ENOMEM;
3877 return -1;
3879 n = strlen(p);
3880 } else {
3881 n = snprintf(buf, bufsize,
3882 ",A_TIME:%lu", a_time);
3884 } else if (StrCaseCmp(name, "a_time") == 0) {
3885 if (determine_size) {
3886 p = talloc_asprintf(ctx, "%lu", a_time);
3887 if (!p) {
3888 errno = ENOMEM;
3889 return -1;
3891 n = strlen(p);
3892 } else {
3893 n = snprintf(buf, bufsize, "%lu", a_time);
3897 if (!determine_size && n > bufsize) {
3898 errno = ERANGE;
3899 return -1;
3901 buf += n;
3902 n_used += n;
3903 bufsize -= n;
3906 if (! exclude_dos_mtime) {
3907 if (all || all_dos) {
3908 if (determine_size) {
3909 p = talloc_asprintf(ctx,
3910 ",M_TIME:%lu",
3911 m_time);
3912 if (!p) {
3913 errno = ENOMEM;
3914 return -1;
3916 n = strlen(p);
3917 } else {
3918 n = snprintf(buf, bufsize,
3919 ",M_TIME:%lu", m_time);
3921 } else if (StrCaseCmp(name, "m_time") == 0) {
3922 if (determine_size) {
3923 p = talloc_asprintf(ctx, "%lu", m_time);
3924 if (!p) {
3925 errno = ENOMEM;
3926 return -1;
3928 n = strlen(p);
3929 } else {
3930 n = snprintf(buf, bufsize, "%lu", m_time);
3934 if (!determine_size && n > bufsize) {
3935 errno = ERANGE;
3936 return -1;
3938 buf += n;
3939 n_used += n;
3940 bufsize -= n;
3943 if (! exclude_dos_inode) {
3944 if (all || all_dos) {
3945 if (determine_size) {
3946 p = talloc_asprintf(
3947 ctx,
3948 ",INODE:%llu",
3949 (unsigned long long) ino);
3950 if (!p) {
3951 errno = ENOMEM;
3952 return -1;
3954 n = strlen(p);
3955 } else {
3956 n = snprintf(buf, bufsize,
3957 ",INODE:%llu",
3958 (unsigned long long) ino);
3960 } else if (StrCaseCmp(name, "inode") == 0) {
3961 if (determine_size) {
3962 p = talloc_asprintf(
3963 ctx,
3964 "%llu",
3965 (unsigned long long) ino);
3966 if (!p) {
3967 errno = ENOMEM;
3968 return -1;
3970 n = strlen(p);
3971 } else {
3972 n = snprintf(buf, bufsize,
3973 "%llu",
3974 (unsigned long long) ino);
3978 if (!determine_size && n > bufsize) {
3979 errno = ERANGE;
3980 return -1;
3982 buf += n;
3983 n_used += n;
3984 bufsize -= n;
3987 /* Restore name pointer to its original value */
3988 name -= 16;
3991 if (n_used == 0) {
3992 errno = ENOATTR;
3993 return -1;
3996 return n_used;
4000 /*****************************************************
4001 set the ACLs on a file given an ascii description
4002 *******************************************************/
4003 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
4004 struct cli_state *ipc_cli, POLICY_HND *pol,
4005 const char *filename, const char *the_acl,
4006 int mode, int flags)
4008 int fnum;
4009 int err = 0;
4010 SEC_DESC *sd = NULL, *old;
4011 SEC_ACL *dacl = NULL;
4012 DOM_SID *owner_sid = NULL;
4013 DOM_SID *grp_sid = NULL;
4014 uint32 i, j;
4015 size_t sd_size;
4016 int ret = 0;
4017 char *p;
4018 BOOL numeric = True;
4020 /* the_acl will be null for REMOVE_ALL operations */
4021 if (the_acl) {
4022 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4023 p > the_acl &&
4024 p[-1] != '+');
4026 /* if this is to set the entire ACL... */
4027 if (*the_acl == '*') {
4028 /* ... then increment past the first colon */
4029 the_acl = p + 1;
4032 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4033 CONST_DISCARD(char *, the_acl));
4035 if (!sd) {
4036 errno = EINVAL;
4037 return -1;
4041 /* The desired access below is the only one I could find that works
4042 with NT4, W2KP and Samba */
4044 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4046 if (fnum == -1) {
4047 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4048 filename, cli_errstr(cli)));
4049 errno = 0;
4050 return -1;
4053 old = cli_query_secdesc(cli, fnum, ctx);
4055 if (!old) {
4056 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4057 errno = 0;
4058 return -1;
4061 cli_close(cli, fnum);
4063 switch (mode) {
4064 case SMBC_XATTR_MODE_REMOVE_ALL:
4065 old->dacl->num_aces = 0;
4066 SAFE_FREE(old->dacl->ace);
4067 SAFE_FREE(old->dacl);
4068 old->off_dacl = 0;
4069 dacl = old->dacl;
4070 break;
4072 case SMBC_XATTR_MODE_REMOVE:
4073 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4074 BOOL found = False;
4076 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4077 if (sec_ace_equal(&sd->dacl->ace[i],
4078 &old->dacl->ace[j])) {
4079 uint32 k;
4080 for (k=j; k<old->dacl->num_aces-1;k++) {
4081 old->dacl->ace[k] = old->dacl->ace[k+1];
4083 old->dacl->num_aces--;
4084 if (old->dacl->num_aces == 0) {
4085 SAFE_FREE(old->dacl->ace);
4086 SAFE_FREE(old->dacl);
4087 old->off_dacl = 0;
4089 found = True;
4090 dacl = old->dacl;
4091 break;
4095 if (!found) {
4096 err = ENOATTR;
4097 ret = -1;
4098 goto failed;
4101 break;
4103 case SMBC_XATTR_MODE_ADD:
4104 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4105 BOOL found = False;
4107 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4108 if (sid_equal(&sd->dacl->ace[i].trustee,
4109 &old->dacl->ace[j].trustee)) {
4110 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4111 err = EEXIST;
4112 ret = -1;
4113 goto failed;
4115 old->dacl->ace[j] = sd->dacl->ace[i];
4116 ret = -1;
4117 found = True;
4121 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4122 err = ENOATTR;
4123 ret = -1;
4124 goto failed;
4127 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4128 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4131 dacl = old->dacl;
4132 break;
4134 case SMBC_XATTR_MODE_SET:
4135 old = sd;
4136 owner_sid = old->owner_sid;
4137 grp_sid = old->grp_sid;
4138 dacl = old->dacl;
4139 break;
4141 case SMBC_XATTR_MODE_CHOWN:
4142 owner_sid = sd->owner_sid;
4143 break;
4145 case SMBC_XATTR_MODE_CHGRP:
4146 grp_sid = sd->grp_sid;
4147 break;
4150 /* Denied ACE entries must come before allowed ones */
4151 sort_acl(old->dacl);
4153 /* Create new security descriptor and set it */
4154 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4155 owner_sid, grp_sid, NULL, dacl, &sd_size);
4157 fnum = cli_nt_create(cli, filename,
4158 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4160 if (fnum == -1) {
4161 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4162 filename, cli_errstr(cli)));
4163 errno = 0;
4164 return -1;
4167 if (!cli_set_secdesc(cli, fnum, sd)) {
4168 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4169 ret = -1;
4172 /* Clean up */
4174 failed:
4175 cli_close(cli, fnum);
4177 if (err != 0) {
4178 errno = err;
4181 return ret;
4185 int smbc_setxattr_ctx(SMBCCTX *context,
4186 const char *fname,
4187 const char *name,
4188 const void *value,
4189 size_t size,
4190 int flags)
4192 int ret;
4193 int ret2;
4194 SMBCSRV *srv;
4195 SMBCSRV *ipc_srv;
4196 fstring server, share, user, password, workgroup;
4197 pstring path;
4198 TALLOC_CTX *ctx;
4199 POLICY_HND pol;
4200 DOS_ATTR_DESC *dad;
4202 if (!context || !context->internal ||
4203 !context->internal->_initialized) {
4205 errno = EINVAL; /* Best I can think of ... */
4206 return -1;
4210 if (!fname) {
4212 errno = EINVAL;
4213 return -1;
4217 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n", fname, name, (int) size, (const char*)value));
4219 if (smbc_parse_path(context, fname,
4220 server, sizeof(server),
4221 share, sizeof(share),
4222 path, sizeof(path),
4223 user, sizeof(user),
4224 password, sizeof(password),
4225 NULL, 0)) {
4226 errno = EINVAL;
4227 return -1;
4230 if (user[0] == (char)0) fstrcpy(user, context->user);
4232 fstrcpy(workgroup, context->workgroup);
4234 srv = smbc_server(context, server, share, workgroup, user, password);
4235 if (!srv) {
4236 return -1; /* errno set by smbc_server */
4239 if (! srv->no_nt_session) {
4240 ipc_srv = smbc_attr_server(context, server, share,
4241 workgroup, user, password,
4242 &pol);
4243 srv->no_nt_session = True;
4244 } else {
4245 ipc_srv = NULL;
4248 ctx = talloc_init("smbc_setxattr");
4249 if (!ctx) {
4250 errno = ENOMEM;
4251 return -1;
4255 * Are they asking to set the entire set of known attributes?
4257 if (StrCaseCmp(name, "system.*") == 0 ||
4258 StrCaseCmp(name, "system.*+") == 0) {
4259 /* Yup. */
4260 char *namevalue =
4261 talloc_asprintf(ctx, "%s:%s", name+7, (const char *) value);
4262 if (! namevalue) {
4263 errno = ENOMEM;
4264 ret = -1;
4265 return -1;
4268 if (ipc_srv) {
4269 ret = cacl_set(ctx, &srv->cli,
4270 &ipc_srv->cli, &pol, path,
4271 namevalue,
4272 (*namevalue == '*'
4273 ? SMBC_XATTR_MODE_SET
4274 : SMBC_XATTR_MODE_ADD),
4275 flags);
4276 } else {
4277 ret = 0;
4280 /* get a DOS Attribute Descriptor with current attributes */
4281 dad = dos_attr_query(context, ctx, path, srv);
4282 if (dad) {
4283 /* Overwrite old with new, using what was provided */
4284 dos_attr_parse(context, dad, srv, namevalue);
4286 /* Set the new DOS attributes */
4287 #if 0 /* not yet implemented */
4288 if (! cli_setpathinfo(&srv->cli, path,
4289 dad->c_time,
4290 dad->a_time,
4291 dad->m_time,
4292 dad->mode)) {
4293 if (!cli_setatr(&srv->cli, path,
4294 dad->mode, dad->m_time)) {
4295 errno = smbc_errno(context, &srv->cli);
4298 #else
4299 if (!cli_setatr(&srv->cli, path,
4300 dad->mode, dad->m_time)) {
4301 errno = smbc_errno(context, &srv->cli);
4303 #endif
4306 /* we only fail if both NT and DOS sets failed */
4307 if (ret < 0 && ! dad) {
4308 ret = -1; /* in case dad was null */
4310 else {
4311 ret = 0;
4314 talloc_destroy(ctx);
4315 return ret;
4319 * Are they asking to set an access control element or to set
4320 * the entire access control list?
4322 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4323 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4324 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4325 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4326 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4328 /* Yup. */
4329 char *namevalue =
4330 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4332 if (! ipc_srv) {
4333 ret = -1; /* errno set by smbc_server() */
4335 else if (! namevalue) {
4336 errno = ENOMEM;
4337 ret = -1;
4338 } else {
4339 ret = cacl_set(ctx, &srv->cli,
4340 &ipc_srv->cli, &pol, path,
4341 namevalue,
4342 (*namevalue == '*'
4343 ? SMBC_XATTR_MODE_SET
4344 : SMBC_XATTR_MODE_ADD),
4345 flags);
4347 talloc_destroy(ctx);
4348 return ret;
4352 * Are they asking to set the owner?
4354 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4355 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
4357 /* Yup. */
4358 char *namevalue =
4359 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4361 if (! ipc_srv) {
4363 ret = -1; /* errno set by smbc_server() */
4365 else if (! namevalue) {
4366 errno = ENOMEM;
4367 ret = -1;
4368 } else {
4369 ret = cacl_set(ctx, &srv->cli,
4370 &ipc_srv->cli, &pol, path,
4371 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4373 talloc_destroy(ctx);
4374 return ret;
4378 * Are they asking to set the group?
4380 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4381 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
4383 /* Yup. */
4384 char *namevalue =
4385 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4387 if (! ipc_srv) {
4388 /* errno set by smbc_server() */
4389 ret = -1;
4391 else if (! namevalue) {
4392 errno = ENOMEM;
4393 ret = -1;
4394 } else {
4395 ret = cacl_set(ctx, &srv->cli,
4396 &ipc_srv->cli, &pol, path,
4397 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4399 talloc_destroy(ctx);
4400 return ret;
4404 * Are they asking to set a DOS attribute?
4406 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4407 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4408 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4409 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4410 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
4412 /* get a DOS Attribute Descriptor with current attributes */
4413 dad = dos_attr_query(context, ctx, path, srv);
4414 if (dad) {
4415 char *namevalue =
4416 talloc_asprintf(ctx, "%s:%s", name+16, (const char *) value);
4417 if (! namevalue) {
4418 errno = ENOMEM;
4419 ret = -1;
4420 } else {
4421 /* Overwrite old with provided new params */
4422 dos_attr_parse(context, dad, srv, namevalue);
4424 /* Set the new DOS attributes */
4425 #if 0 /* not yet implemented */
4426 ret2 = cli_setpathinfo(&srv->cli, path,
4427 dad->c_time,
4428 dad->a_time,
4429 dad->m_time,
4430 dad->mode);
4431 if (! ret2) {
4432 ret2 = cli_setatr(&srv->cli, path,
4433 dad->mode,
4434 dad->m_time);
4435 if (! ret2) {
4436 errno = smbc_errno(context,
4437 &srv->cli);
4440 #else
4441 ret2 = cli_setatr(&srv->cli, path,
4442 dad->mode, dad->m_time);
4443 if (! ret2) {
4444 errno = smbc_errno(context, &srv->cli);
4446 #endif
4448 /* ret2 has True (success) / False (failure) */
4449 if (ret2) {
4450 ret = 0;
4451 } else {
4452 ret = -1;
4455 } else {
4456 ret = -1;
4459 talloc_destroy(ctx);
4460 return ret;
4463 /* Unsupported attribute name */
4464 talloc_destroy(ctx);
4465 errno = EINVAL;
4466 return -1;
4469 int smbc_getxattr_ctx(SMBCCTX *context,
4470 const char *fname,
4471 const char *name,
4472 const void *value,
4473 size_t size)
4475 int ret;
4476 SMBCSRV *srv;
4477 SMBCSRV *ipc_srv;
4478 fstring server, share, user, password, workgroup;
4479 pstring path;
4480 TALLOC_CTX *ctx;
4481 POLICY_HND pol;
4484 if (!context || !context->internal ||
4485 !context->internal->_initialized) {
4487 errno = EINVAL; /* Best I can think of ... */
4488 return -1;
4492 if (!fname) {
4494 errno = EINVAL;
4495 return -1;
4499 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
4501 if (smbc_parse_path(context, fname,
4502 server, sizeof(server),
4503 share, sizeof(share),
4504 path, sizeof(path),
4505 user, sizeof(user),
4506 password, sizeof(password),
4507 NULL, 0)) {
4508 errno = EINVAL;
4509 return -1;
4512 if (user[0] == (char)0) fstrcpy(user, context->user);
4514 fstrcpy(workgroup, context->workgroup);
4516 srv = smbc_server(context, server, share, workgroup, user, password);
4517 if (!srv) {
4518 return -1; /* errno set by smbc_server */
4521 if (! srv->no_nt_session) {
4522 ipc_srv = smbc_attr_server(context, server, share,
4523 workgroup, user, password,
4524 &pol);
4525 if (! ipc_srv) {
4526 srv->no_nt_session = True;
4528 } else {
4529 ipc_srv = NULL;
4532 ctx = talloc_init("smbc:getxattr");
4533 if (!ctx) {
4534 errno = ENOMEM;
4535 return -1;
4538 /* Are they requesting a supported attribute? */
4539 if (StrCaseCmp(name, "system.*") == 0 ||
4540 StrnCaseCmp(name, "system.*!", 9) == 0 ||
4541 StrCaseCmp(name, "system.*+") == 0 ||
4542 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
4543 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4544 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
4545 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4546 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
4547 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4548 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4549 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
4550 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4551 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
4552 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4553 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
4554 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4555 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
4556 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4557 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
4558 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4559 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4560 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
4561 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
4563 /* Yup. */
4564 ret = cacl_get(context, ctx, srv,
4565 ipc_srv == NULL ? NULL : &ipc_srv->cli,
4566 &pol, path,
4567 CONST_DISCARD(char *, name),
4568 CONST_DISCARD(char *, value), size);
4569 if (ret < 0 && errno == 0) {
4570 errno = smbc_errno(context, &srv->cli);
4572 talloc_destroy(ctx);
4573 return ret;
4576 /* Unsupported attribute name */
4577 talloc_destroy(ctx);
4578 errno = EINVAL;
4579 return -1;
4583 int smbc_removexattr_ctx(SMBCCTX *context,
4584 const char *fname,
4585 const char *name)
4587 int ret;
4588 SMBCSRV *srv;
4589 SMBCSRV *ipc_srv;
4590 fstring server, share, user, password, workgroup;
4591 pstring path;
4592 TALLOC_CTX *ctx;
4593 POLICY_HND pol;
4595 if (!context || !context->internal ||
4596 !context->internal->_initialized) {
4598 errno = EINVAL; /* Best I can think of ... */
4599 return -1;
4603 if (!fname) {
4605 errno = EINVAL;
4606 return -1;
4610 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
4612 if (smbc_parse_path(context, fname,
4613 server, sizeof(server),
4614 share, sizeof(share),
4615 path, sizeof(path),
4616 user, sizeof(user),
4617 password, sizeof(password),
4618 NULL, 0)) {
4619 errno = EINVAL;
4620 return -1;
4623 if (user[0] == (char)0) fstrcpy(user, context->user);
4625 fstrcpy(workgroup, context->workgroup);
4627 srv = smbc_server(context, server, share, workgroup, user, password);
4628 if (!srv) {
4629 return -1; /* errno set by smbc_server */
4632 if (! srv->no_nt_session) {
4633 ipc_srv = smbc_attr_server(context, server, share,
4634 workgroup, user, password,
4635 &pol);
4636 srv->no_nt_session = True;
4637 } else {
4638 ipc_srv = NULL;
4641 if (! ipc_srv) {
4642 return -1; /* errno set by smbc_attr_server */
4645 ctx = talloc_init("smbc_removexattr");
4646 if (!ctx) {
4647 errno = ENOMEM;
4648 return -1;
4651 /* Are they asking to set the entire ACL? */
4652 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4653 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
4655 /* Yup. */
4656 ret = cacl_set(ctx, &srv->cli,
4657 &ipc_srv->cli, &pol, path,
4658 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
4659 talloc_destroy(ctx);
4660 return ret;
4664 * Are they asking to remove one or more spceific security descriptor
4665 * attributes?
4667 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4668 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4669 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
4670 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4671 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
4672 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4673 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4675 /* Yup. */
4676 ret = cacl_set(ctx, &srv->cli,
4677 &ipc_srv->cli, &pol, path,
4678 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
4679 talloc_destroy(ctx);
4680 return ret;
4683 /* Unsupported attribute name */
4684 talloc_destroy(ctx);
4685 errno = EINVAL;
4686 return -1;
4689 int smbc_listxattr_ctx(SMBCCTX *context,
4690 const char *fname,
4691 char *list,
4692 size_t size)
4695 * This isn't quite what listxattr() is supposed to do. This returns
4696 * the complete set of attribute names, always, rather than only those
4697 * attribute names which actually exist for a file. Hmmm...
4699 const char supported[] =
4700 "system.*\0"
4701 "system.*+\0"
4702 "system.nt_sec_desc.revision\0"
4703 "system.nt_sec_desc.owner\0"
4704 "system.nt_sec_desc.owner+\0"
4705 "system.nt_sec_desc.group\0"
4706 "system.nt_sec_desc.group+\0"
4707 "system.nt_sec_desc.acl.*\0"
4708 "system.nt_sec_desc.acl\0"
4709 "system.nt_sec_desc.acl+\0"
4710 "system.nt_sec_desc.*\0"
4711 "system.nt_sec_desc.*+\0"
4712 "system.dos_attr.*\0"
4713 "system.dos_attr.mode\0"
4714 "system.dos_attr.c_time\0"
4715 "system.dos_attr.a_time\0"
4716 "system.dos_attr.m_time\0"
4719 if (size == 0) {
4720 return sizeof(supported);
4723 if (sizeof(supported) > size) {
4724 errno = ERANGE;
4725 return -1;
4728 /* this can't be strcpy() because there are embedded null characters */
4729 memcpy(list, supported, sizeof(supported));
4730 return sizeof(supported);
4735 * Open a print file to be written to by other calls
4738 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
4740 fstring server, share, user, password;
4741 pstring path;
4743 if (!context || !context->internal ||
4744 !context->internal->_initialized) {
4746 errno = EINVAL;
4747 return NULL;
4751 if (!fname) {
4753 errno = EINVAL;
4754 return NULL;
4758 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
4760 if (smbc_parse_path(context, fname,
4761 server, sizeof(server),
4762 share, sizeof(share),
4763 path, sizeof(path),
4764 user, sizeof(user),
4765 password, sizeof(password),
4766 NULL, 0)) {
4767 errno = EINVAL;
4768 return NULL;
4771 /* What if the path is empty, or the file exists? */
4773 return context->open(context, fname, O_WRONLY, 666);
4778 * Routine to print a file on a remote server ...
4780 * We open the file, which we assume to be on a remote server, and then
4781 * copy it to a print file on the share specified by printq.
4784 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
4786 SMBCFILE *fid1, *fid2;
4787 int bytes, saverr, tot_bytes = 0;
4788 char buf[4096];
4790 if (!c_file || !c_file->internal->_initialized || !c_print ||
4791 !c_print->internal->_initialized) {
4793 errno = EINVAL;
4794 return -1;
4798 if (!fname && !printq) {
4800 errno = EINVAL;
4801 return -1;
4805 /* Try to open the file for reading ... */
4807 if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
4809 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
4810 return -1; /* smbc_open sets errno */
4814 /* Now, try to open the printer file for writing */
4816 if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
4818 saverr = errno; /* Save errno */
4819 c_file->close(c_file, fid1);
4820 errno = saverr;
4821 return -1;
4825 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
4827 tot_bytes += bytes;
4829 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
4831 saverr = errno;
4832 c_file->close(c_file, fid1);
4833 c_print->close(c_print, fid2);
4834 errno = saverr;
4840 saverr = errno;
4842 c_file->close(c_file, fid1); /* We have to close these anyway */
4843 c_print->close(c_print, fid2);
4845 if (bytes < 0) {
4847 errno = saverr;
4848 return -1;
4852 return tot_bytes;
4857 * Routine to list print jobs on a printer share ...
4860 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
4862 SMBCSRV *srv;
4863 fstring server, share, user, password, workgroup;
4864 pstring path;
4866 if (!context || !context->internal ||
4867 !context->internal->_initialized) {
4869 errno = EINVAL;
4870 return -1;
4874 if (!fname) {
4876 errno = EINVAL;
4877 return -1;
4881 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
4883 if (smbc_parse_path(context, fname,
4884 server, sizeof(server),
4885 share, sizeof(share),
4886 path, sizeof(path),
4887 user, sizeof(user),
4888 password, sizeof(password),
4889 NULL, 0)) {
4890 errno = EINVAL;
4891 return -1;
4894 if (user[0] == (char)0) fstrcpy(user, context->user);
4896 fstrcpy(workgroup, context->workgroup);
4898 srv = smbc_server(context, server, share, workgroup, user, password);
4900 if (!srv) {
4902 return -1; /* errno set by smbc_server */
4906 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
4908 errno = smbc_errno(context, &srv->cli);
4909 return -1;
4913 return 0;
4918 * Delete a print job from a remote printer share
4921 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
4923 SMBCSRV *srv;
4924 fstring server, share, user, password, workgroup;
4925 pstring path;
4926 int err;
4928 if (!context || !context->internal ||
4929 !context->internal->_initialized) {
4931 errno = EINVAL;
4932 return -1;
4936 if (!fname) {
4938 errno = EINVAL;
4939 return -1;
4943 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
4945 if (smbc_parse_path(context, fname,
4946 server, sizeof(server),
4947 share, sizeof(share),
4948 path, sizeof(path),
4949 user, sizeof(user),
4950 password, sizeof(password),
4951 NULL, 0)) {
4952 errno = EINVAL;
4953 return -1;
4956 if (user[0] == (char)0) fstrcpy(user, context->user);
4958 fstrcpy(workgroup, context->workgroup);
4960 srv = smbc_server(context, server, share, workgroup, user, password);
4962 if (!srv) {
4964 return -1; /* errno set by smbc_server */
4968 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
4970 if (err < 0)
4971 errno = smbc_errno(context, &srv->cli);
4972 else if (err == ERRnosuchprintjob)
4973 errno = EINVAL;
4974 return -1;
4978 return 0;
4983 * Get a new empty handle to fill in with your own info
4985 SMBCCTX * smbc_new_context(void)
4987 SMBCCTX * context;
4989 context = SMB_MALLOC_P(SMBCCTX);
4990 if (!context) {
4991 errno = ENOMEM;
4992 return NULL;
4995 ZERO_STRUCTP(context);
4997 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
4998 if (!context->internal) {
4999 errno = ENOMEM;
5000 return NULL;
5003 ZERO_STRUCTP(context->internal);
5006 /* ADD REASONABLE DEFAULTS */
5007 context->debug = 0;
5008 context->timeout = 20000; /* 20 seconds */
5010 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5011 context->options.urlencode_readdir_entries = False;/* backward compat */
5012 context->options.one_share_per_server = False;/* backward compat */
5014 context->open = smbc_open_ctx;
5015 context->creat = smbc_creat_ctx;
5016 context->read = smbc_read_ctx;
5017 context->write = smbc_write_ctx;
5018 context->close = smbc_close_ctx;
5019 context->unlink = smbc_unlink_ctx;
5020 context->rename = smbc_rename_ctx;
5021 context->lseek = smbc_lseek_ctx;
5022 context->stat = smbc_stat_ctx;
5023 context->fstat = smbc_fstat_ctx;
5024 context->opendir = smbc_opendir_ctx;
5025 context->closedir = smbc_closedir_ctx;
5026 context->readdir = smbc_readdir_ctx;
5027 context->getdents = smbc_getdents_ctx;
5028 context->mkdir = smbc_mkdir_ctx;
5029 context->rmdir = smbc_rmdir_ctx;
5030 context->telldir = smbc_telldir_ctx;
5031 context->lseekdir = smbc_lseekdir_ctx;
5032 context->fstatdir = smbc_fstatdir_ctx;
5033 context->chmod = smbc_chmod_ctx;
5034 context->utimes = smbc_utimes_ctx;
5035 context->setxattr = smbc_setxattr_ctx;
5036 context->getxattr = smbc_getxattr_ctx;
5037 context->removexattr = smbc_removexattr_ctx;
5038 context->listxattr = smbc_listxattr_ctx;
5039 context->open_print_job = smbc_open_print_job_ctx;
5040 context->print_file = smbc_print_file_ctx;
5041 context->list_print_jobs = smbc_list_print_jobs_ctx;
5042 context->unlink_print_job = smbc_unlink_print_job_ctx;
5044 context->callbacks.check_server_fn = smbc_check_server;
5045 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5047 smbc_default_cache_functions(context);
5049 return context;
5053 * Free a context
5055 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5056 * and thus you'll be leaking memory if not handled properly.
5059 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
5061 if (!context) {
5062 errno = EBADF;
5063 return 1;
5066 if (shutdown_ctx) {
5067 SMBCFILE * f;
5068 DEBUG(1,("Performing aggressive shutdown.\n"));
5070 f = context->internal->_files;
5071 while (f) {
5072 context->close(context, f);
5073 f = f->next;
5075 context->internal->_files = NULL;
5077 /* First try to remove the servers the nice way. */
5078 if (context->callbacks.purge_cached_fn(context)) {
5079 SMBCSRV * s;
5080 SMBCSRV * next;
5081 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
5082 s = context->internal->_servers;
5083 while (s) {
5084 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
5085 cli_shutdown(&s->cli);
5086 context->callbacks.remove_cached_srv_fn(context, s);
5087 next = s->next;
5088 DLIST_REMOVE(context->internal->_servers, s);
5089 SAFE_FREE(s);
5090 s = next;
5092 context->internal->_servers = NULL;
5095 else {
5096 /* This is the polite way */
5097 if (context->callbacks.purge_cached_fn(context)) {
5098 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
5099 errno = EBUSY;
5100 return 1;
5102 if (context->internal->_servers) {
5103 DEBUG(1, ("Active servers in context, free_context failed.\n"));
5104 errno = EBUSY;
5105 return 1;
5107 if (context->internal->_files) {
5108 DEBUG(1, ("Active files in context, free_context failed.\n"));
5109 errno = EBUSY;
5110 return 1;
5114 /* Things we have to clean up */
5115 SAFE_FREE(context->workgroup);
5116 SAFE_FREE(context->netbios_name);
5117 SAFE_FREE(context->user);
5119 DEBUG(3, ("Context %p succesfully freed\n", context));
5120 SAFE_FREE(context->internal);
5121 SAFE_FREE(context);
5122 return 0;
5127 * Initialise the library etc
5129 * We accept a struct containing handle information.
5130 * valid values for info->debug from 0 to 100,
5131 * and insist that info->fn must be non-null.
5133 SMBCCTX * smbc_init_context(SMBCCTX * context)
5135 pstring conf;
5136 int pid;
5137 char *user = NULL, *home = NULL;
5139 if (!context || !context->internal) {
5140 errno = EBADF;
5141 return NULL;
5144 /* Do not initialise the same client twice */
5145 if (context->internal->_initialized) {
5146 return 0;
5149 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
5151 errno = EINVAL;
5152 return NULL;
5156 if (!smbc_initialized) {
5157 /* Do some library wide intialisations the first time we get called */
5159 /* Set this to what the user wants */
5160 DEBUGLEVEL = context->debug;
5162 setup_logging( "libsmbclient", True);
5164 /* Here we would open the smb.conf file if needed ... */
5166 home = getenv("HOME");
5168 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5170 load_interfaces(); /* Load the list of interfaces ... */
5172 in_client = True; /* FIXME, make a param */
5174 if (!lp_load(conf, True, False, False)) {
5177 * Well, if that failed, try the dyn_CONFIGFILE
5178 * Which points to the standard locn, and if that
5179 * fails, silently ignore it and use the internal
5180 * defaults ...
5183 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
5184 DEBUG(5, ("Could not load either config file: "
5185 "%s or %s\n",
5186 conf, dyn_CONFIGFILE));
5187 } else {
5189 * We loaded the global config file. Now lets
5190 * load user-specific modifications to the
5191 * global config.
5193 slprintf(conf, sizeof(conf),
5194 "%s/.smb/smb.conf.append", home);
5195 if (!lp_load(conf, True, False, False)) {
5196 DEBUG(10,
5197 ("Could not append config file: "
5198 "%s\n",
5199 conf));
5204 reopen_logs(); /* Get logging working ... */
5207 * Block SIGPIPE (from lib/util_sock.c: write())
5208 * It is not needed and should not stop execution
5210 BlockSignals(True, SIGPIPE);
5212 /* Done with one-time initialisation */
5213 smbc_initialized = 1;
5217 if (!context->user) {
5219 * FIXME: Is this the best way to get the user info?
5221 user = getenv("USER");
5222 /* walk around as "guest" if no username can be found */
5223 if (!user) context->user = SMB_STRDUP("guest");
5224 else context->user = SMB_STRDUP(user);
5227 if (!context->netbios_name) {
5229 * We try to get our netbios name from the config. If that fails we fall
5230 * back on constructing our netbios name from our hostname etc
5232 if (global_myname()) {
5233 context->netbios_name = SMB_STRDUP(global_myname());
5235 else {
5237 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
5239 pid = sys_getpid();
5240 context->netbios_name = SMB_MALLOC(17);
5241 if (!context->netbios_name) {
5242 errno = ENOMEM;
5243 return NULL;
5245 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
5249 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
5251 if (!context->workgroup) {
5252 if (lp_workgroup()) {
5253 context->workgroup = SMB_STRDUP(lp_workgroup());
5255 else {
5256 /* TODO: Think about a decent default workgroup */
5257 context->workgroup = SMB_STRDUP("samba");
5261 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
5263 /* shortest timeout is 1 second */
5264 if (context->timeout > 0 && context->timeout < 1000)
5265 context->timeout = 1000;
5268 * FIXME: Should we check the function pointers here?
5271 context->internal->_initialized = 1;
5273 return context;
5277 /* Return the verion of samba, and thus libsmbclient */
5278 const char *
5279 smbc_version(void)
5281 return samba_version_string();