r6155: Fixes bug #1133
[Samba.git] / source / libsmb / libsmbclient.c
blob657d0925b0aed32e8435ec242cd9b15298d1a79c
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;
562 zero_ip(&ip);
563 ZERO_STRUCT(c);
565 if (server[0] == 0) {
566 errno = EPERM;
567 return NULL;
570 srv = find_server(context, server, share,
571 workgroup, username, password);
574 * If we found a connection and we're only allowed one share per
575 * server...
577 if (srv && *share != '\0' && context->options.one_share_per_server) {
580 * ... then if there's no current connection to the share,
581 * connect to it. find_server(), or rather the function
582 * pointed to by context->callbacks.get_cached_srv_fn which
583 * was called by find_server(), will have issued a tree
584 * disconnect if the requested share is not the same as the
585 * one that was already connected.
587 if (srv->cli.cnum == (uint16) -1) {
588 /* Ensure we have accurate auth info */
589 context->callbacks.auth_fn(server, share,
590 workgroup, sizeof(fstring),
591 username, sizeof(fstring),
592 password, sizeof(fstring));
594 if (! cli_send_tconX(&srv->cli, share, "?????",
595 password, strlen(password)+1)) {
597 errno = smbc_errno(context, &srv->cli);
598 cli_shutdown(&srv->cli);
599 context->callbacks.remove_cached_srv_fn(context, srv);
600 srv = NULL;
603 /* Regenerate the dev value since it's based on both server and share */
604 if (srv) {
605 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
610 /* If we have a connection... */
611 if (srv) {
613 /* ... then we're done here. Give 'em what they came for. */
614 return srv;
617 make_nmb_name(&calling, context->netbios_name, 0x0);
618 make_nmb_name(&called , server, 0x20);
620 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
622 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
624 again:
625 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
627 zero_ip(&ip);
629 /* have to open a new connection */
630 if (!cli_initialise(&c)) {
631 errno = ENOMEM;
632 return NULL;
635 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
636 c.use_kerberos = True;
638 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
639 c.fallback_after_kerberos = True;
642 c.timeout = context->timeout;
645 * Force use of port 139 for first try if share is $IPC, empty, or
646 * null, so browse lists can work
648 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0)
650 port_try_first = 139;
651 port_try_next = 445;
653 else
655 port_try_first = 445;
656 port_try_next = 139;
659 c.port = port_try_first;
661 if (!cli_connect(&c, server_n, &ip)) {
663 /* First connection attempt failed. Try alternate port. */
664 c.port = port_try_next;
666 if (!cli_connect(&c, server_n, &ip)) {
667 cli_shutdown(&c);
668 errno = ETIMEDOUT;
669 return NULL;
673 if (!cli_session_request(&c, &calling, &called)) {
674 cli_shutdown(&c);
675 if (strcmp(called.name, "*SMBSERVER")) {
676 make_nmb_name(&called , "*SMBSERVER", 0x20);
677 goto again;
679 else { /* Try one more time, but ensure we don't loop */
681 /* Only try this if server is an IP address ... */
683 if (is_ipaddress(server) && !tried_reverse) {
684 fstring remote_name;
685 struct in_addr rem_ip;
687 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
688 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
689 errno = ETIMEDOUT;
690 return NULL;
693 tried_reverse++; /* Yuck */
695 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
696 make_nmb_name(&called, remote_name, 0x20);
697 goto again;
703 errno = ETIMEDOUT;
704 return NULL;
707 DEBUG(4,(" session request ok\n"));
709 if (!cli_negprot(&c)) {
710 cli_shutdown(&c);
711 errno = ETIMEDOUT;
712 return NULL;
715 if (!cli_session_setup(&c, username,
716 password, strlen(password),
717 password, strlen(password),
718 workgroup) &&
719 /* Try an anonymous login if it failed and this was allowed by flags. */
720 ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
721 !cli_session_setup(&c, "", "", 1,"", 0, workgroup))) {
722 cli_shutdown(&c);
723 errno = EPERM;
724 return NULL;
727 DEBUG(4,(" session setup ok\n"));
729 if (!cli_send_tconX(&c, share, "?????",
730 password, strlen(password)+1)) {
731 errno = smbc_errno(context, &c);
732 cli_shutdown(&c);
733 return NULL;
736 DEBUG(4,(" tconx ok\n"));
739 * Ok, we have got a nice connection
740 * Let's find a free server_fd
743 srv = SMB_MALLOC_P(SMBCSRV);
744 if (!srv) {
745 errno = ENOMEM;
746 goto failed;
749 ZERO_STRUCTP(srv);
750 srv->cli = c;
751 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
753 /* now add it to the cache (internal or external) */
754 /* Let the cache function set errno if it wants to */
755 errno = 0;
756 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
757 int saved_errno = errno;
758 DEBUG(3, (" Failed to add server to cache\n"));
759 errno = saved_errno;
760 if (errno == 0) {
761 errno = ENOMEM;
763 goto failed;
766 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
767 server, share, srv));
769 DLIST_ADD(context->internal->_servers, srv);
770 return srv;
772 failed:
773 cli_shutdown(&c);
774 if (!srv) return NULL;
776 SAFE_FREE(srv);
777 return NULL;
781 * Connect to a server for getting/setting attributes, possibly on an existing
782 * connection. This works similarly to smbc_server().
784 SMBCSRV *smbc_attr_server(SMBCCTX *context,
785 const char *server, const char *share,
786 fstring workgroup,
787 fstring username, fstring password,
788 POLICY_HND *pol)
790 struct in_addr ip;
791 struct cli_state *ipc_cli;
792 NTSTATUS nt_status;
793 SMBCSRV *ipc_srv=NULL;
796 * See if we've already created this special connection. Reference our
797 * "special" share name '*IPC$', which is an impossible real share name
798 * due to the leading asterisk.
800 ipc_srv = find_server(context, server, "*IPC$",
801 workgroup, username, password);
802 if (!ipc_srv) {
804 /* We didn't find a cached connection. Get the password */
805 if (*password == '\0') {
806 /* ... then retrieve it now. */
807 context->callbacks.auth_fn(server, share,
808 workgroup, sizeof(fstring),
809 username, sizeof(fstring),
810 password, sizeof(fstring));
813 zero_ip(&ip);
814 nt_status = cli_full_connection(&ipc_cli,
815 global_myname(), server,
816 &ip, 0, "IPC$", "?????",
817 username, workgroup,
818 password, 0,
819 Undefined, NULL);
820 if (! NT_STATUS_IS_OK(nt_status)) {
821 DEBUG(1,("cli_full_connection failed! (%s)\n",
822 nt_errstr(nt_status)));
823 errno = ENOTSUP;
824 return NULL;
827 if (!cli_nt_session_open(ipc_cli, PI_LSARPC)) {
828 DEBUG(1, ("cli_nt_session_open fail!\n"));
829 errno = ENOTSUP;
830 cli_shutdown(ipc_cli);
831 return NULL;
834 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
835 but NT sends 0x2000000 so we might as well do it too. */
837 nt_status = cli_lsa_open_policy(ipc_cli,
838 ipc_cli->mem_ctx,
839 True,
840 GENERIC_EXECUTE_ACCESS,
841 pol);
843 if (!NT_STATUS_IS_OK(nt_status)) {
844 errno = smbc_errno(context, ipc_cli);
845 cli_shutdown(ipc_cli);
846 return NULL;
849 ipc_srv = SMB_MALLOC_P(SMBCSRV);
850 if (!ipc_srv) {
851 errno = ENOMEM;
852 cli_shutdown(ipc_cli);
853 return NULL;
856 ZERO_STRUCTP(ipc_srv);
857 ipc_srv->cli = *ipc_cli;
859 free(ipc_cli);
861 /* now add it to the cache (internal or external) */
863 errno = 0; /* let cache function set errno if it likes */
864 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
865 server,
866 "*IPC$",
867 workgroup,
868 username)) {
869 DEBUG(3, (" Failed to add server to cache\n"));
870 if (errno == 0) {
871 errno = ENOMEM;
873 cli_shutdown(&ipc_srv->cli);
874 free(ipc_srv);
875 return NULL;
878 DLIST_ADD(context->internal->_servers, ipc_srv);
881 return ipc_srv;
885 * Routine to open() a file ...
888 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
890 fstring server, share, user, password, workgroup;
891 pstring path;
892 SMBCSRV *srv = NULL;
893 SMBCFILE *file = NULL;
894 int fd;
896 if (!context || !context->internal ||
897 !context->internal->_initialized) {
899 errno = EINVAL; /* Best I can think of ... */
900 return NULL;
904 if (!fname) {
906 errno = EINVAL;
907 return NULL;
911 if (smbc_parse_path(context, fname,
912 server, sizeof(server),
913 share, sizeof(share),
914 path, sizeof(path),
915 user, sizeof(user),
916 password, sizeof(password),
917 NULL, 0)) {
918 errno = EINVAL;
919 return NULL;
922 if (user[0] == (char)0) fstrcpy(user, context->user);
924 fstrcpy(workgroup, context->workgroup);
926 srv = smbc_server(context, server, share, workgroup, user, password);
928 if (!srv) {
930 if (errno == EPERM) errno = EACCES;
931 return NULL; /* smbc_server sets errno */
935 /* Hmmm, the test for a directory is suspect here ... FIXME */
937 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
939 fd = -1;
942 else {
944 file = SMB_MALLOC_P(SMBCFILE);
946 if (!file) {
948 errno = ENOMEM;
949 return NULL;
953 ZERO_STRUCTP(file);
955 if ((fd = cli_open(&srv->cli, path, flags, DENY_NONE)) < 0) {
957 /* Handle the error ... */
959 SAFE_FREE(file);
960 errno = smbc_errno(context, &srv->cli);
961 return NULL;
965 /* Fill in file struct */
967 file->cli_fd = fd;
968 file->fname = SMB_STRDUP(fname);
969 file->srv = srv;
970 file->offset = 0;
971 file->file = True;
973 DLIST_ADD(context->internal->_files, file);
976 * If the file was opened in O_APPEND mode, all write
977 * operations should be appended to the file. To do that,
978 * though, using this protocol, would require a getattrE()
979 * call for each and every write, to determine where the end
980 * of the file is. (There does not appear to be an append flag
981 * in the protocol.) Rather than add all of that overhead of
982 * retrieving the current end-of-file offset prior to each
983 * write operation, we'll assume that most append operations
984 * will continuously write, so we'll just set the offset to
985 * the end of the file now and hope that's adequate.
987 * Note to self: If this proves inadequate, and O_APPEND
988 * should, in some cases, be forced for each write, add a
989 * field in the context options structure, for
990 * "strict_append_mode" which would select between the current
991 * behavior (if FALSE) or issuing a getattrE() prior to each
992 * write and forcing the write to the end of the file (if
993 * TRUE). Adding that capability will likely require adding
994 * an "append" flag into the _SMBCFILE structure to track
995 * whether a file was opened in O_APPEND mode. -- djl
997 if (flags & O_APPEND) {
998 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
999 (void) smbc_close_ctx(context, file);
1000 errno = ENXIO;
1001 return NULL;
1005 return file;
1009 /* Check if opendir needed ... */
1011 if (fd == -1) {
1012 int eno = 0;
1014 eno = smbc_errno(context, &srv->cli);
1015 file = context->opendir(context, fname);
1016 if (!file) errno = eno;
1017 return file;
1021 errno = EINVAL; /* FIXME, correct errno ? */
1022 return NULL;
1027 * Routine to create a file
1030 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1032 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
1035 if (!context || !context->internal ||
1036 !context->internal->_initialized) {
1038 errno = EINVAL;
1039 return NULL;
1043 return smbc_open_ctx(context, path, creat_bits, mode);
1047 * Routine to read() a file ...
1050 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1052 int ret;
1055 * offset:
1057 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1058 * appears to pass file->offset (which is type off_t) differently than
1059 * a local variable of type off_t. Using local variable "offset" in
1060 * the call to cli_read() instead of file->offset fixes a problem
1061 * retrieving data at an offset greater than 4GB.
1063 off_t offset = file->offset;
1065 if (!context || !context->internal ||
1066 !context->internal->_initialized) {
1068 errno = EINVAL;
1069 return -1;
1073 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1075 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1077 errno = EBADF;
1078 return -1;
1082 /* Check that the buffer exists ... */
1084 if (buf == NULL) {
1086 errno = EINVAL;
1087 return -1;
1091 ret = cli_read(&file->srv->cli, file->cli_fd, buf, offset, count);
1093 if (ret < 0) {
1095 errno = smbc_errno(context, &file->srv->cli);
1096 return -1;
1100 file->offset += ret;
1102 DEBUG(4, (" --> %d\n", ret));
1104 return ret; /* Success, ret bytes of data ... */
1109 * Routine to write() a file ...
1112 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1114 int ret;
1115 off_t offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1117 if (!context || !context->internal ||
1118 !context->internal->_initialized) {
1120 errno = EINVAL;
1121 return -1;
1125 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1127 errno = EBADF;
1128 return -1;
1132 /* Check that the buffer exists ... */
1134 if (buf == NULL) {
1136 errno = EINVAL;
1137 return -1;
1141 ret = cli_write(&file->srv->cli, file->cli_fd, 0, buf, offset, count);
1143 if (ret <= 0) {
1145 errno = smbc_errno(context, &file->srv->cli);
1146 return -1;
1150 file->offset += ret;
1152 return ret; /* Success, 0 bytes of data ... */
1156 * Routine to close() a file ...
1159 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1161 SMBCSRV *srv;
1163 if (!context || !context->internal ||
1164 !context->internal->_initialized) {
1166 errno = EINVAL;
1167 return -1;
1171 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1173 errno = EBADF;
1174 return -1;
1178 /* IS a dir ... */
1179 if (!file->file) {
1181 return context->closedir(context, file);
1185 if (!cli_close(&file->srv->cli, file->cli_fd)) {
1187 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1188 file->fname));
1189 /* Deallocate slot and remove the server
1190 * from the server cache if unused */
1191 errno = smbc_errno(context, &file->srv->cli);
1192 srv = file->srv;
1193 DLIST_REMOVE(context->internal->_files, file);
1194 SAFE_FREE(file->fname);
1195 SAFE_FREE(file);
1196 context->callbacks.remove_unused_server_fn(context, srv);
1198 return -1;
1202 DLIST_REMOVE(context->internal->_files, file);
1203 SAFE_FREE(file->fname);
1204 SAFE_FREE(file);
1206 return 0;
1210 * Get info from an SMB server on a file. Use a qpathinfo call first
1211 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1213 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1214 uint16 *mode, SMB_OFF_T *size,
1215 time_t *c_time, time_t *a_time, time_t *m_time,
1216 SMB_INO_T *ino)
1219 if (!context || !context->internal ||
1220 !context->internal->_initialized) {
1222 errno = EINVAL;
1223 return -1;
1227 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1229 if (!srv->no_pathinfo2 &&
1230 cli_qpathinfo2(&srv->cli, path, c_time, a_time, m_time, NULL,
1231 size, mode, ino)) return True;
1233 /* if this is NT then don't bother with the getatr */
1234 if (srv->cli.capabilities & CAP_NT_SMBS) {
1235 errno = EPERM;
1236 return False;
1239 if (cli_getatr(&srv->cli, path, mode, size, m_time)) {
1240 a_time = c_time = m_time;
1241 srv->no_pathinfo2 = True;
1242 return True;
1245 errno = EPERM;
1246 return False;
1251 * Routine to unlink() a file
1254 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1256 fstring server, share, user, password, workgroup;
1257 pstring path;
1258 SMBCSRV *srv = NULL;
1260 if (!context || !context->internal ||
1261 !context->internal->_initialized) {
1263 errno = EINVAL; /* Best I can think of ... */
1264 return -1;
1268 if (!fname) {
1270 errno = EINVAL;
1271 return -1;
1275 if (smbc_parse_path(context, fname,
1276 server, sizeof(server),
1277 share, sizeof(share),
1278 path, sizeof(path),
1279 user, sizeof(user),
1280 password, sizeof(password),
1281 NULL, 0)) {
1282 errno = EINVAL;
1283 return -1;
1286 if (user[0] == (char)0) fstrcpy(user, context->user);
1288 fstrcpy(workgroup, context->workgroup);
1290 srv = smbc_server(context, server, share, workgroup, user, password);
1292 if (!srv) {
1294 return -1; /* smbc_server sets errno */
1298 /* if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
1300 int job = smbc_stat_printjob(srv, path, NULL, NULL);
1301 if (job == -1) {
1303 return -1;
1306 if ((err = cli_printjob_del(&srv->cli, job)) != 0) {
1309 return -1;
1312 } else */
1314 if (!cli_unlink(&srv->cli, path)) {
1316 errno = smbc_errno(context, &srv->cli);
1318 if (errno == EACCES) { /* Check if the file is a directory */
1320 int saverr = errno;
1321 SMB_OFF_T size = 0;
1322 uint16 mode = 0;
1323 time_t m_time = 0, a_time = 0, c_time = 0;
1324 SMB_INO_T ino = 0;
1326 if (!smbc_getatr(context, srv, path, &mode, &size,
1327 &c_time, &a_time, &m_time, &ino)) {
1329 /* Hmmm, bad error ... What? */
1331 errno = smbc_errno(context, &srv->cli);
1332 return -1;
1335 else {
1337 if (IS_DOS_DIR(mode))
1338 errno = EISDIR;
1339 else
1340 errno = saverr; /* Restore this */
1345 return -1;
1349 return 0; /* Success ... */
1354 * Routine to rename() a file
1357 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1358 SMBCCTX *ncontext, const char *nname)
1360 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1361 pstring path1, path2;
1362 SMBCSRV *srv = NULL;
1364 if (!ocontext || !ncontext ||
1365 !ocontext->internal || !ncontext->internal ||
1366 !ocontext->internal->_initialized ||
1367 !ncontext->internal->_initialized) {
1369 errno = EINVAL; /* Best I can think of ... */
1370 return -1;
1374 if (!oname || !nname) {
1376 errno = EINVAL;
1377 return -1;
1381 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1383 smbc_parse_path(ocontext, oname,
1384 server1, sizeof(server1),
1385 share1, sizeof(share1),
1386 path1, sizeof(path1),
1387 user1, sizeof(user1),
1388 password1, sizeof(password1),
1389 NULL, 0);
1391 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1393 smbc_parse_path(ncontext, nname,
1394 server2, sizeof(server2),
1395 share2, sizeof(share2),
1396 path2, sizeof(path2),
1397 user2, sizeof(user2),
1398 password2, sizeof(password2),
1399 NULL, 0);
1401 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1403 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1404 strcmp(user1, user2)) {
1406 /* Can't rename across file systems, or users?? */
1408 errno = EXDEV;
1409 return -1;
1413 fstrcpy(workgroup, ocontext->workgroup);
1414 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1415 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1416 if (!srv) {
1418 return -1;
1422 if (!cli_rename(&srv->cli, path1, path2)) {
1423 int eno = smbc_errno(ocontext, &srv->cli);
1425 if (eno != EEXIST ||
1426 !cli_unlink(&srv->cli, path2) ||
1427 !cli_rename(&srv->cli, path1, path2)) {
1429 errno = eno;
1430 return -1;
1435 return 0; /* Success */
1440 * A routine to lseek() a file
1443 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1445 SMB_OFF_T size;
1447 if (!context || !context->internal ||
1448 !context->internal->_initialized) {
1450 errno = EINVAL;
1451 return -1;
1455 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1457 errno = EBADF;
1458 return -1;
1462 if (!file->file) {
1464 errno = EINVAL;
1465 return -1; /* Can't lseek a dir ... */
1469 switch (whence) {
1470 case SEEK_SET:
1471 file->offset = offset;
1472 break;
1474 case SEEK_CUR:
1475 file->offset += offset;
1476 break;
1478 case SEEK_END:
1479 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
1480 NULL, NULL, NULL))
1482 SMB_BIG_UINT b_size = size;
1483 if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
1484 NULL))
1486 errno = EINVAL;
1487 return -1;
1488 } else
1489 size = b_size;
1491 file->offset = size + offset;
1492 break;
1494 default:
1495 errno = EINVAL;
1496 break;
1500 return file->offset;
1505 * Generate an inode number from file name for those things that need it
1508 static
1509 ino_t smbc_inode(SMBCCTX *context, const char *name)
1512 if (!context || !context->internal ||
1513 !context->internal->_initialized) {
1515 errno = EINVAL;
1516 return -1;
1520 if (!*name) return 2; /* FIXME, why 2 ??? */
1521 return (ino_t)str_checksum(name);
1526 * Routine to put basic stat info into a stat structure ... Used by stat and
1527 * fstat below.
1530 static
1531 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname,
1532 SMB_OFF_T size, int mode)
1535 st->st_mode = 0;
1537 if (IS_DOS_DIR(mode)) {
1538 st->st_mode = SMBC_DIR_MODE;
1539 } else {
1540 st->st_mode = SMBC_FILE_MODE;
1543 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1544 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1545 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1546 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1548 st->st_size = size;
1549 #ifdef HAVE_STAT_ST_BLKSIZE
1550 st->st_blksize = 512;
1551 #endif
1552 #ifdef HAVE_STAT_ST_BLOCKS
1553 st->st_blocks = (size+511)/512;
1554 #endif
1555 st->st_uid = getuid();
1556 st->st_gid = getgid();
1558 if (IS_DOS_DIR(mode)) {
1559 st->st_nlink = 2;
1560 } else {
1561 st->st_nlink = 1;
1564 if (st->st_ino == 0) {
1565 st->st_ino = smbc_inode(context, fname);
1568 return True; /* FIXME: Is this needed ? */
1573 * Routine to stat a file given a name
1576 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1578 SMBCSRV *srv;
1579 fstring server, share, user, password, workgroup;
1580 pstring path;
1581 time_t m_time = 0, a_time = 0, c_time = 0;
1582 SMB_OFF_T size = 0;
1583 uint16 mode = 0;
1584 SMB_INO_T ino = 0;
1586 if (!context || !context->internal ||
1587 !context->internal->_initialized) {
1589 errno = EINVAL; /* Best I can think of ... */
1590 return -1;
1594 if (!fname) {
1596 errno = EINVAL;
1597 return -1;
1601 DEBUG(4, ("smbc_stat(%s)\n", fname));
1603 if (smbc_parse_path(context, fname,
1604 server, sizeof(server),
1605 share, sizeof(share),
1606 path, sizeof(path),
1607 user, sizeof(user),
1608 password, sizeof(password),
1609 NULL, 0)) {
1610 errno = EINVAL;
1611 return -1;
1614 if (user[0] == (char)0) fstrcpy(user, context->user);
1616 fstrcpy(workgroup, context->workgroup);
1618 srv = smbc_server(context, server, share, workgroup, user, password);
1620 if (!srv) {
1621 return -1; /* errno set by smbc_server */
1624 if (!smbc_getatr(context, srv, path, &mode, &size,
1625 &c_time, &a_time, &m_time, &ino)) {
1627 errno = smbc_errno(context, &srv->cli);
1628 return -1;
1632 st->st_ino = ino;
1634 smbc_setup_stat(context, st, path, size, mode);
1636 st->st_atime = a_time;
1637 st->st_ctime = c_time;
1638 st->st_mtime = m_time;
1639 st->st_dev = srv->dev;
1641 return 0;
1646 * Routine to stat a file given an fd
1649 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1651 time_t c_time, a_time, m_time;
1652 SMB_OFF_T size;
1653 uint16 mode;
1654 SMB_INO_T ino = 0;
1656 if (!context || !context->internal ||
1657 !context->internal->_initialized) {
1659 errno = EINVAL;
1660 return -1;
1664 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1666 errno = EBADF;
1667 return -1;
1671 if (!file->file) {
1673 return context->fstatdir(context, file, st);
1677 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
1678 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
1679 if (!cli_getattrE(&file->srv->cli, file->cli_fd,
1680 &mode, &size, &c_time, &a_time, &m_time)) {
1682 errno = EINVAL;
1683 return -1;
1687 st->st_ino = ino;
1689 smbc_setup_stat(context, st, file->fname, size, mode);
1691 st->st_atime = a_time;
1692 st->st_ctime = c_time;
1693 st->st_mtime = m_time;
1694 st->st_dev = file->srv->dev;
1696 return 0;
1701 * Routine to open a directory
1702 * We accept the URL syntax explained in smbc_parse_path(), above.
1705 static void smbc_remove_dir(SMBCFILE *dir)
1707 struct smbc_dir_list *d,*f;
1709 d = dir->dir_list;
1710 while (d) {
1712 f = d; d = d->next;
1714 SAFE_FREE(f->dirent);
1715 SAFE_FREE(f);
1719 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
1723 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
1725 struct smbc_dirent *dirent;
1726 int size;
1727 int name_length = (name == NULL ? 0 : strlen(name));
1728 int comment_len = (comment == NULL ? 0 : strlen(comment));
1731 * Allocate space for the dirent, which must be increased by the
1732 * size of the name and the comment and 1 each for the null terminator.
1735 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
1737 dirent = SMB_MALLOC(size);
1739 if (!dirent) {
1741 dir->dir_error = ENOMEM;
1742 return -1;
1746 ZERO_STRUCTP(dirent);
1748 if (dir->dir_list == NULL) {
1750 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
1751 if (!dir->dir_list) {
1753 SAFE_FREE(dirent);
1754 dir->dir_error = ENOMEM;
1755 return -1;
1758 ZERO_STRUCTP(dir->dir_list);
1760 dir->dir_end = dir->dir_next = dir->dir_list;
1762 else {
1764 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
1766 if (!dir->dir_end->next) {
1768 SAFE_FREE(dirent);
1769 dir->dir_error = ENOMEM;
1770 return -1;
1773 ZERO_STRUCTP(dir->dir_end->next);
1775 dir->dir_end = dir->dir_end->next;
1778 dir->dir_end->next = NULL;
1779 dir->dir_end->dirent = dirent;
1781 dirent->smbc_type = type;
1782 dirent->namelen = name_length;
1783 dirent->commentlen = comment_len;
1784 dirent->dirlen = size;
1786 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
1788 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
1789 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
1791 return 0;
1795 static void
1796 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
1798 SMBCFILE *dir = (SMBCFILE *)state;
1799 struct smbc_dir_list *dir_list;
1800 struct smbc_dirent *dirent;
1801 int dirent_type;
1802 int do_remove = 0;
1804 dirent_type = dir->dir_type;
1806 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1808 /* An error occurred, what do we do? */
1809 /* FIXME: Add some code here */
1812 /* Point to the one just added */
1813 dirent = dir->dir_end->dirent;
1815 /* See if this was a duplicate */
1816 for (dir_list = dir->dir_list;
1817 dir_list != dir->dir_end;
1818 dir_list = dir_list->next) {
1819 if (! do_remove &&
1820 strcmp(dir_list->dirent->name, dirent->name) == 0) {
1821 /* Duplicate. End end of list need to be removed. */
1822 do_remove = 1;
1825 if (do_remove && dir_list->next == dir->dir_end) {
1826 /* Found the end of the list. Remove it. */
1827 dir->dir_end = dir_list;
1828 free(dir_list->next);
1829 dir_list->next = NULL;
1830 break;
1835 static void
1836 list_fn(const char *name, uint32 type, const char *comment, void *state)
1838 SMBCFILE *dir = (SMBCFILE *)state;
1839 int dirent_type;
1841 /* We need to process the type a little ... */
1843 if (dir->dir_type == SMBC_FILE_SHARE) {
1845 switch (type) {
1846 case 0: /* Directory tree */
1847 dirent_type = SMBC_FILE_SHARE;
1848 break;
1850 case 1:
1851 dirent_type = SMBC_PRINTER_SHARE;
1852 break;
1854 case 2:
1855 dirent_type = SMBC_COMMS_SHARE;
1856 break;
1858 case 3:
1859 dirent_type = SMBC_IPC_SHARE;
1860 break;
1862 default:
1863 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
1864 break;
1867 else dirent_type = dir->dir_type;
1869 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1871 /* An error occurred, what do we do? */
1872 /* FIXME: Add some code here */
1877 static void
1878 dir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
1881 if (add_dirent((SMBCFILE *)state, finfo->name, "",
1882 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
1884 /* Handle an error ... */
1886 /* FIXME: Add some code ... */
1892 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
1894 fstring server, share, user, password, options;
1895 pstring workgroup;
1896 pstring path;
1897 SMBCSRV *srv = NULL;
1898 SMBCFILE *dir = NULL;
1899 struct in_addr rem_ip;
1901 if (!context || !context->internal ||
1902 !context->internal->_initialized) {
1903 DEBUG(4, ("no valid context\n"));
1904 errno = EINVAL + 8192;
1905 return NULL;
1909 if (!fname) {
1910 DEBUG(4, ("no valid fname\n"));
1911 errno = EINVAL + 8193;
1912 return NULL;
1915 if (smbc_parse_path(context, fname,
1916 server, sizeof(server),
1917 share, sizeof(share),
1918 path, sizeof(path),
1919 user, sizeof(user),
1920 password, sizeof(password),
1921 options, sizeof(options))) {
1922 DEBUG(4, ("no valid path\n"));
1923 errno = EINVAL + 8194;
1924 return NULL;
1927 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
1929 /* Ensure the options are valid */
1930 if (smbc_check_options(server, share, path, options)) {
1931 DEBUG(4, ("unacceptable options (%s)\n", options));
1932 errno = EINVAL + 8195;
1933 return NULL;
1936 if (user[0] == (char)0) fstrcpy(user, context->user);
1938 pstrcpy(workgroup, context->workgroup);
1940 dir = SMB_MALLOC_P(SMBCFILE);
1942 if (!dir) {
1944 errno = ENOMEM;
1945 return NULL;
1949 ZERO_STRUCTP(dir);
1951 dir->cli_fd = 0;
1952 dir->fname = SMB_STRDUP(fname);
1953 dir->srv = NULL;
1954 dir->offset = 0;
1955 dir->file = False;
1956 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
1958 if (server[0] == (char)0) {
1960 int i;
1961 int count;
1962 int max_lmb_count;
1963 struct ip_service *ip_list;
1964 struct ip_service server_addr;
1965 struct user_auth_info u_info;
1966 struct cli_state *cli;
1968 if (share[0] != (char)0 || path[0] != (char)0) {
1970 errno = EINVAL + 8196;
1971 if (dir) {
1972 SAFE_FREE(dir->fname);
1973 SAFE_FREE(dir);
1975 return NULL;
1978 /* Determine how many local master browsers to query */
1979 max_lmb_count = (context->options.browse_max_lmb_count == 0
1980 ? INT_MAX
1981 : context->options.browse_max_lmb_count);
1983 pstrcpy(u_info.username, user);
1984 pstrcpy(u_info.password, password);
1987 * We have server and share and path empty but options
1988 * requesting that we scan all master browsers for their list
1989 * of workgroups/domains. This implies that we must first try
1990 * broadcast queries to find all master browsers, and if that
1991 * doesn't work, then try our other methods which return only
1992 * a single master browser.
1995 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
1996 if (!find_master_ip(workgroup, &server_addr.ip)) {
1998 errno = ENOENT;
1999 return NULL;
2002 ip_list = &server_addr;
2003 count = 1;
2006 for (i = 0; i < count && i < max_lmb_count; i++) {
2007 DEBUG(99, ("Found master browser %d of %d: %s\n", i+1, MAX(count, max_lmb_count), inet_ntoa(ip_list[i].ip)));
2009 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2010 /* cli == NULL is the master browser refused to talk or
2011 could not be found */
2012 if ( !cli )
2013 continue;
2015 fstrcpy(server, cli->desthost);
2016 cli_shutdown(cli);
2018 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2021 * For each returned master browser IP address, get a
2022 * connection to IPC$ on the server if we do not
2023 * already have one, and determine the
2024 * workgroups/domains that it knows about.
2027 srv = smbc_server(context, server,
2028 "IPC$", workgroup, user, password);
2029 if (!srv) {
2030 continue;
2033 dir->srv = srv;
2034 dir->dir_type = SMBC_WORKGROUP;
2036 /* Now, list the stuff ... */
2038 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2039 (void *)dir)) {
2041 continue;
2044 } else {
2046 * Server not an empty string ... Check the rest and see what
2047 * gives
2049 if (share[0] == (char)0) {
2051 if (path[0] != (char)0) { /* Should not have empty share with path */
2053 errno = EINVAL + 8197;
2054 if (dir) {
2055 SAFE_FREE(dir->fname);
2056 SAFE_FREE(dir);
2058 return NULL;
2062 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2063 /* However, we check to see if <server> is an IP address first */
2065 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2066 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2067 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2068 fstring buserver;
2070 dir->dir_type = SMBC_SERVER;
2073 * Get the backup list ...
2077 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2079 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2080 errno = EPERM; /* FIXME, is this correct */
2081 return NULL;
2086 * Get a connection to IPC$ on the server if we do not already have one
2089 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2091 if (!srv) {
2092 DEBUG(0, ("got no contact to IPC$\n"));
2093 if (dir) {
2094 SAFE_FREE(dir->fname);
2095 SAFE_FREE(dir);
2097 return NULL;
2101 dir->srv = srv;
2103 /* Now, list the servers ... */
2105 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2106 (void *)dir)) {
2108 if (dir) {
2109 SAFE_FREE(dir->fname);
2110 SAFE_FREE(dir);
2112 return NULL;
2116 else {
2118 if (resolve_name(server, &rem_ip, 0x20)) {
2120 /* Now, list the shares ... */
2122 dir->dir_type = SMBC_FILE_SHARE;
2124 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2126 if (!srv) {
2128 if (dir) {
2129 SAFE_FREE(dir->fname);
2130 SAFE_FREE(dir);
2132 return NULL;
2136 dir->srv = srv;
2138 /* Now, list the servers ... */
2140 if (cli_RNetShareEnum(&srv->cli, list_fn,
2141 (void *)dir) < 0) {
2143 errno = cli_errno(&srv->cli);
2144 if (dir) {
2145 SAFE_FREE(dir->fname);
2146 SAFE_FREE(dir);
2148 return NULL;
2153 else {
2155 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2156 if (dir) {
2157 SAFE_FREE(dir->fname);
2158 SAFE_FREE(dir);
2160 return NULL;
2167 else { /* The server and share are specified ... work from there ... */
2169 /* Well, we connect to the server and list the directory */
2171 dir->dir_type = SMBC_FILE_SHARE;
2173 srv = smbc_server(context, server, share, workgroup, user, password);
2175 if (!srv) {
2177 if (dir) {
2178 SAFE_FREE(dir->fname);
2179 SAFE_FREE(dir);
2181 return NULL;
2185 dir->srv = srv;
2187 /* Now, list the files ... */
2189 pstrcat(path, "\\*");
2191 if (cli_list(&srv->cli, path, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2192 (void *)dir) < 0) {
2194 if (dir) {
2195 SAFE_FREE(dir->fname);
2196 SAFE_FREE(dir);
2198 errno = smbc_errno(context, &srv->cli);
2199 return NULL;
2206 DLIST_ADD(context->internal->_files, dir);
2207 return dir;
2212 * Routine to close a directory
2215 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2218 if (!context || !context->internal ||
2219 !context->internal->_initialized) {
2221 errno = EINVAL;
2222 return -1;
2226 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2228 errno = EBADF;
2229 return -1;
2233 smbc_remove_dir(dir); /* Clean it up */
2235 DLIST_REMOVE(context->internal->_files, dir);
2237 if (dir) {
2239 SAFE_FREE(dir->fname);
2240 SAFE_FREE(dir); /* Free the space too */
2243 return 0;
2247 static void smbc_readdir_internal(SMBCCTX * context,
2248 struct smbc_dirent *dest,
2249 struct smbc_dirent *src,
2250 int max_namebuf_len)
2252 if (context->options.urlencode_readdir_entries) {
2254 /* url-encode the name. get back remaining buffer space */
2255 max_namebuf_len =
2256 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2258 /* We now know the name length */
2259 dest->namelen = strlen(dest->name);
2261 /* Save the pointer to the beginning of the comment */
2262 dest->comment = dest->name + dest->namelen + 1;
2264 /* Copy the comment */
2265 strncpy(dest->comment, src->comment, max_namebuf_len);
2267 /* Ensure the comment is null terminated */
2268 if (max_namebuf_len > src->commentlen) {
2269 dest->comment[src->commentlen] = '\0';
2270 } else {
2271 dest->comment[max_namebuf_len - 1] = '\0';
2274 /* Save other fields */
2275 dest->smbc_type = src->smbc_type;
2276 dest->commentlen = strlen(dest->comment);
2277 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2278 (char *) dest);
2279 } else {
2281 /* No encoding. Just copy the entry as is. */
2282 memcpy(dest, src, src->dirlen);
2283 dest->comment = (char *)(&dest->name + src->namelen + 1);
2289 * Routine to get a directory entry
2292 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2294 int maxlen;
2295 struct smbc_dirent *dirp, *dirent;
2297 /* Check that all is ok first ... */
2299 if (!context || !context->internal ||
2300 !context->internal->_initialized) {
2302 errno = EINVAL;
2303 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2304 return NULL;
2308 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2310 errno = EBADF;
2311 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2312 return NULL;
2316 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2318 errno = ENOTDIR;
2319 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2320 return NULL;
2324 if (!dir->dir_next) {
2325 return NULL;
2328 dirent = dir->dir_next->dirent;
2329 if (!dirent) {
2331 errno = ENOENT;
2332 return NULL;
2336 dirp = (struct smbc_dirent *)context->internal->_dirent;
2337 maxlen = (sizeof(context->internal->_dirent) -
2338 sizeof(struct smbc_dirent));
2340 smbc_readdir_internal(context, dirp, dirent, maxlen);
2342 dir->dir_next = dir->dir_next->next;
2344 return dirp;
2348 * Routine to get directory entries
2351 static int smbc_getdents_ctx(SMBCCTX *context,
2352 SMBCFILE *dir,
2353 struct smbc_dirent *dirp,
2354 int count)
2356 int rem = count;
2357 int reqd;
2358 int maxlen;
2359 char *ndir = (char *)dirp;
2360 struct smbc_dir_list *dirlist;
2362 /* Check that all is ok first ... */
2364 if (!context || !context->internal ||
2365 !context->internal->_initialized) {
2367 errno = EINVAL;
2368 return -1;
2372 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2374 errno = EBADF;
2375 return -1;
2379 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2381 errno = ENOTDIR;
2382 return -1;
2387 * Now, retrieve the number of entries that will fit in what was passed
2388 * We have to figure out if the info is in the list, or we need to
2389 * send a request to the server to get the info.
2392 while ((dirlist = dir->dir_next)) {
2393 struct smbc_dirent *dirent;
2395 if (!dirlist->dirent) {
2397 errno = ENOENT; /* Bad error */
2398 return -1;
2402 /* Do urlencoding of next entry, if so selected */
2403 dirent = (struct smbc_dirent *)context->internal->_dirent;
2404 maxlen = (sizeof(context->internal->_dirent) -
2405 sizeof(struct smbc_dirent));
2406 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
2408 reqd = dirent->dirlen;
2410 if (rem < reqd) {
2412 if (rem < count) { /* We managed to copy something */
2414 errno = 0;
2415 return count - rem;
2418 else { /* Nothing copied ... */
2420 errno = EINVAL; /* Not enough space ... */
2421 return -1;
2427 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2429 ((struct smbc_dirent *)ndir)->comment =
2430 (char *)(&((struct smbc_dirent *)ndir)->name +
2431 dirent->namelen +
2434 ndir += reqd;
2436 rem -= reqd;
2438 dir->dir_next = dirlist = dirlist -> next;
2441 if (rem == count)
2442 return 0;
2443 else
2444 return count - rem;
2449 * Routine to create a directory ...
2452 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2454 SMBCSRV *srv;
2455 fstring server, share, user, password, workgroup;
2456 pstring path;
2458 if (!context || !context->internal ||
2459 !context->internal->_initialized) {
2461 errno = EINVAL;
2462 return -1;
2466 if (!fname) {
2468 errno = EINVAL;
2469 return -1;
2473 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2475 if (smbc_parse_path(context, fname,
2476 server, sizeof(server),
2477 share, sizeof(share),
2478 path, sizeof(path),
2479 user, sizeof(user),
2480 password, sizeof(password),
2481 NULL, 0)) {
2482 errno = EINVAL;
2483 return -1;
2486 if (user[0] == (char)0) fstrcpy(user, context->user);
2488 fstrcpy(workgroup, context->workgroup);
2490 srv = smbc_server(context, server, share, workgroup, user, password);
2492 if (!srv) {
2494 return -1; /* errno set by smbc_server */
2498 if (!cli_mkdir(&srv->cli, path)) {
2500 errno = smbc_errno(context, &srv->cli);
2501 return -1;
2505 return 0;
2510 * Our list function simply checks to see if a directory is not empty
2513 static int smbc_rmdir_dirempty = True;
2515 static void rmdir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2518 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2519 smbc_rmdir_dirempty = False;
2524 * Routine to remove a directory
2527 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2529 SMBCSRV *srv;
2530 fstring server, share, user, password, workgroup;
2531 pstring path;
2533 if (!context || !context->internal ||
2534 !context->internal->_initialized) {
2536 errno = EINVAL;
2537 return -1;
2541 if (!fname) {
2543 errno = EINVAL;
2544 return -1;
2548 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2550 if (smbc_parse_path(context, fname,
2551 server, sizeof(server),
2552 share, sizeof(share),
2553 path, sizeof(path),
2554 user, sizeof(user),
2555 password, sizeof(password),
2556 NULL, 0))
2558 errno = EINVAL;
2559 return -1;
2562 if (user[0] == (char)0) fstrcpy(user, context->user);
2564 fstrcpy(workgroup, context->workgroup);
2566 srv = smbc_server(context, server, share, workgroup, user, password);
2568 if (!srv) {
2570 return -1; /* errno set by smbc_server */
2574 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2576 mode = aDIR | aRONLY;
2579 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2581 if (strcmp(path, "\\") == 0) {
2583 mode = aDIR | aRONLY;
2586 else {
2588 mode = aRONLY;
2589 smbc_stat_printjob(srv, path, &size, &m_time);
2590 c_time = a_time = m_time;
2593 else { */
2595 if (!cli_rmdir(&srv->cli, path)) {
2597 errno = smbc_errno(context, &srv->cli);
2599 if (errno == EACCES) { /* Check if the dir empty or not */
2601 pstring lpath; /* Local storage to avoid buffer overflows */
2603 smbc_rmdir_dirempty = True; /* Make this so ... */
2605 pstrcpy(lpath, path);
2606 pstrcat(lpath, "\\*");
2608 if (cli_list(&srv->cli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2609 NULL) < 0) {
2611 /* Fix errno to ignore latest error ... */
2613 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
2614 smbc_errno(context, &srv->cli)));
2615 errno = EACCES;
2619 if (smbc_rmdir_dirempty)
2620 errno = EACCES;
2621 else
2622 errno = ENOTEMPTY;
2626 return -1;
2630 return 0;
2635 * Routine to return the current directory position
2638 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
2640 off_t ret_val; /* Squash warnings about cast */
2642 if (!context || !context->internal ||
2643 !context->internal->_initialized) {
2645 errno = EINVAL;
2646 return -1;
2650 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2652 errno = EBADF;
2653 return -1;
2657 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2659 errno = ENOTDIR;
2660 return -1;
2665 * We return the pointer here as the offset
2667 ret_val = (int)dir->dir_next;
2668 return ret_val;
2673 * A routine to run down the list and see if the entry is OK
2676 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
2677 struct smbc_dirent *dirent)
2680 /* Run down the list looking for what we want */
2682 if (dirent) {
2684 struct smbc_dir_list *tmp = list;
2686 while (tmp) {
2688 if (tmp->dirent == dirent)
2689 return tmp;
2691 tmp = tmp->next;
2697 return NULL; /* Not found, or an error */
2703 * Routine to seek on a directory
2706 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
2708 long int l_offset = offset; /* Handle problems of size */
2709 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
2710 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
2712 if (!context || !context->internal ||
2713 !context->internal->_initialized) {
2715 errno = EINVAL;
2716 return -1;
2720 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2722 errno = ENOTDIR;
2723 return -1;
2727 /* Now, check what we were passed and see if it is OK ... */
2729 if (dirent == NULL) { /* Seek to the begining of the list */
2731 dir->dir_next = dir->dir_list;
2732 return 0;
2736 /* Now, run down the list and make sure that the entry is OK */
2737 /* This may need to be changed if we change the format of the list */
2739 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
2741 errno = EINVAL; /* Bad entry */
2742 return -1;
2746 dir->dir_next = list_ent;
2748 return 0;
2753 * Routine to fstat a dir
2756 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
2759 if (!context || !context->internal ||
2760 !context->internal->_initialized) {
2762 errno = EINVAL;
2763 return -1;
2767 /* No code yet ... */
2769 return 0;
2773 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
2775 SMBCSRV *srv;
2776 fstring server, share, user, password, workgroup;
2777 pstring path;
2778 uint16 mode;
2780 if (!context || !context->internal ||
2781 !context->internal->_initialized) {
2783 errno = EINVAL; /* Best I can think of ... */
2784 return -1;
2788 if (!fname) {
2790 errno = EINVAL;
2791 return -1;
2795 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
2797 if (smbc_parse_path(context, fname,
2798 server, sizeof(server),
2799 share, sizeof(share),
2800 path, sizeof(path),
2801 user, sizeof(user),
2802 password, sizeof(password),
2803 NULL, 0)) {
2804 errno = EINVAL;
2805 return -1;
2808 if (user[0] == (char)0) fstrcpy(user, context->user);
2810 fstrcpy(workgroup, context->workgroup);
2812 srv = smbc_server(context, server, share, workgroup, user, password);
2814 if (!srv) {
2815 return -1; /* errno set by smbc_server */
2818 mode = 0;
2820 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
2821 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
2822 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
2823 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
2825 if (!cli_setatr(&srv->cli, path, mode, 0)) {
2826 errno = smbc_errno(context, &srv->cli);
2827 return -1;
2830 return 0;
2833 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
2835 SMBCSRV *srv;
2836 fstring server, share, user, password, workgroup;
2837 pstring path;
2838 uint16 mode;
2839 time_t t = (tbuf == NULL ? time(NULL) : tbuf->tv_sec);
2841 if (!context || !context->internal ||
2842 !context->internal->_initialized) {
2844 errno = EINVAL; /* Best I can think of ... */
2845 return -1;
2849 if (!fname) {
2851 errno = EINVAL;
2852 return -1;
2856 DEBUG(4, ("smbc_utimes(%s, [%s])\n", fname, ctime(&t)));
2858 if (smbc_parse_path(context, fname,
2859 server, sizeof(server),
2860 share, sizeof(share),
2861 path, sizeof(path),
2862 user, sizeof(user),
2863 password, sizeof(password),
2864 NULL, 0)) {
2865 errno = EINVAL;
2866 return -1;
2869 if (user[0] == (char)0) fstrcpy(user, context->user);
2871 fstrcpy(workgroup, context->workgroup);
2873 srv = smbc_server(context, server, share, workgroup, user, password);
2875 if (!srv) {
2876 return -1; /* errno set by smbc_server */
2879 if (!smbc_getatr(context, srv, path,
2880 &mode, NULL,
2881 NULL, NULL, NULL,
2882 NULL)) {
2883 return -1;
2886 if (!cli_setatr(&srv->cli, path, mode, t)) {
2887 /* some servers always refuse directory changes */
2888 if (!(mode & aDIR)) {
2889 errno = smbc_errno(context, &srv->cli);
2890 return -1;
2894 return 0;
2898 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
2899 However NT4 gives a "The information may have been modified by a
2900 computer running Windows NT 5.0" if denied ACEs do not appear before
2901 allowed ACEs. */
2903 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
2905 if (sec_ace_equal(ace1, ace2))
2906 return 0;
2908 if (ace1->type != ace2->type)
2909 return ace2->type - ace1->type;
2911 if (sid_compare(&ace1->trustee, &ace2->trustee))
2912 return sid_compare(&ace1->trustee, &ace2->trustee);
2914 if (ace1->flags != ace2->flags)
2915 return ace1->flags - ace2->flags;
2917 if (ace1->info.mask != ace2->info.mask)
2918 return ace1->info.mask - ace2->info.mask;
2920 if (ace1->size != ace2->size)
2921 return ace1->size - ace2->size;
2923 return memcmp(ace1, ace2, sizeof(SEC_ACE));
2927 static void sort_acl(SEC_ACL *the_acl)
2929 uint32 i;
2930 if (!the_acl) return;
2932 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
2934 for (i=1;i<the_acl->num_aces;) {
2935 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
2936 int j;
2937 for (j=i; j<the_acl->num_aces-1; j++) {
2938 the_acl->ace[j] = the_acl->ace[j+1];
2940 the_acl->num_aces--;
2941 } else {
2942 i++;
2947 /* convert a SID to a string, either numeric or username/group */
2948 static void convert_sid_to_string(struct cli_state *ipc_cli,
2949 POLICY_HND *pol,
2950 fstring str,
2951 BOOL numeric,
2952 DOM_SID *sid)
2954 char **domains = NULL;
2955 char **names = NULL;
2956 uint32 *types = NULL;
2958 sid_to_string(str, sid);
2960 if (numeric) return; /* no lookup desired */
2962 /* Ask LSA to convert the sid to a name */
2964 if (!NT_STATUS_IS_OK(cli_lsa_lookup_sids(ipc_cli, ipc_cli->mem_ctx,
2965 pol, 1, sid, &domains,
2966 &names, &types)) ||
2967 !domains || !domains[0] || !names || !names[0]) {
2968 return;
2971 /* Converted OK */
2973 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
2974 domains[0], lp_winbind_separator(),
2975 names[0]);
2978 /* convert a string to a SID, either numeric or username/group */
2979 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
2980 POLICY_HND *pol,
2981 BOOL numeric,
2982 DOM_SID *sid,
2983 const char *str)
2985 uint32 *types = NULL;
2986 DOM_SID *sids = NULL;
2987 BOOL result = True;
2989 if (numeric) {
2990 if (strncmp(str, "S-", 2) == 0) {
2991 return string_to_sid(sid, str);
2994 result = False;
2995 goto done;
2998 if (!NT_STATUS_IS_OK(cli_lsa_lookup_names(ipc_cli, ipc_cli->mem_ctx,
2999 pol, 1, &str, &sids,
3000 &types))) {
3001 result = False;
3002 goto done;
3005 sid_copy(sid, &sids[0]);
3006 done:
3008 return result;
3012 /* parse an ACE in the same format as print_ace() */
3013 static BOOL parse_ace(struct cli_state *ipc_cli,
3014 POLICY_HND *pol,
3015 SEC_ACE *ace,
3016 BOOL numeric,
3017 char *str)
3019 char *p;
3020 const char *cp;
3021 fstring tok;
3022 unsigned atype, aflags, amask;
3023 DOM_SID sid;
3024 SEC_ACCESS mask;
3025 const struct perm_value *v;
3026 struct perm_value {
3027 const char *perm;
3028 uint32 mask;
3031 /* These values discovered by inspection */
3032 static const struct perm_value special_values[] = {
3033 { "R", 0x00120089 },
3034 { "W", 0x00120116 },
3035 { "X", 0x001200a0 },
3036 { "D", 0x00010000 },
3037 { "P", 0x00040000 },
3038 { "O", 0x00080000 },
3039 { NULL, 0 },
3042 static const struct perm_value standard_values[] = {
3043 { "READ", 0x001200a9 },
3044 { "CHANGE", 0x001301bf },
3045 { "FULL", 0x001f01ff },
3046 { NULL, 0 },
3050 ZERO_STRUCTP(ace);
3051 p = strchr_m(str,':');
3052 if (!p) return False;
3053 *p = '\0';
3054 p++;
3055 /* Try to parse numeric form */
3057 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3058 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3059 goto done;
3062 /* Try to parse text form */
3064 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3065 return False;
3068 cp = p;
3069 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3070 return False;
3073 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3074 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3075 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3076 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3077 } else {
3078 return False;
3081 /* Only numeric form accepted for flags at present */
3083 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3084 sscanf(tok, "%i", &aflags))) {
3085 return False;
3088 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3089 return False;
3092 if (strncmp(tok, "0x", 2) == 0) {
3093 if (sscanf(tok, "%i", &amask) != 1) {
3094 return False;
3096 goto done;
3099 for (v = standard_values; v->perm; v++) {
3100 if (strcmp(tok, v->perm) == 0) {
3101 amask = v->mask;
3102 goto done;
3106 p = tok;
3108 while(*p) {
3109 BOOL found = False;
3111 for (v = special_values; v->perm; v++) {
3112 if (v->perm[0] == *p) {
3113 amask |= v->mask;
3114 found = True;
3118 if (!found) return False;
3119 p++;
3122 if (*p) {
3123 return False;
3126 done:
3127 mask.mask = amask;
3128 init_sec_ace(ace, &sid, atype, mask, aflags);
3129 return True;
3132 /* add an ACE to a list of ACEs in a SEC_ACL */
3133 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3135 SEC_ACL *new;
3136 SEC_ACE *aces;
3137 if (! *the_acl) {
3138 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3139 return True;
3142 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3143 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3144 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3145 new = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3146 SAFE_FREE(aces);
3147 (*the_acl) = new;
3148 return True;
3152 /* parse a ascii version of a security descriptor */
3153 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3154 struct cli_state *ipc_cli,
3155 POLICY_HND *pol,
3156 BOOL numeric,
3157 char *str)
3159 const char *p = str;
3160 fstring tok;
3161 SEC_DESC *ret;
3162 size_t sd_size;
3163 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3164 SEC_ACL *dacl=NULL;
3165 int revision=1;
3167 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3169 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3170 revision = strtol(tok+9, NULL, 16);
3171 continue;
3174 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3175 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3176 if (!owner_sid ||
3177 !convert_string_to_sid(ipc_cli, pol,
3178 numeric,
3179 owner_sid, tok+6)) {
3180 DEBUG(5, ("Failed to parse owner sid\n"));
3181 return NULL;
3183 continue;
3186 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3187 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3188 if (!owner_sid ||
3189 !convert_string_to_sid(ipc_cli, pol,
3190 False,
3191 owner_sid, tok+7)) {
3192 DEBUG(5, ("Failed to parse owner sid\n"));
3193 return NULL;
3195 continue;
3198 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3199 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3200 if (!grp_sid ||
3201 !convert_string_to_sid(ipc_cli, pol,
3202 numeric,
3203 grp_sid, tok+6)) {
3204 DEBUG(5, ("Failed to parse group sid\n"));
3205 return NULL;
3207 continue;
3210 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3211 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3212 if (!grp_sid ||
3213 !convert_string_to_sid(ipc_cli, pol,
3214 False,
3215 grp_sid, tok+6)) {
3216 DEBUG(5, ("Failed to parse group sid\n"));
3217 return NULL;
3219 continue;
3222 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3223 SEC_ACE ace;
3224 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3225 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3226 return NULL;
3228 if(!add_ace(&dacl, &ace, ctx)) {
3229 DEBUG(5, ("Failed to add ACL %s\n", tok));
3230 return NULL;
3232 continue;
3235 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3236 SEC_ACE ace;
3237 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3238 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3239 return NULL;
3241 if(!add_ace(&dacl, &ace, ctx)) {
3242 DEBUG(5, ("Failed to add ACL %s\n", tok));
3243 return NULL;
3245 continue;
3248 DEBUG(5, ("Failed to parse security descriptor\n"));
3249 return NULL;
3252 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3253 owner_sid, grp_sid, NULL, dacl, &sd_size);
3255 SAFE_FREE(grp_sid);
3256 SAFE_FREE(owner_sid);
3258 return ret;
3262 /* Obtain the current dos attributes */
3263 static DOS_ATTR_DESC *dos_attr_query(SMBCCTX *context,
3264 TALLOC_CTX *ctx,
3265 const char *filename,
3266 SMBCSRV *srv)
3268 time_t m_time = 0, a_time = 0, c_time = 0;
3269 SMB_OFF_T size = 0;
3270 uint16 mode = 0;
3271 SMB_INO_T inode = 0;
3272 DOS_ATTR_DESC *ret;
3274 ret = talloc(ctx, sizeof(DOS_ATTR_DESC));
3275 if (!ret) {
3276 errno = ENOMEM;
3277 return NULL;
3280 /* Obtain the DOS attributes */
3281 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
3282 &mode, &size,
3283 &c_time, &a_time, &m_time, &inode)) {
3285 errno = smbc_errno(context, &srv->cli);
3286 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
3287 return NULL;
3291 ret->mode = mode;
3292 ret->size = size;
3293 ret->a_time = a_time;
3294 ret->c_time = c_time;
3295 ret->m_time = m_time;
3296 ret->inode = inode;
3298 return ret;
3302 /* parse a ascii version of a security descriptor */
3303 static void dos_attr_parse(SMBCCTX *context,
3304 DOS_ATTR_DESC *dad,
3305 SMBCSRV *srv,
3306 char *str)
3308 const char *p = str;
3309 fstring tok;
3311 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3313 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
3314 dad->mode = strtol(tok+5, NULL, 16);
3315 continue;
3318 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
3319 dad->size = strtoll(tok+5, NULL, 10);
3320 continue;
3323 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
3324 dad->a_time = strtoll(tok+7, NULL, 10);
3325 continue;
3328 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
3329 dad->c_time = strtoll(tok+7, NULL, 10);
3330 continue;
3333 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
3334 dad->m_time = strtoll(tok+7, NULL, 10);
3335 continue;
3338 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
3339 dad->inode = strtoll(tok+6, NULL, 10);
3340 continue;
3346 /*****************************************************
3347 retrieve the acls for a file
3348 *******************************************************/
3349 static int cacl_get(SMBCCTX *context, TALLOC_CTX *ctx, SMBCSRV *srv,
3350 struct cli_state *ipc_cli, POLICY_HND *pol,
3351 char *filename, char *attr_name, char *buf, int bufsize)
3353 uint32 i;
3354 int n = 0;
3355 int n_used;
3356 BOOL all;
3357 BOOL all_nt;
3358 BOOL all_nt_acls;
3359 BOOL all_dos;
3360 BOOL some_nt;
3361 BOOL some_dos;
3362 BOOL exclude_nt_revision = False;
3363 BOOL exclude_nt_owner = False;
3364 BOOL exclude_nt_group = False;
3365 BOOL exclude_nt_acl = False;
3366 BOOL exclude_dos_mode = False;
3367 BOOL exclude_dos_size = False;
3368 BOOL exclude_dos_ctime = False;
3369 BOOL exclude_dos_atime = False;
3370 BOOL exclude_dos_mtime = False;
3371 BOOL exclude_dos_inode = False;
3372 BOOL numeric = True;
3373 BOOL determine_size = (bufsize == 0);
3374 int fnum = -1;
3375 SEC_DESC *sd;
3376 fstring sidstr;
3377 fstring name_sandbox;
3378 char *name;
3379 char *pExclude;
3380 char *p;
3381 time_t m_time = 0, a_time = 0, c_time = 0;
3382 SMB_OFF_T size = 0;
3383 uint16 mode = 0;
3384 SMB_INO_T ino = 0;
3385 struct cli_state *cli = &srv->cli;
3387 /* Copy name so we can strip off exclusions (if any are specified) */
3388 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
3390 /* Ensure name is null terminated */
3391 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
3393 /* Play in the sandbox */
3394 name = name_sandbox;
3396 /* If there are any exclusions, point to them and mask them from name */
3397 if ((pExclude = strchr(name, '!')) != NULL)
3399 *pExclude++ = '\0';
3402 all = (StrnCaseCmp(name, "system.*", 8) == 0);
3403 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
3404 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
3405 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
3406 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
3407 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
3408 numeric = (* (name + strlen(name) - 1) != '+');
3410 /* Look for exclusions from "all" requests */
3411 if (all || all_nt || all_dos) {
3413 /* Exclusions are delimited by '!' */
3414 for (; pExclude != NULL; pExclude = (p == NULL ? NULL : p + 1)) {
3416 /* Find end of this exclusion name */
3417 if ((p = strchr(pExclude, '!')) != NULL)
3419 *p = '\0';
3422 /* Which exclusion name is this? */
3423 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
3424 exclude_nt_revision = True;
3426 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
3427 exclude_nt_owner = True;
3429 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
3430 exclude_nt_group = True;
3432 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
3433 exclude_nt_acl = True;
3435 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
3436 exclude_dos_mode = True;
3438 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
3439 exclude_dos_size = True;
3441 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
3442 exclude_dos_ctime = True;
3444 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
3445 exclude_dos_atime = True;
3447 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
3448 exclude_dos_mtime = True;
3450 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
3451 exclude_dos_inode = True;
3453 else {
3454 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
3455 pExclude));
3456 errno = ENOATTR;
3457 return -1;
3462 n_used = 0;
3465 * If we are (possibly) talking to an NT or new system and some NT
3466 * attributes have been requested...
3468 if (ipc_cli && (all || some_nt || all_nt_acls)) {
3469 /* Point to the portion after "system.nt_sec_desc." */
3470 name += 19; /* if (all) this will be invalid but unused */
3472 /* ... then obtain any NT attributes which were requested */
3473 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3475 if (fnum == -1) {
3476 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3477 filename, cli_errstr(cli)));
3478 errno = 0;
3479 return -1;
3482 sd = cli_query_secdesc(cli, fnum, ctx);
3484 if (!sd) {
3485 DEBUG(5,
3486 ("cacl_get Failed to query old descriptor\n"));
3487 errno = 0;
3488 return -1;
3491 cli_close(cli, fnum);
3493 if (! exclude_nt_revision) {
3494 if (all || all_nt) {
3495 if (determine_size) {
3496 p = talloc_asprintf(ctx,
3497 "REVISION:%d",
3498 sd->revision);
3499 if (!p) {
3500 errno = ENOMEM;
3501 return -1;
3503 n = strlen(p);
3504 } else {
3505 n = snprintf(buf, bufsize,
3506 "REVISION:%d", sd->revision);
3508 } else if (StrCaseCmp(name, "revision") == 0) {
3509 if (determine_size) {
3510 p = talloc_asprintf(ctx, "%d",
3511 sd->revision);
3512 if (!p) {
3513 errno = ENOMEM;
3514 return -1;
3516 n = strlen(p);
3517 } else {
3518 n = snprintf(buf, bufsize, "%d",
3519 sd->revision);
3523 if (!determine_size && n > bufsize) {
3524 errno = ERANGE;
3525 return -1;
3527 buf += n;
3528 n_used += n;
3529 bufsize -= n;
3532 if (! exclude_nt_owner) {
3533 /* Get owner and group sid */
3534 if (sd->owner_sid) {
3535 convert_sid_to_string(ipc_cli, pol,
3536 sidstr,
3537 numeric,
3538 sd->owner_sid);
3539 } else {
3540 fstrcpy(sidstr, "");
3543 if (all || all_nt) {
3544 if (determine_size) {
3545 p = talloc_asprintf(ctx, ",OWNER:%s",
3546 sidstr);
3547 if (!p) {
3548 errno = ENOMEM;
3549 return -1;
3551 n = strlen(p);
3552 } else {
3553 n = snprintf(buf, bufsize,
3554 ",OWNER:%s", sidstr);
3556 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3557 if (determine_size) {
3558 p = talloc_asprintf(ctx, "%s", sidstr);
3559 if (!p) {
3560 errno = ENOMEM;
3561 return -1;
3563 n = strlen(p);
3564 } else {
3565 n = snprintf(buf, bufsize, "%s",
3566 sidstr);
3570 if (!determine_size && n > bufsize) {
3571 errno = ERANGE;
3572 return -1;
3574 buf += n;
3575 n_used += n;
3576 bufsize -= n;
3579 if (! exclude_nt_group) {
3580 if (sd->grp_sid) {
3581 convert_sid_to_string(ipc_cli, pol,
3582 sidstr, numeric,
3583 sd->grp_sid);
3584 } else {
3585 fstrcpy(sidstr, "");
3588 if (all || all_nt) {
3589 if (determine_size) {
3590 p = talloc_asprintf(ctx, ",GROUP:%s",
3591 sidstr);
3592 if (!p) {
3593 errno = ENOMEM;
3594 return -1;
3596 n = strlen(p);
3597 } else {
3598 n = snprintf(buf, bufsize,
3599 ",GROUP:%s", sidstr);
3601 } else if (StrnCaseCmp(name, "group", 5) == 0) {
3602 if (determine_size) {
3603 p = talloc_asprintf(ctx, "%s", sidstr);
3604 if (!p) {
3605 errno = ENOMEM;
3606 return -1;
3608 n = strlen(p);
3609 } else {
3610 n = snprintf(buf, bufsize, "%s", sidstr);
3614 if (!determine_size && n > bufsize) {
3615 errno = ERANGE;
3616 return -1;
3618 buf += n;
3619 n_used += n;
3620 bufsize -= n;
3623 if (! exclude_nt_acl) {
3624 /* Add aces to value buffer */
3625 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
3627 SEC_ACE *ace = &sd->dacl->ace[i];
3628 convert_sid_to_string(ipc_cli, pol,
3629 sidstr, numeric,
3630 &ace->trustee);
3632 if (all || all_nt) {
3633 if (determine_size) {
3634 p = talloc_asprintf(
3635 ctx,
3636 ",ACL:"
3637 "%s:%d/%d/0x%08x",
3638 sidstr,
3639 ace->type,
3640 ace->flags,
3641 ace->info.mask);
3642 if (!p) {
3643 errno = ENOMEM;
3644 return -1;
3646 n = strlen(p);
3647 } else {
3648 n = snprintf(
3649 buf, bufsize,
3650 ",ACL:%s:%d/%d/0x%08x",
3651 sidstr,
3652 ace->type,
3653 ace->flags,
3654 ace->info.mask);
3656 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
3657 StrCaseCmp(name + 3, sidstr) == 0) ||
3658 (StrnCaseCmp(name, "acl+", 4) == 0 &&
3659 StrCaseCmp(name + 4, sidstr) == 0)) {
3660 if (determine_size) {
3661 p = talloc_asprintf(
3662 ctx,
3663 "%d/%d/0x%08x",
3664 ace->type,
3665 ace->flags,
3666 ace->info.mask);
3667 if (!p) {
3668 errno = ENOMEM;
3669 return -1;
3671 n = strlen(p);
3672 } else {
3673 n = snprintf(buf, bufsize,
3674 "%d/%d/0x%08x",
3675 ace->type,
3676 ace->flags,
3677 ace->info.mask);
3679 } else if (all_nt_acls) {
3680 if (determine_size) {
3681 p = talloc_asprintf(
3682 ctx,
3683 "%s%s:%d/%d/0x%08x",
3684 i ? "," : "",
3685 sidstr,
3686 ace->type,
3687 ace->flags,
3688 ace->info.mask);
3689 if (!p) {
3690 errno = ENOMEM;
3691 return -1;
3693 n = strlen(p);
3694 } else {
3695 n = snprintf(buf, bufsize,
3696 "%s%s:%d/%d/0x%08x",
3697 i ? "," : "",
3698 sidstr,
3699 ace->type,
3700 ace->flags,
3701 ace->info.mask);
3704 if (n > bufsize) {
3705 errno = ERANGE;
3706 return -1;
3708 buf += n;
3709 n_used += n;
3710 bufsize -= n;
3714 /* Restore name pointer to its original value */
3715 name -= 19;
3718 if (all || some_dos) {
3719 /* Point to the portion after "system.dos_attr." */
3720 name += 16; /* if (all) this will be invalid but unused */
3722 /* Obtain the DOS attributes */
3723 if (!smbc_getatr(context, srv, filename, &mode, &size,
3724 &c_time, &a_time, &m_time, &ino)) {
3726 errno = smbc_errno(context, &srv->cli);
3727 return -1;
3731 if (! exclude_dos_mode) {
3732 if (all || all_dos) {
3733 if (determine_size) {
3734 p = talloc_asprintf(ctx,
3735 "%sMODE:0x%x",
3736 (ipc_cli &&
3737 (all || some_nt)
3738 ? ","
3739 : ""),
3740 mode);
3741 if (!p) {
3742 errno = ENOMEM;
3743 return -1;
3745 n = strlen(p);
3746 } else {
3747 n = snprintf(buf, bufsize,
3748 "%sMODE:0x%x",
3749 (ipc_cli &&
3750 (all || some_nt)
3751 ? ","
3752 : ""),
3753 mode);
3755 } else if (StrCaseCmp(name, "mode") == 0) {
3756 if (determine_size) {
3757 p = talloc_asprintf(ctx, "0x%x", mode);
3758 if (!p) {
3759 errno = ENOMEM;
3760 return -1;
3762 n = strlen(p);
3763 } else {
3764 n = snprintf(buf, bufsize, "0x%x", mode);
3768 if (!determine_size && n > bufsize) {
3769 errno = ERANGE;
3770 return -1;
3772 buf += n;
3773 n_used += n;
3774 bufsize -= n;
3777 if (! exclude_dos_size) {
3778 if (all || all_dos) {
3779 if (determine_size) {
3780 p = talloc_asprintf(
3781 ctx,
3782 ",SIZE:%llu",
3783 (unsigned long long) size);
3784 if (!p) {
3785 errno = ENOMEM;
3786 return -1;
3788 n = strlen(p);
3789 } else {
3790 n = snprintf(buf, bufsize,
3791 ",SIZE:%llu",
3792 (unsigned long long) size);
3794 } else if (StrCaseCmp(name, "size") == 0) {
3795 if (determine_size) {
3796 p = talloc_asprintf(
3797 ctx,
3798 "%llu",
3799 (unsigned long long) size);
3800 if (!p) {
3801 errno = ENOMEM;
3802 return -1;
3804 n = strlen(p);
3805 } else {
3806 n = snprintf(buf, bufsize,
3807 "%llu",
3808 (unsigned long long) size);
3812 if (!determine_size && n > bufsize) {
3813 errno = ERANGE;
3814 return -1;
3816 buf += n;
3817 n_used += n;
3818 bufsize -= n;
3821 if (! exclude_dos_ctime) {
3822 if (all || all_dos) {
3823 if (determine_size) {
3824 p = talloc_asprintf(ctx,
3825 ",C_TIME:%lu",
3826 c_time);
3827 if (!p) {
3828 errno = ENOMEM;
3829 return -1;
3831 n = strlen(p);
3832 } else {
3833 n = snprintf(buf, bufsize,
3834 ",C_TIME:%lu", c_time);
3836 } else if (StrCaseCmp(name, "c_time") == 0) {
3837 if (determine_size) {
3838 p = talloc_asprintf(ctx, "%lu", c_time);
3839 if (!p) {
3840 errno = ENOMEM;
3841 return -1;
3843 n = strlen(p);
3844 } else {
3845 n = snprintf(buf, bufsize, "%lu", c_time);
3849 if (!determine_size && n > bufsize) {
3850 errno = ERANGE;
3851 return -1;
3853 buf += n;
3854 n_used += n;
3855 bufsize -= n;
3858 if (! exclude_dos_atime) {
3859 if (all || all_dos) {
3860 if (determine_size) {
3861 p = talloc_asprintf(ctx,
3862 ",A_TIME:%lu",
3863 a_time);
3864 if (!p) {
3865 errno = ENOMEM;
3866 return -1;
3868 n = strlen(p);
3869 } else {
3870 n = snprintf(buf, bufsize,
3871 ",A_TIME:%lu", a_time);
3873 } else if (StrCaseCmp(name, "a_time") == 0) {
3874 if (determine_size) {
3875 p = talloc_asprintf(ctx, "%lu", a_time);
3876 if (!p) {
3877 errno = ENOMEM;
3878 return -1;
3880 n = strlen(p);
3881 } else {
3882 n = snprintf(buf, bufsize, "%lu", a_time);
3886 if (!determine_size && n > bufsize) {
3887 errno = ERANGE;
3888 return -1;
3890 buf += n;
3891 n_used += n;
3892 bufsize -= n;
3895 if (! exclude_dos_mtime) {
3896 if (all || all_dos) {
3897 if (determine_size) {
3898 p = talloc_asprintf(ctx,
3899 ",M_TIME:%lu",
3900 m_time);
3901 if (!p) {
3902 errno = ENOMEM;
3903 return -1;
3905 n = strlen(p);
3906 } else {
3907 n = snprintf(buf, bufsize,
3908 ",M_TIME:%lu", m_time);
3910 } else if (StrCaseCmp(name, "m_time") == 0) {
3911 if (determine_size) {
3912 p = talloc_asprintf(ctx, "%lu", m_time);
3913 if (!p) {
3914 errno = ENOMEM;
3915 return -1;
3917 n = strlen(p);
3918 } else {
3919 n = snprintf(buf, bufsize, "%lu", m_time);
3923 if (!determine_size && n > bufsize) {
3924 errno = ERANGE;
3925 return -1;
3927 buf += n;
3928 n_used += n;
3929 bufsize -= n;
3932 if (! exclude_dos_inode) {
3933 if (all || all_dos) {
3934 if (determine_size) {
3935 p = talloc_asprintf(
3936 ctx,
3937 ",INODE:%llu",
3938 (unsigned long long) ino);
3939 if (!p) {
3940 errno = ENOMEM;
3941 return -1;
3943 n = strlen(p);
3944 } else {
3945 n = snprintf(buf, bufsize,
3946 ",INODE:%llu",
3947 (unsigned long long) ino);
3949 } else if (StrCaseCmp(name, "inode") == 0) {
3950 if (determine_size) {
3951 p = talloc_asprintf(
3952 ctx,
3953 "%llu",
3954 (unsigned long long) ino);
3955 if (!p) {
3956 errno = ENOMEM;
3957 return -1;
3959 n = strlen(p);
3960 } else {
3961 n = snprintf(buf, bufsize,
3962 "%llu",
3963 (unsigned long long) ino);
3967 if (!determine_size && n > bufsize) {
3968 errno = ERANGE;
3969 return -1;
3971 buf += n;
3972 n_used += n;
3973 bufsize -= n;
3976 /* Restore name pointer to its original value */
3977 name -= 16;
3980 if (n_used == 0) {
3981 errno = ENOATTR;
3982 return -1;
3985 return n_used;
3989 /*****************************************************
3990 set the ACLs on a file given an ascii description
3991 *******************************************************/
3992 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
3993 struct cli_state *ipc_cli, POLICY_HND *pol,
3994 const char *filename, const char *the_acl,
3995 int mode, int flags)
3997 int fnum;
3998 int err = 0;
3999 SEC_DESC *sd = NULL, *old;
4000 SEC_ACL *dacl = NULL;
4001 DOM_SID *owner_sid = NULL;
4002 DOM_SID *grp_sid = NULL;
4003 uint32 i, j;
4004 size_t sd_size;
4005 int ret = 0;
4006 char *p;
4007 BOOL numeric = True;
4009 /* the_acl will be null for REMOVE_ALL operations */
4010 if (the_acl) {
4011 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4012 p > the_acl &&
4013 p[-1] != '+');
4015 /* if this is to set the entire ACL... */
4016 if (*the_acl == '*') {
4017 /* ... then increment past the first colon */
4018 the_acl = p + 1;
4021 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4022 CONST_DISCARD(char *, the_acl));
4024 if (!sd) {
4025 errno = EINVAL;
4026 return -1;
4030 /* The desired access below is the only one I could find that works
4031 with NT4, W2KP and Samba */
4033 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4035 if (fnum == -1) {
4036 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4037 filename, cli_errstr(cli)));
4038 errno = 0;
4039 return -1;
4042 old = cli_query_secdesc(cli, fnum, ctx);
4044 if (!old) {
4045 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4046 errno = 0;
4047 return -1;
4050 cli_close(cli, fnum);
4052 switch (mode) {
4053 case SMBC_XATTR_MODE_REMOVE_ALL:
4054 old->dacl->num_aces = 0;
4055 SAFE_FREE(old->dacl->ace);
4056 SAFE_FREE(old->dacl);
4057 old->off_dacl = 0;
4058 dacl = old->dacl;
4059 break;
4061 case SMBC_XATTR_MODE_REMOVE:
4062 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4063 BOOL found = False;
4065 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4066 if (sec_ace_equal(&sd->dacl->ace[i],
4067 &old->dacl->ace[j])) {
4068 uint32 k;
4069 for (k=j; k<old->dacl->num_aces-1;k++) {
4070 old->dacl->ace[k] = old->dacl->ace[k+1];
4072 old->dacl->num_aces--;
4073 if (old->dacl->num_aces == 0) {
4074 SAFE_FREE(old->dacl->ace);
4075 SAFE_FREE(old->dacl);
4076 old->off_dacl = 0;
4078 found = True;
4079 dacl = old->dacl;
4080 break;
4084 if (!found) {
4085 err = ENOATTR;
4086 ret = -1;
4087 goto failed;
4090 break;
4092 case SMBC_XATTR_MODE_ADD:
4093 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4094 BOOL found = False;
4096 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4097 if (sid_equal(&sd->dacl->ace[i].trustee,
4098 &old->dacl->ace[j].trustee)) {
4099 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4100 err = EEXIST;
4101 ret = -1;
4102 goto failed;
4104 old->dacl->ace[j] = sd->dacl->ace[i];
4105 ret = -1;
4106 found = True;
4110 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4111 err = ENOATTR;
4112 ret = -1;
4113 goto failed;
4116 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4117 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4120 dacl = old->dacl;
4121 break;
4123 case SMBC_XATTR_MODE_SET:
4124 old = sd;
4125 owner_sid = old->owner_sid;
4126 grp_sid = old->grp_sid;
4127 dacl = old->dacl;
4128 break;
4130 case SMBC_XATTR_MODE_CHOWN:
4131 owner_sid = sd->owner_sid;
4132 break;
4134 case SMBC_XATTR_MODE_CHGRP:
4135 grp_sid = sd->grp_sid;
4136 break;
4139 /* Denied ACE entries must come before allowed ones */
4140 sort_acl(old->dacl);
4142 /* Create new security descriptor and set it */
4143 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4144 owner_sid, grp_sid, NULL, dacl, &sd_size);
4146 fnum = cli_nt_create(cli, filename,
4147 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4149 if (fnum == -1) {
4150 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4151 filename, cli_errstr(cli)));
4152 errno = 0;
4153 return -1;
4156 if (!cli_set_secdesc(cli, fnum, sd)) {
4157 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4158 ret = -1;
4161 /* Clean up */
4163 failed:
4164 cli_close(cli, fnum);
4166 if (err != 0) {
4167 errno = err;
4170 return ret;
4174 int smbc_setxattr_ctx(SMBCCTX *context,
4175 const char *fname,
4176 const char *name,
4177 const void *value,
4178 size_t size,
4179 int flags)
4181 int ret;
4182 int ret2;
4183 SMBCSRV *srv;
4184 SMBCSRV *ipc_srv;
4185 fstring server, share, user, password, workgroup;
4186 pstring path;
4187 TALLOC_CTX *ctx;
4188 POLICY_HND pol;
4189 DOS_ATTR_DESC *dad;
4191 if (!context || !context->internal ||
4192 !context->internal->_initialized) {
4194 errno = EINVAL; /* Best I can think of ... */
4195 return -1;
4199 if (!fname) {
4201 errno = EINVAL;
4202 return -1;
4206 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n", fname, name, (int) size, (const char*)value));
4208 if (smbc_parse_path(context, fname,
4209 server, sizeof(server),
4210 share, sizeof(share),
4211 path, sizeof(path),
4212 user, sizeof(user),
4213 password, sizeof(password),
4214 NULL, 0)) {
4215 errno = EINVAL;
4216 return -1;
4219 if (user[0] == (char)0) fstrcpy(user, context->user);
4221 fstrcpy(workgroup, context->workgroup);
4223 srv = smbc_server(context, server, share, workgroup, user, password);
4224 if (!srv) {
4225 return -1; /* errno set by smbc_server */
4228 if (! srv->no_nt_session) {
4229 ipc_srv = smbc_attr_server(context, server, share,
4230 workgroup, user, password,
4231 &pol);
4232 srv->no_nt_session = True;
4233 } else {
4234 ipc_srv = NULL;
4237 ctx = talloc_init("smbc_setxattr");
4238 if (!ctx) {
4239 errno = ENOMEM;
4240 return -1;
4244 * Are they asking to set the entire set of known attributes?
4246 if (StrCaseCmp(name, "system.*") == 0 ||
4247 StrCaseCmp(name, "system.*+") == 0) {
4248 /* Yup. */
4249 char *namevalue =
4250 talloc_asprintf(ctx, "%s:%s", name+7, (const char *) value);
4251 if (! namevalue) {
4252 errno = ENOMEM;
4253 ret = -1;
4254 return -1;
4257 if (ipc_srv) {
4258 ret = cacl_set(ctx, &srv->cli,
4259 &ipc_srv->cli, &pol, path,
4260 namevalue,
4261 (*namevalue == '*'
4262 ? SMBC_XATTR_MODE_SET
4263 : SMBC_XATTR_MODE_ADD),
4264 flags);
4265 } else {
4266 ret = 0;
4269 /* get a DOS Attribute Descriptor with current attributes */
4270 dad = dos_attr_query(context, ctx, path, srv);
4271 if (dad) {
4272 /* Overwrite old with new, using what was provided */
4273 dos_attr_parse(context, dad, srv, namevalue);
4275 /* Set the new DOS attributes */
4276 #if 0 /* not yet implemented */
4277 if (! cli_setpathinfo(&srv->cli, path,
4278 dad->c_time,
4279 dad->a_time,
4280 dad->m_time,
4281 dad->mode)) {
4282 if (!cli_setatr(&srv->cli, path,
4283 dad->mode, dad->m_time)) {
4284 errno = smbc_errno(context, &srv->cli);
4287 #else
4288 if (!cli_setatr(&srv->cli, path,
4289 dad->mode, dad->m_time)) {
4290 errno = smbc_errno(context, &srv->cli);
4292 #endif
4295 /* we only fail if both NT and DOS sets failed */
4296 if (ret < 0 && ! dad) {
4297 ret = -1; /* in case dad was null */
4299 else {
4300 ret = 0;
4303 talloc_destroy(ctx);
4304 return ret;
4308 * Are they asking to set an access control element or to set
4309 * the entire access control list?
4311 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4312 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4313 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4314 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4315 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4317 /* Yup. */
4318 char *namevalue =
4319 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4321 if (! ipc_srv) {
4322 ret = -1; /* errno set by smbc_server() */
4324 else if (! namevalue) {
4325 errno = ENOMEM;
4326 ret = -1;
4327 } else {
4328 ret = cacl_set(ctx, &srv->cli,
4329 &ipc_srv->cli, &pol, path,
4330 namevalue,
4331 (*namevalue == '*'
4332 ? SMBC_XATTR_MODE_SET
4333 : SMBC_XATTR_MODE_ADD),
4334 flags);
4336 talloc_destroy(ctx);
4337 return ret;
4341 * Are they asking to set the owner?
4343 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4344 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
4346 /* Yup. */
4347 char *namevalue =
4348 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4350 if (! ipc_srv) {
4352 ret = -1; /* errno set by smbc_server() */
4354 else if (! namevalue) {
4355 errno = ENOMEM;
4356 ret = -1;
4357 } else {
4358 ret = cacl_set(ctx, &srv->cli,
4359 &ipc_srv->cli, &pol, path,
4360 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4362 talloc_destroy(ctx);
4363 return ret;
4367 * Are they asking to set the group?
4369 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4370 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
4372 /* Yup. */
4373 char *namevalue =
4374 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4376 if (! ipc_srv) {
4377 /* errno set by smbc_server() */
4378 ret = -1;
4380 else if (! namevalue) {
4381 errno = ENOMEM;
4382 ret = -1;
4383 } else {
4384 ret = cacl_set(ctx, &srv->cli,
4385 &ipc_srv->cli, &pol, path,
4386 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4388 talloc_destroy(ctx);
4389 return ret;
4393 * Are they asking to set a DOS attribute?
4395 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4396 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4397 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4398 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4399 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
4401 /* get a DOS Attribute Descriptor with current attributes */
4402 dad = dos_attr_query(context, ctx, path, srv);
4403 if (dad) {
4404 char *namevalue =
4405 talloc_asprintf(ctx, "%s:%s", name+16, (const char *) value);
4406 if (! namevalue) {
4407 errno = ENOMEM;
4408 ret = -1;
4409 } else {
4410 /* Overwrite old with provided new params */
4411 dos_attr_parse(context, dad, srv, namevalue);
4413 /* Set the new DOS attributes */
4414 #if 0 /* not yet implemented */
4415 ret2 = cli_setpathinfo(&srv->cli, path,
4416 dad->c_time,
4417 dad->a_time,
4418 dad->m_time,
4419 dad->mode);
4420 if (! ret2) {
4421 ret2 = cli_setatr(&srv->cli, path,
4422 dad->mode,
4423 dad->m_time);
4424 if (! ret2) {
4425 errno = smbc_errno(context,
4426 &srv->cli);
4429 #else
4430 ret2 = cli_setatr(&srv->cli, path,
4431 dad->mode, dad->m_time);
4432 if (! ret2) {
4433 errno = smbc_errno(context, &srv->cli);
4435 #endif
4437 /* ret2 has True (success) / False (failure) */
4438 if (ret2) {
4439 ret = 0;
4440 } else {
4441 ret = -1;
4444 } else {
4445 ret = -1;
4448 talloc_destroy(ctx);
4449 return ret;
4452 /* Unsupported attribute name */
4453 talloc_destroy(ctx);
4454 errno = EINVAL;
4455 return -1;
4458 int smbc_getxattr_ctx(SMBCCTX *context,
4459 const char *fname,
4460 const char *name,
4461 const void *value,
4462 size_t size)
4464 int ret;
4465 SMBCSRV *srv;
4466 SMBCSRV *ipc_srv;
4467 fstring server, share, user, password, workgroup;
4468 pstring path;
4469 TALLOC_CTX *ctx;
4470 POLICY_HND pol;
4473 if (!context || !context->internal ||
4474 !context->internal->_initialized) {
4476 errno = EINVAL; /* Best I can think of ... */
4477 return -1;
4481 if (!fname) {
4483 errno = EINVAL;
4484 return -1;
4488 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
4490 if (smbc_parse_path(context, fname,
4491 server, sizeof(server),
4492 share, sizeof(share),
4493 path, sizeof(path),
4494 user, sizeof(user),
4495 password, sizeof(password),
4496 NULL, 0)) {
4497 errno = EINVAL;
4498 return -1;
4501 if (user[0] == (char)0) fstrcpy(user, context->user);
4503 fstrcpy(workgroup, context->workgroup);
4505 srv = smbc_server(context, server, share, workgroup, user, password);
4506 if (!srv) {
4507 return -1; /* errno set by smbc_server */
4510 if (! srv->no_nt_session) {
4511 ipc_srv = smbc_attr_server(context, server, share,
4512 workgroup, user, password,
4513 &pol);
4514 if (! ipc_srv) {
4515 srv->no_nt_session = True;
4517 } else {
4518 ipc_srv = NULL;
4521 ctx = talloc_init("smbc:getxattr");
4522 if (!ctx) {
4523 errno = ENOMEM;
4524 return -1;
4527 /* Are they requesting a supported attribute? */
4528 if (StrCaseCmp(name, "system.*") == 0 ||
4529 StrnCaseCmp(name, "system.*!", 9) == 0 ||
4530 StrCaseCmp(name, "system.*+") == 0 ||
4531 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
4532 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4533 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
4534 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4535 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
4536 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4537 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4538 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
4539 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4540 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
4541 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4542 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
4543 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4544 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
4545 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4546 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
4547 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4548 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4549 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
4550 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
4552 /* Yup. */
4553 ret = cacl_get(context, ctx, srv,
4554 ipc_srv == NULL ? NULL : &ipc_srv->cli,
4555 &pol, path,
4556 CONST_DISCARD(char *, name),
4557 CONST_DISCARD(char *, value), size);
4558 if (ret < 0 && errno == 0) {
4559 errno = smbc_errno(context, &srv->cli);
4561 talloc_destroy(ctx);
4562 return ret;
4565 /* Unsupported attribute name */
4566 talloc_destroy(ctx);
4567 errno = EINVAL;
4568 return -1;
4572 int smbc_removexattr_ctx(SMBCCTX *context,
4573 const char *fname,
4574 const char *name)
4576 int ret;
4577 SMBCSRV *srv;
4578 SMBCSRV *ipc_srv;
4579 fstring server, share, user, password, workgroup;
4580 pstring path;
4581 TALLOC_CTX *ctx;
4582 POLICY_HND pol;
4584 if (!context || !context->internal ||
4585 !context->internal->_initialized) {
4587 errno = EINVAL; /* Best I can think of ... */
4588 return -1;
4592 if (!fname) {
4594 errno = EINVAL;
4595 return -1;
4599 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
4601 if (smbc_parse_path(context, fname,
4602 server, sizeof(server),
4603 share, sizeof(share),
4604 path, sizeof(path),
4605 user, sizeof(user),
4606 password, sizeof(password),
4607 NULL, 0)) {
4608 errno = EINVAL;
4609 return -1;
4612 if (user[0] == (char)0) fstrcpy(user, context->user);
4614 fstrcpy(workgroup, context->workgroup);
4616 srv = smbc_server(context, server, share, workgroup, user, password);
4617 if (!srv) {
4618 return -1; /* errno set by smbc_server */
4621 if (! srv->no_nt_session) {
4622 ipc_srv = smbc_attr_server(context, server, share,
4623 workgroup, user, password,
4624 &pol);
4625 srv->no_nt_session = True;
4626 } else {
4627 ipc_srv = NULL;
4630 if (! ipc_srv) {
4631 return -1; /* errno set by smbc_attr_server */
4634 ctx = talloc_init("smbc_removexattr");
4635 if (!ctx) {
4636 errno = ENOMEM;
4637 return -1;
4640 /* Are they asking to set the entire ACL? */
4641 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4642 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
4644 /* Yup. */
4645 ret = cacl_set(ctx, &srv->cli,
4646 &ipc_srv->cli, &pol, path,
4647 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
4648 talloc_destroy(ctx);
4649 return ret;
4653 * Are they asking to remove one or more spceific security descriptor
4654 * attributes?
4656 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4657 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4658 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
4659 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4660 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
4661 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4662 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4664 /* Yup. */
4665 ret = cacl_set(ctx, &srv->cli,
4666 &ipc_srv->cli, &pol, path,
4667 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
4668 talloc_destroy(ctx);
4669 return ret;
4672 /* Unsupported attribute name */
4673 talloc_destroy(ctx);
4674 errno = EINVAL;
4675 return -1;
4678 int smbc_listxattr_ctx(SMBCCTX *context,
4679 const char *fname,
4680 char *list,
4681 size_t size)
4684 * This isn't quite what listxattr() is supposed to do. This returns
4685 * the complete set of attribute names, always, rather than only those
4686 * attribute names which actually exist for a file. Hmmm...
4688 const char supported[] =
4689 "system.*\0"
4690 "system.*+\0"
4691 "system.nt_sec_desc.revision\0"
4692 "system.nt_sec_desc.owner\0"
4693 "system.nt_sec_desc.owner+\0"
4694 "system.nt_sec_desc.group\0"
4695 "system.nt_sec_desc.group+\0"
4696 "system.nt_sec_desc.acl.*\0"
4697 "system.nt_sec_desc.acl\0"
4698 "system.nt_sec_desc.acl+\0"
4699 "system.nt_sec_desc.*\0"
4700 "system.nt_sec_desc.*+\0"
4701 "system.dos_attr.*\0"
4702 "system.dos_attr.mode\0"
4703 "system.dos_attr.c_time\0"
4704 "system.dos_attr.a_time\0"
4705 "system.dos_attr.m_time\0"
4708 if (size == 0) {
4709 return sizeof(supported);
4712 if (sizeof(supported) > size) {
4713 errno = ERANGE;
4714 return -1;
4717 /* this can't be strcpy() because there are embedded null characters */
4718 memcpy(list, supported, sizeof(supported));
4719 return sizeof(supported);
4724 * Open a print file to be written to by other calls
4727 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
4729 fstring server, share, user, password;
4730 pstring path;
4732 if (!context || !context->internal ||
4733 !context->internal->_initialized) {
4735 errno = EINVAL;
4736 return NULL;
4740 if (!fname) {
4742 errno = EINVAL;
4743 return NULL;
4747 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
4749 if (smbc_parse_path(context, fname,
4750 server, sizeof(server),
4751 share, sizeof(share),
4752 path, sizeof(path),
4753 user, sizeof(user),
4754 password, sizeof(password),
4755 NULL, 0)) {
4756 errno = EINVAL;
4757 return NULL;
4760 /* What if the path is empty, or the file exists? */
4762 return context->open(context, fname, O_WRONLY, 666);
4767 * Routine to print a file on a remote server ...
4769 * We open the file, which we assume to be on a remote server, and then
4770 * copy it to a print file on the share specified by printq.
4773 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
4775 SMBCFILE *fid1, *fid2;
4776 int bytes, saverr, tot_bytes = 0;
4777 char buf[4096];
4779 if (!c_file || !c_file->internal->_initialized || !c_print ||
4780 !c_print->internal->_initialized) {
4782 errno = EINVAL;
4783 return -1;
4787 if (!fname && !printq) {
4789 errno = EINVAL;
4790 return -1;
4794 /* Try to open the file for reading ... */
4796 if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
4798 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
4799 return -1; /* smbc_open sets errno */
4803 /* Now, try to open the printer file for writing */
4805 if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
4807 saverr = errno; /* Save errno */
4808 c_file->close(c_file, fid1);
4809 errno = saverr;
4810 return -1;
4814 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
4816 tot_bytes += bytes;
4818 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
4820 saverr = errno;
4821 c_file->close(c_file, fid1);
4822 c_print->close(c_print, fid2);
4823 errno = saverr;
4829 saverr = errno;
4831 c_file->close(c_file, fid1); /* We have to close these anyway */
4832 c_print->close(c_print, fid2);
4834 if (bytes < 0) {
4836 errno = saverr;
4837 return -1;
4841 return tot_bytes;
4846 * Routine to list print jobs on a printer share ...
4849 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
4851 SMBCSRV *srv;
4852 fstring server, share, user, password, workgroup;
4853 pstring path;
4855 if (!context || !context->internal ||
4856 !context->internal->_initialized) {
4858 errno = EINVAL;
4859 return -1;
4863 if (!fname) {
4865 errno = EINVAL;
4866 return -1;
4870 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
4872 if (smbc_parse_path(context, fname,
4873 server, sizeof(server),
4874 share, sizeof(share),
4875 path, sizeof(path),
4876 user, sizeof(user),
4877 password, sizeof(password),
4878 NULL, 0)) {
4879 errno = EINVAL;
4880 return -1;
4883 if (user[0] == (char)0) fstrcpy(user, context->user);
4885 fstrcpy(workgroup, context->workgroup);
4887 srv = smbc_server(context, server, share, workgroup, user, password);
4889 if (!srv) {
4891 return -1; /* errno set by smbc_server */
4895 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
4897 errno = smbc_errno(context, &srv->cli);
4898 return -1;
4902 return 0;
4907 * Delete a print job from a remote printer share
4910 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
4912 SMBCSRV *srv;
4913 fstring server, share, user, password, workgroup;
4914 pstring path;
4915 int err;
4917 if (!context || !context->internal ||
4918 !context->internal->_initialized) {
4920 errno = EINVAL;
4921 return -1;
4925 if (!fname) {
4927 errno = EINVAL;
4928 return -1;
4932 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
4934 if (smbc_parse_path(context, fname,
4935 server, sizeof(server),
4936 share, sizeof(share),
4937 path, sizeof(path),
4938 user, sizeof(user),
4939 password, sizeof(password),
4940 NULL, 0)) {
4941 errno = EINVAL;
4942 return -1;
4945 if (user[0] == (char)0) fstrcpy(user, context->user);
4947 fstrcpy(workgroup, context->workgroup);
4949 srv = smbc_server(context, server, share, workgroup, user, password);
4951 if (!srv) {
4953 return -1; /* errno set by smbc_server */
4957 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
4959 if (err < 0)
4960 errno = smbc_errno(context, &srv->cli);
4961 else if (err == ERRnosuchprintjob)
4962 errno = EINVAL;
4963 return -1;
4967 return 0;
4972 * Get a new empty handle to fill in with your own info
4974 SMBCCTX * smbc_new_context(void)
4976 SMBCCTX * context;
4978 context = SMB_MALLOC_P(SMBCCTX);
4979 if (!context) {
4980 errno = ENOMEM;
4981 return NULL;
4984 ZERO_STRUCTP(context);
4986 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
4987 if (!context->internal) {
4988 errno = ENOMEM;
4989 return NULL;
4992 ZERO_STRUCTP(context->internal);
4995 /* ADD REASONABLE DEFAULTS */
4996 context->debug = 0;
4997 context->timeout = 20000; /* 20 seconds */
4999 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5000 context->options.urlencode_readdir_entries = False;/* backward compat */
5001 context->options.one_share_per_server = False;/* backward compat */
5003 context->open = smbc_open_ctx;
5004 context->creat = smbc_creat_ctx;
5005 context->read = smbc_read_ctx;
5006 context->write = smbc_write_ctx;
5007 context->close = smbc_close_ctx;
5008 context->unlink = smbc_unlink_ctx;
5009 context->rename = smbc_rename_ctx;
5010 context->lseek = smbc_lseek_ctx;
5011 context->stat = smbc_stat_ctx;
5012 context->fstat = smbc_fstat_ctx;
5013 context->opendir = smbc_opendir_ctx;
5014 context->closedir = smbc_closedir_ctx;
5015 context->readdir = smbc_readdir_ctx;
5016 context->getdents = smbc_getdents_ctx;
5017 context->mkdir = smbc_mkdir_ctx;
5018 context->rmdir = smbc_rmdir_ctx;
5019 context->telldir = smbc_telldir_ctx;
5020 context->lseekdir = smbc_lseekdir_ctx;
5021 context->fstatdir = smbc_fstatdir_ctx;
5022 context->chmod = smbc_chmod_ctx;
5023 context->utimes = smbc_utimes_ctx;
5024 context->setxattr = smbc_setxattr_ctx;
5025 context->getxattr = smbc_getxattr_ctx;
5026 context->removexattr = smbc_removexattr_ctx;
5027 context->listxattr = smbc_listxattr_ctx;
5028 context->open_print_job = smbc_open_print_job_ctx;
5029 context->print_file = smbc_print_file_ctx;
5030 context->list_print_jobs = smbc_list_print_jobs_ctx;
5031 context->unlink_print_job = smbc_unlink_print_job_ctx;
5033 context->callbacks.check_server_fn = smbc_check_server;
5034 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5036 smbc_default_cache_functions(context);
5038 return context;
5042 * Free a context
5044 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5045 * and thus you'll be leaking memory if not handled properly.
5048 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
5050 if (!context) {
5051 errno = EBADF;
5052 return 1;
5055 if (shutdown_ctx) {
5056 SMBCFILE * f;
5057 DEBUG(1,("Performing aggressive shutdown.\n"));
5059 f = context->internal->_files;
5060 while (f) {
5061 context->close(context, f);
5062 f = f->next;
5064 context->internal->_files = NULL;
5066 /* First try to remove the servers the nice way. */
5067 if (context->callbacks.purge_cached_fn(context)) {
5068 SMBCSRV * s;
5069 SMBCSRV * next;
5070 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
5071 s = context->internal->_servers;
5072 while (s) {
5073 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
5074 cli_shutdown(&s->cli);
5075 context->callbacks.remove_cached_srv_fn(context, s);
5076 next = s->next;
5077 DLIST_REMOVE(context->internal->_servers, s);
5078 SAFE_FREE(s);
5079 s = next;
5081 context->internal->_servers = NULL;
5084 else {
5085 /* This is the polite way */
5086 if (context->callbacks.purge_cached_fn(context)) {
5087 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
5088 errno = EBUSY;
5089 return 1;
5091 if (context->internal->_servers) {
5092 DEBUG(1, ("Active servers in context, free_context failed.\n"));
5093 errno = EBUSY;
5094 return 1;
5096 if (context->internal->_files) {
5097 DEBUG(1, ("Active files in context, free_context failed.\n"));
5098 errno = EBUSY;
5099 return 1;
5103 /* Things we have to clean up */
5104 SAFE_FREE(context->workgroup);
5105 SAFE_FREE(context->netbios_name);
5106 SAFE_FREE(context->user);
5108 DEBUG(3, ("Context %p succesfully freed\n", context));
5109 SAFE_FREE(context->internal);
5110 SAFE_FREE(context);
5111 return 0;
5116 * Initialise the library etc
5118 * We accept a struct containing handle information.
5119 * valid values for info->debug from 0 to 100,
5120 * and insist that info->fn must be non-null.
5122 SMBCCTX * smbc_init_context(SMBCCTX * context)
5124 pstring conf;
5125 int pid;
5126 char *user = NULL, *home = NULL;
5128 if (!context || !context->internal) {
5129 errno = EBADF;
5130 return NULL;
5133 /* Do not initialise the same client twice */
5134 if (context->internal->_initialized) {
5135 return 0;
5138 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
5140 errno = EINVAL;
5141 return NULL;
5145 if (!smbc_initialized) {
5146 /* Do some library wide intialisations the first time we get called */
5148 /* Set this to what the user wants */
5149 DEBUGLEVEL = context->debug;
5151 setup_logging( "libsmbclient", True);
5153 /* Here we would open the smb.conf file if needed ... */
5155 home = getenv("HOME");
5157 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5159 load_interfaces(); /* Load the list of interfaces ... */
5161 in_client = True; /* FIXME, make a param */
5163 if (!lp_load(conf, True, False, False)) {
5166 * Well, if that failed, try the dyn_CONFIGFILE
5167 * Which points to the standard locn, and if that
5168 * fails, silently ignore it and use the internal
5169 * defaults ...
5172 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
5173 DEBUG(5, ("Could not load either config file: "
5174 "%s or %s\n",
5175 conf, dyn_CONFIGFILE));
5176 } else {
5178 * We loaded the global config file. Now lets
5179 * load user-specific modifications to the
5180 * global config.
5182 slprintf(conf, sizeof(conf),
5183 "%s/.smb/smb.conf.append", home);
5184 if (!lp_load(conf, True, False, False)) {
5185 DEBUG(10,
5186 ("Could not append config file: "
5187 "%s\n",
5188 conf));
5193 reopen_logs(); /* Get logging working ... */
5196 * Block SIGPIPE (from lib/util_sock.c: write())
5197 * It is not needed and should not stop execution
5199 BlockSignals(True, SIGPIPE);
5201 /* Done with one-time initialisation */
5202 smbc_initialized = 1;
5206 if (!context->user) {
5208 * FIXME: Is this the best way to get the user info?
5210 user = getenv("USER");
5211 /* walk around as "guest" if no username can be found */
5212 if (!user) context->user = SMB_STRDUP("guest");
5213 else context->user = SMB_STRDUP(user);
5216 if (!context->netbios_name) {
5218 * We try to get our netbios name from the config. If that fails we fall
5219 * back on constructing our netbios name from our hostname etc
5221 if (global_myname()) {
5222 context->netbios_name = SMB_STRDUP(global_myname());
5224 else {
5226 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
5228 pid = sys_getpid();
5229 context->netbios_name = SMB_MALLOC(17);
5230 if (!context->netbios_name) {
5231 errno = ENOMEM;
5232 return NULL;
5234 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
5238 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
5240 if (!context->workgroup) {
5241 if (lp_workgroup()) {
5242 context->workgroup = SMB_STRDUP(lp_workgroup());
5244 else {
5245 /* TODO: Think about a decent default workgroup */
5246 context->workgroup = SMB_STRDUP("samba");
5250 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
5252 /* shortest timeout is 1 second */
5253 if (context->timeout > 0 && context->timeout < 1000)
5254 context->timeout = 1000;
5257 * FIXME: Should we check the function pointers here?
5260 context->internal->_initialized = 1;
5262 return context;
5266 /* Return the verion of samba, and thus libsmbclient */
5267 const char *
5268 smbc_version(void)
5270 return samba_version_string();