r18745: Use the Samba4 data structures for security descriptors and security descriptor
[Samba.git] / source / libsmb / libsmbclient.c
blob15a1ad3055605af398da0a15b6be6caff7ce73e8
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 create_time;
37 time_t access_time;
38 time_t write_time;
39 time_t change_time;
40 SMB_INO_T inode;
41 } DOS_ATTR_DESC;
45 * Internal flags for extended attributes
48 /* internal mode values */
49 #define SMBC_XATTR_MODE_ADD 1
50 #define SMBC_XATTR_MODE_REMOVE 2
51 #define SMBC_XATTR_MODE_REMOVE_ALL 3
52 #define SMBC_XATTR_MODE_SET 4
53 #define SMBC_XATTR_MODE_CHOWN 5
54 #define SMBC_XATTR_MODE_CHGRP 6
56 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
58 /*We should test for this in configure ... */
59 #ifndef ENOTSUP
60 #define ENOTSUP EOPNOTSUPP
61 #endif
64 * Functions exported by libsmb_cache.c that we need here
66 int smbc_default_cache_functions(SMBCCTX *context);
68 /*
69 * check if an element is part of the list.
70 * FIXME: Does not belong here !
71 * Can anyone put this in a macro in dlinklist.h ?
72 * -- Tom
74 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
75 if (!p || !list) return False;
76 do {
77 if (p == list) return True;
78 list = list->next;
79 } while (list);
80 return False;
84 * Find an lsa pipe handle associated with a cli struct.
86 static struct rpc_pipe_client *
87 find_lsa_pipe_hnd(struct cli_state *ipc_cli)
89 struct rpc_pipe_client *pipe_hnd;
91 for (pipe_hnd = ipc_cli->pipe_list;
92 pipe_hnd;
93 pipe_hnd = pipe_hnd->next) {
95 if (pipe_hnd->pipe_idx == PI_LSARPC) {
96 return pipe_hnd;
100 return NULL;
103 static int
104 smbc_close_ctx(SMBCCTX *context,
105 SMBCFILE *file);
106 static off_t
107 smbc_lseek_ctx(SMBCCTX *context,
108 SMBCFILE *file,
109 off_t offset,
110 int whence);
112 extern BOOL in_client;
115 * Is the logging working / configfile read ?
117 static int smbc_initialized = 0;
119 static int
120 hex2int( unsigned int _char )
122 if ( _char >= 'A' && _char <='F')
123 return _char - 'A' + 10;
124 if ( _char >= 'a' && _char <='f')
125 return _char - 'a' + 10;
126 if ( _char >= '0' && _char <='9')
127 return _char - '0';
128 return -1;
132 * smbc_urldecode()
134 * Convert strings of %xx to their single character equivalent. Each 'x' must
135 * be a valid hexadecimal digit, or that % sequence is left undecoded.
137 * dest may, but need not be, the same pointer as src.
139 * Returns the number of % sequences which could not be converted due to lack
140 * of two following hexadecimal digits.
143 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
145 int old_length = strlen(src);
146 int i = 0;
147 int err_count = 0;
148 pstring temp;
149 char * p;
151 if ( old_length == 0 ) {
152 return 0;
155 p = temp;
156 while ( i < old_length ) {
157 unsigned char character = src[ i++ ];
159 if (character == '%') {
160 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
161 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
163 /* Replace valid sequence */
164 if (a != -1 && b != -1) {
166 /* Replace valid %xx sequence with %dd */
167 character = (a * 16) + b;
169 if (character == '\0') {
170 break; /* Stop at %00 */
173 i += 2;
174 } else {
176 err_count++;
180 *p++ = character;
183 *p = '\0';
185 strncpy(dest, temp, max_dest_len - 1);
186 dest[max_dest_len - 1] = '\0';
188 return err_count;
192 * smbc_urlencode()
194 * Convert any characters not specifically allowed in a URL into their %xx
195 * equivalent.
197 * Returns the remaining buffer length.
200 smbc_urlencode(char * dest, char * src, int max_dest_len)
202 char hex[] = "0123456789ABCDEF";
204 for (; *src != '\0' && max_dest_len >= 3; src++) {
206 if ((*src < '0' &&
207 *src != '-' &&
208 *src != '.') ||
209 (*src > '9' &&
210 *src < 'A') ||
211 (*src > 'Z' &&
212 *src < 'a' &&
213 *src != '_') ||
214 (*src > 'z')) {
215 *dest++ = '%';
216 *dest++ = hex[(*src >> 4) & 0x0f];
217 *dest++ = hex[*src & 0x0f];
218 max_dest_len -= 3;
219 } else {
220 *dest++ = *src;
221 max_dest_len--;
225 *dest++ = '\0';
226 max_dest_len--;
228 return max_dest_len;
232 * Function to parse a path and turn it into components
234 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
235 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
236 * general format ("smb:" only; we do not look for "cifs:").
239 * We accept:
240 * smb://[[[domain;]user[:password]@]server[/share[/path[/file]]]][?options]
242 * Meaning of URLs:
244 * smb:// Show all workgroups.
246 * The method of locating the list of workgroups varies
247 * depending upon the setting of the context variable
248 * context->options.browse_max_lmb_count. This value
249 * determine the maximum number of local master browsers to
250 * query for the list of workgroups. In order to ensure that
251 * a complete list of workgroups is obtained, all master
252 * browsers must be queried, but if there are many
253 * workgroups, the time spent querying can begin to add up.
254 * For small networks (not many workgroups), it is suggested
255 * that this variable be set to 0, indicating query all local
256 * master browsers. When the network has many workgroups, a
257 * reasonable setting for this variable might be around 3.
259 * smb://name/ if name<1D> or name<1B> exists, list servers in
260 * workgroup, else, if name<20> exists, list all shares
261 * for server ...
263 * If "options" are provided, this function returns the entire option list as a
264 * string, for later parsing by the caller. Note that currently, no options
265 * are supported.
268 static const char *smbc_prefix = "smb:";
270 static int
271 smbc_parse_path(SMBCCTX *context,
272 const char *fname,
273 char *workgroup, int workgroup_len,
274 char *server, int server_len,
275 char *share, int share_len,
276 char *path, int path_len,
277 char *user, int user_len,
278 char *password, int password_len,
279 char *options, int options_len)
281 static pstring s;
282 pstring userinfo;
283 const char *p;
284 char *q, *r;
285 int len;
287 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
290 * Assume we wont find an authentication domain to parse, so default
291 * to the workgroup in the provided context.
293 if (workgroup != NULL) {
294 strncpy(workgroup, context->workgroup, workgroup_len - 1);
295 workgroup[workgroup_len - 1] = '\0';
298 if (options != NULL && options_len > 0) {
299 options[0] = (char)0;
301 pstrcpy(s, fname);
303 /* see if it has the right prefix */
304 len = strlen(smbc_prefix);
305 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
306 return -1; /* What about no smb: ? */
309 p = s + len;
311 /* Watch the test below, we are testing to see if we should exit */
313 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
315 DEBUG(1, ("Invalid path (does not begin with smb://"));
316 return -1;
320 p += 2; /* Skip the double slash */
322 /* See if any options were specified */
323 if ((q = strrchr(p, '?')) != NULL ) {
324 /* There are options. Null terminate here and point to them */
325 *q++ = '\0';
327 DEBUG(4, ("Found options '%s'", q));
329 /* Copy the options */
330 if (options != NULL && options_len > 0) {
331 safe_strcpy(options, q, options_len - 1);
335 if (*p == (char)0)
336 goto decoding;
338 if (*p == '/') {
340 strncpy(server, context->workgroup,
341 ((strlen(context->workgroup) < 16)
342 ? strlen(context->workgroup)
343 : 16));
344 server[server_len - 1] = '\0';
345 return 0;
350 * ok, its for us. Now parse out the server, share etc.
352 * However, we want to parse out [[domain;]user[:password]@] if it
353 * exists ...
356 /* check that '@' occurs before '/', if '/' exists at all */
357 q = strchr_m(p, '@');
358 r = strchr_m(p, '/');
359 if (q && (!r || q < r)) {
360 pstring username, passwd, domain;
361 const char *u = userinfo;
363 next_token_no_ltrim(&p, userinfo, "@", sizeof(fstring));
365 username[0] = passwd[0] = domain[0] = 0;
367 if (strchr_m(u, ';')) {
369 next_token_no_ltrim(&u, domain, ";", sizeof(fstring));
373 if (strchr_m(u, ':')) {
375 next_token_no_ltrim(&u, username, ":", sizeof(fstring));
377 pstrcpy(passwd, u);
380 else {
382 pstrcpy(username, u);
386 if (domain[0] && workgroup) {
387 strncpy(workgroup, domain, workgroup_len - 1);
388 workgroup[workgroup_len - 1] = '\0';
391 if (username[0]) {
392 strncpy(user, username, user_len - 1);
393 user[user_len - 1] = '\0';
396 if (passwd[0]) {
397 strncpy(password, passwd, password_len - 1);
398 password[password_len - 1] = '\0';
403 if (!next_token(&p, server, "/", sizeof(fstring))) {
405 return -1;
409 if (*p == (char)0) goto decoding; /* That's it ... */
411 if (!next_token(&p, share, "/", sizeof(fstring))) {
413 return -1;
418 * Prepend a leading slash if there's a file path, as required by
419 * NetApp filers.
421 *path = '\0';
422 if (*p != '\0') {
423 *path = '/';
424 safe_strcpy(path + 1, p, path_len - 2);
427 all_string_sub(path, "/", "\\", 0);
429 decoding:
430 (void) smbc_urldecode(path, path, path_len);
431 (void) smbc_urldecode(server, server, server_len);
432 (void) smbc_urldecode(share, share, share_len);
433 (void) smbc_urldecode(user, user, user_len);
434 (void) smbc_urldecode(password, password, password_len);
436 return 0;
440 * Verify that the options specified in a URL are valid
442 static int
443 smbc_check_options(char *server,
444 char *share,
445 char *path,
446 char *options)
448 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' "
449 "path='%s' options='%s'\n",
450 server, share, path, options));
452 /* No options at all is always ok */
453 if (! *options) return 0;
455 /* Currently, we don't support any options. */
456 return -1;
460 * Convert an SMB error into a UNIX error ...
462 static int
463 smbc_errno(SMBCCTX *context,
464 struct cli_state *c)
466 int ret = cli_errno(c);
468 if (cli_is_dos_error(c)) {
469 uint8 eclass;
470 uint32 ecode;
472 cli_dos_error(c, &eclass, &ecode);
474 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
475 (int)eclass, (int)ecode, (int)ecode, ret));
476 } else {
477 NTSTATUS status;
479 status = cli_nt_error(c);
481 DEBUG(3,("smbc errno %s -> %d\n",
482 nt_errstr(status), ret));
485 return ret;
489 * Check a server for being alive and well.
490 * returns 0 if the server is in shape. Returns 1 on error
492 * Also useable outside libsmbclient to enable external cache
493 * to do some checks too.
495 static int
496 smbc_check_server(SMBCCTX * context,
497 SMBCSRV * server)
499 if ( send_keepalive(server->cli->fd) == False )
500 return 1;
502 /* connection is ok */
503 return 0;
507 * Remove a server from the cached server list it's unused.
508 * On success, 0 is returned. 1 is returned if the server could not be removed.
510 * Also useable outside libsmbclient
513 smbc_remove_unused_server(SMBCCTX * context,
514 SMBCSRV * srv)
516 SMBCFILE * file;
518 /* are we being fooled ? */
519 if (!context || !context->internal ||
520 !context->internal->_initialized || !srv) return 1;
523 /* Check all open files/directories for a relation with this server */
524 for (file = context->internal->_files; file; file=file->next) {
525 if (file->srv == srv) {
526 /* Still used */
527 DEBUG(3, ("smbc_remove_usused_server: "
528 "%p still used by %p.\n",
529 srv, file));
530 return 1;
534 DLIST_REMOVE(context->internal->_servers, srv);
536 cli_shutdown(srv->cli);
537 srv->cli = NULL;
539 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
541 context->callbacks.remove_cached_srv_fn(context, srv);
543 SAFE_FREE(srv);
545 return 0;
548 static SMBCSRV *
549 find_server(SMBCCTX *context,
550 const char *server,
551 const char *share,
552 fstring workgroup,
553 fstring username,
554 fstring password)
556 SMBCSRV *srv;
557 int auth_called = 0;
559 check_server_cache:
561 srv = context->callbacks.get_cached_srv_fn(context, server, share,
562 workgroup, username);
564 if (!auth_called && !srv && (!username[0] || !password[0])) {
565 if (context->internal->_auth_fn_with_context != NULL) {
566 context->internal->_auth_fn_with_context(
567 context,
568 server, share,
569 workgroup, sizeof(fstring),
570 username, sizeof(fstring),
571 password, sizeof(fstring));
572 } else {
573 context->callbacks.auth_fn(
574 server, share,
575 workgroup, sizeof(fstring),
576 username, sizeof(fstring),
577 password, sizeof(fstring));
581 * However, smbc_auth_fn may have picked up info relating to
582 * an existing connection, so try for an existing connection
583 * again ...
585 auth_called = 1;
586 goto check_server_cache;
590 if (srv) {
591 if (context->callbacks.check_server_fn(context, srv)) {
593 * This server is no good anymore
594 * Try to remove it and check for more possible
595 * servers in the cache
597 if (context->callbacks.remove_unused_server_fn(context,
598 srv)) {
600 * We could not remove the server completely,
601 * remove it from the cache so we will not get
602 * it again. It will be removed when the last
603 * file/dir is closed.
605 context->callbacks.remove_cached_srv_fn(context,
606 srv);
610 * Maybe there are more cached connections to this
611 * server
613 goto check_server_cache;
616 return srv;
619 return NULL;
623 * Connect to a server, possibly on an existing connection
625 * Here, what we want to do is: If the server and username
626 * match an existing connection, reuse that, otherwise, establish a
627 * new connection.
629 * If we have to create a new connection, call the auth_fn to get the
630 * info we need, unless the username and password were passed in.
633 static SMBCSRV *
634 smbc_server(SMBCCTX *context,
635 BOOL connect_if_not_found,
636 const char *server,
637 const char *share,
638 fstring workgroup,
639 fstring username,
640 fstring password)
642 SMBCSRV *srv=NULL;
643 struct cli_state *c;
644 struct nmb_name called, calling;
645 const char *server_n = server;
646 pstring ipenv;
647 struct in_addr ip;
648 int tried_reverse = 0;
649 int port_try_first;
650 int port_try_next;
651 const char *username_used;
653 zero_ip(&ip);
654 ZERO_STRUCT(c);
656 if (server[0] == 0) {
657 errno = EPERM;
658 return NULL;
661 /* Look for a cached connection */
662 srv = find_server(context, server, share,
663 workgroup, username, password);
666 * If we found a connection and we're only allowed one share per
667 * server...
669 if (srv && *share != '\0' && context->options.one_share_per_server) {
672 * ... then if there's no current connection to the share,
673 * connect to it. find_server(), or rather the function
674 * pointed to by context->callbacks.get_cached_srv_fn which
675 * was called by find_server(), will have issued a tree
676 * disconnect if the requested share is not the same as the
677 * one that was already connected.
679 if (srv->cli->cnum == (uint16) -1) {
680 /* Ensure we have accurate auth info */
681 if (context->internal->_auth_fn_with_context != NULL) {
682 context->internal->_auth_fn_with_context(
683 context,
684 server, share,
685 workgroup, sizeof(fstring),
686 username, sizeof(fstring),
687 password, sizeof(fstring));
688 } else {
689 context->callbacks.auth_fn(
690 server, share,
691 workgroup, sizeof(fstring),
692 username, sizeof(fstring),
693 password, sizeof(fstring));
696 if (! cli_send_tconX(srv->cli, share, "?????",
697 password, strlen(password)+1)) {
699 errno = smbc_errno(context, srv->cli);
700 cli_shutdown(srv->cli);
701 srv->cli = NULL;
702 context->callbacks.remove_cached_srv_fn(context,
703 srv);
704 srv = NULL;
708 * Regenerate the dev value since it's based on both
709 * server and share
711 if (srv) {
712 srv->dev = (dev_t)(str_checksum(server) ^
713 str_checksum(share));
718 /* If we have a connection... */
719 if (srv) {
721 /* ... then we're done here. Give 'em what they came for. */
722 return srv;
725 /* If we're not asked to connect when a connection doesn't exist... */
726 if (! connect_if_not_found) {
727 /* ... then we're done here. */
728 return NULL;
731 make_nmb_name(&calling, context->netbios_name, 0x0);
732 make_nmb_name(&called , server, 0x20);
734 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
736 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
738 again:
739 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
741 zero_ip(&ip);
743 /* have to open a new connection */
744 if ((c = cli_initialise()) == NULL) {
745 errno = ENOMEM;
746 return NULL;
749 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
750 c->use_kerberos = True;
752 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
753 c->fallback_after_kerberos = True;
756 c->timeout = context->timeout;
759 * Force use of port 139 for first try if share is $IPC, empty, or
760 * null, so browse lists can work
762 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
763 port_try_first = 139;
764 port_try_next = 445;
765 } else {
766 port_try_first = 445;
767 port_try_next = 139;
770 c->port = port_try_first;
772 if (!cli_connect(c, server_n, &ip)) {
774 /* First connection attempt failed. Try alternate port. */
775 c->port = port_try_next;
777 if (!cli_connect(c, server_n, &ip)) {
778 cli_shutdown(c);
779 errno = ETIMEDOUT;
780 return NULL;
784 if (!cli_session_request(c, &calling, &called)) {
785 cli_shutdown(c);
786 if (strcmp(called.name, "*SMBSERVER")) {
787 make_nmb_name(&called , "*SMBSERVER", 0x20);
788 goto again;
789 } else { /* Try one more time, but ensure we don't loop */
791 /* Only try this if server is an IP address ... */
793 if (is_ipaddress(server) && !tried_reverse) {
794 fstring remote_name;
795 struct in_addr rem_ip;
797 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
798 DEBUG(4, ("Could not convert IP address "
799 "%s to struct in_addr\n", server));
800 errno = ETIMEDOUT;
801 return NULL;
804 tried_reverse++; /* Yuck */
806 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
807 make_nmb_name(&called, remote_name, 0x20);
808 goto again;
812 errno = ETIMEDOUT;
813 return NULL;
816 DEBUG(4,(" session request ok\n"));
818 if (!cli_negprot(c)) {
819 cli_shutdown(c);
820 errno = ETIMEDOUT;
821 return NULL;
824 username_used = username;
826 if (!NT_STATUS_IS_OK(cli_session_setup(c, username_used,
827 password, strlen(password),
828 password, strlen(password),
829 workgroup))) {
831 /* Failed. Try an anonymous login, if allowed by flags. */
832 username_used = "";
834 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
835 !NT_STATUS_IS_OK(cli_session_setup(c, username_used,
836 password, 1,
837 password, 0,
838 workgroup))) {
840 cli_shutdown(c);
841 errno = EPERM;
842 return NULL;
846 DEBUG(4,(" session setup ok\n"));
848 if (!cli_send_tconX(c, share, "?????",
849 password, strlen(password)+1)) {
850 errno = smbc_errno(context, c);
851 cli_shutdown(c);
852 return NULL;
855 DEBUG(4,(" tconx ok\n"));
858 * Ok, we have got a nice connection
859 * Let's allocate a server structure.
862 srv = SMB_MALLOC_P(SMBCSRV);
863 if (!srv) {
864 errno = ENOMEM;
865 goto failed;
868 ZERO_STRUCTP(srv);
869 srv->cli = c;
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) {
897 return NULL;
900 SAFE_FREE(srv);
901 return NULL;
905 * Connect to a server for getting/setting attributes, possibly on an existing
906 * connection. This works similarly to smbc_server().
908 static SMBCSRV *
909 smbc_attr_server(SMBCCTX *context,
910 const char *server,
911 const char *share,
912 fstring workgroup,
913 fstring username,
914 fstring password,
915 POLICY_HND *pol)
917 struct in_addr ip;
918 struct cli_state *ipc_cli;
919 struct rpc_pipe_client *pipe_hnd;
920 NTSTATUS nt_status;
921 SMBCSRV *ipc_srv=NULL;
924 * See if we've already created this special connection. Reference
925 * our "special" share name '*IPC$', which is an impossible real share
926 * name due to the leading asterisk.
928 ipc_srv = find_server(context, server, "*IPC$",
929 workgroup, username, password);
930 if (!ipc_srv) {
932 /* We didn't find a cached connection. Get the password */
933 if (*password == '\0') {
934 /* ... then retrieve it now. */
935 if (context->internal->_auth_fn_with_context != NULL) {
936 context->internal->_auth_fn_with_context(
937 context,
938 server, share,
939 workgroup, sizeof(fstring),
940 username, sizeof(fstring),
941 password, sizeof(fstring));
942 } else {
943 context->callbacks.auth_fn(
944 server, share,
945 workgroup, sizeof(fstring),
946 username, sizeof(fstring),
947 password, sizeof(fstring));
951 zero_ip(&ip);
952 nt_status = cli_full_connection(&ipc_cli,
953 global_myname(), server,
954 &ip, 0, "IPC$", "?????",
955 username, workgroup,
956 password, 0,
957 Undefined, NULL);
958 if (! NT_STATUS_IS_OK(nt_status)) {
959 DEBUG(1,("cli_full_connection failed! (%s)\n",
960 nt_errstr(nt_status)));
961 errno = ENOTSUP;
962 return NULL;
965 ipc_srv = SMB_MALLOC_P(SMBCSRV);
966 if (!ipc_srv) {
967 errno = ENOMEM;
968 cli_shutdown(ipc_cli);
969 return NULL;
972 ZERO_STRUCTP(ipc_srv);
973 ipc_srv->cli = ipc_cli;
975 if (pol) {
976 pipe_hnd = cli_rpc_pipe_open_noauth(ipc_srv->cli,
977 PI_LSARPC,
978 &nt_status);
979 if (!pipe_hnd) {
980 DEBUG(1, ("cli_nt_session_open fail!\n"));
981 errno = ENOTSUP;
982 cli_shutdown(ipc_srv->cli);
983 free(ipc_srv);
984 return NULL;
988 * Some systems don't support
989 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
990 * so we might as well do it too.
993 nt_status = rpccli_lsa_open_policy(
994 pipe_hnd,
995 ipc_srv->cli->mem_ctx,
996 True,
997 GENERIC_EXECUTE_ACCESS,
998 pol);
1000 if (!NT_STATUS_IS_OK(nt_status)) {
1001 errno = smbc_errno(context, ipc_srv->cli);
1002 cli_shutdown(ipc_srv->cli);
1003 return NULL;
1007 /* now add it to the cache (internal or external) */
1009 errno = 0; /* let cache function set errno if it likes */
1010 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
1011 server,
1012 "*IPC$",
1013 workgroup,
1014 username)) {
1015 DEBUG(3, (" Failed to add server to cache\n"));
1016 if (errno == 0) {
1017 errno = ENOMEM;
1019 cli_shutdown(ipc_srv->cli);
1020 free(ipc_srv);
1021 return NULL;
1024 DLIST_ADD(context->internal->_servers, ipc_srv);
1027 return ipc_srv;
1031 * Routine to open() a file ...
1034 static SMBCFILE *
1035 smbc_open_ctx(SMBCCTX *context,
1036 const char *fname,
1037 int flags,
1038 mode_t mode)
1040 fstring server, share, user, password, workgroup;
1041 pstring path;
1042 pstring targetpath;
1043 struct cli_state *targetcli;
1044 SMBCSRV *srv = NULL;
1045 SMBCFILE *file = NULL;
1046 int fd;
1048 if (!context || !context->internal ||
1049 !context->internal->_initialized) {
1051 errno = EINVAL; /* Best I can think of ... */
1052 return NULL;
1056 if (!fname) {
1058 errno = EINVAL;
1059 return NULL;
1063 if (smbc_parse_path(context, fname,
1064 workgroup, sizeof(workgroup),
1065 server, sizeof(server),
1066 share, sizeof(share),
1067 path, sizeof(path),
1068 user, sizeof(user),
1069 password, sizeof(password),
1070 NULL, 0)) {
1071 errno = EINVAL;
1072 return NULL;
1075 if (user[0] == (char)0) fstrcpy(user, context->user);
1077 srv = smbc_server(context, True,
1078 server, share, workgroup, user, password);
1080 if (!srv) {
1082 if (errno == EPERM) errno = EACCES;
1083 return NULL; /* smbc_server sets errno */
1087 /* Hmmm, the test for a directory is suspect here ... FIXME */
1089 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1091 fd = -1;
1094 else {
1096 file = SMB_MALLOC_P(SMBCFILE);
1098 if (!file) {
1100 errno = ENOMEM;
1101 return NULL;
1105 ZERO_STRUCTP(file);
1107 /*d_printf(">>>open: resolving %s\n", path);*/
1108 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1110 d_printf("Could not resolve %s\n", path);
1111 SAFE_FREE(file);
1112 return NULL;
1114 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1116 if ( targetcli->dfsroot )
1118 pstring temppath;
1119 pstrcpy(temppath, targetpath);
1120 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1123 if ((fd = cli_open(targetcli, targetpath, flags,
1124 context->internal->_share_mode)) < 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, (char *)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, (char *)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 struct timespec *create_time_ts,
1484 struct timespec *access_time_ts,
1485 struct timespec *write_time_ts,
1486 struct timespec *change_time_ts,
1487 SMB_INO_T *ino)
1489 pstring fixedpath;
1490 pstring targetpath;
1491 struct cli_state *targetcli;
1492 time_t write_time;
1494 if (!context || !context->internal ||
1495 !context->internal->_initialized) {
1497 errno = EINVAL;
1498 return -1;
1502 /* path fixup for . and .. */
1503 if (strequal(path, ".") || strequal(path, ".."))
1504 pstrcpy(fixedpath, "\\");
1505 else
1507 pstrcpy(fixedpath, path);
1508 trim_string(fixedpath, NULL, "\\..");
1509 trim_string(fixedpath, NULL, "\\.");
1511 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1513 if (!cli_resolve_path( "", srv->cli, fixedpath, &targetcli, targetpath))
1515 d_printf("Couldn't resolve %s\n", path);
1516 return False;
1519 if ( targetcli->dfsroot )
1521 pstring temppath;
1522 pstrcpy(temppath, targetpath);
1523 cli_dfs_make_full_path(targetpath, targetcli->desthost,
1524 targetcli->share, temppath);
1527 if (!srv->no_pathinfo2 &&
1528 cli_qpathinfo2(targetcli, targetpath,
1529 create_time_ts,
1530 access_time_ts,
1531 write_time_ts,
1532 change_time_ts,
1533 size, mode, ino)) {
1534 return True;
1537 /* if this is NT then don't bother with the getatr */
1538 if (targetcli->capabilities & CAP_NT_SMBS) {
1539 errno = EPERM;
1540 return False;
1543 if (cli_getatr(targetcli, targetpath, mode, size, &write_time)) {
1545 struct timespec w_time_ts;
1547 w_time_ts = convert_time_t_to_timespec(write_time);
1549 if (write_time_ts != NULL) {
1550 *write_time_ts = w_time_ts;
1553 if (create_time_ts != NULL) {
1554 *create_time_ts = w_time_ts;
1557 if (access_time_ts != NULL) {
1558 *access_time_ts = w_time_ts;
1561 if (change_time_ts != NULL) {
1562 *change_time_ts = w_time_ts;
1565 srv->no_pathinfo2 = True;
1566 return True;
1569 errno = EPERM;
1570 return False;
1575 * Set file info on an SMB server. Use setpathinfo call first. If that
1576 * fails, use setattrE..
1578 * Access and modification time parameters are always used and must be
1579 * provided. Create time, if zero, will be determined from the actual create
1580 * time of the file. If non-zero, the create time will be set as well.
1582 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1584 static BOOL
1585 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1586 time_t create_time,
1587 time_t access_time,
1588 time_t write_time,
1589 time_t change_time,
1590 uint16 mode)
1592 int fd;
1593 int ret;
1596 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1597 * modern function for "new code" to be using, and it works given a
1598 * filename rather than requiring that the file be opened to have its
1599 * attributes manipulated.
1601 if (srv->no_pathinfo ||
1602 ! cli_setpathinfo(srv->cli, path,
1603 create_time,
1604 access_time,
1605 write_time,
1606 change_time,
1607 mode)) {
1610 * setpathinfo is not supported; go to plan B.
1612 * cli_setatr() does not work on win98, and it also doesn't
1613 * support setting the access time (only the modification
1614 * time), so in all cases, we open the specified file and use
1615 * cli_setattrE() which should work on all OS versions, and
1616 * supports both times.
1619 /* Don't try {q,set}pathinfo() again, with this server */
1620 srv->no_pathinfo = True;
1622 /* Open the file */
1623 if ((fd = cli_open(srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1625 errno = smbc_errno(context, srv->cli);
1626 return -1;
1629 /* Set the new attributes */
1630 ret = cli_setattrE(srv->cli, fd,
1631 change_time,
1632 access_time,
1633 write_time);
1635 /* Close the file */
1636 cli_close(srv->cli, fd);
1639 * Unfortunately, setattrE() doesn't have a provision for
1640 * setting the access mode (attributes). We'll have to try
1641 * cli_setatr() for that, and with only this parameter, it
1642 * seems to work on win98.
1644 if (ret && mode != (uint16) -1) {
1645 ret = cli_setatr(srv->cli, path, mode, 0);
1648 if (! ret) {
1649 errno = smbc_errno(context, srv->cli);
1650 return False;
1654 return True;
1658 * Routine to unlink() a file
1661 static int
1662 smbc_unlink_ctx(SMBCCTX *context,
1663 const char *fname)
1665 fstring server, share, user, password, workgroup;
1666 pstring path, targetpath;
1667 struct cli_state *targetcli;
1668 SMBCSRV *srv = NULL;
1670 if (!context || !context->internal ||
1671 !context->internal->_initialized) {
1673 errno = EINVAL; /* Best I can think of ... */
1674 return -1;
1678 if (!fname) {
1680 errno = EINVAL;
1681 return -1;
1685 if (smbc_parse_path(context, fname,
1686 workgroup, sizeof(workgroup),
1687 server, sizeof(server),
1688 share, sizeof(share),
1689 path, sizeof(path),
1690 user, sizeof(user),
1691 password, sizeof(password),
1692 NULL, 0)) {
1693 errno = EINVAL;
1694 return -1;
1697 if (user[0] == (char)0) fstrcpy(user, context->user);
1699 srv = smbc_server(context, True,
1700 server, share, workgroup, user, password);
1702 if (!srv) {
1704 return -1; /* smbc_server sets errno */
1708 /*d_printf(">>>unlink: resolving %s\n", path);*/
1709 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1711 d_printf("Could not resolve %s\n", path);
1712 return -1;
1714 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1716 if (!cli_unlink(targetcli, targetpath)) {
1718 errno = smbc_errno(context, targetcli);
1720 if (errno == EACCES) { /* Check if the file is a directory */
1722 int saverr = errno;
1723 SMB_OFF_T size = 0;
1724 uint16 mode = 0;
1725 struct timespec write_time_ts;
1726 struct timespec access_time_ts;
1727 struct timespec change_time_ts;
1728 SMB_INO_T ino = 0;
1730 if (!smbc_getatr(context, srv, path, &mode, &size,
1731 NULL,
1732 &access_time_ts,
1733 &write_time_ts,
1734 &change_time_ts,
1735 &ino)) {
1737 /* Hmmm, bad error ... What? */
1739 errno = smbc_errno(context, targetcli);
1740 return -1;
1743 else {
1745 if (IS_DOS_DIR(mode))
1746 errno = EISDIR;
1747 else
1748 errno = saverr; /* Restore this */
1753 return -1;
1757 return 0; /* Success ... */
1762 * Routine to rename() a file
1765 static int
1766 smbc_rename_ctx(SMBCCTX *ocontext,
1767 const char *oname,
1768 SMBCCTX *ncontext,
1769 const char *nname)
1771 fstring server1;
1772 fstring share1;
1773 fstring server2;
1774 fstring share2;
1775 fstring user1;
1776 fstring user2;
1777 fstring password1;
1778 fstring password2;
1779 fstring workgroup;
1780 pstring path1;
1781 pstring path2;
1782 pstring targetpath1;
1783 pstring targetpath2;
1784 struct cli_state *targetcli1;
1785 struct cli_state *targetcli2;
1786 SMBCSRV *srv = NULL;
1788 if (!ocontext || !ncontext ||
1789 !ocontext->internal || !ncontext->internal ||
1790 !ocontext->internal->_initialized ||
1791 !ncontext->internal->_initialized) {
1793 errno = EINVAL; /* Best I can think of ... */
1794 return -1;
1798 if (!oname || !nname) {
1800 errno = EINVAL;
1801 return -1;
1805 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1807 smbc_parse_path(ocontext, oname,
1808 workgroup, sizeof(workgroup),
1809 server1, sizeof(server1),
1810 share1, sizeof(share1),
1811 path1, sizeof(path1),
1812 user1, sizeof(user1),
1813 password1, sizeof(password1),
1814 NULL, 0);
1816 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1818 smbc_parse_path(ncontext, nname,
1819 NULL, 0,
1820 server2, sizeof(server2),
1821 share2, sizeof(share2),
1822 path2, sizeof(path2),
1823 user2, sizeof(user2),
1824 password2, sizeof(password2),
1825 NULL, 0);
1827 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1829 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1830 strcmp(user1, user2)) {
1832 /* Can't rename across file systems, or users?? */
1834 errno = EXDEV;
1835 return -1;
1839 srv = smbc_server(ocontext, True,
1840 server1, share1, workgroup, user1, password1);
1841 if (!srv) {
1843 return -1;
1847 /*d_printf(">>>rename: resolving %s\n", path1);*/
1848 if (!cli_resolve_path( "", srv->cli, path1, &targetcli1, targetpath1))
1850 d_printf("Could not resolve %s\n", path1);
1851 return -1;
1853 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1854 /*d_printf(">>>rename: resolving %s\n", path2);*/
1855 if (!cli_resolve_path( "", srv->cli, path2, &targetcli2, targetpath2))
1857 d_printf("Could not resolve %s\n", path2);
1858 return -1;
1860 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1862 if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1863 strcmp(targetcli1->share, targetcli2->share))
1865 /* can't rename across file systems */
1867 errno = EXDEV;
1868 return -1;
1871 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1872 int eno = smbc_errno(ocontext, targetcli1);
1874 if (eno != EEXIST ||
1875 !cli_unlink(targetcli1, targetpath2) ||
1876 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1878 errno = eno;
1879 return -1;
1884 return 0; /* Success */
1889 * A routine to lseek() a file
1892 static off_t
1893 smbc_lseek_ctx(SMBCCTX *context,
1894 SMBCFILE *file,
1895 off_t offset,
1896 int whence)
1898 SMB_OFF_T size;
1899 fstring server, share, user, password;
1900 pstring path, targetpath;
1901 struct cli_state *targetcli;
1903 if (!context || !context->internal ||
1904 !context->internal->_initialized) {
1906 errno = EINVAL;
1907 return -1;
1911 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1913 errno = EBADF;
1914 return -1;
1918 if (!file->file) {
1920 errno = EINVAL;
1921 return -1; /* Can't lseek a dir ... */
1925 switch (whence) {
1926 case SEEK_SET:
1927 file->offset = offset;
1928 break;
1930 case SEEK_CUR:
1931 file->offset += offset;
1932 break;
1934 case SEEK_END:
1935 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1936 if (smbc_parse_path(context, file->fname,
1937 NULL, 0,
1938 server, sizeof(server),
1939 share, sizeof(share),
1940 path, sizeof(path),
1941 user, sizeof(user),
1942 password, sizeof(password),
1943 NULL, 0)) {
1945 errno = EINVAL;
1946 return -1;
1949 /*d_printf(">>>lseek: resolving %s\n", path);*/
1950 if (!cli_resolve_path("", file->srv->cli, path,
1951 &targetcli, targetpath))
1953 d_printf("Could not resolve %s\n", path);
1954 return -1;
1956 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1958 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1959 &size, NULL, NULL, NULL, NULL, NULL))
1961 SMB_OFF_T b_size = size;
1962 if (!cli_getattrE(targetcli, file->cli_fd,
1963 NULL, &b_size, NULL, NULL, NULL))
1965 errno = EINVAL;
1966 return -1;
1967 } else
1968 size = b_size;
1970 file->offset = size + offset;
1971 break;
1973 default:
1974 errno = EINVAL;
1975 break;
1979 return file->offset;
1984 * Generate an inode number from file name for those things that need it
1987 static ino_t
1988 smbc_inode(SMBCCTX *context,
1989 const char *name)
1992 if (!context || !context->internal ||
1993 !context->internal->_initialized) {
1995 errno = EINVAL;
1996 return -1;
2000 if (!*name) return 2; /* FIXME, why 2 ??? */
2001 return (ino_t)str_checksum(name);
2006 * Routine to put basic stat info into a stat structure ... Used by stat and
2007 * fstat below.
2010 static int
2011 smbc_setup_stat(SMBCCTX *context,
2012 struct stat *st,
2013 char *fname,
2014 SMB_OFF_T size,
2015 int mode)
2018 st->st_mode = 0;
2020 if (IS_DOS_DIR(mode)) {
2021 st->st_mode = SMBC_DIR_MODE;
2022 } else {
2023 st->st_mode = SMBC_FILE_MODE;
2026 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
2027 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
2028 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
2029 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
2031 st->st_size = size;
2032 #ifdef HAVE_STAT_ST_BLKSIZE
2033 st->st_blksize = 512;
2034 #endif
2035 #ifdef HAVE_STAT_ST_BLOCKS
2036 st->st_blocks = (size+511)/512;
2037 #endif
2038 st->st_uid = getuid();
2039 st->st_gid = getgid();
2041 if (IS_DOS_DIR(mode)) {
2042 st->st_nlink = 2;
2043 } else {
2044 st->st_nlink = 1;
2047 if (st->st_ino == 0) {
2048 st->st_ino = smbc_inode(context, fname);
2051 return True; /* FIXME: Is this needed ? */
2056 * Routine to stat a file given a name
2059 static int
2060 smbc_stat_ctx(SMBCCTX *context,
2061 const char *fname,
2062 struct stat *st)
2064 SMBCSRV *srv;
2065 fstring server;
2066 fstring share;
2067 fstring user;
2068 fstring password;
2069 fstring workgroup;
2070 pstring path;
2071 struct timespec write_time_ts;
2072 struct timespec access_time_ts;
2073 struct timespec change_time_ts;
2074 SMB_OFF_T size = 0;
2075 uint16 mode = 0;
2076 SMB_INO_T ino = 0;
2078 if (!context || !context->internal ||
2079 !context->internal->_initialized) {
2081 errno = EINVAL; /* Best I can think of ... */
2082 return -1;
2086 if (!fname) {
2088 errno = EINVAL;
2089 return -1;
2093 DEBUG(4, ("smbc_stat(%s)\n", fname));
2095 if (smbc_parse_path(context, fname,
2096 workgroup, sizeof(workgroup),
2097 server, sizeof(server),
2098 share, sizeof(share),
2099 path, sizeof(path),
2100 user, sizeof(user),
2101 password, sizeof(password),
2102 NULL, 0)) {
2103 errno = EINVAL;
2104 return -1;
2107 if (user[0] == (char)0) fstrcpy(user, context->user);
2109 srv = smbc_server(context, True,
2110 server, share, workgroup, user, password);
2112 if (!srv) {
2113 return -1; /* errno set by smbc_server */
2116 if (!smbc_getatr(context, srv, path, &mode, &size,
2117 NULL,
2118 &access_time_ts,
2119 &write_time_ts,
2120 &change_time_ts,
2121 &ino)) {
2123 errno = smbc_errno(context, srv->cli);
2124 return -1;
2128 st->st_ino = ino;
2130 smbc_setup_stat(context, st, path, size, mode);
2132 set_atimespec(st, access_time_ts);
2133 set_ctimespec(st, change_time_ts);
2134 set_mtimespec(st, write_time_ts);
2135 st->st_dev = srv->dev;
2137 return 0;
2142 * Routine to stat a file given an fd
2145 static int
2146 smbc_fstat_ctx(SMBCCTX *context,
2147 SMBCFILE *file,
2148 struct stat *st)
2150 struct timespec change_time_ts;
2151 struct timespec access_time_ts;
2152 struct timespec write_time_ts;
2153 SMB_OFF_T size;
2154 uint16 mode;
2155 fstring server;
2156 fstring share;
2157 fstring user;
2158 fstring password;
2159 pstring path;
2160 pstring targetpath;
2161 struct cli_state *targetcli;
2162 SMB_INO_T ino = 0;
2164 if (!context || !context->internal ||
2165 !context->internal->_initialized) {
2167 errno = EINVAL;
2168 return -1;
2172 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2174 errno = EBADF;
2175 return -1;
2179 if (!file->file) {
2181 return context->fstatdir(context, file, st);
2185 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2186 if (smbc_parse_path(context, file->fname,
2187 NULL, 0,
2188 server, sizeof(server),
2189 share, sizeof(share),
2190 path, sizeof(path),
2191 user, sizeof(user),
2192 password, sizeof(password),
2193 NULL, 0)) {
2194 errno = EINVAL;
2195 return -1;
2198 /*d_printf(">>>fstat: resolving %s\n", path);*/
2199 if (!cli_resolve_path("", file->srv->cli, path,
2200 &targetcli, targetpath))
2202 d_printf("Could not resolve %s\n", path);
2203 return -1;
2205 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2207 if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2208 NULL,
2209 &access_time_ts,
2210 &write_time_ts,
2211 &change_time_ts,
2212 &ino)) {
2214 time_t change_time, access_time, write_time;
2216 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2217 &change_time, &access_time, &write_time)) {
2219 errno = EINVAL;
2220 return -1;
2223 change_time_ts = convert_time_t_to_timespec(change_time);
2224 access_time_ts = convert_time_t_to_timespec(access_time);
2225 write_time_ts = convert_time_t_to_timespec(write_time);
2228 st->st_ino = ino;
2230 smbc_setup_stat(context, st, file->fname, size, mode);
2232 set_atimespec(st, access_time_ts);
2233 set_ctimespec(st, change_time_ts);
2234 set_mtimespec(st, write_time_ts);
2235 st->st_dev = file->srv->dev;
2237 return 0;
2242 * Routine to open a directory
2243 * We accept the URL syntax explained in smbc_parse_path(), above.
2246 static void
2247 smbc_remove_dir(SMBCFILE *dir)
2249 struct smbc_dir_list *d,*f;
2251 d = dir->dir_list;
2252 while (d) {
2254 f = d; d = d->next;
2256 SAFE_FREE(f->dirent);
2257 SAFE_FREE(f);
2261 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2265 static int
2266 add_dirent(SMBCFILE *dir,
2267 const char *name,
2268 const char *comment,
2269 uint32 type)
2271 struct smbc_dirent *dirent;
2272 int size;
2273 int name_length = (name == NULL ? 0 : strlen(name));
2274 int comment_len = (comment == NULL ? 0 : strlen(comment));
2277 * Allocate space for the dirent, which must be increased by the
2278 * size of the name and the comment and 1 each for the null terminator.
2281 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2283 dirent = (struct smbc_dirent *)SMB_MALLOC(size);
2285 if (!dirent) {
2287 dir->dir_error = ENOMEM;
2288 return -1;
2292 ZERO_STRUCTP(dirent);
2294 if (dir->dir_list == NULL) {
2296 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2297 if (!dir->dir_list) {
2299 SAFE_FREE(dirent);
2300 dir->dir_error = ENOMEM;
2301 return -1;
2304 ZERO_STRUCTP(dir->dir_list);
2306 dir->dir_end = dir->dir_next = dir->dir_list;
2308 else {
2310 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2312 if (!dir->dir_end->next) {
2314 SAFE_FREE(dirent);
2315 dir->dir_error = ENOMEM;
2316 return -1;
2319 ZERO_STRUCTP(dir->dir_end->next);
2321 dir->dir_end = dir->dir_end->next;
2324 dir->dir_end->next = NULL;
2325 dir->dir_end->dirent = dirent;
2327 dirent->smbc_type = type;
2328 dirent->namelen = name_length;
2329 dirent->commentlen = comment_len;
2330 dirent->dirlen = size;
2333 * dirent->namelen + 1 includes the null (no null termination needed)
2334 * Ditto for dirent->commentlen.
2335 * The space for the two null bytes was allocated.
2337 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2338 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2339 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2341 return 0;
2345 static void
2346 list_unique_wg_fn(const char *name,
2347 uint32 type,
2348 const char *comment,
2349 void *state)
2351 SMBCFILE *dir = (SMBCFILE *)state;
2352 struct smbc_dir_list *dir_list;
2353 struct smbc_dirent *dirent;
2354 int dirent_type;
2355 int do_remove = 0;
2357 dirent_type = dir->dir_type;
2359 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2361 /* An error occurred, what do we do? */
2362 /* FIXME: Add some code here */
2365 /* Point to the one just added */
2366 dirent = dir->dir_end->dirent;
2368 /* See if this was a duplicate */
2369 for (dir_list = dir->dir_list;
2370 dir_list != dir->dir_end;
2371 dir_list = dir_list->next) {
2372 if (! do_remove &&
2373 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2374 /* Duplicate. End end of list need to be removed. */
2375 do_remove = 1;
2378 if (do_remove && dir_list->next == dir->dir_end) {
2379 /* Found the end of the list. Remove it. */
2380 dir->dir_end = dir_list;
2381 free(dir_list->next);
2382 free(dirent);
2383 dir_list->next = NULL;
2384 break;
2389 static void
2390 list_fn(const char *name,
2391 uint32 type,
2392 const char *comment,
2393 void *state)
2395 SMBCFILE *dir = (SMBCFILE *)state;
2396 int dirent_type;
2399 * We need to process the type a little ...
2401 * Disk share = 0x00000000
2402 * Print share = 0x00000001
2403 * Comms share = 0x00000002 (obsolete?)
2404 * IPC$ share = 0x00000003
2406 * administrative shares:
2407 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2410 if (dir->dir_type == SMBC_FILE_SHARE) {
2412 switch (type) {
2413 case 0 | 0x80000000:
2414 case 0:
2415 dirent_type = SMBC_FILE_SHARE;
2416 break;
2418 case 1:
2419 dirent_type = SMBC_PRINTER_SHARE;
2420 break;
2422 case 2:
2423 dirent_type = SMBC_COMMS_SHARE;
2424 break;
2426 case 3 | 0x80000000:
2427 case 3:
2428 dirent_type = SMBC_IPC_SHARE;
2429 break;
2431 default:
2432 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2433 break;
2436 else {
2437 dirent_type = dir->dir_type;
2440 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2442 /* An error occurred, what do we do? */
2443 /* FIXME: Add some code here */
2448 static void
2449 dir_list_fn(const char *mnt,
2450 file_info *finfo,
2451 const char *mask,
2452 void *state)
2455 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2456 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2458 /* Handle an error ... */
2460 /* FIXME: Add some code ... */
2466 static int
2467 net_share_enum_rpc(struct cli_state *cli,
2468 void (*fn)(const char *name,
2469 uint32 type,
2470 const char *comment,
2471 void *state),
2472 void *state)
2474 int i;
2475 WERROR result;
2476 ENUM_HND enum_hnd;
2477 uint32 info_level = 1;
2478 uint32 preferred_len = 0xffffffff;
2479 uint32 type;
2480 SRV_SHARE_INFO_CTR ctr;
2481 fstring name = "";
2482 fstring comment = "";
2483 void *mem_ctx;
2484 struct rpc_pipe_client *pipe_hnd;
2485 NTSTATUS nt_status;
2487 /* Open the server service pipe */
2488 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2489 if (!pipe_hnd) {
2490 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2491 return -1;
2494 /* Allocate a context for parsing and for the entries in "ctr" */
2495 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2496 if (mem_ctx == NULL) {
2497 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2498 cli_rpc_pipe_close(pipe_hnd);
2499 return -1;
2502 /* Issue the NetShareEnum RPC call and retrieve the response */
2503 init_enum_hnd(&enum_hnd, 0);
2504 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2505 mem_ctx,
2506 info_level,
2507 &ctr,
2508 preferred_len,
2509 &enum_hnd);
2511 /* Was it successful? */
2512 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2513 /* Nope. Go clean up. */
2514 goto done;
2517 /* For each returned entry... */
2518 for (i = 0; i < ctr.num_entries; i++) {
2520 /* pull out the share name */
2521 rpcstr_pull_unistr2_fstring(
2522 name, &ctr.share.info1[i].info_1_str.uni_netname);
2524 /* pull out the share's comment */
2525 rpcstr_pull_unistr2_fstring(
2526 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2528 /* Get the type value */
2529 type = ctr.share.info1[i].info_1.type;
2531 /* Add this share to the list */
2532 (*fn)(name, type, comment, state);
2535 done:
2536 /* Close the server service pipe */
2537 cli_rpc_pipe_close(pipe_hnd);
2539 /* Free all memory which was allocated for this request */
2540 TALLOC_FREE(mem_ctx);
2542 /* Tell 'em if it worked */
2543 return W_ERROR_IS_OK(result) ? 0 : -1;
2548 static SMBCFILE *
2549 smbc_opendir_ctx(SMBCCTX *context,
2550 const char *fname)
2552 int saved_errno;
2553 fstring server, share, user, password, options;
2554 pstring workgroup;
2555 pstring path;
2556 uint16 mode;
2557 char *p;
2558 SMBCSRV *srv = NULL;
2559 SMBCFILE *dir = NULL;
2560 struct _smbc_callbacks *cb;
2561 struct in_addr rem_ip;
2563 if (!context || !context->internal ||
2564 !context->internal->_initialized) {
2565 DEBUG(4, ("no valid context\n"));
2566 errno = EINVAL + 8192;
2567 return NULL;
2571 if (!fname) {
2572 DEBUG(4, ("no valid fname\n"));
2573 errno = EINVAL + 8193;
2574 return NULL;
2577 if (smbc_parse_path(context, fname,
2578 workgroup, sizeof(workgroup),
2579 server, sizeof(server),
2580 share, sizeof(share),
2581 path, sizeof(path),
2582 user, sizeof(user),
2583 password, sizeof(password),
2584 options, sizeof(options))) {
2585 DEBUG(4, ("no valid path\n"));
2586 errno = EINVAL + 8194;
2587 return NULL;
2590 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2591 "path='%s' options='%s'\n",
2592 fname, server, share, path, options));
2594 /* Ensure the options are valid */
2595 if (smbc_check_options(server, share, path, options)) {
2596 DEBUG(4, ("unacceptable options (%s)\n", options));
2597 errno = EINVAL + 8195;
2598 return NULL;
2601 if (user[0] == (char)0) fstrcpy(user, context->user);
2603 dir = SMB_MALLOC_P(SMBCFILE);
2605 if (!dir) {
2607 errno = ENOMEM;
2608 return NULL;
2612 ZERO_STRUCTP(dir);
2614 dir->cli_fd = 0;
2615 dir->fname = SMB_STRDUP(fname);
2616 dir->srv = NULL;
2617 dir->offset = 0;
2618 dir->file = False;
2619 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2621 if (server[0] == (char)0) {
2623 int i;
2624 int count;
2625 int max_lmb_count;
2626 struct ip_service *ip_list;
2627 struct ip_service server_addr;
2628 struct user_auth_info u_info;
2629 struct cli_state *cli;
2631 if (share[0] != (char)0 || path[0] != (char)0) {
2633 errno = EINVAL + 8196;
2634 if (dir) {
2635 SAFE_FREE(dir->fname);
2636 SAFE_FREE(dir);
2638 return NULL;
2641 /* Determine how many local master browsers to query */
2642 max_lmb_count = (context->options.browse_max_lmb_count == 0
2643 ? INT_MAX
2644 : context->options.browse_max_lmb_count);
2646 pstrcpy(u_info.username, user);
2647 pstrcpy(u_info.password, password);
2650 * We have server and share and path empty but options
2651 * requesting that we scan all master browsers for their list
2652 * of workgroups/domains. This implies that we must first try
2653 * broadcast queries to find all master browsers, and if that
2654 * doesn't work, then try our other methods which return only
2655 * a single master browser.
2658 ip_list = NULL;
2659 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2661 SAFE_FREE(ip_list);
2663 if (!find_master_ip(workgroup, &server_addr.ip)) {
2665 if (dir) {
2666 SAFE_FREE(dir->fname);
2667 SAFE_FREE(dir);
2669 errno = ENOENT;
2670 return NULL;
2673 ip_list = &server_addr;
2674 count = 1;
2677 for (i = 0; i < count && i < max_lmb_count; i++) {
2678 DEBUG(99, ("Found master browser %d of %d: %s\n",
2679 i+1, MAX(count, max_lmb_count),
2680 inet_ntoa(ip_list[i].ip)));
2682 cli = get_ipc_connect_master_ip(&ip_list[i],
2683 workgroup, &u_info);
2684 /* cli == NULL is the master browser refused to talk or
2685 could not be found */
2686 if ( !cli )
2687 continue;
2689 fstrcpy(server, cli->desthost);
2690 cli_shutdown(cli);
2692 DEBUG(4, ("using workgroup %s %s\n",
2693 workgroup, server));
2696 * For each returned master browser IP address, get a
2697 * connection to IPC$ on the server if we do not
2698 * already have one, and determine the
2699 * workgroups/domains that it knows about.
2702 srv = smbc_server(context, True, server, "IPC$",
2703 workgroup, user, password);
2704 if (!srv) {
2705 continue;
2708 dir->srv = srv;
2709 dir->dir_type = SMBC_WORKGROUP;
2711 /* Now, list the stuff ... */
2713 if (!cli_NetServerEnum(srv->cli,
2714 workgroup,
2715 SV_TYPE_DOMAIN_ENUM,
2716 list_unique_wg_fn,
2717 (void *)dir)) {
2718 continue;
2722 SAFE_FREE(ip_list);
2723 } else {
2725 * Server not an empty string ... Check the rest and see what
2726 * gives
2728 if (*share == '\0') {
2729 if (*path != '\0') {
2731 /* Should not have empty share with path */
2732 errno = EINVAL + 8197;
2733 if (dir) {
2734 SAFE_FREE(dir->fname);
2735 SAFE_FREE(dir);
2737 return NULL;
2742 * We don't know if <server> is really a server name
2743 * or is a workgroup/domain name. If we already have
2744 * a server structure for it, we'll use it.
2745 * Otherwise, check to see if <server><1D>,
2746 * <server><1B>, or <server><20> translates. We check
2747 * to see if <server> is an IP address first.
2751 * See if we have an existing server. Do not
2752 * establish a connection if one does not already
2753 * exist.
2755 srv = smbc_server(context, False, server, "IPC$",
2756 workgroup, user, password);
2759 * If no existing server and not an IP addr, look for
2760 * LMB or DMB
2762 if (!srv &&
2763 !is_ipaddress(server) &&
2764 (resolve_name(server, &rem_ip, 0x1d) || /* LMB */
2765 resolve_name(server, &rem_ip, 0x1b) )) { /* DMB */
2767 fstring buserver;
2769 dir->dir_type = SMBC_SERVER;
2772 * Get the backup list ...
2774 if (!name_status_find(server, 0, 0,
2775 rem_ip, buserver)) {
2777 DEBUG(0, ("Could not get name of "
2778 "local/domain master browser "
2779 "for server %s\n", server));
2780 if (dir) {
2781 SAFE_FREE(dir->fname);
2782 SAFE_FREE(dir);
2784 errno = EPERM;
2785 return NULL;
2790 * Get a connection to IPC$ on the server if
2791 * we do not already have one
2793 srv = smbc_server(context, True,
2794 buserver, "IPC$",
2795 workgroup, user, password);
2796 if (!srv) {
2797 DEBUG(0, ("got no contact to IPC$\n"));
2798 if (dir) {
2799 SAFE_FREE(dir->fname);
2800 SAFE_FREE(dir);
2802 return NULL;
2806 dir->srv = srv;
2808 /* Now, list the servers ... */
2809 if (!cli_NetServerEnum(srv->cli, server,
2810 0x0000FFFE, list_fn,
2811 (void *)dir)) {
2813 if (dir) {
2814 SAFE_FREE(dir->fname);
2815 SAFE_FREE(dir);
2817 return NULL;
2819 } else if (srv ||
2820 (resolve_name(server, &rem_ip, 0x20))) {
2822 /* If we hadn't found the server, get one now */
2823 if (!srv) {
2824 srv = smbc_server(context, True,
2825 server, "IPC$",
2826 workgroup,
2827 user, password);
2830 if (!srv) {
2831 if (dir) {
2832 SAFE_FREE(dir->fname);
2833 SAFE_FREE(dir);
2835 return NULL;
2839 dir->dir_type = SMBC_FILE_SHARE;
2840 dir->srv = srv;
2842 /* List the shares ... */
2844 if (net_share_enum_rpc(
2845 srv->cli,
2846 list_fn,
2847 (void *) dir) < 0 &&
2848 cli_RNetShareEnum(
2849 srv->cli,
2850 list_fn,
2851 (void *)dir) < 0) {
2853 errno = cli_errno(srv->cli);
2854 if (dir) {
2855 SAFE_FREE(dir->fname);
2856 SAFE_FREE(dir);
2858 return NULL;
2861 } else {
2862 /* Neither the workgroup nor server exists */
2863 errno = ECONNREFUSED;
2864 if (dir) {
2865 SAFE_FREE(dir->fname);
2866 SAFE_FREE(dir);
2868 return NULL;
2872 else {
2874 * The server and share are specified ... work from
2875 * there ...
2877 pstring targetpath;
2878 struct cli_state *targetcli;
2880 /* We connect to the server and list the directory */
2881 dir->dir_type = SMBC_FILE_SHARE;
2883 srv = smbc_server(context, True, server, share,
2884 workgroup, user, password);
2886 if (!srv) {
2888 if (dir) {
2889 SAFE_FREE(dir->fname);
2890 SAFE_FREE(dir);
2892 return NULL;
2896 dir->srv = srv;
2898 /* Now, list the files ... */
2900 p = path + strlen(path);
2901 pstrcat(path, "\\*");
2903 if (!cli_resolve_path("", srv->cli, path,
2904 &targetcli, targetpath))
2906 d_printf("Could not resolve %s\n", path);
2907 if (dir) {
2908 SAFE_FREE(dir->fname);
2909 SAFE_FREE(dir);
2911 return NULL;
2914 if (cli_list(targetcli, targetpath,
2915 aDIR | aSYSTEM | aHIDDEN,
2916 dir_list_fn, (void *)dir) < 0) {
2918 if (dir) {
2919 SAFE_FREE(dir->fname);
2920 SAFE_FREE(dir);
2922 saved_errno = smbc_errno(context, targetcli);
2924 if (saved_errno == EINVAL) {
2926 * See if they asked to opendir something
2927 * other than a directory. If so, the
2928 * converted error value we got would have
2929 * been EINVAL rather than ENOTDIR.
2931 *p = '\0'; /* restore original path */
2933 if (smbc_getatr(context, srv, path,
2934 &mode, NULL,
2935 NULL, NULL, NULL, NULL,
2936 NULL) &&
2937 ! IS_DOS_DIR(mode)) {
2939 /* It is. Correct the error value */
2940 saved_errno = ENOTDIR;
2945 * If there was an error and the server is no
2946 * good any more...
2948 cb = &context->callbacks;
2949 if (cli_is_error(targetcli) &&
2950 cb->check_server_fn(context, srv)) {
2952 /* ... then remove it. */
2953 if (cb->remove_unused_server_fn(context,
2954 srv)) {
2956 * We could not remove the server
2957 * completely, remove it from the
2958 * cache so we will not get it
2959 * again. It will be removed when the
2960 * last file/dir is closed.
2962 cb->remove_cached_srv_fn(context, srv);
2966 errno = saved_errno;
2967 return NULL;
2973 DLIST_ADD(context->internal->_files, dir);
2974 return dir;
2979 * Routine to close a directory
2982 static int
2983 smbc_closedir_ctx(SMBCCTX *context,
2984 SMBCFILE *dir)
2987 if (!context || !context->internal ||
2988 !context->internal->_initialized) {
2990 errno = EINVAL;
2991 return -1;
2995 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2997 errno = EBADF;
2998 return -1;
3002 smbc_remove_dir(dir); /* Clean it up */
3004 DLIST_REMOVE(context->internal->_files, dir);
3006 if (dir) {
3008 SAFE_FREE(dir->fname);
3009 SAFE_FREE(dir); /* Free the space too */
3012 return 0;
3016 static void
3017 smbc_readdir_internal(SMBCCTX * context,
3018 struct smbc_dirent *dest,
3019 struct smbc_dirent *src,
3020 int max_namebuf_len)
3022 if (context->options.urlencode_readdir_entries) {
3024 /* url-encode the name. get back remaining buffer space */
3025 max_namebuf_len =
3026 smbc_urlencode(dest->name, src->name, max_namebuf_len);
3028 /* We now know the name length */
3029 dest->namelen = strlen(dest->name);
3031 /* Save the pointer to the beginning of the comment */
3032 dest->comment = dest->name + dest->namelen + 1;
3034 /* Copy the comment */
3035 strncpy(dest->comment, src->comment, max_namebuf_len - 1);
3036 dest->comment[max_namebuf_len - 1] = '\0';
3038 /* Save other fields */
3039 dest->smbc_type = src->smbc_type;
3040 dest->commentlen = strlen(dest->comment);
3041 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
3042 (char *) dest);
3043 } else {
3045 /* No encoding. Just copy the entry as is. */
3046 memcpy(dest, src, src->dirlen);
3047 dest->comment = (char *)(&dest->name + src->namelen + 1);
3053 * Routine to get a directory entry
3056 struct smbc_dirent *
3057 smbc_readdir_ctx(SMBCCTX *context,
3058 SMBCFILE *dir)
3060 int maxlen;
3061 struct smbc_dirent *dirp, *dirent;
3063 /* Check that all is ok first ... */
3065 if (!context || !context->internal ||
3066 !context->internal->_initialized) {
3068 errno = EINVAL;
3069 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
3070 return NULL;
3074 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3076 errno = EBADF;
3077 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
3078 return NULL;
3082 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3084 errno = ENOTDIR;
3085 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
3086 return NULL;
3090 if (!dir->dir_next) {
3091 return NULL;
3094 dirent = dir->dir_next->dirent;
3095 if (!dirent) {
3097 errno = ENOENT;
3098 return NULL;
3102 dirp = (struct smbc_dirent *)context->internal->_dirent;
3103 maxlen = (sizeof(context->internal->_dirent) -
3104 sizeof(struct smbc_dirent));
3106 smbc_readdir_internal(context, dirp, dirent, maxlen);
3108 dir->dir_next = dir->dir_next->next;
3110 return dirp;
3114 * Routine to get directory entries
3117 static int
3118 smbc_getdents_ctx(SMBCCTX *context,
3119 SMBCFILE *dir,
3120 struct smbc_dirent *dirp,
3121 int count)
3123 int rem = count;
3124 int reqd;
3125 int maxlen;
3126 char *ndir = (char *)dirp;
3127 struct smbc_dir_list *dirlist;
3129 /* Check that all is ok first ... */
3131 if (!context || !context->internal ||
3132 !context->internal->_initialized) {
3134 errno = EINVAL;
3135 return -1;
3139 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3141 errno = EBADF;
3142 return -1;
3146 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3148 errno = ENOTDIR;
3149 return -1;
3154 * Now, retrieve the number of entries that will fit in what was passed
3155 * We have to figure out if the info is in the list, or we need to
3156 * send a request to the server to get the info.
3159 while ((dirlist = dir->dir_next)) {
3160 struct smbc_dirent *dirent;
3162 if (!dirlist->dirent) {
3164 errno = ENOENT; /* Bad error */
3165 return -1;
3169 /* Do urlencoding of next entry, if so selected */
3170 dirent = (struct smbc_dirent *)context->internal->_dirent;
3171 maxlen = (sizeof(context->internal->_dirent) -
3172 sizeof(struct smbc_dirent));
3173 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3175 reqd = dirent->dirlen;
3177 if (rem < reqd) {
3179 if (rem < count) { /* We managed to copy something */
3181 errno = 0;
3182 return count - rem;
3185 else { /* Nothing copied ... */
3187 errno = EINVAL; /* Not enough space ... */
3188 return -1;
3194 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3196 ((struct smbc_dirent *)ndir)->comment =
3197 (char *)(&((struct smbc_dirent *)ndir)->name +
3198 dirent->namelen +
3201 ndir += reqd;
3203 rem -= reqd;
3205 dir->dir_next = dirlist = dirlist -> next;
3208 if (rem == count)
3209 return 0;
3210 else
3211 return count - rem;
3216 * Routine to create a directory ...
3219 static int
3220 smbc_mkdir_ctx(SMBCCTX *context,
3221 const char *fname,
3222 mode_t mode)
3224 SMBCSRV *srv;
3225 fstring server;
3226 fstring share;
3227 fstring user;
3228 fstring password;
3229 fstring workgroup;
3230 pstring path, targetpath;
3231 struct cli_state *targetcli;
3233 if (!context || !context->internal ||
3234 !context->internal->_initialized) {
3236 errno = EINVAL;
3237 return -1;
3241 if (!fname) {
3243 errno = EINVAL;
3244 return -1;
3248 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3250 if (smbc_parse_path(context, fname,
3251 workgroup, sizeof(workgroup),
3252 server, sizeof(server),
3253 share, sizeof(share),
3254 path, sizeof(path),
3255 user, sizeof(user),
3256 password, sizeof(password),
3257 NULL, 0)) {
3258 errno = EINVAL;
3259 return -1;
3262 if (user[0] == (char)0) fstrcpy(user, context->user);
3264 srv = smbc_server(context, True,
3265 server, share, workgroup, user, password);
3267 if (!srv) {
3269 return -1; /* errno set by smbc_server */
3273 /*d_printf(">>>mkdir: resolving %s\n", path);*/
3274 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
3276 d_printf("Could not resolve %s\n", path);
3277 return -1;
3279 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3281 if (!cli_mkdir(targetcli, targetpath)) {
3283 errno = smbc_errno(context, targetcli);
3284 return -1;
3288 return 0;
3293 * Our list function simply checks to see if a directory is not empty
3296 static int smbc_rmdir_dirempty = True;
3298 static void
3299 rmdir_list_fn(const char *mnt,
3300 file_info *finfo,
3301 const char *mask,
3302 void *state)
3304 if (strncmp(finfo->name, ".", 1) != 0 &&
3305 strncmp(finfo->name, "..", 2) != 0) {
3307 smbc_rmdir_dirempty = False;
3312 * Routine to remove a directory
3315 static int
3316 smbc_rmdir_ctx(SMBCCTX *context,
3317 const char *fname)
3319 SMBCSRV *srv;
3320 fstring server;
3321 fstring share;
3322 fstring user;
3323 fstring password;
3324 fstring workgroup;
3325 pstring path;
3326 pstring targetpath;
3327 struct cli_state *targetcli;
3329 if (!context || !context->internal ||
3330 !context->internal->_initialized) {
3332 errno = EINVAL;
3333 return -1;
3337 if (!fname) {
3339 errno = EINVAL;
3340 return -1;
3344 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3346 if (smbc_parse_path(context, fname,
3347 workgroup, sizeof(workgroup),
3348 server, sizeof(server),
3349 share, sizeof(share),
3350 path, sizeof(path),
3351 user, sizeof(user),
3352 password, sizeof(password),
3353 NULL, 0))
3355 errno = EINVAL;
3356 return -1;
3359 if (user[0] == (char)0) fstrcpy(user, context->user);
3361 srv = smbc_server(context, True,
3362 server, share, workgroup, user, password);
3364 if (!srv) {
3366 return -1; /* errno set by smbc_server */
3370 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3371 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
3373 d_printf("Could not resolve %s\n", path);
3374 return -1;
3376 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3379 if (!cli_rmdir(targetcli, targetpath)) {
3381 errno = smbc_errno(context, targetcli);
3383 if (errno == EACCES) { /* Check if the dir empty or not */
3385 /* Local storage to avoid buffer overflows */
3386 pstring lpath;
3388 smbc_rmdir_dirempty = True; /* Make this so ... */
3390 pstrcpy(lpath, targetpath);
3391 pstrcat(lpath, "\\*");
3393 if (cli_list(targetcli, lpath,
3394 aDIR | aSYSTEM | aHIDDEN,
3395 rmdir_list_fn, NULL) < 0) {
3397 /* Fix errno to ignore latest error ... */
3398 DEBUG(5, ("smbc_rmdir: "
3399 "cli_list returned an error: %d\n",
3400 smbc_errno(context, targetcli)));
3401 errno = EACCES;
3405 if (smbc_rmdir_dirempty)
3406 errno = EACCES;
3407 else
3408 errno = ENOTEMPTY;
3412 return -1;
3416 return 0;
3421 * Routine to return the current directory position
3424 static off_t
3425 smbc_telldir_ctx(SMBCCTX *context,
3426 SMBCFILE *dir)
3428 off_t ret_val; /* Squash warnings about cast */
3430 if (!context || !context->internal ||
3431 !context->internal->_initialized) {
3433 errno = EINVAL;
3434 return -1;
3438 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3440 errno = EBADF;
3441 return -1;
3445 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3447 errno = ENOTDIR;
3448 return -1;
3453 * We return the pointer here as the offset
3455 ret_val = (off_t)(long)dir->dir_next;
3456 return ret_val;
3461 * A routine to run down the list and see if the entry is OK
3464 struct smbc_dir_list *
3465 smbc_check_dir_ent(struct smbc_dir_list *list,
3466 struct smbc_dirent *dirent)
3469 /* Run down the list looking for what we want */
3471 if (dirent) {
3473 struct smbc_dir_list *tmp = list;
3475 while (tmp) {
3477 if (tmp->dirent == dirent)
3478 return tmp;
3480 tmp = tmp->next;
3486 return NULL; /* Not found, or an error */
3492 * Routine to seek on a directory
3495 static int
3496 smbc_lseekdir_ctx(SMBCCTX *context,
3497 SMBCFILE *dir,
3498 off_t offset)
3500 long int l_offset = offset; /* Handle problems of size */
3501 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3502 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3504 if (!context || !context->internal ||
3505 !context->internal->_initialized) {
3507 errno = EINVAL;
3508 return -1;
3512 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3514 errno = ENOTDIR;
3515 return -1;
3519 /* Now, check what we were passed and see if it is OK ... */
3521 if (dirent == NULL) { /* Seek to the begining of the list */
3523 dir->dir_next = dir->dir_list;
3524 return 0;
3528 /* Now, run down the list and make sure that the entry is OK */
3529 /* This may need to be changed if we change the format of the list */
3531 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3533 errno = EINVAL; /* Bad entry */
3534 return -1;
3538 dir->dir_next = list_ent;
3540 return 0;
3545 * Routine to fstat a dir
3548 static int
3549 smbc_fstatdir_ctx(SMBCCTX *context,
3550 SMBCFILE *dir,
3551 struct stat *st)
3554 if (!context || !context->internal ||
3555 !context->internal->_initialized) {
3557 errno = EINVAL;
3558 return -1;
3562 /* No code yet ... */
3564 return 0;
3568 static int
3569 smbc_chmod_ctx(SMBCCTX *context,
3570 const char *fname,
3571 mode_t newmode)
3573 SMBCSRV *srv;
3574 fstring server;
3575 fstring share;
3576 fstring user;
3577 fstring password;
3578 fstring workgroup;
3579 pstring path;
3580 uint16 mode;
3582 if (!context || !context->internal ||
3583 !context->internal->_initialized) {
3585 errno = EINVAL; /* Best I can think of ... */
3586 return -1;
3590 if (!fname) {
3592 errno = EINVAL;
3593 return -1;
3597 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3599 if (smbc_parse_path(context, fname,
3600 workgroup, sizeof(workgroup),
3601 server, sizeof(server),
3602 share, sizeof(share),
3603 path, sizeof(path),
3604 user, sizeof(user),
3605 password, sizeof(password),
3606 NULL, 0)) {
3607 errno = EINVAL;
3608 return -1;
3611 if (user[0] == (char)0) fstrcpy(user, context->user);
3613 srv = smbc_server(context, True,
3614 server, share, workgroup, user, password);
3616 if (!srv) {
3617 return -1; /* errno set by smbc_server */
3620 mode = 0;
3622 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3623 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3624 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3625 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3627 if (!cli_setatr(srv->cli, path, mode, 0)) {
3628 errno = smbc_errno(context, srv->cli);
3629 return -1;
3632 return 0;
3635 static int
3636 smbc_utimes_ctx(SMBCCTX *context,
3637 const char *fname,
3638 struct timeval *tbuf)
3640 SMBCSRV *srv;
3641 fstring server;
3642 fstring share;
3643 fstring user;
3644 fstring password;
3645 fstring workgroup;
3646 pstring path;
3647 time_t access_time;
3648 time_t write_time;
3650 if (!context || !context->internal ||
3651 !context->internal->_initialized) {
3653 errno = EINVAL; /* Best I can think of ... */
3654 return -1;
3658 if (!fname) {
3660 errno = EINVAL;
3661 return -1;
3665 if (tbuf == NULL) {
3666 access_time = write_time = time(NULL);
3667 } else {
3668 access_time = tbuf[0].tv_sec;
3669 write_time = tbuf[1].tv_sec;
3672 if (DEBUGLVL(4))
3674 char *p;
3675 char atimebuf[32];
3676 char mtimebuf[32];
3678 strncpy(atimebuf, ctime(&access_time), sizeof(atimebuf) - 1);
3679 atimebuf[sizeof(atimebuf) - 1] = '\0';
3680 if ((p = strchr(atimebuf, '\n')) != NULL) {
3681 *p = '\0';
3684 strncpy(mtimebuf, ctime(&write_time), sizeof(mtimebuf) - 1);
3685 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3686 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3687 *p = '\0';
3690 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3691 fname, atimebuf, mtimebuf);
3694 if (smbc_parse_path(context, fname,
3695 workgroup, sizeof(workgroup),
3696 server, sizeof(server),
3697 share, sizeof(share),
3698 path, sizeof(path),
3699 user, sizeof(user),
3700 password, sizeof(password),
3701 NULL, 0)) {
3702 errno = EINVAL;
3703 return -1;
3706 if (user[0] == (char)0) fstrcpy(user, context->user);
3708 srv = smbc_server(context, True,
3709 server, share, workgroup, user, password);
3711 if (!srv) {
3712 return -1; /* errno set by smbc_server */
3715 if (!smbc_setatr(context, srv, path,
3716 0, access_time, write_time, 0, 0)) {
3717 return -1; /* errno set by smbc_setatr */
3720 return 0;
3724 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3725 However NT4 gives a "The information may have been modified by a
3726 computer running Windows NT 5.0" if denied ACEs do not appear before
3727 allowed ACEs. */
3729 static int
3730 ace_compare(SEC_ACE *ace1,
3731 SEC_ACE *ace2)
3733 if (sec_ace_equal(ace1, ace2))
3734 return 0;
3736 if (ace1->type != ace2->type)
3737 return ace2->type - ace1->type;
3739 if (sid_compare(&ace1->trustee, &ace2->trustee))
3740 return sid_compare(&ace1->trustee, &ace2->trustee);
3742 if (ace1->flags != ace2->flags)
3743 return ace1->flags - ace2->flags;
3745 if (ace1->access_mask != ace2->access_mask)
3746 return ace1->access_mask - ace2->access_mask;
3748 if (ace1->size != ace2->size)
3749 return ace1->size - ace2->size;
3751 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3755 static void
3756 sort_acl(SEC_ACL *the_acl)
3758 uint32 i;
3759 if (!the_acl) return;
3761 qsort(the_acl->aces, the_acl->num_aces, sizeof(the_acl->aces[0]),
3762 QSORT_CAST ace_compare);
3764 for (i=1;i<the_acl->num_aces;) {
3765 if (sec_ace_equal(&the_acl->aces[i-1], &the_acl->aces[i])) {
3766 int j;
3767 for (j=i; j<the_acl->num_aces-1; j++) {
3768 the_acl->aces[j] = the_acl->aces[j+1];
3770 the_acl->num_aces--;
3771 } else {
3772 i++;
3777 /* convert a SID to a string, either numeric or username/group */
3778 static void
3779 convert_sid_to_string(struct cli_state *ipc_cli,
3780 POLICY_HND *pol,
3781 fstring str,
3782 BOOL numeric,
3783 DOM_SID *sid)
3785 char **domains = NULL;
3786 char **names = NULL;
3787 enum lsa_SidType *types = NULL;
3788 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3789 sid_to_string(str, sid);
3791 if (numeric) {
3792 return; /* no lookup desired */
3795 if (!pipe_hnd) {
3796 return;
3799 /* Ask LSA to convert the sid to a name */
3801 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3802 pol, 1, sid, &domains,
3803 &names, &types)) ||
3804 !domains || !domains[0] || !names || !names[0]) {
3805 return;
3808 /* Converted OK */
3810 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3811 domains[0], lp_winbind_separator(),
3812 names[0]);
3815 /* convert a string to a SID, either numeric or username/group */
3816 static BOOL
3817 convert_string_to_sid(struct cli_state *ipc_cli,
3818 POLICY_HND *pol,
3819 BOOL numeric,
3820 DOM_SID *sid,
3821 const char *str)
3823 enum lsa_SidType *types = NULL;
3824 DOM_SID *sids = NULL;
3825 BOOL result = True;
3826 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3828 if (!pipe_hnd) {
3829 return False;
3832 if (numeric) {
3833 if (strncmp(str, "S-", 2) == 0) {
3834 return string_to_sid(sid, str);
3837 result = False;
3838 goto done;
3841 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3842 pol, 1, &str, NULL, &sids,
3843 &types))) {
3844 result = False;
3845 goto done;
3848 sid_copy(sid, &sids[0]);
3849 done:
3851 return result;
3855 /* parse an ACE in the same format as print_ace() */
3856 static BOOL
3857 parse_ace(struct cli_state *ipc_cli,
3858 POLICY_HND *pol,
3859 SEC_ACE *ace,
3860 BOOL numeric,
3861 char *str)
3863 char *p;
3864 const char *cp;
3865 fstring tok;
3866 unsigned int atype;
3867 unsigned int aflags;
3868 unsigned int amask;
3869 DOM_SID sid;
3870 SEC_ACCESS mask;
3871 const struct perm_value *v;
3872 struct perm_value {
3873 const char *perm;
3874 uint32 mask;
3877 /* These values discovered by inspection */
3878 static const struct perm_value special_values[] = {
3879 { "R", 0x00120089 },
3880 { "W", 0x00120116 },
3881 { "X", 0x001200a0 },
3882 { "D", 0x00010000 },
3883 { "P", 0x00040000 },
3884 { "O", 0x00080000 },
3885 { NULL, 0 },
3888 static const struct perm_value standard_values[] = {
3889 { "READ", 0x001200a9 },
3890 { "CHANGE", 0x001301bf },
3891 { "FULL", 0x001f01ff },
3892 { NULL, 0 },
3896 ZERO_STRUCTP(ace);
3897 p = strchr_m(str,':');
3898 if (!p) return False;
3899 *p = '\0';
3900 p++;
3901 /* Try to parse numeric form */
3903 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3904 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3905 goto done;
3908 /* Try to parse text form */
3910 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3911 return False;
3914 cp = p;
3915 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3916 return False;
3919 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3920 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3921 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3922 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3923 } else {
3924 return False;
3927 /* Only numeric form accepted for flags at present */
3929 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3930 sscanf(tok, "%i", &aflags))) {
3931 return False;
3934 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3935 return False;
3938 if (strncmp(tok, "0x", 2) == 0) {
3939 if (sscanf(tok, "%i", &amask) != 1) {
3940 return False;
3942 goto done;
3945 for (v = standard_values; v->perm; v++) {
3946 if (strcmp(tok, v->perm) == 0) {
3947 amask = v->mask;
3948 goto done;
3952 p = tok;
3954 while(*p) {
3955 BOOL found = False;
3957 for (v = special_values; v->perm; v++) {
3958 if (v->perm[0] == *p) {
3959 amask |= v->mask;
3960 found = True;
3964 if (!found) return False;
3965 p++;
3968 if (*p) {
3969 return False;
3972 done:
3973 mask = amask;
3974 init_sec_ace(ace, &sid, atype, mask, aflags);
3975 return True;
3978 /* add an ACE to a list of ACEs in a SEC_ACL */
3979 static BOOL
3980 add_ace(SEC_ACL **the_acl,
3981 SEC_ACE *ace,
3982 TALLOC_CTX *ctx)
3984 SEC_ACL *newacl;
3985 SEC_ACE *aces;
3987 if (! *the_acl) {
3988 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3989 return True;
3992 if ((aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces)) == NULL) {
3993 return False;
3995 memcpy(aces, (*the_acl)->aces, (*the_acl)->num_aces * sizeof(SEC_ACE));
3996 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3997 newacl = make_sec_acl(ctx, (*the_acl)->revision,
3998 1+(*the_acl)->num_aces, aces);
3999 SAFE_FREE(aces);
4000 (*the_acl) = newacl;
4001 return True;
4005 /* parse a ascii version of a security descriptor */
4006 static SEC_DESC *
4007 sec_desc_parse(TALLOC_CTX *ctx,
4008 struct cli_state *ipc_cli,
4009 POLICY_HND *pol,
4010 BOOL numeric,
4011 char *str)
4013 const char *p = str;
4014 fstring tok;
4015 SEC_DESC *ret = NULL;
4016 size_t sd_size;
4017 DOM_SID *grp_sid=NULL;
4018 DOM_SID *owner_sid=NULL;
4019 SEC_ACL *dacl=NULL;
4020 int revision=1;
4022 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4024 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
4025 revision = strtol(tok+9, NULL, 16);
4026 continue;
4029 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
4030 if (owner_sid) {
4031 DEBUG(5, ("OWNER specified more than once!\n"));
4032 goto done;
4034 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4035 if (!owner_sid ||
4036 !convert_string_to_sid(ipc_cli, pol,
4037 numeric,
4038 owner_sid, tok+6)) {
4039 DEBUG(5, ("Failed to parse owner sid\n"));
4040 goto done;
4042 continue;
4045 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
4046 if (owner_sid) {
4047 DEBUG(5, ("OWNER specified more than once!\n"));
4048 goto done;
4050 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4051 if (!owner_sid ||
4052 !convert_string_to_sid(ipc_cli, pol,
4053 False,
4054 owner_sid, tok+7)) {
4055 DEBUG(5, ("Failed to parse owner sid\n"));
4056 goto done;
4058 continue;
4061 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
4062 if (grp_sid) {
4063 DEBUG(5, ("GROUP specified more than once!\n"));
4064 goto done;
4066 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4067 if (!grp_sid ||
4068 !convert_string_to_sid(ipc_cli, pol,
4069 numeric,
4070 grp_sid, tok+6)) {
4071 DEBUG(5, ("Failed to parse group sid\n"));
4072 goto done;
4074 continue;
4077 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
4078 if (grp_sid) {
4079 DEBUG(5, ("GROUP specified more than once!\n"));
4080 goto done;
4082 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4083 if (!grp_sid ||
4084 !convert_string_to_sid(ipc_cli, pol,
4085 False,
4086 grp_sid, tok+6)) {
4087 DEBUG(5, ("Failed to parse group sid\n"));
4088 goto done;
4090 continue;
4093 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
4094 SEC_ACE ace;
4095 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
4096 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4097 goto done;
4099 if(!add_ace(&dacl, &ace, ctx)) {
4100 DEBUG(5, ("Failed to add ACL %s\n", tok));
4101 goto done;
4103 continue;
4106 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
4107 SEC_ACE ace;
4108 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
4109 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4110 goto done;
4112 if(!add_ace(&dacl, &ace, ctx)) {
4113 DEBUG(5, ("Failed to add ACL %s\n", tok));
4114 goto done;
4116 continue;
4119 DEBUG(5, ("Failed to parse security descriptor\n"));
4120 goto done;
4123 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
4124 owner_sid, grp_sid, NULL, dacl, &sd_size);
4126 done:
4127 SAFE_FREE(grp_sid);
4128 SAFE_FREE(owner_sid);
4130 return ret;
4134 /* Obtain the current dos attributes */
4135 static DOS_ATTR_DESC *
4136 dos_attr_query(SMBCCTX *context,
4137 TALLOC_CTX *ctx,
4138 const char *filename,
4139 SMBCSRV *srv)
4141 struct timespec create_time_ts;
4142 struct timespec write_time_ts;
4143 struct timespec access_time_ts;
4144 struct timespec change_time_ts;
4145 SMB_OFF_T size = 0;
4146 uint16 mode = 0;
4147 SMB_INO_T inode = 0;
4148 DOS_ATTR_DESC *ret;
4150 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
4151 if (!ret) {
4152 errno = ENOMEM;
4153 return NULL;
4156 /* Obtain the DOS attributes */
4157 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
4158 &mode, &size,
4159 &create_time_ts,
4160 &access_time_ts,
4161 &write_time_ts,
4162 &change_time_ts,
4163 &inode)) {
4165 errno = smbc_errno(context, srv->cli);
4166 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
4167 return NULL;
4171 ret->mode = mode;
4172 ret->size = size;
4173 ret->create_time = convert_timespec_to_time_t(create_time_ts);
4174 ret->access_time = convert_timespec_to_time_t(access_time_ts);
4175 ret->write_time = convert_timespec_to_time_t(write_time_ts);
4176 ret->change_time = convert_timespec_to_time_t(change_time_ts);
4177 ret->inode = inode;
4179 return ret;
4183 /* parse a ascii version of a security descriptor */
4184 static void
4185 dos_attr_parse(SMBCCTX *context,
4186 DOS_ATTR_DESC *dad,
4187 SMBCSRV *srv,
4188 char *str)
4190 int n;
4191 const char *p = str;
4192 fstring tok;
4193 struct {
4194 const char * create_time_attr;
4195 const char * access_time_attr;
4196 const char * write_time_attr;
4197 const char * change_time_attr;
4198 } attr_strings;
4200 /* Determine whether to use old-style or new-style attribute names */
4201 if (context->internal->_full_time_names) {
4202 /* new-style names */
4203 attr_strings.create_time_attr = "CREATE_TIME";
4204 attr_strings.access_time_attr = "ACCESS_TIME";
4205 attr_strings.write_time_attr = "WRITE_TIME";
4206 attr_strings.change_time_attr = "CHANGE_TIME";
4207 } else {
4208 /* old-style names */
4209 attr_strings.create_time_attr = NULL;
4210 attr_strings.access_time_attr = "A_TIME";
4211 attr_strings.write_time_attr = "M_TIME";
4212 attr_strings.change_time_attr = "C_TIME";
4215 /* if this is to set the entire ACL... */
4216 if (*str == '*') {
4217 /* ... then increment past the first colon if there is one */
4218 if ((p = strchr(str, ':')) != NULL) {
4219 ++p;
4220 } else {
4221 p = str;
4225 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4227 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
4228 dad->mode = strtol(tok+5, NULL, 16);
4229 continue;
4232 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4233 dad->size = (SMB_OFF_T)atof(tok+5);
4234 continue;
4237 n = strlen(attr_strings.access_time_attr);
4238 if (StrnCaseCmp(tok, attr_strings.access_time_attr, n) == 0) {
4239 dad->access_time = (time_t)strtol(tok+n+1, NULL, 10);
4240 continue;
4243 n = strlen(attr_strings.change_time_attr);
4244 if (StrnCaseCmp(tok, attr_strings.change_time_attr, n) == 0) {
4245 dad->change_time = (time_t)strtol(tok+n+1, NULL, 10);
4246 continue;
4249 n = strlen(attr_strings.write_time_attr);
4250 if (StrnCaseCmp(tok, attr_strings.write_time_attr, n) == 0) {
4251 dad->write_time = (time_t)strtol(tok+n+1, NULL, 10);
4252 continue;
4255 n = strlen(attr_strings.create_time_attr);
4256 if (attr_strings.create_time_attr != NULL &&
4257 StrnCaseCmp(tok, attr_strings.create_time_attr, n) == 0) {
4258 dad->create_time = (time_t)strtol(tok+n+1, NULL, 10);
4259 continue;
4262 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4263 dad->inode = (SMB_INO_T)atof(tok+6);
4264 continue;
4269 /*****************************************************
4270 Retrieve the acls for a file.
4271 *******************************************************/
4273 static int
4274 cacl_get(SMBCCTX *context,
4275 TALLOC_CTX *ctx,
4276 SMBCSRV *srv,
4277 struct cli_state *ipc_cli,
4278 POLICY_HND *pol,
4279 char *filename,
4280 char *attr_name,
4281 char *buf,
4282 int bufsize)
4284 uint32 i;
4285 int n = 0;
4286 int n_used;
4287 BOOL all;
4288 BOOL all_nt;
4289 BOOL all_nt_acls;
4290 BOOL all_dos;
4291 BOOL some_nt;
4292 BOOL some_dos;
4293 BOOL exclude_nt_revision = False;
4294 BOOL exclude_nt_owner = False;
4295 BOOL exclude_nt_group = False;
4296 BOOL exclude_nt_acl = False;
4297 BOOL exclude_dos_mode = False;
4298 BOOL exclude_dos_size = False;
4299 BOOL exclude_dos_create_time = False;
4300 BOOL exclude_dos_access_time = False;
4301 BOOL exclude_dos_write_time = False;
4302 BOOL exclude_dos_change_time = False;
4303 BOOL exclude_dos_inode = False;
4304 BOOL numeric = True;
4305 BOOL determine_size = (bufsize == 0);
4306 int fnum = -1;
4307 SEC_DESC *sd;
4308 fstring sidstr;
4309 fstring name_sandbox;
4310 char *name;
4311 char *pExclude;
4312 char *p;
4313 struct timespec create_time_ts;
4314 struct timespec write_time_ts;
4315 struct timespec access_time_ts;
4316 struct timespec change_time_ts;
4317 time_t create_time = (time_t)0;
4318 time_t write_time = (time_t)0;
4319 time_t access_time = (time_t)0;
4320 time_t change_time = (time_t)0;
4321 SMB_OFF_T size = 0;
4322 uint16 mode = 0;
4323 SMB_INO_T ino = 0;
4324 struct cli_state *cli = srv->cli;
4325 struct {
4326 const char * create_time_attr;
4327 const char * access_time_attr;
4328 const char * write_time_attr;
4329 const char * change_time_attr;
4330 } attr_strings;
4331 struct {
4332 const char * create_time_attr;
4333 const char * access_time_attr;
4334 const char * write_time_attr;
4335 const char * change_time_attr;
4336 } excl_attr_strings;
4338 /* Determine whether to use old-style or new-style attribute names */
4339 if (context->internal->_full_time_names) {
4340 /* new-style names */
4341 attr_strings.create_time_attr = "CREATE_TIME";
4342 attr_strings.access_time_attr = "ACCESS_TIME";
4343 attr_strings.write_time_attr = "WRITE_TIME";
4344 attr_strings.change_time_attr = "CHANGE_TIME";
4346 excl_attr_strings.create_time_attr = "CREATE_TIME";
4347 excl_attr_strings.access_time_attr = "ACCESS_TIME";
4348 excl_attr_strings.write_time_attr = "WRITE_TIME";
4349 excl_attr_strings.change_time_attr = "CHANGE_TIME";
4350 } else {
4351 /* old-style names */
4352 attr_strings.create_time_attr = NULL;
4353 attr_strings.access_time_attr = "A_TIME";
4354 attr_strings.write_time_attr = "M_TIME";
4355 attr_strings.change_time_attr = "C_TIME";
4357 excl_attr_strings.create_time_attr = NULL;
4358 excl_attr_strings.access_time_attr = "dos_attr.A_TIME";
4359 excl_attr_strings.write_time_attr = "dos_attr.M_TIME";
4360 excl_attr_strings.change_time_attr = "dos_attr.C_TIME";
4363 /* Copy name so we can strip off exclusions (if any are specified) */
4364 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4366 /* Ensure name is null terminated */
4367 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4369 /* Play in the sandbox */
4370 name = name_sandbox;
4372 /* If there are any exclusions, point to them and mask them from name */
4373 if ((pExclude = strchr(name, '!')) != NULL)
4375 *pExclude++ = '\0';
4378 all = (StrnCaseCmp(name, "system.*", 8) == 0);
4379 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4380 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4381 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4382 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4383 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4384 numeric = (* (name + strlen(name) - 1) != '+');
4386 /* Look for exclusions from "all" requests */
4387 if (all || all_nt || all_dos) {
4389 /* Exclusions are delimited by '!' */
4390 for (;
4391 pExclude != NULL;
4392 pExclude = (p == NULL ? NULL : p + 1)) {
4394 /* Find end of this exclusion name */
4395 if ((p = strchr(pExclude, '!')) != NULL)
4397 *p = '\0';
4400 /* Which exclusion name is this? */
4401 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4402 exclude_nt_revision = True;
4404 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4405 exclude_nt_owner = True;
4407 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4408 exclude_nt_group = True;
4410 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4411 exclude_nt_acl = True;
4413 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4414 exclude_dos_mode = True;
4416 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4417 exclude_dos_size = True;
4419 else if (excl_attr_strings.create_time_attr != NULL &&
4420 StrCaseCmp(pExclude,
4421 excl_attr_strings.change_time_attr) == 0) {
4422 exclude_dos_create_time = True;
4424 else if (StrCaseCmp(pExclude,
4425 excl_attr_strings.access_time_attr) == 0) {
4426 exclude_dos_access_time = True;
4428 else if (StrCaseCmp(pExclude,
4429 excl_attr_strings.write_time_attr) == 0) {
4430 exclude_dos_write_time = True;
4432 else if (StrCaseCmp(pExclude,
4433 excl_attr_strings.change_time_attr) == 0) {
4434 exclude_dos_change_time = True;
4436 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4437 exclude_dos_inode = True;
4439 else {
4440 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4441 pExclude));
4442 errno = ENOATTR;
4443 return -1;
4448 n_used = 0;
4451 * If we are (possibly) talking to an NT or new system and some NT
4452 * attributes have been requested...
4454 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4455 /* Point to the portion after "system.nt_sec_desc." */
4456 name += 19; /* if (all) this will be invalid but unused */
4458 /* ... then obtain any NT attributes which were requested */
4459 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4461 if (fnum == -1) {
4462 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4463 filename, cli_errstr(cli)));
4464 errno = 0;
4465 return -1;
4468 sd = cli_query_secdesc(cli, fnum, ctx);
4470 if (!sd) {
4471 DEBUG(5,
4472 ("cacl_get Failed to query old descriptor\n"));
4473 errno = 0;
4474 return -1;
4477 cli_close(cli, fnum);
4479 if (! exclude_nt_revision) {
4480 if (all || all_nt) {
4481 if (determine_size) {
4482 p = talloc_asprintf(ctx,
4483 "REVISION:%d",
4484 sd->revision);
4485 if (!p) {
4486 errno = ENOMEM;
4487 return -1;
4489 n = strlen(p);
4490 } else {
4491 n = snprintf(buf, bufsize,
4492 "REVISION:%d",
4493 sd->revision);
4495 } else if (StrCaseCmp(name, "revision") == 0) {
4496 if (determine_size) {
4497 p = talloc_asprintf(ctx, "%d",
4498 sd->revision);
4499 if (!p) {
4500 errno = ENOMEM;
4501 return -1;
4503 n = strlen(p);
4504 } else {
4505 n = snprintf(buf, bufsize, "%d",
4506 sd->revision);
4510 if (!determine_size && n > bufsize) {
4511 errno = ERANGE;
4512 return -1;
4514 buf += n;
4515 n_used += n;
4516 bufsize -= n;
4519 if (! exclude_nt_owner) {
4520 /* Get owner and group sid */
4521 if (sd->owner_sid) {
4522 convert_sid_to_string(ipc_cli, pol,
4523 sidstr,
4524 numeric,
4525 sd->owner_sid);
4526 } else {
4527 fstrcpy(sidstr, "");
4530 if (all || all_nt) {
4531 if (determine_size) {
4532 p = talloc_asprintf(ctx, ",OWNER:%s",
4533 sidstr);
4534 if (!p) {
4535 errno = ENOMEM;
4536 return -1;
4538 n = strlen(p);
4539 } else {
4540 n = snprintf(buf, bufsize,
4541 ",OWNER:%s", sidstr);
4543 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4544 if (determine_size) {
4545 p = talloc_asprintf(ctx, "%s", sidstr);
4546 if (!p) {
4547 errno = ENOMEM;
4548 return -1;
4550 n = strlen(p);
4551 } else {
4552 n = snprintf(buf, bufsize, "%s",
4553 sidstr);
4557 if (!determine_size && n > bufsize) {
4558 errno = ERANGE;
4559 return -1;
4561 buf += n;
4562 n_used += n;
4563 bufsize -= n;
4566 if (! exclude_nt_group) {
4567 if (sd->group_sid) {
4568 convert_sid_to_string(ipc_cli, pol,
4569 sidstr, numeric,
4570 sd->group_sid);
4571 } else {
4572 fstrcpy(sidstr, "");
4575 if (all || all_nt) {
4576 if (determine_size) {
4577 p = talloc_asprintf(ctx, ",GROUP:%s",
4578 sidstr);
4579 if (!p) {
4580 errno = ENOMEM;
4581 return -1;
4583 n = strlen(p);
4584 } else {
4585 n = snprintf(buf, bufsize,
4586 ",GROUP:%s", sidstr);
4588 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4589 if (determine_size) {
4590 p = talloc_asprintf(ctx, "%s", sidstr);
4591 if (!p) {
4592 errno = ENOMEM;
4593 return -1;
4595 n = strlen(p);
4596 } else {
4597 n = snprintf(buf, bufsize,
4598 "%s", sidstr);
4602 if (!determine_size && n > bufsize) {
4603 errno = ERANGE;
4604 return -1;
4606 buf += n;
4607 n_used += n;
4608 bufsize -= n;
4611 if (! exclude_nt_acl) {
4612 /* Add aces to value buffer */
4613 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4615 SEC_ACE *ace = &sd->dacl->aces[i];
4616 convert_sid_to_string(ipc_cli, pol,
4617 sidstr, numeric,
4618 &ace->trustee);
4620 if (all || all_nt) {
4621 if (determine_size) {
4622 p = talloc_asprintf(
4623 ctx,
4624 ",ACL:"
4625 "%s:%d/%d/0x%08x",
4626 sidstr,
4627 ace->type,
4628 ace->flags,
4629 ace->access_mask);
4630 if (!p) {
4631 errno = ENOMEM;
4632 return -1;
4634 n = strlen(p);
4635 } else {
4636 n = snprintf(
4637 buf, bufsize,
4638 ",ACL:%s:%d/%d/0x%08x",
4639 sidstr,
4640 ace->type,
4641 ace->flags,
4642 ace->access_mask);
4644 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4645 StrCaseCmp(name+3, sidstr) == 0) ||
4646 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4647 StrCaseCmp(name+4, sidstr) == 0)) {
4648 if (determine_size) {
4649 p = talloc_asprintf(
4650 ctx,
4651 "%d/%d/0x%08x",
4652 ace->type,
4653 ace->flags,
4654 ace->access_mask);
4655 if (!p) {
4656 errno = ENOMEM;
4657 return -1;
4659 n = strlen(p);
4660 } else {
4661 n = snprintf(buf, bufsize,
4662 "%d/%d/0x%08x",
4663 ace->type,
4664 ace->flags,
4665 ace->access_mask);
4667 } else if (all_nt_acls) {
4668 if (determine_size) {
4669 p = talloc_asprintf(
4670 ctx,
4671 "%s%s:%d/%d/0x%08x",
4672 i ? "," : "",
4673 sidstr,
4674 ace->type,
4675 ace->flags,
4676 ace->access_mask);
4677 if (!p) {
4678 errno = ENOMEM;
4679 return -1;
4681 n = strlen(p);
4682 } else {
4683 n = snprintf(buf, bufsize,
4684 "%s%s:%d/%d/0x%08x",
4685 i ? "," : "",
4686 sidstr,
4687 ace->type,
4688 ace->flags,
4689 ace->access_mask);
4692 if (n > bufsize) {
4693 errno = ERANGE;
4694 return -1;
4696 buf += n;
4697 n_used += n;
4698 bufsize -= n;
4702 /* Restore name pointer to its original value */
4703 name -= 19;
4706 if (all || some_dos) {
4707 /* Point to the portion after "system.dos_attr." */
4708 name += 16; /* if (all) this will be invalid but unused */
4710 /* Obtain the DOS attributes */
4711 if (!smbc_getatr(context, srv, filename, &mode, &size,
4712 &create_time_ts,
4713 &access_time_ts,
4714 &write_time_ts,
4715 &change_time_ts,
4716 &ino)) {
4718 errno = smbc_errno(context, srv->cli);
4719 return -1;
4723 create_time = convert_timespec_to_time_t(create_time_ts);
4724 access_time = convert_timespec_to_time_t(access_time_ts);
4725 write_time = convert_timespec_to_time_t(write_time_ts);
4726 change_time = convert_timespec_to_time_t(change_time_ts);
4728 if (! exclude_dos_mode) {
4729 if (all || all_dos) {
4730 if (determine_size) {
4731 p = talloc_asprintf(ctx,
4732 "%sMODE:0x%x",
4733 (ipc_cli &&
4734 (all || some_nt)
4735 ? ","
4736 : ""),
4737 mode);
4738 if (!p) {
4739 errno = ENOMEM;
4740 return -1;
4742 n = strlen(p);
4743 } else {
4744 n = snprintf(buf, bufsize,
4745 "%sMODE:0x%x",
4746 (ipc_cli &&
4747 (all || some_nt)
4748 ? ","
4749 : ""),
4750 mode);
4752 } else if (StrCaseCmp(name, "mode") == 0) {
4753 if (determine_size) {
4754 p = talloc_asprintf(ctx, "0x%x", mode);
4755 if (!p) {
4756 errno = ENOMEM;
4757 return -1;
4759 n = strlen(p);
4760 } else {
4761 n = snprintf(buf, bufsize,
4762 "0x%x", mode);
4766 if (!determine_size && n > bufsize) {
4767 errno = ERANGE;
4768 return -1;
4770 buf += n;
4771 n_used += n;
4772 bufsize -= n;
4775 if (! exclude_dos_size) {
4776 if (all || all_dos) {
4777 if (determine_size) {
4778 p = talloc_asprintf(
4779 ctx,
4780 ",SIZE:%.0f",
4781 (double)size);
4782 if (!p) {
4783 errno = ENOMEM;
4784 return -1;
4786 n = strlen(p);
4787 } else {
4788 n = snprintf(buf, bufsize,
4789 ",SIZE:%.0f",
4790 (double)size);
4792 } else if (StrCaseCmp(name, "size") == 0) {
4793 if (determine_size) {
4794 p = talloc_asprintf(
4795 ctx,
4796 "%.0f",
4797 (double)size);
4798 if (!p) {
4799 errno = ENOMEM;
4800 return -1;
4802 n = strlen(p);
4803 } else {
4804 n = snprintf(buf, bufsize,
4805 "%.0f",
4806 (double)size);
4810 if (!determine_size && n > bufsize) {
4811 errno = ERANGE;
4812 return -1;
4814 buf += n;
4815 n_used += n;
4816 bufsize -= n;
4819 if (! exclude_dos_create_time &&
4820 attr_strings.create_time_attr != NULL) {
4821 if (all || all_dos) {
4822 if (determine_size) {
4823 p = talloc_asprintf(ctx,
4824 ",%s:%lu",
4825 attr_strings.create_time_attr,
4826 create_time);
4827 if (!p) {
4828 errno = ENOMEM;
4829 return -1;
4831 n = strlen(p);
4832 } else {
4833 n = snprintf(buf, bufsize,
4834 ",%s:%lu",
4835 attr_strings.create_time_attr,
4836 create_time);
4838 } else if (StrCaseCmp(name, attr_strings.create_time_attr) == 0) {
4839 if (determine_size) {
4840 p = talloc_asprintf(ctx, "%lu", create_time);
4841 if (!p) {
4842 errno = ENOMEM;
4843 return -1;
4845 n = strlen(p);
4846 } else {
4847 n = snprintf(buf, bufsize,
4848 "%lu", create_time);
4852 if (!determine_size && n > bufsize) {
4853 errno = ERANGE;
4854 return -1;
4856 buf += n;
4857 n_used += n;
4858 bufsize -= n;
4861 if (! exclude_dos_access_time) {
4862 if (all || all_dos) {
4863 if (determine_size) {
4864 p = talloc_asprintf(ctx,
4865 ",%s:%lu",
4866 attr_strings.access_time_attr,
4867 access_time);
4868 if (!p) {
4869 errno = ENOMEM;
4870 return -1;
4872 n = strlen(p);
4873 } else {
4874 n = snprintf(buf, bufsize,
4875 ",%s:%lu",
4876 attr_strings.access_time_attr,
4877 access_time);
4879 } else if (StrCaseCmp(name, attr_strings.access_time_attr) == 0) {
4880 if (determine_size) {
4881 p = talloc_asprintf(ctx, "%lu", access_time);
4882 if (!p) {
4883 errno = ENOMEM;
4884 return -1;
4886 n = strlen(p);
4887 } else {
4888 n = snprintf(buf, bufsize,
4889 "%lu", access_time);
4893 if (!determine_size && n > bufsize) {
4894 errno = ERANGE;
4895 return -1;
4897 buf += n;
4898 n_used += n;
4899 bufsize -= n;
4902 if (! exclude_dos_write_time) {
4903 if (all || all_dos) {
4904 if (determine_size) {
4905 p = talloc_asprintf(ctx,
4906 ",%s:%lu",
4907 attr_strings.write_time_attr,
4908 write_time);
4909 if (!p) {
4910 errno = ENOMEM;
4911 return -1;
4913 n = strlen(p);
4914 } else {
4915 n = snprintf(buf, bufsize,
4916 ",%s:%lu",
4917 attr_strings.write_time_attr,
4918 write_time);
4920 } else if (StrCaseCmp(name, attr_strings.write_time_attr) == 0) {
4921 if (determine_size) {
4922 p = talloc_asprintf(ctx, "%lu", write_time);
4923 if (!p) {
4924 errno = ENOMEM;
4925 return -1;
4927 n = strlen(p);
4928 } else {
4929 n = snprintf(buf, bufsize,
4930 "%lu", write_time);
4934 if (!determine_size && n > bufsize) {
4935 errno = ERANGE;
4936 return -1;
4938 buf += n;
4939 n_used += n;
4940 bufsize -= n;
4943 if (! exclude_dos_change_time) {
4944 if (all || all_dos) {
4945 if (determine_size) {
4946 p = talloc_asprintf(ctx,
4947 ",%s:%lu",
4948 attr_strings.change_time_attr,
4949 change_time);
4950 if (!p) {
4951 errno = ENOMEM;
4952 return -1;
4954 n = strlen(p);
4955 } else {
4956 n = snprintf(buf, bufsize,
4957 ",%s:%lu",
4958 attr_strings.change_time_attr,
4959 change_time);
4961 } else if (StrCaseCmp(name, attr_strings.change_time_attr) == 0) {
4962 if (determine_size) {
4963 p = talloc_asprintf(ctx, "%lu", change_time);
4964 if (!p) {
4965 errno = ENOMEM;
4966 return -1;
4968 n = strlen(p);
4969 } else {
4970 n = snprintf(buf, bufsize,
4971 "%lu", change_time);
4975 if (!determine_size && n > bufsize) {
4976 errno = ERANGE;
4977 return -1;
4979 buf += n;
4980 n_used += n;
4981 bufsize -= n;
4984 if (! exclude_dos_inode) {
4985 if (all || all_dos) {
4986 if (determine_size) {
4987 p = talloc_asprintf(
4988 ctx,
4989 ",INODE:%.0f",
4990 (double)ino);
4991 if (!p) {
4992 errno = ENOMEM;
4993 return -1;
4995 n = strlen(p);
4996 } else {
4997 n = snprintf(buf, bufsize,
4998 ",INODE:%.0f",
4999 (double) ino);
5001 } else if (StrCaseCmp(name, "inode") == 0) {
5002 if (determine_size) {
5003 p = talloc_asprintf(
5004 ctx,
5005 "%.0f",
5006 (double) ino);
5007 if (!p) {
5008 errno = ENOMEM;
5009 return -1;
5011 n = strlen(p);
5012 } else {
5013 n = snprintf(buf, bufsize,
5014 "%.0f",
5015 (double) ino);
5019 if (!determine_size && n > bufsize) {
5020 errno = ERANGE;
5021 return -1;
5023 buf += n;
5024 n_used += n;
5025 bufsize -= n;
5028 /* Restore name pointer to its original value */
5029 name -= 16;
5032 if (n_used == 0) {
5033 errno = ENOATTR;
5034 return -1;
5037 return n_used;
5041 /*****************************************************
5042 set the ACLs on a file given an ascii description
5043 *******************************************************/
5044 static int
5045 cacl_set(TALLOC_CTX *ctx,
5046 struct cli_state *cli,
5047 struct cli_state *ipc_cli,
5048 POLICY_HND *pol,
5049 const char *filename,
5050 const char *the_acl,
5051 int mode,
5052 int flags)
5054 int fnum;
5055 int err = 0;
5056 SEC_DESC *sd = NULL, *old;
5057 SEC_ACL *dacl = NULL;
5058 DOM_SID *owner_sid = NULL;
5059 DOM_SID *grp_sid = NULL;
5060 uint32 i, j;
5061 size_t sd_size;
5062 int ret = 0;
5063 char *p;
5064 BOOL numeric = True;
5066 /* the_acl will be null for REMOVE_ALL operations */
5067 if (the_acl) {
5068 numeric = ((p = strchr(the_acl, ':')) != NULL &&
5069 p > the_acl &&
5070 p[-1] != '+');
5072 /* if this is to set the entire ACL... */
5073 if (*the_acl == '*') {
5074 /* ... then increment past the first colon */
5075 the_acl = p + 1;
5078 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
5079 CONST_DISCARD(char *, the_acl));
5081 if (!sd) {
5082 errno = EINVAL;
5083 return -1;
5087 /* SMBC_XATTR_MODE_REMOVE_ALL is the only caller
5088 that doesn't deref sd */
5090 if (!sd && (mode != SMBC_XATTR_MODE_REMOVE_ALL)) {
5091 errno = EINVAL;
5092 return -1;
5095 /* The desired access below is the only one I could find that works
5096 with NT4, W2KP and Samba */
5098 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
5100 if (fnum == -1) {
5101 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5102 filename, cli_errstr(cli)));
5103 errno = 0;
5104 return -1;
5107 old = cli_query_secdesc(cli, fnum, ctx);
5109 if (!old) {
5110 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
5111 errno = 0;
5112 return -1;
5115 cli_close(cli, fnum);
5117 switch (mode) {
5118 case SMBC_XATTR_MODE_REMOVE_ALL:
5119 old->dacl->num_aces = 0;
5120 SAFE_FREE(old->dacl->aces);
5121 SAFE_FREE(old->dacl);
5122 old->dacl = NULL;
5123 dacl = old->dacl;
5124 break;
5126 case SMBC_XATTR_MODE_REMOVE:
5127 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5128 BOOL found = False;
5130 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
5131 if (sec_ace_equal(&sd->dacl->aces[i],
5132 &old->dacl->aces[j])) {
5133 uint32 k;
5134 for (k=j; k<old->dacl->num_aces-1;k++) {
5135 old->dacl->aces[k] =
5136 old->dacl->aces[k+1];
5138 old->dacl->num_aces--;
5139 if (old->dacl->num_aces == 0) {
5140 SAFE_FREE(old->dacl->aces);
5141 SAFE_FREE(old->dacl);
5142 old->dacl = NULL;
5144 found = True;
5145 dacl = old->dacl;
5146 break;
5150 if (!found) {
5151 err = ENOATTR;
5152 ret = -1;
5153 goto failed;
5156 break;
5158 case SMBC_XATTR_MODE_ADD:
5159 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5160 BOOL found = False;
5162 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
5163 if (sid_equal(&sd->dacl->aces[i].trustee,
5164 &old->dacl->aces[j].trustee)) {
5165 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
5166 err = EEXIST;
5167 ret = -1;
5168 goto failed;
5170 old->dacl->aces[j] = sd->dacl->aces[i];
5171 ret = -1;
5172 found = True;
5176 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
5177 err = ENOATTR;
5178 ret = -1;
5179 goto failed;
5182 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5183 add_ace(&old->dacl, &sd->dacl->aces[i], ctx);
5186 dacl = old->dacl;
5187 break;
5189 case SMBC_XATTR_MODE_SET:
5190 old = sd;
5191 owner_sid = old->owner_sid;
5192 grp_sid = old->group_sid;
5193 dacl = old->dacl;
5194 break;
5196 case SMBC_XATTR_MODE_CHOWN:
5197 owner_sid = sd->owner_sid;
5198 break;
5200 case SMBC_XATTR_MODE_CHGRP:
5201 grp_sid = sd->group_sid;
5202 break;
5205 /* Denied ACE entries must come before allowed ones */
5206 sort_acl(old->dacl);
5208 /* Create new security descriptor and set it */
5209 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
5210 owner_sid, grp_sid, NULL, dacl, &sd_size);
5212 fnum = cli_nt_create(cli, filename,
5213 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
5215 if (fnum == -1) {
5216 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5217 filename, cli_errstr(cli)));
5218 errno = 0;
5219 return -1;
5222 if (!cli_set_secdesc(cli, fnum, sd)) {
5223 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
5224 ret = -1;
5227 /* Clean up */
5229 failed:
5230 cli_close(cli, fnum);
5232 if (err != 0) {
5233 errno = err;
5236 return ret;
5240 static int
5241 smbc_setxattr_ctx(SMBCCTX *context,
5242 const char *fname,
5243 const char *name,
5244 const void *value,
5245 size_t size,
5246 int flags)
5248 int ret;
5249 int ret2;
5250 SMBCSRV *srv;
5251 SMBCSRV *ipc_srv;
5252 fstring server;
5253 fstring share;
5254 fstring user;
5255 fstring password;
5256 fstring workgroup;
5257 pstring path;
5258 TALLOC_CTX *ctx;
5259 POLICY_HND pol;
5260 DOS_ATTR_DESC *dad;
5261 struct {
5262 const char * create_time_attr;
5263 const char * access_time_attr;
5264 const char * write_time_attr;
5265 const char * change_time_attr;
5266 } attr_strings;
5268 if (!context || !context->internal ||
5269 !context->internal->_initialized) {
5271 errno = EINVAL; /* Best I can think of ... */
5272 return -1;
5276 if (!fname) {
5278 errno = EINVAL;
5279 return -1;
5283 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
5284 fname, name, (int) size, (const char*)value));
5286 if (smbc_parse_path(context, fname,
5287 workgroup, sizeof(workgroup),
5288 server, sizeof(server),
5289 share, sizeof(share),
5290 path, sizeof(path),
5291 user, sizeof(user),
5292 password, sizeof(password),
5293 NULL, 0)) {
5294 errno = EINVAL;
5295 return -1;
5298 if (user[0] == (char)0) fstrcpy(user, context->user);
5300 srv = smbc_server(context, True,
5301 server, share, workgroup, user, password);
5302 if (!srv) {
5303 return -1; /* errno set by smbc_server */
5306 if (! srv->no_nt_session) {
5307 ipc_srv = smbc_attr_server(context, server, share,
5308 workgroup, user, password,
5309 &pol);
5310 srv->no_nt_session = True;
5311 } else {
5312 ipc_srv = NULL;
5315 ctx = talloc_init("smbc_setxattr");
5316 if (!ctx) {
5317 errno = ENOMEM;
5318 return -1;
5322 * Are they asking to set the entire set of known attributes?
5324 if (StrCaseCmp(name, "system.*") == 0 ||
5325 StrCaseCmp(name, "system.*+") == 0) {
5326 /* Yup. */
5327 char *namevalue =
5328 talloc_asprintf(ctx, "%s:%s",
5329 name+7, (const char *) value);
5330 if (! namevalue) {
5331 errno = ENOMEM;
5332 ret = -1;
5333 return -1;
5336 if (ipc_srv) {
5337 ret = cacl_set(ctx, srv->cli,
5338 ipc_srv->cli, &pol, path,
5339 namevalue,
5340 (*namevalue == '*'
5341 ? SMBC_XATTR_MODE_SET
5342 : SMBC_XATTR_MODE_ADD),
5343 flags);
5344 } else {
5345 ret = 0;
5348 /* get a DOS Attribute Descriptor with current attributes */
5349 dad = dos_attr_query(context, ctx, path, srv);
5350 if (dad) {
5351 /* Overwrite old with new, using what was provided */
5352 dos_attr_parse(context, dad, srv, namevalue);
5354 /* Set the new DOS attributes */
5355 if (! smbc_setatr(context, srv, path,
5356 dad->create_time,
5357 dad->access_time,
5358 dad->write_time,
5359 dad->change_time,
5360 dad->mode)) {
5362 /* cause failure if NT failed too */
5363 dad = NULL;
5367 /* we only fail if both NT and DOS sets failed */
5368 if (ret < 0 && ! dad) {
5369 ret = -1; /* in case dad was null */
5371 else {
5372 ret = 0;
5375 talloc_destroy(ctx);
5376 return ret;
5380 * Are they asking to set an access control element or to set
5381 * the entire access control list?
5383 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5384 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5385 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5386 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5387 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5389 /* Yup. */
5390 char *namevalue =
5391 talloc_asprintf(ctx, "%s:%s",
5392 name+19, (const char *) value);
5394 if (! ipc_srv) {
5395 ret = -1; /* errno set by smbc_server() */
5397 else if (! namevalue) {
5398 errno = ENOMEM;
5399 ret = -1;
5400 } else {
5401 ret = cacl_set(ctx, srv->cli,
5402 ipc_srv->cli, &pol, path,
5403 namevalue,
5404 (*namevalue == '*'
5405 ? SMBC_XATTR_MODE_SET
5406 : SMBC_XATTR_MODE_ADD),
5407 flags);
5409 talloc_destroy(ctx);
5410 return ret;
5414 * Are they asking to set the owner?
5416 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5417 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5419 /* Yup. */
5420 char *namevalue =
5421 talloc_asprintf(ctx, "%s:%s",
5422 name+19, (const char *) value);
5424 if (! ipc_srv) {
5426 ret = -1; /* errno set by smbc_server() */
5428 else if (! namevalue) {
5429 errno = ENOMEM;
5430 ret = -1;
5431 } else {
5432 ret = cacl_set(ctx, srv->cli,
5433 ipc_srv->cli, &pol, path,
5434 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5436 talloc_destroy(ctx);
5437 return ret;
5441 * Are they asking to set the group?
5443 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5444 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5446 /* Yup. */
5447 char *namevalue =
5448 talloc_asprintf(ctx, "%s:%s",
5449 name+19, (const char *) value);
5451 if (! ipc_srv) {
5452 /* errno set by smbc_server() */
5453 ret = -1;
5455 else if (! namevalue) {
5456 errno = ENOMEM;
5457 ret = -1;
5458 } else {
5459 ret = cacl_set(ctx, srv->cli,
5460 ipc_srv->cli, &pol, path,
5461 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5463 talloc_destroy(ctx);
5464 return ret;
5467 /* Determine whether to use old-style or new-style attribute names */
5468 if (context->internal->_full_time_names) {
5469 /* new-style names */
5470 attr_strings.create_time_attr = "system.dos_attr.CREATE_TIME";
5471 attr_strings.access_time_attr = "system.dos_attr.ACCESS_TIME";
5472 attr_strings.write_time_attr = "system.dos_attr.WRITE_TIME";
5473 attr_strings.change_time_attr = "system.dos_attr.CHANGE_TIME";
5474 } else {
5475 /* old-style names */
5476 attr_strings.create_time_attr = NULL;
5477 attr_strings.access_time_attr = "system.dos_attr.A_TIME";
5478 attr_strings.write_time_attr = "system.dos_attr.M_TIME";
5479 attr_strings.change_time_attr = "system.dos_attr.C_TIME";
5483 * Are they asking to set a DOS attribute?
5485 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5486 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5487 (attr_strings.create_time_attr != NULL &&
5488 StrCaseCmp(name, attr_strings.create_time_attr) == 0) ||
5489 StrCaseCmp(name, attr_strings.access_time_attr) == 0 ||
5490 StrCaseCmp(name, attr_strings.write_time_attr) == 0 ||
5491 StrCaseCmp(name, attr_strings.change_time_attr) == 0) {
5493 /* get a DOS Attribute Descriptor with current attributes */
5494 dad = dos_attr_query(context, ctx, path, srv);
5495 if (dad) {
5496 char *namevalue =
5497 talloc_asprintf(ctx, "%s:%s",
5498 name+16, (const char *) value);
5499 if (! namevalue) {
5500 errno = ENOMEM;
5501 ret = -1;
5502 } else {
5503 /* Overwrite old with provided new params */
5504 dos_attr_parse(context, dad, srv, namevalue);
5506 /* Set the new DOS attributes */
5507 ret2 = smbc_setatr(context, srv, path,
5508 dad->create_time,
5509 dad->access_time,
5510 dad->write_time,
5511 dad->change_time,
5512 dad->mode);
5514 /* ret2 has True (success) / False (failure) */
5515 if (ret2) {
5516 ret = 0;
5517 } else {
5518 ret = -1;
5521 } else {
5522 ret = -1;
5525 talloc_destroy(ctx);
5526 return ret;
5529 /* Unsupported attribute name */
5530 talloc_destroy(ctx);
5531 errno = EINVAL;
5532 return -1;
5535 static int
5536 smbc_getxattr_ctx(SMBCCTX *context,
5537 const char *fname,
5538 const char *name,
5539 const void *value,
5540 size_t size)
5542 int ret;
5543 SMBCSRV *srv;
5544 SMBCSRV *ipc_srv;
5545 fstring server;
5546 fstring share;
5547 fstring user;
5548 fstring password;
5549 fstring workgroup;
5550 pstring path;
5551 TALLOC_CTX *ctx;
5552 POLICY_HND pol;
5553 struct {
5554 const char * create_time_attr;
5555 const char * access_time_attr;
5556 const char * write_time_attr;
5557 const char * change_time_attr;
5558 } attr_strings;
5561 if (!context || !context->internal ||
5562 !context->internal->_initialized) {
5564 errno = EINVAL; /* Best I can think of ... */
5565 return -1;
5569 if (!fname) {
5571 errno = EINVAL;
5572 return -1;
5576 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5578 if (smbc_parse_path(context, fname,
5579 workgroup, sizeof(workgroup),
5580 server, sizeof(server),
5581 share, sizeof(share),
5582 path, sizeof(path),
5583 user, sizeof(user),
5584 password, sizeof(password),
5585 NULL, 0)) {
5586 errno = EINVAL;
5587 return -1;
5590 if (user[0] == (char)0) fstrcpy(user, context->user);
5592 srv = smbc_server(context, True,
5593 server, share, workgroup, user, password);
5594 if (!srv) {
5595 return -1; /* errno set by smbc_server */
5598 if (! srv->no_nt_session) {
5599 ipc_srv = smbc_attr_server(context, server, share,
5600 workgroup, user, password,
5601 &pol);
5602 if (! ipc_srv) {
5603 srv->no_nt_session = True;
5605 } else {
5606 ipc_srv = NULL;
5609 ctx = talloc_init("smbc:getxattr");
5610 if (!ctx) {
5611 errno = ENOMEM;
5612 return -1;
5615 /* Determine whether to use old-style or new-style attribute names */
5616 if (context->internal->_full_time_names) {
5617 /* new-style names */
5618 attr_strings.create_time_attr = "system.dos_attr.CREATE_TIME";
5619 attr_strings.access_time_attr = "system.dos_attr.ACCESS_TIME";
5620 attr_strings.write_time_attr = "system.dos_attr.WRITE_TIME";
5621 attr_strings.change_time_attr = "system.dos_attr.CHANGE_TIME";
5622 } else {
5623 /* old-style names */
5624 attr_strings.create_time_attr = NULL;
5625 attr_strings.access_time_attr = "system.dos_attr.A_TIME";
5626 attr_strings.write_time_attr = "system.dos_attr.M_TIME";
5627 attr_strings.change_time_attr = "system.dos_attr.C_TIME";
5630 /* Are they requesting a supported attribute? */
5631 if (StrCaseCmp(name, "system.*") == 0 ||
5632 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5633 StrCaseCmp(name, "system.*+") == 0 ||
5634 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5635 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5636 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5637 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5638 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5639 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5640 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5641 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5642 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5643 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5644 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5645 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5646 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5647 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5648 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5649 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5650 (attr_strings.create_time_attr != NULL &&
5651 StrCaseCmp(name, attr_strings.create_time_attr) == 0) ||
5652 StrCaseCmp(name, attr_strings.access_time_attr) == 0 ||
5653 StrCaseCmp(name, attr_strings.write_time_attr) == 0 ||
5654 StrCaseCmp(name, attr_strings.change_time_attr) == 0 ||
5655 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5657 /* Yup. */
5658 ret = cacl_get(context, ctx, srv,
5659 ipc_srv == NULL ? NULL : ipc_srv->cli,
5660 &pol, path,
5661 CONST_DISCARD(char *, name),
5662 CONST_DISCARD(char *, value), size);
5663 if (ret < 0 && errno == 0) {
5664 errno = smbc_errno(context, srv->cli);
5666 talloc_destroy(ctx);
5667 return ret;
5670 /* Unsupported attribute name */
5671 talloc_destroy(ctx);
5672 errno = EINVAL;
5673 return -1;
5677 static int
5678 smbc_removexattr_ctx(SMBCCTX *context,
5679 const char *fname,
5680 const char *name)
5682 int ret;
5683 SMBCSRV *srv;
5684 SMBCSRV *ipc_srv;
5685 fstring server;
5686 fstring share;
5687 fstring user;
5688 fstring password;
5689 fstring workgroup;
5690 pstring path;
5691 TALLOC_CTX *ctx;
5692 POLICY_HND pol;
5694 if (!context || !context->internal ||
5695 !context->internal->_initialized) {
5697 errno = EINVAL; /* Best I can think of ... */
5698 return -1;
5702 if (!fname) {
5704 errno = EINVAL;
5705 return -1;
5709 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5711 if (smbc_parse_path(context, fname,
5712 workgroup, sizeof(workgroup),
5713 server, sizeof(server),
5714 share, sizeof(share),
5715 path, sizeof(path),
5716 user, sizeof(user),
5717 password, sizeof(password),
5718 NULL, 0)) {
5719 errno = EINVAL;
5720 return -1;
5723 if (user[0] == (char)0) fstrcpy(user, context->user);
5725 srv = smbc_server(context, True,
5726 server, share, workgroup, user, password);
5727 if (!srv) {
5728 return -1; /* errno set by smbc_server */
5731 if (! srv->no_nt_session) {
5732 ipc_srv = smbc_attr_server(context, server, share,
5733 workgroup, user, password,
5734 &pol);
5735 srv->no_nt_session = True;
5736 } else {
5737 ipc_srv = NULL;
5740 if (! ipc_srv) {
5741 return -1; /* errno set by smbc_attr_server */
5744 ctx = talloc_init("smbc_removexattr");
5745 if (!ctx) {
5746 errno = ENOMEM;
5747 return -1;
5750 /* Are they asking to set the entire ACL? */
5751 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5752 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5754 /* Yup. */
5755 ret = cacl_set(ctx, srv->cli,
5756 ipc_srv->cli, &pol, path,
5757 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5758 talloc_destroy(ctx);
5759 return ret;
5763 * Are they asking to remove one or more spceific security descriptor
5764 * attributes?
5766 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5767 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5768 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5769 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5770 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5771 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5772 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5774 /* Yup. */
5775 ret = cacl_set(ctx, srv->cli,
5776 ipc_srv->cli, &pol, path,
5777 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5778 talloc_destroy(ctx);
5779 return ret;
5782 /* Unsupported attribute name */
5783 talloc_destroy(ctx);
5784 errno = EINVAL;
5785 return -1;
5788 static int
5789 smbc_listxattr_ctx(SMBCCTX *context,
5790 const char *fname,
5791 char *list,
5792 size_t size)
5795 * This isn't quite what listxattr() is supposed to do. This returns
5796 * the complete set of attribute names, always, rather than only those
5797 * attribute names which actually exist for a file. Hmmm...
5799 const char supported_old[] =
5800 "system.*\0"
5801 "system.*+\0"
5802 "system.nt_sec_desc.revision\0"
5803 "system.nt_sec_desc.owner\0"
5804 "system.nt_sec_desc.owner+\0"
5805 "system.nt_sec_desc.group\0"
5806 "system.nt_sec_desc.group+\0"
5807 "system.nt_sec_desc.acl.*\0"
5808 "system.nt_sec_desc.acl\0"
5809 "system.nt_sec_desc.acl+\0"
5810 "system.nt_sec_desc.*\0"
5811 "system.nt_sec_desc.*+\0"
5812 "system.dos_attr.*\0"
5813 "system.dos_attr.mode\0"
5814 "system.dos_attr.c_time\0"
5815 "system.dos_attr.a_time\0"
5816 "system.dos_attr.m_time\0"
5818 const char supported_new[] =
5819 "system.*\0"
5820 "system.*+\0"
5821 "system.nt_sec_desc.revision\0"
5822 "system.nt_sec_desc.owner\0"
5823 "system.nt_sec_desc.owner+\0"
5824 "system.nt_sec_desc.group\0"
5825 "system.nt_sec_desc.group+\0"
5826 "system.nt_sec_desc.acl.*\0"
5827 "system.nt_sec_desc.acl\0"
5828 "system.nt_sec_desc.acl+\0"
5829 "system.nt_sec_desc.*\0"
5830 "system.nt_sec_desc.*+\0"
5831 "system.dos_attr.*\0"
5832 "system.dos_attr.mode\0"
5833 "system.dos_attr.create_time\0"
5834 "system.dos_attr.access_time\0"
5835 "system.dos_attr.write_time\0"
5836 "system.dos_attr.change_time\0"
5838 const char * supported;
5840 if (context->internal->_full_time_names) {
5841 supported = supported_new;
5842 } else {
5843 supported = supported_old;
5846 if (size == 0) {
5847 return sizeof(supported);
5850 if (sizeof(supported) > size) {
5851 errno = ERANGE;
5852 return -1;
5855 /* this can't be strcpy() because there are embedded null characters */
5856 memcpy(list, supported, sizeof(supported));
5857 return sizeof(supported);
5862 * Open a print file to be written to by other calls
5865 static SMBCFILE *
5866 smbc_open_print_job_ctx(SMBCCTX *context,
5867 const char *fname)
5869 fstring server;
5870 fstring share;
5871 fstring user;
5872 fstring password;
5873 pstring path;
5875 if (!context || !context->internal ||
5876 !context->internal->_initialized) {
5878 errno = EINVAL;
5879 return NULL;
5883 if (!fname) {
5885 errno = EINVAL;
5886 return NULL;
5890 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5892 if (smbc_parse_path(context, fname,
5893 NULL, 0,
5894 server, sizeof(server),
5895 share, sizeof(share),
5896 path, sizeof(path),
5897 user, sizeof(user),
5898 password, sizeof(password),
5899 NULL, 0)) {
5900 errno = EINVAL;
5901 return NULL;
5904 /* What if the path is empty, or the file exists? */
5906 return context->open(context, fname, O_WRONLY, 666);
5911 * Routine to print a file on a remote server ...
5913 * We open the file, which we assume to be on a remote server, and then
5914 * copy it to a print file on the share specified by printq.
5917 static int
5918 smbc_print_file_ctx(SMBCCTX *c_file,
5919 const char *fname,
5920 SMBCCTX *c_print,
5921 const char *printq)
5923 SMBCFILE *fid1;
5924 SMBCFILE *fid2;
5925 int bytes;
5926 int saverr;
5927 int tot_bytes = 0;
5928 char buf[4096];
5930 if (!c_file || !c_file->internal->_initialized || !c_print ||
5931 !c_print->internal->_initialized) {
5933 errno = EINVAL;
5934 return -1;
5938 if (!fname && !printq) {
5940 errno = EINVAL;
5941 return -1;
5945 /* Try to open the file for reading ... */
5947 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5949 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5950 return -1; /* smbc_open sets errno */
5954 /* Now, try to open the printer file for writing */
5956 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5958 saverr = errno; /* Save errno */
5959 c_file->close_fn(c_file, fid1);
5960 errno = saverr;
5961 return -1;
5965 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5967 tot_bytes += bytes;
5969 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5971 saverr = errno;
5972 c_file->close_fn(c_file, fid1);
5973 c_print->close_fn(c_print, fid2);
5974 errno = saverr;
5980 saverr = errno;
5982 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5983 c_print->close_fn(c_print, fid2);
5985 if (bytes < 0) {
5987 errno = saverr;
5988 return -1;
5992 return tot_bytes;
5997 * Routine to list print jobs on a printer share ...
6000 static int
6001 smbc_list_print_jobs_ctx(SMBCCTX *context,
6002 const char *fname,
6003 smbc_list_print_job_fn fn)
6005 SMBCSRV *srv;
6006 fstring server;
6007 fstring share;
6008 fstring user;
6009 fstring password;
6010 fstring workgroup;
6011 pstring path;
6013 if (!context || !context->internal ||
6014 !context->internal->_initialized) {
6016 errno = EINVAL;
6017 return -1;
6021 if (!fname) {
6023 errno = EINVAL;
6024 return -1;
6028 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
6030 if (smbc_parse_path(context, fname,
6031 workgroup, sizeof(workgroup),
6032 server, sizeof(server),
6033 share, sizeof(share),
6034 path, sizeof(path),
6035 user, sizeof(user),
6036 password, sizeof(password),
6037 NULL, 0)) {
6038 errno = EINVAL;
6039 return -1;
6042 if (user[0] == (char)0) fstrcpy(user, context->user);
6044 srv = smbc_server(context, True,
6045 server, share, workgroup, user, password);
6047 if (!srv) {
6049 return -1; /* errno set by smbc_server */
6053 if (cli_print_queue(srv->cli,
6054 (void (*)(struct print_job_info *))fn) < 0) {
6056 errno = smbc_errno(context, srv->cli);
6057 return -1;
6061 return 0;
6066 * Delete a print job from a remote printer share
6069 static int
6070 smbc_unlink_print_job_ctx(SMBCCTX *context,
6071 const char *fname,
6072 int id)
6074 SMBCSRV *srv;
6075 fstring server;
6076 fstring share;
6077 fstring user;
6078 fstring password;
6079 fstring workgroup;
6080 pstring path;
6081 int err;
6083 if (!context || !context->internal ||
6084 !context->internal->_initialized) {
6086 errno = EINVAL;
6087 return -1;
6091 if (!fname) {
6093 errno = EINVAL;
6094 return -1;
6098 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
6100 if (smbc_parse_path(context, fname,
6101 workgroup, sizeof(workgroup),
6102 server, sizeof(server),
6103 share, sizeof(share),
6104 path, sizeof(path),
6105 user, sizeof(user),
6106 password, sizeof(password),
6107 NULL, 0)) {
6108 errno = EINVAL;
6109 return -1;
6112 if (user[0] == (char)0) fstrcpy(user, context->user);
6114 srv = smbc_server(context, True,
6115 server, share, workgroup, user, password);
6117 if (!srv) {
6119 return -1; /* errno set by smbc_server */
6123 if ((err = cli_printjob_del(srv->cli, id)) != 0) {
6125 if (err < 0)
6126 errno = smbc_errno(context, srv->cli);
6127 else if (err == ERRnosuchprintjob)
6128 errno = EINVAL;
6129 return -1;
6133 return 0;
6138 * Get a new empty handle to fill in with your own info
6140 SMBCCTX *
6141 smbc_new_context(void)
6143 SMBCCTX *context;
6145 context = SMB_MALLOC_P(SMBCCTX);
6146 if (!context) {
6147 errno = ENOMEM;
6148 return NULL;
6151 ZERO_STRUCTP(context);
6153 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
6154 if (!context->internal) {
6155 SAFE_FREE(context);
6156 errno = ENOMEM;
6157 return NULL;
6160 ZERO_STRUCTP(context->internal);
6163 /* ADD REASONABLE DEFAULTS */
6164 context->debug = 0;
6165 context->timeout = 20000; /* 20 seconds */
6167 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
6168 context->options.urlencode_readdir_entries = False;/* backward compat */
6169 context->options.one_share_per_server = False;/* backward compat */
6170 context->internal->_share_mode = SMBC_SHAREMODE_DENY_NONE;
6171 /* backward compat */
6173 context->open = smbc_open_ctx;
6174 context->creat = smbc_creat_ctx;
6175 context->read = smbc_read_ctx;
6176 context->write = smbc_write_ctx;
6177 context->close_fn = smbc_close_ctx;
6178 context->unlink = smbc_unlink_ctx;
6179 context->rename = smbc_rename_ctx;
6180 context->lseek = smbc_lseek_ctx;
6181 context->stat = smbc_stat_ctx;
6182 context->fstat = smbc_fstat_ctx;
6183 context->opendir = smbc_opendir_ctx;
6184 context->closedir = smbc_closedir_ctx;
6185 context->readdir = smbc_readdir_ctx;
6186 context->getdents = smbc_getdents_ctx;
6187 context->mkdir = smbc_mkdir_ctx;
6188 context->rmdir = smbc_rmdir_ctx;
6189 context->telldir = smbc_telldir_ctx;
6190 context->lseekdir = smbc_lseekdir_ctx;
6191 context->fstatdir = smbc_fstatdir_ctx;
6192 context->chmod = smbc_chmod_ctx;
6193 context->utimes = smbc_utimes_ctx;
6194 context->setxattr = smbc_setxattr_ctx;
6195 context->getxattr = smbc_getxattr_ctx;
6196 context->removexattr = smbc_removexattr_ctx;
6197 context->listxattr = smbc_listxattr_ctx;
6198 context->open_print_job = smbc_open_print_job_ctx;
6199 context->print_file = smbc_print_file_ctx;
6200 context->list_print_jobs = smbc_list_print_jobs_ctx;
6201 context->unlink_print_job = smbc_unlink_print_job_ctx;
6203 context->callbacks.check_server_fn = smbc_check_server;
6204 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
6206 smbc_default_cache_functions(context);
6208 return context;
6212 * Free a context
6214 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
6215 * and thus you'll be leaking memory if not handled properly.
6219 smbc_free_context(SMBCCTX *context,
6220 int shutdown_ctx)
6222 if (!context) {
6223 errno = EBADF;
6224 return 1;
6227 if (shutdown_ctx) {
6228 SMBCFILE * f;
6229 DEBUG(1,("Performing aggressive shutdown.\n"));
6231 f = context->internal->_files;
6232 while (f) {
6233 context->close_fn(context, f);
6234 f = f->next;
6236 context->internal->_files = NULL;
6238 /* First try to remove the servers the nice way. */
6239 if (context->callbacks.purge_cached_fn(context)) {
6240 SMBCSRV * s;
6241 SMBCSRV * next;
6242 DEBUG(1, ("Could not purge all servers, "
6243 "Nice way shutdown failed.\n"));
6244 s = context->internal->_servers;
6245 while (s) {
6246 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
6247 s, s->cli->fd));
6248 cli_shutdown(s->cli);
6249 context->callbacks.remove_cached_srv_fn(context,
6251 next = s->next;
6252 DLIST_REMOVE(context->internal->_servers, s);
6253 SAFE_FREE(s);
6254 s = next;
6256 context->internal->_servers = NULL;
6259 else {
6260 /* This is the polite way */
6261 if (context->callbacks.purge_cached_fn(context)) {
6262 DEBUG(1, ("Could not purge all servers, "
6263 "free_context failed.\n"));
6264 errno = EBUSY;
6265 return 1;
6267 if (context->internal->_servers) {
6268 DEBUG(1, ("Active servers in context, "
6269 "free_context failed.\n"));
6270 errno = EBUSY;
6271 return 1;
6273 if (context->internal->_files) {
6274 DEBUG(1, ("Active files in context, "
6275 "free_context failed.\n"));
6276 errno = EBUSY;
6277 return 1;
6281 /* Things we have to clean up */
6282 SAFE_FREE(context->workgroup);
6283 SAFE_FREE(context->netbios_name);
6284 SAFE_FREE(context->user);
6286 DEBUG(3, ("Context %p succesfully freed\n", context));
6287 SAFE_FREE(context->internal);
6288 SAFE_FREE(context);
6289 return 0;
6294 * Each time the context structure is changed, we have binary backward
6295 * compatibility issues. Instead of modifying the public portions of the
6296 * context structure to add new options, instead, we put them in the internal
6297 * portion of the context structure and provide a set function for these new
6298 * options.
6300 void
6301 smbc_option_set(SMBCCTX *context,
6302 char *option_name,
6303 ... /* option_value */)
6305 va_list ap;
6306 union {
6307 int i;
6308 BOOL b;
6309 smbc_get_auth_data_with_context_fn auth_fn;
6310 void *v;
6311 } option_value;
6313 va_start(ap, option_name);
6315 if (strcmp(option_name, "debug_to_stderr") == 0) {
6317 * Log to standard error instead of standard output.
6319 option_value.b = (BOOL) va_arg(ap, int);
6320 context->internal->_debug_stderr = option_value.b;
6322 } else if (strcmp(option_name, "full_time_names") == 0) {
6324 * Use new-style time attribute names, e.g. WRITE_TIME rather
6325 * than the old-style names such as M_TIME. This allows also
6326 * setting/getting CREATE_TIME which was previously
6327 * unimplemented. (Note that the old C_TIME was supposed to
6328 * be CHANGE_TIME but was confused and sometimes referred to
6329 * CREATE_TIME.)
6331 option_value.b = (BOOL) va_arg(ap, int);
6332 context->internal->_full_time_names = option_value.b;
6334 } else if (strcmp(option_name, "open_share_mode") == 0) {
6336 * The share mode to use for files opened with
6337 * smbc_open_ctx(). The default is SMBC_SHAREMODE_DENY_NONE.
6339 option_value.i = va_arg(ap, int);
6340 context->internal->_share_mode =
6341 (smbc_share_mode) option_value.i;
6343 } else if (strcmp(option_name, "auth_function") == 0) {
6345 * Use the new-style authentication function which includes
6346 * the context.
6348 option_value.auth_fn =
6349 va_arg(ap, smbc_get_auth_data_with_context_fn);
6350 context->internal->_auth_fn_with_context =
6351 option_value.auth_fn;
6352 } else if (strcmp(option_name, "user_data") == 0) {
6354 * Save a user data handle which may be retrieved by the user
6355 * with smbc_option_get()
6357 option_value.v = va_arg(ap, void *);
6358 context->internal->_user_data = option_value.v;
6361 va_end(ap);
6366 * Retrieve the current value of an option
6368 void *
6369 smbc_option_get(SMBCCTX *context,
6370 char *option_name)
6372 if (strcmp(option_name, "debug_stderr") == 0) {
6374 * Log to standard error instead of standard output.
6376 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6377 return (void *) (intptr_t) context->internal->_debug_stderr;
6378 #else
6379 return (void *) context->internal->_debug_stderr;
6380 #endif
6381 } else if (strcmp(option_name, "full_time_names") == 0) {
6383 * Use new-style time attribute names, e.g. WRITE_TIME rather
6384 * than the old-style names such as M_TIME. This allows also
6385 * setting/getting CREATE_TIME which was previously
6386 * unimplemented. (Note that the old C_TIME was supposed to
6387 * be CHANGE_TIME but was confused and sometimes referred to
6388 * CREATE_TIME.)
6390 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6391 return (void *) (intptr_t) context->internal->_full_time_names;
6392 #else
6393 return (void *) context->internal->_full_time_names;
6394 #endif
6396 } else if (strcmp(option_name, "auth_function") == 0) {
6398 * Use the new-style authentication function which includes
6399 * the context.
6401 return (void *) context->internal->_auth_fn_with_context;
6402 } else if (strcmp(option_name, "user_data") == 0) {
6404 * Save a user data handle which may be retrieved by the user
6405 * with smbc_option_get()
6407 return context->internal->_user_data;
6410 return NULL;
6415 * Initialise the library etc
6417 * We accept a struct containing handle information.
6418 * valid values for info->debug from 0 to 100,
6419 * and insist that info->fn must be non-null.
6421 SMBCCTX *
6422 smbc_init_context(SMBCCTX *context)
6424 pstring conf;
6425 int pid;
6426 char *user = NULL;
6427 char *home = NULL;
6429 if (!context || !context->internal) {
6430 errno = EBADF;
6431 return NULL;
6434 /* Do not initialise the same client twice */
6435 if (context->internal->_initialized) {
6436 return 0;
6439 if ((!context->callbacks.auth_fn &&
6440 !context->internal->_auth_fn_with_context) ||
6441 context->debug < 0 ||
6442 context->debug > 100) {
6444 errno = EINVAL;
6445 return NULL;
6449 if (!smbc_initialized) {
6451 * Do some library-wide intializations the first time we get
6452 * called
6454 BOOL conf_loaded = False;
6456 /* Set this to what the user wants */
6457 DEBUGLEVEL = context->debug;
6459 load_case_tables();
6461 setup_logging("libsmbclient", True);
6462 if (context->internal->_debug_stderr) {
6463 dbf = x_stderr;
6464 x_setbuf(x_stderr, NULL);
6467 /* Here we would open the smb.conf file if needed ... */
6469 in_client = True; /* FIXME, make a param */
6471 home = getenv("HOME");
6472 if (home) {
6473 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
6474 if (lp_load(conf, True, False, False, True)) {
6475 conf_loaded = True;
6476 } else {
6477 DEBUG(5, ("Could not load config file: %s\n",
6478 conf));
6482 if (!conf_loaded) {
6484 * Well, if that failed, try the dyn_CONFIGFILE
6485 * Which points to the standard locn, and if that
6486 * fails, silently ignore it and use the internal
6487 * defaults ...
6490 if (!lp_load(dyn_CONFIGFILE, True, False, False, False)) {
6491 DEBUG(5, ("Could not load config file: %s\n",
6492 dyn_CONFIGFILE));
6493 } else if (home) {
6495 * We loaded the global config file. Now lets
6496 * load user-specific modifications to the
6497 * global config.
6499 slprintf(conf, sizeof(conf),
6500 "%s/.smb/smb.conf.append", home);
6501 if (!lp_load(conf, True, False, False, False)) {
6502 DEBUG(10,
6503 ("Could not append config file: "
6504 "%s\n",
6505 conf));
6510 load_interfaces(); /* Load the list of interfaces ... */
6512 reopen_logs(); /* Get logging working ... */
6515 * Block SIGPIPE (from lib/util_sock.c: write())
6516 * It is not needed and should not stop execution
6518 BlockSignals(True, SIGPIPE);
6520 /* Done with one-time initialisation */
6521 smbc_initialized = 1;
6525 if (!context->user) {
6527 * FIXME: Is this the best way to get the user info?
6529 user = getenv("USER");
6530 /* walk around as "guest" if no username can be found */
6531 if (!user) context->user = SMB_STRDUP("guest");
6532 else context->user = SMB_STRDUP(user);
6535 if (!context->netbios_name) {
6537 * We try to get our netbios name from the config. If that
6538 * fails we fall back on constructing our netbios name from
6539 * our hostname etc
6541 if (global_myname()) {
6542 context->netbios_name = SMB_STRDUP(global_myname());
6544 else {
6546 * Hmmm, I want to get hostname as well, but I am too
6547 * lazy for the moment
6549 pid = sys_getpid();
6550 context->netbios_name = (char *)SMB_MALLOC(17);
6551 if (!context->netbios_name) {
6552 errno = ENOMEM;
6553 return NULL;
6555 slprintf(context->netbios_name, 16,
6556 "smbc%s%d", context->user, pid);
6560 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
6562 if (!context->workgroup) {
6563 if (lp_workgroup()) {
6564 context->workgroup = SMB_STRDUP(lp_workgroup());
6566 else {
6567 /* TODO: Think about a decent default workgroup */
6568 context->workgroup = SMB_STRDUP("samba");
6572 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
6574 /* shortest timeout is 1 second */
6575 if (context->timeout > 0 && context->timeout < 1000)
6576 context->timeout = 1000;
6579 * FIXME: Should we check the function pointers here?
6582 context->internal->_initialized = True;
6584 return context;
6588 /* Return the verion of samba, and thus libsmbclient */
6589 const char *
6590 smbc_version(void)
6592 return samba_version_string();