2 Unix SMB/Netbios implementation.
3 SMB client library implementation
4 Copyright (C) Andrew Tridgell 1998
5 Copyright (C) Richard Sharpe 2000, 2002
6 Copyright (C) John Terpstra 2000
7 Copyright (C) Tom Jansen (Ninja ISD) 2002
8 Copyright (C) Derrell Lipman 2003, 2004
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include "include/libsmb_internal.h"
31 * DOS Attribute values (used internally)
33 typedef struct DOS_ATTR_DESC {
44 * Internal flags for extended attributes
47 /* internal mode values */
48 #define SMBC_XATTR_MODE_ADD 1
49 #define SMBC_XATTR_MODE_REMOVE 2
50 #define SMBC_XATTR_MODE_REMOVE_ALL 3
51 #define SMBC_XATTR_MODE_SET 4
52 #define SMBC_XATTR_MODE_CHOWN 5
53 #define SMBC_XATTR_MODE_CHGRP 6
55 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
57 /*We should test for this in configure ... */
59 #define ENOTSUP EOPNOTSUPP
63 * Functions exported by libsmb_cache.c that we need here
65 int smbc_default_cache_functions(SMBCCTX *context);
68 * check if an element is part of the list.
69 * FIXME: Does not belong here !
70 * Can anyone put this in a macro in dlinklist.h ?
73 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
74 if (!p || !list) return False;
76 if (p == list) return True;
83 * Find an lsa pipe handle associated with a cli struct.
86 static struct rpc_pipe_client *find_lsa_pipe_hnd(struct cli_state *ipc_cli)
88 struct rpc_pipe_client *pipe_hnd;
90 for (pipe_hnd = ipc_cli->pipe_list; pipe_hnd; pipe_hnd = pipe_hnd->next) {
91 if (pipe_hnd->pipe_idx == PI_LSARPC) {
99 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file);
100 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence);
102 extern BOOL in_client;
105 * Is the logging working / configfile read ?
107 static int smbc_initialized = 0;
110 hex2int( unsigned int _char )
112 if ( _char >= 'A' && _char <='F')
113 return _char - 'A' + 10;
114 if ( _char >= 'a' && _char <='f')
115 return _char - 'a' + 10;
116 if ( _char >= '0' && _char <='9')
124 * Convert strings of %xx to their single character equivalent. Each 'x' must
125 * be a valid hexadecimal digit, or that % sequence is left undecoded.
127 * dest may, but need not be, the same pointer as src.
129 * Returns the number of % sequences which could not be converted due to lack
130 * of two following hexadecimal digits.
133 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
135 int old_length = strlen(src);
141 if ( old_length == 0 ) {
146 while ( i < old_length ) {
147 unsigned char character = src[ i++ ];
149 if (character == '%') {
150 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
151 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
153 /* Replace valid sequence */
154 if (a != -1 && b != -1) {
156 /* Replace valid %xx sequence with %dd */
157 character = (a * 16) + b;
159 if (character == '\0') {
160 break; /* Stop at %00 */
175 strncpy(dest, temp, max_dest_len);
183 * Convert any characters not specifically allowed in a URL into their %xx
186 * Returns the remaining buffer length.
189 smbc_urlencode(char * dest, char * src, int max_dest_len)
191 char hex[] = "0123456789ABCDEF";
193 for (; *src != '\0' && max_dest_len >= 3; src++) {
205 *dest++ = hex[(*src >> 4) & 0x0f];
206 *dest++ = hex[*src & 0x0f];
221 * Function to parse a path and turn it into components
223 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
224 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
225 * general format ("smb:" only; we do not look for "cifs:").
229 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
233 * smb:// Show all workgroups.
235 * The method of locating the list of workgroups varies
236 * depending upon the setting of the context variable
237 * context->options.browse_max_lmb_count. This value
238 * determine the maximum number of local master browsers to
239 * query for the list of workgroups. In order to ensure that
240 * a complete list of workgroups is obtained, all master
241 * browsers must be queried, but if there are many
242 * workgroups, the time spent querying can begin to add up.
243 * For small networks (not many workgroups), it is suggested
244 * that this variable be set to 0, indicating query all local
245 * master browsers. When the network has many workgroups, a
246 * reasonable setting for this variable might be around 3.
248 * smb://name/ if name<1D> or name<1B> exists, list servers in
249 * workgroup, else, if name<20> exists, list all shares
252 * If "options" are provided, this function returns the entire option list as a
253 * string, for later parsing by the caller. Note that currently, no options
257 static const char *smbc_prefix = "smb:";
260 smbc_parse_path(SMBCCTX *context,
262 char *server, int server_len,
263 char *share, int share_len,
264 char *path, int path_len,
265 char *user, int user_len,
266 char *password, int password_len,
267 char *options, int options_len)
275 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
276 if (options != NULL && options_len > 0) {
277 options[0] = (char)0;
281 /* see if it has the right prefix */
282 len = strlen(smbc_prefix);
283 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
284 return -1; /* What about no smb: ? */
289 /* Watch the test below, we are testing to see if we should exit */
291 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
293 DEBUG(1, ("Invalid path (does not begin with smb://"));
298 p += 2; /* Skip the double slash */
300 /* See if any options were specified */
301 if ((q = strrchr(p, '?')) != NULL ) {
302 /* There are options. Null terminate here and point to them */
305 DEBUG(4, ("Found options '%s'", q));
307 /* Copy the options */
308 if (options != NULL && options_len > 0) {
309 safe_strcpy(options, q, options_len - 1);
318 strncpy(server, context->workgroup,
319 (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
325 * ok, its for us. Now parse out the server, share etc.
327 * However, we want to parse out [[domain;]user[:password]@] if it
331 /* check that '@' occurs before '/', if '/' exists at all */
332 q = strchr_m(p, '@');
333 r = strchr_m(p, '/');
334 if (q && (!r || q < r)) {
335 pstring username, passwd, domain;
336 const char *u = userinfo;
338 next_token(&p, userinfo, "@", sizeof(fstring));
340 username[0] = passwd[0] = domain[0] = 0;
342 if (strchr_m(u, ';')) {
344 next_token(&u, domain, ";", sizeof(fstring));
348 if (strchr_m(u, ':')) {
350 next_token(&u, username, ":", sizeof(fstring));
357 pstrcpy(username, u);
362 strncpy(user, username, user_len); /* FIXME, domain */
365 strncpy(password, passwd, password_len);
369 if (!next_token(&p, server, "/", sizeof(fstring))) {
375 if (*p == (char)0) goto decoding; /* That's it ... */
377 if (!next_token(&p, share, "/", sizeof(fstring))) {
383 safe_strcpy(path, p, path_len - 1);
385 all_string_sub(path, "/", "\\", 0);
388 (void) smbc_urldecode(path, path, path_len);
389 (void) smbc_urldecode(server, server, server_len);
390 (void) smbc_urldecode(share, share, share_len);
391 (void) smbc_urldecode(user, user, user_len);
392 (void) smbc_urldecode(password, password, password_len);
398 * Verify that the options specified in a URL are valid
400 static int smbc_check_options(char *server, char *share, char *path, char *options)
402 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' path='%s' options='%s'\n", server, share, path, options));
404 /* No options at all is always ok */
405 if (! *options) return 0;
407 /* Currently, we don't support any options. */
412 * Convert an SMB error into a UNIX error ...
414 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
416 int ret = cli_errno(c);
418 if (cli_is_dos_error(c)) {
422 cli_dos_error(c, &eclass, &ecode);
424 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
425 (int)eclass, (int)ecode, (int)ecode, ret));
429 status = cli_nt_error(c);
431 DEBUG(3,("smbc errno %s -> %d\n",
432 nt_errstr(status), ret));
439 * Check a server for being alive and well.
440 * returns 0 if the server is in shape. Returns 1 on error
442 * Also useable outside libsmbclient to enable external cache
443 * to do some checks too.
445 int smbc_check_server(SMBCCTX * context, SMBCSRV * server)
447 if ( send_keepalive(server->cli.fd) == False )
450 /* connection is ok */
455 * Remove a server from the cached server list it's unused.
456 * On success, 0 is returned. 1 is returned if the server could not be removed.
458 * Also useable outside libsmbclient
460 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
464 /* are we being fooled ? */
465 if (!context || !context->internal ||
466 !context->internal->_initialized || !srv) return 1;
469 /* Check all open files/directories for a relation with this server */
470 for (file = context->internal->_files; file; file=file->next) {
471 if (file->srv == srv) {
473 DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n",
479 DLIST_REMOVE(context->internal->_servers, srv);
481 cli_shutdown(&srv->cli);
483 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
485 context->callbacks.remove_cached_srv_fn(context, srv);
490 SMBCSRV *find_server(SMBCCTX *context,
502 srv = context->callbacks.get_cached_srv_fn(context, server, share,
503 workgroup, username);
505 if (!auth_called && !srv && (!username[0] || !password[0])) {
506 context->callbacks.auth_fn(server, share,
507 workgroup, sizeof(fstring),
508 username, sizeof(fstring),
509 password, sizeof(fstring));
511 * However, smbc_auth_fn may have picked up info relating to
512 * an existing connection, so try for an existing connection
516 goto check_server_cache;
521 if (context->callbacks.check_server_fn(context, srv)) {
523 * This server is no good anymore
524 * Try to remove it and check for more possible
525 * servers in the cache
527 if (context->callbacks.remove_unused_server_fn(context,
530 * We could not remove the server completely,
531 * remove it from the cache so we will not get
532 * it again. It will be removed when the last
533 * file/dir is closed.
535 context->callbacks.remove_cached_srv_fn(context,
540 * Maybe there are more cached connections to this
543 goto check_server_cache;
553 * Connect to a server, possibly on an existing connection
555 * Here, what we want to do is: If the server and username
556 * match an existing connection, reuse that, otherwise, establish a
559 * If we have to create a new connection, call the auth_fn to get the
560 * info we need, unless the username and password were passed in.
563 SMBCSRV *smbc_server(SMBCCTX *context,
564 const char *server, const char *share,
565 fstring workgroup, fstring username,
570 struct nmb_name called, calling;
571 const char *server_n = server;
574 int tried_reverse = 0;
577 const char *username_used;
582 if (server[0] == 0) {
588 /* Look for a cached connection, using the provided authinfo */
589 srv = find_server(context, server, share,
590 workgroup, username, password);
592 /* If we didn't find one... */
595 /* ... then see if there's one using anonymous login */
596 fstring anonymous = "";
597 srv = find_server(context, server, share,
598 workgroup, anonymous, password);
601 /* Look for a cached connection */
602 srv = find_server(context, server, share,
603 workgroup, username, password);
607 * If we found a connection and we're only allowed one share per
610 if (srv && *share != '\0' && context->options.one_share_per_server) {
613 * ... then if there's no current connection to the share,
614 * connect to it. find_server(), or rather the function
615 * pointed to by context->callbacks.get_cached_srv_fn which
616 * was called by find_server(), will have issued a tree
617 * disconnect if the requested share is not the same as the
618 * one that was already connected.
620 if (srv->cli.cnum == (uint16) -1) {
621 /* Ensure we have accurate auth info */
622 context->callbacks.auth_fn(server, share,
623 workgroup, sizeof(fstring),
624 username, sizeof(fstring),
625 password, sizeof(fstring));
627 if (! cli_send_tconX(&srv->cli, share, "?????",
628 password, strlen(password)+1)) {
630 errno = smbc_errno(context, &srv->cli);
631 cli_shutdown(&srv->cli);
632 context->callbacks.remove_cached_srv_fn(context, srv);
636 /* Regenerate the dev value since it's based on both server and share */
638 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
643 /* If we have a connection... */
646 /* ... then we're done here. Give 'em what they came for. */
650 make_nmb_name(&calling, context->netbios_name, 0x0);
651 make_nmb_name(&called , server, 0x20);
653 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
655 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
658 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
662 /* have to open a new connection */
663 if (!cli_initialise(&c)) {
668 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
669 c.use_kerberos = True;
671 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
672 c.fallback_after_kerberos = True;
675 c.timeout = context->timeout;
678 * Force use of port 139 for first try if share is $IPC, empty, or
679 * null, so browse lists can work
681 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
682 port_try_first = 139;
685 port_try_first = 445;
689 c.port = port_try_first;
691 if (!cli_connect(&c, server_n, &ip)) {
693 /* First connection attempt failed. Try alternate port. */
694 c.port = port_try_next;
696 if (!cli_connect(&c, server_n, &ip)) {
703 if (!cli_session_request(&c, &calling, &called)) {
705 if (strcmp(called.name, "*SMBSERVER")) {
706 make_nmb_name(&called , "*SMBSERVER", 0x20);
709 else { /* Try one more time, but ensure we don't loop */
711 /* Only try this if server is an IP address ... */
713 if (is_ipaddress(server) && !tried_reverse) {
715 struct in_addr rem_ip;
717 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
718 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
723 tried_reverse++; /* Yuck */
725 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
726 make_nmb_name(&called, remote_name, 0x20);
737 DEBUG(4,(" session request ok\n"));
739 if (!cli_negprot(&c)) {
745 username_used = username;
747 if (!cli_session_setup(&c, username_used,
748 password, strlen(password),
749 password, strlen(password),
752 /* Failed. Try an anonymous login, if allowed by flags. */
755 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
756 !cli_session_setup(&c, username_used,
767 DEBUG(4,(" session setup ok\n"));
769 if (!cli_send_tconX(&c, share, "?????",
770 password, strlen(password)+1)) {
771 errno = smbc_errno(context, &c);
776 DEBUG(4,(" tconx ok\n"));
779 * Ok, we have got a nice connection
780 * Let's allocate a server structure.
783 srv = SMB_MALLOC_P(SMBCSRV);
791 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
792 srv->no_pathinfo = False;
793 srv->no_pathinfo2 = False;
794 srv->no_nt_session = False;
796 /* now add it to the cache (internal or external) */
797 /* Let the cache function set errno if it wants to */
800 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username_used)) {
802 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
804 int saved_errno = errno;
805 DEBUG(3, (" Failed to add server to cache\n"));
813 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
814 server, share, srv));
816 DLIST_ADD(context->internal->_servers, srv);
821 if (!srv) return NULL;
828 * Connect to a server for getting/setting attributes, possibly on an existing
829 * connection. This works similarly to smbc_server().
831 SMBCSRV *smbc_attr_server(SMBCCTX *context,
832 const char *server, const char *share,
834 fstring username, fstring password,
838 struct cli_state *ipc_cli;
839 struct rpc_pipe_client *pipe_hnd;
841 SMBCSRV *ipc_srv=NULL;
844 * See if we've already created this special connection. Reference our
845 * "special" share name '*IPC$', which is an impossible real share name
846 * due to the leading asterisk.
848 ipc_srv = find_server(context, server, "*IPC$",
849 workgroup, username, password);
852 /* We didn't find a cached connection. Get the password */
853 if (*password == '\0') {
854 /* ... then retrieve it now. */
855 context->callbacks.auth_fn(server, share,
856 workgroup, sizeof(fstring),
857 username, sizeof(fstring),
858 password, sizeof(fstring));
862 nt_status = cli_full_connection(&ipc_cli,
863 global_myname(), server,
864 &ip, 0, "IPC$", "?????",
868 if (! NT_STATUS_IS_OK(nt_status)) {
869 DEBUG(1,("cli_full_connection failed! (%s)\n",
870 nt_errstr(nt_status)));
876 pipe_hnd = cli_rpc_pipe_open_noauth(ipc_cli, PI_LSARPC, &nt_status);
878 DEBUG(1, ("cli_nt_session_open fail!\n"));
880 cli_shutdown(ipc_cli);
884 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
885 but NT sends 0x2000000 so we might as well do it too. */
887 nt_status = rpccli_lsa_open_policy(pipe_hnd,
890 GENERIC_EXECUTE_ACCESS,
893 if (!NT_STATUS_IS_OK(nt_status)) {
894 errno = smbc_errno(context, ipc_cli);
895 cli_shutdown(ipc_cli);
900 ipc_srv = SMB_MALLOC_P(SMBCSRV);
903 cli_shutdown(ipc_cli);
907 ZERO_STRUCTP(ipc_srv);
908 ipc_srv->cli = *ipc_cli;
912 /* now add it to the cache (internal or external) */
914 errno = 0; /* let cache function set errno if it likes */
915 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
920 DEBUG(3, (" Failed to add server to cache\n"));
924 cli_shutdown(&ipc_srv->cli);
929 DLIST_ADD(context->internal->_servers, ipc_srv);
936 * Routine to open() a file ...
939 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
941 fstring server, share, user, password, workgroup;
944 struct cli_state *targetcli;
946 SMBCFILE *file = NULL;
949 if (!context || !context->internal ||
950 !context->internal->_initialized) {
952 errno = EINVAL; /* Best I can think of ... */
964 if (smbc_parse_path(context, fname,
965 server, sizeof(server),
966 share, sizeof(share),
969 password, sizeof(password),
975 if (user[0] == (char)0) fstrcpy(user, context->user);
977 fstrcpy(workgroup, context->workgroup);
979 srv = smbc_server(context, server, share, workgroup, user, password);
983 if (errno == EPERM) errno = EACCES;
984 return NULL; /* smbc_server sets errno */
988 /* Hmmm, the test for a directory is suspect here ... FIXME */
990 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
997 file = SMB_MALLOC_P(SMBCFILE);
1008 /*d_printf(">>>open: resolving %s\n", path);*/
1009 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1011 d_printf("Could not resolve %s\n", path);
1014 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1016 if ( targetcli->dfsroot )
1019 pstrcpy(temppath, targetpath);
1020 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1023 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1025 /* Handle the error ... */
1028 errno = smbc_errno(context, targetcli);
1033 /* Fill in file struct */
1036 file->fname = SMB_STRDUP(fname);
1041 DLIST_ADD(context->internal->_files, file);
1044 * If the file was opened in O_APPEND mode, all write
1045 * operations should be appended to the file. To do that,
1046 * though, using this protocol, would require a getattrE()
1047 * call for each and every write, to determine where the end
1048 * of the file is. (There does not appear to be an append flag
1049 * in the protocol.) Rather than add all of that overhead of
1050 * retrieving the current end-of-file offset prior to each
1051 * write operation, we'll assume that most append operations
1052 * will continuously write, so we'll just set the offset to
1053 * the end of the file now and hope that's adequate.
1055 * Note to self: If this proves inadequate, and O_APPEND
1056 * should, in some cases, be forced for each write, add a
1057 * field in the context options structure, for
1058 * "strict_append_mode" which would select between the current
1059 * behavior (if FALSE) or issuing a getattrE() prior to each
1060 * write and forcing the write to the end of the file (if
1061 * TRUE). Adding that capability will likely require adding
1062 * an "append" flag into the _SMBCFILE structure to track
1063 * whether a file was opened in O_APPEND mode. -- djl
1065 if (flags & O_APPEND) {
1066 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1067 (void) smbc_close_ctx(context, file);
1077 /* Check if opendir needed ... */
1082 eno = smbc_errno(context, &srv->cli);
1083 file = context->opendir(context, fname);
1084 if (!file) errno = eno;
1089 errno = EINVAL; /* FIXME, correct errno ? */
1095 * Routine to create a file
1098 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1100 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
1103 if (!context || !context->internal ||
1104 !context->internal->_initialized) {
1111 return smbc_open_ctx(context, path, creat_bits, mode);
1115 * Routine to read() a file ...
1118 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1121 fstring server, share, user, password;
1122 pstring path, targetpath;
1123 struct cli_state *targetcli;
1128 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1129 * appears to pass file->offset (which is type off_t) differently than
1130 * a local variable of type off_t. Using local variable "offset" in
1131 * the call to cli_read() instead of file->offset fixes a problem
1132 * retrieving data at an offset greater than 4GB.
1134 off_t offset = file->offset;
1136 if (!context || !context->internal ||
1137 !context->internal->_initialized) {
1144 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1146 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1153 /* Check that the buffer exists ... */
1162 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1163 if (smbc_parse_path(context, file->fname,
1164 server, sizeof(server),
1165 share, sizeof(share),
1168 password, sizeof(password),
1174 /*d_printf(">>>read: resolving %s\n", path);*/
1175 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1177 d_printf("Could not resolve %s\n", path);
1180 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1182 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1186 errno = smbc_errno(context, targetcli);
1191 file->offset += ret;
1193 DEBUG(4, (" --> %d\n", ret));
1195 return ret; /* Success, ret bytes of data ... */
1200 * Routine to write() a file ...
1203 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1206 off_t offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1207 fstring server, share, user, password;
1208 pstring path, targetpath;
1209 struct cli_state *targetcli;
1211 if (!context || !context->internal ||
1212 !context->internal->_initialized) {
1219 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1226 /* Check that the buffer exists ... */
1235 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1236 if (smbc_parse_path(context, file->fname,
1237 server, sizeof(server),
1238 share, sizeof(share),
1241 password, sizeof(password),
1247 /*d_printf(">>>write: resolving %s\n", path);*/
1248 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1250 d_printf("Could not resolve %s\n", path);
1253 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1256 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1260 errno = smbc_errno(context, targetcli);
1265 file->offset += ret;
1267 return ret; /* Success, 0 bytes of data ... */
1271 * Routine to close() a file ...
1274 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1277 fstring server, share, user, password;
1278 pstring path, targetpath;
1279 struct cli_state *targetcli;
1281 if (!context || !context->internal ||
1282 !context->internal->_initialized) {
1289 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1299 return context->closedir(context, file);
1303 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1304 if (smbc_parse_path(context, file->fname,
1305 server, sizeof(server),
1306 share, sizeof(share),
1309 password, sizeof(password),
1315 /*d_printf(">>>close: resolving %s\n", path);*/
1316 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1318 d_printf("Could not resolve %s\n", path);
1321 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1323 if (!cli_close(targetcli, file->cli_fd)) {
1325 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1327 /* Deallocate slot and remove the server
1328 * from the server cache if unused */
1329 errno = smbc_errno(context, targetcli);
1331 DLIST_REMOVE(context->internal->_files, file);
1332 SAFE_FREE(file->fname);
1334 context->callbacks.remove_unused_server_fn(context, srv);
1340 DLIST_REMOVE(context->internal->_files, file);
1341 SAFE_FREE(file->fname);
1348 * Get info from an SMB server on a file. Use a qpathinfo call first
1349 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1351 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1352 uint16 *mode, SMB_OFF_T *size,
1353 time_t *c_time, time_t *a_time, time_t *m_time,
1358 struct cli_state *targetcli;
1359 if (!context || !context->internal ||
1360 !context->internal->_initialized) {
1367 /* path fixup for . and .. */
1368 if (strequal(path, ".") || strequal(path, ".."))
1369 pstrcpy(fixedpath, "\\");
1372 pstrcpy(fixedpath, path);
1373 trim_string(fixedpath, NULL, "\\..");
1374 trim_string(fixedpath, NULL, "\\.");
1376 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1378 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1380 d_printf("Couldn't resolve %s\n", path);
1384 if ( targetcli->dfsroot )
1387 pstrcpy(temppath, targetpath);
1388 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1391 if (!srv->no_pathinfo2 &&
1392 cli_qpathinfo2(targetcli, targetpath, c_time, a_time, m_time, NULL,
1393 size, mode, ino)) return True;
1395 /* if this is NT then don't bother with the getatr */
1396 if (targetcli->capabilities & CAP_NT_SMBS) {
1401 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1402 if (m_time != NULL) {
1403 if (a_time != NULL) *a_time = *m_time;
1404 if (c_time != NULL) *c_time = *m_time;
1406 srv->no_pathinfo2 = True;
1416 * Set file info on an SMB server. Use setpathinfo call first. If that
1417 * fails, use setattrE..
1419 * Access and modification time parameters are always used and must be
1420 * provided. Create time, if zero, will be determined from the actual create
1421 * time of the file. If non-zero, the create time will be set as well.
1423 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1425 static BOOL smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1426 time_t c_time, time_t a_time, time_t m_time,
1433 * Get the create time of the file (if not provided); we'll need it in
1436 if (! srv->no_pathinfo && c_time == 0) {
1437 if (! cli_qpathinfo(&srv->cli, path,
1438 &c_time, NULL, NULL, NULL, NULL)) {
1439 /* qpathinfo not available */
1440 srv->no_pathinfo = True;
1443 * We got a creation time. Some OS versions don't
1444 * return a valid create time, though. If we got an
1445 * invalid time, start with the current time instead.
1447 if (c_time == 0 || c_time == (time_t) -1) {
1448 c_time = time(NULL);
1452 * We got a creation time. For sanity sake, since
1453 * there is no POSIX function to set the create time
1454 * of a file, if the existing create time is greater
1455 * than either of access time or modification time,
1456 * set create time to the smallest of those. This
1457 * ensure that the create time of a file is never
1458 * greater than its last access or modification time.
1460 if (c_time > a_time) c_time = a_time;
1461 if (c_time > m_time) c_time = m_time;
1466 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1467 * modern function for "new code" to be using, and it works given a
1468 * filename rather than requiring that the file be opened to have its
1469 * attributes manipulated.
1471 if (srv->no_pathinfo ||
1472 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1475 * setpathinfo is not supported; go to plan B.
1477 * cli_setatr() does not work on win98, and it also doesn't
1478 * support setting the access time (only the modification
1479 * time), so in all cases, we open the specified file and use
1480 * cli_setattrE() which should work on all OS versions, and
1481 * supports both times.
1484 /* Don't try {q,set}pathinfo() again, with this server */
1485 srv->no_pathinfo = True;
1488 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1490 errno = smbc_errno(context, &srv->cli);
1495 * Get the creat time of the file (if it wasn't provided).
1496 * We'll need it in the set call
1499 ret = cli_getattrE(&srv->cli, fd,
1501 &c_time, NULL, NULL);
1506 /* If we got create time, set times */
1508 /* Some OS versions don't support create time */
1509 if (c_time == 0 || c_time == -1) {
1510 c_time = time(NULL);
1514 * For sanity sake, since there is no POSIX function
1515 * to set the create time of a file, if the existing
1516 * create time is greater than either of access time
1517 * or modification time, set create time to the
1518 * smallest of those. This ensure that the create
1519 * time of a file is never greater than its last
1520 * access or modification time.
1522 if (c_time > a_time) c_time = a_time;
1523 if (c_time > m_time) c_time = m_time;
1525 /* Set the new attributes */
1526 ret = cli_setattrE(&srv->cli, fd,
1527 c_time, a_time, m_time);
1528 cli_close(&srv->cli, fd);
1532 * Unfortunately, setattrE() doesn't have a provision for
1533 * setting the access mode (attributes). We'll have to try
1534 * cli_setatr() for that, and with only this parameter, it
1535 * seems to work on win98.
1537 if (ret && mode != (uint16) -1) {
1538 ret = cli_setatr(&srv->cli, path, mode, 0);
1542 errno = smbc_errno(context, &srv->cli);
1551 * Routine to unlink() a file
1554 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1556 fstring server, share, user, password, workgroup;
1557 pstring path, targetpath;
1558 struct cli_state *targetcli;
1559 SMBCSRV *srv = NULL;
1561 if (!context || !context->internal ||
1562 !context->internal->_initialized) {
1564 errno = EINVAL; /* Best I can think of ... */
1576 if (smbc_parse_path(context, fname,
1577 server, sizeof(server),
1578 share, sizeof(share),
1581 password, sizeof(password),
1587 if (user[0] == (char)0) fstrcpy(user, context->user);
1589 fstrcpy(workgroup, context->workgroup);
1591 srv = smbc_server(context, server, share, workgroup, user, password);
1595 return -1; /* smbc_server sets errno */
1599 /*d_printf(">>>unlink: resolving %s\n", path);*/
1600 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1602 d_printf("Could not resolve %s\n", path);
1605 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1607 if (!cli_unlink(targetcli, targetpath)) {
1609 errno = smbc_errno(context, targetcli);
1611 if (errno == EACCES) { /* Check if the file is a directory */
1616 time_t m_time = 0, a_time = 0, c_time = 0;
1619 if (!smbc_getatr(context, srv, path, &mode, &size,
1620 &c_time, &a_time, &m_time, &ino)) {
1622 /* Hmmm, bad error ... What? */
1624 errno = smbc_errno(context, targetcli);
1630 if (IS_DOS_DIR(mode))
1633 errno = saverr; /* Restore this */
1642 return 0; /* Success ... */
1647 * Routine to rename() a file
1650 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1651 SMBCCTX *ncontext, const char *nname)
1653 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1654 pstring path1, path2, targetpath1, targetpath2;
1655 struct cli_state *targetcli1, *targetcli2;
1656 SMBCSRV *srv = NULL;
1658 if (!ocontext || !ncontext ||
1659 !ocontext->internal || !ncontext->internal ||
1660 !ocontext->internal->_initialized ||
1661 !ncontext->internal->_initialized) {
1663 errno = EINVAL; /* Best I can think of ... */
1668 if (!oname || !nname) {
1675 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1677 smbc_parse_path(ocontext, oname,
1678 server1, sizeof(server1),
1679 share1, sizeof(share1),
1680 path1, sizeof(path1),
1681 user1, sizeof(user1),
1682 password1, sizeof(password1),
1685 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1687 smbc_parse_path(ncontext, nname,
1688 server2, sizeof(server2),
1689 share2, sizeof(share2),
1690 path2, sizeof(path2),
1691 user2, sizeof(user2),
1692 password2, sizeof(password2),
1695 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1697 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1698 strcmp(user1, user2)) {
1700 /* Can't rename across file systems, or users?? */
1707 fstrcpy(workgroup, ocontext->workgroup);
1708 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1709 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1716 /*d_printf(">>>rename: resolving %s\n", path1);*/
1717 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1719 d_printf("Could not resolve %s\n", path1);
1722 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1723 /*d_printf(">>>rename: resolving %s\n", path2);*/
1724 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1726 d_printf("Could not resolve %s\n", path2);
1729 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1731 if (strcmp(targetcli1->desthost, targetcli2->desthost) || strcmp(targetcli1->share, targetcli2->share))
1733 /* can't rename across file systems */
1739 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1740 int eno = smbc_errno(ocontext, targetcli1);
1742 if (eno != EEXIST ||
1743 !cli_unlink(targetcli1, targetpath2) ||
1744 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1752 return 0; /* Success */
1757 * A routine to lseek() a file
1760 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1763 fstring server, share, user, password;
1764 pstring path, targetpath;
1765 struct cli_state *targetcli;
1767 if (!context || !context->internal ||
1768 !context->internal->_initialized) {
1775 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1785 return -1; /* Can't lseek a dir ... */
1791 file->offset = offset;
1795 file->offset += offset;
1799 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1800 if (smbc_parse_path(context, file->fname,
1801 server, sizeof(server),
1802 share, sizeof(share),
1805 password, sizeof(password),
1811 /*d_printf(">>>lseek: resolving %s\n", path);*/
1812 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1814 d_printf("Could not resolve %s\n", path);
1817 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1819 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL, &size, NULL, NULL,
1822 SMB_OFF_T b_size = size;
1823 if (!cli_getattrE(targetcli, file->cli_fd, NULL, &b_size, NULL, NULL,
1831 file->offset = size + offset;
1840 return file->offset;
1845 * Generate an inode number from file name for those things that need it
1849 ino_t smbc_inode(SMBCCTX *context, const char *name)
1852 if (!context || !context->internal ||
1853 !context->internal->_initialized) {
1860 if (!*name) return 2; /* FIXME, why 2 ??? */
1861 return (ino_t)str_checksum(name);
1866 * Routine to put basic stat info into a stat structure ... Used by stat and
1871 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname,
1872 SMB_OFF_T size, int mode)
1877 if (IS_DOS_DIR(mode)) {
1878 st->st_mode = SMBC_DIR_MODE;
1880 st->st_mode = SMBC_FILE_MODE;
1883 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1884 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1885 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1886 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1889 #ifdef HAVE_STAT_ST_BLKSIZE
1890 st->st_blksize = 512;
1892 #ifdef HAVE_STAT_ST_BLOCKS
1893 st->st_blocks = (size+511)/512;
1895 st->st_uid = getuid();
1896 st->st_gid = getgid();
1898 if (IS_DOS_DIR(mode)) {
1904 if (st->st_ino == 0) {
1905 st->st_ino = smbc_inode(context, fname);
1908 return True; /* FIXME: Is this needed ? */
1913 * Routine to stat a file given a name
1916 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1919 fstring server, share, user, password, workgroup;
1921 time_t m_time = 0, a_time = 0, c_time = 0;
1926 if (!context || !context->internal ||
1927 !context->internal->_initialized) {
1929 errno = EINVAL; /* Best I can think of ... */
1941 DEBUG(4, ("smbc_stat(%s)\n", fname));
1943 if (smbc_parse_path(context, fname,
1944 server, sizeof(server),
1945 share, sizeof(share),
1948 password, sizeof(password),
1954 if (user[0] == (char)0) fstrcpy(user, context->user);
1956 fstrcpy(workgroup, context->workgroup);
1958 srv = smbc_server(context, server, share, workgroup, user, password);
1961 return -1; /* errno set by smbc_server */
1964 if (!smbc_getatr(context, srv, path, &mode, &size,
1965 &c_time, &a_time, &m_time, &ino)) {
1967 errno = smbc_errno(context, &srv->cli);
1974 smbc_setup_stat(context, st, path, size, mode);
1976 st->st_atime = a_time;
1977 st->st_ctime = c_time;
1978 st->st_mtime = m_time;
1979 st->st_dev = srv->dev;
1986 * Routine to stat a file given an fd
1989 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1991 time_t c_time, a_time, m_time;
1994 fstring server, share, user, password;
1995 pstring path, targetpath;
1996 struct cli_state *targetcli;
1999 if (!context || !context->internal ||
2000 !context->internal->_initialized) {
2007 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2016 return context->fstatdir(context, file, st);
2020 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2021 if (smbc_parse_path(context, file->fname,
2022 server, sizeof(server),
2023 share, sizeof(share),
2026 password, sizeof(password),
2032 /*d_printf(">>>fstat: resolving %s\n", path);*/
2033 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
2035 d_printf("Could not resolve %s\n", path);
2038 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2040 if (!cli_qfileinfo(targetcli, file->cli_fd,
2041 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
2042 if (!cli_getattrE(targetcli, file->cli_fd,
2043 &mode, &size, &c_time, &a_time, &m_time)) {
2052 smbc_setup_stat(context, st, file->fname, size, mode);
2054 st->st_atime = a_time;
2055 st->st_ctime = c_time;
2056 st->st_mtime = m_time;
2057 st->st_dev = file->srv->dev;
2064 * Routine to open a directory
2065 * We accept the URL syntax explained in smbc_parse_path(), above.
2068 static void smbc_remove_dir(SMBCFILE *dir)
2070 struct smbc_dir_list *d,*f;
2077 SAFE_FREE(f->dirent);
2082 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2086 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
2088 struct smbc_dirent *dirent;
2090 int name_length = (name == NULL ? 0 : strlen(name));
2091 int comment_len = (comment == NULL ? 0 : strlen(comment));
2094 * Allocate space for the dirent, which must be increased by the
2095 * size of the name and the comment and 1 each for the null terminator.
2098 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2100 dirent = SMB_MALLOC(size);
2104 dir->dir_error = ENOMEM;
2109 ZERO_STRUCTP(dirent);
2111 if (dir->dir_list == NULL) {
2113 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2114 if (!dir->dir_list) {
2117 dir->dir_error = ENOMEM;
2121 ZERO_STRUCTP(dir->dir_list);
2123 dir->dir_end = dir->dir_next = dir->dir_list;
2127 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2129 if (!dir->dir_end->next) {
2132 dir->dir_error = ENOMEM;
2136 ZERO_STRUCTP(dir->dir_end->next);
2138 dir->dir_end = dir->dir_end->next;
2141 dir->dir_end->next = NULL;
2142 dir->dir_end->dirent = dirent;
2144 dirent->smbc_type = type;
2145 dirent->namelen = name_length;
2146 dirent->commentlen = comment_len;
2147 dirent->dirlen = size;
2149 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2151 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2152 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2159 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
2161 SMBCFILE *dir = (SMBCFILE *)state;
2162 struct smbc_dir_list *dir_list;
2163 struct smbc_dirent *dirent;
2167 dirent_type = dir->dir_type;
2169 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2171 /* An error occurred, what do we do? */
2172 /* FIXME: Add some code here */
2175 /* Point to the one just added */
2176 dirent = dir->dir_end->dirent;
2178 /* See if this was a duplicate */
2179 for (dir_list = dir->dir_list;
2180 dir_list != dir->dir_end;
2181 dir_list = dir_list->next) {
2183 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2184 /* Duplicate. End end of list need to be removed. */
2188 if (do_remove && dir_list->next == dir->dir_end) {
2189 /* Found the end of the list. Remove it. */
2190 dir->dir_end = dir_list;
2191 free(dir_list->next);
2193 dir_list->next = NULL;
2200 list_fn(const char *name, uint32 type, const char *comment, void *state)
2202 SMBCFILE *dir = (SMBCFILE *)state;
2205 /* We need to process the type a little ... */
2207 if (dir->dir_type == SMBC_FILE_SHARE) {
2210 case 0: /* Directory tree */
2211 dirent_type = SMBC_FILE_SHARE;
2215 dirent_type = SMBC_PRINTER_SHARE;
2219 dirent_type = SMBC_COMMS_SHARE;
2223 dirent_type = SMBC_IPC_SHARE;
2227 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2231 else dirent_type = dir->dir_type;
2233 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2235 /* An error occurred, what do we do? */
2236 /* FIXME: Add some code here */
2242 dir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2245 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2246 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2248 /* Handle an error ... */
2250 /* FIXME: Add some code ... */
2256 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
2258 fstring server, share, user, password, options;
2263 SMBCSRV *srv = NULL;
2264 SMBCFILE *dir = NULL;
2265 struct in_addr rem_ip;
2267 if (!context || !context->internal ||
2268 !context->internal->_initialized) {
2269 DEBUG(4, ("no valid context\n"));
2270 errno = EINVAL + 8192;
2276 DEBUG(4, ("no valid fname\n"));
2277 errno = EINVAL + 8193;
2281 if (smbc_parse_path(context, fname,
2282 server, sizeof(server),
2283 share, sizeof(share),
2286 password, sizeof(password),
2287 options, sizeof(options))) {
2288 DEBUG(4, ("no valid path\n"));
2289 errno = EINVAL + 8194;
2293 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
2295 /* Ensure the options are valid */
2296 if (smbc_check_options(server, share, path, options)) {
2297 DEBUG(4, ("unacceptable options (%s)\n", options));
2298 errno = EINVAL + 8195;
2302 if (user[0] == (char)0) fstrcpy(user, context->user);
2304 pstrcpy(workgroup, context->workgroup);
2306 dir = SMB_MALLOC_P(SMBCFILE);
2318 dir->fname = SMB_STRDUP(fname);
2322 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2324 if (server[0] == (char)0) {
2329 struct ip_service *ip_list;
2330 struct ip_service server_addr;
2331 struct user_auth_info u_info;
2332 struct cli_state *cli;
2334 if (share[0] != (char)0 || path[0] != (char)0) {
2336 errno = EINVAL + 8196;
2338 SAFE_FREE(dir->fname);
2344 /* Determine how many local master browsers to query */
2345 max_lmb_count = (context->options.browse_max_lmb_count == 0
2347 : context->options.browse_max_lmb_count);
2349 pstrcpy(u_info.username, user);
2350 pstrcpy(u_info.password, password);
2353 * We have server and share and path empty but options
2354 * requesting that we scan all master browsers for their list
2355 * of workgroups/domains. This implies that we must first try
2356 * broadcast queries to find all master browsers, and if that
2357 * doesn't work, then try our other methods which return only
2358 * a single master browser.
2362 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2366 if (!find_master_ip(workgroup, &server_addr.ip)) {
2372 ip_list = &server_addr;
2376 for (i = 0; i < count && i < max_lmb_count; i++) {
2377 DEBUG(99, ("Found master browser %d of %d: %s\n", i+1, MAX(count, max_lmb_count), inet_ntoa(ip_list[i].ip)));
2379 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2380 /* cli == NULL is the master browser refused to talk or
2381 could not be found */
2385 fstrcpy(server, cli->desthost);
2388 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2391 * For each returned master browser IP address, get a
2392 * connection to IPC$ on the server if we do not
2393 * already have one, and determine the
2394 * workgroups/domains that it knows about.
2397 srv = smbc_server(context, server,
2398 "IPC$", workgroup, user, password);
2404 dir->dir_type = SMBC_WORKGROUP;
2406 /* Now, list the stuff ... */
2408 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2412 SAFE_FREE(dir->fname);
2423 * Server not an empty string ... Check the rest and see what
2426 if (share[0] == (char)0) {
2428 if (path[0] != (char)0) { /* Should not have empty share with path */
2430 errno = EINVAL + 8197;
2432 SAFE_FREE(dir->fname);
2439 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2440 /* However, we check to see if <server> is an IP address first */
2442 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2443 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2444 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2447 dir->dir_type = SMBC_SERVER;
2450 * Get the backup list ...
2454 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2456 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2457 errno = EPERM; /* FIXME, is this correct */
2463 * Get a connection to IPC$ on the server if we do not already have one
2466 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2469 DEBUG(0, ("got no contact to IPC$\n"));
2471 SAFE_FREE(dir->fname);
2480 /* Now, list the servers ... */
2482 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2486 SAFE_FREE(dir->fname);
2495 if (resolve_name(server, &rem_ip, 0x20)) {
2497 /* Now, list the shares ... */
2499 dir->dir_type = SMBC_FILE_SHARE;
2501 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2506 SAFE_FREE(dir->fname);
2515 /* Now, list the servers ... */
2517 if (cli_RNetShareEnum(&srv->cli, list_fn,
2520 errno = cli_errno(&srv->cli);
2522 SAFE_FREE(dir->fname);
2532 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2534 SAFE_FREE(dir->fname);
2544 else { /* The server and share are specified ... work from there ... */
2546 struct cli_state *targetcli;
2548 /* Well, we connect to the server and list the directory */
2550 dir->dir_type = SMBC_FILE_SHARE;
2552 srv = smbc_server(context, server, share, workgroup, user, password);
2557 SAFE_FREE(dir->fname);
2566 /* Now, list the files ... */
2568 p = path + strlen(path);
2569 pstrcat(path, "\\*");
2571 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2573 d_printf("Could not resolve %s\n", path);
2577 if (cli_list(targetcli, targetpath, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2581 SAFE_FREE(dir->fname);
2584 errno = smbc_errno(context, targetcli);
2586 if (errno == EINVAL) {
2588 * See if they asked to opendir something
2589 * other than a directory. If so, the
2590 * converted error value we got would have
2591 * been EINVAL rather than ENOTDIR.
2593 *p = '\0'; /* restore original path */
2595 if (smbc_getatr(context, srv, path,
2599 ! IS_DOS_DIR(mode)) {
2601 /* It is. Correct the error value */
2613 DLIST_ADD(context->internal->_files, dir);
2619 * Routine to close a directory
2622 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2625 if (!context || !context->internal ||
2626 !context->internal->_initialized) {
2633 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2640 smbc_remove_dir(dir); /* Clean it up */
2642 DLIST_REMOVE(context->internal->_files, dir);
2646 SAFE_FREE(dir->fname);
2647 SAFE_FREE(dir); /* Free the space too */
2654 static void smbc_readdir_internal(SMBCCTX * context,
2655 struct smbc_dirent *dest,
2656 struct smbc_dirent *src,
2657 int max_namebuf_len)
2659 if (context->options.urlencode_readdir_entries) {
2661 /* url-encode the name. get back remaining buffer space */
2663 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2665 /* We now know the name length */
2666 dest->namelen = strlen(dest->name);
2668 /* Save the pointer to the beginning of the comment */
2669 dest->comment = dest->name + dest->namelen + 1;
2671 /* Copy the comment */
2672 strncpy(dest->comment, src->comment, max_namebuf_len);
2674 /* Ensure the comment is null terminated */
2675 if (max_namebuf_len > src->commentlen) {
2676 dest->comment[src->commentlen] = '\0';
2678 dest->comment[max_namebuf_len - 1] = '\0';
2681 /* Save other fields */
2682 dest->smbc_type = src->smbc_type;
2683 dest->commentlen = strlen(dest->comment);
2684 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2688 /* No encoding. Just copy the entry as is. */
2689 memcpy(dest, src, src->dirlen);
2690 dest->comment = (char *)(&dest->name + src->namelen + 1);
2696 * Routine to get a directory entry
2699 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2702 struct smbc_dirent *dirp, *dirent;
2704 /* Check that all is ok first ... */
2706 if (!context || !context->internal ||
2707 !context->internal->_initialized) {
2710 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2715 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2718 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2723 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2726 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2731 if (!dir->dir_next) {
2735 dirent = dir->dir_next->dirent;
2743 dirp = (struct smbc_dirent *)context->internal->_dirent;
2744 maxlen = (sizeof(context->internal->_dirent) -
2745 sizeof(struct smbc_dirent));
2747 smbc_readdir_internal(context, dirp, dirent, maxlen);
2749 dir->dir_next = dir->dir_next->next;
2755 * Routine to get directory entries
2758 static int smbc_getdents_ctx(SMBCCTX *context,
2760 struct smbc_dirent *dirp,
2766 char *ndir = (char *)dirp;
2767 struct smbc_dir_list *dirlist;
2769 /* Check that all is ok first ... */
2771 if (!context || !context->internal ||
2772 !context->internal->_initialized) {
2779 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2786 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2794 * Now, retrieve the number of entries that will fit in what was passed
2795 * We have to figure out if the info is in the list, or we need to
2796 * send a request to the server to get the info.
2799 while ((dirlist = dir->dir_next)) {
2800 struct smbc_dirent *dirent;
2802 if (!dirlist->dirent) {
2804 errno = ENOENT; /* Bad error */
2809 /* Do urlencoding of next entry, if so selected */
2810 dirent = (struct smbc_dirent *)context->internal->_dirent;
2811 maxlen = (sizeof(context->internal->_dirent) -
2812 sizeof(struct smbc_dirent));
2813 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
2815 reqd = dirent->dirlen;
2819 if (rem < count) { /* We managed to copy something */
2825 else { /* Nothing copied ... */
2827 errno = EINVAL; /* Not enough space ... */
2834 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2836 ((struct smbc_dirent *)ndir)->comment =
2837 (char *)(&((struct smbc_dirent *)ndir)->name +
2845 dir->dir_next = dirlist = dirlist -> next;
2856 * Routine to create a directory ...
2859 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2862 fstring server, share, user, password, workgroup;
2863 pstring path, targetpath;
2864 struct cli_state *targetcli;
2866 if (!context || !context->internal ||
2867 !context->internal->_initialized) {
2881 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2883 if (smbc_parse_path(context, fname,
2884 server, sizeof(server),
2885 share, sizeof(share),
2888 password, sizeof(password),
2894 if (user[0] == (char)0) fstrcpy(user, context->user);
2896 fstrcpy(workgroup, context->workgroup);
2898 srv = smbc_server(context, server, share, workgroup, user, password);
2902 return -1; /* errno set by smbc_server */
2906 /*d_printf(">>>mkdir: resolving %s\n", path);*/
2907 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2909 d_printf("Could not resolve %s\n", path);
2912 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
2914 if (!cli_mkdir(targetcli, targetpath)) {
2916 errno = smbc_errno(context, targetcli);
2926 * Our list function simply checks to see if a directory is not empty
2929 static int smbc_rmdir_dirempty = True;
2931 static void rmdir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2934 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2935 smbc_rmdir_dirempty = False;
2940 * Routine to remove a directory
2943 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2946 fstring server, share, user, password, workgroup;
2947 pstring path, targetpath;
2948 struct cli_state *targetcli;
2950 if (!context || !context->internal ||
2951 !context->internal->_initialized) {
2965 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2967 if (smbc_parse_path(context, fname,
2968 server, sizeof(server),
2969 share, sizeof(share),
2972 password, sizeof(password),
2979 if (user[0] == (char)0) fstrcpy(user, context->user);
2981 fstrcpy(workgroup, context->workgroup);
2983 srv = smbc_server(context, server, share, workgroup, user, password);
2987 return -1; /* errno set by smbc_server */
2991 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2993 mode = aDIR | aRONLY;
2996 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2998 if (strcmp(path, "\\") == 0) {
3000 mode = aDIR | aRONLY;
3006 smbc_stat_printjob(srv, path, &size, &m_time);
3007 c_time = a_time = m_time;
3012 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3013 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3015 d_printf("Could not resolve %s\n", path);
3018 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3021 if (!cli_rmdir(targetcli, targetpath)) {
3023 errno = smbc_errno(context, targetcli);
3025 if (errno == EACCES) { /* Check if the dir empty or not */
3027 pstring lpath; /* Local storage to avoid buffer overflows */
3029 smbc_rmdir_dirempty = True; /* Make this so ... */
3031 pstrcpy(lpath, targetpath);
3032 pstrcat(lpath, "\\*");
3034 if (cli_list(targetcli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
3037 /* Fix errno to ignore latest error ... */
3039 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
3040 smbc_errno(context, targetcli)));
3045 if (smbc_rmdir_dirempty)
3061 * Routine to return the current directory position
3064 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
3066 off_t ret_val; /* Squash warnings about cast */
3068 if (!context || !context->internal ||
3069 !context->internal->_initialized) {
3076 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3083 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3091 * We return the pointer here as the offset
3093 ret_val = (off_t)(long)dir->dir_next;
3099 * A routine to run down the list and see if the entry is OK
3102 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
3103 struct smbc_dirent *dirent)
3106 /* Run down the list looking for what we want */
3110 struct smbc_dir_list *tmp = list;
3114 if (tmp->dirent == dirent)
3123 return NULL; /* Not found, or an error */
3129 * Routine to seek on a directory
3132 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
3134 long int l_offset = offset; /* Handle problems of size */
3135 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3136 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3138 if (!context || !context->internal ||
3139 !context->internal->_initialized) {
3146 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3153 /* Now, check what we were passed and see if it is OK ... */
3155 if (dirent == NULL) { /* Seek to the begining of the list */
3157 dir->dir_next = dir->dir_list;
3162 /* Now, run down the list and make sure that the entry is OK */
3163 /* This may need to be changed if we change the format of the list */
3165 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3167 errno = EINVAL; /* Bad entry */
3172 dir->dir_next = list_ent;
3179 * Routine to fstat a dir
3182 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
3185 if (!context || !context->internal ||
3186 !context->internal->_initialized) {
3193 /* No code yet ... */
3199 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
3202 fstring server, share, user, password, workgroup;
3206 if (!context || !context->internal ||
3207 !context->internal->_initialized) {
3209 errno = EINVAL; /* Best I can think of ... */
3221 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3223 if (smbc_parse_path(context, fname,
3224 server, sizeof(server),
3225 share, sizeof(share),
3228 password, sizeof(password),
3234 if (user[0] == (char)0) fstrcpy(user, context->user);
3236 fstrcpy(workgroup, context->workgroup);
3238 srv = smbc_server(context, server, share, workgroup, user, password);
3241 return -1; /* errno set by smbc_server */
3246 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3247 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3248 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3249 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3251 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3252 errno = smbc_errno(context, &srv->cli);
3259 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
3262 fstring server, share, user, password, workgroup;
3267 if (!context || !context->internal ||
3268 !context->internal->_initialized) {
3270 errno = EINVAL; /* Best I can think of ... */
3283 a_time = m_time = time(NULL);
3285 a_time = tbuf[0].tv_sec;
3286 m_time = tbuf[1].tv_sec;
3295 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf));
3296 atimebuf[sizeof(atimebuf) - 1] = '\0';
3297 if ((p = strchr(atimebuf, '\n')) != NULL) {
3301 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf));
3302 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3303 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3307 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3308 fname, atimebuf, mtimebuf);
3311 if (smbc_parse_path(context, fname,
3312 server, sizeof(server),
3313 share, sizeof(share),
3316 password, sizeof(password),
3322 if (user[0] == (char)0) fstrcpy(user, context->user);
3324 fstrcpy(workgroup, context->workgroup);
3326 srv = smbc_server(context, server, share, workgroup, user, password);
3329 return -1; /* errno set by smbc_server */
3332 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3333 return -1; /* errno set by smbc_setatr */
3340 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3341 However NT4 gives a "The information may have been modified by a
3342 computer running Windows NT 5.0" if denied ACEs do not appear before
3345 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
3347 if (sec_ace_equal(ace1, ace2))
3350 if (ace1->type != ace2->type)
3351 return ace2->type - ace1->type;
3353 if (sid_compare(&ace1->trustee, &ace2->trustee))
3354 return sid_compare(&ace1->trustee, &ace2->trustee);
3356 if (ace1->flags != ace2->flags)
3357 return ace1->flags - ace2->flags;
3359 if (ace1->info.mask != ace2->info.mask)
3360 return ace1->info.mask - ace2->info.mask;
3362 if (ace1->size != ace2->size)
3363 return ace1->size - ace2->size;
3365 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3369 static void sort_acl(SEC_ACL *the_acl)
3372 if (!the_acl) return;
3374 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
3376 for (i=1;i<the_acl->num_aces;) {
3377 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3379 for (j=i; j<the_acl->num_aces-1; j++) {
3380 the_acl->ace[j] = the_acl->ace[j+1];
3382 the_acl->num_aces--;
3389 /* convert a SID to a string, either numeric or username/group */
3390 static void convert_sid_to_string(struct cli_state *ipc_cli,
3396 char **domains = NULL;
3397 char **names = NULL;
3398 uint32 *types = NULL;
3399 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3400 sid_to_string(str, sid);
3403 return; /* no lookup desired */
3410 /* Ask LSA to convert the sid to a name */
3412 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3413 pol, 1, sid, &domains,
3415 !domains || !domains[0] || !names || !names[0]) {
3421 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3422 domains[0], lp_winbind_separator(),
3426 /* convert a string to a SID, either numeric or username/group */
3427 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
3433 uint32 *types = NULL;
3434 DOM_SID *sids = NULL;
3436 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3443 if (strncmp(str, "S-", 2) == 0) {
3444 return string_to_sid(sid, str);
3451 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3452 pol, 1, &str, &sids,
3458 sid_copy(sid, &sids[0]);
3465 /* parse an ACE in the same format as print_ace() */
3466 static BOOL parse_ace(struct cli_state *ipc_cli,
3475 unsigned atype, aflags, amask;
3478 const struct perm_value *v;
3484 /* These values discovered by inspection */
3485 static const struct perm_value special_values[] = {
3486 { "R", 0x00120089 },
3487 { "W", 0x00120116 },
3488 { "X", 0x001200a0 },
3489 { "D", 0x00010000 },
3490 { "P", 0x00040000 },
3491 { "O", 0x00080000 },
3495 static const struct perm_value standard_values[] = {
3496 { "READ", 0x001200a9 },
3497 { "CHANGE", 0x001301bf },
3498 { "FULL", 0x001f01ff },
3504 p = strchr_m(str,':');
3505 if (!p) return False;
3508 /* Try to parse numeric form */
3510 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3511 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3515 /* Try to parse text form */
3517 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3522 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3526 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3527 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3528 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3529 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3534 /* Only numeric form accepted for flags at present */
3536 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3537 sscanf(tok, "%i", &aflags))) {
3541 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3545 if (strncmp(tok, "0x", 2) == 0) {
3546 if (sscanf(tok, "%i", &amask) != 1) {
3552 for (v = standard_values; v->perm; v++) {
3553 if (strcmp(tok, v->perm) == 0) {
3564 for (v = special_values; v->perm; v++) {
3565 if (v->perm[0] == *p) {
3571 if (!found) return False;
3581 init_sec_ace(ace, &sid, atype, mask, aflags);
3585 /* add an ACE to a list of ACEs in a SEC_ACL */
3586 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3591 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3595 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3596 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3597 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3598 newacl = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3600 (*the_acl) = newacl;
3605 /* parse a ascii version of a security descriptor */
3606 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3607 struct cli_state *ipc_cli,
3612 const char *p = str;
3616 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3620 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3622 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3623 revision = strtol(tok+9, NULL, 16);
3627 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3628 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3630 !convert_string_to_sid(ipc_cli, pol,
3632 owner_sid, tok+6)) {
3633 DEBUG(5, ("Failed to parse owner sid\n"));
3639 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3640 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3642 !convert_string_to_sid(ipc_cli, pol,
3644 owner_sid, tok+7)) {
3645 DEBUG(5, ("Failed to parse owner sid\n"));
3651 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3652 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3654 !convert_string_to_sid(ipc_cli, pol,
3657 DEBUG(5, ("Failed to parse group sid\n"));
3663 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3664 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3666 !convert_string_to_sid(ipc_cli, pol,
3669 DEBUG(5, ("Failed to parse group sid\n"));
3675 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3677 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3678 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3681 if(!add_ace(&dacl, &ace, ctx)) {
3682 DEBUG(5, ("Failed to add ACL %s\n", tok));
3688 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3690 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3691 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3694 if(!add_ace(&dacl, &ace, ctx)) {
3695 DEBUG(5, ("Failed to add ACL %s\n", tok));
3701 DEBUG(5, ("Failed to parse security descriptor\n"));
3705 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3706 owner_sid, grp_sid, NULL, dacl, &sd_size);
3709 SAFE_FREE(owner_sid);
3715 /* Obtain the current dos attributes */
3716 static DOS_ATTR_DESC *dos_attr_query(SMBCCTX *context,
3718 const char *filename,
3721 time_t m_time = 0, a_time = 0, c_time = 0;
3724 SMB_INO_T inode = 0;
3727 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
3733 /* Obtain the DOS attributes */
3734 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
3736 &c_time, &a_time, &m_time, &inode)) {
3738 errno = smbc_errno(context, &srv->cli);
3739 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
3746 ret->a_time = a_time;
3747 ret->c_time = c_time;
3748 ret->m_time = m_time;
3755 /* parse a ascii version of a security descriptor */
3756 static void dos_attr_parse(SMBCCTX *context,
3761 const char *p = str;
3764 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3766 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
3767 dad->mode = strtol(tok+5, NULL, 16);
3771 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
3772 dad->size = (SMB_OFF_T)atof(tok+5);
3776 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
3777 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
3781 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
3782 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
3786 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
3787 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
3791 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
3792 dad->inode = (SMB_INO_T)atof(tok+6);
3798 /*****************************************************
3799 Retrieve the acls for a file.
3800 *******************************************************/
3802 static int cacl_get(SMBCCTX *context, TALLOC_CTX *ctx, SMBCSRV *srv,
3803 struct cli_state *ipc_cli, POLICY_HND *pol,
3804 char *filename, char *attr_name, char *buf, int bufsize)
3815 BOOL exclude_nt_revision = False;
3816 BOOL exclude_nt_owner = False;
3817 BOOL exclude_nt_group = False;
3818 BOOL exclude_nt_acl = False;
3819 BOOL exclude_dos_mode = False;
3820 BOOL exclude_dos_size = False;
3821 BOOL exclude_dos_ctime = False;
3822 BOOL exclude_dos_atime = False;
3823 BOOL exclude_dos_mtime = False;
3824 BOOL exclude_dos_inode = False;
3825 BOOL numeric = True;
3826 BOOL determine_size = (bufsize == 0);
3830 fstring name_sandbox;
3834 time_t m_time = 0, a_time = 0, c_time = 0;
3838 struct cli_state *cli = &srv->cli;
3840 /* Copy name so we can strip off exclusions (if any are specified) */
3841 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
3843 /* Ensure name is null terminated */
3844 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
3846 /* Play in the sandbox */
3847 name = name_sandbox;
3849 /* If there are any exclusions, point to them and mask them from name */
3850 if ((pExclude = strchr(name, '!')) != NULL)
3855 all = (StrnCaseCmp(name, "system.*", 8) == 0);
3856 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
3857 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
3858 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
3859 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
3860 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
3861 numeric = (* (name + strlen(name) - 1) != '+');
3863 /* Look for exclusions from "all" requests */
3864 if (all || all_nt || all_dos) {
3866 /* Exclusions are delimited by '!' */
3867 for (; pExclude != NULL; pExclude = (p == NULL ? NULL : p + 1)) {
3869 /* Find end of this exclusion name */
3870 if ((p = strchr(pExclude, '!')) != NULL)
3875 /* Which exclusion name is this? */
3876 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
3877 exclude_nt_revision = True;
3879 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
3880 exclude_nt_owner = True;
3882 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
3883 exclude_nt_group = True;
3885 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
3886 exclude_nt_acl = True;
3888 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
3889 exclude_dos_mode = True;
3891 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
3892 exclude_dos_size = True;
3894 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
3895 exclude_dos_ctime = True;
3897 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
3898 exclude_dos_atime = True;
3900 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
3901 exclude_dos_mtime = True;
3903 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
3904 exclude_dos_inode = True;
3907 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
3918 * If we are (possibly) talking to an NT or new system and some NT
3919 * attributes have been requested...
3921 if (ipc_cli && (all || some_nt || all_nt_acls)) {
3922 /* Point to the portion after "system.nt_sec_desc." */
3923 name += 19; /* if (all) this will be invalid but unused */
3925 /* ... then obtain any NT attributes which were requested */
3926 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3929 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3930 filename, cli_errstr(cli)));
3935 sd = cli_query_secdesc(cli, fnum, ctx);
3939 ("cacl_get Failed to query old descriptor\n"));
3944 cli_close(cli, fnum);
3946 if (! exclude_nt_revision) {
3947 if (all || all_nt) {
3948 if (determine_size) {
3949 p = talloc_asprintf(ctx,
3958 n = snprintf(buf, bufsize,
3959 "REVISION:%d", sd->revision);
3961 } else if (StrCaseCmp(name, "revision") == 0) {
3962 if (determine_size) {
3963 p = talloc_asprintf(ctx, "%d",
3971 n = snprintf(buf, bufsize, "%d",
3976 if (!determine_size && n > bufsize) {
3985 if (! exclude_nt_owner) {
3986 /* Get owner and group sid */
3987 if (sd->owner_sid) {
3988 convert_sid_to_string(ipc_cli, pol,
3993 fstrcpy(sidstr, "");
3996 if (all || all_nt) {
3997 if (determine_size) {
3998 p = talloc_asprintf(ctx, ",OWNER:%s",
4006 n = snprintf(buf, bufsize,
4007 ",OWNER:%s", sidstr);
4009 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4010 if (determine_size) {
4011 p = talloc_asprintf(ctx, "%s", sidstr);
4018 n = snprintf(buf, bufsize, "%s",
4023 if (!determine_size && n > bufsize) {
4032 if (! exclude_nt_group) {
4034 convert_sid_to_string(ipc_cli, pol,
4038 fstrcpy(sidstr, "");
4041 if (all || all_nt) {
4042 if (determine_size) {
4043 p = talloc_asprintf(ctx, ",GROUP:%s",
4051 n = snprintf(buf, bufsize,
4052 ",GROUP:%s", sidstr);
4054 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4055 if (determine_size) {
4056 p = talloc_asprintf(ctx, "%s", sidstr);
4063 n = snprintf(buf, bufsize, "%s", sidstr);
4067 if (!determine_size && n > bufsize) {
4076 if (! exclude_nt_acl) {
4077 /* Add aces to value buffer */
4078 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4080 SEC_ACE *ace = &sd->dacl->ace[i];
4081 convert_sid_to_string(ipc_cli, pol,
4085 if (all || all_nt) {
4086 if (determine_size) {
4087 p = talloc_asprintf(
4103 ",ACL:%s:%d/%d/0x%08x",
4109 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4110 StrCaseCmp(name + 3, sidstr) == 0) ||
4111 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4112 StrCaseCmp(name + 4, sidstr) == 0)) {
4113 if (determine_size) {
4114 p = talloc_asprintf(
4126 n = snprintf(buf, bufsize,
4132 } else if (all_nt_acls) {
4133 if (determine_size) {
4134 p = talloc_asprintf(
4136 "%s%s:%d/%d/0x%08x",
4148 n = snprintf(buf, bufsize,
4149 "%s%s:%d/%d/0x%08x",
4167 /* Restore name pointer to its original value */
4171 if (all || some_dos) {
4172 /* Point to the portion after "system.dos_attr." */
4173 name += 16; /* if (all) this will be invalid but unused */
4175 /* Obtain the DOS attributes */
4176 if (!smbc_getatr(context, srv, filename, &mode, &size,
4177 &c_time, &a_time, &m_time, &ino)) {
4179 errno = smbc_errno(context, &srv->cli);
4184 if (! exclude_dos_mode) {
4185 if (all || all_dos) {
4186 if (determine_size) {
4187 p = talloc_asprintf(ctx,
4200 n = snprintf(buf, bufsize,
4208 } else if (StrCaseCmp(name, "mode") == 0) {
4209 if (determine_size) {
4210 p = talloc_asprintf(ctx, "0x%x", mode);
4217 n = snprintf(buf, bufsize, "0x%x", mode);
4221 if (!determine_size && n > bufsize) {
4230 if (! exclude_dos_size) {
4231 if (all || all_dos) {
4232 if (determine_size) {
4233 p = talloc_asprintf(
4243 n = snprintf(buf, bufsize,
4247 } else if (StrCaseCmp(name, "size") == 0) {
4248 if (determine_size) {
4249 p = talloc_asprintf(
4259 n = snprintf(buf, bufsize,
4265 if (!determine_size && n > bufsize) {
4274 if (! exclude_dos_ctime) {
4275 if (all || all_dos) {
4276 if (determine_size) {
4277 p = talloc_asprintf(ctx,
4286 n = snprintf(buf, bufsize,
4287 ",C_TIME:%lu", c_time);
4289 } else if (StrCaseCmp(name, "c_time") == 0) {
4290 if (determine_size) {
4291 p = talloc_asprintf(ctx, "%lu", c_time);
4298 n = snprintf(buf, bufsize, "%lu", c_time);
4302 if (!determine_size && n > bufsize) {
4311 if (! exclude_dos_atime) {
4312 if (all || all_dos) {
4313 if (determine_size) {
4314 p = talloc_asprintf(ctx,
4323 n = snprintf(buf, bufsize,
4324 ",A_TIME:%lu", a_time);
4326 } else if (StrCaseCmp(name, "a_time") == 0) {
4327 if (determine_size) {
4328 p = talloc_asprintf(ctx, "%lu", a_time);
4335 n = snprintf(buf, bufsize, "%lu", a_time);
4339 if (!determine_size && n > bufsize) {
4348 if (! exclude_dos_mtime) {
4349 if (all || all_dos) {
4350 if (determine_size) {
4351 p = talloc_asprintf(ctx,
4360 n = snprintf(buf, bufsize,
4361 ",M_TIME:%lu", m_time);
4363 } else if (StrCaseCmp(name, "m_time") == 0) {
4364 if (determine_size) {
4365 p = talloc_asprintf(ctx, "%lu", m_time);
4372 n = snprintf(buf, bufsize, "%lu", m_time);
4376 if (!determine_size && n > bufsize) {
4385 if (! exclude_dos_inode) {
4386 if (all || all_dos) {
4387 if (determine_size) {
4388 p = talloc_asprintf(
4398 n = snprintf(buf, bufsize,
4402 } else if (StrCaseCmp(name, "inode") == 0) {
4403 if (determine_size) {
4404 p = talloc_asprintf(
4414 n = snprintf(buf, bufsize,
4420 if (!determine_size && n > bufsize) {
4429 /* Restore name pointer to its original value */
4442 /*****************************************************
4443 set the ACLs on a file given an ascii description
4444 *******************************************************/
4445 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
4446 struct cli_state *ipc_cli, POLICY_HND *pol,
4447 const char *filename, const char *the_acl,
4448 int mode, int flags)
4452 SEC_DESC *sd = NULL, *old;
4453 SEC_ACL *dacl = NULL;
4454 DOM_SID *owner_sid = NULL;
4455 DOM_SID *grp_sid = NULL;
4460 BOOL numeric = True;
4462 /* the_acl will be null for REMOVE_ALL operations */
4464 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4468 /* if this is to set the entire ACL... */
4469 if (*the_acl == '*') {
4470 /* ... then increment past the first colon */
4474 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4475 CONST_DISCARD(char *, the_acl));
4483 /* The desired access below is the only one I could find that works
4484 with NT4, W2KP and Samba */
4486 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4489 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4490 filename, cli_errstr(cli)));
4495 old = cli_query_secdesc(cli, fnum, ctx);
4498 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4503 cli_close(cli, fnum);
4506 case SMBC_XATTR_MODE_REMOVE_ALL:
4507 old->dacl->num_aces = 0;
4508 SAFE_FREE(old->dacl->ace);
4509 SAFE_FREE(old->dacl);
4514 case SMBC_XATTR_MODE_REMOVE:
4515 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4518 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4519 if (sec_ace_equal(&sd->dacl->ace[i],
4520 &old->dacl->ace[j])) {
4522 for (k=j; k<old->dacl->num_aces-1;k++) {
4523 old->dacl->ace[k] = old->dacl->ace[k+1];
4525 old->dacl->num_aces--;
4526 if (old->dacl->num_aces == 0) {
4527 SAFE_FREE(old->dacl->ace);
4528 SAFE_FREE(old->dacl);
4545 case SMBC_XATTR_MODE_ADD:
4546 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4549 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4550 if (sid_equal(&sd->dacl->ace[i].trustee,
4551 &old->dacl->ace[j].trustee)) {
4552 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4557 old->dacl->ace[j] = sd->dacl->ace[i];
4563 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4569 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4570 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4576 case SMBC_XATTR_MODE_SET:
4578 owner_sid = old->owner_sid;
4579 grp_sid = old->grp_sid;
4583 case SMBC_XATTR_MODE_CHOWN:
4584 owner_sid = sd->owner_sid;
4587 case SMBC_XATTR_MODE_CHGRP:
4588 grp_sid = sd->grp_sid;
4592 /* Denied ACE entries must come before allowed ones */
4593 sort_acl(old->dacl);
4595 /* Create new security descriptor and set it */
4596 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4597 owner_sid, grp_sid, NULL, dacl, &sd_size);
4599 fnum = cli_nt_create(cli, filename,
4600 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4603 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4604 filename, cli_errstr(cli)));
4609 if (!cli_set_secdesc(cli, fnum, sd)) {
4610 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4617 cli_close(cli, fnum);
4627 int smbc_setxattr_ctx(SMBCCTX *context,
4638 fstring server, share, user, password, workgroup;
4644 if (!context || !context->internal ||
4645 !context->internal->_initialized) {
4647 errno = EINVAL; /* Best I can think of ... */
4659 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n", fname, name, (int) size, (const char*)value));
4661 if (smbc_parse_path(context, fname,
4662 server, sizeof(server),
4663 share, sizeof(share),
4666 password, sizeof(password),
4672 if (user[0] == (char)0) fstrcpy(user, context->user);
4674 fstrcpy(workgroup, context->workgroup);
4676 srv = smbc_server(context, server, share, workgroup, user, password);
4678 return -1; /* errno set by smbc_server */
4681 if (! srv->no_nt_session) {
4682 ipc_srv = smbc_attr_server(context, server, share,
4683 workgroup, user, password,
4685 srv->no_nt_session = True;
4690 ctx = talloc_init("smbc_setxattr");
4697 * Are they asking to set the entire set of known attributes?
4699 if (StrCaseCmp(name, "system.*") == 0 ||
4700 StrCaseCmp(name, "system.*+") == 0) {
4703 talloc_asprintf(ctx, "%s:%s", name+7, (const char *) value);
4711 ret = cacl_set(ctx, &srv->cli,
4712 &ipc_srv->cli, &pol, path,
4715 ? SMBC_XATTR_MODE_SET
4716 : SMBC_XATTR_MODE_ADD),
4722 /* get a DOS Attribute Descriptor with current attributes */
4723 dad = dos_attr_query(context, ctx, path, srv);
4725 /* Overwrite old with new, using what was provided */
4726 dos_attr_parse(context, dad, srv, namevalue);
4728 /* Set the new DOS attributes */
4729 if (! smbc_setatr(context, srv, path,
4735 /* cause failure if NT failed too */
4740 /* we only fail if both NT and DOS sets failed */
4741 if (ret < 0 && ! dad) {
4742 ret = -1; /* in case dad was null */
4748 talloc_destroy(ctx);
4753 * Are they asking to set an access control element or to set
4754 * the entire access control list?
4756 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4757 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4758 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4759 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4760 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4764 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4767 ret = -1; /* errno set by smbc_server() */
4769 else if (! namevalue) {
4773 ret = cacl_set(ctx, &srv->cli,
4774 &ipc_srv->cli, &pol, path,
4777 ? SMBC_XATTR_MODE_SET
4778 : SMBC_XATTR_MODE_ADD),
4781 talloc_destroy(ctx);
4786 * Are they asking to set the owner?
4788 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4789 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
4793 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4797 ret = -1; /* errno set by smbc_server() */
4799 else if (! namevalue) {
4803 ret = cacl_set(ctx, &srv->cli,
4804 &ipc_srv->cli, &pol, path,
4805 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4807 talloc_destroy(ctx);
4812 * Are they asking to set the group?
4814 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4815 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
4819 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4822 /* errno set by smbc_server() */
4825 else if (! namevalue) {
4829 ret = cacl_set(ctx, &srv->cli,
4830 &ipc_srv->cli, &pol, path,
4831 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4833 talloc_destroy(ctx);
4838 * Are they asking to set a DOS attribute?
4840 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4841 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4842 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4843 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4844 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
4846 /* get a DOS Attribute Descriptor with current attributes */
4847 dad = dos_attr_query(context, ctx, path, srv);
4850 talloc_asprintf(ctx, "%s:%s", name+16, (const char *) value);
4855 /* Overwrite old with provided new params */
4856 dos_attr_parse(context, dad, srv, namevalue);
4858 /* Set the new DOS attributes */
4859 ret2 = smbc_setatr(context, srv, path,
4865 /* ret2 has True (success) / False (failure) */
4876 talloc_destroy(ctx);
4880 /* Unsupported attribute name */
4881 talloc_destroy(ctx);
4886 int smbc_getxattr_ctx(SMBCCTX *context,
4895 fstring server, share, user, password, workgroup;
4901 if (!context || !context->internal ||
4902 !context->internal->_initialized) {
4904 errno = EINVAL; /* Best I can think of ... */
4916 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
4918 if (smbc_parse_path(context, fname,
4919 server, sizeof(server),
4920 share, sizeof(share),
4923 password, sizeof(password),
4929 if (user[0] == (char)0) fstrcpy(user, context->user);
4931 fstrcpy(workgroup, context->workgroup);
4933 srv = smbc_server(context, server, share, workgroup, user, password);
4935 return -1; /* errno set by smbc_server */
4938 if (! srv->no_nt_session) {
4939 ipc_srv = smbc_attr_server(context, server, share,
4940 workgroup, user, password,
4943 srv->no_nt_session = True;
4949 ctx = talloc_init("smbc:getxattr");
4955 /* Are they requesting a supported attribute? */
4956 if (StrCaseCmp(name, "system.*") == 0 ||
4957 StrnCaseCmp(name, "system.*!", 9) == 0 ||
4958 StrCaseCmp(name, "system.*+") == 0 ||
4959 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
4960 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4961 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
4962 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4963 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
4964 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4965 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4966 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
4967 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4968 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
4969 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4970 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
4971 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4972 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
4973 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4974 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
4975 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4976 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4977 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
4978 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
4981 ret = cacl_get(context, ctx, srv,
4982 ipc_srv == NULL ? NULL : &ipc_srv->cli,
4984 CONST_DISCARD(char *, name),
4985 CONST_DISCARD(char *, value), size);
4986 if (ret < 0 && errno == 0) {
4987 errno = smbc_errno(context, &srv->cli);
4989 talloc_destroy(ctx);
4993 /* Unsupported attribute name */
4994 talloc_destroy(ctx);
5000 int smbc_removexattr_ctx(SMBCCTX *context,
5007 fstring server, share, user, password, workgroup;
5012 if (!context || !context->internal ||
5013 !context->internal->_initialized) {
5015 errno = EINVAL; /* Best I can think of ... */
5027 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5029 if (smbc_parse_path(context, fname,
5030 server, sizeof(server),
5031 share, sizeof(share),
5034 password, sizeof(password),
5040 if (user[0] == (char)0) fstrcpy(user, context->user);
5042 fstrcpy(workgroup, context->workgroup);
5044 srv = smbc_server(context, server, share, workgroup, user, password);
5046 return -1; /* errno set by smbc_server */
5049 if (! srv->no_nt_session) {
5050 ipc_srv = smbc_attr_server(context, server, share,
5051 workgroup, user, password,
5053 srv->no_nt_session = True;
5059 return -1; /* errno set by smbc_attr_server */
5062 ctx = talloc_init("smbc_removexattr");
5068 /* Are they asking to set the entire ACL? */
5069 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5070 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5073 ret = cacl_set(ctx, &srv->cli,
5074 &ipc_srv->cli, &pol, path,
5075 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5076 talloc_destroy(ctx);
5081 * Are they asking to remove one or more spceific security descriptor
5084 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5085 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5086 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5087 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5088 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5089 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5090 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5093 ret = cacl_set(ctx, &srv->cli,
5094 &ipc_srv->cli, &pol, path,
5095 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5096 talloc_destroy(ctx);
5100 /* Unsupported attribute name */
5101 talloc_destroy(ctx);
5106 int smbc_listxattr_ctx(SMBCCTX *context,
5112 * This isn't quite what listxattr() is supposed to do. This returns
5113 * the complete set of attribute names, always, rather than only those
5114 * attribute names which actually exist for a file. Hmmm...
5116 const char supported[] =
5119 "system.nt_sec_desc.revision\0"
5120 "system.nt_sec_desc.owner\0"
5121 "system.nt_sec_desc.owner+\0"
5122 "system.nt_sec_desc.group\0"
5123 "system.nt_sec_desc.group+\0"
5124 "system.nt_sec_desc.acl.*\0"
5125 "system.nt_sec_desc.acl\0"
5126 "system.nt_sec_desc.acl+\0"
5127 "system.nt_sec_desc.*\0"
5128 "system.nt_sec_desc.*+\0"
5129 "system.dos_attr.*\0"
5130 "system.dos_attr.mode\0"
5131 "system.dos_attr.c_time\0"
5132 "system.dos_attr.a_time\0"
5133 "system.dos_attr.m_time\0"
5137 return sizeof(supported);
5140 if (sizeof(supported) > size) {
5145 /* this can't be strcpy() because there are embedded null characters */
5146 memcpy(list, supported, sizeof(supported));
5147 return sizeof(supported);
5152 * Open a print file to be written to by other calls
5155 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
5157 fstring server, share, user, password;
5160 if (!context || !context->internal ||
5161 !context->internal->_initialized) {
5175 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5177 if (smbc_parse_path(context, fname,
5178 server, sizeof(server),
5179 share, sizeof(share),
5182 password, sizeof(password),
5188 /* What if the path is empty, or the file exists? */
5190 return context->open(context, fname, O_WRONLY, 666);
5195 * Routine to print a file on a remote server ...
5197 * We open the file, which we assume to be on a remote server, and then
5198 * copy it to a print file on the share specified by printq.
5201 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
5203 SMBCFILE *fid1, *fid2;
5204 int bytes, saverr, tot_bytes = 0;
5207 if (!c_file || !c_file->internal->_initialized || !c_print ||
5208 !c_print->internal->_initialized) {
5215 if (!fname && !printq) {
5222 /* Try to open the file for reading ... */
5224 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5226 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5227 return -1; /* smbc_open sets errno */
5231 /* Now, try to open the printer file for writing */
5233 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5235 saverr = errno; /* Save errno */
5236 c_file->close_fn(c_file, fid1);
5242 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5246 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5249 c_file->close_fn(c_file, fid1);
5250 c_print->close_fn(c_print, fid2);
5259 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5260 c_print->close_fn(c_print, fid2);
5274 * Routine to list print jobs on a printer share ...
5277 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
5280 fstring server, share, user, password, workgroup;
5283 if (!context || !context->internal ||
5284 !context->internal->_initialized) {
5298 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5300 if (smbc_parse_path(context, fname,
5301 server, sizeof(server),
5302 share, sizeof(share),
5305 password, sizeof(password),
5311 if (user[0] == (char)0) fstrcpy(user, context->user);
5313 fstrcpy(workgroup, context->workgroup);
5315 srv = smbc_server(context, server, share, workgroup, user, password);
5319 return -1; /* errno set by smbc_server */
5323 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
5325 errno = smbc_errno(context, &srv->cli);
5335 * Delete a print job from a remote printer share
5338 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
5341 fstring server, share, user, password, workgroup;
5345 if (!context || !context->internal ||
5346 !context->internal->_initialized) {
5360 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5362 if (smbc_parse_path(context, fname,
5363 server, sizeof(server),
5364 share, sizeof(share),
5367 password, sizeof(password),
5373 if (user[0] == (char)0) fstrcpy(user, context->user);
5375 fstrcpy(workgroup, context->workgroup);
5377 srv = smbc_server(context, server, share, workgroup, user, password);
5381 return -1; /* errno set by smbc_server */
5385 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5388 errno = smbc_errno(context, &srv->cli);
5389 else if (err == ERRnosuchprintjob)
5400 * Get a new empty handle to fill in with your own info
5402 SMBCCTX * smbc_new_context(void)
5406 context = SMB_MALLOC_P(SMBCCTX);
5412 ZERO_STRUCTP(context);
5414 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5415 if (!context->internal) {
5420 ZERO_STRUCTP(context->internal);
5423 /* ADD REASONABLE DEFAULTS */
5425 context->timeout = 20000; /* 20 seconds */
5427 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5428 context->options.urlencode_readdir_entries = False;/* backward compat */
5429 context->options.one_share_per_server = False;/* backward compat */
5431 context->open = smbc_open_ctx;
5432 context->creat = smbc_creat_ctx;
5433 context->read = smbc_read_ctx;
5434 context->write = smbc_write_ctx;
5435 context->close_fn = smbc_close_ctx;
5436 context->unlink = smbc_unlink_ctx;
5437 context->rename = smbc_rename_ctx;
5438 context->lseek = smbc_lseek_ctx;
5439 context->stat = smbc_stat_ctx;
5440 context->fstat = smbc_fstat_ctx;
5441 context->opendir = smbc_opendir_ctx;
5442 context->closedir = smbc_closedir_ctx;
5443 context->readdir = smbc_readdir_ctx;
5444 context->getdents = smbc_getdents_ctx;
5445 context->mkdir = smbc_mkdir_ctx;
5446 context->rmdir = smbc_rmdir_ctx;
5447 context->telldir = smbc_telldir_ctx;
5448 context->lseekdir = smbc_lseekdir_ctx;
5449 context->fstatdir = smbc_fstatdir_ctx;
5450 context->chmod = smbc_chmod_ctx;
5451 context->utimes = smbc_utimes_ctx;
5452 context->setxattr = smbc_setxattr_ctx;
5453 context->getxattr = smbc_getxattr_ctx;
5454 context->removexattr = smbc_removexattr_ctx;
5455 context->listxattr = smbc_listxattr_ctx;
5456 context->open_print_job = smbc_open_print_job_ctx;
5457 context->print_file = smbc_print_file_ctx;
5458 context->list_print_jobs = smbc_list_print_jobs_ctx;
5459 context->unlink_print_job = smbc_unlink_print_job_ctx;
5461 context->callbacks.check_server_fn = smbc_check_server;
5462 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5464 smbc_default_cache_functions(context);
5472 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5473 * and thus you'll be leaking memory if not handled properly.
5476 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
5485 DEBUG(1,("Performing aggressive shutdown.\n"));
5487 f = context->internal->_files;
5489 context->close_fn(context, f);
5492 context->internal->_files = NULL;
5494 /* First try to remove the servers the nice way. */
5495 if (context->callbacks.purge_cached_fn(context)) {
5498 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
5499 s = context->internal->_servers;
5501 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
5502 cli_shutdown(&s->cli);
5503 context->callbacks.remove_cached_srv_fn(context, s);
5505 DLIST_REMOVE(context->internal->_servers, s);
5509 context->internal->_servers = NULL;
5513 /* This is the polite way */
5514 if (context->callbacks.purge_cached_fn(context)) {
5515 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
5519 if (context->internal->_servers) {
5520 DEBUG(1, ("Active servers in context, free_context failed.\n"));
5524 if (context->internal->_files) {
5525 DEBUG(1, ("Active files in context, free_context failed.\n"));
5531 /* Things we have to clean up */
5532 SAFE_FREE(context->workgroup);
5533 SAFE_FREE(context->netbios_name);
5534 SAFE_FREE(context->user);
5536 DEBUG(3, ("Context %p succesfully freed\n", context));
5537 SAFE_FREE(context->internal);
5544 * Initialise the library etc
5546 * We accept a struct containing handle information.
5547 * valid values for info->debug from 0 to 100,
5548 * and insist that info->fn must be non-null.
5550 SMBCCTX * smbc_init_context(SMBCCTX * context)
5554 char *user = NULL, *home = NULL;
5556 if (!context || !context->internal) {
5561 /* Do not initialise the same client twice */
5562 if (context->internal->_initialized) {
5566 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
5573 if (!smbc_initialized) {
5574 /* Do some library wide intialisations the first time we get called */
5575 BOOL conf_loaded = False;
5577 /* Set this to what the user wants */
5578 DEBUGLEVEL = context->debug;
5580 setup_logging( "libsmbclient", True);
5582 /* Here we would open the smb.conf file if needed ... */
5584 load_interfaces(); /* Load the list of interfaces ... */
5586 in_client = True; /* FIXME, make a param */
5588 home = getenv("HOME");
5590 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5591 if (lp_load(conf, True, False, False)) {
5594 DEBUG(5, ("Could not load config file: %s\n",
5601 * Well, if that failed, try the dyn_CONFIGFILE
5602 * Which points to the standard locn, and if that
5603 * fails, silently ignore it and use the internal
5607 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
5608 DEBUG(5, ("Could not load config file: %s\n",
5612 * We loaded the global config file. Now lets
5613 * load user-specific modifications to the
5616 slprintf(conf, sizeof(conf),
5617 "%s/.smb/smb.conf.append", home);
5618 if (!lp_load(conf, True, False, False)) {
5620 ("Could not append config file: "
5627 reopen_logs(); /* Get logging working ... */
5630 * Block SIGPIPE (from lib/util_sock.c: write())
5631 * It is not needed and should not stop execution
5633 BlockSignals(True, SIGPIPE);
5635 /* Done with one-time initialisation */
5636 smbc_initialized = 1;
5640 if (!context->user) {
5642 * FIXME: Is this the best way to get the user info?
5644 user = getenv("USER");
5645 /* walk around as "guest" if no username can be found */
5646 if (!user) context->user = SMB_STRDUP("guest");
5647 else context->user = SMB_STRDUP(user);
5650 if (!context->netbios_name) {
5652 * We try to get our netbios name from the config. If that fails we fall
5653 * back on constructing our netbios name from our hostname etc
5655 if (global_myname()) {
5656 context->netbios_name = SMB_STRDUP(global_myname());
5660 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
5663 context->netbios_name = SMB_MALLOC(17);
5664 if (!context->netbios_name) {
5668 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
5672 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
5674 if (!context->workgroup) {
5675 if (lp_workgroup()) {
5676 context->workgroup = SMB_STRDUP(lp_workgroup());
5679 /* TODO: Think about a decent default workgroup */
5680 context->workgroup = SMB_STRDUP("samba");
5684 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
5686 /* shortest timeout is 1 second */
5687 if (context->timeout > 0 && context->timeout < 1000)
5688 context->timeout = 1000;
5691 * FIXME: Should we check the function pointers here?
5694 context->internal->_initialized = 1;
5700 /* Return the verion of samba, and thus libsmbclient */
5704 return samba_version_string();