Samba 3: added Samba 3.0.24 sources
[tomato.git] / release / src / router / samba3 / source / libsmb / libsmbclient.c
blob80b09fab1a1ed0bed6121409bea3e4372323f533
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 {
34 int mode;
35 SMB_OFF_T size;
36 time_t a_time;
37 time_t c_time;
38 time_t m_time;
39 SMB_INO_T inode;
40 } DOS_ATTR_DESC;
44 * Internal flags for extended attributes
47 /* internal mode values */
48 #define SMBC_XATTR_MODE_ADD 1
49 #define SMBC_XATTR_MODE_REMOVE 2
50 #define SMBC_XATTR_MODE_REMOVE_ALL 3
51 #define SMBC_XATTR_MODE_SET 4
52 #define SMBC_XATTR_MODE_CHOWN 5
53 #define SMBC_XATTR_MODE_CHGRP 6
55 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
57 /*We should test for this in configure ... */
58 #ifndef ENOTSUP
59 #define ENOTSUP EOPNOTSUPP
60 #endif
63 * Functions exported by libsmb_cache.c that we need here
65 int smbc_default_cache_functions(SMBCCTX *context);
67 /*
68 * check if an element is part of the list.
69 * FIXME: Does not belong here !
70 * Can anyone put this in a macro in dlinklist.h ?
71 * -- Tom
73 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
74 if (!p || !list) return False;
75 do {
76 if (p == list) return True;
77 list = list->next;
78 } while (list);
79 return False;
83 * Find an lsa pipe handle associated with a cli struct.
85 static struct rpc_pipe_client *
86 find_lsa_pipe_hnd(struct cli_state *ipc_cli)
88 struct rpc_pipe_client *pipe_hnd;
90 for (pipe_hnd = ipc_cli->pipe_list;
91 pipe_hnd;
92 pipe_hnd = pipe_hnd->next) {
94 if (pipe_hnd->pipe_idx == PI_LSARPC) {
95 return pipe_hnd;
99 return NULL;
102 static int
103 smbc_close_ctx(SMBCCTX *context,
104 SMBCFILE *file);
105 static off_t
106 smbc_lseek_ctx(SMBCCTX *context,
107 SMBCFILE *file,
108 off_t offset,
109 int whence);
111 extern BOOL in_client;
114 * Is the logging working / configfile read ?
116 static int smbc_initialized = 0;
118 static int
119 hex2int( unsigned int _char )
121 if ( _char >= 'A' && _char <='F')
122 return _char - 'A' + 10;
123 if ( _char >= 'a' && _char <='f')
124 return _char - 'a' + 10;
125 if ( _char >= '0' && _char <='9')
126 return _char - '0';
127 return -1;
131 * smbc_urldecode()
133 * Convert strings of %xx to their single character equivalent. Each 'x' must
134 * be a valid hexadecimal digit, or that % sequence is left undecoded.
136 * dest may, but need not be, the same pointer as src.
138 * Returns the number of % sequences which could not be converted due to lack
139 * of two following hexadecimal digits.
142 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
144 int old_length = strlen(src);
145 int i = 0;
146 int err_count = 0;
147 pstring temp;
148 char * p;
150 if ( old_length == 0 ) {
151 return 0;
154 p = temp;
155 while ( i < old_length ) {
156 unsigned char character = src[ i++ ];
158 if (character == '%') {
159 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
160 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
162 /* Replace valid sequence */
163 if (a != -1 && b != -1) {
165 /* Replace valid %xx sequence with %dd */
166 character = (a * 16) + b;
168 if (character == '\0') {
169 break; /* Stop at %00 */
172 i += 2;
173 } else {
175 err_count++;
179 *p++ = character;
182 *p = '\0';
184 strncpy(dest, temp, max_dest_len - 1);
185 dest[max_dest_len - 1] = '\0';
187 return err_count;
191 * smbc_urlencode()
193 * Convert any characters not specifically allowed in a URL into their %xx
194 * equivalent.
196 * Returns the remaining buffer length.
199 smbc_urlencode(char * dest, char * src, int max_dest_len)
201 char hex[] = "0123456789ABCDEF";
203 for (; *src != '\0' && max_dest_len >= 3; src++) {
205 if ((*src < '0' &&
206 *src != '-' &&
207 *src != '.') ||
208 (*src > '9' &&
209 *src < 'A') ||
210 (*src > 'Z' &&
211 *src < 'a' &&
212 *src != '_') ||
213 (*src > 'z')) {
214 *dest++ = '%';
215 *dest++ = hex[(*src >> 4) & 0x0f];
216 *dest++ = hex[*src & 0x0f];
217 max_dest_len -= 3;
218 } else {
219 *dest++ = *src;
220 max_dest_len--;
224 *dest++ = '\0';
225 max_dest_len--;
227 return max_dest_len;
231 * Function to parse a path and turn it into components
233 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
234 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
235 * general format ("smb:" only; we do not look for "cifs:").
238 * We accept:
239 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
241 * Meaning of URLs:
243 * smb:// Show all workgroups.
245 * The method of locating the list of workgroups varies
246 * depending upon the setting of the context variable
247 * context->options.browse_max_lmb_count. This value
248 * determine the maximum number of local master browsers to
249 * query for the list of workgroups. In order to ensure that
250 * a complete list of workgroups is obtained, all master
251 * browsers must be queried, but if there are many
252 * workgroups, the time spent querying can begin to add up.
253 * For small networks (not many workgroups), it is suggested
254 * that this variable be set to 0, indicating query all local
255 * master browsers. When the network has many workgroups, a
256 * reasonable setting for this variable might be around 3.
258 * smb://name/ if name<1D> or name<1B> exists, list servers in
259 * workgroup, else, if name<20> exists, list all shares
260 * for server ...
262 * If "options" are provided, this function returns the entire option list as a
263 * string, for later parsing by the caller. Note that currently, no options
264 * are supported.
267 static const char *smbc_prefix = "smb:";
269 static int
270 smbc_parse_path(SMBCCTX *context,
271 const char *fname,
272 char *workgroup, int workgroup_len,
273 char *server, int server_len,
274 char *share, int share_len,
275 char *path, int path_len,
276 char *user, int user_len,
277 char *password, int password_len,
278 char *options, int options_len)
280 static pstring s;
281 pstring userinfo;
282 const char *p;
283 char *q, *r;
284 int len;
286 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
289 * Assume we wont find an authentication domain to parse, so default
290 * to the workgroup in the provided context.
292 if (workgroup != NULL) {
293 strncpy(workgroup, context->workgroup, workgroup_len - 1);
294 workgroup[workgroup_len - 1] = '\0';
297 if (options != NULL && options_len > 0) {
298 options[0] = (char)0;
300 pstrcpy(s, fname);
302 /* see if it has the right prefix */
303 len = strlen(smbc_prefix);
304 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
305 return -1; /* What about no smb: ? */
308 p = s + len;
310 /* Watch the test below, we are testing to see if we should exit */
312 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
314 DEBUG(1, ("Invalid path (does not begin with smb://"));
315 return -1;
319 p += 2; /* Skip the double slash */
321 /* See if any options were specified */
322 if ((q = strrchr(p, '?')) != NULL ) {
323 /* There are options. Null terminate here and point to them */
324 *q++ = '\0';
326 DEBUG(4, ("Found options '%s'", q));
328 /* Copy the options */
329 if (options != NULL && options_len > 0) {
330 safe_strcpy(options, q, options_len - 1);
334 if (*p == (char)0)
335 goto decoding;
337 if (*p == '/') {
339 strncpy(server, context->workgroup,
340 ((strlen(context->workgroup) < 16)
341 ? strlen(context->workgroup)
342 : 16));
343 server[server_len - 1] = '\0';
344 return 0;
349 * ok, its for us. Now parse out the server, share etc.
351 * However, we want to parse out [[domain;]user[:password]@] if it
352 * exists ...
355 /* check that '@' occurs before '/', if '/' exists at all */
356 q = strchr_m(p, '@');
357 r = strchr_m(p, '/');
358 if (q && (!r || q < r)) {
359 pstring username, passwd, domain;
360 const char *u = userinfo;
362 next_token(&p, userinfo, "@", sizeof(fstring));
364 username[0] = passwd[0] = domain[0] = 0;
366 if (strchr_m(u, ';')) {
368 next_token(&u, domain, ";", sizeof(fstring));
372 if (strchr_m(u, ':')) {
374 next_token(&u, username, ":", sizeof(fstring));
376 pstrcpy(passwd, u);
379 else {
381 pstrcpy(username, u);
385 if (domain[0] && workgroup) {
386 strncpy(workgroup, domain, workgroup_len - 1);
387 workgroup[workgroup_len - 1] = '\0';
390 if (username[0]) {
391 strncpy(user, username, user_len - 1);
392 user[user_len - 1] = '\0';
395 if (passwd[0]) {
396 strncpy(password, passwd, password_len - 1);
397 password[password_len - 1] = '\0';
402 if (!next_token(&p, server, "/", sizeof(fstring))) {
404 return -1;
408 if (*p == (char)0) goto decoding; /* That's it ... */
410 if (!next_token(&p, share, "/", sizeof(fstring))) {
412 return -1;
417 * Prepend a leading slash if there's a file path, as required by
418 * NetApp filers.
420 *path = '\0';
421 if (*p != '\0') {
422 *path = '/';
423 safe_strcpy(path + 1, p, path_len - 2);
426 all_string_sub(path, "/", "\\", 0);
428 decoding:
429 (void) smbc_urldecode(path, path, path_len);
430 (void) smbc_urldecode(server, server, server_len);
431 (void) smbc_urldecode(share, share, share_len);
432 (void) smbc_urldecode(user, user, user_len);
433 (void) smbc_urldecode(password, password, password_len);
435 return 0;
439 * Verify that the options specified in a URL are valid
441 static int
442 smbc_check_options(char *server,
443 char *share,
444 char *path,
445 char *options)
447 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' "
448 "path='%s' options='%s'\n",
449 server, share, path, options));
451 /* No options at all is always ok */
452 if (! *options) return 0;
454 /* Currently, we don't support any options. */
455 return -1;
459 * Convert an SMB error into a UNIX error ...
461 static int
462 smbc_errno(SMBCCTX *context,
463 struct cli_state *c)
465 int ret = cli_errno(c);
467 if (cli_is_dos_error(c)) {
468 uint8 eclass;
469 uint32 ecode;
471 cli_dos_error(c, &eclass, &ecode);
473 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
474 (int)eclass, (int)ecode, (int)ecode, ret));
475 } else {
476 NTSTATUS status;
478 status = cli_nt_error(c);
480 DEBUG(3,("smbc errno %s -> %d\n",
481 nt_errstr(status), ret));
484 return ret;
488 * Check a server for being alive and well.
489 * returns 0 if the server is in shape. Returns 1 on error
491 * Also useable outside libsmbclient to enable external cache
492 * to do some checks too.
494 static int
495 smbc_check_server(SMBCCTX * context,
496 SMBCSRV * server)
498 if ( send_keepalive(server->cli.fd) == False )
499 return 1;
501 /* connection is ok */
502 return 0;
506 * Remove a server from the cached server list it's unused.
507 * On success, 0 is returned. 1 is returned if the server could not be removed.
509 * Also useable outside libsmbclient
512 smbc_remove_unused_server(SMBCCTX * context,
513 SMBCSRV * srv)
515 SMBCFILE * file;
517 /* are we being fooled ? */
518 if (!context || !context->internal ||
519 !context->internal->_initialized || !srv) return 1;
522 /* Check all open files/directories for a relation with this server */
523 for (file = context->internal->_files; file; file=file->next) {
524 if (file->srv == srv) {
525 /* Still used */
526 DEBUG(3, ("smbc_remove_usused_server: "
527 "%p still used by %p.\n",
528 srv, file));
529 return 1;
533 DLIST_REMOVE(context->internal->_servers, srv);
535 cli_shutdown(&srv->cli);
537 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
539 context->callbacks.remove_cached_srv_fn(context, srv);
541 SAFE_FREE(srv);
543 return 0;
546 static SMBCSRV *
547 find_server(SMBCCTX *context,
548 const char *server,
549 const char *share,
550 fstring workgroup,
551 fstring username,
552 fstring password)
554 SMBCSRV *srv;
555 int auth_called = 0;
557 check_server_cache:
559 srv = context->callbacks.get_cached_srv_fn(context, server, share,
560 workgroup, username);
562 if (!auth_called && !srv && (!username[0] || !password[0])) {
563 if (context->internal->_auth_fn_with_context != NULL) {
564 context->internal->_auth_fn_with_context(
565 context,
566 server, share,
567 workgroup, sizeof(fstring),
568 username, sizeof(fstring),
569 password, sizeof(fstring));
570 } else {
571 context->callbacks.auth_fn(
572 server, share,
573 workgroup, sizeof(fstring),
574 username, sizeof(fstring),
575 password, sizeof(fstring));
579 * However, smbc_auth_fn may have picked up info relating to
580 * an existing connection, so try for an existing connection
581 * again ...
583 auth_called = 1;
584 goto check_server_cache;
588 if (srv) {
589 if (context->callbacks.check_server_fn(context, srv)) {
591 * This server is no good anymore
592 * Try to remove it and check for more possible
593 * servers in the cache
595 if (context->callbacks.remove_unused_server_fn(context,
596 srv)) {
598 * We could not remove the server completely,
599 * remove it from the cache so we will not get
600 * it again. It will be removed when the last
601 * file/dir is closed.
603 context->callbacks.remove_cached_srv_fn(context,
604 srv);
608 * Maybe there are more cached connections to this
609 * server
611 goto check_server_cache;
614 return srv;
617 return NULL;
621 * Connect to a server, possibly on an existing connection
623 * Here, what we want to do is: If the server and username
624 * match an existing connection, reuse that, otherwise, establish a
625 * new connection.
627 * If we have to create a new connection, call the auth_fn to get the
628 * info we need, unless the username and password were passed in.
631 static SMBCSRV *
632 smbc_server(SMBCCTX *context,
633 BOOL connect_if_not_found,
634 const char *server,
635 const char *share,
636 fstring workgroup,
637 fstring username,
638 fstring password)
640 SMBCSRV *srv=NULL;
641 struct cli_state c;
642 struct nmb_name called, calling;
643 const char *server_n = server;
644 pstring ipenv;
645 struct in_addr ip;
646 int tried_reverse = 0;
647 int port_try_first;
648 int port_try_next;
649 const char *username_used;
651 zero_ip(&ip);
652 ZERO_STRUCT(c);
654 if (server[0] == 0) {
655 errno = EPERM;
656 return NULL;
659 /* Look for a cached connection */
660 srv = find_server(context, server, share,
661 workgroup, username, password);
664 * If we found a connection and we're only allowed one share per
665 * server...
667 if (srv && *share != '\0' && context->options.one_share_per_server) {
670 * ... then if there's no current connection to the share,
671 * connect to it. find_server(), or rather the function
672 * pointed to by context->callbacks.get_cached_srv_fn which
673 * was called by find_server(), will have issued a tree
674 * disconnect if the requested share is not the same as the
675 * one that was already connected.
677 if (srv->cli.cnum == (uint16) -1) {
678 /* Ensure we have accurate auth info */
679 if (context->internal->_auth_fn_with_context != NULL) {
680 context->internal->_auth_fn_with_context(
681 context,
682 server, share,
683 workgroup, sizeof(fstring),
684 username, sizeof(fstring),
685 password, sizeof(fstring));
686 } else {
687 context->callbacks.auth_fn(
688 server, share,
689 workgroup, sizeof(fstring),
690 username, sizeof(fstring),
691 password, sizeof(fstring));
694 if (! cli_send_tconX(&srv->cli, share, "?????",
695 password, strlen(password)+1)) {
697 errno = smbc_errno(context, &srv->cli);
698 cli_shutdown(&srv->cli);
699 context->callbacks.remove_cached_srv_fn(context,
700 srv);
701 srv = NULL;
705 * Regenerate the dev value since it's based on both
706 * server and share
708 if (srv) {
709 srv->dev = (dev_t)(str_checksum(server) ^
710 str_checksum(share));
715 /* If we have a connection... */
716 if (srv) {
718 /* ... then we're done here. Give 'em what they came for. */
719 return srv;
722 /* If we're not asked to connect when a connection doesn't exist... */
723 if (! connect_if_not_found) {
724 /* ... then we're done here. */
725 return NULL;
728 make_nmb_name(&calling, context->netbios_name, 0x0);
729 make_nmb_name(&called , server, 0x20);
731 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
733 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
735 again:
736 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
738 zero_ip(&ip);
740 /* have to open a new connection */
741 if (!cli_initialise(&c)) {
742 errno = ENOMEM;
743 return NULL;
746 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
747 c.use_kerberos = True;
749 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
750 c.fallback_after_kerberos = True;
753 c.timeout = context->timeout;
756 * Force use of port 139 for first try if share is $IPC, empty, or
757 * null, so browse lists can work
759 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
760 port_try_first = 139;
761 port_try_next = 445;
762 } else {
763 port_try_first = 445;
764 port_try_next = 139;
767 c.port = port_try_first;
769 if (!cli_connect(&c, server_n, &ip)) {
771 /* First connection attempt failed. Try alternate port. */
772 c.port = port_try_next;
774 if (!cli_connect(&c, server_n, &ip)) {
775 cli_shutdown(&c);
776 errno = ETIMEDOUT;
777 return NULL;
781 if (!cli_session_request(&c, &calling, &called)) {
782 cli_shutdown(&c);
783 if (strcmp(called.name, "*SMBSERVER")) {
784 make_nmb_name(&called , "*SMBSERVER", 0x20);
785 goto again;
787 else { /* Try one more time, but ensure we don't loop */
789 /* Only try this if server is an IP address ... */
791 if (is_ipaddress(server) && !tried_reverse) {
792 fstring remote_name;
793 struct in_addr rem_ip;
795 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
796 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
797 errno = ETIMEDOUT;
798 return NULL;
801 tried_reverse++; /* Yuck */
803 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
804 make_nmb_name(&called, remote_name, 0x20);
805 goto again;
811 errno = ETIMEDOUT;
812 return NULL;
815 DEBUG(4,(" session request ok\n"));
817 if (!cli_negprot(&c)) {
818 cli_shutdown(&c);
819 errno = ETIMEDOUT;
820 return NULL;
823 username_used = username;
825 if (!cli_session_setup(&c, username_used,
826 password, strlen(password),
827 password, strlen(password),
828 workgroup)) {
830 /* Failed. Try an anonymous login, if allowed by flags. */
831 username_used = "";
833 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
834 !cli_session_setup(&c, username_used,
835 password, 1,
836 password, 0,
837 workgroup)) {
839 cli_shutdown(&c);
840 errno = EPERM;
841 return NULL;
845 DEBUG(4,(" session setup ok\n"));
847 if (!cli_send_tconX(&c, share, "?????",
848 password, strlen(password)+1)) {
849 errno = smbc_errno(context, &c);
850 cli_shutdown(&c);
851 return NULL;
854 DEBUG(4,(" tconx ok\n"));
857 * Ok, we have got a nice connection
858 * Let's allocate a server structure.
861 srv = SMB_MALLOC_P(SMBCSRV);
862 if (!srv) {
863 errno = ENOMEM;
864 goto failed;
867 ZERO_STRUCTP(srv);
868 srv->cli = c;
869 srv->cli.allocated = False;
870 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
871 srv->no_pathinfo = False;
872 srv->no_pathinfo2 = False;
873 srv->no_nt_session = False;
875 /* now add it to the cache (internal or external) */
876 /* Let the cache function set errno if it wants to */
877 errno = 0;
878 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
879 int saved_errno = errno;
880 DEBUG(3, (" Failed to add server to cache\n"));
881 errno = saved_errno;
882 if (errno == 0) {
883 errno = ENOMEM;
885 goto failed;
888 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
889 server, share, srv));
891 DLIST_ADD(context->internal->_servers, srv);
892 return srv;
894 failed:
895 cli_shutdown(&c);
896 if (!srv) return NULL;
898 SAFE_FREE(srv);
899 return NULL;
903 * Connect to a server for getting/setting attributes, possibly on an existing
904 * connection. This works similarly to smbc_server().
906 static SMBCSRV *
907 smbc_attr_server(SMBCCTX *context,
908 const char *server,
909 const char *share,
910 fstring workgroup,
911 fstring username,
912 fstring password,
913 POLICY_HND *pol)
915 struct in_addr ip;
916 struct cli_state *ipc_cli;
917 struct rpc_pipe_client *pipe_hnd;
918 NTSTATUS nt_status;
919 SMBCSRV *ipc_srv=NULL;
922 * See if we've already created this special connection. Reference
923 * our "special" share name '*IPC$', which is an impossible real share
924 * name due to the leading asterisk.
926 ipc_srv = find_server(context, server, "*IPC$",
927 workgroup, username, password);
928 if (!ipc_srv) {
930 /* We didn't find a cached connection. Get the password */
931 if (*password == '\0') {
932 /* ... then retrieve it now. */
933 if (context->internal->_auth_fn_with_context != NULL) {
934 context->internal->_auth_fn_with_context(
935 context,
936 server, share,
937 workgroup, sizeof(fstring),
938 username, sizeof(fstring),
939 password, sizeof(fstring));
940 } else {
941 context->callbacks.auth_fn(
942 server, share,
943 workgroup, sizeof(fstring),
944 username, sizeof(fstring),
945 password, sizeof(fstring));
949 zero_ip(&ip);
950 nt_status = cli_full_connection(&ipc_cli,
951 global_myname(), server,
952 &ip, 0, "IPC$", "?????",
953 username, workgroup,
954 password, 0,
955 Undefined, NULL);
956 if (! NT_STATUS_IS_OK(nt_status)) {
957 DEBUG(1,("cli_full_connection failed! (%s)\n",
958 nt_errstr(nt_status)));
959 errno = ENOTSUP;
960 return NULL;
963 ipc_srv = SMB_MALLOC_P(SMBCSRV);
964 if (!ipc_srv) {
965 errno = ENOMEM;
966 cli_shutdown(ipc_cli);
967 return NULL;
970 ZERO_STRUCTP(ipc_srv);
971 ipc_srv->cli = *ipc_cli;
972 ipc_srv->cli.allocated = False;
974 free(ipc_cli);
976 if (pol) {
977 pipe_hnd = cli_rpc_pipe_open_noauth(&ipc_srv->cli,
978 PI_LSARPC,
979 &nt_status);
980 if (!pipe_hnd) {
981 DEBUG(1, ("cli_nt_session_open fail!\n"));
982 errno = ENOTSUP;
983 cli_shutdown(&ipc_srv->cli);
984 free(ipc_srv);
985 return NULL;
989 * Some systems don't support
990 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
991 * so we might as well do it too.
994 nt_status = rpccli_lsa_open_policy(
995 pipe_hnd,
996 ipc_srv->cli.mem_ctx,
997 True,
998 GENERIC_EXECUTE_ACCESS,
999 pol);
1001 if (!NT_STATUS_IS_OK(nt_status)) {
1002 errno = smbc_errno(context, &ipc_srv->cli);
1003 cli_shutdown(&ipc_srv->cli);
1004 return NULL;
1008 /* now add it to the cache (internal or external) */
1010 errno = 0; /* let cache function set errno if it likes */
1011 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
1012 server,
1013 "*IPC$",
1014 workgroup,
1015 username)) {
1016 DEBUG(3, (" Failed to add server to cache\n"));
1017 if (errno == 0) {
1018 errno = ENOMEM;
1020 cli_shutdown(&ipc_srv->cli);
1021 free(ipc_srv);
1022 return NULL;
1025 DLIST_ADD(context->internal->_servers, ipc_srv);
1028 return ipc_srv;
1032 * Routine to open() a file ...
1035 static SMBCFILE *
1036 smbc_open_ctx(SMBCCTX *context,
1037 const char *fname,
1038 int flags,
1039 mode_t mode)
1041 fstring server, share, user, password, workgroup;
1042 pstring path;
1043 pstring targetpath;
1044 struct cli_state *targetcli;
1045 SMBCSRV *srv = NULL;
1046 SMBCFILE *file = NULL;
1047 int fd;
1049 if (!context || !context->internal ||
1050 !context->internal->_initialized) {
1052 errno = EINVAL; /* Best I can think of ... */
1053 return NULL;
1057 if (!fname) {
1059 errno = EINVAL;
1060 return NULL;
1064 if (smbc_parse_path(context, fname,
1065 workgroup, sizeof(workgroup),
1066 server, sizeof(server),
1067 share, sizeof(share),
1068 path, sizeof(path),
1069 user, sizeof(user),
1070 password, sizeof(password),
1071 NULL, 0)) {
1072 errno = EINVAL;
1073 return NULL;
1076 if (user[0] == (char)0) fstrcpy(user, context->user);
1078 srv = smbc_server(context, True,
1079 server, share, workgroup, user, password);
1081 if (!srv) {
1083 if (errno == EPERM) errno = EACCES;
1084 return NULL; /* smbc_server sets errno */
1088 /* Hmmm, the test for a directory is suspect here ... FIXME */
1090 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1092 fd = -1;
1095 else {
1097 file = SMB_MALLOC_P(SMBCFILE);
1099 if (!file) {
1101 errno = ENOMEM;
1102 return NULL;
1106 ZERO_STRUCTP(file);
1108 /*d_printf(">>>open: resolving %s\n", path);*/
1109 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1111 d_printf("Could not resolve %s\n", path);
1112 SAFE_FREE(file);
1113 return NULL;
1115 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1117 if ( targetcli->dfsroot )
1119 pstring temppath;
1120 pstrcpy(temppath, targetpath);
1121 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1124 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1126 /* Handle the error ... */
1128 SAFE_FREE(file);
1129 errno = smbc_errno(context, targetcli);
1130 return NULL;
1134 /* Fill in file struct */
1136 file->cli_fd = fd;
1137 file->fname = SMB_STRDUP(fname);
1138 file->srv = srv;
1139 file->offset = 0;
1140 file->file = True;
1142 DLIST_ADD(context->internal->_files, file);
1145 * If the file was opened in O_APPEND mode, all write
1146 * operations should be appended to the file. To do that,
1147 * though, using this protocol, would require a getattrE()
1148 * call for each and every write, to determine where the end
1149 * of the file is. (There does not appear to be an append flag
1150 * in the protocol.) Rather than add all of that overhead of
1151 * retrieving the current end-of-file offset prior to each
1152 * write operation, we'll assume that most append operations
1153 * will continuously write, so we'll just set the offset to
1154 * the end of the file now and hope that's adequate.
1156 * Note to self: If this proves inadequate, and O_APPEND
1157 * should, in some cases, be forced for each write, add a
1158 * field in the context options structure, for
1159 * "strict_append_mode" which would select between the current
1160 * behavior (if FALSE) or issuing a getattrE() prior to each
1161 * write and forcing the write to the end of the file (if
1162 * TRUE). Adding that capability will likely require adding
1163 * an "append" flag into the _SMBCFILE structure to track
1164 * whether a file was opened in O_APPEND mode. -- djl
1166 if (flags & O_APPEND) {
1167 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1168 (void) smbc_close_ctx(context, file);
1169 errno = ENXIO;
1170 return NULL;
1174 return file;
1178 /* Check if opendir needed ... */
1180 if (fd == -1) {
1181 int eno = 0;
1183 eno = smbc_errno(context, &srv->cli);
1184 file = context->opendir(context, fname);
1185 if (!file) errno = eno;
1186 return file;
1190 errno = EINVAL; /* FIXME, correct errno ? */
1191 return NULL;
1196 * Routine to create a file
1199 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1201 static SMBCFILE *
1202 smbc_creat_ctx(SMBCCTX *context,
1203 const char *path,
1204 mode_t mode)
1207 if (!context || !context->internal ||
1208 !context->internal->_initialized) {
1210 errno = EINVAL;
1211 return NULL;
1215 return smbc_open_ctx(context, path, creat_bits, mode);
1219 * Routine to read() a file ...
1222 static ssize_t
1223 smbc_read_ctx(SMBCCTX *context,
1224 SMBCFILE *file,
1225 void *buf,
1226 size_t count)
1228 int ret;
1229 fstring server, share, user, password;
1230 pstring path, targetpath;
1231 struct cli_state *targetcli;
1234 * offset:
1236 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1237 * appears to pass file->offset (which is type off_t) differently than
1238 * a local variable of type off_t. Using local variable "offset" in
1239 * the call to cli_read() instead of file->offset fixes a problem
1240 * retrieving data at an offset greater than 4GB.
1242 off_t offset;
1244 if (!context || !context->internal ||
1245 !context->internal->_initialized) {
1247 errno = EINVAL;
1248 return -1;
1252 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1254 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1256 errno = EBADF;
1257 return -1;
1261 offset = file->offset;
1263 /* Check that the buffer exists ... */
1265 if (buf == NULL) {
1267 errno = EINVAL;
1268 return -1;
1272 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1273 if (smbc_parse_path(context, file->fname,
1274 NULL, 0,
1275 server, sizeof(server),
1276 share, sizeof(share),
1277 path, sizeof(path),
1278 user, sizeof(user),
1279 password, sizeof(password),
1280 NULL, 0)) {
1281 errno = EINVAL;
1282 return -1;
1285 /*d_printf(">>>read: resolving %s\n", path);*/
1286 if (!cli_resolve_path("", &file->srv->cli, path,
1287 &targetcli, targetpath))
1289 d_printf("Could not resolve %s\n", path);
1290 return -1;
1292 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1294 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1296 if (ret < 0) {
1298 errno = smbc_errno(context, targetcli);
1299 return -1;
1303 file->offset += ret;
1305 DEBUG(4, (" --> %d\n", ret));
1307 return ret; /* Success, ret bytes of data ... */
1312 * Routine to write() a file ...
1315 static ssize_t
1316 smbc_write_ctx(SMBCCTX *context,
1317 SMBCFILE *file,
1318 void *buf,
1319 size_t count)
1321 int ret;
1322 off_t offset;
1323 fstring server, share, user, password;
1324 pstring path, targetpath;
1325 struct cli_state *targetcli;
1327 /* First check all pointers before dereferencing them */
1329 if (!context || !context->internal ||
1330 !context->internal->_initialized) {
1332 errno = EINVAL;
1333 return -1;
1337 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1339 errno = EBADF;
1340 return -1;
1344 /* Check that the buffer exists ... */
1346 if (buf == NULL) {
1348 errno = EINVAL;
1349 return -1;
1353 offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1355 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1356 if (smbc_parse_path(context, file->fname,
1357 NULL, 0,
1358 server, sizeof(server),
1359 share, sizeof(share),
1360 path, sizeof(path),
1361 user, sizeof(user),
1362 password, sizeof(password),
1363 NULL, 0)) {
1364 errno = EINVAL;
1365 return -1;
1368 /*d_printf(">>>write: resolving %s\n", path);*/
1369 if (!cli_resolve_path("", &file->srv->cli, path,
1370 &targetcli, targetpath))
1372 d_printf("Could not resolve %s\n", path);
1373 return -1;
1375 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1378 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1380 if (ret <= 0) {
1382 errno = smbc_errno(context, targetcli);
1383 return -1;
1387 file->offset += ret;
1389 return ret; /* Success, 0 bytes of data ... */
1393 * Routine to close() a file ...
1396 static int
1397 smbc_close_ctx(SMBCCTX *context,
1398 SMBCFILE *file)
1400 SMBCSRV *srv;
1401 fstring server, share, user, password;
1402 pstring path, targetpath;
1403 struct cli_state *targetcli;
1405 if (!context || !context->internal ||
1406 !context->internal->_initialized) {
1408 errno = EINVAL;
1409 return -1;
1413 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1415 errno = EBADF;
1416 return -1;
1420 /* IS a dir ... */
1421 if (!file->file) {
1423 return context->closedir(context, file);
1427 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1428 if (smbc_parse_path(context, file->fname,
1429 NULL, 0,
1430 server, sizeof(server),
1431 share, sizeof(share),
1432 path, sizeof(path),
1433 user, sizeof(user),
1434 password, sizeof(password),
1435 NULL, 0)) {
1436 errno = EINVAL;
1437 return -1;
1440 /*d_printf(">>>close: resolving %s\n", path);*/
1441 if (!cli_resolve_path("", &file->srv->cli, path,
1442 &targetcli, targetpath))
1444 d_printf("Could not resolve %s\n", path);
1445 return -1;
1447 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1449 if (!cli_close(targetcli, file->cli_fd)) {
1451 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1452 file->fname));
1453 /* Deallocate slot and remove the server
1454 * from the server cache if unused */
1455 errno = smbc_errno(context, targetcli);
1456 srv = file->srv;
1457 DLIST_REMOVE(context->internal->_files, file);
1458 SAFE_FREE(file->fname);
1459 SAFE_FREE(file);
1460 context->callbacks.remove_unused_server_fn(context, srv);
1462 return -1;
1466 DLIST_REMOVE(context->internal->_files, file);
1467 SAFE_FREE(file->fname);
1468 SAFE_FREE(file);
1470 return 0;
1474 * Get info from an SMB server on a file. Use a qpathinfo call first
1475 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1477 static BOOL
1478 smbc_getatr(SMBCCTX * context,
1479 SMBCSRV *srv,
1480 char *path,
1481 uint16 *mode,
1482 SMB_OFF_T *size,
1483 time_t *c_time,
1484 time_t *a_time,
1485 time_t *m_time,
1486 SMB_INO_T *ino)
1488 pstring fixedpath;
1489 pstring targetpath;
1490 struct cli_state *targetcli;
1492 if (!context || !context->internal ||
1493 !context->internal->_initialized) {
1495 errno = EINVAL;
1496 return -1;
1500 /* path fixup for . and .. */
1501 if (strequal(path, ".") || strequal(path, ".."))
1502 pstrcpy(fixedpath, "\\");
1503 else
1505 pstrcpy(fixedpath, path);
1506 trim_string(fixedpath, NULL, "\\..");
1507 trim_string(fixedpath, NULL, "\\.");
1509 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1511 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1513 d_printf("Couldn't resolve %s\n", path);
1514 return False;
1517 if ( targetcli->dfsroot )
1519 pstring temppath;
1520 pstrcpy(temppath, targetpath);
1521 cli_dfs_make_full_path(targetpath, targetcli->desthost,
1522 targetcli->share, temppath);
1525 if (!srv->no_pathinfo2 &&
1526 cli_qpathinfo2(targetcli, targetpath,
1527 NULL, a_time, m_time, c_time, size, mode, ino)) {
1528 return True;
1531 /* if this is NT then don't bother with the getatr */
1532 if (targetcli->capabilities & CAP_NT_SMBS) {
1533 errno = EPERM;
1534 return False;
1537 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1538 if (m_time != NULL) {
1539 if (a_time != NULL) *a_time = *m_time;
1540 if (c_time != NULL) *c_time = *m_time;
1542 srv->no_pathinfo2 = True;
1543 return True;
1546 errno = EPERM;
1547 return False;
1552 * Set file info on an SMB server. Use setpathinfo call first. If that
1553 * fails, use setattrE..
1555 * Access and modification time parameters are always used and must be
1556 * provided. Create time, if zero, will be determined from the actual create
1557 * time of the file. If non-zero, the create time will be set as well.
1559 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1561 static BOOL
1562 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1563 time_t c_time, time_t a_time, time_t m_time,
1564 uint16 mode)
1566 int fd;
1567 int ret;
1570 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1571 * modern function for "new code" to be using, and it works given a
1572 * filename rather than requiring that the file be opened to have its
1573 * attributes manipulated.
1575 if (srv->no_pathinfo ||
1576 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1579 * setpathinfo is not supported; go to plan B.
1581 * cli_setatr() does not work on win98, and it also doesn't
1582 * support setting the access time (only the modification
1583 * time), so in all cases, we open the specified file and use
1584 * cli_setattrE() which should work on all OS versions, and
1585 * supports both times.
1588 /* Don't try {q,set}pathinfo() again, with this server */
1589 srv->no_pathinfo = True;
1591 /* Open the file */
1592 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1594 errno = smbc_errno(context, &srv->cli);
1595 return -1;
1599 * Get the creat time of the file (if it wasn't provided).
1600 * We'll need it in the set call
1602 if (c_time == 0) {
1603 ret = cli_getattrE(&srv->cli, fd,
1604 NULL, NULL,
1605 &c_time, NULL, NULL);
1606 } else {
1607 ret = True;
1610 /* If we got create time, set times */
1611 if (ret) {
1612 /* Some OS versions don't support create time */
1613 if (c_time == 0 || c_time == -1) {
1614 c_time = time(NULL);
1618 * For sanity sake, since there is no POSIX function
1619 * to set the create time of a file, if the existing
1620 * create time is greater than either of access time
1621 * or modification time, set create time to the
1622 * smallest of those. This ensure that the create
1623 * time of a file is never greater than its last
1624 * access or modification time.
1626 if (c_time > a_time) c_time = a_time;
1627 if (c_time > m_time) c_time = m_time;
1629 /* Set the new attributes */
1630 ret = cli_setattrE(&srv->cli, fd,
1631 c_time, a_time, m_time);
1632 cli_close(&srv->cli, fd);
1636 * Unfortunately, setattrE() doesn't have a provision for
1637 * setting the access mode (attributes). We'll have to try
1638 * cli_setatr() for that, and with only this parameter, it
1639 * seems to work on win98.
1641 if (ret && mode != (uint16) -1) {
1642 ret = cli_setatr(&srv->cli, path, mode, 0);
1645 if (! ret) {
1646 errno = smbc_errno(context, &srv->cli);
1647 return False;
1651 return True;
1655 * Routine to unlink() a file
1658 static int
1659 smbc_unlink_ctx(SMBCCTX *context,
1660 const char *fname)
1662 fstring server, share, user, password, workgroup;
1663 pstring path, targetpath;
1664 struct cli_state *targetcli;
1665 SMBCSRV *srv = NULL;
1667 if (!context || !context->internal ||
1668 !context->internal->_initialized) {
1670 errno = EINVAL; /* Best I can think of ... */
1671 return -1;
1675 if (!fname) {
1677 errno = EINVAL;
1678 return -1;
1682 if (smbc_parse_path(context, fname,
1683 workgroup, sizeof(workgroup),
1684 server, sizeof(server),
1685 share, sizeof(share),
1686 path, sizeof(path),
1687 user, sizeof(user),
1688 password, sizeof(password),
1689 NULL, 0)) {
1690 errno = EINVAL;
1691 return -1;
1694 if (user[0] == (char)0) fstrcpy(user, context->user);
1696 srv = smbc_server(context, True,
1697 server, share, workgroup, user, password);
1699 if (!srv) {
1701 return -1; /* smbc_server sets errno */
1705 /*d_printf(">>>unlink: resolving %s\n", path);*/
1706 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1708 d_printf("Could not resolve %s\n", path);
1709 return -1;
1711 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1713 if (!cli_unlink(targetcli, targetpath)) {
1715 errno = smbc_errno(context, targetcli);
1717 if (errno == EACCES) { /* Check if the file is a directory */
1719 int saverr = errno;
1720 SMB_OFF_T size = 0;
1721 uint16 mode = 0;
1722 time_t m_time = 0, a_time = 0, c_time = 0;
1723 SMB_INO_T ino = 0;
1725 if (!smbc_getatr(context, srv, path, &mode, &size,
1726 &c_time, &a_time, &m_time, &ino)) {
1728 /* Hmmm, bad error ... What? */
1730 errno = smbc_errno(context, targetcli);
1731 return -1;
1734 else {
1736 if (IS_DOS_DIR(mode))
1737 errno = EISDIR;
1738 else
1739 errno = saverr; /* Restore this */
1744 return -1;
1748 return 0; /* Success ... */
1753 * Routine to rename() a file
1756 static int
1757 smbc_rename_ctx(SMBCCTX *ocontext,
1758 const char *oname,
1759 SMBCCTX *ncontext,
1760 const char *nname)
1762 fstring server1;
1763 fstring share1;
1764 fstring server2;
1765 fstring share2;
1766 fstring user1;
1767 fstring user2;
1768 fstring password1;
1769 fstring password2;
1770 fstring workgroup;
1771 pstring path1;
1772 pstring path2;
1773 pstring targetpath1;
1774 pstring targetpath2;
1775 struct cli_state *targetcli1;
1776 struct cli_state *targetcli2;
1777 SMBCSRV *srv = NULL;
1779 if (!ocontext || !ncontext ||
1780 !ocontext->internal || !ncontext->internal ||
1781 !ocontext->internal->_initialized ||
1782 !ncontext->internal->_initialized) {
1784 errno = EINVAL; /* Best I can think of ... */
1785 return -1;
1789 if (!oname || !nname) {
1791 errno = EINVAL;
1792 return -1;
1796 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1798 smbc_parse_path(ocontext, oname,
1799 workgroup, sizeof(workgroup),
1800 server1, sizeof(server1),
1801 share1, sizeof(share1),
1802 path1, sizeof(path1),
1803 user1, sizeof(user1),
1804 password1, sizeof(password1),
1805 NULL, 0);
1807 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1809 smbc_parse_path(ncontext, nname,
1810 NULL, 0,
1811 server2, sizeof(server2),
1812 share2, sizeof(share2),
1813 path2, sizeof(path2),
1814 user2, sizeof(user2),
1815 password2, sizeof(password2),
1816 NULL, 0);
1818 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1820 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1821 strcmp(user1, user2)) {
1823 /* Can't rename across file systems, or users?? */
1825 errno = EXDEV;
1826 return -1;
1830 srv = smbc_server(ocontext, True,
1831 server1, share1, workgroup, user1, password1);
1832 if (!srv) {
1834 return -1;
1838 /*d_printf(">>>rename: resolving %s\n", path1);*/
1839 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1841 d_printf("Could not resolve %s\n", path1);
1842 return -1;
1844 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1845 /*d_printf(">>>rename: resolving %s\n", path2);*/
1846 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1848 d_printf("Could not resolve %s\n", path2);
1849 return -1;
1851 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1853 if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1854 strcmp(targetcli1->share, targetcli2->share))
1856 /* can't rename across file systems */
1858 errno = EXDEV;
1859 return -1;
1862 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1863 int eno = smbc_errno(ocontext, targetcli1);
1865 if (eno != EEXIST ||
1866 !cli_unlink(targetcli1, targetpath2) ||
1867 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1869 errno = eno;
1870 return -1;
1875 return 0; /* Success */
1880 * A routine to lseek() a file
1883 static off_t
1884 smbc_lseek_ctx(SMBCCTX *context,
1885 SMBCFILE *file,
1886 off_t offset,
1887 int whence)
1889 SMB_OFF_T size;
1890 fstring server, share, user, password;
1891 pstring path, targetpath;
1892 struct cli_state *targetcli;
1894 if (!context || !context->internal ||
1895 !context->internal->_initialized) {
1897 errno = EINVAL;
1898 return -1;
1902 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1904 errno = EBADF;
1905 return -1;
1909 if (!file->file) {
1911 errno = EINVAL;
1912 return -1; /* Can't lseek a dir ... */
1916 switch (whence) {
1917 case SEEK_SET:
1918 file->offset = offset;
1919 break;
1921 case SEEK_CUR:
1922 file->offset += offset;
1923 break;
1925 case SEEK_END:
1926 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1927 if (smbc_parse_path(context, file->fname,
1928 NULL, 0,
1929 server, sizeof(server),
1930 share, sizeof(share),
1931 path, sizeof(path),
1932 user, sizeof(user),
1933 password, sizeof(password),
1934 NULL, 0)) {
1936 errno = EINVAL;
1937 return -1;
1940 /*d_printf(">>>lseek: resolving %s\n", path);*/
1941 if (!cli_resolve_path("", &file->srv->cli, path,
1942 &targetcli, targetpath))
1944 d_printf("Could not resolve %s\n", path);
1945 return -1;
1947 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1949 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1950 &size, NULL, NULL, NULL, NULL, NULL))
1952 SMB_OFF_T b_size = size;
1953 if (!cli_getattrE(targetcli, file->cli_fd,
1954 NULL, &b_size, NULL, NULL, NULL))
1956 errno = EINVAL;
1957 return -1;
1958 } else
1959 size = b_size;
1961 file->offset = size + offset;
1962 break;
1964 default:
1965 errno = EINVAL;
1966 break;
1970 return file->offset;
1975 * Generate an inode number from file name for those things that need it
1978 static ino_t
1979 smbc_inode(SMBCCTX *context,
1980 const char *name)
1983 if (!context || !context->internal ||
1984 !context->internal->_initialized) {
1986 errno = EINVAL;
1987 return -1;
1991 if (!*name) return 2; /* FIXME, why 2 ??? */
1992 return (ino_t)str_checksum(name);
1997 * Routine to put basic stat info into a stat structure ... Used by stat and
1998 * fstat below.
2001 static int
2002 smbc_setup_stat(SMBCCTX *context,
2003 struct stat *st,
2004 char *fname,
2005 SMB_OFF_T size,
2006 int mode)
2009 st->st_mode = 0;
2011 if (IS_DOS_DIR(mode)) {
2012 st->st_mode = SMBC_DIR_MODE;
2013 } else {
2014 st->st_mode = SMBC_FILE_MODE;
2017 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
2018 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
2019 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
2020 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
2022 st->st_size = size;
2023 #ifdef HAVE_STAT_ST_BLKSIZE
2024 st->st_blksize = 512;
2025 #endif
2026 #ifdef HAVE_STAT_ST_BLOCKS
2027 st->st_blocks = (size+511)/512;
2028 #endif
2029 st->st_uid = getuid();
2030 st->st_gid = getgid();
2032 if (IS_DOS_DIR(mode)) {
2033 st->st_nlink = 2;
2034 } else {
2035 st->st_nlink = 1;
2038 if (st->st_ino == 0) {
2039 st->st_ino = smbc_inode(context, fname);
2042 return True; /* FIXME: Is this needed ? */
2047 * Routine to stat a file given a name
2050 static int
2051 smbc_stat_ctx(SMBCCTX *context,
2052 const char *fname,
2053 struct stat *st)
2055 SMBCSRV *srv;
2056 fstring server;
2057 fstring share;
2058 fstring user;
2059 fstring password;
2060 fstring workgroup;
2061 pstring path;
2062 time_t m_time = 0;
2063 time_t a_time = 0;
2064 time_t c_time = 0;
2065 SMB_OFF_T size = 0;
2066 uint16 mode = 0;
2067 SMB_INO_T ino = 0;
2069 if (!context || !context->internal ||
2070 !context->internal->_initialized) {
2072 errno = EINVAL; /* Best I can think of ... */
2073 return -1;
2077 if (!fname) {
2079 errno = EINVAL;
2080 return -1;
2084 DEBUG(4, ("smbc_stat(%s)\n", fname));
2086 if (smbc_parse_path(context, fname,
2087 workgroup, sizeof(workgroup),
2088 server, sizeof(server),
2089 share, sizeof(share),
2090 path, sizeof(path),
2091 user, sizeof(user),
2092 password, sizeof(password),
2093 NULL, 0)) {
2094 errno = EINVAL;
2095 return -1;
2098 if (user[0] == (char)0) fstrcpy(user, context->user);
2100 srv = smbc_server(context, True,
2101 server, share, workgroup, user, password);
2103 if (!srv) {
2104 return -1; /* errno set by smbc_server */
2107 if (!smbc_getatr(context, srv, path, &mode, &size,
2108 &c_time, &a_time, &m_time, &ino)) {
2110 errno = smbc_errno(context, &srv->cli);
2111 return -1;
2115 st->st_ino = ino;
2117 smbc_setup_stat(context, st, path, size, mode);
2119 st->st_atime = a_time;
2120 st->st_ctime = c_time;
2121 st->st_mtime = m_time;
2122 st->st_dev = srv->dev;
2124 return 0;
2129 * Routine to stat a file given an fd
2132 static int
2133 smbc_fstat_ctx(SMBCCTX *context,
2134 SMBCFILE *file,
2135 struct stat *st)
2137 time_t c_time;
2138 time_t a_time;
2139 time_t m_time;
2140 SMB_OFF_T size;
2141 uint16 mode;
2142 fstring server;
2143 fstring share;
2144 fstring user;
2145 fstring password;
2146 pstring path;
2147 pstring targetpath;
2148 struct cli_state *targetcli;
2149 SMB_INO_T ino = 0;
2151 if (!context || !context->internal ||
2152 !context->internal->_initialized) {
2154 errno = EINVAL;
2155 return -1;
2159 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2161 errno = EBADF;
2162 return -1;
2166 if (!file->file) {
2168 return context->fstatdir(context, file, st);
2172 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2173 if (smbc_parse_path(context, file->fname,
2174 NULL, 0,
2175 server, sizeof(server),
2176 share, sizeof(share),
2177 path, sizeof(path),
2178 user, sizeof(user),
2179 password, sizeof(password),
2180 NULL, 0)) {
2181 errno = EINVAL;
2182 return -1;
2185 /*d_printf(">>>fstat: resolving %s\n", path);*/
2186 if (!cli_resolve_path("", &file->srv->cli, path,
2187 &targetcli, targetpath))
2189 d_printf("Could not resolve %s\n", path);
2190 return -1;
2192 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2194 if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2195 NULL, &a_time, &m_time, &c_time, &ino)) {
2196 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2197 &c_time, &a_time, &m_time)) {
2199 errno = EINVAL;
2200 return -1;
2204 st->st_ino = ino;
2206 smbc_setup_stat(context, st, file->fname, size, mode);
2208 st->st_atime = a_time;
2209 st->st_ctime = c_time;
2210 st->st_mtime = m_time;
2211 st->st_dev = file->srv->dev;
2213 return 0;
2218 * Routine to open a directory
2219 * We accept the URL syntax explained in smbc_parse_path(), above.
2222 static void
2223 smbc_remove_dir(SMBCFILE *dir)
2225 struct smbc_dir_list *d,*f;
2227 d = dir->dir_list;
2228 while (d) {
2230 f = d; d = d->next;
2232 SAFE_FREE(f->dirent);
2233 SAFE_FREE(f);
2237 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2241 static int
2242 add_dirent(SMBCFILE *dir,
2243 const char *name,
2244 const char *comment,
2245 uint32 type)
2247 struct smbc_dirent *dirent;
2248 int size;
2249 int name_length = (name == NULL ? 0 : strlen(name));
2250 int comment_len = (comment == NULL ? 0 : strlen(comment));
2253 * Allocate space for the dirent, which must be increased by the
2254 * size of the name and the comment and 1 each for the null terminator.
2257 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2259 dirent = SMB_MALLOC(size);
2261 if (!dirent) {
2263 dir->dir_error = ENOMEM;
2264 return -1;
2268 ZERO_STRUCTP(dirent);
2270 if (dir->dir_list == NULL) {
2272 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2273 if (!dir->dir_list) {
2275 SAFE_FREE(dirent);
2276 dir->dir_error = ENOMEM;
2277 return -1;
2280 ZERO_STRUCTP(dir->dir_list);
2282 dir->dir_end = dir->dir_next = dir->dir_list;
2284 else {
2286 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2288 if (!dir->dir_end->next) {
2290 SAFE_FREE(dirent);
2291 dir->dir_error = ENOMEM;
2292 return -1;
2295 ZERO_STRUCTP(dir->dir_end->next);
2297 dir->dir_end = dir->dir_end->next;
2300 dir->dir_end->next = NULL;
2301 dir->dir_end->dirent = dirent;
2303 dirent->smbc_type = type;
2304 dirent->namelen = name_length;
2305 dirent->commentlen = comment_len;
2306 dirent->dirlen = size;
2309 * dirent->namelen + 1 includes the null (no null termination needed)
2310 * Ditto for dirent->commentlen.
2311 * The space for the two null bytes was allocated.
2313 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2314 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2315 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2317 return 0;
2321 static void
2322 list_unique_wg_fn(const char *name,
2323 uint32 type,
2324 const char *comment,
2325 void *state)
2327 SMBCFILE *dir = (SMBCFILE *)state;
2328 struct smbc_dir_list *dir_list;
2329 struct smbc_dirent *dirent;
2330 int dirent_type;
2331 int do_remove = 0;
2333 dirent_type = dir->dir_type;
2335 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2337 /* An error occurred, what do we do? */
2338 /* FIXME: Add some code here */
2341 /* Point to the one just added */
2342 dirent = dir->dir_end->dirent;
2344 /* See if this was a duplicate */
2345 for (dir_list = dir->dir_list;
2346 dir_list != dir->dir_end;
2347 dir_list = dir_list->next) {
2348 if (! do_remove &&
2349 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2350 /* Duplicate. End end of list need to be removed. */
2351 do_remove = 1;
2354 if (do_remove && dir_list->next == dir->dir_end) {
2355 /* Found the end of the list. Remove it. */
2356 dir->dir_end = dir_list;
2357 free(dir_list->next);
2358 free(dirent);
2359 dir_list->next = NULL;
2360 break;
2365 static void
2366 list_fn(const char *name,
2367 uint32 type,
2368 const char *comment,
2369 void *state)
2371 SMBCFILE *dir = (SMBCFILE *)state;
2372 int dirent_type;
2375 * We need to process the type a little ...
2377 * Disk share = 0x00000000
2378 * Print share = 0x00000001
2379 * Comms share = 0x00000002 (obsolete?)
2380 * IPC$ share = 0x00000003
2382 * administrative shares:
2383 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2386 if (dir->dir_type == SMBC_FILE_SHARE) {
2388 switch (type) {
2389 case 0 | 0x80000000:
2390 case 0:
2391 dirent_type = SMBC_FILE_SHARE;
2392 break;
2394 case 1:
2395 dirent_type = SMBC_PRINTER_SHARE;
2396 break;
2398 case 2:
2399 dirent_type = SMBC_COMMS_SHARE;
2400 break;
2402 case 3 | 0x80000000:
2403 case 3:
2404 dirent_type = SMBC_IPC_SHARE;
2405 break;
2407 default:
2408 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2409 break;
2412 else {
2413 dirent_type = dir->dir_type;
2416 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2418 /* An error occurred, what do we do? */
2419 /* FIXME: Add some code here */
2424 static void
2425 dir_list_fn(const char *mnt,
2426 file_info *finfo,
2427 const char *mask,
2428 void *state)
2431 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2432 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2434 /* Handle an error ... */
2436 /* FIXME: Add some code ... */
2442 static int
2443 net_share_enum_rpc(struct cli_state *cli,
2444 void (*fn)(const char *name,
2445 uint32 type,
2446 const char *comment,
2447 void *state),
2448 void *state)
2450 int i;
2451 WERROR result;
2452 ENUM_HND enum_hnd;
2453 uint32 info_level = 1;
2454 uint32 preferred_len = 0xffffffff;
2455 uint32 type;
2456 SRV_SHARE_INFO_CTR ctr;
2457 fstring name = "";
2458 fstring comment = "";
2459 void *mem_ctx;
2460 struct rpc_pipe_client *pipe_hnd;
2461 NTSTATUS nt_status;
2463 /* Open the server service pipe */
2464 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2465 if (!pipe_hnd) {
2466 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2467 return -1;
2470 /* Allocate a context for parsing and for the entries in "ctr" */
2471 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2472 if (mem_ctx == NULL) {
2473 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2474 cli_rpc_pipe_close(pipe_hnd);
2475 return -1;
2478 /* Issue the NetShareEnum RPC call and retrieve the response */
2479 init_enum_hnd(&enum_hnd, 0);
2480 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2481 mem_ctx,
2482 info_level,
2483 &ctr,
2484 preferred_len,
2485 &enum_hnd);
2487 /* Was it successful? */
2488 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2489 /* Nope. Go clean up. */
2490 goto done;
2493 /* For each returned entry... */
2494 for (i = 0; i < ctr.num_entries; i++) {
2496 /* pull out the share name */
2497 rpcstr_pull_unistr2_fstring(
2498 name, &ctr.share.info1[i].info_1_str.uni_netname);
2500 /* pull out the share's comment */
2501 rpcstr_pull_unistr2_fstring(
2502 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2504 /* Get the type value */
2505 type = ctr.share.info1[i].info_1.type;
2507 /* Add this share to the list */
2508 (*fn)(name, type, comment, state);
2511 done:
2512 /* Close the server service pipe */
2513 cli_rpc_pipe_close(pipe_hnd);
2515 /* Free all memory which was allocated for this request */
2516 TALLOC_FREE(mem_ctx);
2518 /* Tell 'em if it worked */
2519 return W_ERROR_IS_OK(result) ? 0 : -1;
2524 static SMBCFILE *
2525 smbc_opendir_ctx(SMBCCTX *context,
2526 const char *fname)
2528 fstring server, share, user, password, options;
2529 pstring workgroup;
2530 pstring path;
2531 uint16 mode;
2532 char *p;
2533 SMBCSRV *srv = NULL;
2534 SMBCFILE *dir = NULL;
2535 struct in_addr rem_ip;
2537 if (!context || !context->internal ||
2538 !context->internal->_initialized) {
2539 DEBUG(4, ("no valid context\n"));
2540 errno = EINVAL + 8192;
2541 return NULL;
2545 if (!fname) {
2546 DEBUG(4, ("no valid fname\n"));
2547 errno = EINVAL + 8193;
2548 return NULL;
2551 if (smbc_parse_path(context, fname,
2552 workgroup, sizeof(workgroup),
2553 server, sizeof(server),
2554 share, sizeof(share),
2555 path, sizeof(path),
2556 user, sizeof(user),
2557 password, sizeof(password),
2558 options, sizeof(options))) {
2559 DEBUG(4, ("no valid path\n"));
2560 errno = EINVAL + 8194;
2561 return NULL;
2564 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2565 "path='%s' options='%s'\n",
2566 fname, server, share, path, options));
2568 /* Ensure the options are valid */
2569 if (smbc_check_options(server, share, path, options)) {
2570 DEBUG(4, ("unacceptable options (%s)\n", options));
2571 errno = EINVAL + 8195;
2572 return NULL;
2575 if (user[0] == (char)0) fstrcpy(user, context->user);
2577 dir = SMB_MALLOC_P(SMBCFILE);
2579 if (!dir) {
2581 errno = ENOMEM;
2582 return NULL;
2586 ZERO_STRUCTP(dir);
2588 dir->cli_fd = 0;
2589 dir->fname = SMB_STRDUP(fname);
2590 dir->srv = NULL;
2591 dir->offset = 0;
2592 dir->file = False;
2593 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2595 if (server[0] == (char)0) {
2597 int i;
2598 int count;
2599 int max_lmb_count;
2600 struct ip_service *ip_list;
2601 struct ip_service server_addr;
2602 struct user_auth_info u_info;
2603 struct cli_state *cli;
2605 if (share[0] != (char)0 || path[0] != (char)0) {
2607 errno = EINVAL + 8196;
2608 if (dir) {
2609 SAFE_FREE(dir->fname);
2610 SAFE_FREE(dir);
2612 return NULL;
2615 /* Determine how many local master browsers to query */
2616 max_lmb_count = (context->options.browse_max_lmb_count == 0
2617 ? INT_MAX
2618 : context->options.browse_max_lmb_count);
2620 pstrcpy(u_info.username, user);
2621 pstrcpy(u_info.password, password);
2624 * We have server and share and path empty but options
2625 * requesting that we scan all master browsers for their list
2626 * of workgroups/domains. This implies that we must first try
2627 * broadcast queries to find all master browsers, and if that
2628 * doesn't work, then try our other methods which return only
2629 * a single master browser.
2632 ip_list = NULL;
2633 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2635 SAFE_FREE(ip_list);
2637 if (!find_master_ip(workgroup, &server_addr.ip)) {
2639 if (dir) {
2640 SAFE_FREE(dir->fname);
2641 SAFE_FREE(dir);
2643 errno = ENOENT;
2644 return NULL;
2647 ip_list = &server_addr;
2648 count = 1;
2651 for (i = 0; i < count && i < max_lmb_count; i++) {
2652 DEBUG(99, ("Found master browser %d of %d: %s\n",
2653 i+1, MAX(count, max_lmb_count),
2654 inet_ntoa(ip_list[i].ip)));
2656 cli = get_ipc_connect_master_ip(&ip_list[i],
2657 workgroup, &u_info);
2658 /* cli == NULL is the master browser refused to talk or
2659 could not be found */
2660 if ( !cli )
2661 continue;
2663 fstrcpy(server, cli->desthost);
2664 cli_shutdown(cli);
2666 DEBUG(4, ("using workgroup %s %s\n",
2667 workgroup, server));
2670 * For each returned master browser IP address, get a
2671 * connection to IPC$ on the server if we do not
2672 * already have one, and determine the
2673 * workgroups/domains that it knows about.
2676 srv = smbc_server(context, True, server, "IPC$",
2677 workgroup, user, password);
2678 if (!srv) {
2679 continue;
2682 dir->srv = srv;
2683 dir->dir_type = SMBC_WORKGROUP;
2685 /* Now, list the stuff ... */
2687 if (!cli_NetServerEnum(&srv->cli,
2688 workgroup,
2689 SV_TYPE_DOMAIN_ENUM,
2690 list_unique_wg_fn,
2691 (void *)dir)) {
2692 continue;
2696 SAFE_FREE(ip_list);
2697 } else {
2699 * Server not an empty string ... Check the rest and see what
2700 * gives
2702 if (*share == '\0') {
2703 if (*path != '\0') {
2705 /* Should not have empty share with path */
2706 errno = EINVAL + 8197;
2707 if (dir) {
2708 SAFE_FREE(dir->fname);
2709 SAFE_FREE(dir);
2711 return NULL;
2716 * We don't know if <server> is really a server name
2717 * or is a workgroup/domain name. If we already have
2718 * a server structure for it, we'll use it.
2719 * Otherwise, check to see if <server><1D>,
2720 * <server><1B>, or <server><20> translates. We check
2721 * to see if <server> is an IP address first.
2725 * See if we have an existing server. Do not
2726 * establish a connection if one does not already
2727 * exist.
2729 srv = smbc_server(context, False, server, "IPC$",
2730 workgroup, user, password);
2733 * If no existing server and not an IP addr, look for
2734 * LMB or DMB
2736 if (!srv &&
2737 !is_ipaddress(server) &&
2738 (resolve_name(server, &rem_ip, 0x1d) || /* LMB */
2739 resolve_name(server, &rem_ip, 0x1b) )) { /* DMB */
2741 fstring buserver;
2743 dir->dir_type = SMBC_SERVER;
2746 * Get the backup list ...
2748 if (!name_status_find(server, 0, 0,
2749 rem_ip, buserver)) {
2751 DEBUG(0, ("Could not get name of "
2752 "local/domain master browser "
2753 "for server %s\n", server));
2754 if (dir) {
2755 SAFE_FREE(dir->fname);
2756 SAFE_FREE(dir);
2758 errno = EPERM;
2759 return NULL;
2764 * Get a connection to IPC$ on the server if
2765 * we do not already have one
2767 srv = smbc_server(context, True,
2768 buserver, "IPC$",
2769 workgroup, user, password);
2770 if (!srv) {
2771 DEBUG(0, ("got no contact to IPC$\n"));
2772 if (dir) {
2773 SAFE_FREE(dir->fname);
2774 SAFE_FREE(dir);
2776 return NULL;
2780 dir->srv = srv;
2782 /* Now, list the servers ... */
2783 if (!cli_NetServerEnum(&srv->cli, server,
2784 0x0000FFFE, list_fn,
2785 (void *)dir)) {
2787 if (dir) {
2788 SAFE_FREE(dir->fname);
2789 SAFE_FREE(dir);
2791 return NULL;
2793 } else if (srv ||
2794 (resolve_name(server, &rem_ip, 0x20))) {
2796 /* If we hadn't found the server, get one now */
2797 if (!srv) {
2798 srv = smbc_server(context, True,
2799 server, "IPC$",
2800 workgroup,
2801 user, password);
2804 if (!srv) {
2805 if (dir) {
2806 SAFE_FREE(dir->fname);
2807 SAFE_FREE(dir);
2809 return NULL;
2813 dir->dir_type = SMBC_FILE_SHARE;
2814 dir->srv = srv;
2816 /* List the shares ... */
2818 if (net_share_enum_rpc(
2819 &srv->cli,
2820 list_fn,
2821 (void *) dir) < 0 &&
2822 cli_RNetShareEnum(
2823 &srv->cli,
2824 list_fn,
2825 (void *)dir) < 0) {
2827 errno = cli_errno(&srv->cli);
2828 if (dir) {
2829 SAFE_FREE(dir->fname);
2830 SAFE_FREE(dir);
2832 return NULL;
2835 } else {
2836 /* Neither the workgroup nor server exists */
2837 errno = ECONNREFUSED;
2838 if (dir) {
2839 SAFE_FREE(dir->fname);
2840 SAFE_FREE(dir);
2842 return NULL;
2846 else {
2848 * The server and share are specified ... work from
2849 * there ...
2851 pstring targetpath;
2852 struct cli_state *targetcli;
2854 /* We connect to the server and list the directory */
2855 dir->dir_type = SMBC_FILE_SHARE;
2857 srv = smbc_server(context, True, server, share,
2858 workgroup, user, password);
2860 if (!srv) {
2862 if (dir) {
2863 SAFE_FREE(dir->fname);
2864 SAFE_FREE(dir);
2866 return NULL;
2870 dir->srv = srv;
2872 /* Now, list the files ... */
2874 p = path + strlen(path);
2875 pstrcat(path, "\\*");
2877 if (!cli_resolve_path("", &srv->cli, path,
2878 &targetcli, targetpath))
2880 d_printf("Could not resolve %s\n", path);
2881 if (dir) {
2882 SAFE_FREE(dir->fname);
2883 SAFE_FREE(dir);
2885 return NULL;
2888 if (cli_list(targetcli, targetpath,
2889 aDIR | aSYSTEM | aHIDDEN,
2890 dir_list_fn, (void *)dir) < 0) {
2892 if (dir) {
2893 SAFE_FREE(dir->fname);
2894 SAFE_FREE(dir);
2896 errno = smbc_errno(context, targetcli);
2898 if (errno == EINVAL) {
2900 * See if they asked to opendir something
2901 * other than a directory. If so, the
2902 * converted error value we got would have
2903 * been EINVAL rather than ENOTDIR.
2905 *p = '\0'; /* restore original path */
2907 if (smbc_getatr(context, srv, path,
2908 &mode, NULL,
2909 NULL, NULL, NULL,
2910 NULL) &&
2911 ! IS_DOS_DIR(mode)) {
2913 /* It is. Correct the error value */
2914 errno = ENOTDIR;
2918 return NULL;
2925 DLIST_ADD(context->internal->_files, dir);
2926 return dir;
2931 * Routine to close a directory
2934 static int
2935 smbc_closedir_ctx(SMBCCTX *context,
2936 SMBCFILE *dir)
2939 if (!context || !context->internal ||
2940 !context->internal->_initialized) {
2942 errno = EINVAL;
2943 return -1;
2947 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2949 errno = EBADF;
2950 return -1;
2954 smbc_remove_dir(dir); /* Clean it up */
2956 DLIST_REMOVE(context->internal->_files, dir);
2958 if (dir) {
2960 SAFE_FREE(dir->fname);
2961 SAFE_FREE(dir); /* Free the space too */
2964 return 0;
2968 static void
2969 smbc_readdir_internal(SMBCCTX * context,
2970 struct smbc_dirent *dest,
2971 struct smbc_dirent *src,
2972 int max_namebuf_len)
2974 if (context->options.urlencode_readdir_entries) {
2976 /* url-encode the name. get back remaining buffer space */
2977 max_namebuf_len =
2978 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2980 /* We now know the name length */
2981 dest->namelen = strlen(dest->name);
2983 /* Save the pointer to the beginning of the comment */
2984 dest->comment = dest->name + dest->namelen + 1;
2986 /* Copy the comment */
2987 strncpy(dest->comment, src->comment, max_namebuf_len - 1);
2988 dest->comment[max_namebuf_len - 1] = '\0';
2990 /* Save other fields */
2991 dest->smbc_type = src->smbc_type;
2992 dest->commentlen = strlen(dest->comment);
2993 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2994 (char *) dest);
2995 } else {
2997 /* No encoding. Just copy the entry as is. */
2998 memcpy(dest, src, src->dirlen);
2999 dest->comment = (char *)(&dest->name + src->namelen + 1);
3005 * Routine to get a directory entry
3008 struct smbc_dirent *
3009 smbc_readdir_ctx(SMBCCTX *context,
3010 SMBCFILE *dir)
3012 int maxlen;
3013 struct smbc_dirent *dirp, *dirent;
3015 /* Check that all is ok first ... */
3017 if (!context || !context->internal ||
3018 !context->internal->_initialized) {
3020 errno = EINVAL;
3021 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
3022 return NULL;
3026 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3028 errno = EBADF;
3029 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
3030 return NULL;
3034 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3036 errno = ENOTDIR;
3037 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
3038 return NULL;
3042 if (!dir->dir_next) {
3043 return NULL;
3046 dirent = dir->dir_next->dirent;
3047 if (!dirent) {
3049 errno = ENOENT;
3050 return NULL;
3054 dirp = (struct smbc_dirent *)context->internal->_dirent;
3055 maxlen = (sizeof(context->internal->_dirent) -
3056 sizeof(struct smbc_dirent));
3058 smbc_readdir_internal(context, dirp, dirent, maxlen);
3060 dir->dir_next = dir->dir_next->next;
3062 return dirp;
3066 * Routine to get directory entries
3069 static int
3070 smbc_getdents_ctx(SMBCCTX *context,
3071 SMBCFILE *dir,
3072 struct smbc_dirent *dirp,
3073 int count)
3075 int rem = count;
3076 int reqd;
3077 int maxlen;
3078 char *ndir = (char *)dirp;
3079 struct smbc_dir_list *dirlist;
3081 /* Check that all is ok first ... */
3083 if (!context || !context->internal ||
3084 !context->internal->_initialized) {
3086 errno = EINVAL;
3087 return -1;
3091 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3093 errno = EBADF;
3094 return -1;
3098 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3100 errno = ENOTDIR;
3101 return -1;
3106 * Now, retrieve the number of entries that will fit in what was passed
3107 * We have to figure out if the info is in the list, or we need to
3108 * send a request to the server to get the info.
3111 while ((dirlist = dir->dir_next)) {
3112 struct smbc_dirent *dirent;
3114 if (!dirlist->dirent) {
3116 errno = ENOENT; /* Bad error */
3117 return -1;
3121 /* Do urlencoding of next entry, if so selected */
3122 dirent = (struct smbc_dirent *)context->internal->_dirent;
3123 maxlen = (sizeof(context->internal->_dirent) -
3124 sizeof(struct smbc_dirent));
3125 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3127 reqd = dirent->dirlen;
3129 if (rem < reqd) {
3131 if (rem < count) { /* We managed to copy something */
3133 errno = 0;
3134 return count - rem;
3137 else { /* Nothing copied ... */
3139 errno = EINVAL; /* Not enough space ... */
3140 return -1;
3146 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3148 ((struct smbc_dirent *)ndir)->comment =
3149 (char *)(&((struct smbc_dirent *)ndir)->name +
3150 dirent->namelen +
3153 ndir += reqd;
3155 rem -= reqd;
3157 dir->dir_next = dirlist = dirlist -> next;
3160 if (rem == count)
3161 return 0;
3162 else
3163 return count - rem;
3168 * Routine to create a directory ...
3171 static int
3172 smbc_mkdir_ctx(SMBCCTX *context,
3173 const char *fname,
3174 mode_t mode)
3176 SMBCSRV *srv;
3177 fstring server;
3178 fstring share;
3179 fstring user;
3180 fstring password;
3181 fstring workgroup;
3182 pstring path, targetpath;
3183 struct cli_state *targetcli;
3185 if (!context || !context->internal ||
3186 !context->internal->_initialized) {
3188 errno = EINVAL;
3189 return -1;
3193 if (!fname) {
3195 errno = EINVAL;
3196 return -1;
3200 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3202 if (smbc_parse_path(context, fname,
3203 workgroup, sizeof(workgroup),
3204 server, sizeof(server),
3205 share, sizeof(share),
3206 path, sizeof(path),
3207 user, sizeof(user),
3208 password, sizeof(password),
3209 NULL, 0)) {
3210 errno = EINVAL;
3211 return -1;
3214 if (user[0] == (char)0) fstrcpy(user, context->user);
3216 srv = smbc_server(context, True,
3217 server, share, workgroup, user, password);
3219 if (!srv) {
3221 return -1; /* errno set by smbc_server */
3225 /*d_printf(">>>mkdir: resolving %s\n", path);*/
3226 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3228 d_printf("Could not resolve %s\n", path);
3229 return -1;
3231 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3233 if (!cli_mkdir(targetcli, targetpath)) {
3235 errno = smbc_errno(context, targetcli);
3236 return -1;
3240 return 0;
3245 * Our list function simply checks to see if a directory is not empty
3248 static int smbc_rmdir_dirempty = True;
3250 static void
3251 rmdir_list_fn(const char *mnt,
3252 file_info *finfo,
3253 const char *mask,
3254 void *state)
3256 if (strncmp(finfo->name, ".", 1) != 0 &&
3257 strncmp(finfo->name, "..", 2) != 0) {
3259 smbc_rmdir_dirempty = False;
3264 * Routine to remove a directory
3267 static int
3268 smbc_rmdir_ctx(SMBCCTX *context,
3269 const char *fname)
3271 SMBCSRV *srv;
3272 fstring server;
3273 fstring share;
3274 fstring user;
3275 fstring password;
3276 fstring workgroup;
3277 pstring path;
3278 pstring targetpath;
3279 struct cli_state *targetcli;
3281 if (!context || !context->internal ||
3282 !context->internal->_initialized) {
3284 errno = EINVAL;
3285 return -1;
3289 if (!fname) {
3291 errno = EINVAL;
3292 return -1;
3296 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3298 if (smbc_parse_path(context, fname,
3299 workgroup, sizeof(workgroup),
3300 server, sizeof(server),
3301 share, sizeof(share),
3302 path, sizeof(path),
3303 user, sizeof(user),
3304 password, sizeof(password),
3305 NULL, 0))
3307 errno = EINVAL;
3308 return -1;
3311 if (user[0] == (char)0) fstrcpy(user, context->user);
3313 srv = smbc_server(context, True,
3314 server, share, workgroup, user, password);
3316 if (!srv) {
3318 return -1; /* errno set by smbc_server */
3322 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3323 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3325 d_printf("Could not resolve %s\n", path);
3326 return -1;
3328 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3331 if (!cli_rmdir(targetcli, targetpath)) {
3333 errno = smbc_errno(context, targetcli);
3335 if (errno == EACCES) { /* Check if the dir empty or not */
3337 /* Local storage to avoid buffer overflows */
3338 pstring lpath;
3340 smbc_rmdir_dirempty = True; /* Make this so ... */
3342 pstrcpy(lpath, targetpath);
3343 pstrcat(lpath, "\\*");
3345 if (cli_list(targetcli, lpath,
3346 aDIR | aSYSTEM | aHIDDEN,
3347 rmdir_list_fn, NULL) < 0) {
3349 /* Fix errno to ignore latest error ... */
3350 DEBUG(5, ("smbc_rmdir: "
3351 "cli_list returned an error: %d\n",
3352 smbc_errno(context, targetcli)));
3353 errno = EACCES;
3357 if (smbc_rmdir_dirempty)
3358 errno = EACCES;
3359 else
3360 errno = ENOTEMPTY;
3364 return -1;
3368 return 0;
3373 * Routine to return the current directory position
3376 static off_t
3377 smbc_telldir_ctx(SMBCCTX *context,
3378 SMBCFILE *dir)
3380 off_t ret_val; /* Squash warnings about cast */
3382 if (!context || !context->internal ||
3383 !context->internal->_initialized) {
3385 errno = EINVAL;
3386 return -1;
3390 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3392 errno = EBADF;
3393 return -1;
3397 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3399 errno = ENOTDIR;
3400 return -1;
3405 * We return the pointer here as the offset
3407 ret_val = (off_t)(long)dir->dir_next;
3408 return ret_val;
3413 * A routine to run down the list and see if the entry is OK
3416 struct smbc_dir_list *
3417 smbc_check_dir_ent(struct smbc_dir_list *list,
3418 struct smbc_dirent *dirent)
3421 /* Run down the list looking for what we want */
3423 if (dirent) {
3425 struct smbc_dir_list *tmp = list;
3427 while (tmp) {
3429 if (tmp->dirent == dirent)
3430 return tmp;
3432 tmp = tmp->next;
3438 return NULL; /* Not found, or an error */
3444 * Routine to seek on a directory
3447 static int
3448 smbc_lseekdir_ctx(SMBCCTX *context,
3449 SMBCFILE *dir,
3450 off_t offset)
3452 long int l_offset = offset; /* Handle problems of size */
3453 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3454 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3456 if (!context || !context->internal ||
3457 !context->internal->_initialized) {
3459 errno = EINVAL;
3460 return -1;
3464 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3466 errno = ENOTDIR;
3467 return -1;
3471 /* Now, check what we were passed and see if it is OK ... */
3473 if (dirent == NULL) { /* Seek to the begining of the list */
3475 dir->dir_next = dir->dir_list;
3476 return 0;
3480 /* Now, run down the list and make sure that the entry is OK */
3481 /* This may need to be changed if we change the format of the list */
3483 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3485 errno = EINVAL; /* Bad entry */
3486 return -1;
3490 dir->dir_next = list_ent;
3492 return 0;
3497 * Routine to fstat a dir
3500 static int
3501 smbc_fstatdir_ctx(SMBCCTX *context,
3502 SMBCFILE *dir,
3503 struct stat *st)
3506 if (!context || !context->internal ||
3507 !context->internal->_initialized) {
3509 errno = EINVAL;
3510 return -1;
3514 /* No code yet ... */
3516 return 0;
3520 static int
3521 smbc_chmod_ctx(SMBCCTX *context,
3522 const char *fname,
3523 mode_t newmode)
3525 SMBCSRV *srv;
3526 fstring server;
3527 fstring share;
3528 fstring user;
3529 fstring password;
3530 fstring workgroup;
3531 pstring path;
3532 uint16 mode;
3534 if (!context || !context->internal ||
3535 !context->internal->_initialized) {
3537 errno = EINVAL; /* Best I can think of ... */
3538 return -1;
3542 if (!fname) {
3544 errno = EINVAL;
3545 return -1;
3549 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3551 if (smbc_parse_path(context, fname,
3552 workgroup, sizeof(workgroup),
3553 server, sizeof(server),
3554 share, sizeof(share),
3555 path, sizeof(path),
3556 user, sizeof(user),
3557 password, sizeof(password),
3558 NULL, 0)) {
3559 errno = EINVAL;
3560 return -1;
3563 if (user[0] == (char)0) fstrcpy(user, context->user);
3565 srv = smbc_server(context, True,
3566 server, share, workgroup, user, password);
3568 if (!srv) {
3569 return -1; /* errno set by smbc_server */
3572 mode = 0;
3574 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3575 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3576 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3577 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3579 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3580 errno = smbc_errno(context, &srv->cli);
3581 return -1;
3584 return 0;
3587 static int
3588 smbc_utimes_ctx(SMBCCTX *context,
3589 const char *fname,
3590 struct timeval *tbuf)
3592 SMBCSRV *srv;
3593 fstring server;
3594 fstring share;
3595 fstring user;
3596 fstring password;
3597 fstring workgroup;
3598 pstring path;
3599 time_t a_time;
3600 time_t m_time;
3602 if (!context || !context->internal ||
3603 !context->internal->_initialized) {
3605 errno = EINVAL; /* Best I can think of ... */
3606 return -1;
3610 if (!fname) {
3612 errno = EINVAL;
3613 return -1;
3617 if (tbuf == NULL) {
3618 a_time = m_time = time(NULL);
3619 } else {
3620 a_time = tbuf[0].tv_sec;
3621 m_time = tbuf[1].tv_sec;
3624 if (DEBUGLVL(4))
3626 char *p;
3627 char atimebuf[32];
3628 char mtimebuf[32];
3630 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf) - 1);
3631 atimebuf[sizeof(atimebuf) - 1] = '\0';
3632 if ((p = strchr(atimebuf, '\n')) != NULL) {
3633 *p = '\0';
3636 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf) - 1);
3637 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3638 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3639 *p = '\0';
3642 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3643 fname, atimebuf, mtimebuf);
3646 if (smbc_parse_path(context, fname,
3647 workgroup, sizeof(workgroup),
3648 server, sizeof(server),
3649 share, sizeof(share),
3650 path, sizeof(path),
3651 user, sizeof(user),
3652 password, sizeof(password),
3653 NULL, 0)) {
3654 errno = EINVAL;
3655 return -1;
3658 if (user[0] == (char)0) fstrcpy(user, context->user);
3660 srv = smbc_server(context, True,
3661 server, share, workgroup, user, password);
3663 if (!srv) {
3664 return -1; /* errno set by smbc_server */
3667 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3668 return -1; /* errno set by smbc_setatr */
3671 return 0;
3675 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3676 However NT4 gives a "The information may have been modified by a
3677 computer running Windows NT 5.0" if denied ACEs do not appear before
3678 allowed ACEs. */
3680 static int
3681 ace_compare(SEC_ACE *ace1,
3682 SEC_ACE *ace2)
3684 if (sec_ace_equal(ace1, ace2))
3685 return 0;
3687 if (ace1->type != ace2->type)
3688 return ace2->type - ace1->type;
3690 if (sid_compare(&ace1->trustee, &ace2->trustee))
3691 return sid_compare(&ace1->trustee, &ace2->trustee);
3693 if (ace1->flags != ace2->flags)
3694 return ace1->flags - ace2->flags;
3696 if (ace1->info.mask != ace2->info.mask)
3697 return ace1->info.mask - ace2->info.mask;
3699 if (ace1->size != ace2->size)
3700 return ace1->size - ace2->size;
3702 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3706 static void
3707 sort_acl(SEC_ACL *the_acl)
3709 uint32 i;
3710 if (!the_acl) return;
3712 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]),
3713 QSORT_CAST ace_compare);
3715 for (i=1;i<the_acl->num_aces;) {
3716 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3717 int j;
3718 for (j=i; j<the_acl->num_aces-1; j++) {
3719 the_acl->ace[j] = the_acl->ace[j+1];
3721 the_acl->num_aces--;
3722 } else {
3723 i++;
3728 /* convert a SID to a string, either numeric or username/group */
3729 static void
3730 convert_sid_to_string(struct cli_state *ipc_cli,
3731 POLICY_HND *pol,
3732 fstring str,
3733 BOOL numeric,
3734 DOM_SID *sid)
3736 char **domains = NULL;
3737 char **names = NULL;
3738 uint32 *types = NULL;
3739 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3740 sid_to_string(str, sid);
3742 if (numeric) {
3743 return; /* no lookup desired */
3746 if (!pipe_hnd) {
3747 return;
3750 /* Ask LSA to convert the sid to a name */
3752 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3753 pol, 1, sid, &domains,
3754 &names, &types)) ||
3755 !domains || !domains[0] || !names || !names[0]) {
3756 return;
3759 /* Converted OK */
3761 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3762 domains[0], lp_winbind_separator(),
3763 names[0]);
3766 /* convert a string to a SID, either numeric or username/group */
3767 static BOOL
3768 convert_string_to_sid(struct cli_state *ipc_cli,
3769 POLICY_HND *pol,
3770 BOOL numeric,
3771 DOM_SID *sid,
3772 const char *str)
3774 uint32 *types = NULL;
3775 DOM_SID *sids = NULL;
3776 BOOL result = True;
3777 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3779 if (!pipe_hnd) {
3780 return False;
3783 if (numeric) {
3784 if (strncmp(str, "S-", 2) == 0) {
3785 return string_to_sid(sid, str);
3788 result = False;
3789 goto done;
3792 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3793 pol, 1, &str, NULL, &sids,
3794 &types))) {
3795 result = False;
3796 goto done;
3799 sid_copy(sid, &sids[0]);
3800 done:
3802 return result;
3806 /* parse an ACE in the same format as print_ace() */
3807 static BOOL
3808 parse_ace(struct cli_state *ipc_cli,
3809 POLICY_HND *pol,
3810 SEC_ACE *ace,
3811 BOOL numeric,
3812 char *str)
3814 char *p;
3815 const char *cp;
3816 fstring tok;
3817 unsigned int atype;
3818 unsigned int aflags;
3819 unsigned int amask;
3820 DOM_SID sid;
3821 SEC_ACCESS mask;
3822 const struct perm_value *v;
3823 struct perm_value {
3824 const char *perm;
3825 uint32 mask;
3828 /* These values discovered by inspection */
3829 static const struct perm_value special_values[] = {
3830 { "R", 0x00120089 },
3831 { "W", 0x00120116 },
3832 { "X", 0x001200a0 },
3833 { "D", 0x00010000 },
3834 { "P", 0x00040000 },
3835 { "O", 0x00080000 },
3836 { NULL, 0 },
3839 static const struct perm_value standard_values[] = {
3840 { "READ", 0x001200a9 },
3841 { "CHANGE", 0x001301bf },
3842 { "FULL", 0x001f01ff },
3843 { NULL, 0 },
3847 ZERO_STRUCTP(ace);
3848 p = strchr_m(str,':');
3849 if (!p) return False;
3850 *p = '\0';
3851 p++;
3852 /* Try to parse numeric form */
3854 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3855 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3856 goto done;
3859 /* Try to parse text form */
3861 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3862 return False;
3865 cp = p;
3866 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3867 return False;
3870 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3871 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3872 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3873 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3874 } else {
3875 return False;
3878 /* Only numeric form accepted for flags at present */
3880 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3881 sscanf(tok, "%i", &aflags))) {
3882 return False;
3885 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3886 return False;
3889 if (strncmp(tok, "0x", 2) == 0) {
3890 if (sscanf(tok, "%i", &amask) != 1) {
3891 return False;
3893 goto done;
3896 for (v = standard_values; v->perm; v++) {
3897 if (strcmp(tok, v->perm) == 0) {
3898 amask = v->mask;
3899 goto done;
3903 p = tok;
3905 while(*p) {
3906 BOOL found = False;
3908 for (v = special_values; v->perm; v++) {
3909 if (v->perm[0] == *p) {
3910 amask |= v->mask;
3911 found = True;
3915 if (!found) return False;
3916 p++;
3919 if (*p) {
3920 return False;
3923 done:
3924 mask.mask = amask;
3925 init_sec_ace(ace, &sid, atype, mask, aflags);
3926 return True;
3929 /* add an ACE to a list of ACEs in a SEC_ACL */
3930 static BOOL
3931 add_ace(SEC_ACL **the_acl,
3932 SEC_ACE *ace,
3933 TALLOC_CTX *ctx)
3935 SEC_ACL *newacl;
3936 SEC_ACE *aces;
3938 if (! *the_acl) {
3939 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3940 return True;
3943 if ((aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces)) == NULL) {
3944 return False;
3946 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3947 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3948 newacl = make_sec_acl(ctx, (*the_acl)->revision,
3949 1+(*the_acl)->num_aces, aces);
3950 SAFE_FREE(aces);
3951 (*the_acl) = newacl;
3952 return True;
3956 /* parse a ascii version of a security descriptor */
3957 static SEC_DESC *
3958 sec_desc_parse(TALLOC_CTX *ctx,
3959 struct cli_state *ipc_cli,
3960 POLICY_HND *pol,
3961 BOOL numeric,
3962 char *str)
3964 const char *p = str;
3965 fstring tok;
3966 SEC_DESC *ret = NULL;
3967 size_t sd_size;
3968 DOM_SID *grp_sid=NULL;
3969 DOM_SID *owner_sid=NULL;
3970 SEC_ACL *dacl=NULL;
3971 int revision=1;
3973 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3975 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3976 revision = strtol(tok+9, NULL, 16);
3977 continue;
3980 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3981 if (owner_sid) {
3982 DEBUG(5, ("OWNER specified more than once!\n"));
3983 goto done;
3985 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3986 if (!owner_sid ||
3987 !convert_string_to_sid(ipc_cli, pol,
3988 numeric,
3989 owner_sid, tok+6)) {
3990 DEBUG(5, ("Failed to parse owner sid\n"));
3991 goto done;
3993 continue;
3996 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3997 if (owner_sid) {
3998 DEBUG(5, ("OWNER specified more than once!\n"));
3999 goto done;
4001 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4002 if (!owner_sid ||
4003 !convert_string_to_sid(ipc_cli, pol,
4004 False,
4005 owner_sid, tok+7)) {
4006 DEBUG(5, ("Failed to parse owner sid\n"));
4007 goto done;
4009 continue;
4012 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
4013 if (grp_sid) {
4014 DEBUG(5, ("GROUP specified more than once!\n"));
4015 goto done;
4017 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4018 if (!grp_sid ||
4019 !convert_string_to_sid(ipc_cli, pol,
4020 numeric,
4021 grp_sid, tok+6)) {
4022 DEBUG(5, ("Failed to parse group sid\n"));
4023 goto done;
4025 continue;
4028 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
4029 if (grp_sid) {
4030 DEBUG(5, ("GROUP specified more than once!\n"));
4031 goto done;
4033 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4034 if (!grp_sid ||
4035 !convert_string_to_sid(ipc_cli, pol,
4036 False,
4037 grp_sid, tok+6)) {
4038 DEBUG(5, ("Failed to parse group sid\n"));
4039 goto done;
4041 continue;
4044 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
4045 SEC_ACE ace;
4046 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
4047 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4048 goto done;
4050 if(!add_ace(&dacl, &ace, ctx)) {
4051 DEBUG(5, ("Failed to add ACL %s\n", tok));
4052 goto done;
4054 continue;
4057 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
4058 SEC_ACE ace;
4059 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
4060 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4061 goto done;
4063 if(!add_ace(&dacl, &ace, ctx)) {
4064 DEBUG(5, ("Failed to add ACL %s\n", tok));
4065 goto done;
4067 continue;
4070 DEBUG(5, ("Failed to parse security descriptor\n"));
4071 goto done;
4074 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
4075 owner_sid, grp_sid, NULL, dacl, &sd_size);
4077 done:
4078 SAFE_FREE(grp_sid);
4079 SAFE_FREE(owner_sid);
4081 return ret;
4085 /* Obtain the current dos attributes */
4086 static DOS_ATTR_DESC *
4087 dos_attr_query(SMBCCTX *context,
4088 TALLOC_CTX *ctx,
4089 const char *filename,
4090 SMBCSRV *srv)
4092 time_t m_time = 0, a_time = 0, c_time = 0;
4093 SMB_OFF_T size = 0;
4094 uint16 mode = 0;
4095 SMB_INO_T inode = 0;
4096 DOS_ATTR_DESC *ret;
4098 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
4099 if (!ret) {
4100 errno = ENOMEM;
4101 return NULL;
4104 /* Obtain the DOS attributes */
4105 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
4106 &mode, &size,
4107 &c_time, &a_time, &m_time, &inode)) {
4109 errno = smbc_errno(context, &srv->cli);
4110 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
4111 return NULL;
4115 ret->mode = mode;
4116 ret->size = size;
4117 ret->a_time = a_time;
4118 ret->c_time = c_time;
4119 ret->m_time = m_time;
4120 ret->inode = inode;
4122 return ret;
4126 /* parse a ascii version of a security descriptor */
4127 static void
4128 dos_attr_parse(SMBCCTX *context,
4129 DOS_ATTR_DESC *dad,
4130 SMBCSRV *srv,
4131 char *str)
4133 const char *p = str;
4134 fstring tok;
4136 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4138 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
4139 dad->mode = strtol(tok+5, NULL, 16);
4140 continue;
4143 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4144 dad->size = (SMB_OFF_T)atof(tok+5);
4145 continue;
4148 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
4149 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
4150 continue;
4153 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
4154 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
4155 continue;
4158 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
4159 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
4160 continue;
4163 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4164 dad->inode = (SMB_INO_T)atof(tok+6);
4165 continue;
4170 /*****************************************************
4171 Retrieve the acls for a file.
4172 *******************************************************/
4174 static int
4175 cacl_get(SMBCCTX *context,
4176 TALLOC_CTX *ctx,
4177 SMBCSRV *srv,
4178 struct cli_state *ipc_cli,
4179 POLICY_HND *pol,
4180 char *filename,
4181 char *attr_name,
4182 char *buf,
4183 int bufsize)
4185 uint32 i;
4186 int n = 0;
4187 int n_used;
4188 BOOL all;
4189 BOOL all_nt;
4190 BOOL all_nt_acls;
4191 BOOL all_dos;
4192 BOOL some_nt;
4193 BOOL some_dos;
4194 BOOL exclude_nt_revision = False;
4195 BOOL exclude_nt_owner = False;
4196 BOOL exclude_nt_group = False;
4197 BOOL exclude_nt_acl = False;
4198 BOOL exclude_dos_mode = False;
4199 BOOL exclude_dos_size = False;
4200 BOOL exclude_dos_ctime = False;
4201 BOOL exclude_dos_atime = False;
4202 BOOL exclude_dos_mtime = False;
4203 BOOL exclude_dos_inode = False;
4204 BOOL numeric = True;
4205 BOOL determine_size = (bufsize == 0);
4206 int fnum = -1;
4207 SEC_DESC *sd;
4208 fstring sidstr;
4209 fstring name_sandbox;
4210 char *name;
4211 char *pExclude;
4212 char *p;
4213 time_t m_time = 0, a_time = 0, c_time = 0;
4214 SMB_OFF_T size = 0;
4215 uint16 mode = 0;
4216 SMB_INO_T ino = 0;
4217 struct cli_state *cli = &srv->cli;
4219 /* Copy name so we can strip off exclusions (if any are specified) */
4220 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4222 /* Ensure name is null terminated */
4223 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4225 /* Play in the sandbox */
4226 name = name_sandbox;
4228 /* If there are any exclusions, point to them and mask them from name */
4229 if ((pExclude = strchr(name, '!')) != NULL)
4231 *pExclude++ = '\0';
4234 all = (StrnCaseCmp(name, "system.*", 8) == 0);
4235 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4236 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4237 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4238 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4239 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4240 numeric = (* (name + strlen(name) - 1) != '+');
4242 /* Look for exclusions from "all" requests */
4243 if (all || all_nt || all_dos) {
4245 /* Exclusions are delimited by '!' */
4246 for (;
4247 pExclude != NULL;
4248 pExclude = (p == NULL ? NULL : p + 1)) {
4250 /* Find end of this exclusion name */
4251 if ((p = strchr(pExclude, '!')) != NULL)
4253 *p = '\0';
4256 /* Which exclusion name is this? */
4257 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4258 exclude_nt_revision = True;
4260 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4261 exclude_nt_owner = True;
4263 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4264 exclude_nt_group = True;
4266 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4267 exclude_nt_acl = True;
4269 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4270 exclude_dos_mode = True;
4272 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4273 exclude_dos_size = True;
4275 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
4276 exclude_dos_ctime = True;
4278 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
4279 exclude_dos_atime = True;
4281 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
4282 exclude_dos_mtime = True;
4284 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4285 exclude_dos_inode = True;
4287 else {
4288 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4289 pExclude));
4290 errno = ENOATTR;
4291 return -1;
4296 n_used = 0;
4299 * If we are (possibly) talking to an NT or new system and some NT
4300 * attributes have been requested...
4302 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4303 /* Point to the portion after "system.nt_sec_desc." */
4304 name += 19; /* if (all) this will be invalid but unused */
4306 /* ... then obtain any NT attributes which were requested */
4307 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4309 if (fnum == -1) {
4310 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4311 filename, cli_errstr(cli)));
4312 errno = 0;
4313 return -1;
4316 sd = cli_query_secdesc(cli, fnum, ctx);
4318 if (!sd) {
4319 DEBUG(5,
4320 ("cacl_get Failed to query old descriptor\n"));
4321 errno = 0;
4322 return -1;
4325 cli_close(cli, fnum);
4327 if (! exclude_nt_revision) {
4328 if (all || all_nt) {
4329 if (determine_size) {
4330 p = talloc_asprintf(ctx,
4331 "REVISION:%d",
4332 sd->revision);
4333 if (!p) {
4334 errno = ENOMEM;
4335 return -1;
4337 n = strlen(p);
4338 } else {
4339 n = snprintf(buf, bufsize,
4340 "REVISION:%d",
4341 sd->revision);
4343 } else if (StrCaseCmp(name, "revision") == 0) {
4344 if (determine_size) {
4345 p = talloc_asprintf(ctx, "%d",
4346 sd->revision);
4347 if (!p) {
4348 errno = ENOMEM;
4349 return -1;
4351 n = strlen(p);
4352 } else {
4353 n = snprintf(buf, bufsize, "%d",
4354 sd->revision);
4358 if (!determine_size && n > bufsize) {
4359 errno = ERANGE;
4360 return -1;
4362 buf += n;
4363 n_used += n;
4364 bufsize -= n;
4367 if (! exclude_nt_owner) {
4368 /* Get owner and group sid */
4369 if (sd->owner_sid) {
4370 convert_sid_to_string(ipc_cli, pol,
4371 sidstr,
4372 numeric,
4373 sd->owner_sid);
4374 } else {
4375 fstrcpy(sidstr, "");
4378 if (all || all_nt) {
4379 if (determine_size) {
4380 p = talloc_asprintf(ctx, ",OWNER:%s",
4381 sidstr);
4382 if (!p) {
4383 errno = ENOMEM;
4384 return -1;
4386 n = strlen(p);
4387 } else {
4388 n = snprintf(buf, bufsize,
4389 ",OWNER:%s", sidstr);
4391 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4392 if (determine_size) {
4393 p = talloc_asprintf(ctx, "%s", sidstr);
4394 if (!p) {
4395 errno = ENOMEM;
4396 return -1;
4398 n = strlen(p);
4399 } else {
4400 n = snprintf(buf, bufsize, "%s",
4401 sidstr);
4405 if (!determine_size && n > bufsize) {
4406 errno = ERANGE;
4407 return -1;
4409 buf += n;
4410 n_used += n;
4411 bufsize -= n;
4414 if (! exclude_nt_group) {
4415 if (sd->grp_sid) {
4416 convert_sid_to_string(ipc_cli, pol,
4417 sidstr, numeric,
4418 sd->grp_sid);
4419 } else {
4420 fstrcpy(sidstr, "");
4423 if (all || all_nt) {
4424 if (determine_size) {
4425 p = talloc_asprintf(ctx, ",GROUP:%s",
4426 sidstr);
4427 if (!p) {
4428 errno = ENOMEM;
4429 return -1;
4431 n = strlen(p);
4432 } else {
4433 n = snprintf(buf, bufsize,
4434 ",GROUP:%s", sidstr);
4436 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4437 if (determine_size) {
4438 p = talloc_asprintf(ctx, "%s", sidstr);
4439 if (!p) {
4440 errno = ENOMEM;
4441 return -1;
4443 n = strlen(p);
4444 } else {
4445 n = snprintf(buf, bufsize,
4446 "%s", sidstr);
4450 if (!determine_size && n > bufsize) {
4451 errno = ERANGE;
4452 return -1;
4454 buf += n;
4455 n_used += n;
4456 bufsize -= n;
4459 if (! exclude_nt_acl) {
4460 /* Add aces to value buffer */
4461 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4463 SEC_ACE *ace = &sd->dacl->ace[i];
4464 convert_sid_to_string(ipc_cli, pol,
4465 sidstr, numeric,
4466 &ace->trustee);
4468 if (all || all_nt) {
4469 if (determine_size) {
4470 p = talloc_asprintf(
4471 ctx,
4472 ",ACL:"
4473 "%s:%d/%d/0x%08x",
4474 sidstr,
4475 ace->type,
4476 ace->flags,
4477 ace->info.mask);
4478 if (!p) {
4479 errno = ENOMEM;
4480 return -1;
4482 n = strlen(p);
4483 } else {
4484 n = snprintf(
4485 buf, bufsize,
4486 ",ACL:%s:%d/%d/0x%08x",
4487 sidstr,
4488 ace->type,
4489 ace->flags,
4490 ace->info.mask);
4492 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4493 StrCaseCmp(name+3, sidstr) == 0) ||
4494 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4495 StrCaseCmp(name+4, sidstr) == 0)) {
4496 if (determine_size) {
4497 p = talloc_asprintf(
4498 ctx,
4499 "%d/%d/0x%08x",
4500 ace->type,
4501 ace->flags,
4502 ace->info.mask);
4503 if (!p) {
4504 errno = ENOMEM;
4505 return -1;
4507 n = strlen(p);
4508 } else {
4509 n = snprintf(buf, bufsize,
4510 "%d/%d/0x%08x",
4511 ace->type,
4512 ace->flags,
4513 ace->info.mask);
4515 } else if (all_nt_acls) {
4516 if (determine_size) {
4517 p = talloc_asprintf(
4518 ctx,
4519 "%s%s:%d/%d/0x%08x",
4520 i ? "," : "",
4521 sidstr,
4522 ace->type,
4523 ace->flags,
4524 ace->info.mask);
4525 if (!p) {
4526 errno = ENOMEM;
4527 return -1;
4529 n = strlen(p);
4530 } else {
4531 n = snprintf(buf, bufsize,
4532 "%s%s:%d/%d/0x%08x",
4533 i ? "," : "",
4534 sidstr,
4535 ace->type,
4536 ace->flags,
4537 ace->info.mask);
4540 if (n > bufsize) {
4541 errno = ERANGE;
4542 return -1;
4544 buf += n;
4545 n_used += n;
4546 bufsize -= n;
4550 /* Restore name pointer to its original value */
4551 name -= 19;
4554 if (all || some_dos) {
4555 /* Point to the portion after "system.dos_attr." */
4556 name += 16; /* if (all) this will be invalid but unused */
4558 /* Obtain the DOS attributes */
4559 if (!smbc_getatr(context, srv, filename, &mode, &size,
4560 &c_time, &a_time, &m_time, &ino)) {
4562 errno = smbc_errno(context, &srv->cli);
4563 return -1;
4567 if (! exclude_dos_mode) {
4568 if (all || all_dos) {
4569 if (determine_size) {
4570 p = talloc_asprintf(ctx,
4571 "%sMODE:0x%x",
4572 (ipc_cli &&
4573 (all || some_nt)
4574 ? ","
4575 : ""),
4576 mode);
4577 if (!p) {
4578 errno = ENOMEM;
4579 return -1;
4581 n = strlen(p);
4582 } else {
4583 n = snprintf(buf, bufsize,
4584 "%sMODE:0x%x",
4585 (ipc_cli &&
4586 (all || some_nt)
4587 ? ","
4588 : ""),
4589 mode);
4591 } else if (StrCaseCmp(name, "mode") == 0) {
4592 if (determine_size) {
4593 p = talloc_asprintf(ctx, "0x%x", mode);
4594 if (!p) {
4595 errno = ENOMEM;
4596 return -1;
4598 n = strlen(p);
4599 } else {
4600 n = snprintf(buf, bufsize,
4601 "0x%x", mode);
4605 if (!determine_size && n > bufsize) {
4606 errno = ERANGE;
4607 return -1;
4609 buf += n;
4610 n_used += n;
4611 bufsize -= n;
4614 if (! exclude_dos_size) {
4615 if (all || all_dos) {
4616 if (determine_size) {
4617 p = talloc_asprintf(
4618 ctx,
4619 ",SIZE:%.0f",
4620 (double)size);
4621 if (!p) {
4622 errno = ENOMEM;
4623 return -1;
4625 n = strlen(p);
4626 } else {
4627 n = snprintf(buf, bufsize,
4628 ",SIZE:%.0f",
4629 (double)size);
4631 } else if (StrCaseCmp(name, "size") == 0) {
4632 if (determine_size) {
4633 p = talloc_asprintf(
4634 ctx,
4635 "%.0f",
4636 (double)size);
4637 if (!p) {
4638 errno = ENOMEM;
4639 return -1;
4641 n = strlen(p);
4642 } else {
4643 n = snprintf(buf, bufsize,
4644 "%.0f",
4645 (double)size);
4649 if (!determine_size && n > bufsize) {
4650 errno = ERANGE;
4651 return -1;
4653 buf += n;
4654 n_used += n;
4655 bufsize -= n;
4658 if (! exclude_dos_ctime) {
4659 if (all || all_dos) {
4660 if (determine_size) {
4661 p = talloc_asprintf(ctx,
4662 ",C_TIME:%lu",
4663 c_time);
4664 if (!p) {
4665 errno = ENOMEM;
4666 return -1;
4668 n = strlen(p);
4669 } else {
4670 n = snprintf(buf, bufsize,
4671 ",C_TIME:%lu", c_time);
4673 } else if (StrCaseCmp(name, "c_time") == 0) {
4674 if (determine_size) {
4675 p = talloc_asprintf(ctx, "%lu", c_time);
4676 if (!p) {
4677 errno = ENOMEM;
4678 return -1;
4680 n = strlen(p);
4681 } else {
4682 n = snprintf(buf, bufsize,
4683 "%lu", c_time);
4687 if (!determine_size && n > bufsize) {
4688 errno = ERANGE;
4689 return -1;
4691 buf += n;
4692 n_used += n;
4693 bufsize -= n;
4696 if (! exclude_dos_atime) {
4697 if (all || all_dos) {
4698 if (determine_size) {
4699 p = talloc_asprintf(ctx,
4700 ",A_TIME:%lu",
4701 a_time);
4702 if (!p) {
4703 errno = ENOMEM;
4704 return -1;
4706 n = strlen(p);
4707 } else {
4708 n = snprintf(buf, bufsize,
4709 ",A_TIME:%lu", a_time);
4711 } else if (StrCaseCmp(name, "a_time") == 0) {
4712 if (determine_size) {
4713 p = talloc_asprintf(ctx, "%lu", a_time);
4714 if (!p) {
4715 errno = ENOMEM;
4716 return -1;
4718 n = strlen(p);
4719 } else {
4720 n = snprintf(buf, bufsize,
4721 "%lu", a_time);
4725 if (!determine_size && n > bufsize) {
4726 errno = ERANGE;
4727 return -1;
4729 buf += n;
4730 n_used += n;
4731 bufsize -= n;
4734 if (! exclude_dos_mtime) {
4735 if (all || all_dos) {
4736 if (determine_size) {
4737 p = talloc_asprintf(ctx,
4738 ",M_TIME:%lu",
4739 m_time);
4740 if (!p) {
4741 errno = ENOMEM;
4742 return -1;
4744 n = strlen(p);
4745 } else {
4746 n = snprintf(buf, bufsize,
4747 ",M_TIME:%lu", m_time);
4749 } else if (StrCaseCmp(name, "m_time") == 0) {
4750 if (determine_size) {
4751 p = talloc_asprintf(ctx, "%lu", m_time);
4752 if (!p) {
4753 errno = ENOMEM;
4754 return -1;
4756 n = strlen(p);
4757 } else {
4758 n = snprintf(buf, bufsize,
4759 "%lu", m_time);
4763 if (!determine_size && n > bufsize) {
4764 errno = ERANGE;
4765 return -1;
4767 buf += n;
4768 n_used += n;
4769 bufsize -= n;
4772 if (! exclude_dos_inode) {
4773 if (all || all_dos) {
4774 if (determine_size) {
4775 p = talloc_asprintf(
4776 ctx,
4777 ",INODE:%.0f",
4778 (double)ino);
4779 if (!p) {
4780 errno = ENOMEM;
4781 return -1;
4783 n = strlen(p);
4784 } else {
4785 n = snprintf(buf, bufsize,
4786 ",INODE:%.0f",
4787 (double) ino);
4789 } else if (StrCaseCmp(name, "inode") == 0) {
4790 if (determine_size) {
4791 p = talloc_asprintf(
4792 ctx,
4793 "%.0f",
4794 (double) ino);
4795 if (!p) {
4796 errno = ENOMEM;
4797 return -1;
4799 n = strlen(p);
4800 } else {
4801 n = snprintf(buf, bufsize,
4802 "%.0f",
4803 (double) ino);
4807 if (!determine_size && n > bufsize) {
4808 errno = ERANGE;
4809 return -1;
4811 buf += n;
4812 n_used += n;
4813 bufsize -= n;
4816 /* Restore name pointer to its original value */
4817 name -= 16;
4820 if (n_used == 0) {
4821 errno = ENOATTR;
4822 return -1;
4825 return n_used;
4829 /*****************************************************
4830 set the ACLs on a file given an ascii description
4831 *******************************************************/
4832 static int
4833 cacl_set(TALLOC_CTX *ctx,
4834 struct cli_state *cli,
4835 struct cli_state *ipc_cli,
4836 POLICY_HND *pol,
4837 const char *filename,
4838 const char *the_acl,
4839 int mode,
4840 int flags)
4842 int fnum;
4843 int err = 0;
4844 SEC_DESC *sd = NULL, *old;
4845 SEC_ACL *dacl = NULL;
4846 DOM_SID *owner_sid = NULL;
4847 DOM_SID *grp_sid = NULL;
4848 uint32 i, j;
4849 size_t sd_size;
4850 int ret = 0;
4851 char *p;
4852 BOOL numeric = True;
4854 /* the_acl will be null for REMOVE_ALL operations */
4855 if (the_acl) {
4856 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4857 p > the_acl &&
4858 p[-1] != '+');
4860 /* if this is to set the entire ACL... */
4861 if (*the_acl == '*') {
4862 /* ... then increment past the first colon */
4863 the_acl = p + 1;
4866 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4867 CONST_DISCARD(char *, the_acl));
4869 if (!sd) {
4870 errno = EINVAL;
4871 return -1;
4875 /* SMBC_XATTR_MODE_REMOVE_ALL is the only caller
4876 that doesn't deref sd */
4878 if (!sd && (mode != SMBC_XATTR_MODE_REMOVE_ALL)) {
4879 errno = EINVAL;
4880 return -1;
4883 /* The desired access below is the only one I could find that works
4884 with NT4, W2KP and Samba */
4886 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4888 if (fnum == -1) {
4889 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4890 filename, cli_errstr(cli)));
4891 errno = 0;
4892 return -1;
4895 old = cli_query_secdesc(cli, fnum, ctx);
4897 if (!old) {
4898 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4899 errno = 0;
4900 return -1;
4903 cli_close(cli, fnum);
4905 switch (mode) {
4906 case SMBC_XATTR_MODE_REMOVE_ALL:
4907 old->dacl->num_aces = 0;
4908 SAFE_FREE(old->dacl->ace);
4909 SAFE_FREE(old->dacl);
4910 old->off_dacl = 0;
4911 dacl = old->dacl;
4912 break;
4914 case SMBC_XATTR_MODE_REMOVE:
4915 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4916 BOOL found = False;
4918 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4919 if (sec_ace_equal(&sd->dacl->ace[i],
4920 &old->dacl->ace[j])) {
4921 uint32 k;
4922 for (k=j; k<old->dacl->num_aces-1;k++) {
4923 old->dacl->ace[k] =
4924 old->dacl->ace[k+1];
4926 old->dacl->num_aces--;
4927 if (old->dacl->num_aces == 0) {
4928 SAFE_FREE(old->dacl->ace);
4929 SAFE_FREE(old->dacl);
4930 old->off_dacl = 0;
4932 found = True;
4933 dacl = old->dacl;
4934 break;
4938 if (!found) {
4939 err = ENOATTR;
4940 ret = -1;
4941 goto failed;
4944 break;
4946 case SMBC_XATTR_MODE_ADD:
4947 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4948 BOOL found = False;
4950 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4951 if (sid_equal(&sd->dacl->ace[i].trustee,
4952 &old->dacl->ace[j].trustee)) {
4953 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4954 err = EEXIST;
4955 ret = -1;
4956 goto failed;
4958 old->dacl->ace[j] = sd->dacl->ace[i];
4959 ret = -1;
4960 found = True;
4964 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4965 err = ENOATTR;
4966 ret = -1;
4967 goto failed;
4970 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4971 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4974 dacl = old->dacl;
4975 break;
4977 case SMBC_XATTR_MODE_SET:
4978 old = sd;
4979 owner_sid = old->owner_sid;
4980 grp_sid = old->grp_sid;
4981 dacl = old->dacl;
4982 break;
4984 case SMBC_XATTR_MODE_CHOWN:
4985 owner_sid = sd->owner_sid;
4986 break;
4988 case SMBC_XATTR_MODE_CHGRP:
4989 grp_sid = sd->grp_sid;
4990 break;
4993 /* Denied ACE entries must come before allowed ones */
4994 sort_acl(old->dacl);
4996 /* Create new security descriptor and set it */
4997 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4998 owner_sid, grp_sid, NULL, dacl, &sd_size);
5000 fnum = cli_nt_create(cli, filename,
5001 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
5003 if (fnum == -1) {
5004 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5005 filename, cli_errstr(cli)));
5006 errno = 0;
5007 return -1;
5010 if (!cli_set_secdesc(cli, fnum, sd)) {
5011 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
5012 ret = -1;
5015 /* Clean up */
5017 failed:
5018 cli_close(cli, fnum);
5020 if (err != 0) {
5021 errno = err;
5024 return ret;
5028 static int
5029 smbc_setxattr_ctx(SMBCCTX *context,
5030 const char *fname,
5031 const char *name,
5032 const void *value,
5033 size_t size,
5034 int flags)
5036 int ret;
5037 int ret2;
5038 SMBCSRV *srv;
5039 SMBCSRV *ipc_srv;
5040 fstring server;
5041 fstring share;
5042 fstring user;
5043 fstring password;
5044 fstring workgroup;
5045 pstring path;
5046 TALLOC_CTX *ctx;
5047 POLICY_HND pol;
5048 DOS_ATTR_DESC *dad;
5050 if (!context || !context->internal ||
5051 !context->internal->_initialized) {
5053 errno = EINVAL; /* Best I can think of ... */
5054 return -1;
5058 if (!fname) {
5060 errno = EINVAL;
5061 return -1;
5065 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
5066 fname, name, (int) size, (const char*)value));
5068 if (smbc_parse_path(context, fname,
5069 workgroup, sizeof(workgroup),
5070 server, sizeof(server),
5071 share, sizeof(share),
5072 path, sizeof(path),
5073 user, sizeof(user),
5074 password, sizeof(password),
5075 NULL, 0)) {
5076 errno = EINVAL;
5077 return -1;
5080 if (user[0] == (char)0) fstrcpy(user, context->user);
5082 srv = smbc_server(context, True,
5083 server, share, workgroup, user, password);
5084 if (!srv) {
5085 return -1; /* errno set by smbc_server */
5088 if (! srv->no_nt_session) {
5089 ipc_srv = smbc_attr_server(context, server, share,
5090 workgroup, user, password,
5091 &pol);
5092 srv->no_nt_session = True;
5093 } else {
5094 ipc_srv = NULL;
5097 ctx = talloc_init("smbc_setxattr");
5098 if (!ctx) {
5099 errno = ENOMEM;
5100 return -1;
5104 * Are they asking to set the entire set of known attributes?
5106 if (StrCaseCmp(name, "system.*") == 0 ||
5107 StrCaseCmp(name, "system.*+") == 0) {
5108 /* Yup. */
5109 char *namevalue =
5110 talloc_asprintf(ctx, "%s:%s",
5111 name+7, (const char *) value);
5112 if (! namevalue) {
5113 errno = ENOMEM;
5114 ret = -1;
5115 return -1;
5118 if (ipc_srv) {
5119 ret = cacl_set(ctx, &srv->cli,
5120 &ipc_srv->cli, &pol, path,
5121 namevalue,
5122 (*namevalue == '*'
5123 ? SMBC_XATTR_MODE_SET
5124 : SMBC_XATTR_MODE_ADD),
5125 flags);
5126 } else {
5127 ret = 0;
5130 /* get a DOS Attribute Descriptor with current attributes */
5131 dad = dos_attr_query(context, ctx, path, srv);
5132 if (dad) {
5133 /* Overwrite old with new, using what was provided */
5134 dos_attr_parse(context, dad, srv, namevalue);
5136 /* Set the new DOS attributes */
5137 if (! smbc_setatr(context, srv, path,
5138 dad->c_time,
5139 dad->a_time,
5140 dad->m_time,
5141 dad->mode)) {
5143 /* cause failure if NT failed too */
5144 dad = NULL;
5148 /* we only fail if both NT and DOS sets failed */
5149 if (ret < 0 && ! dad) {
5150 ret = -1; /* in case dad was null */
5152 else {
5153 ret = 0;
5156 talloc_destroy(ctx);
5157 return ret;
5161 * Are they asking to set an access control element or to set
5162 * the entire access control list?
5164 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5165 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5166 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5167 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5168 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5170 /* Yup. */
5171 char *namevalue =
5172 talloc_asprintf(ctx, "%s:%s",
5173 name+19, (const char *) value);
5175 if (! ipc_srv) {
5176 ret = -1; /* errno set by smbc_server() */
5178 else if (! namevalue) {
5179 errno = ENOMEM;
5180 ret = -1;
5181 } else {
5182 ret = cacl_set(ctx, &srv->cli,
5183 &ipc_srv->cli, &pol, path,
5184 namevalue,
5185 (*namevalue == '*'
5186 ? SMBC_XATTR_MODE_SET
5187 : SMBC_XATTR_MODE_ADD),
5188 flags);
5190 talloc_destroy(ctx);
5191 return ret;
5195 * Are they asking to set the owner?
5197 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5198 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5200 /* Yup. */
5201 char *namevalue =
5202 talloc_asprintf(ctx, "%s:%s",
5203 name+19, (const char *) value);
5205 if (! ipc_srv) {
5207 ret = -1; /* errno set by smbc_server() */
5209 else if (! namevalue) {
5210 errno = ENOMEM;
5211 ret = -1;
5212 } else {
5213 ret = cacl_set(ctx, &srv->cli,
5214 &ipc_srv->cli, &pol, path,
5215 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5217 talloc_destroy(ctx);
5218 return ret;
5222 * Are they asking to set the group?
5224 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5225 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5227 /* Yup. */
5228 char *namevalue =
5229 talloc_asprintf(ctx, "%s:%s",
5230 name+19, (const char *) value);
5232 if (! ipc_srv) {
5233 /* errno set by smbc_server() */
5234 ret = -1;
5236 else if (! namevalue) {
5237 errno = ENOMEM;
5238 ret = -1;
5239 } else {
5240 ret = cacl_set(ctx, &srv->cli,
5241 &ipc_srv->cli, &pol, path,
5242 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5244 talloc_destroy(ctx);
5245 return ret;
5249 * Are they asking to set a DOS attribute?
5251 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5252 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5253 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5254 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5255 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
5257 /* get a DOS Attribute Descriptor with current attributes */
5258 dad = dos_attr_query(context, ctx, path, srv);
5259 if (dad) {
5260 char *namevalue =
5261 talloc_asprintf(ctx, "%s:%s",
5262 name+16, (const char *) value);
5263 if (! namevalue) {
5264 errno = ENOMEM;
5265 ret = -1;
5266 } else {
5267 /* Overwrite old with provided new params */
5268 dos_attr_parse(context, dad, srv, namevalue);
5270 /* Set the new DOS attributes */
5271 ret2 = smbc_setatr(context, srv, path,
5272 dad->c_time,
5273 dad->a_time,
5274 dad->m_time,
5275 dad->mode);
5277 /* ret2 has True (success) / False (failure) */
5278 if (ret2) {
5279 ret = 0;
5280 } else {
5281 ret = -1;
5284 } else {
5285 ret = -1;
5288 talloc_destroy(ctx);
5289 return ret;
5292 /* Unsupported attribute name */
5293 talloc_destroy(ctx);
5294 errno = EINVAL;
5295 return -1;
5298 static int
5299 smbc_getxattr_ctx(SMBCCTX *context,
5300 const char *fname,
5301 const char *name,
5302 const void *value,
5303 size_t size)
5305 int ret;
5306 SMBCSRV *srv;
5307 SMBCSRV *ipc_srv;
5308 fstring server;
5309 fstring share;
5310 fstring user;
5311 fstring password;
5312 fstring workgroup;
5313 pstring path;
5314 TALLOC_CTX *ctx;
5315 POLICY_HND pol;
5318 if (!context || !context->internal ||
5319 !context->internal->_initialized) {
5321 errno = EINVAL; /* Best I can think of ... */
5322 return -1;
5326 if (!fname) {
5328 errno = EINVAL;
5329 return -1;
5333 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5335 if (smbc_parse_path(context, fname,
5336 workgroup, sizeof(workgroup),
5337 server, sizeof(server),
5338 share, sizeof(share),
5339 path, sizeof(path),
5340 user, sizeof(user),
5341 password, sizeof(password),
5342 NULL, 0)) {
5343 errno = EINVAL;
5344 return -1;
5347 if (user[0] == (char)0) fstrcpy(user, context->user);
5349 srv = smbc_server(context, True,
5350 server, share, workgroup, user, password);
5351 if (!srv) {
5352 return -1; /* errno set by smbc_server */
5355 if (! srv->no_nt_session) {
5356 ipc_srv = smbc_attr_server(context, server, share,
5357 workgroup, user, password,
5358 &pol);
5359 if (! ipc_srv) {
5360 srv->no_nt_session = True;
5362 } else {
5363 ipc_srv = NULL;
5366 ctx = talloc_init("smbc:getxattr");
5367 if (!ctx) {
5368 errno = ENOMEM;
5369 return -1;
5372 /* Are they requesting a supported attribute? */
5373 if (StrCaseCmp(name, "system.*") == 0 ||
5374 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5375 StrCaseCmp(name, "system.*+") == 0 ||
5376 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5377 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5378 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5379 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5380 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5381 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5382 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5383 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5384 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5385 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5386 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5387 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5388 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5389 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5390 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5391 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5392 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5393 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5394 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
5395 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5397 /* Yup. */
5398 ret = cacl_get(context, ctx, srv,
5399 ipc_srv == NULL ? NULL : &ipc_srv->cli,
5400 &pol, path,
5401 CONST_DISCARD(char *, name),
5402 CONST_DISCARD(char *, value), size);
5403 if (ret < 0 && errno == 0) {
5404 errno = smbc_errno(context, &srv->cli);
5406 talloc_destroy(ctx);
5407 return ret;
5410 /* Unsupported attribute name */
5411 talloc_destroy(ctx);
5412 errno = EINVAL;
5413 return -1;
5417 static int
5418 smbc_removexattr_ctx(SMBCCTX *context,
5419 const char *fname,
5420 const char *name)
5422 int ret;
5423 SMBCSRV *srv;
5424 SMBCSRV *ipc_srv;
5425 fstring server;
5426 fstring share;
5427 fstring user;
5428 fstring password;
5429 fstring workgroup;
5430 pstring path;
5431 TALLOC_CTX *ctx;
5432 POLICY_HND pol;
5434 if (!context || !context->internal ||
5435 !context->internal->_initialized) {
5437 errno = EINVAL; /* Best I can think of ... */
5438 return -1;
5442 if (!fname) {
5444 errno = EINVAL;
5445 return -1;
5449 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5451 if (smbc_parse_path(context, fname,
5452 workgroup, sizeof(workgroup),
5453 server, sizeof(server),
5454 share, sizeof(share),
5455 path, sizeof(path),
5456 user, sizeof(user),
5457 password, sizeof(password),
5458 NULL, 0)) {
5459 errno = EINVAL;
5460 return -1;
5463 if (user[0] == (char)0) fstrcpy(user, context->user);
5465 srv = smbc_server(context, True,
5466 server, share, workgroup, user, password);
5467 if (!srv) {
5468 return -1; /* errno set by smbc_server */
5471 if (! srv->no_nt_session) {
5472 ipc_srv = smbc_attr_server(context, server, share,
5473 workgroup, user, password,
5474 &pol);
5475 srv->no_nt_session = True;
5476 } else {
5477 ipc_srv = NULL;
5480 if (! ipc_srv) {
5481 return -1; /* errno set by smbc_attr_server */
5484 ctx = talloc_init("smbc_removexattr");
5485 if (!ctx) {
5486 errno = ENOMEM;
5487 return -1;
5490 /* Are they asking to set the entire ACL? */
5491 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5492 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5494 /* Yup. */
5495 ret = cacl_set(ctx, &srv->cli,
5496 &ipc_srv->cli, &pol, path,
5497 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5498 talloc_destroy(ctx);
5499 return ret;
5503 * Are they asking to remove one or more spceific security descriptor
5504 * attributes?
5506 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5507 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5508 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5509 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5510 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5511 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5512 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5514 /* Yup. */
5515 ret = cacl_set(ctx, &srv->cli,
5516 &ipc_srv->cli, &pol, path,
5517 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5518 talloc_destroy(ctx);
5519 return ret;
5522 /* Unsupported attribute name */
5523 talloc_destroy(ctx);
5524 errno = EINVAL;
5525 return -1;
5528 static int
5529 smbc_listxattr_ctx(SMBCCTX *context,
5530 const char *fname,
5531 char *list,
5532 size_t size)
5535 * This isn't quite what listxattr() is supposed to do. This returns
5536 * the complete set of attribute names, always, rather than only those
5537 * attribute names which actually exist for a file. Hmmm...
5539 const char supported[] =
5540 "system.*\0"
5541 "system.*+\0"
5542 "system.nt_sec_desc.revision\0"
5543 "system.nt_sec_desc.owner\0"
5544 "system.nt_sec_desc.owner+\0"
5545 "system.nt_sec_desc.group\0"
5546 "system.nt_sec_desc.group+\0"
5547 "system.nt_sec_desc.acl.*\0"
5548 "system.nt_sec_desc.acl\0"
5549 "system.nt_sec_desc.acl+\0"
5550 "system.nt_sec_desc.*\0"
5551 "system.nt_sec_desc.*+\0"
5552 "system.dos_attr.*\0"
5553 "system.dos_attr.mode\0"
5554 "system.dos_attr.c_time\0"
5555 "system.dos_attr.a_time\0"
5556 "system.dos_attr.m_time\0"
5559 if (size == 0) {
5560 return sizeof(supported);
5563 if (sizeof(supported) > size) {
5564 errno = ERANGE;
5565 return -1;
5568 /* this can't be strcpy() because there are embedded null characters */
5569 memcpy(list, supported, sizeof(supported));
5570 return sizeof(supported);
5575 * Open a print file to be written to by other calls
5578 static SMBCFILE *
5579 smbc_open_print_job_ctx(SMBCCTX *context,
5580 const char *fname)
5582 fstring server;
5583 fstring share;
5584 fstring user;
5585 fstring password;
5586 pstring path;
5588 if (!context || !context->internal ||
5589 !context->internal->_initialized) {
5591 errno = EINVAL;
5592 return NULL;
5596 if (!fname) {
5598 errno = EINVAL;
5599 return NULL;
5603 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5605 if (smbc_parse_path(context, fname,
5606 NULL, 0,
5607 server, sizeof(server),
5608 share, sizeof(share),
5609 path, sizeof(path),
5610 user, sizeof(user),
5611 password, sizeof(password),
5612 NULL, 0)) {
5613 errno = EINVAL;
5614 return NULL;
5617 /* What if the path is empty, or the file exists? */
5619 return context->open(context, fname, O_WRONLY, 666);
5624 * Routine to print a file on a remote server ...
5626 * We open the file, which we assume to be on a remote server, and then
5627 * copy it to a print file on the share specified by printq.
5630 static int
5631 smbc_print_file_ctx(SMBCCTX *c_file,
5632 const char *fname,
5633 SMBCCTX *c_print,
5634 const char *printq)
5636 SMBCFILE *fid1;
5637 SMBCFILE *fid2;
5638 int bytes;
5639 int saverr;
5640 int tot_bytes = 0;
5641 char buf[4096];
5643 if (!c_file || !c_file->internal->_initialized || !c_print ||
5644 !c_print->internal->_initialized) {
5646 errno = EINVAL;
5647 return -1;
5651 if (!fname && !printq) {
5653 errno = EINVAL;
5654 return -1;
5658 /* Try to open the file for reading ... */
5660 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5662 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5663 return -1; /* smbc_open sets errno */
5667 /* Now, try to open the printer file for writing */
5669 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5671 saverr = errno; /* Save errno */
5672 c_file->close_fn(c_file, fid1);
5673 errno = saverr;
5674 return -1;
5678 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5680 tot_bytes += bytes;
5682 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5684 saverr = errno;
5685 c_file->close_fn(c_file, fid1);
5686 c_print->close_fn(c_print, fid2);
5687 errno = saverr;
5693 saverr = errno;
5695 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5696 c_print->close_fn(c_print, fid2);
5698 if (bytes < 0) {
5700 errno = saverr;
5701 return -1;
5705 return tot_bytes;
5710 * Routine to list print jobs on a printer share ...
5713 static int
5714 smbc_list_print_jobs_ctx(SMBCCTX *context,
5715 const char *fname,
5716 smbc_list_print_job_fn fn)
5718 SMBCSRV *srv;
5719 fstring server;
5720 fstring share;
5721 fstring user;
5722 fstring password;
5723 fstring workgroup;
5724 pstring path;
5726 if (!context || !context->internal ||
5727 !context->internal->_initialized) {
5729 errno = EINVAL;
5730 return -1;
5734 if (!fname) {
5736 errno = EINVAL;
5737 return -1;
5741 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5743 if (smbc_parse_path(context, fname,
5744 workgroup, sizeof(workgroup),
5745 server, sizeof(server),
5746 share, sizeof(share),
5747 path, sizeof(path),
5748 user, sizeof(user),
5749 password, sizeof(password),
5750 NULL, 0)) {
5751 errno = EINVAL;
5752 return -1;
5755 if (user[0] == (char)0) fstrcpy(user, context->user);
5757 srv = smbc_server(context, True,
5758 server, share, workgroup, user, password);
5760 if (!srv) {
5762 return -1; /* errno set by smbc_server */
5766 if (cli_print_queue(&srv->cli,
5767 (void (*)(struct print_job_info *))fn) < 0) {
5769 errno = smbc_errno(context, &srv->cli);
5770 return -1;
5774 return 0;
5779 * Delete a print job from a remote printer share
5782 static int
5783 smbc_unlink_print_job_ctx(SMBCCTX *context,
5784 const char *fname,
5785 int id)
5787 SMBCSRV *srv;
5788 fstring server;
5789 fstring share;
5790 fstring user;
5791 fstring password;
5792 fstring workgroup;
5793 pstring path;
5794 int err;
5796 if (!context || !context->internal ||
5797 !context->internal->_initialized) {
5799 errno = EINVAL;
5800 return -1;
5804 if (!fname) {
5806 errno = EINVAL;
5807 return -1;
5811 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5813 if (smbc_parse_path(context, fname,
5814 workgroup, sizeof(workgroup),
5815 server, sizeof(server),
5816 share, sizeof(share),
5817 path, sizeof(path),
5818 user, sizeof(user),
5819 password, sizeof(password),
5820 NULL, 0)) {
5821 errno = EINVAL;
5822 return -1;
5825 if (user[0] == (char)0) fstrcpy(user, context->user);
5827 srv = smbc_server(context, True,
5828 server, share, workgroup, user, password);
5830 if (!srv) {
5832 return -1; /* errno set by smbc_server */
5836 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5838 if (err < 0)
5839 errno = smbc_errno(context, &srv->cli);
5840 else if (err == ERRnosuchprintjob)
5841 errno = EINVAL;
5842 return -1;
5846 return 0;
5851 * Get a new empty handle to fill in with your own info
5853 SMBCCTX *
5854 smbc_new_context(void)
5856 SMBCCTX *context;
5858 context = SMB_MALLOC_P(SMBCCTX);
5859 if (!context) {
5860 errno = ENOMEM;
5861 return NULL;
5864 ZERO_STRUCTP(context);
5866 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5867 if (!context->internal) {
5868 SAFE_FREE(context);
5869 errno = ENOMEM;
5870 return NULL;
5873 ZERO_STRUCTP(context->internal);
5876 /* ADD REASONABLE DEFAULTS */
5877 context->debug = 0;
5878 context->timeout = 20000; /* 20 seconds */
5880 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5881 context->options.urlencode_readdir_entries = False;/* backward compat */
5882 context->options.one_share_per_server = False;/* backward compat */
5884 context->open = smbc_open_ctx;
5885 context->creat = smbc_creat_ctx;
5886 context->read = smbc_read_ctx;
5887 context->write = smbc_write_ctx;
5888 context->close_fn = smbc_close_ctx;
5889 context->unlink = smbc_unlink_ctx;
5890 context->rename = smbc_rename_ctx;
5891 context->lseek = smbc_lseek_ctx;
5892 context->stat = smbc_stat_ctx;
5893 context->fstat = smbc_fstat_ctx;
5894 context->opendir = smbc_opendir_ctx;
5895 context->closedir = smbc_closedir_ctx;
5896 context->readdir = smbc_readdir_ctx;
5897 context->getdents = smbc_getdents_ctx;
5898 context->mkdir = smbc_mkdir_ctx;
5899 context->rmdir = smbc_rmdir_ctx;
5900 context->telldir = smbc_telldir_ctx;
5901 context->lseekdir = smbc_lseekdir_ctx;
5902 context->fstatdir = smbc_fstatdir_ctx;
5903 context->chmod = smbc_chmod_ctx;
5904 context->utimes = smbc_utimes_ctx;
5905 context->setxattr = smbc_setxattr_ctx;
5906 context->getxattr = smbc_getxattr_ctx;
5907 context->removexattr = smbc_removexattr_ctx;
5908 context->listxattr = smbc_listxattr_ctx;
5909 context->open_print_job = smbc_open_print_job_ctx;
5910 context->print_file = smbc_print_file_ctx;
5911 context->list_print_jobs = smbc_list_print_jobs_ctx;
5912 context->unlink_print_job = smbc_unlink_print_job_ctx;
5914 context->callbacks.check_server_fn = smbc_check_server;
5915 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5917 smbc_default_cache_functions(context);
5919 return context;
5923 * Free a context
5925 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5926 * and thus you'll be leaking memory if not handled properly.
5930 smbc_free_context(SMBCCTX *context,
5931 int shutdown_ctx)
5933 if (!context) {
5934 errno = EBADF;
5935 return 1;
5938 if (shutdown_ctx) {
5939 SMBCFILE * f;
5940 DEBUG(1,("Performing aggressive shutdown.\n"));
5942 f = context->internal->_files;
5943 while (f) {
5944 context->close_fn(context, f);
5945 f = f->next;
5947 context->internal->_files = NULL;
5949 /* First try to remove the servers the nice way. */
5950 if (context->callbacks.purge_cached_fn(context)) {
5951 SMBCSRV * s;
5952 SMBCSRV * next;
5953 DEBUG(1, ("Could not purge all servers, "
5954 "Nice way shutdown failed.\n"));
5955 s = context->internal->_servers;
5956 while (s) {
5957 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
5958 s, s->cli.fd));
5959 cli_shutdown(&s->cli);
5960 context->callbacks.remove_cached_srv_fn(context,
5962 next = s->next;
5963 DLIST_REMOVE(context->internal->_servers, s);
5964 SAFE_FREE(s);
5965 s = next;
5967 context->internal->_servers = NULL;
5970 else {
5971 /* This is the polite way */
5972 if (context->callbacks.purge_cached_fn(context)) {
5973 DEBUG(1, ("Could not purge all servers, "
5974 "free_context failed.\n"));
5975 errno = EBUSY;
5976 return 1;
5978 if (context->internal->_servers) {
5979 DEBUG(1, ("Active servers in context, "
5980 "free_context failed.\n"));
5981 errno = EBUSY;
5982 return 1;
5984 if (context->internal->_files) {
5985 DEBUG(1, ("Active files in context, "
5986 "free_context failed.\n"));
5987 errno = EBUSY;
5988 return 1;
5992 /* Things we have to clean up */
5993 SAFE_FREE(context->workgroup);
5994 SAFE_FREE(context->netbios_name);
5995 SAFE_FREE(context->user);
5997 DEBUG(3, ("Context %p succesfully freed\n", context));
5998 SAFE_FREE(context->internal);
5999 SAFE_FREE(context);
6000 return 0;
6005 * Each time the context structure is changed, we have binary backward
6006 * compatibility issues. Instead of modifying the public portions of the
6007 * context structure to add new options, instead, we put them in the internal
6008 * portion of the context structure and provide a set function for these new
6009 * options.
6011 void
6012 smbc_option_set(SMBCCTX *context,
6013 char *option_name,
6014 void *option_value)
6016 if (strcmp(option_name, "debug_stderr") == 0) {
6018 * Log to standard error instead of standard output.
6020 context->internal->_debug_stderr =
6021 (option_value == NULL ? False : True);
6022 } else if (strcmp(option_name, "auth_function") == 0) {
6024 * Use the new-style authentication function which includes
6025 * the context.
6027 context->internal->_auth_fn_with_context = option_value;
6028 } else if (strcmp(option_name, "user_data") == 0) {
6030 * Save a user data handle which may be retrieved by the user
6031 * with smbc_option_get()
6033 context->internal->_user_data = option_value;
6039 * Retrieve the current value of an option
6041 void *
6042 smbc_option_get(SMBCCTX *context,
6043 char *option_name)
6045 if (strcmp(option_name, "debug_stderr") == 0) {
6047 * Log to standard error instead of standard output.
6049 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6050 return (void *) (intptr_t) context->internal->_debug_stderr;
6051 #else
6052 return (void *) context->internal->_debug_stderr;
6053 #endif
6054 } else if (strcmp(option_name, "auth_function") == 0) {
6056 * Use the new-style authentication function which includes
6057 * the context.
6059 return (void *) context->internal->_auth_fn_with_context;
6060 } else if (strcmp(option_name, "user_data") == 0) {
6062 * Save a user data handle which may be retrieved by the user
6063 * with smbc_option_get()
6065 return context->internal->_user_data;
6068 return NULL;
6073 * Initialise the library etc
6075 * We accept a struct containing handle information.
6076 * valid values for info->debug from 0 to 100,
6077 * and insist that info->fn must be non-null.
6079 SMBCCTX *
6080 smbc_init_context(SMBCCTX *context)
6082 pstring conf;
6083 int pid;
6084 char *user = NULL;
6085 char *home = NULL;
6087 if (!context || !context->internal) {
6088 errno = EBADF;
6089 return NULL;
6092 /* Do not initialise the same client twice */
6093 if (context->internal->_initialized) {
6094 return 0;
6097 if ((!context->callbacks.auth_fn &&
6098 !context->internal->_auth_fn_with_context) ||
6099 context->debug < 0 ||
6100 context->debug > 100) {
6102 errno = EINVAL;
6103 return NULL;
6107 if (!smbc_initialized) {
6109 * Do some library-wide intializations the first time we get
6110 * called
6112 BOOL conf_loaded = False;
6114 /* Set this to what the user wants */
6115 DEBUGLEVEL = context->debug;
6117 load_case_tables();
6119 setup_logging("libsmbclient", True);
6120 if (context->internal->_debug_stderr) {
6121 dbf = x_stderr;
6122 x_setbuf(x_stderr, NULL);
6125 /* Here we would open the smb.conf file if needed ... */
6127 in_client = True; /* FIXME, make a param */
6129 home = getenv("HOME");
6130 if (home) {
6131 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
6132 if (lp_load(conf, True, False, False, True)) {
6133 conf_loaded = True;
6134 } else {
6135 DEBUG(5, ("Could not load config file: %s\n",
6136 conf));
6140 if (!conf_loaded) {
6142 * Well, if that failed, try the dyn_CONFIGFILE
6143 * Which points to the standard locn, and if that
6144 * fails, silently ignore it and use the internal
6145 * defaults ...
6148 if (!lp_load(dyn_CONFIGFILE, True, False, False, False)) {
6149 DEBUG(5, ("Could not load config file: %s\n",
6150 dyn_CONFIGFILE));
6151 } else if (home) {
6153 * We loaded the global config file. Now lets
6154 * load user-specific modifications to the
6155 * global config.
6157 slprintf(conf, sizeof(conf),
6158 "%s/.smb/smb.conf.append", home);
6159 if (!lp_load(conf, True, False, False, False)) {
6160 DEBUG(10,
6161 ("Could not append config file: "
6162 "%s\n",
6163 conf));
6168 load_interfaces(); /* Load the list of interfaces ... */
6170 reopen_logs(); /* Get logging working ... */
6173 * Block SIGPIPE (from lib/util_sock.c: write())
6174 * It is not needed and should not stop execution
6176 BlockSignals(True, SIGPIPE);
6178 /* Done with one-time initialisation */
6179 smbc_initialized = 1;
6183 if (!context->user) {
6185 * FIXME: Is this the best way to get the user info?
6187 user = getenv("USER");
6188 /* walk around as "guest" if no username can be found */
6189 if (!user) context->user = SMB_STRDUP("guest");
6190 else context->user = SMB_STRDUP(user);
6193 if (!context->netbios_name) {
6195 * We try to get our netbios name from the config. If that
6196 * fails we fall back on constructing our netbios name from
6197 * our hostname etc
6199 if (global_myname()) {
6200 context->netbios_name = SMB_STRDUP(global_myname());
6202 else {
6204 * Hmmm, I want to get hostname as well, but I am too
6205 * lazy for the moment
6207 pid = sys_getpid();
6208 context->netbios_name = SMB_MALLOC(17);
6209 if (!context->netbios_name) {
6210 errno = ENOMEM;
6211 return NULL;
6213 slprintf(context->netbios_name, 16,
6214 "smbc%s%d", context->user, pid);
6218 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
6220 if (!context->workgroup) {
6221 if (lp_workgroup()) {
6222 context->workgroup = SMB_STRDUP(lp_workgroup());
6224 else {
6225 /* TODO: Think about a decent default workgroup */
6226 context->workgroup = SMB_STRDUP("samba");
6230 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
6232 /* shortest timeout is 1 second */
6233 if (context->timeout > 0 && context->timeout < 1000)
6234 context->timeout = 1000;
6237 * FIXME: Should we check the function pointers here?
6240 context->internal->_initialized = True;
6242 return context;
6246 /* Return the verion of samba, and thus libsmbclient */
6247 const char *
6248 smbc_version(void)
6250 return samba_version_string();