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) {
587 /* Look for a cached connection */
588 srv = find_server(context, server, share,
589 workgroup, username, password);
592 * If we found a connection and we're only allowed one share per
595 if (srv && *share != '\0' && context->options.one_share_per_server) {
598 * ... then if there's no current connection to the share,
599 * connect to it. find_server(), or rather the function
600 * pointed to by context->callbacks.get_cached_srv_fn which
601 * was called by find_server(), will have issued a tree
602 * disconnect if the requested share is not the same as the
603 * one that was already connected.
605 if (srv->cli.cnum == (uint16) -1) {
606 /* Ensure we have accurate auth info */
607 context->callbacks.auth_fn(server, share,
608 workgroup, sizeof(fstring),
609 username, sizeof(fstring),
610 password, sizeof(fstring));
612 if (! cli_send_tconX(&srv->cli, share, "?????",
613 password, strlen(password)+1)) {
615 errno = smbc_errno(context, &srv->cli);
616 cli_shutdown(&srv->cli);
617 context->callbacks.remove_cached_srv_fn(context, srv);
621 /* Regenerate the dev value since it's based on both server and share */
623 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
628 /* If we have a connection... */
631 /* ... then we're done here. Give 'em what they came for. */
635 make_nmb_name(&calling, context->netbios_name, 0x0);
636 make_nmb_name(&called , server, 0x20);
638 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
640 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
643 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
647 /* have to open a new connection */
648 if (!cli_initialise(&c)) {
653 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
654 c.use_kerberos = True;
656 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
657 c.fallback_after_kerberos = True;
660 c.timeout = context->timeout;
663 * Force use of port 139 for first try if share is $IPC, empty, or
664 * null, so browse lists can work
666 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
667 port_try_first = 139;
670 port_try_first = 445;
674 c.port = port_try_first;
676 if (!cli_connect(&c, server_n, &ip)) {
678 /* First connection attempt failed. Try alternate port. */
679 c.port = port_try_next;
681 if (!cli_connect(&c, server_n, &ip)) {
688 if (!cli_session_request(&c, &calling, &called)) {
690 if (strcmp(called.name, "*SMBSERVER")) {
691 make_nmb_name(&called , "*SMBSERVER", 0x20);
694 else { /* Try one more time, but ensure we don't loop */
696 /* Only try this if server is an IP address ... */
698 if (is_ipaddress(server) && !tried_reverse) {
700 struct in_addr rem_ip;
702 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
703 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
708 tried_reverse++; /* Yuck */
710 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
711 make_nmb_name(&called, remote_name, 0x20);
722 DEBUG(4,(" session request ok\n"));
724 if (!cli_negprot(&c)) {
730 username_used = username;
732 if (!cli_session_setup(&c, username_used,
733 password, strlen(password),
734 password, strlen(password),
737 /* Failed. Try an anonymous login, if allowed by flags. */
740 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
741 !cli_session_setup(&c, username_used,
752 DEBUG(4,(" session setup ok\n"));
754 if (!cli_send_tconX(&c, share, "?????",
755 password, strlen(password)+1)) {
756 errno = smbc_errno(context, &c);
761 DEBUG(4,(" tconx ok\n"));
764 * Ok, we have got a nice connection
765 * Let's allocate a server structure.
768 srv = SMB_MALLOC_P(SMBCSRV);
776 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
777 srv->no_pathinfo = False;
778 srv->no_pathinfo2 = False;
779 srv->no_nt_session = False;
781 /* now add it to the cache (internal or external) */
782 /* Let the cache function set errno if it wants to */
784 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
785 int saved_errno = errno;
786 DEBUG(3, (" Failed to add server to cache\n"));
794 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
795 server, share, srv));
797 DLIST_ADD(context->internal->_servers, srv);
802 if (!srv) return NULL;
809 * Connect to a server for getting/setting attributes, possibly on an existing
810 * connection. This works similarly to smbc_server().
812 SMBCSRV *smbc_attr_server(SMBCCTX *context,
813 const char *server, const char *share,
815 fstring username, fstring password,
819 struct cli_state *ipc_cli;
820 struct rpc_pipe_client *pipe_hnd;
822 SMBCSRV *ipc_srv=NULL;
825 * See if we've already created this special connection. Reference our
826 * "special" share name '*IPC$', which is an impossible real share name
827 * due to the leading asterisk.
829 ipc_srv = find_server(context, server, "*IPC$",
830 workgroup, username, password);
833 /* We didn't find a cached connection. Get the password */
834 if (*password == '\0') {
835 /* ... then retrieve it now. */
836 context->callbacks.auth_fn(server, share,
837 workgroup, sizeof(fstring),
838 username, sizeof(fstring),
839 password, sizeof(fstring));
843 nt_status = cli_full_connection(&ipc_cli,
844 global_myname(), server,
845 &ip, 0, "IPC$", "?????",
849 if (! NT_STATUS_IS_OK(nt_status)) {
850 DEBUG(1,("cli_full_connection failed! (%s)\n",
851 nt_errstr(nt_status)));
857 pipe_hnd = cli_rpc_pipe_open_noauth(ipc_cli, PI_LSARPC, &nt_status);
859 DEBUG(1, ("cli_nt_session_open fail!\n"));
861 cli_shutdown(ipc_cli);
865 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
866 but NT sends 0x2000000 so we might as well do it too. */
868 nt_status = rpccli_lsa_open_policy(pipe_hnd,
871 GENERIC_EXECUTE_ACCESS,
874 if (!NT_STATUS_IS_OK(nt_status)) {
875 errno = smbc_errno(context, ipc_cli);
876 cli_shutdown(ipc_cli);
881 ipc_srv = SMB_MALLOC_P(SMBCSRV);
884 cli_shutdown(ipc_cli);
888 ZERO_STRUCTP(ipc_srv);
889 ipc_srv->cli = *ipc_cli;
893 /* now add it to the cache (internal or external) */
895 errno = 0; /* let cache function set errno if it likes */
896 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
901 DEBUG(3, (" Failed to add server to cache\n"));
905 cli_shutdown(&ipc_srv->cli);
910 DLIST_ADD(context->internal->_servers, ipc_srv);
917 * Routine to open() a file ...
920 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
922 fstring server, share, user, password, workgroup;
925 struct cli_state *targetcli;
927 SMBCFILE *file = NULL;
930 if (!context || !context->internal ||
931 !context->internal->_initialized) {
933 errno = EINVAL; /* Best I can think of ... */
945 if (smbc_parse_path(context, fname,
946 server, sizeof(server),
947 share, sizeof(share),
950 password, sizeof(password),
956 if (user[0] == (char)0) fstrcpy(user, context->user);
958 fstrcpy(workgroup, context->workgroup);
960 srv = smbc_server(context, server, share, workgroup, user, password);
964 if (errno == EPERM) errno = EACCES;
965 return NULL; /* smbc_server sets errno */
969 /* Hmmm, the test for a directory is suspect here ... FIXME */
971 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
978 file = SMB_MALLOC_P(SMBCFILE);
989 /*d_printf(">>>open: resolving %s\n", path);*/
990 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
992 d_printf("Could not resolve %s\n", path);
995 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
997 if ( targetcli->dfsroot )
1000 pstrcpy(temppath, targetpath);
1001 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1004 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1006 /* Handle the error ... */
1009 errno = smbc_errno(context, targetcli);
1014 /* Fill in file struct */
1017 file->fname = SMB_STRDUP(fname);
1022 DLIST_ADD(context->internal->_files, file);
1025 * If the file was opened in O_APPEND mode, all write
1026 * operations should be appended to the file. To do that,
1027 * though, using this protocol, would require a getattrE()
1028 * call for each and every write, to determine where the end
1029 * of the file is. (There does not appear to be an append flag
1030 * in the protocol.) Rather than add all of that overhead of
1031 * retrieving the current end-of-file offset prior to each
1032 * write operation, we'll assume that most append operations
1033 * will continuously write, so we'll just set the offset to
1034 * the end of the file now and hope that's adequate.
1036 * Note to self: If this proves inadequate, and O_APPEND
1037 * should, in some cases, be forced for each write, add a
1038 * field in the context options structure, for
1039 * "strict_append_mode" which would select between the current
1040 * behavior (if FALSE) or issuing a getattrE() prior to each
1041 * write and forcing the write to the end of the file (if
1042 * TRUE). Adding that capability will likely require adding
1043 * an "append" flag into the _SMBCFILE structure to track
1044 * whether a file was opened in O_APPEND mode. -- djl
1046 if (flags & O_APPEND) {
1047 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1048 (void) smbc_close_ctx(context, file);
1058 /* Check if opendir needed ... */
1063 eno = smbc_errno(context, &srv->cli);
1064 file = context->opendir(context, fname);
1065 if (!file) errno = eno;
1070 errno = EINVAL; /* FIXME, correct errno ? */
1076 * Routine to create a file
1079 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1081 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
1084 if (!context || !context->internal ||
1085 !context->internal->_initialized) {
1092 return smbc_open_ctx(context, path, creat_bits, mode);
1096 * Routine to read() a file ...
1099 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1102 fstring server, share, user, password;
1103 pstring path, targetpath;
1104 struct cli_state *targetcli;
1109 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1110 * appears to pass file->offset (which is type off_t) differently than
1111 * a local variable of type off_t. Using local variable "offset" in
1112 * the call to cli_read() instead of file->offset fixes a problem
1113 * retrieving data at an offset greater than 4GB.
1115 off_t offset = file->offset;
1117 if (!context || !context->internal ||
1118 !context->internal->_initialized) {
1125 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1127 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1134 /* Check that the buffer exists ... */
1143 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1144 if (smbc_parse_path(context, file->fname,
1145 server, sizeof(server),
1146 share, sizeof(share),
1149 password, sizeof(password),
1155 /*d_printf(">>>read: resolving %s\n", path);*/
1156 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1158 d_printf("Could not resolve %s\n", path);
1161 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1163 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1167 errno = smbc_errno(context, targetcli);
1172 file->offset += ret;
1174 DEBUG(4, (" --> %d\n", ret));
1176 return ret; /* Success, ret bytes of data ... */
1181 * Routine to write() a file ...
1184 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1187 off_t offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1188 fstring server, share, user, password;
1189 pstring path, targetpath;
1190 struct cli_state *targetcli;
1192 if (!context || !context->internal ||
1193 !context->internal->_initialized) {
1200 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1207 /* Check that the buffer exists ... */
1216 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1217 if (smbc_parse_path(context, file->fname,
1218 server, sizeof(server),
1219 share, sizeof(share),
1222 password, sizeof(password),
1228 /*d_printf(">>>write: resolving %s\n", path);*/
1229 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1231 d_printf("Could not resolve %s\n", path);
1234 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1237 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1241 errno = smbc_errno(context, targetcli);
1246 file->offset += ret;
1248 return ret; /* Success, 0 bytes of data ... */
1252 * Routine to close() a file ...
1255 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1258 fstring server, share, user, password;
1259 pstring path, targetpath;
1260 struct cli_state *targetcli;
1262 if (!context || !context->internal ||
1263 !context->internal->_initialized) {
1270 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1280 return context->closedir(context, file);
1284 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1285 if (smbc_parse_path(context, file->fname,
1286 server, sizeof(server),
1287 share, sizeof(share),
1290 password, sizeof(password),
1296 /*d_printf(">>>close: resolving %s\n", path);*/
1297 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1299 d_printf("Could not resolve %s\n", path);
1302 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1304 if (!cli_close(targetcli, file->cli_fd)) {
1306 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1308 /* Deallocate slot and remove the server
1309 * from the server cache if unused */
1310 errno = smbc_errno(context, targetcli);
1312 DLIST_REMOVE(context->internal->_files, file);
1313 SAFE_FREE(file->fname);
1315 context->callbacks.remove_unused_server_fn(context, srv);
1321 DLIST_REMOVE(context->internal->_files, file);
1322 SAFE_FREE(file->fname);
1329 * Get info from an SMB server on a file. Use a qpathinfo call first
1330 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1332 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1333 uint16 *mode, SMB_OFF_T *size,
1334 time_t *c_time, time_t *a_time, time_t *m_time,
1339 struct cli_state *targetcli;
1340 if (!context || !context->internal ||
1341 !context->internal->_initialized) {
1348 /* path fixup for . and .. */
1349 if (strequal(path, ".") || strequal(path, ".."))
1350 pstrcpy(fixedpath, "\\");
1353 pstrcpy(fixedpath, path);
1354 trim_string(fixedpath, NULL, "\\..");
1355 trim_string(fixedpath, NULL, "\\.");
1357 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1359 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1361 d_printf("Couldn't resolve %s\n", path);
1365 if ( targetcli->dfsroot )
1368 pstrcpy(temppath, targetpath);
1369 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1372 if (!srv->no_pathinfo2 &&
1373 cli_qpathinfo2(targetcli, targetpath, c_time, a_time, m_time, NULL,
1374 size, mode, ino)) return True;
1376 /* if this is NT then don't bother with the getatr */
1377 if (targetcli->capabilities & CAP_NT_SMBS) {
1382 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1383 if (m_time != NULL) {
1384 if (a_time != NULL) *a_time = *m_time;
1385 if (c_time != NULL) *c_time = *m_time;
1387 srv->no_pathinfo2 = True;
1397 * Set file info on an SMB server. Use setpathinfo call first. If that
1398 * fails, use setattrE..
1400 * Access and modification time parameters are always used and must be
1401 * provided. Create time, if zero, will be determined from the actual create
1402 * time of the file. If non-zero, the create time will be set as well.
1404 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1406 static BOOL smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1407 time_t c_time, time_t a_time, time_t m_time,
1414 * Get the create time of the file (if not provided); we'll need it in
1417 if (! srv->no_pathinfo && c_time == 0) {
1418 if (! cli_qpathinfo(&srv->cli, path,
1419 &c_time, NULL, NULL, NULL, NULL)) {
1420 /* qpathinfo not available */
1421 srv->no_pathinfo = True;
1424 * We got a creation time. Some OS versions don't
1425 * return a valid create time, though. If we got an
1426 * invalid time, start with the current time instead.
1428 if (c_time == 0 || c_time == (time_t) -1) {
1429 c_time = time(NULL);
1433 * We got a creation time. For sanity sake, since
1434 * there is no POSIX function to set the create time
1435 * of a file, if the existing create time is greater
1436 * than either of access time or modification time,
1437 * set create time to the smallest of those. This
1438 * ensure that the create time of a file is never
1439 * greater than its last access or modification time.
1441 if (c_time > a_time) c_time = a_time;
1442 if (c_time > m_time) c_time = m_time;
1447 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1448 * modern function for "new code" to be using, and it works given a
1449 * filename rather than requiring that the file be opened to have its
1450 * attributes manipulated.
1452 if (srv->no_pathinfo ||
1453 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1456 * setpathinfo is not supported; go to plan B.
1458 * cli_setatr() does not work on win98, and it also doesn't
1459 * support setting the access time (only the modification
1460 * time), so in all cases, we open the specified file and use
1461 * cli_setattrE() which should work on all OS versions, and
1462 * supports both times.
1465 /* Don't try {q,set}pathinfo() again, with this server */
1466 srv->no_pathinfo = True;
1469 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1471 errno = smbc_errno(context, &srv->cli);
1476 * Get the creat time of the file (if it wasn't provided).
1477 * We'll need it in the set call
1480 ret = cli_getattrE(&srv->cli, fd,
1482 &c_time, NULL, NULL);
1487 /* If we got create time, set times */
1489 /* Some OS versions don't support create time */
1490 if (c_time == 0 || c_time == -1) {
1491 c_time = time(NULL);
1495 * For sanity sake, since there is no POSIX function
1496 * to set the create time of a file, if the existing
1497 * create time is greater than either of access time
1498 * or modification time, set create time to the
1499 * smallest of those. This ensure that the create
1500 * time of a file is never greater than its last
1501 * access or modification time.
1503 if (c_time > a_time) c_time = a_time;
1504 if (c_time > m_time) c_time = m_time;
1506 /* Set the new attributes */
1507 ret = cli_setattrE(&srv->cli, fd,
1508 c_time, a_time, m_time);
1509 cli_close(&srv->cli, fd);
1513 * Unfortunately, setattrE() doesn't have a provision for
1514 * setting the access mode (attributes). We'll have to try
1515 * cli_setatr() for that, and with only this parameter, it
1516 * seems to work on win98.
1518 if (ret && mode != (uint16) -1) {
1519 ret = cli_setatr(&srv->cli, path, mode, 0);
1523 errno = smbc_errno(context, &srv->cli);
1532 * Routine to unlink() a file
1535 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1537 fstring server, share, user, password, workgroup;
1538 pstring path, targetpath;
1539 struct cli_state *targetcli;
1540 SMBCSRV *srv = NULL;
1542 if (!context || !context->internal ||
1543 !context->internal->_initialized) {
1545 errno = EINVAL; /* Best I can think of ... */
1557 if (smbc_parse_path(context, fname,
1558 server, sizeof(server),
1559 share, sizeof(share),
1562 password, sizeof(password),
1568 if (user[0] == (char)0) fstrcpy(user, context->user);
1570 fstrcpy(workgroup, context->workgroup);
1572 srv = smbc_server(context, server, share, workgroup, user, password);
1576 return -1; /* smbc_server sets errno */
1580 /*d_printf(">>>unlink: resolving %s\n", path);*/
1581 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1583 d_printf("Could not resolve %s\n", path);
1586 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1588 if (!cli_unlink(targetcli, targetpath)) {
1590 errno = smbc_errno(context, targetcli);
1592 if (errno == EACCES) { /* Check if the file is a directory */
1597 time_t m_time = 0, a_time = 0, c_time = 0;
1600 if (!smbc_getatr(context, srv, path, &mode, &size,
1601 &c_time, &a_time, &m_time, &ino)) {
1603 /* Hmmm, bad error ... What? */
1605 errno = smbc_errno(context, targetcli);
1611 if (IS_DOS_DIR(mode))
1614 errno = saverr; /* Restore this */
1623 return 0; /* Success ... */
1628 * Routine to rename() a file
1631 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1632 SMBCCTX *ncontext, const char *nname)
1634 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1635 pstring path1, path2, targetpath1, targetpath2;
1636 struct cli_state *targetcli1, *targetcli2;
1637 SMBCSRV *srv = NULL;
1639 if (!ocontext || !ncontext ||
1640 !ocontext->internal || !ncontext->internal ||
1641 !ocontext->internal->_initialized ||
1642 !ncontext->internal->_initialized) {
1644 errno = EINVAL; /* Best I can think of ... */
1649 if (!oname || !nname) {
1656 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1658 smbc_parse_path(ocontext, oname,
1659 server1, sizeof(server1),
1660 share1, sizeof(share1),
1661 path1, sizeof(path1),
1662 user1, sizeof(user1),
1663 password1, sizeof(password1),
1666 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1668 smbc_parse_path(ncontext, nname,
1669 server2, sizeof(server2),
1670 share2, sizeof(share2),
1671 path2, sizeof(path2),
1672 user2, sizeof(user2),
1673 password2, sizeof(password2),
1676 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1678 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1679 strcmp(user1, user2)) {
1681 /* Can't rename across file systems, or users?? */
1688 fstrcpy(workgroup, ocontext->workgroup);
1689 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1690 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1697 /*d_printf(">>>rename: resolving %s\n", path1);*/
1698 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1700 d_printf("Could not resolve %s\n", path1);
1703 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1704 /*d_printf(">>>rename: resolving %s\n", path2);*/
1705 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1707 d_printf("Could not resolve %s\n", path2);
1710 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1712 if (strcmp(targetcli1->desthost, targetcli2->desthost) || strcmp(targetcli1->share, targetcli2->share))
1714 /* can't rename across file systems */
1720 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1721 int eno = smbc_errno(ocontext, targetcli1);
1723 if (eno != EEXIST ||
1724 !cli_unlink(targetcli1, targetpath2) ||
1725 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1733 return 0; /* Success */
1738 * A routine to lseek() a file
1741 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1744 fstring server, share, user, password;
1745 pstring path, targetpath;
1746 struct cli_state *targetcli;
1748 if (!context || !context->internal ||
1749 !context->internal->_initialized) {
1756 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1766 return -1; /* Can't lseek a dir ... */
1772 file->offset = offset;
1776 file->offset += offset;
1780 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1781 if (smbc_parse_path(context, file->fname,
1782 server, sizeof(server),
1783 share, sizeof(share),
1786 password, sizeof(password),
1792 /*d_printf(">>>lseek: resolving %s\n", path);*/
1793 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1795 d_printf("Could not resolve %s\n", path);
1798 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1800 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL, &size, NULL, NULL,
1803 SMB_OFF_T b_size = size;
1804 if (!cli_getattrE(targetcli, file->cli_fd, NULL, &b_size, NULL, NULL,
1812 file->offset = size + offset;
1821 return file->offset;
1826 * Generate an inode number from file name for those things that need it
1830 ino_t smbc_inode(SMBCCTX *context, const char *name)
1833 if (!context || !context->internal ||
1834 !context->internal->_initialized) {
1841 if (!*name) return 2; /* FIXME, why 2 ??? */
1842 return (ino_t)str_checksum(name);
1847 * Routine to put basic stat info into a stat structure ... Used by stat and
1852 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname,
1853 SMB_OFF_T size, int mode)
1858 if (IS_DOS_DIR(mode)) {
1859 st->st_mode = SMBC_DIR_MODE;
1861 st->st_mode = SMBC_FILE_MODE;
1864 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1865 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1866 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1867 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1870 #ifdef HAVE_STAT_ST_BLKSIZE
1871 st->st_blksize = 512;
1873 #ifdef HAVE_STAT_ST_BLOCKS
1874 st->st_blocks = (size+511)/512;
1876 st->st_uid = getuid();
1877 st->st_gid = getgid();
1879 if (IS_DOS_DIR(mode)) {
1885 if (st->st_ino == 0) {
1886 st->st_ino = smbc_inode(context, fname);
1889 return True; /* FIXME: Is this needed ? */
1894 * Routine to stat a file given a name
1897 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1900 fstring server, share, user, password, workgroup;
1902 time_t m_time = 0, a_time = 0, c_time = 0;
1907 if (!context || !context->internal ||
1908 !context->internal->_initialized) {
1910 errno = EINVAL; /* Best I can think of ... */
1922 DEBUG(4, ("smbc_stat(%s)\n", fname));
1924 if (smbc_parse_path(context, fname,
1925 server, sizeof(server),
1926 share, sizeof(share),
1929 password, sizeof(password),
1935 if (user[0] == (char)0) fstrcpy(user, context->user);
1937 fstrcpy(workgroup, context->workgroup);
1939 srv = smbc_server(context, server, share, workgroup, user, password);
1942 return -1; /* errno set by smbc_server */
1945 if (!smbc_getatr(context, srv, path, &mode, &size,
1946 &c_time, &a_time, &m_time, &ino)) {
1948 errno = smbc_errno(context, &srv->cli);
1955 smbc_setup_stat(context, st, path, size, mode);
1957 st->st_atime = a_time;
1958 st->st_ctime = c_time;
1959 st->st_mtime = m_time;
1960 st->st_dev = srv->dev;
1967 * Routine to stat a file given an fd
1970 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1972 time_t c_time, a_time, m_time;
1975 fstring server, share, user, password;
1976 pstring path, targetpath;
1977 struct cli_state *targetcli;
1980 if (!context || !context->internal ||
1981 !context->internal->_initialized) {
1988 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1997 return context->fstatdir(context, file, st);
2001 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2002 if (smbc_parse_path(context, file->fname,
2003 server, sizeof(server),
2004 share, sizeof(share),
2007 password, sizeof(password),
2013 /*d_printf(">>>fstat: resolving %s\n", path);*/
2014 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
2016 d_printf("Could not resolve %s\n", path);
2019 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2021 if (!cli_qfileinfo(targetcli, file->cli_fd,
2022 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
2023 if (!cli_getattrE(targetcli, file->cli_fd,
2024 &mode, &size, &c_time, &a_time, &m_time)) {
2033 smbc_setup_stat(context, st, file->fname, size, mode);
2035 st->st_atime = a_time;
2036 st->st_ctime = c_time;
2037 st->st_mtime = m_time;
2038 st->st_dev = file->srv->dev;
2045 * Routine to open a directory
2046 * We accept the URL syntax explained in smbc_parse_path(), above.
2049 static void smbc_remove_dir(SMBCFILE *dir)
2051 struct smbc_dir_list *d,*f;
2058 SAFE_FREE(f->dirent);
2063 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2067 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
2069 struct smbc_dirent *dirent;
2071 int name_length = (name == NULL ? 0 : strlen(name));
2072 int comment_len = (comment == NULL ? 0 : strlen(comment));
2075 * Allocate space for the dirent, which must be increased by the
2076 * size of the name and the comment and 1 each for the null terminator.
2079 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2081 dirent = SMB_MALLOC(size);
2085 dir->dir_error = ENOMEM;
2090 ZERO_STRUCTP(dirent);
2092 if (dir->dir_list == NULL) {
2094 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2095 if (!dir->dir_list) {
2098 dir->dir_error = ENOMEM;
2102 ZERO_STRUCTP(dir->dir_list);
2104 dir->dir_end = dir->dir_next = dir->dir_list;
2108 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2110 if (!dir->dir_end->next) {
2113 dir->dir_error = ENOMEM;
2117 ZERO_STRUCTP(dir->dir_end->next);
2119 dir->dir_end = dir->dir_end->next;
2122 dir->dir_end->next = NULL;
2123 dir->dir_end->dirent = dirent;
2125 dirent->smbc_type = type;
2126 dirent->namelen = name_length;
2127 dirent->commentlen = comment_len;
2128 dirent->dirlen = size;
2130 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2132 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2133 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2140 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
2142 SMBCFILE *dir = (SMBCFILE *)state;
2143 struct smbc_dir_list *dir_list;
2144 struct smbc_dirent *dirent;
2148 dirent_type = dir->dir_type;
2150 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2152 /* An error occurred, what do we do? */
2153 /* FIXME: Add some code here */
2156 /* Point to the one just added */
2157 dirent = dir->dir_end->dirent;
2159 /* See if this was a duplicate */
2160 for (dir_list = dir->dir_list;
2161 dir_list != dir->dir_end;
2162 dir_list = dir_list->next) {
2164 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2165 /* Duplicate. End end of list need to be removed. */
2169 if (do_remove && dir_list->next == dir->dir_end) {
2170 /* Found the end of the list. Remove it. */
2171 dir->dir_end = dir_list;
2172 free(dir_list->next);
2174 dir_list->next = NULL;
2181 list_fn(const char *name, uint32 type, const char *comment, void *state)
2183 SMBCFILE *dir = (SMBCFILE *)state;
2186 /* We need to process the type a little ... */
2188 if (dir->dir_type == SMBC_FILE_SHARE) {
2191 case 0: /* Directory tree */
2192 dirent_type = SMBC_FILE_SHARE;
2196 dirent_type = SMBC_PRINTER_SHARE;
2200 dirent_type = SMBC_COMMS_SHARE;
2204 dirent_type = SMBC_IPC_SHARE;
2208 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2212 else dirent_type = dir->dir_type;
2214 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2216 /* An error occurred, what do we do? */
2217 /* FIXME: Add some code here */
2223 dir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2226 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2227 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2229 /* Handle an error ... */
2231 /* FIXME: Add some code ... */
2237 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
2239 fstring server, share, user, password, options;
2244 SMBCSRV *srv = NULL;
2245 SMBCFILE *dir = NULL;
2246 struct in_addr rem_ip;
2248 if (!context || !context->internal ||
2249 !context->internal->_initialized) {
2250 DEBUG(4, ("no valid context\n"));
2251 errno = EINVAL + 8192;
2257 DEBUG(4, ("no valid fname\n"));
2258 errno = EINVAL + 8193;
2262 if (smbc_parse_path(context, fname,
2263 server, sizeof(server),
2264 share, sizeof(share),
2267 password, sizeof(password),
2268 options, sizeof(options))) {
2269 DEBUG(4, ("no valid path\n"));
2270 errno = EINVAL + 8194;
2274 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
2276 /* Ensure the options are valid */
2277 if (smbc_check_options(server, share, path, options)) {
2278 DEBUG(4, ("unacceptable options (%s)\n", options));
2279 errno = EINVAL + 8195;
2283 if (user[0] == (char)0) fstrcpy(user, context->user);
2285 pstrcpy(workgroup, context->workgroup);
2287 dir = SMB_MALLOC_P(SMBCFILE);
2299 dir->fname = SMB_STRDUP(fname);
2303 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2305 if (server[0] == (char)0) {
2310 struct ip_service *ip_list;
2311 struct ip_service server_addr;
2312 struct user_auth_info u_info;
2313 struct cli_state *cli;
2315 if (share[0] != (char)0 || path[0] != (char)0) {
2317 errno = EINVAL + 8196;
2319 SAFE_FREE(dir->fname);
2325 /* Determine how many local master browsers to query */
2326 max_lmb_count = (context->options.browse_max_lmb_count == 0
2328 : context->options.browse_max_lmb_count);
2330 pstrcpy(u_info.username, user);
2331 pstrcpy(u_info.password, password);
2334 * We have server and share and path empty but options
2335 * requesting that we scan all master browsers for their list
2336 * of workgroups/domains. This implies that we must first try
2337 * broadcast queries to find all master browsers, and if that
2338 * doesn't work, then try our other methods which return only
2339 * a single master browser.
2343 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2347 if (!find_master_ip(workgroup, &server_addr.ip)) {
2353 ip_list = &server_addr;
2357 for (i = 0; i < count && i < max_lmb_count; i++) {
2358 DEBUG(99, ("Found master browser %d of %d: %s\n", i+1, MAX(count, max_lmb_count), inet_ntoa(ip_list[i].ip)));
2360 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2361 /* cli == NULL is the master browser refused to talk or
2362 could not be found */
2366 fstrcpy(server, cli->desthost);
2369 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2372 * For each returned master browser IP address, get a
2373 * connection to IPC$ on the server if we do not
2374 * already have one, and determine the
2375 * workgroups/domains that it knows about.
2378 srv = smbc_server(context, server,
2379 "IPC$", workgroup, user, password);
2385 dir->dir_type = SMBC_WORKGROUP;
2387 /* Now, list the stuff ... */
2389 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2393 SAFE_FREE(dir->fname);
2404 * Server not an empty string ... Check the rest and see what
2407 if (share[0] == (char)0) {
2409 if (path[0] != (char)0) { /* Should not have empty share with path */
2411 errno = EINVAL + 8197;
2413 SAFE_FREE(dir->fname);
2420 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2421 /* However, we check to see if <server> is an IP address first */
2423 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2424 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2425 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2428 dir->dir_type = SMBC_SERVER;
2431 * Get the backup list ...
2435 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2437 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2438 errno = EPERM; /* FIXME, is this correct */
2444 * Get a connection to IPC$ on the server if we do not already have one
2447 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2450 DEBUG(0, ("got no contact to IPC$\n"));
2452 SAFE_FREE(dir->fname);
2461 /* Now, list the servers ... */
2463 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2467 SAFE_FREE(dir->fname);
2476 if (resolve_name(server, &rem_ip, 0x20)) {
2478 /* Now, list the shares ... */
2480 dir->dir_type = SMBC_FILE_SHARE;
2482 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2487 SAFE_FREE(dir->fname);
2496 /* Now, list the servers ... */
2498 if (cli_RNetShareEnum(&srv->cli, list_fn,
2501 errno = cli_errno(&srv->cli);
2503 SAFE_FREE(dir->fname);
2513 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2515 SAFE_FREE(dir->fname);
2525 else { /* The server and share are specified ... work from there ... */
2527 struct cli_state *targetcli;
2529 /* Well, we connect to the server and list the directory */
2531 dir->dir_type = SMBC_FILE_SHARE;
2533 srv = smbc_server(context, server, share, workgroup, user, password);
2538 SAFE_FREE(dir->fname);
2547 /* Now, list the files ... */
2549 p = path + strlen(path);
2550 pstrcat(path, "\\*");
2552 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2554 d_printf("Could not resolve %s\n", path);
2558 if (cli_list(targetcli, targetpath, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2562 SAFE_FREE(dir->fname);
2565 errno = smbc_errno(context, targetcli);
2567 if (errno == EINVAL) {
2569 * See if they asked to opendir something
2570 * other than a directory. If so, the
2571 * converted error value we got would have
2572 * been EINVAL rather than ENOTDIR.
2574 *p = '\0'; /* restore original path */
2576 if (smbc_getatr(context, srv, path,
2580 ! IS_DOS_DIR(mode)) {
2582 /* It is. Correct the error value */
2594 DLIST_ADD(context->internal->_files, dir);
2600 * Routine to close a directory
2603 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2606 if (!context || !context->internal ||
2607 !context->internal->_initialized) {
2614 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2621 smbc_remove_dir(dir); /* Clean it up */
2623 DLIST_REMOVE(context->internal->_files, dir);
2627 SAFE_FREE(dir->fname);
2628 SAFE_FREE(dir); /* Free the space too */
2635 static void smbc_readdir_internal(SMBCCTX * context,
2636 struct smbc_dirent *dest,
2637 struct smbc_dirent *src,
2638 int max_namebuf_len)
2640 if (context->options.urlencode_readdir_entries) {
2642 /* url-encode the name. get back remaining buffer space */
2644 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2646 /* We now know the name length */
2647 dest->namelen = strlen(dest->name);
2649 /* Save the pointer to the beginning of the comment */
2650 dest->comment = dest->name + dest->namelen + 1;
2652 /* Copy the comment */
2653 strncpy(dest->comment, src->comment, max_namebuf_len);
2655 /* Ensure the comment is null terminated */
2656 if (max_namebuf_len > src->commentlen) {
2657 dest->comment[src->commentlen] = '\0';
2659 dest->comment[max_namebuf_len - 1] = '\0';
2662 /* Save other fields */
2663 dest->smbc_type = src->smbc_type;
2664 dest->commentlen = strlen(dest->comment);
2665 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2669 /* No encoding. Just copy the entry as is. */
2670 memcpy(dest, src, src->dirlen);
2671 dest->comment = (char *)(&dest->name + src->namelen + 1);
2677 * Routine to get a directory entry
2680 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2683 struct smbc_dirent *dirp, *dirent;
2685 /* Check that all is ok first ... */
2687 if (!context || !context->internal ||
2688 !context->internal->_initialized) {
2691 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2696 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2699 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2704 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2707 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2712 if (!dir->dir_next) {
2716 dirent = dir->dir_next->dirent;
2724 dirp = (struct smbc_dirent *)context->internal->_dirent;
2725 maxlen = (sizeof(context->internal->_dirent) -
2726 sizeof(struct smbc_dirent));
2728 smbc_readdir_internal(context, dirp, dirent, maxlen);
2730 dir->dir_next = dir->dir_next->next;
2736 * Routine to get directory entries
2739 static int smbc_getdents_ctx(SMBCCTX *context,
2741 struct smbc_dirent *dirp,
2747 char *ndir = (char *)dirp;
2748 struct smbc_dir_list *dirlist;
2750 /* Check that all is ok first ... */
2752 if (!context || !context->internal ||
2753 !context->internal->_initialized) {
2760 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2767 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2775 * Now, retrieve the number of entries that will fit in what was passed
2776 * We have to figure out if the info is in the list, or we need to
2777 * send a request to the server to get the info.
2780 while ((dirlist = dir->dir_next)) {
2781 struct smbc_dirent *dirent;
2783 if (!dirlist->dirent) {
2785 errno = ENOENT; /* Bad error */
2790 /* Do urlencoding of next entry, if so selected */
2791 dirent = (struct smbc_dirent *)context->internal->_dirent;
2792 maxlen = (sizeof(context->internal->_dirent) -
2793 sizeof(struct smbc_dirent));
2794 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
2796 reqd = dirent->dirlen;
2800 if (rem < count) { /* We managed to copy something */
2806 else { /* Nothing copied ... */
2808 errno = EINVAL; /* Not enough space ... */
2815 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2817 ((struct smbc_dirent *)ndir)->comment =
2818 (char *)(&((struct smbc_dirent *)ndir)->name +
2826 dir->dir_next = dirlist = dirlist -> next;
2837 * Routine to create a directory ...
2840 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2843 fstring server, share, user, password, workgroup;
2844 pstring path, targetpath;
2845 struct cli_state *targetcli;
2847 if (!context || !context->internal ||
2848 !context->internal->_initialized) {
2862 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2864 if (smbc_parse_path(context, fname,
2865 server, sizeof(server),
2866 share, sizeof(share),
2869 password, sizeof(password),
2875 if (user[0] == (char)0) fstrcpy(user, context->user);
2877 fstrcpy(workgroup, context->workgroup);
2879 srv = smbc_server(context, server, share, workgroup, user, password);
2883 return -1; /* errno set by smbc_server */
2887 /*d_printf(">>>mkdir: resolving %s\n", path);*/
2888 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2890 d_printf("Could not resolve %s\n", path);
2893 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
2895 if (!cli_mkdir(targetcli, targetpath)) {
2897 errno = smbc_errno(context, targetcli);
2907 * Our list function simply checks to see if a directory is not empty
2910 static int smbc_rmdir_dirempty = True;
2912 static void rmdir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2915 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2916 smbc_rmdir_dirempty = False;
2921 * Routine to remove a directory
2924 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2927 fstring server, share, user, password, workgroup;
2928 pstring path, targetpath;
2929 struct cli_state *targetcli;
2931 if (!context || !context->internal ||
2932 !context->internal->_initialized) {
2946 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2948 if (smbc_parse_path(context, fname,
2949 server, sizeof(server),
2950 share, sizeof(share),
2953 password, sizeof(password),
2960 if (user[0] == (char)0) fstrcpy(user, context->user);
2962 fstrcpy(workgroup, context->workgroup);
2964 srv = smbc_server(context, server, share, workgroup, user, password);
2968 return -1; /* errno set by smbc_server */
2972 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2974 mode = aDIR | aRONLY;
2977 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2979 if (strcmp(path, "\\") == 0) {
2981 mode = aDIR | aRONLY;
2987 smbc_stat_printjob(srv, path, &size, &m_time);
2988 c_time = a_time = m_time;
2993 /*d_printf(">>>rmdir: resolving %s\n", path);*/
2994 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2996 d_printf("Could not resolve %s\n", path);
2999 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3002 if (!cli_rmdir(targetcli, targetpath)) {
3004 errno = smbc_errno(context, targetcli);
3006 if (errno == EACCES) { /* Check if the dir empty or not */
3008 pstring lpath; /* Local storage to avoid buffer overflows */
3010 smbc_rmdir_dirempty = True; /* Make this so ... */
3012 pstrcpy(lpath, targetpath);
3013 pstrcat(lpath, "\\*");
3015 if (cli_list(targetcli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
3018 /* Fix errno to ignore latest error ... */
3020 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
3021 smbc_errno(context, targetcli)));
3026 if (smbc_rmdir_dirempty)
3042 * Routine to return the current directory position
3045 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
3047 off_t ret_val; /* Squash warnings about cast */
3049 if (!context || !context->internal ||
3050 !context->internal->_initialized) {
3057 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3064 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3072 * We return the pointer here as the offset
3074 ret_val = (off_t)(long)dir->dir_next;
3080 * A routine to run down the list and see if the entry is OK
3083 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
3084 struct smbc_dirent *dirent)
3087 /* Run down the list looking for what we want */
3091 struct smbc_dir_list *tmp = list;
3095 if (tmp->dirent == dirent)
3104 return NULL; /* Not found, or an error */
3110 * Routine to seek on a directory
3113 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
3115 long int l_offset = offset; /* Handle problems of size */
3116 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3117 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3119 if (!context || !context->internal ||
3120 !context->internal->_initialized) {
3127 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3134 /* Now, check what we were passed and see if it is OK ... */
3136 if (dirent == NULL) { /* Seek to the begining of the list */
3138 dir->dir_next = dir->dir_list;
3143 /* Now, run down the list and make sure that the entry is OK */
3144 /* This may need to be changed if we change the format of the list */
3146 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3148 errno = EINVAL; /* Bad entry */
3153 dir->dir_next = list_ent;
3160 * Routine to fstat a dir
3163 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
3166 if (!context || !context->internal ||
3167 !context->internal->_initialized) {
3174 /* No code yet ... */
3180 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
3183 fstring server, share, user, password, workgroup;
3187 if (!context || !context->internal ||
3188 !context->internal->_initialized) {
3190 errno = EINVAL; /* Best I can think of ... */
3202 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3204 if (smbc_parse_path(context, fname,
3205 server, sizeof(server),
3206 share, sizeof(share),
3209 password, sizeof(password),
3215 if (user[0] == (char)0) fstrcpy(user, context->user);
3217 fstrcpy(workgroup, context->workgroup);
3219 srv = smbc_server(context, server, share, workgroup, user, password);
3222 return -1; /* errno set by smbc_server */
3227 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3228 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3229 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3230 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3232 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3233 errno = smbc_errno(context, &srv->cli);
3240 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
3243 fstring server, share, user, password, workgroup;
3248 if (!context || !context->internal ||
3249 !context->internal->_initialized) {
3251 errno = EINVAL; /* Best I can think of ... */
3264 a_time = m_time = time(NULL);
3266 a_time = tbuf[0].tv_sec;
3267 m_time = tbuf[1].tv_sec;
3276 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf));
3277 atimebuf[sizeof(atimebuf) - 1] = '\0';
3278 if ((p = strchr(atimebuf, '\n')) != NULL) {
3282 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf));
3283 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3284 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3288 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3289 fname, atimebuf, mtimebuf);
3292 if (smbc_parse_path(context, fname,
3293 server, sizeof(server),
3294 share, sizeof(share),
3297 password, sizeof(password),
3303 if (user[0] == (char)0) fstrcpy(user, context->user);
3305 fstrcpy(workgroup, context->workgroup);
3307 srv = smbc_server(context, server, share, workgroup, user, password);
3310 return -1; /* errno set by smbc_server */
3313 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3314 return -1; /* errno set by smbc_setatr */
3321 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3322 However NT4 gives a "The information may have been modified by a
3323 computer running Windows NT 5.0" if denied ACEs do not appear before
3326 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
3328 if (sec_ace_equal(ace1, ace2))
3331 if (ace1->type != ace2->type)
3332 return ace2->type - ace1->type;
3334 if (sid_compare(&ace1->trustee, &ace2->trustee))
3335 return sid_compare(&ace1->trustee, &ace2->trustee);
3337 if (ace1->flags != ace2->flags)
3338 return ace1->flags - ace2->flags;
3340 if (ace1->info.mask != ace2->info.mask)
3341 return ace1->info.mask - ace2->info.mask;
3343 if (ace1->size != ace2->size)
3344 return ace1->size - ace2->size;
3346 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3350 static void sort_acl(SEC_ACL *the_acl)
3353 if (!the_acl) return;
3355 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
3357 for (i=1;i<the_acl->num_aces;) {
3358 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3360 for (j=i; j<the_acl->num_aces-1; j++) {
3361 the_acl->ace[j] = the_acl->ace[j+1];
3363 the_acl->num_aces--;
3370 /* convert a SID to a string, either numeric or username/group */
3371 static void convert_sid_to_string(struct cli_state *ipc_cli,
3377 char **domains = NULL;
3378 char **names = NULL;
3379 uint32 *types = NULL;
3380 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3381 sid_to_string(str, sid);
3384 return; /* no lookup desired */
3391 /* Ask LSA to convert the sid to a name */
3393 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3394 pol, 1, sid, &domains,
3396 !domains || !domains[0] || !names || !names[0]) {
3402 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3403 domains[0], lp_winbind_separator(),
3407 /* convert a string to a SID, either numeric or username/group */
3408 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
3414 uint32 *types = NULL;
3415 DOM_SID *sids = NULL;
3417 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3424 if (strncmp(str, "S-", 2) == 0) {
3425 return string_to_sid(sid, str);
3432 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3433 pol, 1, &str, &sids,
3439 sid_copy(sid, &sids[0]);
3446 /* parse an ACE in the same format as print_ace() */
3447 static BOOL parse_ace(struct cli_state *ipc_cli,
3456 unsigned atype, aflags, amask;
3459 const struct perm_value *v;
3465 /* These values discovered by inspection */
3466 static const struct perm_value special_values[] = {
3467 { "R", 0x00120089 },
3468 { "W", 0x00120116 },
3469 { "X", 0x001200a0 },
3470 { "D", 0x00010000 },
3471 { "P", 0x00040000 },
3472 { "O", 0x00080000 },
3476 static const struct perm_value standard_values[] = {
3477 { "READ", 0x001200a9 },
3478 { "CHANGE", 0x001301bf },
3479 { "FULL", 0x001f01ff },
3485 p = strchr_m(str,':');
3486 if (!p) return False;
3489 /* Try to parse numeric form */
3491 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3492 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3496 /* Try to parse text form */
3498 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3503 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3507 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3508 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3509 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3510 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3515 /* Only numeric form accepted for flags at present */
3517 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3518 sscanf(tok, "%i", &aflags))) {
3522 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3526 if (strncmp(tok, "0x", 2) == 0) {
3527 if (sscanf(tok, "%i", &amask) != 1) {
3533 for (v = standard_values; v->perm; v++) {
3534 if (strcmp(tok, v->perm) == 0) {
3545 for (v = special_values; v->perm; v++) {
3546 if (v->perm[0] == *p) {
3552 if (!found) return False;
3562 init_sec_ace(ace, &sid, atype, mask, aflags);
3566 /* add an ACE to a list of ACEs in a SEC_ACL */
3567 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3572 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3576 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3577 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3578 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3579 newacl = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3581 (*the_acl) = newacl;
3586 /* parse a ascii version of a security descriptor */
3587 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3588 struct cli_state *ipc_cli,
3593 const char *p = str;
3597 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3601 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3603 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3604 revision = strtol(tok+9, NULL, 16);
3608 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3609 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3611 !convert_string_to_sid(ipc_cli, pol,
3613 owner_sid, tok+6)) {
3614 DEBUG(5, ("Failed to parse owner sid\n"));
3620 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3621 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3623 !convert_string_to_sid(ipc_cli, pol,
3625 owner_sid, tok+7)) {
3626 DEBUG(5, ("Failed to parse owner sid\n"));
3632 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3633 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3635 !convert_string_to_sid(ipc_cli, pol,
3638 DEBUG(5, ("Failed to parse group sid\n"));
3644 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3645 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3647 !convert_string_to_sid(ipc_cli, pol,
3650 DEBUG(5, ("Failed to parse group sid\n"));
3656 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3658 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3659 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3662 if(!add_ace(&dacl, &ace, ctx)) {
3663 DEBUG(5, ("Failed to add ACL %s\n", tok));
3669 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3671 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3672 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3675 if(!add_ace(&dacl, &ace, ctx)) {
3676 DEBUG(5, ("Failed to add ACL %s\n", tok));
3682 DEBUG(5, ("Failed to parse security descriptor\n"));
3686 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3687 owner_sid, grp_sid, NULL, dacl, &sd_size);
3690 SAFE_FREE(owner_sid);
3696 /* Obtain the current dos attributes */
3697 static DOS_ATTR_DESC *dos_attr_query(SMBCCTX *context,
3699 const char *filename,
3702 time_t m_time = 0, a_time = 0, c_time = 0;
3705 SMB_INO_T inode = 0;
3708 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
3714 /* Obtain the DOS attributes */
3715 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
3717 &c_time, &a_time, &m_time, &inode)) {
3719 errno = smbc_errno(context, &srv->cli);
3720 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
3727 ret->a_time = a_time;
3728 ret->c_time = c_time;
3729 ret->m_time = m_time;
3736 /* parse a ascii version of a security descriptor */
3737 static void dos_attr_parse(SMBCCTX *context,
3742 const char *p = str;
3745 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3747 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
3748 dad->mode = strtol(tok+5, NULL, 16);
3752 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
3753 dad->size = (SMB_OFF_T)atof(tok+5);
3757 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
3758 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
3762 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
3763 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
3767 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
3768 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
3772 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
3773 dad->inode = (SMB_INO_T)atof(tok+6);
3779 /*****************************************************
3780 Retrieve the acls for a file.
3781 *******************************************************/
3783 static int cacl_get(SMBCCTX *context, TALLOC_CTX *ctx, SMBCSRV *srv,
3784 struct cli_state *ipc_cli, POLICY_HND *pol,
3785 char *filename, char *attr_name, char *buf, int bufsize)
3796 BOOL exclude_nt_revision = False;
3797 BOOL exclude_nt_owner = False;
3798 BOOL exclude_nt_group = False;
3799 BOOL exclude_nt_acl = False;
3800 BOOL exclude_dos_mode = False;
3801 BOOL exclude_dos_size = False;
3802 BOOL exclude_dos_ctime = False;
3803 BOOL exclude_dos_atime = False;
3804 BOOL exclude_dos_mtime = False;
3805 BOOL exclude_dos_inode = False;
3806 BOOL numeric = True;
3807 BOOL determine_size = (bufsize == 0);
3811 fstring name_sandbox;
3815 time_t m_time = 0, a_time = 0, c_time = 0;
3819 struct cli_state *cli = &srv->cli;
3821 /* Copy name so we can strip off exclusions (if any are specified) */
3822 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
3824 /* Ensure name is null terminated */
3825 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
3827 /* Play in the sandbox */
3828 name = name_sandbox;
3830 /* If there are any exclusions, point to them and mask them from name */
3831 if ((pExclude = strchr(name, '!')) != NULL)
3836 all = (StrnCaseCmp(name, "system.*", 8) == 0);
3837 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
3838 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
3839 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
3840 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
3841 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
3842 numeric = (* (name + strlen(name) - 1) != '+');
3844 /* Look for exclusions from "all" requests */
3845 if (all || all_nt || all_dos) {
3847 /* Exclusions are delimited by '!' */
3848 for (; pExclude != NULL; pExclude = (p == NULL ? NULL : p + 1)) {
3850 /* Find end of this exclusion name */
3851 if ((p = strchr(pExclude, '!')) != NULL)
3856 /* Which exclusion name is this? */
3857 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
3858 exclude_nt_revision = True;
3860 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
3861 exclude_nt_owner = True;
3863 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
3864 exclude_nt_group = True;
3866 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
3867 exclude_nt_acl = True;
3869 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
3870 exclude_dos_mode = True;
3872 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
3873 exclude_dos_size = True;
3875 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
3876 exclude_dos_ctime = True;
3878 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
3879 exclude_dos_atime = True;
3881 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
3882 exclude_dos_mtime = True;
3884 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
3885 exclude_dos_inode = True;
3888 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
3899 * If we are (possibly) talking to an NT or new system and some NT
3900 * attributes have been requested...
3902 if (ipc_cli && (all || some_nt || all_nt_acls)) {
3903 /* Point to the portion after "system.nt_sec_desc." */
3904 name += 19; /* if (all) this will be invalid but unused */
3906 /* ... then obtain any NT attributes which were requested */
3907 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3910 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3911 filename, cli_errstr(cli)));
3916 sd = cli_query_secdesc(cli, fnum, ctx);
3920 ("cacl_get Failed to query old descriptor\n"));
3925 cli_close(cli, fnum);
3927 if (! exclude_nt_revision) {
3928 if (all || all_nt) {
3929 if (determine_size) {
3930 p = talloc_asprintf(ctx,
3939 n = snprintf(buf, bufsize,
3940 "REVISION:%d", sd->revision);
3942 } else if (StrCaseCmp(name, "revision") == 0) {
3943 if (determine_size) {
3944 p = talloc_asprintf(ctx, "%d",
3952 n = snprintf(buf, bufsize, "%d",
3957 if (!determine_size && n > bufsize) {
3966 if (! exclude_nt_owner) {
3967 /* Get owner and group sid */
3968 if (sd->owner_sid) {
3969 convert_sid_to_string(ipc_cli, pol,
3974 fstrcpy(sidstr, "");
3977 if (all || all_nt) {
3978 if (determine_size) {
3979 p = talloc_asprintf(ctx, ",OWNER:%s",
3987 n = snprintf(buf, bufsize,
3988 ",OWNER:%s", sidstr);
3990 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3991 if (determine_size) {
3992 p = talloc_asprintf(ctx, "%s", sidstr);
3999 n = snprintf(buf, bufsize, "%s",
4004 if (!determine_size && n > bufsize) {
4013 if (! exclude_nt_group) {
4015 convert_sid_to_string(ipc_cli, pol,
4019 fstrcpy(sidstr, "");
4022 if (all || all_nt) {
4023 if (determine_size) {
4024 p = talloc_asprintf(ctx, ",GROUP:%s",
4032 n = snprintf(buf, bufsize,
4033 ",GROUP:%s", sidstr);
4035 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4036 if (determine_size) {
4037 p = talloc_asprintf(ctx, "%s", sidstr);
4044 n = snprintf(buf, bufsize, "%s", sidstr);
4048 if (!determine_size && n > bufsize) {
4057 if (! exclude_nt_acl) {
4058 /* Add aces to value buffer */
4059 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4061 SEC_ACE *ace = &sd->dacl->ace[i];
4062 convert_sid_to_string(ipc_cli, pol,
4066 if (all || all_nt) {
4067 if (determine_size) {
4068 p = talloc_asprintf(
4084 ",ACL:%s:%d/%d/0x%08x",
4090 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4091 StrCaseCmp(name + 3, sidstr) == 0) ||
4092 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4093 StrCaseCmp(name + 4, sidstr) == 0)) {
4094 if (determine_size) {
4095 p = talloc_asprintf(
4107 n = snprintf(buf, bufsize,
4113 } else if (all_nt_acls) {
4114 if (determine_size) {
4115 p = talloc_asprintf(
4117 "%s%s:%d/%d/0x%08x",
4129 n = snprintf(buf, bufsize,
4130 "%s%s:%d/%d/0x%08x",
4148 /* Restore name pointer to its original value */
4152 if (all || some_dos) {
4153 /* Point to the portion after "system.dos_attr." */
4154 name += 16; /* if (all) this will be invalid but unused */
4156 /* Obtain the DOS attributes */
4157 if (!smbc_getatr(context, srv, filename, &mode, &size,
4158 &c_time, &a_time, &m_time, &ino)) {
4160 errno = smbc_errno(context, &srv->cli);
4165 if (! exclude_dos_mode) {
4166 if (all || all_dos) {
4167 if (determine_size) {
4168 p = talloc_asprintf(ctx,
4181 n = snprintf(buf, bufsize,
4189 } else if (StrCaseCmp(name, "mode") == 0) {
4190 if (determine_size) {
4191 p = talloc_asprintf(ctx, "0x%x", mode);
4198 n = snprintf(buf, bufsize, "0x%x", mode);
4202 if (!determine_size && n > bufsize) {
4211 if (! exclude_dos_size) {
4212 if (all || all_dos) {
4213 if (determine_size) {
4214 p = talloc_asprintf(
4224 n = snprintf(buf, bufsize,
4228 } else if (StrCaseCmp(name, "size") == 0) {
4229 if (determine_size) {
4230 p = talloc_asprintf(
4240 n = snprintf(buf, bufsize,
4246 if (!determine_size && n > bufsize) {
4255 if (! exclude_dos_ctime) {
4256 if (all || all_dos) {
4257 if (determine_size) {
4258 p = talloc_asprintf(ctx,
4267 n = snprintf(buf, bufsize,
4268 ",C_TIME:%lu", c_time);
4270 } else if (StrCaseCmp(name, "c_time") == 0) {
4271 if (determine_size) {
4272 p = talloc_asprintf(ctx, "%lu", c_time);
4279 n = snprintf(buf, bufsize, "%lu", c_time);
4283 if (!determine_size && n > bufsize) {
4292 if (! exclude_dos_atime) {
4293 if (all || all_dos) {
4294 if (determine_size) {
4295 p = talloc_asprintf(ctx,
4304 n = snprintf(buf, bufsize,
4305 ",A_TIME:%lu", a_time);
4307 } else if (StrCaseCmp(name, "a_time") == 0) {
4308 if (determine_size) {
4309 p = talloc_asprintf(ctx, "%lu", a_time);
4316 n = snprintf(buf, bufsize, "%lu", a_time);
4320 if (!determine_size && n > bufsize) {
4329 if (! exclude_dos_mtime) {
4330 if (all || all_dos) {
4331 if (determine_size) {
4332 p = talloc_asprintf(ctx,
4341 n = snprintf(buf, bufsize,
4342 ",M_TIME:%lu", m_time);
4344 } else if (StrCaseCmp(name, "m_time") == 0) {
4345 if (determine_size) {
4346 p = talloc_asprintf(ctx, "%lu", m_time);
4353 n = snprintf(buf, bufsize, "%lu", m_time);
4357 if (!determine_size && n > bufsize) {
4366 if (! exclude_dos_inode) {
4367 if (all || all_dos) {
4368 if (determine_size) {
4369 p = talloc_asprintf(
4379 n = snprintf(buf, bufsize,
4383 } else if (StrCaseCmp(name, "inode") == 0) {
4384 if (determine_size) {
4385 p = talloc_asprintf(
4395 n = snprintf(buf, bufsize,
4401 if (!determine_size && n > bufsize) {
4410 /* Restore name pointer to its original value */
4423 /*****************************************************
4424 set the ACLs on a file given an ascii description
4425 *******************************************************/
4426 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
4427 struct cli_state *ipc_cli, POLICY_HND *pol,
4428 const char *filename, const char *the_acl,
4429 int mode, int flags)
4433 SEC_DESC *sd = NULL, *old;
4434 SEC_ACL *dacl = NULL;
4435 DOM_SID *owner_sid = NULL;
4436 DOM_SID *grp_sid = NULL;
4441 BOOL numeric = True;
4443 /* the_acl will be null for REMOVE_ALL operations */
4445 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4449 /* if this is to set the entire ACL... */
4450 if (*the_acl == '*') {
4451 /* ... then increment past the first colon */
4455 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4456 CONST_DISCARD(char *, the_acl));
4464 /* The desired access below is the only one I could find that works
4465 with NT4, W2KP and Samba */
4467 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4470 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4471 filename, cli_errstr(cli)));
4476 old = cli_query_secdesc(cli, fnum, ctx);
4479 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4484 cli_close(cli, fnum);
4487 case SMBC_XATTR_MODE_REMOVE_ALL:
4488 old->dacl->num_aces = 0;
4489 SAFE_FREE(old->dacl->ace);
4490 SAFE_FREE(old->dacl);
4495 case SMBC_XATTR_MODE_REMOVE:
4496 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4499 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4500 if (sec_ace_equal(&sd->dacl->ace[i],
4501 &old->dacl->ace[j])) {
4503 for (k=j; k<old->dacl->num_aces-1;k++) {
4504 old->dacl->ace[k] = old->dacl->ace[k+1];
4506 old->dacl->num_aces--;
4507 if (old->dacl->num_aces == 0) {
4508 SAFE_FREE(old->dacl->ace);
4509 SAFE_FREE(old->dacl);
4526 case SMBC_XATTR_MODE_ADD:
4527 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4530 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4531 if (sid_equal(&sd->dacl->ace[i].trustee,
4532 &old->dacl->ace[j].trustee)) {
4533 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4538 old->dacl->ace[j] = sd->dacl->ace[i];
4544 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4550 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4551 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4557 case SMBC_XATTR_MODE_SET:
4559 owner_sid = old->owner_sid;
4560 grp_sid = old->grp_sid;
4564 case SMBC_XATTR_MODE_CHOWN:
4565 owner_sid = sd->owner_sid;
4568 case SMBC_XATTR_MODE_CHGRP:
4569 grp_sid = sd->grp_sid;
4573 /* Denied ACE entries must come before allowed ones */
4574 sort_acl(old->dacl);
4576 /* Create new security descriptor and set it */
4577 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4578 owner_sid, grp_sid, NULL, dacl, &sd_size);
4580 fnum = cli_nt_create(cli, filename,
4581 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4584 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4585 filename, cli_errstr(cli)));
4590 if (!cli_set_secdesc(cli, fnum, sd)) {
4591 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4598 cli_close(cli, fnum);
4608 int smbc_setxattr_ctx(SMBCCTX *context,
4619 fstring server, share, user, password, workgroup;
4625 if (!context || !context->internal ||
4626 !context->internal->_initialized) {
4628 errno = EINVAL; /* Best I can think of ... */
4640 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n", fname, name, (int) size, (const char*)value));
4642 if (smbc_parse_path(context, fname,
4643 server, sizeof(server),
4644 share, sizeof(share),
4647 password, sizeof(password),
4653 if (user[0] == (char)0) fstrcpy(user, context->user);
4655 fstrcpy(workgroup, context->workgroup);
4657 srv = smbc_server(context, server, share, workgroup, user, password);
4659 return -1; /* errno set by smbc_server */
4662 if (! srv->no_nt_session) {
4663 ipc_srv = smbc_attr_server(context, server, share,
4664 workgroup, user, password,
4666 srv->no_nt_session = True;
4671 ctx = talloc_init("smbc_setxattr");
4678 * Are they asking to set the entire set of known attributes?
4680 if (StrCaseCmp(name, "system.*") == 0 ||
4681 StrCaseCmp(name, "system.*+") == 0) {
4684 talloc_asprintf(ctx, "%s:%s", name+7, (const char *) value);
4692 ret = cacl_set(ctx, &srv->cli,
4693 &ipc_srv->cli, &pol, path,
4696 ? SMBC_XATTR_MODE_SET
4697 : SMBC_XATTR_MODE_ADD),
4703 /* get a DOS Attribute Descriptor with current attributes */
4704 dad = dos_attr_query(context, ctx, path, srv);
4706 /* Overwrite old with new, using what was provided */
4707 dos_attr_parse(context, dad, srv, namevalue);
4709 /* Set the new DOS attributes */
4710 if (! smbc_setatr(context, srv, path,
4716 /* cause failure if NT failed too */
4721 /* we only fail if both NT and DOS sets failed */
4722 if (ret < 0 && ! dad) {
4723 ret = -1; /* in case dad was null */
4729 talloc_destroy(ctx);
4734 * Are they asking to set an access control element or to set
4735 * the entire access control list?
4737 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4738 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4739 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4740 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4741 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4745 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4748 ret = -1; /* errno set by smbc_server() */
4750 else if (! namevalue) {
4754 ret = cacl_set(ctx, &srv->cli,
4755 &ipc_srv->cli, &pol, path,
4758 ? SMBC_XATTR_MODE_SET
4759 : SMBC_XATTR_MODE_ADD),
4762 talloc_destroy(ctx);
4767 * Are they asking to set the owner?
4769 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4770 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
4774 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4778 ret = -1; /* errno set by smbc_server() */
4780 else if (! namevalue) {
4784 ret = cacl_set(ctx, &srv->cli,
4785 &ipc_srv->cli, &pol, path,
4786 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4788 talloc_destroy(ctx);
4793 * Are they asking to set the group?
4795 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4796 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
4800 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4803 /* errno set by smbc_server() */
4806 else if (! namevalue) {
4810 ret = cacl_set(ctx, &srv->cli,
4811 &ipc_srv->cli, &pol, path,
4812 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4814 talloc_destroy(ctx);
4819 * Are they asking to set a DOS attribute?
4821 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4822 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4823 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4824 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4825 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
4827 /* get a DOS Attribute Descriptor with current attributes */
4828 dad = dos_attr_query(context, ctx, path, srv);
4831 talloc_asprintf(ctx, "%s:%s", name+16, (const char *) value);
4836 /* Overwrite old with provided new params */
4837 dos_attr_parse(context, dad, srv, namevalue);
4839 /* Set the new DOS attributes */
4840 ret2 = smbc_setatr(context, srv, path,
4846 /* ret2 has True (success) / False (failure) */
4857 talloc_destroy(ctx);
4861 /* Unsupported attribute name */
4862 talloc_destroy(ctx);
4867 int smbc_getxattr_ctx(SMBCCTX *context,
4876 fstring server, share, user, password, workgroup;
4882 if (!context || !context->internal ||
4883 !context->internal->_initialized) {
4885 errno = EINVAL; /* Best I can think of ... */
4897 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
4899 if (smbc_parse_path(context, fname,
4900 server, sizeof(server),
4901 share, sizeof(share),
4904 password, sizeof(password),
4910 if (user[0] == (char)0) fstrcpy(user, context->user);
4912 fstrcpy(workgroup, context->workgroup);
4914 srv = smbc_server(context, server, share, workgroup, user, password);
4916 return -1; /* errno set by smbc_server */
4919 if (! srv->no_nt_session) {
4920 ipc_srv = smbc_attr_server(context, server, share,
4921 workgroup, user, password,
4924 srv->no_nt_session = True;
4930 ctx = talloc_init("smbc:getxattr");
4936 /* Are they requesting a supported attribute? */
4937 if (StrCaseCmp(name, "system.*") == 0 ||
4938 StrnCaseCmp(name, "system.*!", 9) == 0 ||
4939 StrCaseCmp(name, "system.*+") == 0 ||
4940 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
4941 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4942 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
4943 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4944 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
4945 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4946 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4947 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
4948 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4949 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
4950 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4951 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
4952 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4953 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
4954 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4955 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
4956 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4957 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4958 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
4959 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
4962 ret = cacl_get(context, ctx, srv,
4963 ipc_srv == NULL ? NULL : &ipc_srv->cli,
4965 CONST_DISCARD(char *, name),
4966 CONST_DISCARD(char *, value), size);
4967 if (ret < 0 && errno == 0) {
4968 errno = smbc_errno(context, &srv->cli);
4970 talloc_destroy(ctx);
4974 /* Unsupported attribute name */
4975 talloc_destroy(ctx);
4981 int smbc_removexattr_ctx(SMBCCTX *context,
4988 fstring server, share, user, password, workgroup;
4993 if (!context || !context->internal ||
4994 !context->internal->_initialized) {
4996 errno = EINVAL; /* Best I can think of ... */
5008 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5010 if (smbc_parse_path(context, fname,
5011 server, sizeof(server),
5012 share, sizeof(share),
5015 password, sizeof(password),
5021 if (user[0] == (char)0) fstrcpy(user, context->user);
5023 fstrcpy(workgroup, context->workgroup);
5025 srv = smbc_server(context, server, share, workgroup, user, password);
5027 return -1; /* errno set by smbc_server */
5030 if (! srv->no_nt_session) {
5031 ipc_srv = smbc_attr_server(context, server, share,
5032 workgroup, user, password,
5034 srv->no_nt_session = True;
5040 return -1; /* errno set by smbc_attr_server */
5043 ctx = talloc_init("smbc_removexattr");
5049 /* Are they asking to set the entire ACL? */
5050 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5051 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5054 ret = cacl_set(ctx, &srv->cli,
5055 &ipc_srv->cli, &pol, path,
5056 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5057 talloc_destroy(ctx);
5062 * Are they asking to remove one or more spceific security descriptor
5065 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5066 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5067 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5068 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5069 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5070 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5071 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5074 ret = cacl_set(ctx, &srv->cli,
5075 &ipc_srv->cli, &pol, path,
5076 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5077 talloc_destroy(ctx);
5081 /* Unsupported attribute name */
5082 talloc_destroy(ctx);
5087 int smbc_listxattr_ctx(SMBCCTX *context,
5093 * This isn't quite what listxattr() is supposed to do. This returns
5094 * the complete set of attribute names, always, rather than only those
5095 * attribute names which actually exist for a file. Hmmm...
5097 const char supported[] =
5100 "system.nt_sec_desc.revision\0"
5101 "system.nt_sec_desc.owner\0"
5102 "system.nt_sec_desc.owner+\0"
5103 "system.nt_sec_desc.group\0"
5104 "system.nt_sec_desc.group+\0"
5105 "system.nt_sec_desc.acl.*\0"
5106 "system.nt_sec_desc.acl\0"
5107 "system.nt_sec_desc.acl+\0"
5108 "system.nt_sec_desc.*\0"
5109 "system.nt_sec_desc.*+\0"
5110 "system.dos_attr.*\0"
5111 "system.dos_attr.mode\0"
5112 "system.dos_attr.c_time\0"
5113 "system.dos_attr.a_time\0"
5114 "system.dos_attr.m_time\0"
5118 return sizeof(supported);
5121 if (sizeof(supported) > size) {
5126 /* this can't be strcpy() because there are embedded null characters */
5127 memcpy(list, supported, sizeof(supported));
5128 return sizeof(supported);
5133 * Open a print file to be written to by other calls
5136 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
5138 fstring server, share, user, password;
5141 if (!context || !context->internal ||
5142 !context->internal->_initialized) {
5156 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5158 if (smbc_parse_path(context, fname,
5159 server, sizeof(server),
5160 share, sizeof(share),
5163 password, sizeof(password),
5169 /* What if the path is empty, or the file exists? */
5171 return context->open(context, fname, O_WRONLY, 666);
5176 * Routine to print a file on a remote server ...
5178 * We open the file, which we assume to be on a remote server, and then
5179 * copy it to a print file on the share specified by printq.
5182 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
5184 SMBCFILE *fid1, *fid2;
5185 int bytes, saverr, tot_bytes = 0;
5188 if (!c_file || !c_file->internal->_initialized || !c_print ||
5189 !c_print->internal->_initialized) {
5196 if (!fname && !printq) {
5203 /* Try to open the file for reading ... */
5205 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5207 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5208 return -1; /* smbc_open sets errno */
5212 /* Now, try to open the printer file for writing */
5214 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5216 saverr = errno; /* Save errno */
5217 c_file->close_fn(c_file, fid1);
5223 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5227 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5230 c_file->close_fn(c_file, fid1);
5231 c_print->close_fn(c_print, fid2);
5240 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5241 c_print->close_fn(c_print, fid2);
5255 * Routine to list print jobs on a printer share ...
5258 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
5261 fstring server, share, user, password, workgroup;
5264 if (!context || !context->internal ||
5265 !context->internal->_initialized) {
5279 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5281 if (smbc_parse_path(context, fname,
5282 server, sizeof(server),
5283 share, sizeof(share),
5286 password, sizeof(password),
5292 if (user[0] == (char)0) fstrcpy(user, context->user);
5294 fstrcpy(workgroup, context->workgroup);
5296 srv = smbc_server(context, server, share, workgroup, user, password);
5300 return -1; /* errno set by smbc_server */
5304 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
5306 errno = smbc_errno(context, &srv->cli);
5316 * Delete a print job from a remote printer share
5319 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
5322 fstring server, share, user, password, workgroup;
5326 if (!context || !context->internal ||
5327 !context->internal->_initialized) {
5341 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5343 if (smbc_parse_path(context, fname,
5344 server, sizeof(server),
5345 share, sizeof(share),
5348 password, sizeof(password),
5354 if (user[0] == (char)0) fstrcpy(user, context->user);
5356 fstrcpy(workgroup, context->workgroup);
5358 srv = smbc_server(context, server, share, workgroup, user, password);
5362 return -1; /* errno set by smbc_server */
5366 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5369 errno = smbc_errno(context, &srv->cli);
5370 else if (err == ERRnosuchprintjob)
5381 * Get a new empty handle to fill in with your own info
5383 SMBCCTX * smbc_new_context(void)
5387 context = SMB_MALLOC_P(SMBCCTX);
5393 ZERO_STRUCTP(context);
5395 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5396 if (!context->internal) {
5401 ZERO_STRUCTP(context->internal);
5404 /* ADD REASONABLE DEFAULTS */
5406 context->timeout = 20000; /* 20 seconds */
5408 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5409 context->options.urlencode_readdir_entries = False;/* backward compat */
5410 context->options.one_share_per_server = False;/* backward compat */
5412 context->open = smbc_open_ctx;
5413 context->creat = smbc_creat_ctx;
5414 context->read = smbc_read_ctx;
5415 context->write = smbc_write_ctx;
5416 context->close_fn = smbc_close_ctx;
5417 context->unlink = smbc_unlink_ctx;
5418 context->rename = smbc_rename_ctx;
5419 context->lseek = smbc_lseek_ctx;
5420 context->stat = smbc_stat_ctx;
5421 context->fstat = smbc_fstat_ctx;
5422 context->opendir = smbc_opendir_ctx;
5423 context->closedir = smbc_closedir_ctx;
5424 context->readdir = smbc_readdir_ctx;
5425 context->getdents = smbc_getdents_ctx;
5426 context->mkdir = smbc_mkdir_ctx;
5427 context->rmdir = smbc_rmdir_ctx;
5428 context->telldir = smbc_telldir_ctx;
5429 context->lseekdir = smbc_lseekdir_ctx;
5430 context->fstatdir = smbc_fstatdir_ctx;
5431 context->chmod = smbc_chmod_ctx;
5432 context->utimes = smbc_utimes_ctx;
5433 context->setxattr = smbc_setxattr_ctx;
5434 context->getxattr = smbc_getxattr_ctx;
5435 context->removexattr = smbc_removexattr_ctx;
5436 context->listxattr = smbc_listxattr_ctx;
5437 context->open_print_job = smbc_open_print_job_ctx;
5438 context->print_file = smbc_print_file_ctx;
5439 context->list_print_jobs = smbc_list_print_jobs_ctx;
5440 context->unlink_print_job = smbc_unlink_print_job_ctx;
5442 context->callbacks.check_server_fn = smbc_check_server;
5443 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5445 smbc_default_cache_functions(context);
5453 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5454 * and thus you'll be leaking memory if not handled properly.
5457 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
5466 DEBUG(1,("Performing aggressive shutdown.\n"));
5468 f = context->internal->_files;
5470 context->close_fn(context, f);
5473 context->internal->_files = NULL;
5475 /* First try to remove the servers the nice way. */
5476 if (context->callbacks.purge_cached_fn(context)) {
5479 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
5480 s = context->internal->_servers;
5482 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
5483 cli_shutdown(&s->cli);
5484 context->callbacks.remove_cached_srv_fn(context, s);
5486 DLIST_REMOVE(context->internal->_servers, s);
5490 context->internal->_servers = NULL;
5494 /* This is the polite way */
5495 if (context->callbacks.purge_cached_fn(context)) {
5496 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
5500 if (context->internal->_servers) {
5501 DEBUG(1, ("Active servers in context, free_context failed.\n"));
5505 if (context->internal->_files) {
5506 DEBUG(1, ("Active files in context, free_context failed.\n"));
5512 /* Things we have to clean up */
5513 SAFE_FREE(context->workgroup);
5514 SAFE_FREE(context->netbios_name);
5515 SAFE_FREE(context->user);
5517 DEBUG(3, ("Context %p succesfully freed\n", context));
5518 SAFE_FREE(context->internal);
5525 * Initialise the library etc
5527 * We accept a struct containing handle information.
5528 * valid values for info->debug from 0 to 100,
5529 * and insist that info->fn must be non-null.
5531 SMBCCTX * smbc_init_context(SMBCCTX * context)
5535 char *user = NULL, *home = NULL;
5537 if (!context || !context->internal) {
5542 /* Do not initialise the same client twice */
5543 if (context->internal->_initialized) {
5547 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
5554 if (!smbc_initialized) {
5555 /* Do some library wide intialisations the first time we get called */
5556 BOOL conf_loaded = False;
5558 /* Set this to what the user wants */
5559 DEBUGLEVEL = context->debug;
5561 setup_logging( "libsmbclient", True);
5563 /* Here we would open the smb.conf file if needed ... */
5565 load_interfaces(); /* Load the list of interfaces ... */
5567 in_client = True; /* FIXME, make a param */
5569 home = getenv("HOME");
5571 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5572 if (lp_load(conf, True, False, False)) {
5575 DEBUG(5, ("Could not load config file: %s\n",
5582 * Well, if that failed, try the dyn_CONFIGFILE
5583 * Which points to the standard locn, and if that
5584 * fails, silently ignore it and use the internal
5588 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
5589 DEBUG(5, ("Could not load config file: %s\n",
5593 * We loaded the global config file. Now lets
5594 * load user-specific modifications to the
5597 slprintf(conf, sizeof(conf),
5598 "%s/.smb/smb.conf.append", home);
5599 if (!lp_load(conf, True, False, False)) {
5601 ("Could not append config file: "
5608 reopen_logs(); /* Get logging working ... */
5611 * Block SIGPIPE (from lib/util_sock.c: write())
5612 * It is not needed and should not stop execution
5614 BlockSignals(True, SIGPIPE);
5616 /* Done with one-time initialisation */
5617 smbc_initialized = 1;
5621 if (!context->user) {
5623 * FIXME: Is this the best way to get the user info?
5625 user = getenv("USER");
5626 /* walk around as "guest" if no username can be found */
5627 if (!user) context->user = SMB_STRDUP("guest");
5628 else context->user = SMB_STRDUP(user);
5631 if (!context->netbios_name) {
5633 * We try to get our netbios name from the config. If that fails we fall
5634 * back on constructing our netbios name from our hostname etc
5636 if (global_myname()) {
5637 context->netbios_name = SMB_STRDUP(global_myname());
5641 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
5644 context->netbios_name = SMB_MALLOC(17);
5645 if (!context->netbios_name) {
5649 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
5653 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
5655 if (!context->workgroup) {
5656 if (lp_workgroup()) {
5657 context->workgroup = SMB_STRDUP(lp_workgroup());
5660 /* TODO: Think about a decent default workgroup */
5661 context->workgroup = SMB_STRDUP("samba");
5665 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
5667 /* shortest timeout is 1 second */
5668 if (context->timeout > 0 && context->timeout < 1000)
5669 context->timeout = 1000;
5672 * FIXME: Should we check the function pointers here?
5675 context->internal->_initialized = 1;
5681 /* Return the verion of samba, and thus libsmbclient */
5685 return samba_version_string();