r23784: use the GPLv3 boilerplate as recommended by the FSF and the license text
[Samba/bb.git] / source / libsmb / libsmbclient.c
blob90cde9100af4d33ca01ba7ea26bdcb53ee3a8e22
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 3 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, see <http://www.gnu.org/licenses/>.
24 #include "includes.h"
26 #include "include/libsmb_internal.h"
28 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir);
29 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
30 struct smbc_dirent *dirent);
33 * DOS Attribute values (used internally)
35 typedef struct DOS_ATTR_DESC {
36 int mode;
37 SMB_OFF_T size;
38 time_t create_time;
39 time_t access_time;
40 time_t write_time;
41 time_t change_time;
42 SMB_INO_T inode;
43 } DOS_ATTR_DESC;
47 * Internal flags for extended attributes
50 /* internal mode values */
51 #define SMBC_XATTR_MODE_ADD 1
52 #define SMBC_XATTR_MODE_REMOVE 2
53 #define SMBC_XATTR_MODE_REMOVE_ALL 3
54 #define SMBC_XATTR_MODE_SET 4
55 #define SMBC_XATTR_MODE_CHOWN 5
56 #define SMBC_XATTR_MODE_CHGRP 6
58 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
60 /*We should test for this in configure ... */
61 #ifndef ENOTSUP
62 #define ENOTSUP EOPNOTSUPP
63 #endif
66 * Functions exported by libsmb_cache.c that we need here
68 int smbc_default_cache_functions(SMBCCTX *context);
70 /*
71 * check if an element is part of the list.
72 * FIXME: Does not belong here !
73 * Can anyone put this in a macro in dlinklist.h ?
74 * -- Tom
76 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
77 if (!p || !list) return False;
78 do {
79 if (p == list) return True;
80 list = list->next;
81 } while (list);
82 return False;
86 * Find an lsa pipe handle associated with a cli struct.
88 static struct rpc_pipe_client *
89 find_lsa_pipe_hnd(struct cli_state *ipc_cli)
91 struct rpc_pipe_client *pipe_hnd;
93 for (pipe_hnd = ipc_cli->pipe_list;
94 pipe_hnd;
95 pipe_hnd = pipe_hnd->next) {
97 if (pipe_hnd->pipe_idx == PI_LSARPC) {
98 return pipe_hnd;
102 return NULL;
105 static int
106 smbc_close_ctx(SMBCCTX *context,
107 SMBCFILE *file);
108 static off_t
109 smbc_lseek_ctx(SMBCCTX *context,
110 SMBCFILE *file,
111 off_t offset,
112 int whence);
114 extern BOOL in_client;
117 * Is the logging working / configfile read ?
119 static int smbc_initialized = 0;
121 static int
122 hex2int( unsigned int _char )
124 if ( _char >= 'A' && _char <='F')
125 return _char - 'A' + 10;
126 if ( _char >= 'a' && _char <='f')
127 return _char - 'a' + 10;
128 if ( _char >= '0' && _char <='9')
129 return _char - '0';
130 return -1;
134 * smbc_urldecode()
136 * Convert strings of %xx to their single character equivalent. Each 'x' must
137 * be a valid hexadecimal digit, or that % sequence is left undecoded.
139 * dest may, but need not be, the same pointer as src.
141 * Returns the number of % sequences which could not be converted due to lack
142 * of two following hexadecimal digits.
145 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
147 int old_length = strlen(src);
148 int i = 0;
149 int err_count = 0;
150 pstring temp;
151 char * p;
153 if ( old_length == 0 ) {
154 return 0;
157 p = temp;
158 while ( i < old_length ) {
159 unsigned char character = src[ i++ ];
161 if (character == '%') {
162 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
163 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
165 /* Replace valid sequence */
166 if (a != -1 && b != -1) {
168 /* Replace valid %xx sequence with %dd */
169 character = (a * 16) + b;
171 if (character == '\0') {
172 break; /* Stop at %00 */
175 i += 2;
176 } else {
178 err_count++;
182 *p++ = character;
185 *p = '\0';
187 strncpy(dest, temp, max_dest_len - 1);
188 dest[max_dest_len - 1] = '\0';
190 return err_count;
194 * smbc_urlencode()
196 * Convert any characters not specifically allowed in a URL into their %xx
197 * equivalent.
199 * Returns the remaining buffer length.
202 smbc_urlencode(char * dest, char * src, int max_dest_len)
204 char hex[] = "0123456789ABCDEF";
206 for (; *src != '\0' && max_dest_len >= 3; src++) {
208 if ((*src < '0' &&
209 *src != '-' &&
210 *src != '.') ||
211 (*src > '9' &&
212 *src < 'A') ||
213 (*src > 'Z' &&
214 *src < 'a' &&
215 *src != '_') ||
216 (*src > 'z')) {
217 *dest++ = '%';
218 *dest++ = hex[(*src >> 4) & 0x0f];
219 *dest++ = hex[*src & 0x0f];
220 max_dest_len -= 3;
221 } else {
222 *dest++ = *src;
223 max_dest_len--;
227 *dest++ = '\0';
228 max_dest_len--;
230 return max_dest_len;
234 * Function to parse a path and turn it into components
236 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
237 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
238 * general format ("smb:" only; we do not look for "cifs:").
241 * We accept:
242 * smb://[[[domain;]user[:password]@]server[/share[/path[/file]]]][?options]
244 * Meaning of URLs:
246 * smb:// Show all workgroups.
248 * The method of locating the list of workgroups varies
249 * depending upon the setting of the context variable
250 * context->options.browse_max_lmb_count. This value
251 * determine the maximum number of local master browsers to
252 * query for the list of workgroups. In order to ensure that
253 * a complete list of workgroups is obtained, all master
254 * browsers must be queried, but if there are many
255 * workgroups, the time spent querying can begin to add up.
256 * For small networks (not many workgroups), it is suggested
257 * that this variable be set to 0, indicating query all local
258 * master browsers. When the network has many workgroups, a
259 * reasonable setting for this variable might be around 3.
261 * smb://name/ if name<1D> or name<1B> exists, list servers in
262 * workgroup, else, if name<20> exists, list all shares
263 * for server ...
265 * If "options" are provided, this function returns the entire option list as a
266 * string, for later parsing by the caller. Note that currently, no options
267 * are supported.
270 static const char *smbc_prefix = "smb:";
272 static int
273 smbc_parse_path(SMBCCTX *context,
274 const char *fname,
275 char *workgroup, int workgroup_len,
276 char *server, int server_len,
277 char *share, int share_len,
278 char *path, int path_len,
279 char *user, int user_len,
280 char *password, int password_len,
281 char *options, int options_len)
283 static pstring s;
284 pstring userinfo;
285 const char *p;
286 char *q, *r;
287 int len;
289 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
292 * Assume we wont find an authentication domain to parse, so default
293 * to the workgroup in the provided context.
295 if (workgroup != NULL) {
296 strncpy(workgroup, context->workgroup, workgroup_len - 1);
297 workgroup[workgroup_len - 1] = '\0';
300 if (options != NULL && options_len > 0) {
301 options[0] = (char)0;
303 pstrcpy(s, fname);
305 /* see if it has the right prefix */
306 len = strlen(smbc_prefix);
307 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
308 return -1; /* What about no smb: ? */
311 p = s + len;
313 /* Watch the test below, we are testing to see if we should exit */
315 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
317 DEBUG(1, ("Invalid path (does not begin with smb://"));
318 return -1;
322 p += 2; /* Skip the double slash */
324 /* See if any options were specified */
325 if ((q = strrchr(p, '?')) != NULL ) {
326 /* There are options. Null terminate here and point to them */
327 *q++ = '\0';
329 DEBUG(4, ("Found options '%s'", q));
331 /* Copy the options */
332 if (options != NULL && options_len > 0) {
333 safe_strcpy(options, q, options_len - 1);
337 if (*p == (char)0)
338 goto decoding;
340 if (*p == '/') {
341 int wl = strlen(context->workgroup);
343 if (wl > 16) {
344 wl = 16;
347 strncpy(server, context->workgroup, wl);
348 server[wl] = '\0';
349 return 0;
353 * ok, its for us. Now parse out the server, share etc.
355 * However, we want to parse out [[domain;]user[:password]@] if it
356 * exists ...
359 /* check that '@' occurs before '/', if '/' exists at all */
360 q = strchr_m(p, '@');
361 r = strchr_m(p, '/');
362 if (q && (!r || q < r)) {
363 pstring username, passwd, domain;
364 const char *u = userinfo;
366 next_token_no_ltrim(&p, userinfo, "@", sizeof(fstring));
368 username[0] = passwd[0] = domain[0] = 0;
370 if (strchr_m(u, ';')) {
372 next_token_no_ltrim(&u, domain, ";", sizeof(fstring));
376 if (strchr_m(u, ':')) {
378 next_token_no_ltrim(&u, username, ":", sizeof(fstring));
380 pstrcpy(passwd, u);
383 else {
385 pstrcpy(username, u);
389 if (domain[0] && workgroup) {
390 strncpy(workgroup, domain, workgroup_len - 1);
391 workgroup[workgroup_len - 1] = '\0';
394 if (username[0]) {
395 strncpy(user, username, user_len - 1);
396 user[user_len - 1] = '\0';
399 if (passwd[0]) {
400 strncpy(password, passwd, password_len - 1);
401 password[password_len - 1] = '\0';
406 if (!next_token(&p, server, "/", sizeof(fstring))) {
408 return -1;
412 if (*p == (char)0) goto decoding; /* That's it ... */
414 if (!next_token(&p, share, "/", sizeof(fstring))) {
416 return -1;
421 * Prepend a leading slash if there's a file path, as required by
422 * NetApp filers.
424 *path = '\0';
425 if (*p != '\0') {
426 *path = '/';
427 safe_strcpy(path + 1, p, path_len - 2);
430 all_string_sub(path, "/", "\\", 0);
432 decoding:
433 (void) smbc_urldecode(path, path, path_len);
434 (void) smbc_urldecode(server, server, server_len);
435 (void) smbc_urldecode(share, share, share_len);
436 (void) smbc_urldecode(user, user, user_len);
437 (void) smbc_urldecode(password, password, password_len);
439 return 0;
443 * Verify that the options specified in a URL are valid
445 static int
446 smbc_check_options(char *server,
447 char *share,
448 char *path,
449 char *options)
451 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' "
452 "path='%s' options='%s'\n",
453 server, share, path, options));
455 /* No options at all is always ok */
456 if (! *options) return 0;
458 /* Currently, we don't support any options. */
459 return -1;
463 * Convert an SMB error into a UNIX error ...
465 static int
466 smbc_errno(SMBCCTX *context,
467 struct cli_state *c)
469 int ret = cli_errno(c);
471 if (cli_is_dos_error(c)) {
472 uint8 eclass;
473 uint32 ecode;
475 cli_dos_error(c, &eclass, &ecode);
477 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
478 (int)eclass, (int)ecode, (int)ecode, ret));
479 } else {
480 NTSTATUS status;
482 status = cli_nt_error(c);
484 DEBUG(3,("smbc errno %s -> %d\n",
485 nt_errstr(status), ret));
488 return ret;
492 * Check a server for being alive and well.
493 * returns 0 if the server is in shape. Returns 1 on error
495 * Also useable outside libsmbclient to enable external cache
496 * to do some checks too.
498 static int
499 smbc_check_server(SMBCCTX * context,
500 SMBCSRV * server)
502 socklen_t size;
503 struct sockaddr addr;
506 * Although the use of port 139 is not a guarantee that we're using
507 * netbios, we assume so. We don't want to send a keepalive packet if
508 * not netbios because it's not valid, and Vista, at least,
509 * disconnects the client on such a request.
511 if (server->cli->port == 139) {
512 /* Assuming netbios. Send a keepalive packet */
513 if ( send_keepalive(server->cli->fd) == False ) {
514 return 1;
516 } else {
518 * Assuming not netbios. Try a different method to detect if
519 * the connection is still alive.
521 size = sizeof(addr);
522 if (getpeername(server->cli->fd, &addr, &size) == -1) {
523 return 1;
527 /* connection is ok */
528 return 0;
532 * Remove a server from the cached server list it's unused.
533 * On success, 0 is returned. 1 is returned if the server could not be removed.
535 * Also useable outside libsmbclient
538 smbc_remove_unused_server(SMBCCTX * context,
539 SMBCSRV * srv)
541 SMBCFILE * file;
543 /* are we being fooled ? */
544 if (!context || !context->internal ||
545 !context->internal->_initialized || !srv) return 1;
548 /* Check all open files/directories for a relation with this server */
549 for (file = context->internal->_files; file; file=file->next) {
550 if (file->srv == srv) {
551 /* Still used */
552 DEBUG(3, ("smbc_remove_usused_server: "
553 "%p still used by %p.\n",
554 srv, file));
555 return 1;
559 DLIST_REMOVE(context->internal->_servers, srv);
561 cli_shutdown(srv->cli);
562 srv->cli = NULL;
564 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
566 context->callbacks.remove_cached_srv_fn(context, srv);
568 SAFE_FREE(srv);
570 return 0;
573 static SMBCSRV *
574 find_server(SMBCCTX *context,
575 const char *server,
576 const char *share,
577 fstring workgroup,
578 fstring username,
579 fstring password)
581 SMBCSRV *srv;
582 int auth_called = 0;
584 check_server_cache:
586 srv = context->callbacks.get_cached_srv_fn(context, server, share,
587 workgroup, username);
589 if (!auth_called && !srv && (!username[0] || !password[0])) {
590 if (context->internal->_auth_fn_with_context != NULL) {
591 context->internal->_auth_fn_with_context(
592 context,
593 server, share,
594 workgroup, sizeof(fstring),
595 username, sizeof(fstring),
596 password, sizeof(fstring));
597 } else {
598 context->callbacks.auth_fn(
599 server, share,
600 workgroup, sizeof(fstring),
601 username, sizeof(fstring),
602 password, sizeof(fstring));
606 * However, smbc_auth_fn may have picked up info relating to
607 * an existing connection, so try for an existing connection
608 * again ...
610 auth_called = 1;
611 goto check_server_cache;
615 if (srv) {
616 if (context->callbacks.check_server_fn(context, srv)) {
618 * This server is no good anymore
619 * Try to remove it and check for more possible
620 * servers in the cache
622 if (context->callbacks.remove_unused_server_fn(context,
623 srv)) {
625 * We could not remove the server completely,
626 * remove it from the cache so we will not get
627 * it again. It will be removed when the last
628 * file/dir is closed.
630 context->callbacks.remove_cached_srv_fn(context,
631 srv);
635 * Maybe there are more cached connections to this
636 * server
638 goto check_server_cache;
641 return srv;
644 return NULL;
648 * Connect to a server, possibly on an existing connection
650 * Here, what we want to do is: If the server and username
651 * match an existing connection, reuse that, otherwise, establish a
652 * new connection.
654 * If we have to create a new connection, call the auth_fn to get the
655 * info we need, unless the username and password were passed in.
658 static SMBCSRV *
659 smbc_server(SMBCCTX *context,
660 BOOL connect_if_not_found,
661 const char *server,
662 const char *share,
663 fstring workgroup,
664 fstring username,
665 fstring password)
667 SMBCSRV *srv=NULL;
668 struct cli_state *c;
669 struct nmb_name called, calling;
670 const char *server_n = server;
671 pstring ipenv;
672 struct in_addr ip;
673 int tried_reverse = 0;
674 int port_try_first;
675 int port_try_next;
676 const char *username_used;
677 NTSTATUS status;
679 zero_ip(&ip);
680 ZERO_STRUCT(c);
682 if (server[0] == 0) {
683 errno = EPERM;
684 return NULL;
687 /* Look for a cached connection */
688 srv = find_server(context, server, share,
689 workgroup, username, password);
692 * If we found a connection and we're only allowed one share per
693 * server...
695 if (srv && *share != '\0' && context->options.one_share_per_server) {
698 * ... then if there's no current connection to the share,
699 * connect to it. find_server(), or rather the function
700 * pointed to by context->callbacks.get_cached_srv_fn which
701 * was called by find_server(), will have issued a tree
702 * disconnect if the requested share is not the same as the
703 * one that was already connected.
705 if (srv->cli->cnum == (uint16) -1) {
706 /* Ensure we have accurate auth info */
707 if (context->internal->_auth_fn_with_context != NULL) {
708 context->internal->_auth_fn_with_context(
709 context,
710 server, share,
711 workgroup, sizeof(fstring),
712 username, sizeof(fstring),
713 password, sizeof(fstring));
714 } else {
715 context->callbacks.auth_fn(
716 server, share,
717 workgroup, sizeof(fstring),
718 username, sizeof(fstring),
719 password, sizeof(fstring));
722 if (! cli_send_tconX(srv->cli, share, "?????",
723 password, strlen(password)+1)) {
725 errno = smbc_errno(context, srv->cli);
726 cli_shutdown(srv->cli);
727 srv->cli = NULL;
728 context->callbacks.remove_cached_srv_fn(context,
729 srv);
730 srv = NULL;
734 * Regenerate the dev value since it's based on both
735 * server and share
737 if (srv) {
738 srv->dev = (dev_t)(str_checksum(server) ^
739 str_checksum(share));
744 /* If we have a connection... */
745 if (srv) {
747 /* ... then we're done here. Give 'em what they came for. */
748 return srv;
751 /* If we're not asked to connect when a connection doesn't exist... */
752 if (! connect_if_not_found) {
753 /* ... then we're done here. */
754 return NULL;
757 make_nmb_name(&calling, context->netbios_name, 0x0);
758 make_nmb_name(&called , server, 0x20);
760 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
762 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
764 again:
765 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
767 zero_ip(&ip);
769 /* have to open a new connection */
770 if ((c = cli_initialise()) == NULL) {
771 errno = ENOMEM;
772 return NULL;
775 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
776 c->use_kerberos = True;
778 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
779 c->fallback_after_kerberos = True;
782 c->timeout = context->timeout;
785 * Force use of port 139 for first try if share is $IPC, empty, or
786 * null, so browse lists can work
788 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
789 port_try_first = 139;
790 port_try_next = 445;
791 } else {
792 port_try_first = 445;
793 port_try_next = 139;
796 c->port = port_try_first;
798 status = cli_connect(c, server_n, &ip);
799 if (!NT_STATUS_IS_OK(status)) {
801 /* First connection attempt failed. Try alternate port. */
802 c->port = port_try_next;
804 status = cli_connect(c, server_n, &ip);
805 if (!NT_STATUS_IS_OK(status)) {
806 cli_shutdown(c);
807 errno = ETIMEDOUT;
808 return NULL;
812 if (!cli_session_request(c, &calling, &called)) {
813 cli_shutdown(c);
814 if (strcmp(called.name, "*SMBSERVER")) {
815 make_nmb_name(&called , "*SMBSERVER", 0x20);
816 goto again;
817 } else { /* Try one more time, but ensure we don't loop */
819 /* Only try this if server is an IP address ... */
821 if (is_ipaddress(server) && !tried_reverse) {
822 fstring remote_name;
823 struct in_addr rem_ip;
825 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
826 DEBUG(4, ("Could not convert IP address "
827 "%s to struct in_addr\n", server));
828 errno = ETIMEDOUT;
829 return NULL;
832 tried_reverse++; /* Yuck */
834 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
835 make_nmb_name(&called, remote_name, 0x20);
836 goto again;
840 errno = ETIMEDOUT;
841 return NULL;
844 DEBUG(4,(" session request ok\n"));
846 if (!cli_negprot(c)) {
847 cli_shutdown(c);
848 errno = ETIMEDOUT;
849 return NULL;
852 username_used = username;
854 if (!NT_STATUS_IS_OK(cli_session_setup(c, username_used,
855 password, strlen(password),
856 password, strlen(password),
857 workgroup))) {
859 /* Failed. Try an anonymous login, if allowed by flags. */
860 username_used = "";
862 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
863 !NT_STATUS_IS_OK(cli_session_setup(c, username_used,
864 password, 1,
865 password, 0,
866 workgroup))) {
868 cli_shutdown(c);
869 errno = EPERM;
870 return NULL;
874 DEBUG(4,(" session setup ok\n"));
876 if (!cli_send_tconX(c, share, "?????",
877 password, strlen(password)+1)) {
878 errno = smbc_errno(context, c);
879 cli_shutdown(c);
880 return NULL;
883 DEBUG(4,(" tconx ok\n"));
886 * Ok, we have got a nice connection
887 * Let's allocate a server structure.
890 srv = SMB_MALLOC_P(SMBCSRV);
891 if (!srv) {
892 errno = ENOMEM;
893 goto failed;
896 ZERO_STRUCTP(srv);
897 srv->cli = c;
898 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
899 srv->no_pathinfo = False;
900 srv->no_pathinfo2 = False;
901 srv->no_nt_session = False;
903 /* now add it to the cache (internal or external) */
904 /* Let the cache function set errno if it wants to */
905 errno = 0;
906 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
907 int saved_errno = errno;
908 DEBUG(3, (" Failed to add server to cache\n"));
909 errno = saved_errno;
910 if (errno == 0) {
911 errno = ENOMEM;
913 goto failed;
916 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
917 server, share, srv));
919 DLIST_ADD(context->internal->_servers, srv);
920 return srv;
922 failed:
923 cli_shutdown(c);
924 if (!srv) {
925 return NULL;
928 SAFE_FREE(srv);
929 return NULL;
933 * Connect to a server for getting/setting attributes, possibly on an existing
934 * connection. This works similarly to smbc_server().
936 static SMBCSRV *
937 smbc_attr_server(SMBCCTX *context,
938 const char *server,
939 const char *share,
940 fstring workgroup,
941 fstring username,
942 fstring password,
943 POLICY_HND *pol)
945 int flags;
946 struct in_addr ip;
947 struct cli_state *ipc_cli;
948 struct rpc_pipe_client *pipe_hnd;
949 NTSTATUS nt_status;
950 SMBCSRV *ipc_srv=NULL;
953 * See if we've already created this special connection. Reference
954 * our "special" share name '*IPC$', which is an impossible real share
955 * name due to the leading asterisk.
957 ipc_srv = find_server(context, server, "*IPC$",
958 workgroup, username, password);
959 if (!ipc_srv) {
961 /* We didn't find a cached connection. Get the password */
962 if (*password == '\0') {
963 /* ... then retrieve it now. */
964 if (context->internal->_auth_fn_with_context != NULL) {
965 context->internal->_auth_fn_with_context(
966 context,
967 server, share,
968 workgroup, sizeof(fstring),
969 username, sizeof(fstring),
970 password, sizeof(fstring));
971 } else {
972 context->callbacks.auth_fn(
973 server, share,
974 workgroup, sizeof(fstring),
975 username, sizeof(fstring),
976 password, sizeof(fstring));
980 flags = 0;
981 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
982 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
985 zero_ip(&ip);
986 nt_status = cli_full_connection(&ipc_cli,
987 global_myname(), server,
988 &ip, 0, "IPC$", "?????",
989 username, workgroup,
990 password, flags,
991 Undefined, NULL);
992 if (! NT_STATUS_IS_OK(nt_status)) {
993 DEBUG(1,("cli_full_connection failed! (%s)\n",
994 nt_errstr(nt_status)));
995 errno = ENOTSUP;
996 return NULL;
999 ipc_srv = SMB_MALLOC_P(SMBCSRV);
1000 if (!ipc_srv) {
1001 errno = ENOMEM;
1002 cli_shutdown(ipc_cli);
1003 return NULL;
1006 ZERO_STRUCTP(ipc_srv);
1007 ipc_srv->cli = ipc_cli;
1009 if (pol) {
1010 pipe_hnd = cli_rpc_pipe_open_noauth(ipc_srv->cli,
1011 PI_LSARPC,
1012 &nt_status);
1013 if (!pipe_hnd) {
1014 DEBUG(1, ("cli_nt_session_open fail!\n"));
1015 errno = ENOTSUP;
1016 cli_shutdown(ipc_srv->cli);
1017 free(ipc_srv);
1018 return NULL;
1022 * Some systems don't support
1023 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
1024 * so we might as well do it too.
1027 nt_status = rpccli_lsa_open_policy(
1028 pipe_hnd,
1029 ipc_srv->cli->mem_ctx,
1030 True,
1031 GENERIC_EXECUTE_ACCESS,
1032 pol);
1034 if (!NT_STATUS_IS_OK(nt_status)) {
1035 errno = smbc_errno(context, ipc_srv->cli);
1036 cli_shutdown(ipc_srv->cli);
1037 return NULL;
1041 /* now add it to the cache (internal or external) */
1043 errno = 0; /* let cache function set errno if it likes */
1044 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
1045 server,
1046 "*IPC$",
1047 workgroup,
1048 username)) {
1049 DEBUG(3, (" Failed to add server to cache\n"));
1050 if (errno == 0) {
1051 errno = ENOMEM;
1053 cli_shutdown(ipc_srv->cli);
1054 free(ipc_srv);
1055 return NULL;
1058 DLIST_ADD(context->internal->_servers, ipc_srv);
1061 return ipc_srv;
1065 * Routine to open() a file ...
1068 static SMBCFILE *
1069 smbc_open_ctx(SMBCCTX *context,
1070 const char *fname,
1071 int flags,
1072 mode_t mode)
1074 fstring server, share, user, password, workgroup;
1075 pstring path;
1076 pstring targetpath;
1077 struct cli_state *targetcli;
1078 SMBCSRV *srv = NULL;
1079 SMBCFILE *file = NULL;
1080 int fd;
1082 if (!context || !context->internal ||
1083 !context->internal->_initialized) {
1085 errno = EINVAL; /* Best I can think of ... */
1086 return NULL;
1090 if (!fname) {
1092 errno = EINVAL;
1093 return NULL;
1097 if (smbc_parse_path(context, fname,
1098 workgroup, sizeof(workgroup),
1099 server, sizeof(server),
1100 share, sizeof(share),
1101 path, sizeof(path),
1102 user, sizeof(user),
1103 password, sizeof(password),
1104 NULL, 0)) {
1105 errno = EINVAL;
1106 return NULL;
1109 if (user[0] == (char)0) fstrcpy(user, context->user);
1111 srv = smbc_server(context, True,
1112 server, share, workgroup, user, password);
1114 if (!srv) {
1116 if (errno == EPERM) errno = EACCES;
1117 return NULL; /* smbc_server sets errno */
1121 /* Hmmm, the test for a directory is suspect here ... FIXME */
1123 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1125 fd = -1;
1128 else {
1130 file = SMB_MALLOC_P(SMBCFILE);
1132 if (!file) {
1134 errno = ENOMEM;
1135 return NULL;
1139 ZERO_STRUCTP(file);
1141 /*d_printf(">>>open: resolving %s\n", path);*/
1142 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1144 d_printf("Could not resolve %s\n", path);
1145 SAFE_FREE(file);
1146 return NULL;
1148 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1150 if ((fd = cli_open(targetcli, targetpath, flags,
1151 context->internal->_share_mode)) < 0) {
1153 /* Handle the error ... */
1155 SAFE_FREE(file);
1156 errno = smbc_errno(context, targetcli);
1157 return NULL;
1161 /* Fill in file struct */
1163 file->cli_fd = fd;
1164 file->fname = SMB_STRDUP(fname);
1165 file->srv = srv;
1166 file->offset = 0;
1167 file->file = True;
1169 DLIST_ADD(context->internal->_files, file);
1172 * If the file was opened in O_APPEND mode, all write
1173 * operations should be appended to the file. To do that,
1174 * though, using this protocol, would require a getattrE()
1175 * call for each and every write, to determine where the end
1176 * of the file is. (There does not appear to be an append flag
1177 * in the protocol.) Rather than add all of that overhead of
1178 * retrieving the current end-of-file offset prior to each
1179 * write operation, we'll assume that most append operations
1180 * will continuously write, so we'll just set the offset to
1181 * the end of the file now and hope that's adequate.
1183 * Note to self: If this proves inadequate, and O_APPEND
1184 * should, in some cases, be forced for each write, add a
1185 * field in the context options structure, for
1186 * "strict_append_mode" which would select between the current
1187 * behavior (if FALSE) or issuing a getattrE() prior to each
1188 * write and forcing the write to the end of the file (if
1189 * TRUE). Adding that capability will likely require adding
1190 * an "append" flag into the _SMBCFILE structure to track
1191 * whether a file was opened in O_APPEND mode. -- djl
1193 if (flags & O_APPEND) {
1194 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1195 (void) smbc_close_ctx(context, file);
1196 errno = ENXIO;
1197 return NULL;
1201 return file;
1205 /* Check if opendir needed ... */
1207 if (fd == -1) {
1208 int eno = 0;
1210 eno = smbc_errno(context, srv->cli);
1211 file = context->opendir(context, fname);
1212 if (!file) errno = eno;
1213 return file;
1217 errno = EINVAL; /* FIXME, correct errno ? */
1218 return NULL;
1223 * Routine to create a file
1226 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1228 static SMBCFILE *
1229 smbc_creat_ctx(SMBCCTX *context,
1230 const char *path,
1231 mode_t mode)
1234 if (!context || !context->internal ||
1235 !context->internal->_initialized) {
1237 errno = EINVAL;
1238 return NULL;
1242 return smbc_open_ctx(context, path, creat_bits, mode);
1246 * Routine to read() a file ...
1249 static ssize_t
1250 smbc_read_ctx(SMBCCTX *context,
1251 SMBCFILE *file,
1252 void *buf,
1253 size_t count)
1255 int ret;
1256 fstring server, share, user, password;
1257 pstring path, targetpath;
1258 struct cli_state *targetcli;
1261 * offset:
1263 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1264 * appears to pass file->offset (which is type off_t) differently than
1265 * a local variable of type off_t. Using local variable "offset" in
1266 * the call to cli_read() instead of file->offset fixes a problem
1267 * retrieving data at an offset greater than 4GB.
1269 off_t offset;
1271 if (!context || !context->internal ||
1272 !context->internal->_initialized) {
1274 errno = EINVAL;
1275 return -1;
1279 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1281 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1283 errno = EBADF;
1284 return -1;
1288 offset = file->offset;
1290 /* Check that the buffer exists ... */
1292 if (buf == NULL) {
1294 errno = EINVAL;
1295 return -1;
1299 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1300 if (smbc_parse_path(context, file->fname,
1301 NULL, 0,
1302 server, sizeof(server),
1303 share, sizeof(share),
1304 path, sizeof(path),
1305 user, sizeof(user),
1306 password, sizeof(password),
1307 NULL, 0)) {
1308 errno = EINVAL;
1309 return -1;
1312 /*d_printf(">>>read: resolving %s\n", path);*/
1313 if (!cli_resolve_path("", file->srv->cli, path,
1314 &targetcli, targetpath))
1316 d_printf("Could not resolve %s\n", path);
1317 return -1;
1319 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1321 ret = cli_read(targetcli, file->cli_fd, (char *)buf, offset, count);
1323 if (ret < 0) {
1325 errno = smbc_errno(context, targetcli);
1326 return -1;
1330 file->offset += ret;
1332 DEBUG(4, (" --> %d\n", ret));
1334 return ret; /* Success, ret bytes of data ... */
1339 * Routine to write() a file ...
1342 static ssize_t
1343 smbc_write_ctx(SMBCCTX *context,
1344 SMBCFILE *file,
1345 void *buf,
1346 size_t count)
1348 int ret;
1349 off_t offset;
1350 fstring server, share, user, password;
1351 pstring path, targetpath;
1352 struct cli_state *targetcli;
1354 /* First check all pointers before dereferencing them */
1356 if (!context || !context->internal ||
1357 !context->internal->_initialized) {
1359 errno = EINVAL;
1360 return -1;
1364 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1366 errno = EBADF;
1367 return -1;
1371 /* Check that the buffer exists ... */
1373 if (buf == NULL) {
1375 errno = EINVAL;
1376 return -1;
1380 offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1382 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1383 if (smbc_parse_path(context, file->fname,
1384 NULL, 0,
1385 server, sizeof(server),
1386 share, sizeof(share),
1387 path, sizeof(path),
1388 user, sizeof(user),
1389 password, sizeof(password),
1390 NULL, 0)) {
1391 errno = EINVAL;
1392 return -1;
1395 /*d_printf(">>>write: resolving %s\n", path);*/
1396 if (!cli_resolve_path("", file->srv->cli, path,
1397 &targetcli, targetpath))
1399 d_printf("Could not resolve %s\n", path);
1400 return -1;
1402 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1405 ret = cli_write(targetcli, file->cli_fd, 0, (char *)buf, offset, count);
1407 if (ret <= 0) {
1409 errno = smbc_errno(context, targetcli);
1410 return -1;
1414 file->offset += ret;
1416 return ret; /* Success, 0 bytes of data ... */
1420 * Routine to close() a file ...
1423 static int
1424 smbc_close_ctx(SMBCCTX *context,
1425 SMBCFILE *file)
1427 SMBCSRV *srv;
1428 fstring server, share, user, password;
1429 pstring path, targetpath;
1430 struct cli_state *targetcli;
1432 if (!context || !context->internal ||
1433 !context->internal->_initialized) {
1435 errno = EINVAL;
1436 return -1;
1440 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1442 errno = EBADF;
1443 return -1;
1447 /* IS a dir ... */
1448 if (!file->file) {
1450 return context->closedir(context, file);
1454 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1455 if (smbc_parse_path(context, file->fname,
1456 NULL, 0,
1457 server, sizeof(server),
1458 share, sizeof(share),
1459 path, sizeof(path),
1460 user, sizeof(user),
1461 password, sizeof(password),
1462 NULL, 0)) {
1463 errno = EINVAL;
1464 return -1;
1467 /*d_printf(">>>close: resolving %s\n", path);*/
1468 if (!cli_resolve_path("", file->srv->cli, path,
1469 &targetcli, targetpath))
1471 d_printf("Could not resolve %s\n", path);
1472 return -1;
1474 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1476 if (!cli_close(targetcli, file->cli_fd)) {
1478 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1479 file->fname));
1480 /* Deallocate slot and remove the server
1481 * from the server cache if unused */
1482 errno = smbc_errno(context, targetcli);
1483 srv = file->srv;
1484 DLIST_REMOVE(context->internal->_files, file);
1485 SAFE_FREE(file->fname);
1486 SAFE_FREE(file);
1487 context->callbacks.remove_unused_server_fn(context, srv);
1489 return -1;
1493 DLIST_REMOVE(context->internal->_files, file);
1494 SAFE_FREE(file->fname);
1495 SAFE_FREE(file);
1497 return 0;
1501 * Get info from an SMB server on a file. Use a qpathinfo call first
1502 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1504 static BOOL
1505 smbc_getatr(SMBCCTX * context,
1506 SMBCSRV *srv,
1507 char *path,
1508 uint16 *mode,
1509 SMB_OFF_T *size,
1510 struct timespec *create_time_ts,
1511 struct timespec *access_time_ts,
1512 struct timespec *write_time_ts,
1513 struct timespec *change_time_ts,
1514 SMB_INO_T *ino)
1516 pstring fixedpath;
1517 pstring targetpath;
1518 struct cli_state *targetcli;
1519 time_t write_time;
1521 if (!context || !context->internal ||
1522 !context->internal->_initialized) {
1524 errno = EINVAL;
1525 return -1;
1529 /* path fixup for . and .. */
1530 if (strequal(path, ".") || strequal(path, ".."))
1531 pstrcpy(fixedpath, "\\");
1532 else
1534 pstrcpy(fixedpath, path);
1535 trim_string(fixedpath, NULL, "\\..");
1536 trim_string(fixedpath, NULL, "\\.");
1538 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1540 if (!cli_resolve_path( "", srv->cli, fixedpath, &targetcli, targetpath))
1542 d_printf("Couldn't resolve %s\n", path);
1543 return False;
1546 if (!srv->no_pathinfo2 &&
1547 cli_qpathinfo2(targetcli, targetpath,
1548 create_time_ts,
1549 access_time_ts,
1550 write_time_ts,
1551 change_time_ts,
1552 size, mode, ino)) {
1553 return True;
1556 /* if this is NT then don't bother with the getatr */
1557 if (targetcli->capabilities & CAP_NT_SMBS) {
1558 errno = EPERM;
1559 return False;
1562 if (cli_getatr(targetcli, targetpath, mode, size, &write_time)) {
1564 struct timespec w_time_ts;
1566 w_time_ts = convert_time_t_to_timespec(write_time);
1568 if (write_time_ts != NULL) {
1569 *write_time_ts = w_time_ts;
1572 if (create_time_ts != NULL) {
1573 *create_time_ts = w_time_ts;
1576 if (access_time_ts != NULL) {
1577 *access_time_ts = w_time_ts;
1580 if (change_time_ts != NULL) {
1581 *change_time_ts = w_time_ts;
1584 srv->no_pathinfo2 = True;
1585 return True;
1588 errno = EPERM;
1589 return False;
1594 * Set file info on an SMB server. Use setpathinfo call first. If that
1595 * fails, use setattrE..
1597 * Access and modification time parameters are always used and must be
1598 * provided. Create time, if zero, will be determined from the actual create
1599 * time of the file. If non-zero, the create time will be set as well.
1601 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1603 static BOOL
1604 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1605 time_t create_time,
1606 time_t access_time,
1607 time_t write_time,
1608 time_t change_time,
1609 uint16 mode)
1611 int fd;
1612 int ret;
1615 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1616 * modern function for "new code" to be using, and it works given a
1617 * filename rather than requiring that the file be opened to have its
1618 * attributes manipulated.
1620 if (srv->no_pathinfo ||
1621 ! cli_setpathinfo(srv->cli, path,
1622 create_time,
1623 access_time,
1624 write_time,
1625 change_time,
1626 mode)) {
1629 * setpathinfo is not supported; go to plan B.
1631 * cli_setatr() does not work on win98, and it also doesn't
1632 * support setting the access time (only the modification
1633 * time), so in all cases, we open the specified file and use
1634 * cli_setattrE() which should work on all OS versions, and
1635 * supports both times.
1638 /* Don't try {q,set}pathinfo() again, with this server */
1639 srv->no_pathinfo = True;
1641 /* Open the file */
1642 if ((fd = cli_open(srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1644 errno = smbc_errno(context, srv->cli);
1645 return -1;
1648 /* Set the new attributes */
1649 ret = cli_setattrE(srv->cli, fd,
1650 change_time,
1651 access_time,
1652 write_time);
1654 /* Close the file */
1655 cli_close(srv->cli, fd);
1658 * Unfortunately, setattrE() doesn't have a provision for
1659 * setting the access mode (attributes). We'll have to try
1660 * cli_setatr() for that, and with only this parameter, it
1661 * seems to work on win98.
1663 if (ret && mode != (uint16) -1) {
1664 ret = cli_setatr(srv->cli, path, mode, 0);
1667 if (! ret) {
1668 errno = smbc_errno(context, srv->cli);
1669 return False;
1673 return True;
1677 * Routine to unlink() a file
1680 static int
1681 smbc_unlink_ctx(SMBCCTX *context,
1682 const char *fname)
1684 fstring server, share, user, password, workgroup;
1685 pstring path, targetpath;
1686 struct cli_state *targetcli;
1687 SMBCSRV *srv = NULL;
1689 if (!context || !context->internal ||
1690 !context->internal->_initialized) {
1692 errno = EINVAL; /* Best I can think of ... */
1693 return -1;
1697 if (!fname) {
1699 errno = EINVAL;
1700 return -1;
1704 if (smbc_parse_path(context, fname,
1705 workgroup, sizeof(workgroup),
1706 server, sizeof(server),
1707 share, sizeof(share),
1708 path, sizeof(path),
1709 user, sizeof(user),
1710 password, sizeof(password),
1711 NULL, 0)) {
1712 errno = EINVAL;
1713 return -1;
1716 if (user[0] == (char)0) fstrcpy(user, context->user);
1718 srv = smbc_server(context, True,
1719 server, share, workgroup, user, password);
1721 if (!srv) {
1723 return -1; /* smbc_server sets errno */
1727 /*d_printf(">>>unlink: resolving %s\n", path);*/
1728 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1730 d_printf("Could not resolve %s\n", path);
1731 return -1;
1733 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1735 if (!cli_unlink(targetcli, targetpath)) {
1737 errno = smbc_errno(context, targetcli);
1739 if (errno == EACCES) { /* Check if the file is a directory */
1741 int saverr = errno;
1742 SMB_OFF_T size = 0;
1743 uint16 mode = 0;
1744 struct timespec write_time_ts;
1745 struct timespec access_time_ts;
1746 struct timespec change_time_ts;
1747 SMB_INO_T ino = 0;
1749 if (!smbc_getatr(context, srv, path, &mode, &size,
1750 NULL,
1751 &access_time_ts,
1752 &write_time_ts,
1753 &change_time_ts,
1754 &ino)) {
1756 /* Hmmm, bad error ... What? */
1758 errno = smbc_errno(context, targetcli);
1759 return -1;
1762 else {
1764 if (IS_DOS_DIR(mode))
1765 errno = EISDIR;
1766 else
1767 errno = saverr; /* Restore this */
1772 return -1;
1776 return 0; /* Success ... */
1781 * Routine to rename() a file
1784 static int
1785 smbc_rename_ctx(SMBCCTX *ocontext,
1786 const char *oname,
1787 SMBCCTX *ncontext,
1788 const char *nname)
1790 fstring server1;
1791 fstring share1;
1792 fstring server2;
1793 fstring share2;
1794 fstring user1;
1795 fstring user2;
1796 fstring password1;
1797 fstring password2;
1798 fstring workgroup;
1799 pstring path1;
1800 pstring path2;
1801 pstring targetpath1;
1802 pstring targetpath2;
1803 struct cli_state *targetcli1;
1804 struct cli_state *targetcli2;
1805 SMBCSRV *srv = NULL;
1807 if (!ocontext || !ncontext ||
1808 !ocontext->internal || !ncontext->internal ||
1809 !ocontext->internal->_initialized ||
1810 !ncontext->internal->_initialized) {
1812 errno = EINVAL; /* Best I can think of ... */
1813 return -1;
1817 if (!oname || !nname) {
1819 errno = EINVAL;
1820 return -1;
1824 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1826 smbc_parse_path(ocontext, oname,
1827 workgroup, sizeof(workgroup),
1828 server1, sizeof(server1),
1829 share1, sizeof(share1),
1830 path1, sizeof(path1),
1831 user1, sizeof(user1),
1832 password1, sizeof(password1),
1833 NULL, 0);
1835 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1837 smbc_parse_path(ncontext, nname,
1838 NULL, 0,
1839 server2, sizeof(server2),
1840 share2, sizeof(share2),
1841 path2, sizeof(path2),
1842 user2, sizeof(user2),
1843 password2, sizeof(password2),
1844 NULL, 0);
1846 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1848 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1849 strcmp(user1, user2)) {
1851 /* Can't rename across file systems, or users?? */
1853 errno = EXDEV;
1854 return -1;
1858 srv = smbc_server(ocontext, True,
1859 server1, share1, workgroup, user1, password1);
1860 if (!srv) {
1862 return -1;
1866 /*d_printf(">>>rename: resolving %s\n", path1);*/
1867 if (!cli_resolve_path( "", srv->cli, path1, &targetcli1, targetpath1))
1869 d_printf("Could not resolve %s\n", path1);
1870 return -1;
1872 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1873 /*d_printf(">>>rename: resolving %s\n", path2);*/
1874 if (!cli_resolve_path( "", srv->cli, path2, &targetcli2, targetpath2))
1876 d_printf("Could not resolve %s\n", path2);
1877 return -1;
1879 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1881 if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1882 strcmp(targetcli1->share, targetcli2->share))
1884 /* can't rename across file systems */
1886 errno = EXDEV;
1887 return -1;
1890 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1891 int eno = smbc_errno(ocontext, targetcli1);
1893 if (eno != EEXIST ||
1894 !cli_unlink(targetcli1, targetpath2) ||
1895 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1897 errno = eno;
1898 return -1;
1903 return 0; /* Success */
1908 * A routine to lseek() a file
1911 static off_t
1912 smbc_lseek_ctx(SMBCCTX *context,
1913 SMBCFILE *file,
1914 off_t offset,
1915 int whence)
1917 SMB_OFF_T size;
1918 fstring server, share, user, password;
1919 pstring path, targetpath;
1920 struct cli_state *targetcli;
1922 if (!context || !context->internal ||
1923 !context->internal->_initialized) {
1925 errno = EINVAL;
1926 return -1;
1930 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1932 errno = EBADF;
1933 return -1;
1937 if (!file->file) {
1939 errno = EINVAL;
1940 return -1; /* Can't lseek a dir ... */
1944 switch (whence) {
1945 case SEEK_SET:
1946 file->offset = offset;
1947 break;
1949 case SEEK_CUR:
1950 file->offset += offset;
1951 break;
1953 case SEEK_END:
1954 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1955 if (smbc_parse_path(context, file->fname,
1956 NULL, 0,
1957 server, sizeof(server),
1958 share, sizeof(share),
1959 path, sizeof(path),
1960 user, sizeof(user),
1961 password, sizeof(password),
1962 NULL, 0)) {
1964 errno = EINVAL;
1965 return -1;
1968 /*d_printf(">>>lseek: resolving %s\n", path);*/
1969 if (!cli_resolve_path("", file->srv->cli, path,
1970 &targetcli, targetpath))
1972 d_printf("Could not resolve %s\n", path);
1973 return -1;
1975 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1977 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1978 &size, NULL, NULL, NULL, NULL, NULL))
1980 SMB_OFF_T b_size = size;
1981 if (!cli_getattrE(targetcli, file->cli_fd,
1982 NULL, &b_size, NULL, NULL, NULL))
1984 errno = EINVAL;
1985 return -1;
1986 } else
1987 size = b_size;
1989 file->offset = size + offset;
1990 break;
1992 default:
1993 errno = EINVAL;
1994 break;
1998 return file->offset;
2003 * Generate an inode number from file name for those things that need it
2006 static ino_t
2007 smbc_inode(SMBCCTX *context,
2008 const char *name)
2011 if (!context || !context->internal ||
2012 !context->internal->_initialized) {
2014 errno = EINVAL;
2015 return -1;
2019 if (!*name) return 2; /* FIXME, why 2 ??? */
2020 return (ino_t)str_checksum(name);
2025 * Routine to put basic stat info into a stat structure ... Used by stat and
2026 * fstat below.
2029 static int
2030 smbc_setup_stat(SMBCCTX *context,
2031 struct stat *st,
2032 char *fname,
2033 SMB_OFF_T size,
2034 int mode)
2037 st->st_mode = 0;
2039 if (IS_DOS_DIR(mode)) {
2040 st->st_mode = SMBC_DIR_MODE;
2041 } else {
2042 st->st_mode = SMBC_FILE_MODE;
2045 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
2046 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
2047 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
2048 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
2050 st->st_size = size;
2051 #ifdef HAVE_STAT_ST_BLKSIZE
2052 st->st_blksize = 512;
2053 #endif
2054 #ifdef HAVE_STAT_ST_BLOCKS
2055 st->st_blocks = (size+511)/512;
2056 #endif
2057 st->st_uid = getuid();
2058 st->st_gid = getgid();
2060 if (IS_DOS_DIR(mode)) {
2061 st->st_nlink = 2;
2062 } else {
2063 st->st_nlink = 1;
2066 if (st->st_ino == 0) {
2067 st->st_ino = smbc_inode(context, fname);
2070 return True; /* FIXME: Is this needed ? */
2075 * Routine to stat a file given a name
2078 static int
2079 smbc_stat_ctx(SMBCCTX *context,
2080 const char *fname,
2081 struct stat *st)
2083 SMBCSRV *srv;
2084 fstring server;
2085 fstring share;
2086 fstring user;
2087 fstring password;
2088 fstring workgroup;
2089 pstring path;
2090 struct timespec write_time_ts;
2091 struct timespec access_time_ts;
2092 struct timespec change_time_ts;
2093 SMB_OFF_T size = 0;
2094 uint16 mode = 0;
2095 SMB_INO_T ino = 0;
2097 if (!context || !context->internal ||
2098 !context->internal->_initialized) {
2100 errno = EINVAL; /* Best I can think of ... */
2101 return -1;
2105 if (!fname) {
2107 errno = EINVAL;
2108 return -1;
2112 DEBUG(4, ("smbc_stat(%s)\n", fname));
2114 if (smbc_parse_path(context, fname,
2115 workgroup, sizeof(workgroup),
2116 server, sizeof(server),
2117 share, sizeof(share),
2118 path, sizeof(path),
2119 user, sizeof(user),
2120 password, sizeof(password),
2121 NULL, 0)) {
2122 errno = EINVAL;
2123 return -1;
2126 if (user[0] == (char)0) fstrcpy(user, context->user);
2128 srv = smbc_server(context, True,
2129 server, share, workgroup, user, password);
2131 if (!srv) {
2132 return -1; /* errno set by smbc_server */
2135 if (!smbc_getatr(context, srv, path, &mode, &size,
2136 NULL,
2137 &access_time_ts,
2138 &write_time_ts,
2139 &change_time_ts,
2140 &ino)) {
2142 errno = smbc_errno(context, srv->cli);
2143 return -1;
2147 st->st_ino = ino;
2149 smbc_setup_stat(context, st, path, size, mode);
2151 set_atimespec(st, access_time_ts);
2152 set_ctimespec(st, change_time_ts);
2153 set_mtimespec(st, write_time_ts);
2154 st->st_dev = srv->dev;
2156 return 0;
2161 * Routine to stat a file given an fd
2164 static int
2165 smbc_fstat_ctx(SMBCCTX *context,
2166 SMBCFILE *file,
2167 struct stat *st)
2169 struct timespec change_time_ts;
2170 struct timespec access_time_ts;
2171 struct timespec write_time_ts;
2172 SMB_OFF_T size;
2173 uint16 mode;
2174 fstring server;
2175 fstring share;
2176 fstring user;
2177 fstring password;
2178 pstring path;
2179 pstring targetpath;
2180 struct cli_state *targetcli;
2181 SMB_INO_T ino = 0;
2183 if (!context || !context->internal ||
2184 !context->internal->_initialized) {
2186 errno = EINVAL;
2187 return -1;
2191 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2193 errno = EBADF;
2194 return -1;
2198 if (!file->file) {
2200 return context->fstatdir(context, file, st);
2204 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2205 if (smbc_parse_path(context, file->fname,
2206 NULL, 0,
2207 server, sizeof(server),
2208 share, sizeof(share),
2209 path, sizeof(path),
2210 user, sizeof(user),
2211 password, sizeof(password),
2212 NULL, 0)) {
2213 errno = EINVAL;
2214 return -1;
2217 /*d_printf(">>>fstat: resolving %s\n", path);*/
2218 if (!cli_resolve_path("", file->srv->cli, path,
2219 &targetcli, targetpath))
2221 d_printf("Could not resolve %s\n", path);
2222 return -1;
2224 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2226 if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2227 NULL,
2228 &access_time_ts,
2229 &write_time_ts,
2230 &change_time_ts,
2231 &ino)) {
2233 time_t change_time, access_time, write_time;
2235 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2236 &change_time, &access_time, &write_time)) {
2238 errno = EINVAL;
2239 return -1;
2242 change_time_ts = convert_time_t_to_timespec(change_time);
2243 access_time_ts = convert_time_t_to_timespec(access_time);
2244 write_time_ts = convert_time_t_to_timespec(write_time);
2247 st->st_ino = ino;
2249 smbc_setup_stat(context, st, file->fname, size, mode);
2251 set_atimespec(st, access_time_ts);
2252 set_ctimespec(st, change_time_ts);
2253 set_mtimespec(st, write_time_ts);
2254 st->st_dev = file->srv->dev;
2256 return 0;
2261 * Routine to open a directory
2262 * We accept the URL syntax explained in smbc_parse_path(), above.
2265 static void
2266 smbc_remove_dir(SMBCFILE *dir)
2268 struct smbc_dir_list *d,*f;
2270 d = dir->dir_list;
2271 while (d) {
2273 f = d; d = d->next;
2275 SAFE_FREE(f->dirent);
2276 SAFE_FREE(f);
2280 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2284 static int
2285 add_dirent(SMBCFILE *dir,
2286 const char *name,
2287 const char *comment,
2288 uint32 type)
2290 struct smbc_dirent *dirent;
2291 int size;
2292 int name_length = (name == NULL ? 0 : strlen(name));
2293 int comment_len = (comment == NULL ? 0 : strlen(comment));
2296 * Allocate space for the dirent, which must be increased by the
2297 * size of the name and the comment and 1 each for the null terminator.
2300 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2302 dirent = (struct smbc_dirent *)SMB_MALLOC(size);
2304 if (!dirent) {
2306 dir->dir_error = ENOMEM;
2307 return -1;
2311 ZERO_STRUCTP(dirent);
2313 if (dir->dir_list == NULL) {
2315 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2316 if (!dir->dir_list) {
2318 SAFE_FREE(dirent);
2319 dir->dir_error = ENOMEM;
2320 return -1;
2323 ZERO_STRUCTP(dir->dir_list);
2325 dir->dir_end = dir->dir_next = dir->dir_list;
2327 else {
2329 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2331 if (!dir->dir_end->next) {
2333 SAFE_FREE(dirent);
2334 dir->dir_error = ENOMEM;
2335 return -1;
2338 ZERO_STRUCTP(dir->dir_end->next);
2340 dir->dir_end = dir->dir_end->next;
2343 dir->dir_end->next = NULL;
2344 dir->dir_end->dirent = dirent;
2346 dirent->smbc_type = type;
2347 dirent->namelen = name_length;
2348 dirent->commentlen = comment_len;
2349 dirent->dirlen = size;
2352 * dirent->namelen + 1 includes the null (no null termination needed)
2353 * Ditto for dirent->commentlen.
2354 * The space for the two null bytes was allocated.
2356 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2357 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2358 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2360 return 0;
2364 static void
2365 list_unique_wg_fn(const char *name,
2366 uint32 type,
2367 const char *comment,
2368 void *state)
2370 SMBCFILE *dir = (SMBCFILE *)state;
2371 struct smbc_dir_list *dir_list;
2372 struct smbc_dirent *dirent;
2373 int dirent_type;
2374 int do_remove = 0;
2376 dirent_type = dir->dir_type;
2378 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2380 /* An error occurred, what do we do? */
2381 /* FIXME: Add some code here */
2384 /* Point to the one just added */
2385 dirent = dir->dir_end->dirent;
2387 /* See if this was a duplicate */
2388 for (dir_list = dir->dir_list;
2389 dir_list != dir->dir_end;
2390 dir_list = dir_list->next) {
2391 if (! do_remove &&
2392 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2393 /* Duplicate. End end of list need to be removed. */
2394 do_remove = 1;
2397 if (do_remove && dir_list->next == dir->dir_end) {
2398 /* Found the end of the list. Remove it. */
2399 dir->dir_end = dir_list;
2400 free(dir_list->next);
2401 free(dirent);
2402 dir_list->next = NULL;
2403 break;
2408 static void
2409 list_fn(const char *name,
2410 uint32 type,
2411 const char *comment,
2412 void *state)
2414 SMBCFILE *dir = (SMBCFILE *)state;
2415 int dirent_type;
2418 * We need to process the type a little ...
2420 * Disk share = 0x00000000
2421 * Print share = 0x00000001
2422 * Comms share = 0x00000002 (obsolete?)
2423 * IPC$ share = 0x00000003
2425 * administrative shares:
2426 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2429 if (dir->dir_type == SMBC_FILE_SHARE) {
2431 switch (type) {
2432 case 0 | 0x80000000:
2433 case 0:
2434 dirent_type = SMBC_FILE_SHARE;
2435 break;
2437 case 1:
2438 dirent_type = SMBC_PRINTER_SHARE;
2439 break;
2441 case 2:
2442 dirent_type = SMBC_COMMS_SHARE;
2443 break;
2445 case 3 | 0x80000000:
2446 case 3:
2447 dirent_type = SMBC_IPC_SHARE;
2448 break;
2450 default:
2451 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2452 break;
2455 else {
2456 dirent_type = dir->dir_type;
2459 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2461 /* An error occurred, what do we do? */
2462 /* FIXME: Add some code here */
2467 static void
2468 dir_list_fn(const char *mnt,
2469 file_info *finfo,
2470 const char *mask,
2471 void *state)
2474 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2475 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2477 /* Handle an error ... */
2479 /* FIXME: Add some code ... */
2485 static int
2486 net_share_enum_rpc(struct cli_state *cli,
2487 void (*fn)(const char *name,
2488 uint32 type,
2489 const char *comment,
2490 void *state),
2491 void *state)
2493 int i;
2494 NTSTATUS result;
2495 uint32 enum_hnd;
2496 uint32 info_level = 1;
2497 uint32 preferred_len = 0xffffffff;
2498 struct srvsvc_NetShareCtr1 ctr1;
2499 union srvsvc_NetShareCtr ctr;
2500 void *mem_ctx;
2501 struct rpc_pipe_client *pipe_hnd;
2502 uint32 numentries;
2503 NTSTATUS nt_status;
2505 /* Open the server service pipe */
2506 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2507 if (!pipe_hnd) {
2508 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2509 return -1;
2512 /* Allocate a context for parsing and for the entries in "ctr" */
2513 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2514 if (mem_ctx == NULL) {
2515 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2516 cli_rpc_pipe_close(pipe_hnd);
2517 return -1;
2520 ZERO_STRUCT(ctr1);
2521 ctr.ctr1 = &ctr1;
2523 /* Issue the NetShareEnum RPC call and retrieve the response */
2524 enum_hnd = 0;
2525 result = rpccli_srvsvc_NetShareEnum(pipe_hnd, mem_ctx, NULL,
2526 &info_level, &ctr, preferred_len,
2527 &numentries, &enum_hnd);
2529 /* Was it successful? */
2530 if (!NT_STATUS_IS_OK(result) || numentries == 0) {
2531 /* Nope. Go clean up. */
2532 goto done;
2535 /* For each returned entry... */
2536 for (i = 0; i < numentries; i++) {
2538 /* Add this share to the list */
2539 (*fn)(ctr.ctr1->array[i].name,
2540 ctr.ctr1->array[i].type,
2541 ctr.ctr1->array[i].comment, state);
2544 done:
2545 /* Close the server service pipe */
2546 cli_rpc_pipe_close(pipe_hnd);
2548 /* Free all memory which was allocated for this request */
2549 TALLOC_FREE(mem_ctx);
2551 /* Tell 'em if it worked */
2552 return NT_STATUS_IS_OK(result) ? 0 : -1;
2557 static SMBCFILE *
2558 smbc_opendir_ctx(SMBCCTX *context,
2559 const char *fname)
2561 int saved_errno;
2562 fstring server, share, user, password, options;
2563 pstring workgroup;
2564 pstring path;
2565 uint16 mode;
2566 char *p;
2567 SMBCSRV *srv = NULL;
2568 SMBCFILE *dir = NULL;
2569 struct _smbc_callbacks *cb;
2570 struct in_addr rem_ip;
2572 if (!context || !context->internal ||
2573 !context->internal->_initialized) {
2574 DEBUG(4, ("no valid context\n"));
2575 errno = EINVAL + 8192;
2576 return NULL;
2580 if (!fname) {
2581 DEBUG(4, ("no valid fname\n"));
2582 errno = EINVAL + 8193;
2583 return NULL;
2586 if (smbc_parse_path(context, fname,
2587 workgroup, sizeof(workgroup),
2588 server, sizeof(server),
2589 share, sizeof(share),
2590 path, sizeof(path),
2591 user, sizeof(user),
2592 password, sizeof(password),
2593 options, sizeof(options))) {
2594 DEBUG(4, ("no valid path\n"));
2595 errno = EINVAL + 8194;
2596 return NULL;
2599 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2600 "path='%s' options='%s'\n",
2601 fname, server, share, path, options));
2603 /* Ensure the options are valid */
2604 if (smbc_check_options(server, share, path, options)) {
2605 DEBUG(4, ("unacceptable options (%s)\n", options));
2606 errno = EINVAL + 8195;
2607 return NULL;
2610 if (user[0] == (char)0) fstrcpy(user, context->user);
2612 dir = SMB_MALLOC_P(SMBCFILE);
2614 if (!dir) {
2616 errno = ENOMEM;
2617 return NULL;
2621 ZERO_STRUCTP(dir);
2623 dir->cli_fd = 0;
2624 dir->fname = SMB_STRDUP(fname);
2625 dir->srv = NULL;
2626 dir->offset = 0;
2627 dir->file = False;
2628 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2630 if (server[0] == (char)0) {
2632 int i;
2633 int count;
2634 int max_lmb_count;
2635 struct ip_service *ip_list;
2636 struct ip_service server_addr;
2637 struct user_auth_info u_info;
2638 struct cli_state *cli;
2640 if (share[0] != (char)0 || path[0] != (char)0) {
2642 errno = EINVAL + 8196;
2643 if (dir) {
2644 SAFE_FREE(dir->fname);
2645 SAFE_FREE(dir);
2647 return NULL;
2650 /* Determine how many local master browsers to query */
2651 max_lmb_count = (context->options.browse_max_lmb_count == 0
2652 ? INT_MAX
2653 : context->options.browse_max_lmb_count);
2655 pstrcpy(u_info.username, user);
2656 pstrcpy(u_info.password, password);
2659 * We have server and share and path empty but options
2660 * requesting that we scan all master browsers for their list
2661 * of workgroups/domains. This implies that we must first try
2662 * broadcast queries to find all master browsers, and if that
2663 * doesn't work, then try our other methods which return only
2664 * a single master browser.
2667 ip_list = NULL;
2668 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2670 SAFE_FREE(ip_list);
2672 if (!find_master_ip(workgroup, &server_addr.ip)) {
2674 if (dir) {
2675 SAFE_FREE(dir->fname);
2676 SAFE_FREE(dir);
2678 errno = ENOENT;
2679 return NULL;
2682 ip_list = &server_addr;
2683 count = 1;
2686 for (i = 0; i < count && i < max_lmb_count; i++) {
2687 DEBUG(99, ("Found master browser %d of %d: %s\n",
2688 i+1, MAX(count, max_lmb_count),
2689 inet_ntoa(ip_list[i].ip)));
2691 cli = get_ipc_connect_master_ip(&ip_list[i],
2692 workgroup, &u_info);
2693 /* cli == NULL is the master browser refused to talk or
2694 could not be found */
2695 if ( !cli )
2696 continue;
2698 fstrcpy(server, cli->desthost);
2699 cli_shutdown(cli);
2701 DEBUG(4, ("using workgroup %s %s\n",
2702 workgroup, server));
2705 * For each returned master browser IP address, get a
2706 * connection to IPC$ on the server if we do not
2707 * already have one, and determine the
2708 * workgroups/domains that it knows about.
2711 srv = smbc_server(context, True, server, "IPC$",
2712 workgroup, user, password);
2713 if (!srv) {
2714 continue;
2717 dir->srv = srv;
2718 dir->dir_type = SMBC_WORKGROUP;
2720 /* Now, list the stuff ... */
2722 if (!cli_NetServerEnum(srv->cli,
2723 workgroup,
2724 SV_TYPE_DOMAIN_ENUM,
2725 list_unique_wg_fn,
2726 (void *)dir)) {
2727 continue;
2731 SAFE_FREE(ip_list);
2732 } else {
2734 * Server not an empty string ... Check the rest and see what
2735 * gives
2737 if (*share == '\0') {
2738 if (*path != '\0') {
2740 /* Should not have empty share with path */
2741 errno = EINVAL + 8197;
2742 if (dir) {
2743 SAFE_FREE(dir->fname);
2744 SAFE_FREE(dir);
2746 return NULL;
2751 * We don't know if <server> is really a server name
2752 * or is a workgroup/domain name. If we already have
2753 * a server structure for it, we'll use it.
2754 * Otherwise, check to see if <server><1D>,
2755 * <server><1B>, or <server><20> translates. We check
2756 * to see if <server> is an IP address first.
2760 * See if we have an existing server. Do not
2761 * establish a connection if one does not already
2762 * exist.
2764 srv = smbc_server(context, False, server, "IPC$",
2765 workgroup, user, password);
2768 * If no existing server and not an IP addr, look for
2769 * LMB or DMB
2771 if (!srv &&
2772 !is_ipaddress(server) &&
2773 (resolve_name(server, &rem_ip, 0x1d) || /* LMB */
2774 resolve_name(server, &rem_ip, 0x1b) )) { /* DMB */
2776 fstring buserver;
2778 dir->dir_type = SMBC_SERVER;
2781 * Get the backup list ...
2783 if (!name_status_find(server, 0, 0,
2784 rem_ip, buserver)) {
2786 DEBUG(0, ("Could not get name of "
2787 "local/domain master browser "
2788 "for server %s\n", server));
2789 if (dir) {
2790 SAFE_FREE(dir->fname);
2791 SAFE_FREE(dir);
2793 errno = EPERM;
2794 return NULL;
2799 * Get a connection to IPC$ on the server if
2800 * we do not already have one
2802 srv = smbc_server(context, True,
2803 buserver, "IPC$",
2804 workgroup, user, password);
2805 if (!srv) {
2806 DEBUG(0, ("got no contact to IPC$\n"));
2807 if (dir) {
2808 SAFE_FREE(dir->fname);
2809 SAFE_FREE(dir);
2811 return NULL;
2815 dir->srv = srv;
2817 /* Now, list the servers ... */
2818 if (!cli_NetServerEnum(srv->cli, server,
2819 0x0000FFFE, list_fn,
2820 (void *)dir)) {
2822 if (dir) {
2823 SAFE_FREE(dir->fname);
2824 SAFE_FREE(dir);
2826 return NULL;
2828 } else if (srv ||
2829 (resolve_name(server, &rem_ip, 0x20))) {
2831 /* If we hadn't found the server, get one now */
2832 if (!srv) {
2833 srv = smbc_server(context, True,
2834 server, "IPC$",
2835 workgroup,
2836 user, password);
2839 if (!srv) {
2840 if (dir) {
2841 SAFE_FREE(dir->fname);
2842 SAFE_FREE(dir);
2844 return NULL;
2848 dir->dir_type = SMBC_FILE_SHARE;
2849 dir->srv = srv;
2851 /* List the shares ... */
2853 if (net_share_enum_rpc(
2854 srv->cli,
2855 list_fn,
2856 (void *) dir) < 0 &&
2857 cli_RNetShareEnum(
2858 srv->cli,
2859 list_fn,
2860 (void *)dir) < 0) {
2862 errno = cli_errno(srv->cli);
2863 if (dir) {
2864 SAFE_FREE(dir->fname);
2865 SAFE_FREE(dir);
2867 return NULL;
2870 } else {
2871 /* Neither the workgroup nor server exists */
2872 errno = ECONNREFUSED;
2873 if (dir) {
2874 SAFE_FREE(dir->fname);
2875 SAFE_FREE(dir);
2877 return NULL;
2881 else {
2883 * The server and share are specified ... work from
2884 * there ...
2886 pstring targetpath;
2887 struct cli_state *targetcli;
2889 /* We connect to the server and list the directory */
2890 dir->dir_type = SMBC_FILE_SHARE;
2892 srv = smbc_server(context, True, server, share,
2893 workgroup, user, password);
2895 if (!srv) {
2897 if (dir) {
2898 SAFE_FREE(dir->fname);
2899 SAFE_FREE(dir);
2901 return NULL;
2905 dir->srv = srv;
2907 /* Now, list the files ... */
2909 p = path + strlen(path);
2910 pstrcat(path, "\\*");
2912 if (!cli_resolve_path("", srv->cli, path,
2913 &targetcli, targetpath))
2915 d_printf("Could not resolve %s\n", path);
2916 if (dir) {
2917 SAFE_FREE(dir->fname);
2918 SAFE_FREE(dir);
2920 return NULL;
2923 if (cli_list(targetcli, targetpath,
2924 aDIR | aSYSTEM | aHIDDEN,
2925 dir_list_fn, (void *)dir) < 0) {
2927 if (dir) {
2928 SAFE_FREE(dir->fname);
2929 SAFE_FREE(dir);
2931 saved_errno = smbc_errno(context, targetcli);
2933 if (saved_errno == EINVAL) {
2935 * See if they asked to opendir something
2936 * other than a directory. If so, the
2937 * converted error value we got would have
2938 * been EINVAL rather than ENOTDIR.
2940 *p = '\0'; /* restore original path */
2942 if (smbc_getatr(context, srv, path,
2943 &mode, NULL,
2944 NULL, NULL, NULL, NULL,
2945 NULL) &&
2946 ! IS_DOS_DIR(mode)) {
2948 /* It is. Correct the error value */
2949 saved_errno = ENOTDIR;
2954 * If there was an error and the server is no
2955 * good any more...
2957 cb = &context->callbacks;
2958 if (cli_is_error(targetcli) &&
2959 cb->check_server_fn(context, srv)) {
2961 /* ... then remove it. */
2962 if (cb->remove_unused_server_fn(context,
2963 srv)) {
2965 * We could not remove the server
2966 * completely, remove it from the
2967 * cache so we will not get it
2968 * again. It will be removed when the
2969 * last file/dir is closed.
2971 cb->remove_cached_srv_fn(context, srv);
2975 errno = saved_errno;
2976 return NULL;
2982 DLIST_ADD(context->internal->_files, dir);
2983 return dir;
2988 * Routine to close a directory
2991 static int
2992 smbc_closedir_ctx(SMBCCTX *context,
2993 SMBCFILE *dir)
2996 if (!context || !context->internal ||
2997 !context->internal->_initialized) {
2999 errno = EINVAL;
3000 return -1;
3004 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3006 errno = EBADF;
3007 return -1;
3011 smbc_remove_dir(dir); /* Clean it up */
3013 DLIST_REMOVE(context->internal->_files, dir);
3015 if (dir) {
3017 SAFE_FREE(dir->fname);
3018 SAFE_FREE(dir); /* Free the space too */
3021 return 0;
3025 static void
3026 smbc_readdir_internal(SMBCCTX * context,
3027 struct smbc_dirent *dest,
3028 struct smbc_dirent *src,
3029 int max_namebuf_len)
3031 if (context->options.urlencode_readdir_entries) {
3033 /* url-encode the name. get back remaining buffer space */
3034 max_namebuf_len =
3035 smbc_urlencode(dest->name, src->name, max_namebuf_len);
3037 /* We now know the name length */
3038 dest->namelen = strlen(dest->name);
3040 /* Save the pointer to the beginning of the comment */
3041 dest->comment = dest->name + dest->namelen + 1;
3043 /* Copy the comment */
3044 strncpy(dest->comment, src->comment, max_namebuf_len - 1);
3045 dest->comment[max_namebuf_len - 1] = '\0';
3047 /* Save other fields */
3048 dest->smbc_type = src->smbc_type;
3049 dest->commentlen = strlen(dest->comment);
3050 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
3051 (char *) dest);
3052 } else {
3054 /* No encoding. Just copy the entry as is. */
3055 memcpy(dest, src, src->dirlen);
3056 dest->comment = (char *)(&dest->name + src->namelen + 1);
3062 * Routine to get a directory entry
3065 struct smbc_dirent *
3066 smbc_readdir_ctx(SMBCCTX *context,
3067 SMBCFILE *dir)
3069 int maxlen;
3070 struct smbc_dirent *dirp, *dirent;
3072 /* Check that all is ok first ... */
3074 if (!context || !context->internal ||
3075 !context->internal->_initialized) {
3077 errno = EINVAL;
3078 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
3079 return NULL;
3083 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3085 errno = EBADF;
3086 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
3087 return NULL;
3091 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3093 errno = ENOTDIR;
3094 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
3095 return NULL;
3099 if (!dir->dir_next) {
3100 return NULL;
3103 dirent = dir->dir_next->dirent;
3104 if (!dirent) {
3106 errno = ENOENT;
3107 return NULL;
3111 dirp = (struct smbc_dirent *)context->internal->_dirent;
3112 maxlen = (sizeof(context->internal->_dirent) -
3113 sizeof(struct smbc_dirent));
3115 smbc_readdir_internal(context, dirp, dirent, maxlen);
3117 dir->dir_next = dir->dir_next->next;
3119 return dirp;
3123 * Routine to get directory entries
3126 static int
3127 smbc_getdents_ctx(SMBCCTX *context,
3128 SMBCFILE *dir,
3129 struct smbc_dirent *dirp,
3130 int count)
3132 int rem = count;
3133 int reqd;
3134 int maxlen;
3135 char *ndir = (char *)dirp;
3136 struct smbc_dir_list *dirlist;
3138 /* Check that all is ok first ... */
3140 if (!context || !context->internal ||
3141 !context->internal->_initialized) {
3143 errno = EINVAL;
3144 return -1;
3148 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3150 errno = EBADF;
3151 return -1;
3155 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3157 errno = ENOTDIR;
3158 return -1;
3163 * Now, retrieve the number of entries that will fit in what was passed
3164 * We have to figure out if the info is in the list, or we need to
3165 * send a request to the server to get the info.
3168 while ((dirlist = dir->dir_next)) {
3169 struct smbc_dirent *dirent;
3171 if (!dirlist->dirent) {
3173 errno = ENOENT; /* Bad error */
3174 return -1;
3178 /* Do urlencoding of next entry, if so selected */
3179 dirent = (struct smbc_dirent *)context->internal->_dirent;
3180 maxlen = (sizeof(context->internal->_dirent) -
3181 sizeof(struct smbc_dirent));
3182 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3184 reqd = dirent->dirlen;
3186 if (rem < reqd) {
3188 if (rem < count) { /* We managed to copy something */
3190 errno = 0;
3191 return count - rem;
3194 else { /* Nothing copied ... */
3196 errno = EINVAL; /* Not enough space ... */
3197 return -1;
3203 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3205 ((struct smbc_dirent *)ndir)->comment =
3206 (char *)(&((struct smbc_dirent *)ndir)->name +
3207 dirent->namelen +
3210 ndir += reqd;
3212 rem -= reqd;
3214 dir->dir_next = dirlist = dirlist -> next;
3217 if (rem == count)
3218 return 0;
3219 else
3220 return count - rem;
3225 * Routine to create a directory ...
3228 static int
3229 smbc_mkdir_ctx(SMBCCTX *context,
3230 const char *fname,
3231 mode_t mode)
3233 SMBCSRV *srv;
3234 fstring server;
3235 fstring share;
3236 fstring user;
3237 fstring password;
3238 fstring workgroup;
3239 pstring path, targetpath;
3240 struct cli_state *targetcli;
3242 if (!context || !context->internal ||
3243 !context->internal->_initialized) {
3245 errno = EINVAL;
3246 return -1;
3250 if (!fname) {
3252 errno = EINVAL;
3253 return -1;
3257 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3259 if (smbc_parse_path(context, fname,
3260 workgroup, sizeof(workgroup),
3261 server, sizeof(server),
3262 share, sizeof(share),
3263 path, sizeof(path),
3264 user, sizeof(user),
3265 password, sizeof(password),
3266 NULL, 0)) {
3267 errno = EINVAL;
3268 return -1;
3271 if (user[0] == (char)0) fstrcpy(user, context->user);
3273 srv = smbc_server(context, True,
3274 server, share, workgroup, user, password);
3276 if (!srv) {
3278 return -1; /* errno set by smbc_server */
3282 /*d_printf(">>>mkdir: resolving %s\n", path);*/
3283 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
3285 d_printf("Could not resolve %s\n", path);
3286 return -1;
3288 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3290 if (!cli_mkdir(targetcli, targetpath)) {
3292 errno = smbc_errno(context, targetcli);
3293 return -1;
3297 return 0;
3302 * Our list function simply checks to see if a directory is not empty
3305 static int smbc_rmdir_dirempty = True;
3307 static void
3308 rmdir_list_fn(const char *mnt,
3309 file_info *finfo,
3310 const char *mask,
3311 void *state)
3313 if (strncmp(finfo->name, ".", 1) != 0 &&
3314 strncmp(finfo->name, "..", 2) != 0) {
3316 smbc_rmdir_dirempty = False;
3321 * Routine to remove a directory
3324 static int
3325 smbc_rmdir_ctx(SMBCCTX *context,
3326 const char *fname)
3328 SMBCSRV *srv;
3329 fstring server;
3330 fstring share;
3331 fstring user;
3332 fstring password;
3333 fstring workgroup;
3334 pstring path;
3335 pstring targetpath;
3336 struct cli_state *targetcli;
3338 if (!context || !context->internal ||
3339 !context->internal->_initialized) {
3341 errno = EINVAL;
3342 return -1;
3346 if (!fname) {
3348 errno = EINVAL;
3349 return -1;
3353 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3355 if (smbc_parse_path(context, fname,
3356 workgroup, sizeof(workgroup),
3357 server, sizeof(server),
3358 share, sizeof(share),
3359 path, sizeof(path),
3360 user, sizeof(user),
3361 password, sizeof(password),
3362 NULL, 0))
3364 errno = EINVAL;
3365 return -1;
3368 if (user[0] == (char)0) fstrcpy(user, context->user);
3370 srv = smbc_server(context, True,
3371 server, share, workgroup, user, password);
3373 if (!srv) {
3375 return -1; /* errno set by smbc_server */
3379 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3380 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
3382 d_printf("Could not resolve %s\n", path);
3383 return -1;
3385 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3388 if (!cli_rmdir(targetcli, targetpath)) {
3390 errno = smbc_errno(context, targetcli);
3392 if (errno == EACCES) { /* Check if the dir empty or not */
3394 /* Local storage to avoid buffer overflows */
3395 pstring lpath;
3397 smbc_rmdir_dirempty = True; /* Make this so ... */
3399 pstrcpy(lpath, targetpath);
3400 pstrcat(lpath, "\\*");
3402 if (cli_list(targetcli, lpath,
3403 aDIR | aSYSTEM | aHIDDEN,
3404 rmdir_list_fn, NULL) < 0) {
3406 /* Fix errno to ignore latest error ... */
3407 DEBUG(5, ("smbc_rmdir: "
3408 "cli_list returned an error: %d\n",
3409 smbc_errno(context, targetcli)));
3410 errno = EACCES;
3414 if (smbc_rmdir_dirempty)
3415 errno = EACCES;
3416 else
3417 errno = ENOTEMPTY;
3421 return -1;
3425 return 0;
3430 * Routine to return the current directory position
3433 static off_t
3434 smbc_telldir_ctx(SMBCCTX *context,
3435 SMBCFILE *dir)
3437 off_t ret_val; /* Squash warnings about cast */
3439 if (!context || !context->internal ||
3440 !context->internal->_initialized) {
3442 errno = EINVAL;
3443 return -1;
3447 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3449 errno = EBADF;
3450 return -1;
3454 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3456 errno = ENOTDIR;
3457 return -1;
3462 * We return the pointer here as the offset
3464 ret_val = (off_t)(long)dir->dir_next;
3465 return ret_val;
3470 * A routine to run down the list and see if the entry is OK
3473 struct smbc_dir_list *
3474 smbc_check_dir_ent(struct smbc_dir_list *list,
3475 struct smbc_dirent *dirent)
3478 /* Run down the list looking for what we want */
3480 if (dirent) {
3482 struct smbc_dir_list *tmp = list;
3484 while (tmp) {
3486 if (tmp->dirent == dirent)
3487 return tmp;
3489 tmp = tmp->next;
3495 return NULL; /* Not found, or an error */
3501 * Routine to seek on a directory
3504 static int
3505 smbc_lseekdir_ctx(SMBCCTX *context,
3506 SMBCFILE *dir,
3507 off_t offset)
3509 long int l_offset = offset; /* Handle problems of size */
3510 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3511 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3513 if (!context || !context->internal ||
3514 !context->internal->_initialized) {
3516 errno = EINVAL;
3517 return -1;
3521 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3523 errno = ENOTDIR;
3524 return -1;
3528 /* Now, check what we were passed and see if it is OK ... */
3530 if (dirent == NULL) { /* Seek to the begining of the list */
3532 dir->dir_next = dir->dir_list;
3533 return 0;
3537 /* Now, run down the list and make sure that the entry is OK */
3538 /* This may need to be changed if we change the format of the list */
3540 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3542 errno = EINVAL; /* Bad entry */
3543 return -1;
3547 dir->dir_next = list_ent;
3549 return 0;
3554 * Routine to fstat a dir
3557 static int
3558 smbc_fstatdir_ctx(SMBCCTX *context,
3559 SMBCFILE *dir,
3560 struct stat *st)
3563 if (!context || !context->internal ||
3564 !context->internal->_initialized) {
3566 errno = EINVAL;
3567 return -1;
3571 /* No code yet ... */
3573 return 0;
3577 static int
3578 smbc_chmod_ctx(SMBCCTX *context,
3579 const char *fname,
3580 mode_t newmode)
3582 SMBCSRV *srv;
3583 fstring server;
3584 fstring share;
3585 fstring user;
3586 fstring password;
3587 fstring workgroup;
3588 pstring path;
3589 uint16 mode;
3591 if (!context || !context->internal ||
3592 !context->internal->_initialized) {
3594 errno = EINVAL; /* Best I can think of ... */
3595 return -1;
3599 if (!fname) {
3601 errno = EINVAL;
3602 return -1;
3606 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3608 if (smbc_parse_path(context, fname,
3609 workgroup, sizeof(workgroup),
3610 server, sizeof(server),
3611 share, sizeof(share),
3612 path, sizeof(path),
3613 user, sizeof(user),
3614 password, sizeof(password),
3615 NULL, 0)) {
3616 errno = EINVAL;
3617 return -1;
3620 if (user[0] == (char)0) fstrcpy(user, context->user);
3622 srv = smbc_server(context, True,
3623 server, share, workgroup, user, password);
3625 if (!srv) {
3626 return -1; /* errno set by smbc_server */
3629 mode = 0;
3631 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3632 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3633 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3634 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3636 if (!cli_setatr(srv->cli, path, mode, 0)) {
3637 errno = smbc_errno(context, srv->cli);
3638 return -1;
3641 return 0;
3644 static int
3645 smbc_utimes_ctx(SMBCCTX *context,
3646 const char *fname,
3647 struct timeval *tbuf)
3649 SMBCSRV *srv;
3650 fstring server;
3651 fstring share;
3652 fstring user;
3653 fstring password;
3654 fstring workgroup;
3655 pstring path;
3656 time_t access_time;
3657 time_t write_time;
3659 if (!context || !context->internal ||
3660 !context->internal->_initialized) {
3662 errno = EINVAL; /* Best I can think of ... */
3663 return -1;
3667 if (!fname) {
3669 errno = EINVAL;
3670 return -1;
3674 if (tbuf == NULL) {
3675 access_time = write_time = time(NULL);
3676 } else {
3677 access_time = tbuf[0].tv_sec;
3678 write_time = tbuf[1].tv_sec;
3681 if (DEBUGLVL(4))
3683 char *p;
3684 char atimebuf[32];
3685 char mtimebuf[32];
3687 strncpy(atimebuf, ctime(&access_time), sizeof(atimebuf) - 1);
3688 atimebuf[sizeof(atimebuf) - 1] = '\0';
3689 if ((p = strchr(atimebuf, '\n')) != NULL) {
3690 *p = '\0';
3693 strncpy(mtimebuf, ctime(&write_time), sizeof(mtimebuf) - 1);
3694 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3695 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3696 *p = '\0';
3699 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3700 fname, atimebuf, mtimebuf);
3703 if (smbc_parse_path(context, fname,
3704 workgroup, sizeof(workgroup),
3705 server, sizeof(server),
3706 share, sizeof(share),
3707 path, sizeof(path),
3708 user, sizeof(user),
3709 password, sizeof(password),
3710 NULL, 0)) {
3711 errno = EINVAL;
3712 return -1;
3715 if (user[0] == (char)0) fstrcpy(user, context->user);
3717 srv = smbc_server(context, True,
3718 server, share, workgroup, user, password);
3720 if (!srv) {
3721 return -1; /* errno set by smbc_server */
3724 if (!smbc_setatr(context, srv, path,
3725 0, access_time, write_time, 0, 0)) {
3726 return -1; /* errno set by smbc_setatr */
3729 return 0;
3733 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3734 However NT4 gives a "The information may have been modified by a
3735 computer running Windows NT 5.0" if denied ACEs do not appear before
3736 allowed ACEs. */
3738 static int
3739 ace_compare(SEC_ACE *ace1,
3740 SEC_ACE *ace2)
3742 if (sec_ace_equal(ace1, ace2))
3743 return 0;
3745 if (ace1->type != ace2->type)
3746 return ace2->type - ace1->type;
3748 if (sid_compare(&ace1->trustee, &ace2->trustee))
3749 return sid_compare(&ace1->trustee, &ace2->trustee);
3751 if (ace1->flags != ace2->flags)
3752 return ace1->flags - ace2->flags;
3754 if (ace1->access_mask != ace2->access_mask)
3755 return ace1->access_mask - ace2->access_mask;
3757 if (ace1->size != ace2->size)
3758 return ace1->size - ace2->size;
3760 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3764 static void
3765 sort_acl(SEC_ACL *the_acl)
3767 uint32 i;
3768 if (!the_acl) return;
3770 qsort(the_acl->aces, the_acl->num_aces, sizeof(the_acl->aces[0]),
3771 QSORT_CAST ace_compare);
3773 for (i=1;i<the_acl->num_aces;) {
3774 if (sec_ace_equal(&the_acl->aces[i-1], &the_acl->aces[i])) {
3775 int j;
3776 for (j=i; j<the_acl->num_aces-1; j++) {
3777 the_acl->aces[j] = the_acl->aces[j+1];
3779 the_acl->num_aces--;
3780 } else {
3781 i++;
3786 /* convert a SID to a string, either numeric or username/group */
3787 static void
3788 convert_sid_to_string(struct cli_state *ipc_cli,
3789 POLICY_HND *pol,
3790 fstring str,
3791 BOOL numeric,
3792 DOM_SID *sid)
3794 char **domains = NULL;
3795 char **names = NULL;
3796 enum lsa_SidType *types = NULL;
3797 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3798 sid_to_string(str, sid);
3800 if (numeric) {
3801 return; /* no lookup desired */
3804 if (!pipe_hnd) {
3805 return;
3808 /* Ask LSA to convert the sid to a name */
3810 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3811 pol, 1, sid, &domains,
3812 &names, &types)) ||
3813 !domains || !domains[0] || !names || !names[0]) {
3814 return;
3817 /* Converted OK */
3819 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3820 domains[0], lp_winbind_separator(),
3821 names[0]);
3824 /* convert a string to a SID, either numeric or username/group */
3825 static BOOL
3826 convert_string_to_sid(struct cli_state *ipc_cli,
3827 POLICY_HND *pol,
3828 BOOL numeric,
3829 DOM_SID *sid,
3830 const char *str)
3832 enum lsa_SidType *types = NULL;
3833 DOM_SID *sids = NULL;
3834 BOOL result = True;
3835 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3837 if (!pipe_hnd) {
3838 return False;
3841 if (numeric) {
3842 if (strncmp(str, "S-", 2) == 0) {
3843 return string_to_sid(sid, str);
3846 result = False;
3847 goto done;
3850 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3851 pol, 1, &str, NULL, 1, &sids,
3852 &types))) {
3853 result = False;
3854 goto done;
3857 sid_copy(sid, &sids[0]);
3858 done:
3860 return result;
3864 /* parse an ACE in the same format as print_ace() */
3865 static BOOL
3866 parse_ace(struct cli_state *ipc_cli,
3867 POLICY_HND *pol,
3868 SEC_ACE *ace,
3869 BOOL numeric,
3870 char *str)
3872 char *p;
3873 const char *cp;
3874 fstring tok;
3875 unsigned int atype;
3876 unsigned int aflags;
3877 unsigned int amask;
3878 DOM_SID sid;
3879 SEC_ACCESS mask;
3880 const struct perm_value *v;
3881 struct perm_value {
3882 const char *perm;
3883 uint32 mask;
3886 /* These values discovered by inspection */
3887 static const struct perm_value special_values[] = {
3888 { "R", 0x00120089 },
3889 { "W", 0x00120116 },
3890 { "X", 0x001200a0 },
3891 { "D", 0x00010000 },
3892 { "P", 0x00040000 },
3893 { "O", 0x00080000 },
3894 { NULL, 0 },
3897 static const struct perm_value standard_values[] = {
3898 { "READ", 0x001200a9 },
3899 { "CHANGE", 0x001301bf },
3900 { "FULL", 0x001f01ff },
3901 { NULL, 0 },
3905 ZERO_STRUCTP(ace);
3906 p = strchr_m(str,':');
3907 if (!p) return False;
3908 *p = '\0';
3909 p++;
3910 /* Try to parse numeric form */
3912 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3913 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3914 goto done;
3917 /* Try to parse text form */
3919 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3920 return False;
3923 cp = p;
3924 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3925 return False;
3928 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3929 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3930 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3931 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3932 } else {
3933 return False;
3936 /* Only numeric form accepted for flags at present */
3938 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3939 sscanf(tok, "%i", &aflags))) {
3940 return False;
3943 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3944 return False;
3947 if (strncmp(tok, "0x", 2) == 0) {
3948 if (sscanf(tok, "%i", &amask) != 1) {
3949 return False;
3951 goto done;
3954 for (v = standard_values; v->perm; v++) {
3955 if (strcmp(tok, v->perm) == 0) {
3956 amask = v->mask;
3957 goto done;
3961 p = tok;
3963 while(*p) {
3964 BOOL found = False;
3966 for (v = special_values; v->perm; v++) {
3967 if (v->perm[0] == *p) {
3968 amask |= v->mask;
3969 found = True;
3973 if (!found) return False;
3974 p++;
3977 if (*p) {
3978 return False;
3981 done:
3982 mask = amask;
3983 init_sec_ace(ace, &sid, atype, mask, aflags);
3984 return True;
3987 /* add an ACE to a list of ACEs in a SEC_ACL */
3988 static BOOL
3989 add_ace(SEC_ACL **the_acl,
3990 SEC_ACE *ace,
3991 TALLOC_CTX *ctx)
3993 SEC_ACL *newacl;
3994 SEC_ACE *aces;
3996 if (! *the_acl) {
3997 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3998 return True;
4001 if ((aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces)) == NULL) {
4002 return False;
4004 memcpy(aces, (*the_acl)->aces, (*the_acl)->num_aces * sizeof(SEC_ACE));
4005 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
4006 newacl = make_sec_acl(ctx, (*the_acl)->revision,
4007 1+(*the_acl)->num_aces, aces);
4008 SAFE_FREE(aces);
4009 (*the_acl) = newacl;
4010 return True;
4014 /* parse a ascii version of a security descriptor */
4015 static SEC_DESC *
4016 sec_desc_parse(TALLOC_CTX *ctx,
4017 struct cli_state *ipc_cli,
4018 POLICY_HND *pol,
4019 BOOL numeric,
4020 char *str)
4022 const char *p = str;
4023 fstring tok;
4024 SEC_DESC *ret = NULL;
4025 size_t sd_size;
4026 DOM_SID *grp_sid=NULL;
4027 DOM_SID *owner_sid=NULL;
4028 SEC_ACL *dacl=NULL;
4029 int revision=1;
4031 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4033 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
4034 revision = strtol(tok+9, NULL, 16);
4035 continue;
4038 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
4039 if (owner_sid) {
4040 DEBUG(5, ("OWNER specified more than once!\n"));
4041 goto done;
4043 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4044 if (!owner_sid ||
4045 !convert_string_to_sid(ipc_cli, pol,
4046 numeric,
4047 owner_sid, tok+6)) {
4048 DEBUG(5, ("Failed to parse owner sid\n"));
4049 goto done;
4051 continue;
4054 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
4055 if (owner_sid) {
4056 DEBUG(5, ("OWNER specified more than once!\n"));
4057 goto done;
4059 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4060 if (!owner_sid ||
4061 !convert_string_to_sid(ipc_cli, pol,
4062 False,
4063 owner_sid, tok+7)) {
4064 DEBUG(5, ("Failed to parse owner sid\n"));
4065 goto done;
4067 continue;
4070 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
4071 if (grp_sid) {
4072 DEBUG(5, ("GROUP specified more than once!\n"));
4073 goto done;
4075 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4076 if (!grp_sid ||
4077 !convert_string_to_sid(ipc_cli, pol,
4078 numeric,
4079 grp_sid, tok+6)) {
4080 DEBUG(5, ("Failed to parse group sid\n"));
4081 goto done;
4083 continue;
4086 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
4087 if (grp_sid) {
4088 DEBUG(5, ("GROUP specified more than once!\n"));
4089 goto done;
4091 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4092 if (!grp_sid ||
4093 !convert_string_to_sid(ipc_cli, pol,
4094 False,
4095 grp_sid, tok+6)) {
4096 DEBUG(5, ("Failed to parse group sid\n"));
4097 goto done;
4099 continue;
4102 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
4103 SEC_ACE ace;
4104 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
4105 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4106 goto done;
4108 if(!add_ace(&dacl, &ace, ctx)) {
4109 DEBUG(5, ("Failed to add ACL %s\n", tok));
4110 goto done;
4112 continue;
4115 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
4116 SEC_ACE ace;
4117 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
4118 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4119 goto done;
4121 if(!add_ace(&dacl, &ace, ctx)) {
4122 DEBUG(5, ("Failed to add ACL %s\n", tok));
4123 goto done;
4125 continue;
4128 DEBUG(5, ("Failed to parse security descriptor\n"));
4129 goto done;
4132 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
4133 owner_sid, grp_sid, NULL, dacl, &sd_size);
4135 done:
4136 SAFE_FREE(grp_sid);
4137 SAFE_FREE(owner_sid);
4139 return ret;
4143 /* Obtain the current dos attributes */
4144 static DOS_ATTR_DESC *
4145 dos_attr_query(SMBCCTX *context,
4146 TALLOC_CTX *ctx,
4147 const char *filename,
4148 SMBCSRV *srv)
4150 struct timespec create_time_ts;
4151 struct timespec write_time_ts;
4152 struct timespec access_time_ts;
4153 struct timespec change_time_ts;
4154 SMB_OFF_T size = 0;
4155 uint16 mode = 0;
4156 SMB_INO_T inode = 0;
4157 DOS_ATTR_DESC *ret;
4159 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
4160 if (!ret) {
4161 errno = ENOMEM;
4162 return NULL;
4165 /* Obtain the DOS attributes */
4166 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
4167 &mode, &size,
4168 &create_time_ts,
4169 &access_time_ts,
4170 &write_time_ts,
4171 &change_time_ts,
4172 &inode)) {
4174 errno = smbc_errno(context, srv->cli);
4175 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
4176 return NULL;
4180 ret->mode = mode;
4181 ret->size = size;
4182 ret->create_time = convert_timespec_to_time_t(create_time_ts);
4183 ret->access_time = convert_timespec_to_time_t(access_time_ts);
4184 ret->write_time = convert_timespec_to_time_t(write_time_ts);
4185 ret->change_time = convert_timespec_to_time_t(change_time_ts);
4186 ret->inode = inode;
4188 return ret;
4192 /* parse a ascii version of a security descriptor */
4193 static void
4194 dos_attr_parse(SMBCCTX *context,
4195 DOS_ATTR_DESC *dad,
4196 SMBCSRV *srv,
4197 char *str)
4199 int n;
4200 const char *p = str;
4201 fstring tok;
4202 struct {
4203 const char * create_time_attr;
4204 const char * access_time_attr;
4205 const char * write_time_attr;
4206 const char * change_time_attr;
4207 } attr_strings;
4209 /* Determine whether to use old-style or new-style attribute names */
4210 if (context->internal->_full_time_names) {
4211 /* new-style names */
4212 attr_strings.create_time_attr = "CREATE_TIME";
4213 attr_strings.access_time_attr = "ACCESS_TIME";
4214 attr_strings.write_time_attr = "WRITE_TIME";
4215 attr_strings.change_time_attr = "CHANGE_TIME";
4216 } else {
4217 /* old-style names */
4218 attr_strings.create_time_attr = NULL;
4219 attr_strings.access_time_attr = "A_TIME";
4220 attr_strings.write_time_attr = "M_TIME";
4221 attr_strings.change_time_attr = "C_TIME";
4224 /* if this is to set the entire ACL... */
4225 if (*str == '*') {
4226 /* ... then increment past the first colon if there is one */
4227 if ((p = strchr(str, ':')) != NULL) {
4228 ++p;
4229 } else {
4230 p = str;
4234 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4236 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
4237 dad->mode = strtol(tok+5, NULL, 16);
4238 continue;
4241 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4242 dad->size = (SMB_OFF_T)atof(tok+5);
4243 continue;
4246 n = strlen(attr_strings.access_time_attr);
4247 if (StrnCaseCmp(tok, attr_strings.access_time_attr, n) == 0) {
4248 dad->access_time = (time_t)strtol(tok+n+1, NULL, 10);
4249 continue;
4252 n = strlen(attr_strings.change_time_attr);
4253 if (StrnCaseCmp(tok, attr_strings.change_time_attr, n) == 0) {
4254 dad->change_time = (time_t)strtol(tok+n+1, NULL, 10);
4255 continue;
4258 n = strlen(attr_strings.write_time_attr);
4259 if (StrnCaseCmp(tok, attr_strings.write_time_attr, n) == 0) {
4260 dad->write_time = (time_t)strtol(tok+n+1, NULL, 10);
4261 continue;
4264 if (attr_strings.create_time_attr != NULL) {
4265 n = strlen(attr_strings.create_time_attr);
4266 if (StrnCaseCmp(tok, attr_strings.create_time_attr,
4267 n) == 0) {
4268 dad->create_time = (time_t)strtol(tok+n+1,
4269 NULL, 10);
4270 continue;
4274 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4275 dad->inode = (SMB_INO_T)atof(tok+6);
4276 continue;
4281 /*****************************************************
4282 Retrieve the acls for a file.
4283 *******************************************************/
4285 static int
4286 cacl_get(SMBCCTX *context,
4287 TALLOC_CTX *ctx,
4288 SMBCSRV *srv,
4289 struct cli_state *ipc_cli,
4290 POLICY_HND *pol,
4291 char *filename,
4292 char *attr_name,
4293 char *buf,
4294 int bufsize)
4296 uint32 i;
4297 int n = 0;
4298 int n_used;
4299 BOOL all;
4300 BOOL all_nt;
4301 BOOL all_nt_acls;
4302 BOOL all_dos;
4303 BOOL some_nt;
4304 BOOL some_dos;
4305 BOOL exclude_nt_revision = False;
4306 BOOL exclude_nt_owner = False;
4307 BOOL exclude_nt_group = False;
4308 BOOL exclude_nt_acl = False;
4309 BOOL exclude_dos_mode = False;
4310 BOOL exclude_dos_size = False;
4311 BOOL exclude_dos_create_time = False;
4312 BOOL exclude_dos_access_time = False;
4313 BOOL exclude_dos_write_time = False;
4314 BOOL exclude_dos_change_time = False;
4315 BOOL exclude_dos_inode = False;
4316 BOOL numeric = True;
4317 BOOL determine_size = (bufsize == 0);
4318 int fnum = -1;
4319 SEC_DESC *sd;
4320 fstring sidstr;
4321 fstring name_sandbox;
4322 char *name;
4323 char *pExclude;
4324 char *p;
4325 struct timespec create_time_ts;
4326 struct timespec write_time_ts;
4327 struct timespec access_time_ts;
4328 struct timespec change_time_ts;
4329 time_t create_time = (time_t)0;
4330 time_t write_time = (time_t)0;
4331 time_t access_time = (time_t)0;
4332 time_t change_time = (time_t)0;
4333 SMB_OFF_T size = 0;
4334 uint16 mode = 0;
4335 SMB_INO_T ino = 0;
4336 struct cli_state *cli = srv->cli;
4337 struct {
4338 const char * create_time_attr;
4339 const char * access_time_attr;
4340 const char * write_time_attr;
4341 const char * change_time_attr;
4342 } attr_strings;
4343 struct {
4344 const char * create_time_attr;
4345 const char * access_time_attr;
4346 const char * write_time_attr;
4347 const char * change_time_attr;
4348 } excl_attr_strings;
4350 /* Determine whether to use old-style or new-style attribute names */
4351 if (context->internal->_full_time_names) {
4352 /* new-style names */
4353 attr_strings.create_time_attr = "CREATE_TIME";
4354 attr_strings.access_time_attr = "ACCESS_TIME";
4355 attr_strings.write_time_attr = "WRITE_TIME";
4356 attr_strings.change_time_attr = "CHANGE_TIME";
4358 excl_attr_strings.create_time_attr = "CREATE_TIME";
4359 excl_attr_strings.access_time_attr = "ACCESS_TIME";
4360 excl_attr_strings.write_time_attr = "WRITE_TIME";
4361 excl_attr_strings.change_time_attr = "CHANGE_TIME";
4362 } else {
4363 /* old-style names */
4364 attr_strings.create_time_attr = NULL;
4365 attr_strings.access_time_attr = "A_TIME";
4366 attr_strings.write_time_attr = "M_TIME";
4367 attr_strings.change_time_attr = "C_TIME";
4369 excl_attr_strings.create_time_attr = NULL;
4370 excl_attr_strings.access_time_attr = "dos_attr.A_TIME";
4371 excl_attr_strings.write_time_attr = "dos_attr.M_TIME";
4372 excl_attr_strings.change_time_attr = "dos_attr.C_TIME";
4375 /* Copy name so we can strip off exclusions (if any are specified) */
4376 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4378 /* Ensure name is null terminated */
4379 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4381 /* Play in the sandbox */
4382 name = name_sandbox;
4384 /* If there are any exclusions, point to them and mask them from name */
4385 if ((pExclude = strchr(name, '!')) != NULL)
4387 *pExclude++ = '\0';
4390 all = (StrnCaseCmp(name, "system.*", 8) == 0);
4391 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4392 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4393 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4394 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4395 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4396 numeric = (* (name + strlen(name) - 1) != '+');
4398 /* Look for exclusions from "all" requests */
4399 if (all || all_nt || all_dos) {
4401 /* Exclusions are delimited by '!' */
4402 for (;
4403 pExclude != NULL;
4404 pExclude = (p == NULL ? NULL : p + 1)) {
4406 /* Find end of this exclusion name */
4407 if ((p = strchr(pExclude, '!')) != NULL)
4409 *p = '\0';
4412 /* Which exclusion name is this? */
4413 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4414 exclude_nt_revision = True;
4416 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4417 exclude_nt_owner = True;
4419 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4420 exclude_nt_group = True;
4422 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4423 exclude_nt_acl = True;
4425 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4426 exclude_dos_mode = True;
4428 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4429 exclude_dos_size = True;
4431 else if (excl_attr_strings.create_time_attr != NULL &&
4432 StrCaseCmp(pExclude,
4433 excl_attr_strings.change_time_attr) == 0) {
4434 exclude_dos_create_time = True;
4436 else if (StrCaseCmp(pExclude,
4437 excl_attr_strings.access_time_attr) == 0) {
4438 exclude_dos_access_time = True;
4440 else if (StrCaseCmp(pExclude,
4441 excl_attr_strings.write_time_attr) == 0) {
4442 exclude_dos_write_time = True;
4444 else if (StrCaseCmp(pExclude,
4445 excl_attr_strings.change_time_attr) == 0) {
4446 exclude_dos_change_time = True;
4448 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4449 exclude_dos_inode = True;
4451 else {
4452 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4453 pExclude));
4454 errno = ENOATTR;
4455 return -1;
4460 n_used = 0;
4463 * If we are (possibly) talking to an NT or new system and some NT
4464 * attributes have been requested...
4466 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4467 /* Point to the portion after "system.nt_sec_desc." */
4468 name += 19; /* if (all) this will be invalid but unused */
4470 /* ... then obtain any NT attributes which were requested */
4471 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4473 if (fnum == -1) {
4474 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4475 filename, cli_errstr(cli)));
4476 errno = 0;
4477 return -1;
4480 sd = cli_query_secdesc(cli, fnum, ctx);
4482 if (!sd) {
4483 DEBUG(5,
4484 ("cacl_get Failed to query old descriptor\n"));
4485 errno = 0;
4486 return -1;
4489 cli_close(cli, fnum);
4491 if (! exclude_nt_revision) {
4492 if (all || all_nt) {
4493 if (determine_size) {
4494 p = talloc_asprintf(ctx,
4495 "REVISION:%d",
4496 sd->revision);
4497 if (!p) {
4498 errno = ENOMEM;
4499 return -1;
4501 n = strlen(p);
4502 } else {
4503 n = snprintf(buf, bufsize,
4504 "REVISION:%d",
4505 sd->revision);
4507 } else if (StrCaseCmp(name, "revision") == 0) {
4508 if (determine_size) {
4509 p = talloc_asprintf(ctx, "%d",
4510 sd->revision);
4511 if (!p) {
4512 errno = ENOMEM;
4513 return -1;
4515 n = strlen(p);
4516 } else {
4517 n = snprintf(buf, bufsize, "%d",
4518 sd->revision);
4522 if (!determine_size && n > bufsize) {
4523 errno = ERANGE;
4524 return -1;
4526 buf += n;
4527 n_used += n;
4528 bufsize -= n;
4531 if (! exclude_nt_owner) {
4532 /* Get owner and group sid */
4533 if (sd->owner_sid) {
4534 convert_sid_to_string(ipc_cli, pol,
4535 sidstr,
4536 numeric,
4537 sd->owner_sid);
4538 } else {
4539 fstrcpy(sidstr, "");
4542 if (all || all_nt) {
4543 if (determine_size) {
4544 p = talloc_asprintf(ctx, ",OWNER:%s",
4545 sidstr);
4546 if (!p) {
4547 errno = ENOMEM;
4548 return -1;
4550 n = strlen(p);
4551 } else if (sidstr[0] != '\0') {
4552 n = snprintf(buf, bufsize,
4553 ",OWNER:%s", sidstr);
4555 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4556 if (determine_size) {
4557 p = talloc_asprintf(ctx, "%s", sidstr);
4558 if (!p) {
4559 errno = ENOMEM;
4560 return -1;
4562 n = strlen(p);
4563 } else {
4564 n = snprintf(buf, bufsize, "%s",
4565 sidstr);
4569 if (!determine_size && n > bufsize) {
4570 errno = ERANGE;
4571 return -1;
4573 buf += n;
4574 n_used += n;
4575 bufsize -= n;
4578 if (! exclude_nt_group) {
4579 if (sd->group_sid) {
4580 convert_sid_to_string(ipc_cli, pol,
4581 sidstr, numeric,
4582 sd->group_sid);
4583 } else {
4584 fstrcpy(sidstr, "");
4587 if (all || all_nt) {
4588 if (determine_size) {
4589 p = talloc_asprintf(ctx, ",GROUP:%s",
4590 sidstr);
4591 if (!p) {
4592 errno = ENOMEM;
4593 return -1;
4595 n = strlen(p);
4596 } else if (sidstr[0] != '\0') {
4597 n = snprintf(buf, bufsize,
4598 ",GROUP:%s", sidstr);
4600 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4601 if (determine_size) {
4602 p = talloc_asprintf(ctx, "%s", sidstr);
4603 if (!p) {
4604 errno = ENOMEM;
4605 return -1;
4607 n = strlen(p);
4608 } else {
4609 n = snprintf(buf, bufsize,
4610 "%s", sidstr);
4614 if (!determine_size && n > bufsize) {
4615 errno = ERANGE;
4616 return -1;
4618 buf += n;
4619 n_used += n;
4620 bufsize -= n;
4623 if (! exclude_nt_acl) {
4624 /* Add aces to value buffer */
4625 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4627 SEC_ACE *ace = &sd->dacl->aces[i];
4628 convert_sid_to_string(ipc_cli, pol,
4629 sidstr, numeric,
4630 &ace->trustee);
4632 if (all || all_nt) {
4633 if (determine_size) {
4634 p = talloc_asprintf(
4635 ctx,
4636 ",ACL:"
4637 "%s:%d/%d/0x%08x",
4638 sidstr,
4639 ace->type,
4640 ace->flags,
4641 ace->access_mask);
4642 if (!p) {
4643 errno = ENOMEM;
4644 return -1;
4646 n = strlen(p);
4647 } else {
4648 n = snprintf(
4649 buf, bufsize,
4650 ",ACL:%s:%d/%d/0x%08x",
4651 sidstr,
4652 ace->type,
4653 ace->flags,
4654 ace->access_mask);
4656 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4657 StrCaseCmp(name+3, sidstr) == 0) ||
4658 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4659 StrCaseCmp(name+4, sidstr) == 0)) {
4660 if (determine_size) {
4661 p = talloc_asprintf(
4662 ctx,
4663 "%d/%d/0x%08x",
4664 ace->type,
4665 ace->flags,
4666 ace->access_mask);
4667 if (!p) {
4668 errno = ENOMEM;
4669 return -1;
4671 n = strlen(p);
4672 } else {
4673 n = snprintf(buf, bufsize,
4674 "%d/%d/0x%08x",
4675 ace->type,
4676 ace->flags,
4677 ace->access_mask);
4679 } else if (all_nt_acls) {
4680 if (determine_size) {
4681 p = talloc_asprintf(
4682 ctx,
4683 "%s%s:%d/%d/0x%08x",
4684 i ? "," : "",
4685 sidstr,
4686 ace->type,
4687 ace->flags,
4688 ace->access_mask);
4689 if (!p) {
4690 errno = ENOMEM;
4691 return -1;
4693 n = strlen(p);
4694 } else {
4695 n = snprintf(buf, bufsize,
4696 "%s%s:%d/%d/0x%08x",
4697 i ? "," : "",
4698 sidstr,
4699 ace->type,
4700 ace->flags,
4701 ace->access_mask);
4704 if (!determine_size && n > bufsize) {
4705 errno = ERANGE;
4706 return -1;
4708 buf += n;
4709 n_used += n;
4710 bufsize -= n;
4714 /* Restore name pointer to its original value */
4715 name -= 19;
4718 if (all || some_dos) {
4719 /* Point to the portion after "system.dos_attr." */
4720 name += 16; /* if (all) this will be invalid but unused */
4722 /* Obtain the DOS attributes */
4723 if (!smbc_getatr(context, srv, filename, &mode, &size,
4724 &create_time_ts,
4725 &access_time_ts,
4726 &write_time_ts,
4727 &change_time_ts,
4728 &ino)) {
4730 errno = smbc_errno(context, srv->cli);
4731 return -1;
4735 create_time = convert_timespec_to_time_t(create_time_ts);
4736 access_time = convert_timespec_to_time_t(access_time_ts);
4737 write_time = convert_timespec_to_time_t(write_time_ts);
4738 change_time = convert_timespec_to_time_t(change_time_ts);
4740 if (! exclude_dos_mode) {
4741 if (all || all_dos) {
4742 if (determine_size) {
4743 p = talloc_asprintf(ctx,
4744 "%sMODE:0x%x",
4745 (ipc_cli &&
4746 (all || some_nt)
4747 ? ","
4748 : ""),
4749 mode);
4750 if (!p) {
4751 errno = ENOMEM;
4752 return -1;
4754 n = strlen(p);
4755 } else {
4756 n = snprintf(buf, bufsize,
4757 "%sMODE:0x%x",
4758 (ipc_cli &&
4759 (all || some_nt)
4760 ? ","
4761 : ""),
4762 mode);
4764 } else if (StrCaseCmp(name, "mode") == 0) {
4765 if (determine_size) {
4766 p = talloc_asprintf(ctx, "0x%x", mode);
4767 if (!p) {
4768 errno = ENOMEM;
4769 return -1;
4771 n = strlen(p);
4772 } else {
4773 n = snprintf(buf, bufsize,
4774 "0x%x", mode);
4778 if (!determine_size && n > bufsize) {
4779 errno = ERANGE;
4780 return -1;
4782 buf += n;
4783 n_used += n;
4784 bufsize -= n;
4787 if (! exclude_dos_size) {
4788 if (all || all_dos) {
4789 if (determine_size) {
4790 p = talloc_asprintf(
4791 ctx,
4792 ",SIZE:%.0f",
4793 (double)size);
4794 if (!p) {
4795 errno = ENOMEM;
4796 return -1;
4798 n = strlen(p);
4799 } else {
4800 n = snprintf(buf, bufsize,
4801 ",SIZE:%.0f",
4802 (double)size);
4804 } else if (StrCaseCmp(name, "size") == 0) {
4805 if (determine_size) {
4806 p = talloc_asprintf(
4807 ctx,
4808 "%.0f",
4809 (double)size);
4810 if (!p) {
4811 errno = ENOMEM;
4812 return -1;
4814 n = strlen(p);
4815 } else {
4816 n = snprintf(buf, bufsize,
4817 "%.0f",
4818 (double)size);
4822 if (!determine_size && n > bufsize) {
4823 errno = ERANGE;
4824 return -1;
4826 buf += n;
4827 n_used += n;
4828 bufsize -= n;
4831 if (! exclude_dos_create_time &&
4832 attr_strings.create_time_attr != NULL) {
4833 if (all || all_dos) {
4834 if (determine_size) {
4835 p = talloc_asprintf(ctx,
4836 ",%s:%lu",
4837 attr_strings.create_time_attr,
4838 create_time);
4839 if (!p) {
4840 errno = ENOMEM;
4841 return -1;
4843 n = strlen(p);
4844 } else {
4845 n = snprintf(buf, bufsize,
4846 ",%s:%lu",
4847 attr_strings.create_time_attr,
4848 create_time);
4850 } else if (StrCaseCmp(name, attr_strings.create_time_attr) == 0) {
4851 if (determine_size) {
4852 p = talloc_asprintf(ctx, "%lu", create_time);
4853 if (!p) {
4854 errno = ENOMEM;
4855 return -1;
4857 n = strlen(p);
4858 } else {
4859 n = snprintf(buf, bufsize,
4860 "%lu", create_time);
4864 if (!determine_size && n > bufsize) {
4865 errno = ERANGE;
4866 return -1;
4868 buf += n;
4869 n_used += n;
4870 bufsize -= n;
4873 if (! exclude_dos_access_time) {
4874 if (all || all_dos) {
4875 if (determine_size) {
4876 p = talloc_asprintf(ctx,
4877 ",%s:%lu",
4878 attr_strings.access_time_attr,
4879 access_time);
4880 if (!p) {
4881 errno = ENOMEM;
4882 return -1;
4884 n = strlen(p);
4885 } else {
4886 n = snprintf(buf, bufsize,
4887 ",%s:%lu",
4888 attr_strings.access_time_attr,
4889 access_time);
4891 } else if (StrCaseCmp(name, attr_strings.access_time_attr) == 0) {
4892 if (determine_size) {
4893 p = talloc_asprintf(ctx, "%lu", access_time);
4894 if (!p) {
4895 errno = ENOMEM;
4896 return -1;
4898 n = strlen(p);
4899 } else {
4900 n = snprintf(buf, bufsize,
4901 "%lu", access_time);
4905 if (!determine_size && n > bufsize) {
4906 errno = ERANGE;
4907 return -1;
4909 buf += n;
4910 n_used += n;
4911 bufsize -= n;
4914 if (! exclude_dos_write_time) {
4915 if (all || all_dos) {
4916 if (determine_size) {
4917 p = talloc_asprintf(ctx,
4918 ",%s:%lu",
4919 attr_strings.write_time_attr,
4920 write_time);
4921 if (!p) {
4922 errno = ENOMEM;
4923 return -1;
4925 n = strlen(p);
4926 } else {
4927 n = snprintf(buf, bufsize,
4928 ",%s:%lu",
4929 attr_strings.write_time_attr,
4930 write_time);
4932 } else if (StrCaseCmp(name, attr_strings.write_time_attr) == 0) {
4933 if (determine_size) {
4934 p = talloc_asprintf(ctx, "%lu", write_time);
4935 if (!p) {
4936 errno = ENOMEM;
4937 return -1;
4939 n = strlen(p);
4940 } else {
4941 n = snprintf(buf, bufsize,
4942 "%lu", write_time);
4946 if (!determine_size && n > bufsize) {
4947 errno = ERANGE;
4948 return -1;
4950 buf += n;
4951 n_used += n;
4952 bufsize -= n;
4955 if (! exclude_dos_change_time) {
4956 if (all || all_dos) {
4957 if (determine_size) {
4958 p = talloc_asprintf(ctx,
4959 ",%s:%lu",
4960 attr_strings.change_time_attr,
4961 change_time);
4962 if (!p) {
4963 errno = ENOMEM;
4964 return -1;
4966 n = strlen(p);
4967 } else {
4968 n = snprintf(buf, bufsize,
4969 ",%s:%lu",
4970 attr_strings.change_time_attr,
4971 change_time);
4973 } else if (StrCaseCmp(name, attr_strings.change_time_attr) == 0) {
4974 if (determine_size) {
4975 p = talloc_asprintf(ctx, "%lu", change_time);
4976 if (!p) {
4977 errno = ENOMEM;
4978 return -1;
4980 n = strlen(p);
4981 } else {
4982 n = snprintf(buf, bufsize,
4983 "%lu", change_time);
4987 if (!determine_size && n > bufsize) {
4988 errno = ERANGE;
4989 return -1;
4991 buf += n;
4992 n_used += n;
4993 bufsize -= n;
4996 if (! exclude_dos_inode) {
4997 if (all || all_dos) {
4998 if (determine_size) {
4999 p = talloc_asprintf(
5000 ctx,
5001 ",INODE:%.0f",
5002 (double)ino);
5003 if (!p) {
5004 errno = ENOMEM;
5005 return -1;
5007 n = strlen(p);
5008 } else {
5009 n = snprintf(buf, bufsize,
5010 ",INODE:%.0f",
5011 (double) ino);
5013 } else if (StrCaseCmp(name, "inode") == 0) {
5014 if (determine_size) {
5015 p = talloc_asprintf(
5016 ctx,
5017 "%.0f",
5018 (double) ino);
5019 if (!p) {
5020 errno = ENOMEM;
5021 return -1;
5023 n = strlen(p);
5024 } else {
5025 n = snprintf(buf, bufsize,
5026 "%.0f",
5027 (double) ino);
5031 if (!determine_size && n > bufsize) {
5032 errno = ERANGE;
5033 return -1;
5035 buf += n;
5036 n_used += n;
5037 bufsize -= n;
5040 /* Restore name pointer to its original value */
5041 name -= 16;
5044 if (n_used == 0) {
5045 errno = ENOATTR;
5046 return -1;
5049 return n_used;
5053 /*****************************************************
5054 set the ACLs on a file given an ascii description
5055 *******************************************************/
5056 static int
5057 cacl_set(TALLOC_CTX *ctx,
5058 struct cli_state *cli,
5059 struct cli_state *ipc_cli,
5060 POLICY_HND *pol,
5061 const char *filename,
5062 const char *the_acl,
5063 int mode,
5064 int flags)
5066 int fnum;
5067 int err = 0;
5068 SEC_DESC *sd = NULL, *old;
5069 SEC_ACL *dacl = NULL;
5070 DOM_SID *owner_sid = NULL;
5071 DOM_SID *grp_sid = NULL;
5072 uint32 i, j;
5073 size_t sd_size;
5074 int ret = 0;
5075 char *p;
5076 BOOL numeric = True;
5078 /* the_acl will be null for REMOVE_ALL operations */
5079 if (the_acl) {
5080 numeric = ((p = strchr(the_acl, ':')) != NULL &&
5081 p > the_acl &&
5082 p[-1] != '+');
5084 /* if this is to set the entire ACL... */
5085 if (*the_acl == '*') {
5086 /* ... then increment past the first colon */
5087 the_acl = p + 1;
5090 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
5091 CONST_DISCARD(char *, the_acl));
5093 if (!sd) {
5094 errno = EINVAL;
5095 return -1;
5099 /* SMBC_XATTR_MODE_REMOVE_ALL is the only caller
5100 that doesn't deref sd */
5102 if (!sd && (mode != SMBC_XATTR_MODE_REMOVE_ALL)) {
5103 errno = EINVAL;
5104 return -1;
5107 /* The desired access below is the only one I could find that works
5108 with NT4, W2KP and Samba */
5110 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
5112 if (fnum == -1) {
5113 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5114 filename, cli_errstr(cli)));
5115 errno = 0;
5116 return -1;
5119 old = cli_query_secdesc(cli, fnum, ctx);
5121 if (!old) {
5122 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
5123 errno = 0;
5124 return -1;
5127 cli_close(cli, fnum);
5129 switch (mode) {
5130 case SMBC_XATTR_MODE_REMOVE_ALL:
5131 old->dacl->num_aces = 0;
5132 SAFE_FREE(old->dacl->aces);
5133 SAFE_FREE(old->dacl);
5134 old->dacl = NULL;
5135 dacl = old->dacl;
5136 break;
5138 case SMBC_XATTR_MODE_REMOVE:
5139 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5140 BOOL found = False;
5142 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
5143 if (sec_ace_equal(&sd->dacl->aces[i],
5144 &old->dacl->aces[j])) {
5145 uint32 k;
5146 for (k=j; k<old->dacl->num_aces-1;k++) {
5147 old->dacl->aces[k] =
5148 old->dacl->aces[k+1];
5150 old->dacl->num_aces--;
5151 if (old->dacl->num_aces == 0) {
5152 SAFE_FREE(old->dacl->aces);
5153 SAFE_FREE(old->dacl);
5154 old->dacl = NULL;
5156 found = True;
5157 dacl = old->dacl;
5158 break;
5162 if (!found) {
5163 err = ENOATTR;
5164 ret = -1;
5165 goto failed;
5168 break;
5170 case SMBC_XATTR_MODE_ADD:
5171 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5172 BOOL found = False;
5174 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
5175 if (sid_equal(&sd->dacl->aces[i].trustee,
5176 &old->dacl->aces[j].trustee)) {
5177 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
5178 err = EEXIST;
5179 ret = -1;
5180 goto failed;
5182 old->dacl->aces[j] = sd->dacl->aces[i];
5183 ret = -1;
5184 found = True;
5188 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
5189 err = ENOATTR;
5190 ret = -1;
5191 goto failed;
5194 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5195 add_ace(&old->dacl, &sd->dacl->aces[i], ctx);
5198 dacl = old->dacl;
5199 break;
5201 case SMBC_XATTR_MODE_SET:
5202 old = sd;
5203 owner_sid = old->owner_sid;
5204 grp_sid = old->group_sid;
5205 dacl = old->dacl;
5206 break;
5208 case SMBC_XATTR_MODE_CHOWN:
5209 owner_sid = sd->owner_sid;
5210 break;
5212 case SMBC_XATTR_MODE_CHGRP:
5213 grp_sid = sd->group_sid;
5214 break;
5217 /* Denied ACE entries must come before allowed ones */
5218 sort_acl(old->dacl);
5220 /* Create new security descriptor and set it */
5221 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
5222 owner_sid, grp_sid, NULL, dacl, &sd_size);
5224 fnum = cli_nt_create(cli, filename,
5225 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
5227 if (fnum == -1) {
5228 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5229 filename, cli_errstr(cli)));
5230 errno = 0;
5231 return -1;
5234 if (!cli_set_secdesc(cli, fnum, sd)) {
5235 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
5236 ret = -1;
5239 /* Clean up */
5241 failed:
5242 cli_close(cli, fnum);
5244 if (err != 0) {
5245 errno = err;
5248 return ret;
5252 static int
5253 smbc_setxattr_ctx(SMBCCTX *context,
5254 const char *fname,
5255 const char *name,
5256 const void *value,
5257 size_t size,
5258 int flags)
5260 int ret;
5261 int ret2;
5262 SMBCSRV *srv;
5263 SMBCSRV *ipc_srv;
5264 fstring server;
5265 fstring share;
5266 fstring user;
5267 fstring password;
5268 fstring workgroup;
5269 pstring path;
5270 TALLOC_CTX *ctx;
5271 POLICY_HND pol;
5272 DOS_ATTR_DESC *dad;
5273 struct {
5274 const char * create_time_attr;
5275 const char * access_time_attr;
5276 const char * write_time_attr;
5277 const char * change_time_attr;
5278 } attr_strings;
5280 if (!context || !context->internal ||
5281 !context->internal->_initialized) {
5283 errno = EINVAL; /* Best I can think of ... */
5284 return -1;
5288 if (!fname) {
5290 errno = EINVAL;
5291 return -1;
5295 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
5296 fname, name, (int) size, (const char*)value));
5298 if (smbc_parse_path(context, fname,
5299 workgroup, sizeof(workgroup),
5300 server, sizeof(server),
5301 share, sizeof(share),
5302 path, sizeof(path),
5303 user, sizeof(user),
5304 password, sizeof(password),
5305 NULL, 0)) {
5306 errno = EINVAL;
5307 return -1;
5310 if (user[0] == (char)0) fstrcpy(user, context->user);
5312 srv = smbc_server(context, True,
5313 server, share, workgroup, user, password);
5314 if (!srv) {
5315 return -1; /* errno set by smbc_server */
5318 if (! srv->no_nt_session) {
5319 ipc_srv = smbc_attr_server(context, server, share,
5320 workgroup, user, password,
5321 &pol);
5322 if (! ipc_srv) {
5323 srv->no_nt_session = True;
5325 } else {
5326 ipc_srv = NULL;
5329 ctx = talloc_init("smbc_setxattr");
5330 if (!ctx) {
5331 errno = ENOMEM;
5332 return -1;
5336 * Are they asking to set the entire set of known attributes?
5338 if (StrCaseCmp(name, "system.*") == 0 ||
5339 StrCaseCmp(name, "system.*+") == 0) {
5340 /* Yup. */
5341 char *namevalue =
5342 talloc_asprintf(ctx, "%s:%s",
5343 name+7, (const char *) value);
5344 if (! namevalue) {
5345 errno = ENOMEM;
5346 ret = -1;
5347 return -1;
5350 if (ipc_srv) {
5351 ret = cacl_set(ctx, srv->cli,
5352 ipc_srv->cli, &pol, path,
5353 namevalue,
5354 (*namevalue == '*'
5355 ? SMBC_XATTR_MODE_SET
5356 : SMBC_XATTR_MODE_ADD),
5357 flags);
5358 } else {
5359 ret = 0;
5362 /* get a DOS Attribute Descriptor with current attributes */
5363 dad = dos_attr_query(context, ctx, path, srv);
5364 if (dad) {
5365 /* Overwrite old with new, using what was provided */
5366 dos_attr_parse(context, dad, srv, namevalue);
5368 /* Set the new DOS attributes */
5369 if (! smbc_setatr(context, srv, path,
5370 dad->create_time,
5371 dad->access_time,
5372 dad->write_time,
5373 dad->change_time,
5374 dad->mode)) {
5376 /* cause failure if NT failed too */
5377 dad = NULL;
5381 /* we only fail if both NT and DOS sets failed */
5382 if (ret < 0 && ! dad) {
5383 ret = -1; /* in case dad was null */
5385 else {
5386 ret = 0;
5389 talloc_destroy(ctx);
5390 return ret;
5394 * Are they asking to set an access control element or to set
5395 * the entire access control list?
5397 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5398 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5399 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5400 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5401 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5403 /* Yup. */
5404 char *namevalue =
5405 talloc_asprintf(ctx, "%s:%s",
5406 name+19, (const char *) value);
5408 if (! ipc_srv) {
5409 ret = -1; /* errno set by smbc_server() */
5411 else if (! namevalue) {
5412 errno = ENOMEM;
5413 ret = -1;
5414 } else {
5415 ret = cacl_set(ctx, srv->cli,
5416 ipc_srv->cli, &pol, path,
5417 namevalue,
5418 (*namevalue == '*'
5419 ? SMBC_XATTR_MODE_SET
5420 : SMBC_XATTR_MODE_ADD),
5421 flags);
5423 talloc_destroy(ctx);
5424 return ret;
5428 * Are they asking to set the owner?
5430 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5431 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5433 /* Yup. */
5434 char *namevalue =
5435 talloc_asprintf(ctx, "%s:%s",
5436 name+19, (const char *) value);
5438 if (! ipc_srv) {
5440 ret = -1; /* errno set by smbc_server() */
5442 else if (! namevalue) {
5443 errno = ENOMEM;
5444 ret = -1;
5445 } else {
5446 ret = cacl_set(ctx, srv->cli,
5447 ipc_srv->cli, &pol, path,
5448 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5450 talloc_destroy(ctx);
5451 return ret;
5455 * Are they asking to set the group?
5457 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5458 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5460 /* Yup. */
5461 char *namevalue =
5462 talloc_asprintf(ctx, "%s:%s",
5463 name+19, (const char *) value);
5465 if (! ipc_srv) {
5466 /* errno set by smbc_server() */
5467 ret = -1;
5469 else if (! namevalue) {
5470 errno = ENOMEM;
5471 ret = -1;
5472 } else {
5473 ret = cacl_set(ctx, srv->cli,
5474 ipc_srv->cli, &pol, path,
5475 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5477 talloc_destroy(ctx);
5478 return ret;
5481 /* Determine whether to use old-style or new-style attribute names */
5482 if (context->internal->_full_time_names) {
5483 /* new-style names */
5484 attr_strings.create_time_attr = "system.dos_attr.CREATE_TIME";
5485 attr_strings.access_time_attr = "system.dos_attr.ACCESS_TIME";
5486 attr_strings.write_time_attr = "system.dos_attr.WRITE_TIME";
5487 attr_strings.change_time_attr = "system.dos_attr.CHANGE_TIME";
5488 } else {
5489 /* old-style names */
5490 attr_strings.create_time_attr = NULL;
5491 attr_strings.access_time_attr = "system.dos_attr.A_TIME";
5492 attr_strings.write_time_attr = "system.dos_attr.M_TIME";
5493 attr_strings.change_time_attr = "system.dos_attr.C_TIME";
5497 * Are they asking to set a DOS attribute?
5499 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5500 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5501 (attr_strings.create_time_attr != NULL &&
5502 StrCaseCmp(name, attr_strings.create_time_attr) == 0) ||
5503 StrCaseCmp(name, attr_strings.access_time_attr) == 0 ||
5504 StrCaseCmp(name, attr_strings.write_time_attr) == 0 ||
5505 StrCaseCmp(name, attr_strings.change_time_attr) == 0) {
5507 /* get a DOS Attribute Descriptor with current attributes */
5508 dad = dos_attr_query(context, ctx, path, srv);
5509 if (dad) {
5510 char *namevalue =
5511 talloc_asprintf(ctx, "%s:%s",
5512 name+16, (const char *) value);
5513 if (! namevalue) {
5514 errno = ENOMEM;
5515 ret = -1;
5516 } else {
5517 /* Overwrite old with provided new params */
5518 dos_attr_parse(context, dad, srv, namevalue);
5520 /* Set the new DOS attributes */
5521 ret2 = smbc_setatr(context, srv, path,
5522 dad->create_time,
5523 dad->access_time,
5524 dad->write_time,
5525 dad->change_time,
5526 dad->mode);
5528 /* ret2 has True (success) / False (failure) */
5529 if (ret2) {
5530 ret = 0;
5531 } else {
5532 ret = -1;
5535 } else {
5536 ret = -1;
5539 talloc_destroy(ctx);
5540 return ret;
5543 /* Unsupported attribute name */
5544 talloc_destroy(ctx);
5545 errno = EINVAL;
5546 return -1;
5549 static int
5550 smbc_getxattr_ctx(SMBCCTX *context,
5551 const char *fname,
5552 const char *name,
5553 const void *value,
5554 size_t size)
5556 int ret;
5557 SMBCSRV *srv;
5558 SMBCSRV *ipc_srv;
5559 fstring server;
5560 fstring share;
5561 fstring user;
5562 fstring password;
5563 fstring workgroup;
5564 pstring path;
5565 TALLOC_CTX *ctx;
5566 POLICY_HND pol;
5567 struct {
5568 const char * create_time_attr;
5569 const char * access_time_attr;
5570 const char * write_time_attr;
5571 const char * change_time_attr;
5572 } attr_strings;
5575 if (!context || !context->internal ||
5576 !context->internal->_initialized) {
5578 errno = EINVAL; /* Best I can think of ... */
5579 return -1;
5583 if (!fname) {
5585 errno = EINVAL;
5586 return -1;
5590 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5592 if (smbc_parse_path(context, fname,
5593 workgroup, sizeof(workgroup),
5594 server, sizeof(server),
5595 share, sizeof(share),
5596 path, sizeof(path),
5597 user, sizeof(user),
5598 password, sizeof(password),
5599 NULL, 0)) {
5600 errno = EINVAL;
5601 return -1;
5604 if (user[0] == (char)0) fstrcpy(user, context->user);
5606 srv = smbc_server(context, True,
5607 server, share, workgroup, user, password);
5608 if (!srv) {
5609 return -1; /* errno set by smbc_server */
5612 if (! srv->no_nt_session) {
5613 ipc_srv = smbc_attr_server(context, server, share,
5614 workgroup, user, password,
5615 &pol);
5616 if (! ipc_srv) {
5617 srv->no_nt_session = True;
5619 } else {
5620 ipc_srv = NULL;
5623 ctx = talloc_init("smbc:getxattr");
5624 if (!ctx) {
5625 errno = ENOMEM;
5626 return -1;
5629 /* Determine whether to use old-style or new-style attribute names */
5630 if (context->internal->_full_time_names) {
5631 /* new-style names */
5632 attr_strings.create_time_attr = "system.dos_attr.CREATE_TIME";
5633 attr_strings.access_time_attr = "system.dos_attr.ACCESS_TIME";
5634 attr_strings.write_time_attr = "system.dos_attr.WRITE_TIME";
5635 attr_strings.change_time_attr = "system.dos_attr.CHANGE_TIME";
5636 } else {
5637 /* old-style names */
5638 attr_strings.create_time_attr = NULL;
5639 attr_strings.access_time_attr = "system.dos_attr.A_TIME";
5640 attr_strings.write_time_attr = "system.dos_attr.M_TIME";
5641 attr_strings.change_time_attr = "system.dos_attr.C_TIME";
5644 /* Are they requesting a supported attribute? */
5645 if (StrCaseCmp(name, "system.*") == 0 ||
5646 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5647 StrCaseCmp(name, "system.*+") == 0 ||
5648 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5649 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5650 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5651 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5652 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5653 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5654 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5655 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5656 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5657 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5658 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5659 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5660 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5661 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5662 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5663 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5664 (attr_strings.create_time_attr != NULL &&
5665 StrCaseCmp(name, attr_strings.create_time_attr) == 0) ||
5666 StrCaseCmp(name, attr_strings.access_time_attr) == 0 ||
5667 StrCaseCmp(name, attr_strings.write_time_attr) == 0 ||
5668 StrCaseCmp(name, attr_strings.change_time_attr) == 0 ||
5669 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5671 /* Yup. */
5672 ret = cacl_get(context, ctx, srv,
5673 ipc_srv == NULL ? NULL : ipc_srv->cli,
5674 &pol, path,
5675 CONST_DISCARD(char *, name),
5676 CONST_DISCARD(char *, value), size);
5677 if (ret < 0 && errno == 0) {
5678 errno = smbc_errno(context, srv->cli);
5680 talloc_destroy(ctx);
5681 return ret;
5684 /* Unsupported attribute name */
5685 talloc_destroy(ctx);
5686 errno = EINVAL;
5687 return -1;
5691 static int
5692 smbc_removexattr_ctx(SMBCCTX *context,
5693 const char *fname,
5694 const char *name)
5696 int ret;
5697 SMBCSRV *srv;
5698 SMBCSRV *ipc_srv;
5699 fstring server;
5700 fstring share;
5701 fstring user;
5702 fstring password;
5703 fstring workgroup;
5704 pstring path;
5705 TALLOC_CTX *ctx;
5706 POLICY_HND pol;
5708 if (!context || !context->internal ||
5709 !context->internal->_initialized) {
5711 errno = EINVAL; /* Best I can think of ... */
5712 return -1;
5716 if (!fname) {
5718 errno = EINVAL;
5719 return -1;
5723 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5725 if (smbc_parse_path(context, fname,
5726 workgroup, sizeof(workgroup),
5727 server, sizeof(server),
5728 share, sizeof(share),
5729 path, sizeof(path),
5730 user, sizeof(user),
5731 password, sizeof(password),
5732 NULL, 0)) {
5733 errno = EINVAL;
5734 return -1;
5737 if (user[0] == (char)0) fstrcpy(user, context->user);
5739 srv = smbc_server(context, True,
5740 server, share, workgroup, user, password);
5741 if (!srv) {
5742 return -1; /* errno set by smbc_server */
5745 if (! srv->no_nt_session) {
5746 ipc_srv = smbc_attr_server(context, server, share,
5747 workgroup, user, password,
5748 &pol);
5749 if (! ipc_srv) {
5750 srv->no_nt_session = True;
5752 } else {
5753 ipc_srv = NULL;
5756 if (! ipc_srv) {
5757 return -1; /* errno set by smbc_attr_server */
5760 ctx = talloc_init("smbc_removexattr");
5761 if (!ctx) {
5762 errno = ENOMEM;
5763 return -1;
5766 /* Are they asking to set the entire ACL? */
5767 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5768 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5770 /* Yup. */
5771 ret = cacl_set(ctx, srv->cli,
5772 ipc_srv->cli, &pol, path,
5773 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5774 talloc_destroy(ctx);
5775 return ret;
5779 * Are they asking to remove one or more spceific security descriptor
5780 * attributes?
5782 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5783 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5784 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5785 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5786 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5787 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5788 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5790 /* Yup. */
5791 ret = cacl_set(ctx, srv->cli,
5792 ipc_srv->cli, &pol, path,
5793 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5794 talloc_destroy(ctx);
5795 return ret;
5798 /* Unsupported attribute name */
5799 talloc_destroy(ctx);
5800 errno = EINVAL;
5801 return -1;
5804 static int
5805 smbc_listxattr_ctx(SMBCCTX *context,
5806 const char *fname,
5807 char *list,
5808 size_t size)
5811 * This isn't quite what listxattr() is supposed to do. This returns
5812 * the complete set of attribute names, always, rather than only those
5813 * attribute names which actually exist for a file. Hmmm...
5815 const char supported_old[] =
5816 "system.*\0"
5817 "system.*+\0"
5818 "system.nt_sec_desc.revision\0"
5819 "system.nt_sec_desc.owner\0"
5820 "system.nt_sec_desc.owner+\0"
5821 "system.nt_sec_desc.group\0"
5822 "system.nt_sec_desc.group+\0"
5823 "system.nt_sec_desc.acl.*\0"
5824 "system.nt_sec_desc.acl\0"
5825 "system.nt_sec_desc.acl+\0"
5826 "system.nt_sec_desc.*\0"
5827 "system.nt_sec_desc.*+\0"
5828 "system.dos_attr.*\0"
5829 "system.dos_attr.mode\0"
5830 "system.dos_attr.c_time\0"
5831 "system.dos_attr.a_time\0"
5832 "system.dos_attr.m_time\0"
5834 const char supported_new[] =
5835 "system.*\0"
5836 "system.*+\0"
5837 "system.nt_sec_desc.revision\0"
5838 "system.nt_sec_desc.owner\0"
5839 "system.nt_sec_desc.owner+\0"
5840 "system.nt_sec_desc.group\0"
5841 "system.nt_sec_desc.group+\0"
5842 "system.nt_sec_desc.acl.*\0"
5843 "system.nt_sec_desc.acl\0"
5844 "system.nt_sec_desc.acl+\0"
5845 "system.nt_sec_desc.*\0"
5846 "system.nt_sec_desc.*+\0"
5847 "system.dos_attr.*\0"
5848 "system.dos_attr.mode\0"
5849 "system.dos_attr.create_time\0"
5850 "system.dos_attr.access_time\0"
5851 "system.dos_attr.write_time\0"
5852 "system.dos_attr.change_time\0"
5854 const char * supported;
5856 if (context->internal->_full_time_names) {
5857 supported = supported_new;
5858 } else {
5859 supported = supported_old;
5862 if (size == 0) {
5863 return sizeof(supported);
5866 if (sizeof(supported) > size) {
5867 errno = ERANGE;
5868 return -1;
5871 /* this can't be strcpy() because there are embedded null characters */
5872 memcpy(list, supported, sizeof(supported));
5873 return sizeof(supported);
5878 * Open a print file to be written to by other calls
5881 static SMBCFILE *
5882 smbc_open_print_job_ctx(SMBCCTX *context,
5883 const char *fname)
5885 fstring server;
5886 fstring share;
5887 fstring user;
5888 fstring password;
5889 pstring path;
5891 if (!context || !context->internal ||
5892 !context->internal->_initialized) {
5894 errno = EINVAL;
5895 return NULL;
5899 if (!fname) {
5901 errno = EINVAL;
5902 return NULL;
5906 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5908 if (smbc_parse_path(context, fname,
5909 NULL, 0,
5910 server, sizeof(server),
5911 share, sizeof(share),
5912 path, sizeof(path),
5913 user, sizeof(user),
5914 password, sizeof(password),
5915 NULL, 0)) {
5916 errno = EINVAL;
5917 return NULL;
5920 /* What if the path is empty, or the file exists? */
5922 return context->open(context, fname, O_WRONLY, 666);
5927 * Routine to print a file on a remote server ...
5929 * We open the file, which we assume to be on a remote server, and then
5930 * copy it to a print file on the share specified by printq.
5933 static int
5934 smbc_print_file_ctx(SMBCCTX *c_file,
5935 const char *fname,
5936 SMBCCTX *c_print,
5937 const char *printq)
5939 SMBCFILE *fid1;
5940 SMBCFILE *fid2;
5941 int bytes;
5942 int saverr;
5943 int tot_bytes = 0;
5944 char buf[4096];
5946 if (!c_file || !c_file->internal->_initialized || !c_print ||
5947 !c_print->internal->_initialized) {
5949 errno = EINVAL;
5950 return -1;
5954 if (!fname && !printq) {
5956 errno = EINVAL;
5957 return -1;
5961 /* Try to open the file for reading ... */
5963 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5965 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5966 return -1; /* smbc_open sets errno */
5970 /* Now, try to open the printer file for writing */
5972 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5974 saverr = errno; /* Save errno */
5975 c_file->close_fn(c_file, fid1);
5976 errno = saverr;
5977 return -1;
5981 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5983 tot_bytes += bytes;
5985 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5987 saverr = errno;
5988 c_file->close_fn(c_file, fid1);
5989 c_print->close_fn(c_print, fid2);
5990 errno = saverr;
5996 saverr = errno;
5998 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5999 c_print->close_fn(c_print, fid2);
6001 if (bytes < 0) {
6003 errno = saverr;
6004 return -1;
6008 return tot_bytes;
6013 * Routine to list print jobs on a printer share ...
6016 static int
6017 smbc_list_print_jobs_ctx(SMBCCTX *context,
6018 const char *fname,
6019 smbc_list_print_job_fn fn)
6021 SMBCSRV *srv;
6022 fstring server;
6023 fstring share;
6024 fstring user;
6025 fstring password;
6026 fstring workgroup;
6027 pstring path;
6029 if (!context || !context->internal ||
6030 !context->internal->_initialized) {
6032 errno = EINVAL;
6033 return -1;
6037 if (!fname) {
6039 errno = EINVAL;
6040 return -1;
6044 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
6046 if (smbc_parse_path(context, fname,
6047 workgroup, sizeof(workgroup),
6048 server, sizeof(server),
6049 share, sizeof(share),
6050 path, sizeof(path),
6051 user, sizeof(user),
6052 password, sizeof(password),
6053 NULL, 0)) {
6054 errno = EINVAL;
6055 return -1;
6058 if (user[0] == (char)0) fstrcpy(user, context->user);
6060 srv = smbc_server(context, True,
6061 server, share, workgroup, user, password);
6063 if (!srv) {
6065 return -1; /* errno set by smbc_server */
6069 if (cli_print_queue(srv->cli,
6070 (void (*)(struct print_job_info *))fn) < 0) {
6072 errno = smbc_errno(context, srv->cli);
6073 return -1;
6077 return 0;
6082 * Delete a print job from a remote printer share
6085 static int
6086 smbc_unlink_print_job_ctx(SMBCCTX *context,
6087 const char *fname,
6088 int id)
6090 SMBCSRV *srv;
6091 fstring server;
6092 fstring share;
6093 fstring user;
6094 fstring password;
6095 fstring workgroup;
6096 pstring path;
6097 int err;
6099 if (!context || !context->internal ||
6100 !context->internal->_initialized) {
6102 errno = EINVAL;
6103 return -1;
6107 if (!fname) {
6109 errno = EINVAL;
6110 return -1;
6114 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
6116 if (smbc_parse_path(context, fname,
6117 workgroup, sizeof(workgroup),
6118 server, sizeof(server),
6119 share, sizeof(share),
6120 path, sizeof(path),
6121 user, sizeof(user),
6122 password, sizeof(password),
6123 NULL, 0)) {
6124 errno = EINVAL;
6125 return -1;
6128 if (user[0] == (char)0) fstrcpy(user, context->user);
6130 srv = smbc_server(context, True,
6131 server, share, workgroup, user, password);
6133 if (!srv) {
6135 return -1; /* errno set by smbc_server */
6139 if ((err = cli_printjob_del(srv->cli, id)) != 0) {
6141 if (err < 0)
6142 errno = smbc_errno(context, srv->cli);
6143 else if (err == ERRnosuchprintjob)
6144 errno = EINVAL;
6145 return -1;
6149 return 0;
6154 * Get a new empty handle to fill in with your own info
6156 SMBCCTX *
6157 smbc_new_context(void)
6159 SMBCCTX *context;
6161 context = SMB_MALLOC_P(SMBCCTX);
6162 if (!context) {
6163 errno = ENOMEM;
6164 return NULL;
6167 ZERO_STRUCTP(context);
6169 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
6170 if (!context->internal) {
6171 SAFE_FREE(context);
6172 errno = ENOMEM;
6173 return NULL;
6176 ZERO_STRUCTP(context->internal);
6179 /* ADD REASONABLE DEFAULTS */
6180 context->debug = 0;
6181 context->timeout = 20000; /* 20 seconds */
6183 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
6184 context->options.urlencode_readdir_entries = False;/* backward compat */
6185 context->options.one_share_per_server = False;/* backward compat */
6186 context->internal->_share_mode = SMBC_SHAREMODE_DENY_NONE;
6187 /* backward compat */
6189 context->open = smbc_open_ctx;
6190 context->creat = smbc_creat_ctx;
6191 context->read = smbc_read_ctx;
6192 context->write = smbc_write_ctx;
6193 context->close_fn = smbc_close_ctx;
6194 context->unlink = smbc_unlink_ctx;
6195 context->rename = smbc_rename_ctx;
6196 context->lseek = smbc_lseek_ctx;
6197 context->stat = smbc_stat_ctx;
6198 context->fstat = smbc_fstat_ctx;
6199 context->opendir = smbc_opendir_ctx;
6200 context->closedir = smbc_closedir_ctx;
6201 context->readdir = smbc_readdir_ctx;
6202 context->getdents = smbc_getdents_ctx;
6203 context->mkdir = smbc_mkdir_ctx;
6204 context->rmdir = smbc_rmdir_ctx;
6205 context->telldir = smbc_telldir_ctx;
6206 context->lseekdir = smbc_lseekdir_ctx;
6207 context->fstatdir = smbc_fstatdir_ctx;
6208 context->chmod = smbc_chmod_ctx;
6209 context->utimes = smbc_utimes_ctx;
6210 context->setxattr = smbc_setxattr_ctx;
6211 context->getxattr = smbc_getxattr_ctx;
6212 context->removexattr = smbc_removexattr_ctx;
6213 context->listxattr = smbc_listxattr_ctx;
6214 context->open_print_job = smbc_open_print_job_ctx;
6215 context->print_file = smbc_print_file_ctx;
6216 context->list_print_jobs = smbc_list_print_jobs_ctx;
6217 context->unlink_print_job = smbc_unlink_print_job_ctx;
6219 context->callbacks.check_server_fn = smbc_check_server;
6220 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
6222 smbc_default_cache_functions(context);
6224 return context;
6228 * Free a context
6230 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
6231 * and thus you'll be leaking memory if not handled properly.
6235 smbc_free_context(SMBCCTX *context,
6236 int shutdown_ctx)
6238 if (!context) {
6239 errno = EBADF;
6240 return 1;
6243 if (shutdown_ctx) {
6244 SMBCFILE * f;
6245 DEBUG(1,("Performing aggressive shutdown.\n"));
6247 f = context->internal->_files;
6248 while (f) {
6249 context->close_fn(context, f);
6250 f = f->next;
6252 context->internal->_files = NULL;
6254 /* First try to remove the servers the nice way. */
6255 if (context->callbacks.purge_cached_fn(context)) {
6256 SMBCSRV * s;
6257 SMBCSRV * next;
6258 DEBUG(1, ("Could not purge all servers, "
6259 "Nice way shutdown failed.\n"));
6260 s = context->internal->_servers;
6261 while (s) {
6262 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
6263 s, s->cli->fd));
6264 cli_shutdown(s->cli);
6265 context->callbacks.remove_cached_srv_fn(context,
6267 next = s->next;
6268 DLIST_REMOVE(context->internal->_servers, s);
6269 SAFE_FREE(s);
6270 s = next;
6272 context->internal->_servers = NULL;
6275 else {
6276 /* This is the polite way */
6277 if (context->callbacks.purge_cached_fn(context)) {
6278 DEBUG(1, ("Could not purge all servers, "
6279 "free_context failed.\n"));
6280 errno = EBUSY;
6281 return 1;
6283 if (context->internal->_servers) {
6284 DEBUG(1, ("Active servers in context, "
6285 "free_context failed.\n"));
6286 errno = EBUSY;
6287 return 1;
6289 if (context->internal->_files) {
6290 DEBUG(1, ("Active files in context, "
6291 "free_context failed.\n"));
6292 errno = EBUSY;
6293 return 1;
6297 /* Things we have to clean up */
6298 SAFE_FREE(context->workgroup);
6299 SAFE_FREE(context->netbios_name);
6300 SAFE_FREE(context->user);
6302 DEBUG(3, ("Context %p succesfully freed\n", context));
6303 SAFE_FREE(context->internal);
6304 SAFE_FREE(context);
6305 return 0;
6310 * Each time the context structure is changed, we have binary backward
6311 * compatibility issues. Instead of modifying the public portions of the
6312 * context structure to add new options, instead, we put them in the internal
6313 * portion of the context structure and provide a set function for these new
6314 * options.
6316 void
6317 smbc_option_set(SMBCCTX *context,
6318 char *option_name,
6319 ... /* option_value */)
6321 va_list ap;
6322 union {
6323 int i;
6324 BOOL b;
6325 smbc_get_auth_data_with_context_fn auth_fn;
6326 void *v;
6327 } option_value;
6329 va_start(ap, option_name);
6331 if (strcmp(option_name, "debug_to_stderr") == 0) {
6333 * Log to standard error instead of standard output.
6335 option_value.b = (BOOL) va_arg(ap, int);
6336 context->internal->_debug_stderr = option_value.b;
6338 } else if (strcmp(option_name, "full_time_names") == 0) {
6340 * Use new-style time attribute names, e.g. WRITE_TIME rather
6341 * than the old-style names such as M_TIME. This allows also
6342 * setting/getting CREATE_TIME which was previously
6343 * unimplemented. (Note that the old C_TIME was supposed to
6344 * be CHANGE_TIME but was confused and sometimes referred to
6345 * CREATE_TIME.)
6347 option_value.b = (BOOL) va_arg(ap, int);
6348 context->internal->_full_time_names = option_value.b;
6350 } else if (strcmp(option_name, "open_share_mode") == 0) {
6352 * The share mode to use for files opened with
6353 * smbc_open_ctx(). The default is SMBC_SHAREMODE_DENY_NONE.
6355 option_value.i = va_arg(ap, int);
6356 context->internal->_share_mode =
6357 (smbc_share_mode) option_value.i;
6359 } else if (strcmp(option_name, "auth_function") == 0) {
6361 * Use the new-style authentication function which includes
6362 * the context.
6364 option_value.auth_fn =
6365 va_arg(ap, smbc_get_auth_data_with_context_fn);
6366 context->internal->_auth_fn_with_context =
6367 option_value.auth_fn;
6368 } else if (strcmp(option_name, "user_data") == 0) {
6370 * Save a user data handle which may be retrieved by the user
6371 * with smbc_option_get()
6373 option_value.v = va_arg(ap, void *);
6374 context->internal->_user_data = option_value.v;
6377 va_end(ap);
6382 * Retrieve the current value of an option
6384 void *
6385 smbc_option_get(SMBCCTX *context,
6386 char *option_name)
6388 if (strcmp(option_name, "debug_stderr") == 0) {
6390 * Log to standard error instead of standard output.
6392 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6393 return (void *) (intptr_t) context->internal->_debug_stderr;
6394 #else
6395 return (void *) context->internal->_debug_stderr;
6396 #endif
6397 } else if (strcmp(option_name, "full_time_names") == 0) {
6399 * Use new-style time attribute names, e.g. WRITE_TIME rather
6400 * than the old-style names such as M_TIME. This allows also
6401 * setting/getting CREATE_TIME which was previously
6402 * unimplemented. (Note that the old C_TIME was supposed to
6403 * be CHANGE_TIME but was confused and sometimes referred to
6404 * CREATE_TIME.)
6406 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6407 return (void *) (intptr_t) context->internal->_full_time_names;
6408 #else
6409 return (void *) context->internal->_full_time_names;
6410 #endif
6412 } else if (strcmp(option_name, "auth_function") == 0) {
6414 * Use the new-style authentication function which includes
6415 * the context.
6417 return (void *) context->internal->_auth_fn_with_context;
6418 } else if (strcmp(option_name, "user_data") == 0) {
6420 * Save a user data handle which may be retrieved by the user
6421 * with smbc_option_get()
6423 return context->internal->_user_data;
6426 return NULL;
6431 * Initialise the library etc
6433 * We accept a struct containing handle information.
6434 * valid values for info->debug from 0 to 100,
6435 * and insist that info->fn must be non-null.
6437 SMBCCTX *
6438 smbc_init_context(SMBCCTX *context)
6440 pstring conf;
6441 int pid;
6442 char *user = NULL;
6443 char *home = NULL;
6445 if (!context || !context->internal) {
6446 errno = EBADF;
6447 return NULL;
6450 /* Do not initialise the same client twice */
6451 if (context->internal->_initialized) {
6452 return 0;
6455 if ((!context->callbacks.auth_fn &&
6456 !context->internal->_auth_fn_with_context) ||
6457 context->debug < 0 ||
6458 context->debug > 100) {
6460 errno = EINVAL;
6461 return NULL;
6465 if (!smbc_initialized) {
6467 * Do some library-wide intializations the first time we get
6468 * called
6470 BOOL conf_loaded = False;
6472 /* Set this to what the user wants */
6473 DEBUGLEVEL = context->debug;
6475 load_case_tables();
6477 setup_logging("libsmbclient", True);
6478 if (context->internal->_debug_stderr) {
6479 dbf = x_stderr;
6480 x_setbuf(x_stderr, NULL);
6483 /* Here we would open the smb.conf file if needed ... */
6485 in_client = True; /* FIXME, make a param */
6487 home = getenv("HOME");
6488 if (home) {
6489 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
6490 if (lp_load(conf, True, False, False, True)) {
6491 conf_loaded = True;
6492 } else {
6493 DEBUG(5, ("Could not load config file: %s\n",
6494 conf));
6498 if (!conf_loaded) {
6500 * Well, if that failed, try the dyn_CONFIGFILE
6501 * Which points to the standard locn, and if that
6502 * fails, silently ignore it and use the internal
6503 * defaults ...
6506 if (!lp_load(dyn_CONFIGFILE, True, False, False, False)) {
6507 DEBUG(5, ("Could not load config file: %s\n",
6508 dyn_CONFIGFILE));
6509 } else if (home) {
6511 * We loaded the global config file. Now lets
6512 * load user-specific modifications to the
6513 * global config.
6515 slprintf(conf, sizeof(conf),
6516 "%s/.smb/smb.conf.append", home);
6517 if (!lp_load(conf, True, False, False, False)) {
6518 DEBUG(10,
6519 ("Could not append config file: "
6520 "%s\n",
6521 conf));
6526 load_interfaces(); /* Load the list of interfaces ... */
6528 reopen_logs(); /* Get logging working ... */
6531 * Block SIGPIPE (from lib/util_sock.c: write())
6532 * It is not needed and should not stop execution
6534 BlockSignals(True, SIGPIPE);
6536 /* Done with one-time initialisation */
6537 smbc_initialized = 1;
6541 if (!context->user) {
6543 * FIXME: Is this the best way to get the user info?
6545 user = getenv("USER");
6546 /* walk around as "guest" if no username can be found */
6547 if (!user) context->user = SMB_STRDUP("guest");
6548 else context->user = SMB_STRDUP(user);
6551 if (!context->netbios_name) {
6553 * We try to get our netbios name from the config. If that
6554 * fails we fall back on constructing our netbios name from
6555 * our hostname etc
6557 if (global_myname()) {
6558 context->netbios_name = SMB_STRDUP(global_myname());
6560 else {
6562 * Hmmm, I want to get hostname as well, but I am too
6563 * lazy for the moment
6565 pid = sys_getpid();
6566 context->netbios_name = (char *)SMB_MALLOC(17);
6567 if (!context->netbios_name) {
6568 errno = ENOMEM;
6569 return NULL;
6571 slprintf(context->netbios_name, 16,
6572 "smbc%s%d", context->user, pid);
6576 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
6578 if (!context->workgroup) {
6579 if (lp_workgroup()) {
6580 context->workgroup = SMB_STRDUP(lp_workgroup());
6582 else {
6583 /* TODO: Think about a decent default workgroup */
6584 context->workgroup = SMB_STRDUP("samba");
6588 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
6590 /* shortest timeout is 1 second */
6591 if (context->timeout > 0 && context->timeout < 1000)
6592 context->timeout = 1000;
6595 * FIXME: Should we check the function pointers here?
6598 context->internal->_initialized = True;
6600 return context;
6604 /* Return the verion of samba, and thus libsmbclient */
6605 const char *
6606 smbc_version(void)
6608 return samba_version_string();