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.
85 static struct rpc_pipe_client *
86 find_lsa_pipe_hnd(struct cli_state *ipc_cli)
88 struct rpc_pipe_client *pipe_hnd;
90 for (pipe_hnd = ipc_cli->pipe_list;
92 pipe_hnd = pipe_hnd->next) {
94 if (pipe_hnd->pipe_idx == PI_LSARPC) {
103 smbc_close_ctx(SMBCCTX *context,
106 smbc_lseek_ctx(SMBCCTX *context,
111 extern BOOL in_client;
114 * Is the logging working / configfile read ?
116 static int smbc_initialized = 0;
119 hex2int( unsigned int _char )
121 if ( _char >= 'A' && _char <='F')
122 return _char - 'A' + 10;
123 if ( _char >= 'a' && _char <='f')
124 return _char - 'a' + 10;
125 if ( _char >= '0' && _char <='9')
133 * Convert strings of %xx to their single character equivalent. Each 'x' must
134 * be a valid hexadecimal digit, or that % sequence is left undecoded.
136 * dest may, but need not be, the same pointer as src.
138 * Returns the number of % sequences which could not be converted due to lack
139 * of two following hexadecimal digits.
142 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
144 int old_length = strlen(src);
150 if ( old_length == 0 ) {
155 while ( i < old_length ) {
156 unsigned char character = src[ i++ ];
158 if (character == '%') {
159 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
160 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
162 /* Replace valid sequence */
163 if (a != -1 && b != -1) {
165 /* Replace valid %xx sequence with %dd */
166 character = (a * 16) + b;
168 if (character == '\0') {
169 break; /* Stop at %00 */
184 strncpy(dest, temp, max_dest_len - 1);
185 dest[max_dest_len - 1] = '\0';
193 * Convert any characters not specifically allowed in a URL into their %xx
196 * Returns the remaining buffer length.
199 smbc_urlencode(char * dest, char * src, int max_dest_len)
201 char hex[] = "0123456789ABCDEF";
203 for (; *src != '\0' && max_dest_len >= 3; src++) {
215 *dest++ = hex[(*src >> 4) & 0x0f];
216 *dest++ = hex[*src & 0x0f];
231 * Function to parse a path and turn it into components
233 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
234 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
235 * general format ("smb:" only; we do not look for "cifs:").
239 * smb://[[[domain;]user[:password]@]server[/share[/path[/file]]]][?options]
243 * smb:// Show all workgroups.
245 * The method of locating the list of workgroups varies
246 * depending upon the setting of the context variable
247 * context->options.browse_max_lmb_count. This value
248 * determine the maximum number of local master browsers to
249 * query for the list of workgroups. In order to ensure that
250 * a complete list of workgroups is obtained, all master
251 * browsers must be queried, but if there are many
252 * workgroups, the time spent querying can begin to add up.
253 * For small networks (not many workgroups), it is suggested
254 * that this variable be set to 0, indicating query all local
255 * master browsers. When the network has many workgroups, a
256 * reasonable setting for this variable might be around 3.
258 * smb://name/ if name<1D> or name<1B> exists, list servers in
259 * workgroup, else, if name<20> exists, list all shares
262 * If "options" are provided, this function returns the entire option list as a
263 * string, for later parsing by the caller. Note that currently, no options
267 static const char *smbc_prefix = "smb:";
270 smbc_parse_path(SMBCCTX *context,
272 char *workgroup, int workgroup_len,
273 char *server, int server_len,
274 char *share, int share_len,
275 char *path, int path_len,
276 char *user, int user_len,
277 char *password, int password_len,
278 char *options, int options_len)
286 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
289 * Assume we wont find an authentication domain to parse, so default
290 * to the workgroup in the provided context.
292 if (workgroup != NULL) {
293 strncpy(workgroup, context->workgroup, workgroup_len - 1);
294 workgroup[workgroup_len - 1] = '\0';
297 if (options != NULL && options_len > 0) {
298 options[0] = (char)0;
302 /* see if it has the right prefix */
303 len = strlen(smbc_prefix);
304 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
305 return -1; /* What about no smb: ? */
310 /* Watch the test below, we are testing to see if we should exit */
312 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
314 DEBUG(1, ("Invalid path (does not begin with smb://"));
319 p += 2; /* Skip the double slash */
321 /* See if any options were specified */
322 if ((q = strrchr(p, '?')) != NULL ) {
323 /* There are options. Null terminate here and point to them */
326 DEBUG(4, ("Found options '%s'", q));
328 /* Copy the options */
329 if (options != NULL && options_len > 0) {
330 safe_strcpy(options, q, options_len - 1);
339 strncpy(server, context->workgroup,
340 ((strlen(context->workgroup) < 16)
341 ? strlen(context->workgroup)
343 server[server_len - 1] = '\0';
349 * ok, its for us. Now parse out the server, share etc.
351 * However, we want to parse out [[domain;]user[:password]@] if it
355 /* check that '@' occurs before '/', if '/' exists at all */
356 q = strchr_m(p, '@');
357 r = strchr_m(p, '/');
358 if (q && (!r || q < r)) {
359 pstring username, passwd, domain;
360 const char *u = userinfo;
362 next_token_no_ltrim(&p, userinfo, "@", sizeof(fstring));
364 username[0] = passwd[0] = domain[0] = 0;
366 if (strchr_m(u, ';')) {
368 next_token_no_ltrim(&u, domain, ";", sizeof(fstring));
372 if (strchr_m(u, ':')) {
374 next_token_no_ltrim(&u, username, ":", sizeof(fstring));
381 pstrcpy(username, u);
385 if (domain[0] && workgroup) {
386 strncpy(workgroup, domain, workgroup_len - 1);
387 workgroup[workgroup_len - 1] = '\0';
391 strncpy(user, username, user_len - 1);
392 user[user_len - 1] = '\0';
396 strncpy(password, passwd, password_len - 1);
397 password[password_len - 1] = '\0';
402 if (!next_token(&p, server, "/", sizeof(fstring))) {
408 if (*p == (char)0) goto decoding; /* That's it ... */
410 if (!next_token(&p, share, "/", sizeof(fstring))) {
416 safe_strcpy(path, p, path_len - 1);
418 all_string_sub(path, "/", "\\", 0);
421 (void) smbc_urldecode(path, path, path_len);
422 (void) smbc_urldecode(server, server, server_len);
423 (void) smbc_urldecode(share, share, share_len);
424 (void) smbc_urldecode(user, user, user_len);
425 (void) smbc_urldecode(password, password, password_len);
431 * Verify that the options specified in a URL are valid
434 smbc_check_options(char *server,
439 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' "
440 "path='%s' options='%s'\n",
441 server, share, path, options));
443 /* No options at all is always ok */
444 if (! *options) return 0;
446 /* Currently, we don't support any options. */
451 * Convert an SMB error into a UNIX error ...
454 smbc_errno(SMBCCTX *context,
457 int ret = cli_errno(c);
459 if (cli_is_dos_error(c)) {
463 cli_dos_error(c, &eclass, &ecode);
465 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
466 (int)eclass, (int)ecode, (int)ecode, ret));
470 status = cli_nt_error(c);
472 DEBUG(3,("smbc errno %s -> %d\n",
473 nt_errstr(status), ret));
480 * Check a server for being alive and well.
481 * returns 0 if the server is in shape. Returns 1 on error
483 * Also useable outside libsmbclient to enable external cache
484 * to do some checks too.
487 smbc_check_server(SMBCCTX * context,
490 if ( send_keepalive(server->cli->fd) == False )
493 /* connection is ok */
498 * Remove a server from the cached server list it's unused.
499 * On success, 0 is returned. 1 is returned if the server could not be removed.
501 * Also useable outside libsmbclient
504 smbc_remove_unused_server(SMBCCTX * context,
509 /* are we being fooled ? */
510 if (!context || !context->internal ||
511 !context->internal->_initialized || !srv) return 1;
514 /* Check all open files/directories for a relation with this server */
515 for (file = context->internal->_files; file; file=file->next) {
516 if (file->srv == srv) {
518 DEBUG(3, ("smbc_remove_usused_server: "
519 "%p still used by %p.\n",
525 DLIST_REMOVE(context->internal->_servers, srv);
527 cli_shutdown(srv->cli);
530 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
532 context->callbacks.remove_cached_srv_fn(context, srv);
540 find_server(SMBCCTX *context,
552 srv = context->callbacks.get_cached_srv_fn(context, server, share,
553 workgroup, username);
555 if (!auth_called && !srv && (!username[0] || !password[0])) {
556 if (context->internal->_auth_fn_with_context != NULL) {
557 context->internal->_auth_fn_with_context(
560 workgroup, sizeof(fstring),
561 username, sizeof(fstring),
562 password, sizeof(fstring));
564 context->callbacks.auth_fn(
566 workgroup, sizeof(fstring),
567 username, sizeof(fstring),
568 password, sizeof(fstring));
572 * However, smbc_auth_fn may have picked up info relating to
573 * an existing connection, so try for an existing connection
577 goto check_server_cache;
582 if (context->callbacks.check_server_fn(context, srv)) {
584 * This server is no good anymore
585 * Try to remove it and check for more possible
586 * servers in the cache
588 if (context->callbacks.remove_unused_server_fn(context,
591 * We could not remove the server completely,
592 * remove it from the cache so we will not get
593 * it again. It will be removed when the last
594 * file/dir is closed.
596 context->callbacks.remove_cached_srv_fn(context,
601 * Maybe there are more cached connections to this
604 goto check_server_cache;
614 * Connect to a server, possibly on an existing connection
616 * Here, what we want to do is: If the server and username
617 * match an existing connection, reuse that, otherwise, establish a
620 * If we have to create a new connection, call the auth_fn to get the
621 * info we need, unless the username and password were passed in.
625 smbc_server(SMBCCTX *context,
626 BOOL connect_if_not_found,
635 struct nmb_name called, calling;
636 const char *server_n = server;
639 int tried_reverse = 0;
642 const char *username_used;
647 if (server[0] == 0) {
652 /* Look for a cached connection */
653 srv = find_server(context, server, share,
654 workgroup, username, password);
657 * If we found a connection and we're only allowed one share per
660 if (srv && *share != '\0' && context->options.one_share_per_server) {
663 * ... then if there's no current connection to the share,
664 * connect to it. find_server(), or rather the function
665 * pointed to by context->callbacks.get_cached_srv_fn which
666 * was called by find_server(), will have issued a tree
667 * disconnect if the requested share is not the same as the
668 * one that was already connected.
670 if (srv->cli->cnum == (uint16) -1) {
671 /* Ensure we have accurate auth info */
672 if (context->internal->_auth_fn_with_context != NULL) {
673 context->internal->_auth_fn_with_context(
676 workgroup, sizeof(fstring),
677 username, sizeof(fstring),
678 password, sizeof(fstring));
680 context->callbacks.auth_fn(
682 workgroup, sizeof(fstring),
683 username, sizeof(fstring),
684 password, sizeof(fstring));
687 if (! cli_send_tconX(srv->cli, share, "?????",
688 password, strlen(password)+1)) {
690 errno = smbc_errno(context, srv->cli);
691 cli_shutdown(srv->cli);
693 context->callbacks.remove_cached_srv_fn(context,
699 * Regenerate the dev value since it's based on both
703 srv->dev = (dev_t)(str_checksum(server) ^
704 str_checksum(share));
709 /* If we have a connection... */
712 /* ... then we're done here. Give 'em what they came for. */
716 /* If we're not asked to connect when a connection doesn't exist... */
717 if (! connect_if_not_found) {
718 /* ... then we're done here. */
722 make_nmb_name(&calling, context->netbios_name, 0x0);
723 make_nmb_name(&called , server, 0x20);
725 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
727 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
730 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
734 /* have to open a new connection */
735 if ((c = cli_initialise()) == NULL) {
740 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
741 c->use_kerberos = True;
743 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
744 c->fallback_after_kerberos = True;
747 c->timeout = context->timeout;
750 * Force use of port 139 for first try if share is $IPC, empty, or
751 * null, so browse lists can work
753 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
754 port_try_first = 139;
757 port_try_first = 445;
761 c->port = port_try_first;
763 if (!cli_connect(c, server_n, &ip)) {
765 /* First connection attempt failed. Try alternate port. */
766 c->port = port_try_next;
768 if (!cli_connect(c, server_n, &ip)) {
775 if (!cli_session_request(c, &calling, &called)) {
777 if (strcmp(called.name, "*SMBSERVER")) {
778 make_nmb_name(&called , "*SMBSERVER", 0x20);
780 } else { /* Try one more time, but ensure we don't loop */
782 /* Only try this if server is an IP address ... */
784 if (is_ipaddress(server) && !tried_reverse) {
786 struct in_addr rem_ip;
788 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
789 DEBUG(4, ("Could not convert IP address "
790 "%s to struct in_addr\n", server));
795 tried_reverse++; /* Yuck */
797 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
798 make_nmb_name(&called, remote_name, 0x20);
807 DEBUG(4,(" session request ok\n"));
809 if (!cli_negprot(c)) {
815 username_used = username;
817 if (!NT_STATUS_IS_OK(cli_session_setup(c, username_used,
818 password, strlen(password),
819 password, strlen(password),
822 /* Failed. Try an anonymous login, if allowed by flags. */
825 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
826 !NT_STATUS_IS_OK(cli_session_setup(c, username_used,
837 DEBUG(4,(" session setup ok\n"));
839 if (!cli_send_tconX(c, share, "?????",
840 password, strlen(password)+1)) {
841 errno = smbc_errno(context, c);
846 DEBUG(4,(" tconx ok\n"));
849 * Ok, we have got a nice connection
850 * Let's allocate a server structure.
853 srv = SMB_MALLOC_P(SMBCSRV);
861 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
862 srv->no_pathinfo = False;
863 srv->no_pathinfo2 = False;
864 srv->no_nt_session = False;
866 /* now add it to the cache (internal or external) */
867 /* Let the cache function set errno if it wants to */
869 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
870 int saved_errno = errno;
871 DEBUG(3, (" Failed to add server to cache\n"));
879 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
880 server, share, srv));
882 DLIST_ADD(context->internal->_servers, srv);
896 * Connect to a server for getting/setting attributes, possibly on an existing
897 * connection. This works similarly to smbc_server().
900 smbc_attr_server(SMBCCTX *context,
909 struct cli_state *ipc_cli;
910 struct rpc_pipe_client *pipe_hnd;
912 SMBCSRV *ipc_srv=NULL;
915 * See if we've already created this special connection. Reference
916 * our "special" share name '*IPC$', which is an impossible real share
917 * name due to the leading asterisk.
919 ipc_srv = find_server(context, server, "*IPC$",
920 workgroup, username, password);
923 /* We didn't find a cached connection. Get the password */
924 if (*password == '\0') {
925 /* ... then retrieve it now. */
926 if (context->internal->_auth_fn_with_context != NULL) {
927 context->internal->_auth_fn_with_context(
930 workgroup, sizeof(fstring),
931 username, sizeof(fstring),
932 password, sizeof(fstring));
934 context->callbacks.auth_fn(
936 workgroup, sizeof(fstring),
937 username, sizeof(fstring),
938 password, sizeof(fstring));
943 nt_status = cli_full_connection(&ipc_cli,
944 global_myname(), server,
945 &ip, 0, "IPC$", "?????",
949 if (! NT_STATUS_IS_OK(nt_status)) {
950 DEBUG(1,("cli_full_connection failed! (%s)\n",
951 nt_errstr(nt_status)));
956 ipc_srv = SMB_MALLOC_P(SMBCSRV);
959 cli_shutdown(ipc_cli);
963 ZERO_STRUCTP(ipc_srv);
964 ipc_srv->cli = ipc_cli;
967 pipe_hnd = cli_rpc_pipe_open_noauth(ipc_srv->cli,
971 DEBUG(1, ("cli_nt_session_open fail!\n"));
973 cli_shutdown(ipc_srv->cli);
979 * Some systems don't support
980 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
981 * so we might as well do it too.
984 nt_status = rpccli_lsa_open_policy(
986 ipc_srv->cli->mem_ctx,
988 GENERIC_EXECUTE_ACCESS,
991 if (!NT_STATUS_IS_OK(nt_status)) {
992 errno = smbc_errno(context, ipc_srv->cli);
993 cli_shutdown(ipc_srv->cli);
998 /* now add it to the cache (internal or external) */
1000 errno = 0; /* let cache function set errno if it likes */
1001 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
1006 DEBUG(3, (" Failed to add server to cache\n"));
1010 cli_shutdown(ipc_srv->cli);
1015 DLIST_ADD(context->internal->_servers, ipc_srv);
1022 * Routine to open() a file ...
1026 smbc_open_ctx(SMBCCTX *context,
1031 fstring server, share, user, password, workgroup;
1034 struct cli_state *targetcli;
1035 SMBCSRV *srv = NULL;
1036 SMBCFILE *file = NULL;
1039 if (!context || !context->internal ||
1040 !context->internal->_initialized) {
1042 errno = EINVAL; /* Best I can think of ... */
1054 if (smbc_parse_path(context, fname,
1055 workgroup, sizeof(workgroup),
1056 server, sizeof(server),
1057 share, sizeof(share),
1060 password, sizeof(password),
1066 if (user[0] == (char)0) fstrcpy(user, context->user);
1068 srv = smbc_server(context, True,
1069 server, share, workgroup, user, password);
1073 if (errno == EPERM) errno = EACCES;
1074 return NULL; /* smbc_server sets errno */
1078 /* Hmmm, the test for a directory is suspect here ... FIXME */
1080 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1087 file = SMB_MALLOC_P(SMBCFILE);
1098 /*d_printf(">>>open: resolving %s\n", path);*/
1099 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1101 d_printf("Could not resolve %s\n", path);
1105 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1107 if ( targetcli->dfsroot )
1110 pstrcpy(temppath, targetpath);
1111 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1114 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1116 /* Handle the error ... */
1119 errno = smbc_errno(context, targetcli);
1124 /* Fill in file struct */
1127 file->fname = SMB_STRDUP(fname);
1132 DLIST_ADD(context->internal->_files, file);
1135 * If the file was opened in O_APPEND mode, all write
1136 * operations should be appended to the file. To do that,
1137 * though, using this protocol, would require a getattrE()
1138 * call for each and every write, to determine where the end
1139 * of the file is. (There does not appear to be an append flag
1140 * in the protocol.) Rather than add all of that overhead of
1141 * retrieving the current end-of-file offset prior to each
1142 * write operation, we'll assume that most append operations
1143 * will continuously write, so we'll just set the offset to
1144 * the end of the file now and hope that's adequate.
1146 * Note to self: If this proves inadequate, and O_APPEND
1147 * should, in some cases, be forced for each write, add a
1148 * field in the context options structure, for
1149 * "strict_append_mode" which would select between the current
1150 * behavior (if FALSE) or issuing a getattrE() prior to each
1151 * write and forcing the write to the end of the file (if
1152 * TRUE). Adding that capability will likely require adding
1153 * an "append" flag into the _SMBCFILE structure to track
1154 * whether a file was opened in O_APPEND mode. -- djl
1156 if (flags & O_APPEND) {
1157 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1158 (void) smbc_close_ctx(context, file);
1168 /* Check if opendir needed ... */
1173 eno = smbc_errno(context, srv->cli);
1174 file = context->opendir(context, fname);
1175 if (!file) errno = eno;
1180 errno = EINVAL; /* FIXME, correct errno ? */
1186 * Routine to create a file
1189 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1192 smbc_creat_ctx(SMBCCTX *context,
1197 if (!context || !context->internal ||
1198 !context->internal->_initialized) {
1205 return smbc_open_ctx(context, path, creat_bits, mode);
1209 * Routine to read() a file ...
1213 smbc_read_ctx(SMBCCTX *context,
1219 fstring server, share, user, password;
1220 pstring path, targetpath;
1221 struct cli_state *targetcli;
1226 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1227 * appears to pass file->offset (which is type off_t) differently than
1228 * a local variable of type off_t. Using local variable "offset" in
1229 * the call to cli_read() instead of file->offset fixes a problem
1230 * retrieving data at an offset greater than 4GB.
1234 if (!context || !context->internal ||
1235 !context->internal->_initialized) {
1242 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1244 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1251 offset = file->offset;
1253 /* Check that the buffer exists ... */
1262 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1263 if (smbc_parse_path(context, file->fname,
1265 server, sizeof(server),
1266 share, sizeof(share),
1269 password, sizeof(password),
1275 /*d_printf(">>>read: resolving %s\n", path);*/
1276 if (!cli_resolve_path("", file->srv->cli, path,
1277 &targetcli, targetpath))
1279 d_printf("Could not resolve %s\n", path);
1282 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1284 ret = cli_read(targetcli, file->cli_fd, (char *)buf, offset, count);
1288 errno = smbc_errno(context, targetcli);
1293 file->offset += ret;
1295 DEBUG(4, (" --> %d\n", ret));
1297 return ret; /* Success, ret bytes of data ... */
1302 * Routine to write() a file ...
1306 smbc_write_ctx(SMBCCTX *context,
1313 fstring server, share, user, password;
1314 pstring path, targetpath;
1315 struct cli_state *targetcli;
1317 /* First check all pointers before dereferencing them */
1319 if (!context || !context->internal ||
1320 !context->internal->_initialized) {
1327 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1334 /* Check that the buffer exists ... */
1343 offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1345 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1346 if (smbc_parse_path(context, file->fname,
1348 server, sizeof(server),
1349 share, sizeof(share),
1352 password, sizeof(password),
1358 /*d_printf(">>>write: resolving %s\n", path);*/
1359 if (!cli_resolve_path("", file->srv->cli, path,
1360 &targetcli, targetpath))
1362 d_printf("Could not resolve %s\n", path);
1365 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1368 ret = cli_write(targetcli, file->cli_fd, 0, (char *)buf, offset, count);
1372 errno = smbc_errno(context, targetcli);
1377 file->offset += ret;
1379 return ret; /* Success, 0 bytes of data ... */
1383 * Routine to close() a file ...
1387 smbc_close_ctx(SMBCCTX *context,
1391 fstring server, share, user, password;
1392 pstring path, targetpath;
1393 struct cli_state *targetcli;
1395 if (!context || !context->internal ||
1396 !context->internal->_initialized) {
1403 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1413 return context->closedir(context, file);
1417 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1418 if (smbc_parse_path(context, file->fname,
1420 server, sizeof(server),
1421 share, sizeof(share),
1424 password, sizeof(password),
1430 /*d_printf(">>>close: resolving %s\n", path);*/
1431 if (!cli_resolve_path("", file->srv->cli, path,
1432 &targetcli, targetpath))
1434 d_printf("Could not resolve %s\n", path);
1437 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1439 if (!cli_close(targetcli, file->cli_fd)) {
1441 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1443 /* Deallocate slot and remove the server
1444 * from the server cache if unused */
1445 errno = smbc_errno(context, targetcli);
1447 DLIST_REMOVE(context->internal->_files, file);
1448 SAFE_FREE(file->fname);
1450 context->callbacks.remove_unused_server_fn(context, srv);
1456 DLIST_REMOVE(context->internal->_files, file);
1457 SAFE_FREE(file->fname);
1464 * Get info from an SMB server on a file. Use a qpathinfo call first
1465 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1468 smbc_getatr(SMBCCTX * context,
1473 struct timespec *c_time_ts,
1474 struct timespec *a_time_ts,
1475 struct timespec *m_time_ts,
1480 struct cli_state *targetcli;
1483 if (!context || !context->internal ||
1484 !context->internal->_initialized) {
1491 /* path fixup for . and .. */
1492 if (strequal(path, ".") || strequal(path, ".."))
1493 pstrcpy(fixedpath, "\\");
1496 pstrcpy(fixedpath, path);
1497 trim_string(fixedpath, NULL, "\\..");
1498 trim_string(fixedpath, NULL, "\\.");
1500 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1502 if (!cli_resolve_path( "", srv->cli, fixedpath, &targetcli, targetpath))
1504 d_printf("Couldn't resolve %s\n", path);
1508 if ( targetcli->dfsroot )
1511 pstrcpy(temppath, targetpath);
1512 cli_dfs_make_full_path(targetpath, targetcli->desthost,
1513 targetcli->share, temppath);
1516 if (!srv->no_pathinfo2 &&
1517 cli_qpathinfo2(targetcli, targetpath,
1518 NULL, a_time_ts, m_time_ts, c_time_ts, size, mode, ino)) {
1522 /* if this is NT then don't bother with the getatr */
1523 if (targetcli->capabilities & CAP_NT_SMBS) {
1528 if (cli_getatr(targetcli, targetpath, mode, size, &m_time)) {
1529 if (m_time_ts != NULL) {
1530 *m_time_ts = convert_time_t_to_timespec(m_time);
1531 if (a_time_ts != NULL) *a_time_ts = *m_time_ts;
1532 if (c_time_ts != NULL) *c_time_ts = *m_time_ts;
1534 srv->no_pathinfo2 = True;
1544 * Set file info on an SMB server. Use setpathinfo call first. If that
1545 * fails, use setattrE..
1547 * Access and modification time parameters are always used and must be
1548 * provided. Create time, if zero, will be determined from the actual create
1549 * time of the file. If non-zero, the create time will be set as well.
1551 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1554 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1555 time_t c_time, time_t a_time, time_t m_time,
1562 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1563 * modern function for "new code" to be using, and it works given a
1564 * filename rather than requiring that the file be opened to have its
1565 * attributes manipulated.
1567 if (srv->no_pathinfo ||
1568 ! cli_setpathinfo(srv->cli, path, c_time, a_time, m_time, mode)) {
1571 * setpathinfo is not supported; go to plan B.
1573 * cli_setatr() does not work on win98, and it also doesn't
1574 * support setting the access time (only the modification
1575 * time), so in all cases, we open the specified file and use
1576 * cli_setattrE() which should work on all OS versions, and
1577 * supports both times.
1580 /* Don't try {q,set}pathinfo() again, with this server */
1581 srv->no_pathinfo = True;
1584 if ((fd = cli_open(srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1586 errno = smbc_errno(context, srv->cli);
1591 * Get the creat time of the file (if it wasn't provided).
1592 * We'll need it in the set call
1595 ret = cli_getattrE(srv->cli, fd,
1597 &c_time, NULL, NULL);
1602 /* If we got create time, set times */
1604 /* Some OS versions don't support create time */
1605 if (c_time == 0 || c_time == -1) {
1606 c_time = time(NULL);
1610 * For sanity sake, since there is no POSIX function
1611 * to set the create time of a file, if the existing
1612 * create time is greater than either of access time
1613 * or modification time, set create time to the
1614 * smallest of those. This ensure that the create
1615 * time of a file is never greater than its last
1616 * access or modification time.
1618 if (c_time > a_time) c_time = a_time;
1619 if (c_time > m_time) c_time = m_time;
1621 /* Set the new attributes */
1622 ret = cli_setattrE(srv->cli, fd,
1623 c_time, a_time, m_time);
1624 cli_close(srv->cli, fd);
1628 * Unfortunately, setattrE() doesn't have a provision for
1629 * setting the access mode (attributes). We'll have to try
1630 * cli_setatr() for that, and with only this parameter, it
1631 * seems to work on win98.
1633 if (ret && mode != (uint16) -1) {
1634 ret = cli_setatr(srv->cli, path, mode, 0);
1638 errno = smbc_errno(context, srv->cli);
1647 * Routine to unlink() a file
1651 smbc_unlink_ctx(SMBCCTX *context,
1654 fstring server, share, user, password, workgroup;
1655 pstring path, targetpath;
1656 struct cli_state *targetcli;
1657 SMBCSRV *srv = NULL;
1659 if (!context || !context->internal ||
1660 !context->internal->_initialized) {
1662 errno = EINVAL; /* Best I can think of ... */
1674 if (smbc_parse_path(context, fname,
1675 workgroup, sizeof(workgroup),
1676 server, sizeof(server),
1677 share, sizeof(share),
1680 password, sizeof(password),
1686 if (user[0] == (char)0) fstrcpy(user, context->user);
1688 srv = smbc_server(context, True,
1689 server, share, workgroup, user, password);
1693 return -1; /* smbc_server sets errno */
1697 /*d_printf(">>>unlink: resolving %s\n", path);*/
1698 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1700 d_printf("Could not resolve %s\n", path);
1703 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1705 if (!cli_unlink(targetcli, targetpath)) {
1707 errno = smbc_errno(context, targetcli);
1709 if (errno == EACCES) { /* Check if the file is a directory */
1714 struct timespec m_time_ts, a_time_ts, c_time_ts;
1717 if (!smbc_getatr(context, srv, path, &mode, &size,
1718 &c_time_ts, &a_time_ts, &m_time_ts, &ino)) {
1720 /* Hmmm, bad error ... What? */
1722 errno = smbc_errno(context, targetcli);
1728 if (IS_DOS_DIR(mode))
1731 errno = saverr; /* Restore this */
1740 return 0; /* Success ... */
1745 * Routine to rename() a file
1749 smbc_rename_ctx(SMBCCTX *ocontext,
1765 pstring targetpath1;
1766 pstring targetpath2;
1767 struct cli_state *targetcli1;
1768 struct cli_state *targetcli2;
1769 SMBCSRV *srv = NULL;
1771 if (!ocontext || !ncontext ||
1772 !ocontext->internal || !ncontext->internal ||
1773 !ocontext->internal->_initialized ||
1774 !ncontext->internal->_initialized) {
1776 errno = EINVAL; /* Best I can think of ... */
1781 if (!oname || !nname) {
1788 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1790 smbc_parse_path(ocontext, oname,
1791 workgroup, sizeof(workgroup),
1792 server1, sizeof(server1),
1793 share1, sizeof(share1),
1794 path1, sizeof(path1),
1795 user1, sizeof(user1),
1796 password1, sizeof(password1),
1799 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1801 smbc_parse_path(ncontext, nname,
1803 server2, sizeof(server2),
1804 share2, sizeof(share2),
1805 path2, sizeof(path2),
1806 user2, sizeof(user2),
1807 password2, sizeof(password2),
1810 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1812 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1813 strcmp(user1, user2)) {
1815 /* Can't rename across file systems, or users?? */
1822 srv = smbc_server(ocontext, True,
1823 server1, share1, workgroup, user1, password1);
1830 /*d_printf(">>>rename: resolving %s\n", path1);*/
1831 if (!cli_resolve_path( "", srv->cli, path1, &targetcli1, targetpath1))
1833 d_printf("Could not resolve %s\n", path1);
1836 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1837 /*d_printf(">>>rename: resolving %s\n", path2);*/
1838 if (!cli_resolve_path( "", srv->cli, path2, &targetcli2, targetpath2))
1840 d_printf("Could not resolve %s\n", path2);
1843 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1845 if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1846 strcmp(targetcli1->share, targetcli2->share))
1848 /* can't rename across file systems */
1854 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1855 int eno = smbc_errno(ocontext, targetcli1);
1857 if (eno != EEXIST ||
1858 !cli_unlink(targetcli1, targetpath2) ||
1859 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1867 return 0; /* Success */
1872 * A routine to lseek() a file
1876 smbc_lseek_ctx(SMBCCTX *context,
1882 fstring server, share, user, password;
1883 pstring path, targetpath;
1884 struct cli_state *targetcli;
1886 if (!context || !context->internal ||
1887 !context->internal->_initialized) {
1894 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1904 return -1; /* Can't lseek a dir ... */
1910 file->offset = offset;
1914 file->offset += offset;
1918 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1919 if (smbc_parse_path(context, file->fname,
1921 server, sizeof(server),
1922 share, sizeof(share),
1925 password, sizeof(password),
1932 /*d_printf(">>>lseek: resolving %s\n", path);*/
1933 if (!cli_resolve_path("", file->srv->cli, path,
1934 &targetcli, targetpath))
1936 d_printf("Could not resolve %s\n", path);
1939 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1941 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1942 &size, NULL, NULL, NULL, NULL, NULL))
1944 SMB_OFF_T b_size = size;
1945 if (!cli_getattrE(targetcli, file->cli_fd,
1946 NULL, &b_size, NULL, NULL, NULL))
1953 file->offset = size + offset;
1962 return file->offset;
1967 * Generate an inode number from file name for those things that need it
1971 smbc_inode(SMBCCTX *context,
1975 if (!context || !context->internal ||
1976 !context->internal->_initialized) {
1983 if (!*name) return 2; /* FIXME, why 2 ??? */
1984 return (ino_t)str_checksum(name);
1989 * Routine to put basic stat info into a stat structure ... Used by stat and
1994 smbc_setup_stat(SMBCCTX *context,
2003 if (IS_DOS_DIR(mode)) {
2004 st->st_mode = SMBC_DIR_MODE;
2006 st->st_mode = SMBC_FILE_MODE;
2009 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
2010 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
2011 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
2012 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
2015 #ifdef HAVE_STAT_ST_BLKSIZE
2016 st->st_blksize = 512;
2018 #ifdef HAVE_STAT_ST_BLOCKS
2019 st->st_blocks = (size+511)/512;
2021 st->st_uid = getuid();
2022 st->st_gid = getgid();
2024 if (IS_DOS_DIR(mode)) {
2030 if (st->st_ino == 0) {
2031 st->st_ino = smbc_inode(context, fname);
2034 return True; /* FIXME: Is this needed ? */
2039 * Routine to stat a file given a name
2043 smbc_stat_ctx(SMBCCTX *context,
2054 struct timespec m_time_ts;
2055 struct timespec a_time_ts;
2056 struct timespec c_time_ts;
2061 if (!context || !context->internal ||
2062 !context->internal->_initialized) {
2064 errno = EINVAL; /* Best I can think of ... */
2076 DEBUG(4, ("smbc_stat(%s)\n", fname));
2078 if (smbc_parse_path(context, fname,
2079 workgroup, sizeof(workgroup),
2080 server, sizeof(server),
2081 share, sizeof(share),
2084 password, sizeof(password),
2090 if (user[0] == (char)0) fstrcpy(user, context->user);
2092 srv = smbc_server(context, True,
2093 server, share, workgroup, user, password);
2096 return -1; /* errno set by smbc_server */
2099 if (!smbc_getatr(context, srv, path, &mode, &size,
2100 &c_time_ts, &a_time_ts, &m_time_ts, &ino)) {
2102 errno = smbc_errno(context, srv->cli);
2109 smbc_setup_stat(context, st, path, size, mode);
2111 set_atimespec(st, a_time_ts);
2112 set_ctimespec(st, c_time_ts);
2113 set_mtimespec(st, m_time_ts);
2114 st->st_dev = srv->dev;
2121 * Routine to stat a file given an fd
2125 smbc_fstat_ctx(SMBCCTX *context,
2129 struct timespec c_time_ts;
2130 struct timespec a_time_ts;
2131 struct timespec m_time_ts;
2140 struct cli_state *targetcli;
2143 if (!context || !context->internal ||
2144 !context->internal->_initialized) {
2151 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2160 return context->fstatdir(context, file, st);
2164 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2165 if (smbc_parse_path(context, file->fname,
2167 server, sizeof(server),
2168 share, sizeof(share),
2171 password, sizeof(password),
2177 /*d_printf(">>>fstat: resolving %s\n", path);*/
2178 if (!cli_resolve_path("", file->srv->cli, path,
2179 &targetcli, targetpath))
2181 d_printf("Could not resolve %s\n", path);
2184 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2186 if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2187 NULL, &a_time_ts, &m_time_ts, &c_time_ts, &ino)) {
2188 time_t c_time, a_time, m_time;
2189 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2190 &c_time, &a_time, &m_time)) {
2195 c_time_ts = convert_time_t_to_timespec(c_time);
2196 a_time_ts = convert_time_t_to_timespec(a_time);
2197 m_time_ts = convert_time_t_to_timespec(m_time);
2202 smbc_setup_stat(context, st, file->fname, size, mode);
2204 set_atimespec(st, a_time_ts);
2205 set_ctimespec(st, c_time_ts);
2206 set_mtimespec(st, m_time_ts);
2207 st->st_dev = file->srv->dev;
2214 * Routine to open a directory
2215 * We accept the URL syntax explained in smbc_parse_path(), above.
2219 smbc_remove_dir(SMBCFILE *dir)
2221 struct smbc_dir_list *d,*f;
2228 SAFE_FREE(f->dirent);
2233 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2238 add_dirent(SMBCFILE *dir,
2240 const char *comment,
2243 struct smbc_dirent *dirent;
2245 int name_length = (name == NULL ? 0 : strlen(name));
2246 int comment_len = (comment == NULL ? 0 : strlen(comment));
2249 * Allocate space for the dirent, which must be increased by the
2250 * size of the name and the comment and 1 each for the null terminator.
2253 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2255 dirent = (struct smbc_dirent *)SMB_MALLOC(size);
2259 dir->dir_error = ENOMEM;
2264 ZERO_STRUCTP(dirent);
2266 if (dir->dir_list == NULL) {
2268 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2269 if (!dir->dir_list) {
2272 dir->dir_error = ENOMEM;
2276 ZERO_STRUCTP(dir->dir_list);
2278 dir->dir_end = dir->dir_next = dir->dir_list;
2282 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2284 if (!dir->dir_end->next) {
2287 dir->dir_error = ENOMEM;
2291 ZERO_STRUCTP(dir->dir_end->next);
2293 dir->dir_end = dir->dir_end->next;
2296 dir->dir_end->next = NULL;
2297 dir->dir_end->dirent = dirent;
2299 dirent->smbc_type = type;
2300 dirent->namelen = name_length;
2301 dirent->commentlen = comment_len;
2302 dirent->dirlen = size;
2305 * dirent->namelen + 1 includes the null (no null termination needed)
2306 * Ditto for dirent->commentlen.
2307 * The space for the two null bytes was allocated.
2309 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2310 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2311 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2318 list_unique_wg_fn(const char *name,
2320 const char *comment,
2323 SMBCFILE *dir = (SMBCFILE *)state;
2324 struct smbc_dir_list *dir_list;
2325 struct smbc_dirent *dirent;
2329 dirent_type = dir->dir_type;
2331 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2333 /* An error occurred, what do we do? */
2334 /* FIXME: Add some code here */
2337 /* Point to the one just added */
2338 dirent = dir->dir_end->dirent;
2340 /* See if this was a duplicate */
2341 for (dir_list = dir->dir_list;
2342 dir_list != dir->dir_end;
2343 dir_list = dir_list->next) {
2345 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2346 /* Duplicate. End end of list need to be removed. */
2350 if (do_remove && dir_list->next == dir->dir_end) {
2351 /* Found the end of the list. Remove it. */
2352 dir->dir_end = dir_list;
2353 free(dir_list->next);
2355 dir_list->next = NULL;
2362 list_fn(const char *name,
2364 const char *comment,
2367 SMBCFILE *dir = (SMBCFILE *)state;
2371 * We need to process the type a little ...
2373 * Disk share = 0x00000000
2374 * Print share = 0x00000001
2375 * Comms share = 0x00000002 (obsolete?)
2376 * IPC$ share = 0x00000003
2378 * administrative shares:
2379 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2382 if (dir->dir_type == SMBC_FILE_SHARE) {
2385 case 0 | 0x80000000:
2387 dirent_type = SMBC_FILE_SHARE;
2391 dirent_type = SMBC_PRINTER_SHARE;
2395 dirent_type = SMBC_COMMS_SHARE;
2398 case 3 | 0x80000000:
2400 dirent_type = SMBC_IPC_SHARE;
2404 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2409 dirent_type = dir->dir_type;
2412 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2414 /* An error occurred, what do we do? */
2415 /* FIXME: Add some code here */
2421 dir_list_fn(const char *mnt,
2427 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2428 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2430 /* Handle an error ... */
2432 /* FIXME: Add some code ... */
2439 net_share_enum_rpc(struct cli_state *cli,
2440 void (*fn)(const char *name,
2442 const char *comment,
2449 uint32 info_level = 1;
2450 uint32 preferred_len = 0xffffffff;
2452 SRV_SHARE_INFO_CTR ctr;
2454 fstring comment = "";
2456 struct rpc_pipe_client *pipe_hnd;
2459 /* Open the server service pipe */
2460 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2462 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2466 /* Allocate a context for parsing and for the entries in "ctr" */
2467 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2468 if (mem_ctx == NULL) {
2469 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2470 cli_rpc_pipe_close(pipe_hnd);
2474 /* Issue the NetShareEnum RPC call and retrieve the response */
2475 init_enum_hnd(&enum_hnd, 0);
2476 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2483 /* Was it successful? */
2484 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2485 /* Nope. Go clean up. */
2489 /* For each returned entry... */
2490 for (i = 0; i < ctr.num_entries; i++) {
2492 /* pull out the share name */
2493 rpcstr_pull_unistr2_fstring(
2494 name, &ctr.share.info1[i].info_1_str.uni_netname);
2496 /* pull out the share's comment */
2497 rpcstr_pull_unistr2_fstring(
2498 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2500 /* Get the type value */
2501 type = ctr.share.info1[i].info_1.type;
2503 /* Add this share to the list */
2504 (*fn)(name, type, comment, state);
2508 /* Close the server service pipe */
2509 cli_rpc_pipe_close(pipe_hnd);
2511 /* Free all memory which was allocated for this request */
2512 TALLOC_FREE(mem_ctx);
2514 /* Tell 'em if it worked */
2515 return W_ERROR_IS_OK(result) ? 0 : -1;
2521 smbc_opendir_ctx(SMBCCTX *context,
2524 fstring server, share, user, password, options;
2529 SMBCSRV *srv = NULL;
2530 SMBCFILE *dir = NULL;
2531 struct in_addr rem_ip;
2533 if (!context || !context->internal ||
2534 !context->internal->_initialized) {
2535 DEBUG(4, ("no valid context\n"));
2536 errno = EINVAL + 8192;
2542 DEBUG(4, ("no valid fname\n"));
2543 errno = EINVAL + 8193;
2547 if (smbc_parse_path(context, fname,
2548 workgroup, sizeof(workgroup),
2549 server, sizeof(server),
2550 share, sizeof(share),
2553 password, sizeof(password),
2554 options, sizeof(options))) {
2555 DEBUG(4, ("no valid path\n"));
2556 errno = EINVAL + 8194;
2560 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2561 "path='%s' options='%s'\n",
2562 fname, server, share, path, options));
2564 /* Ensure the options are valid */
2565 if (smbc_check_options(server, share, path, options)) {
2566 DEBUG(4, ("unacceptable options (%s)\n", options));
2567 errno = EINVAL + 8195;
2571 if (user[0] == (char)0) fstrcpy(user, context->user);
2573 dir = SMB_MALLOC_P(SMBCFILE);
2585 dir->fname = SMB_STRDUP(fname);
2589 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2591 if (server[0] == (char)0) {
2596 struct ip_service *ip_list;
2597 struct ip_service server_addr;
2598 struct user_auth_info u_info;
2599 struct cli_state *cli;
2601 if (share[0] != (char)0 || path[0] != (char)0) {
2603 errno = EINVAL + 8196;
2605 SAFE_FREE(dir->fname);
2611 /* Determine how many local master browsers to query */
2612 max_lmb_count = (context->options.browse_max_lmb_count == 0
2614 : context->options.browse_max_lmb_count);
2616 pstrcpy(u_info.username, user);
2617 pstrcpy(u_info.password, password);
2620 * We have server and share and path empty but options
2621 * requesting that we scan all master browsers for their list
2622 * of workgroups/domains. This implies that we must first try
2623 * broadcast queries to find all master browsers, and if that
2624 * doesn't work, then try our other methods which return only
2625 * a single master browser.
2629 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2633 if (!find_master_ip(workgroup, &server_addr.ip)) {
2636 SAFE_FREE(dir->fname);
2643 ip_list = &server_addr;
2647 for (i = 0; i < count && i < max_lmb_count; i++) {
2648 DEBUG(99, ("Found master browser %d of %d: %s\n",
2649 i+1, MAX(count, max_lmb_count),
2650 inet_ntoa(ip_list[i].ip)));
2652 cli = get_ipc_connect_master_ip(&ip_list[i],
2653 workgroup, &u_info);
2654 /* cli == NULL is the master browser refused to talk or
2655 could not be found */
2659 fstrcpy(server, cli->desthost);
2662 DEBUG(4, ("using workgroup %s %s\n",
2663 workgroup, server));
2666 * For each returned master browser IP address, get a
2667 * connection to IPC$ on the server if we do not
2668 * already have one, and determine the
2669 * workgroups/domains that it knows about.
2672 srv = smbc_server(context, True, server, "IPC$",
2673 workgroup, user, password);
2679 dir->dir_type = SMBC_WORKGROUP;
2681 /* Now, list the stuff ... */
2683 if (!cli_NetServerEnum(srv->cli,
2685 SV_TYPE_DOMAIN_ENUM,
2695 * Server not an empty string ... Check the rest and see what
2698 if (*share == '\0') {
2699 if (*path != '\0') {
2701 /* Should not have empty share with path */
2702 errno = EINVAL + 8197;
2704 SAFE_FREE(dir->fname);
2712 * We don't know if <server> is really a server name
2713 * or is a workgroup/domain name. If we already have
2714 * a server structure for it, we'll use it.
2715 * Otherwise, check to see if <server><1D>,
2716 * <server><1B>, or <server><20> translates. We check
2717 * to see if <server> is an IP address first.
2721 * See if we have an existing server. Do not
2722 * establish a connection if one does not already
2725 srv = smbc_server(context, False, server, "IPC$",
2726 workgroup, user, password);
2729 * If no existing server and not an IP addr, look for
2733 !is_ipaddress(server) &&
2734 (resolve_name(server, &rem_ip, 0x1d) || /* LMB */
2735 resolve_name(server, &rem_ip, 0x1b) )) { /* DMB */
2739 dir->dir_type = SMBC_SERVER;
2742 * Get the backup list ...
2744 if (!name_status_find(server, 0, 0,
2745 rem_ip, buserver)) {
2747 DEBUG(0, ("Could not get name of "
2748 "local/domain master browser "
2749 "for server %s\n", server));
2751 SAFE_FREE(dir->fname);
2760 * Get a connection to IPC$ on the server if
2761 * we do not already have one
2763 srv = smbc_server(context, True,
2765 workgroup, user, password);
2767 DEBUG(0, ("got no contact to IPC$\n"));
2769 SAFE_FREE(dir->fname);
2778 /* Now, list the servers ... */
2779 if (!cli_NetServerEnum(srv->cli, server,
2780 0x0000FFFE, list_fn,
2784 SAFE_FREE(dir->fname);
2790 (resolve_name(server, &rem_ip, 0x20))) {
2792 /* If we hadn't found the server, get one now */
2794 srv = smbc_server(context, True,
2802 SAFE_FREE(dir->fname);
2809 dir->dir_type = SMBC_FILE_SHARE;
2812 /* List the shares ... */
2814 if (net_share_enum_rpc(
2817 (void *) dir) < 0 &&
2823 errno = cli_errno(srv->cli);
2825 SAFE_FREE(dir->fname);
2832 /* Neither the workgroup nor server exists */
2833 errno = ECONNREFUSED;
2835 SAFE_FREE(dir->fname);
2844 * The server and share are specified ... work from
2848 struct cli_state *targetcli;
2850 /* We connect to the server and list the directory */
2851 dir->dir_type = SMBC_FILE_SHARE;
2853 srv = smbc_server(context, True, server, share,
2854 workgroup, user, password);
2859 SAFE_FREE(dir->fname);
2868 /* Now, list the files ... */
2870 p = path + strlen(path);
2871 pstrcat(path, "\\*");
2873 if (!cli_resolve_path("", srv->cli, path,
2874 &targetcli, targetpath))
2876 d_printf("Could not resolve %s\n", path);
2878 SAFE_FREE(dir->fname);
2884 if (cli_list(targetcli, targetpath,
2885 aDIR | aSYSTEM | aHIDDEN,
2886 dir_list_fn, (void *)dir) < 0) {
2889 SAFE_FREE(dir->fname);
2892 errno = smbc_errno(context, targetcli);
2894 if (errno == EINVAL) {
2896 * See if they asked to opendir something
2897 * other than a directory. If so, the
2898 * converted error value we got would have
2899 * been EINVAL rather than ENOTDIR.
2901 *p = '\0'; /* restore original path */
2903 if (smbc_getatr(context, srv, path,
2907 ! IS_DOS_DIR(mode)) {
2909 /* It is. Correct the error value */
2921 DLIST_ADD(context->internal->_files, dir);
2927 * Routine to close a directory
2931 smbc_closedir_ctx(SMBCCTX *context,
2935 if (!context || !context->internal ||
2936 !context->internal->_initialized) {
2943 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2950 smbc_remove_dir(dir); /* Clean it up */
2952 DLIST_REMOVE(context->internal->_files, dir);
2956 SAFE_FREE(dir->fname);
2957 SAFE_FREE(dir); /* Free the space too */
2965 smbc_readdir_internal(SMBCCTX * context,
2966 struct smbc_dirent *dest,
2967 struct smbc_dirent *src,
2968 int max_namebuf_len)
2970 if (context->options.urlencode_readdir_entries) {
2972 /* url-encode the name. get back remaining buffer space */
2974 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2976 /* We now know the name length */
2977 dest->namelen = strlen(dest->name);
2979 /* Save the pointer to the beginning of the comment */
2980 dest->comment = dest->name + dest->namelen + 1;
2982 /* Copy the comment */
2983 strncpy(dest->comment, src->comment, max_namebuf_len - 1);
2984 dest->comment[max_namebuf_len - 1] = '\0';
2986 /* Save other fields */
2987 dest->smbc_type = src->smbc_type;
2988 dest->commentlen = strlen(dest->comment);
2989 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2993 /* No encoding. Just copy the entry as is. */
2994 memcpy(dest, src, src->dirlen);
2995 dest->comment = (char *)(&dest->name + src->namelen + 1);
3001 * Routine to get a directory entry
3004 struct smbc_dirent *
3005 smbc_readdir_ctx(SMBCCTX *context,
3009 struct smbc_dirent *dirp, *dirent;
3011 /* Check that all is ok first ... */
3013 if (!context || !context->internal ||
3014 !context->internal->_initialized) {
3017 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
3022 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3025 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
3030 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3033 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
3038 if (!dir->dir_next) {
3042 dirent = dir->dir_next->dirent;
3050 dirp = (struct smbc_dirent *)context->internal->_dirent;
3051 maxlen = (sizeof(context->internal->_dirent) -
3052 sizeof(struct smbc_dirent));
3054 smbc_readdir_internal(context, dirp, dirent, maxlen);
3056 dir->dir_next = dir->dir_next->next;
3062 * Routine to get directory entries
3066 smbc_getdents_ctx(SMBCCTX *context,
3068 struct smbc_dirent *dirp,
3074 char *ndir = (char *)dirp;
3075 struct smbc_dir_list *dirlist;
3077 /* Check that all is ok first ... */
3079 if (!context || !context->internal ||
3080 !context->internal->_initialized) {
3087 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3094 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3102 * Now, retrieve the number of entries that will fit in what was passed
3103 * We have to figure out if the info is in the list, or we need to
3104 * send a request to the server to get the info.
3107 while ((dirlist = dir->dir_next)) {
3108 struct smbc_dirent *dirent;
3110 if (!dirlist->dirent) {
3112 errno = ENOENT; /* Bad error */
3117 /* Do urlencoding of next entry, if so selected */
3118 dirent = (struct smbc_dirent *)context->internal->_dirent;
3119 maxlen = (sizeof(context->internal->_dirent) -
3120 sizeof(struct smbc_dirent));
3121 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3123 reqd = dirent->dirlen;
3127 if (rem < count) { /* We managed to copy something */
3133 else { /* Nothing copied ... */
3135 errno = EINVAL; /* Not enough space ... */
3142 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3144 ((struct smbc_dirent *)ndir)->comment =
3145 (char *)(&((struct smbc_dirent *)ndir)->name +
3153 dir->dir_next = dirlist = dirlist -> next;
3164 * Routine to create a directory ...
3168 smbc_mkdir_ctx(SMBCCTX *context,
3178 pstring path, targetpath;
3179 struct cli_state *targetcli;
3181 if (!context || !context->internal ||
3182 !context->internal->_initialized) {
3196 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3198 if (smbc_parse_path(context, fname,
3199 workgroup, sizeof(workgroup),
3200 server, sizeof(server),
3201 share, sizeof(share),
3204 password, sizeof(password),
3210 if (user[0] == (char)0) fstrcpy(user, context->user);
3212 srv = smbc_server(context, True,
3213 server, share, workgroup, user, password);
3217 return -1; /* errno set by smbc_server */
3221 /*d_printf(">>>mkdir: resolving %s\n", path);*/
3222 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
3224 d_printf("Could not resolve %s\n", path);
3227 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3229 if (!cli_mkdir(targetcli, targetpath)) {
3231 errno = smbc_errno(context, targetcli);
3241 * Our list function simply checks to see if a directory is not empty
3244 static int smbc_rmdir_dirempty = True;
3247 rmdir_list_fn(const char *mnt,
3252 if (strncmp(finfo->name, ".", 1) != 0 &&
3253 strncmp(finfo->name, "..", 2) != 0) {
3255 smbc_rmdir_dirempty = False;
3260 * Routine to remove a directory
3264 smbc_rmdir_ctx(SMBCCTX *context,
3275 struct cli_state *targetcli;
3277 if (!context || !context->internal ||
3278 !context->internal->_initialized) {
3292 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3294 if (smbc_parse_path(context, fname,
3295 workgroup, sizeof(workgroup),
3296 server, sizeof(server),
3297 share, sizeof(share),
3300 password, sizeof(password),
3307 if (user[0] == (char)0) fstrcpy(user, context->user);
3309 srv = smbc_server(context, True,
3310 server, share, workgroup, user, password);
3314 return -1; /* errno set by smbc_server */
3318 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3319 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
3321 d_printf("Could not resolve %s\n", path);
3324 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3327 if (!cli_rmdir(targetcli, targetpath)) {
3329 errno = smbc_errno(context, targetcli);
3331 if (errno == EACCES) { /* Check if the dir empty or not */
3333 /* Local storage to avoid buffer overflows */
3336 smbc_rmdir_dirempty = True; /* Make this so ... */
3338 pstrcpy(lpath, targetpath);
3339 pstrcat(lpath, "\\*");
3341 if (cli_list(targetcli, lpath,
3342 aDIR | aSYSTEM | aHIDDEN,
3343 rmdir_list_fn, NULL) < 0) {
3345 /* Fix errno to ignore latest error ... */
3346 DEBUG(5, ("smbc_rmdir: "
3347 "cli_list returned an error: %d\n",
3348 smbc_errno(context, targetcli)));
3353 if (smbc_rmdir_dirempty)
3369 * Routine to return the current directory position
3373 smbc_telldir_ctx(SMBCCTX *context,
3376 off_t ret_val; /* Squash warnings about cast */
3378 if (!context || !context->internal ||
3379 !context->internal->_initialized) {
3386 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3393 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3401 * We return the pointer here as the offset
3403 ret_val = (off_t)(long)dir->dir_next;
3409 * A routine to run down the list and see if the entry is OK
3412 struct smbc_dir_list *
3413 smbc_check_dir_ent(struct smbc_dir_list *list,
3414 struct smbc_dirent *dirent)
3417 /* Run down the list looking for what we want */
3421 struct smbc_dir_list *tmp = list;
3425 if (tmp->dirent == dirent)
3434 return NULL; /* Not found, or an error */
3440 * Routine to seek on a directory
3444 smbc_lseekdir_ctx(SMBCCTX *context,
3448 long int l_offset = offset; /* Handle problems of size */
3449 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3450 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3452 if (!context || !context->internal ||
3453 !context->internal->_initialized) {
3460 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3467 /* Now, check what we were passed and see if it is OK ... */
3469 if (dirent == NULL) { /* Seek to the begining of the list */
3471 dir->dir_next = dir->dir_list;
3476 /* Now, run down the list and make sure that the entry is OK */
3477 /* This may need to be changed if we change the format of the list */
3479 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3481 errno = EINVAL; /* Bad entry */
3486 dir->dir_next = list_ent;
3493 * Routine to fstat a dir
3497 smbc_fstatdir_ctx(SMBCCTX *context,
3502 if (!context || !context->internal ||
3503 !context->internal->_initialized) {
3510 /* No code yet ... */
3517 smbc_chmod_ctx(SMBCCTX *context,
3530 if (!context || !context->internal ||
3531 !context->internal->_initialized) {
3533 errno = EINVAL; /* Best I can think of ... */
3545 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3547 if (smbc_parse_path(context, fname,
3548 workgroup, sizeof(workgroup),
3549 server, sizeof(server),
3550 share, sizeof(share),
3553 password, sizeof(password),
3559 if (user[0] == (char)0) fstrcpy(user, context->user);
3561 srv = smbc_server(context, True,
3562 server, share, workgroup, user, password);
3565 return -1; /* errno set by smbc_server */
3570 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3571 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3572 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3573 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3575 if (!cli_setatr(srv->cli, path, mode, 0)) {
3576 errno = smbc_errno(context, srv->cli);
3584 smbc_utimes_ctx(SMBCCTX *context,
3586 struct timeval *tbuf)
3598 if (!context || !context->internal ||
3599 !context->internal->_initialized) {
3601 errno = EINVAL; /* Best I can think of ... */
3614 a_time = m_time = time(NULL);
3616 a_time = tbuf[0].tv_sec;
3617 m_time = tbuf[1].tv_sec;
3626 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf) - 1);
3627 atimebuf[sizeof(atimebuf) - 1] = '\0';
3628 if ((p = strchr(atimebuf, '\n')) != NULL) {
3632 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf) - 1);
3633 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3634 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3638 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3639 fname, atimebuf, mtimebuf);
3642 if (smbc_parse_path(context, fname,
3643 workgroup, sizeof(workgroup),
3644 server, sizeof(server),
3645 share, sizeof(share),
3648 password, sizeof(password),
3654 if (user[0] == (char)0) fstrcpy(user, context->user);
3656 srv = smbc_server(context, True,
3657 server, share, workgroup, user, password);
3660 return -1; /* errno set by smbc_server */
3663 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3664 return -1; /* errno set by smbc_setatr */
3671 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3672 However NT4 gives a "The information may have been modified by a
3673 computer running Windows NT 5.0" if denied ACEs do not appear before
3677 ace_compare(SEC_ACE *ace1,
3680 if (sec_ace_equal(ace1, ace2))
3683 if (ace1->type != ace2->type)
3684 return ace2->type - ace1->type;
3686 if (sid_compare(&ace1->trustee, &ace2->trustee))
3687 return sid_compare(&ace1->trustee, &ace2->trustee);
3689 if (ace1->flags != ace2->flags)
3690 return ace1->flags - ace2->flags;
3692 if (ace1->info.mask != ace2->info.mask)
3693 return ace1->info.mask - ace2->info.mask;
3695 if (ace1->size != ace2->size)
3696 return ace1->size - ace2->size;
3698 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3703 sort_acl(SEC_ACL *the_acl)
3706 if (!the_acl) return;
3708 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]),
3709 QSORT_CAST ace_compare);
3711 for (i=1;i<the_acl->num_aces;) {
3712 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3714 for (j=i; j<the_acl->num_aces-1; j++) {
3715 the_acl->ace[j] = the_acl->ace[j+1];
3717 the_acl->num_aces--;
3724 /* convert a SID to a string, either numeric or username/group */
3726 convert_sid_to_string(struct cli_state *ipc_cli,
3732 char **domains = NULL;
3733 char **names = NULL;
3734 enum SID_NAME_USE *types = NULL;
3735 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3736 sid_to_string(str, sid);
3739 return; /* no lookup desired */
3746 /* Ask LSA to convert the sid to a name */
3748 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3749 pol, 1, sid, &domains,
3751 !domains || !domains[0] || !names || !names[0]) {
3757 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3758 domains[0], lp_winbind_separator(),
3762 /* convert a string to a SID, either numeric or username/group */
3764 convert_string_to_sid(struct cli_state *ipc_cli,
3770 enum SID_NAME_USE *types = NULL;
3771 DOM_SID *sids = NULL;
3773 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3780 if (strncmp(str, "S-", 2) == 0) {
3781 return string_to_sid(sid, str);
3788 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3789 pol, 1, &str, NULL, &sids,
3795 sid_copy(sid, &sids[0]);
3802 /* parse an ACE in the same format as print_ace() */
3804 parse_ace(struct cli_state *ipc_cli,
3814 unsigned int aflags;
3818 const struct perm_value *v;
3824 /* These values discovered by inspection */
3825 static const struct perm_value special_values[] = {
3826 { "R", 0x00120089 },
3827 { "W", 0x00120116 },
3828 { "X", 0x001200a0 },
3829 { "D", 0x00010000 },
3830 { "P", 0x00040000 },
3831 { "O", 0x00080000 },
3835 static const struct perm_value standard_values[] = {
3836 { "READ", 0x001200a9 },
3837 { "CHANGE", 0x001301bf },
3838 { "FULL", 0x001f01ff },
3844 p = strchr_m(str,':');
3845 if (!p) return False;
3848 /* Try to parse numeric form */
3850 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3851 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3855 /* Try to parse text form */
3857 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3862 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3866 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3867 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3868 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3869 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3874 /* Only numeric form accepted for flags at present */
3876 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3877 sscanf(tok, "%i", &aflags))) {
3881 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3885 if (strncmp(tok, "0x", 2) == 0) {
3886 if (sscanf(tok, "%i", &amask) != 1) {
3892 for (v = standard_values; v->perm; v++) {
3893 if (strcmp(tok, v->perm) == 0) {
3904 for (v = special_values; v->perm; v++) {
3905 if (v->perm[0] == *p) {
3911 if (!found) return False;
3921 init_sec_ace(ace, &sid, atype, mask, aflags);
3925 /* add an ACE to a list of ACEs in a SEC_ACL */
3927 add_ace(SEC_ACL **the_acl,
3935 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3939 if ((aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces)) == NULL) {
3942 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3943 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3944 newacl = make_sec_acl(ctx, (*the_acl)->revision,
3945 1+(*the_acl)->num_aces, aces);
3947 (*the_acl) = newacl;
3952 /* parse a ascii version of a security descriptor */
3954 sec_desc_parse(TALLOC_CTX *ctx,
3955 struct cli_state *ipc_cli,
3960 const char *p = str;
3962 SEC_DESC *ret = NULL;
3964 DOM_SID *grp_sid=NULL;
3965 DOM_SID *owner_sid=NULL;
3969 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3971 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3972 revision = strtol(tok+9, NULL, 16);
3976 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3978 DEBUG(5, ("OWNER specified more than once!\n"));
3981 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3983 !convert_string_to_sid(ipc_cli, pol,
3985 owner_sid, tok+6)) {
3986 DEBUG(5, ("Failed to parse owner sid\n"));
3992 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3994 DEBUG(5, ("OWNER specified more than once!\n"));
3997 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3999 !convert_string_to_sid(ipc_cli, pol,
4001 owner_sid, tok+7)) {
4002 DEBUG(5, ("Failed to parse owner sid\n"));
4008 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
4010 DEBUG(5, ("GROUP specified more than once!\n"));
4013 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4015 !convert_string_to_sid(ipc_cli, pol,
4018 DEBUG(5, ("Failed to parse group sid\n"));
4024 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
4026 DEBUG(5, ("GROUP specified more than once!\n"));
4029 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4031 !convert_string_to_sid(ipc_cli, pol,
4034 DEBUG(5, ("Failed to parse group sid\n"));
4040 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
4042 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
4043 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4046 if(!add_ace(&dacl, &ace, ctx)) {
4047 DEBUG(5, ("Failed to add ACL %s\n", tok));
4053 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
4055 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
4056 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4059 if(!add_ace(&dacl, &ace, ctx)) {
4060 DEBUG(5, ("Failed to add ACL %s\n", tok));
4066 DEBUG(5, ("Failed to parse security descriptor\n"));
4070 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
4071 owner_sid, grp_sid, NULL, dacl, &sd_size);
4075 SAFE_FREE(owner_sid);
4081 /* Obtain the current dos attributes */
4082 static DOS_ATTR_DESC *
4083 dos_attr_query(SMBCCTX *context,
4085 const char *filename,
4088 struct timespec m_time_ts, a_time_ts, c_time_ts;
4091 SMB_INO_T inode = 0;
4094 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
4100 /* Obtain the DOS attributes */
4101 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
4103 &c_time_ts, &a_time_ts, &m_time_ts, &inode)) {
4105 errno = smbc_errno(context, srv->cli);
4106 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
4113 ret->a_time = convert_timespec_to_time_t(a_time_ts);
4114 ret->c_time = convert_timespec_to_time_t(c_time_ts);
4115 ret->m_time = convert_timespec_to_time_t(m_time_ts);
4122 /* parse a ascii version of a security descriptor */
4124 dos_attr_parse(SMBCCTX *context,
4129 const char *p = str;
4132 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4134 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
4135 dad->mode = strtol(tok+5, NULL, 16);
4139 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4140 dad->size = (SMB_OFF_T)atof(tok+5);
4144 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
4145 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
4149 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
4150 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
4154 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
4155 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
4159 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4160 dad->inode = (SMB_INO_T)atof(tok+6);
4166 /*****************************************************
4167 Retrieve the acls for a file.
4168 *******************************************************/
4171 cacl_get(SMBCCTX *context,
4174 struct cli_state *ipc_cli,
4190 BOOL exclude_nt_revision = False;
4191 BOOL exclude_nt_owner = False;
4192 BOOL exclude_nt_group = False;
4193 BOOL exclude_nt_acl = False;
4194 BOOL exclude_dos_mode = False;
4195 BOOL exclude_dos_size = False;
4196 BOOL exclude_dos_ctime = False;
4197 BOOL exclude_dos_atime = False;
4198 BOOL exclude_dos_mtime = False;
4199 BOOL exclude_dos_inode = False;
4200 BOOL numeric = True;
4201 BOOL determine_size = (bufsize == 0);
4205 fstring name_sandbox;
4209 struct timespec m_time_ts, a_time_ts, c_time_ts;
4210 time_t m_time = (time_t)0, a_time = (time_t)0, c_time = (time_t)0;
4214 struct cli_state *cli = srv->cli;
4216 /* Copy name so we can strip off exclusions (if any are specified) */
4217 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4219 /* Ensure name is null terminated */
4220 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4222 /* Play in the sandbox */
4223 name = name_sandbox;
4225 /* If there are any exclusions, point to them and mask them from name */
4226 if ((pExclude = strchr(name, '!')) != NULL)
4231 all = (StrnCaseCmp(name, "system.*", 8) == 0);
4232 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4233 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4234 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4235 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4236 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4237 numeric = (* (name + strlen(name) - 1) != '+');
4239 /* Look for exclusions from "all" requests */
4240 if (all || all_nt || all_dos) {
4242 /* Exclusions are delimited by '!' */
4245 pExclude = (p == NULL ? NULL : p + 1)) {
4247 /* Find end of this exclusion name */
4248 if ((p = strchr(pExclude, '!')) != NULL)
4253 /* Which exclusion name is this? */
4254 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4255 exclude_nt_revision = True;
4257 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4258 exclude_nt_owner = True;
4260 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4261 exclude_nt_group = True;
4263 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4264 exclude_nt_acl = True;
4266 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4267 exclude_dos_mode = True;
4269 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4270 exclude_dos_size = True;
4272 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
4273 exclude_dos_ctime = True;
4275 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
4276 exclude_dos_atime = True;
4278 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
4279 exclude_dos_mtime = True;
4281 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4282 exclude_dos_inode = True;
4285 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4296 * If we are (possibly) talking to an NT or new system and some NT
4297 * attributes have been requested...
4299 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4300 /* Point to the portion after "system.nt_sec_desc." */
4301 name += 19; /* if (all) this will be invalid but unused */
4303 /* ... then obtain any NT attributes which were requested */
4304 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4307 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4308 filename, cli_errstr(cli)));
4313 sd = cli_query_secdesc(cli, fnum, ctx);
4317 ("cacl_get Failed to query old descriptor\n"));
4322 cli_close(cli, fnum);
4324 if (! exclude_nt_revision) {
4325 if (all || all_nt) {
4326 if (determine_size) {
4327 p = talloc_asprintf(ctx,
4336 n = snprintf(buf, bufsize,
4340 } else if (StrCaseCmp(name, "revision") == 0) {
4341 if (determine_size) {
4342 p = talloc_asprintf(ctx, "%d",
4350 n = snprintf(buf, bufsize, "%d",
4355 if (!determine_size && n > bufsize) {
4364 if (! exclude_nt_owner) {
4365 /* Get owner and group sid */
4366 if (sd->owner_sid) {
4367 convert_sid_to_string(ipc_cli, pol,
4372 fstrcpy(sidstr, "");
4375 if (all || all_nt) {
4376 if (determine_size) {
4377 p = talloc_asprintf(ctx, ",OWNER:%s",
4385 n = snprintf(buf, bufsize,
4386 ",OWNER:%s", sidstr);
4388 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4389 if (determine_size) {
4390 p = talloc_asprintf(ctx, "%s", sidstr);
4397 n = snprintf(buf, bufsize, "%s",
4402 if (!determine_size && n > bufsize) {
4411 if (! exclude_nt_group) {
4413 convert_sid_to_string(ipc_cli, pol,
4417 fstrcpy(sidstr, "");
4420 if (all || all_nt) {
4421 if (determine_size) {
4422 p = talloc_asprintf(ctx, ",GROUP:%s",
4430 n = snprintf(buf, bufsize,
4431 ",GROUP:%s", sidstr);
4433 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4434 if (determine_size) {
4435 p = talloc_asprintf(ctx, "%s", sidstr);
4442 n = snprintf(buf, bufsize,
4447 if (!determine_size && n > bufsize) {
4456 if (! exclude_nt_acl) {
4457 /* Add aces to value buffer */
4458 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4460 SEC_ACE *ace = &sd->dacl->ace[i];
4461 convert_sid_to_string(ipc_cli, pol,
4465 if (all || all_nt) {
4466 if (determine_size) {
4467 p = talloc_asprintf(
4483 ",ACL:%s:%d/%d/0x%08x",
4489 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4490 StrCaseCmp(name+3, sidstr) == 0) ||
4491 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4492 StrCaseCmp(name+4, sidstr) == 0)) {
4493 if (determine_size) {
4494 p = talloc_asprintf(
4506 n = snprintf(buf, bufsize,
4512 } else if (all_nt_acls) {
4513 if (determine_size) {
4514 p = talloc_asprintf(
4516 "%s%s:%d/%d/0x%08x",
4528 n = snprintf(buf, bufsize,
4529 "%s%s:%d/%d/0x%08x",
4547 /* Restore name pointer to its original value */
4551 if (all || some_dos) {
4552 /* Point to the portion after "system.dos_attr." */
4553 name += 16; /* if (all) this will be invalid but unused */
4555 /* Obtain the DOS attributes */
4556 if (!smbc_getatr(context, srv, filename, &mode, &size,
4557 &c_time_ts, &a_time_ts, &m_time_ts, &ino)) {
4559 errno = smbc_errno(context, srv->cli);
4563 c_time = convert_timespec_to_time_t(c_time_ts);
4564 a_time = convert_timespec_to_time_t(a_time_ts);
4565 m_time = convert_timespec_to_time_t(m_time_ts);
4567 if (! exclude_dos_mode) {
4568 if (all || all_dos) {
4569 if (determine_size) {
4570 p = talloc_asprintf(ctx,
4583 n = snprintf(buf, bufsize,
4591 } else if (StrCaseCmp(name, "mode") == 0) {
4592 if (determine_size) {
4593 p = talloc_asprintf(ctx, "0x%x", mode);
4600 n = snprintf(buf, bufsize,
4605 if (!determine_size && n > bufsize) {
4614 if (! exclude_dos_size) {
4615 if (all || all_dos) {
4616 if (determine_size) {
4617 p = talloc_asprintf(
4627 n = snprintf(buf, bufsize,
4631 } else if (StrCaseCmp(name, "size") == 0) {
4632 if (determine_size) {
4633 p = talloc_asprintf(
4643 n = snprintf(buf, bufsize,
4649 if (!determine_size && n > bufsize) {
4658 if (! exclude_dos_ctime) {
4659 if (all || all_dos) {
4660 if (determine_size) {
4661 p = talloc_asprintf(ctx,
4670 n = snprintf(buf, bufsize,
4671 ",C_TIME:%lu", c_time);
4673 } else if (StrCaseCmp(name, "c_time") == 0) {
4674 if (determine_size) {
4675 p = talloc_asprintf(ctx, "%lu", c_time);
4682 n = snprintf(buf, bufsize,
4687 if (!determine_size && n > bufsize) {
4696 if (! exclude_dos_atime) {
4697 if (all || all_dos) {
4698 if (determine_size) {
4699 p = talloc_asprintf(ctx,
4708 n = snprintf(buf, bufsize,
4709 ",A_TIME:%lu", a_time);
4711 } else if (StrCaseCmp(name, "a_time") == 0) {
4712 if (determine_size) {
4713 p = talloc_asprintf(ctx, "%lu", a_time);
4720 n = snprintf(buf, bufsize,
4725 if (!determine_size && n > bufsize) {
4734 if (! exclude_dos_mtime) {
4735 if (all || all_dos) {
4736 if (determine_size) {
4737 p = talloc_asprintf(ctx,
4746 n = snprintf(buf, bufsize,
4747 ",M_TIME:%lu", m_time);
4749 } else if (StrCaseCmp(name, "m_time") == 0) {
4750 if (determine_size) {
4751 p = talloc_asprintf(ctx, "%lu", m_time);
4758 n = snprintf(buf, bufsize,
4763 if (!determine_size && n > bufsize) {
4772 if (! exclude_dos_inode) {
4773 if (all || all_dos) {
4774 if (determine_size) {
4775 p = talloc_asprintf(
4785 n = snprintf(buf, bufsize,
4789 } else if (StrCaseCmp(name, "inode") == 0) {
4790 if (determine_size) {
4791 p = talloc_asprintf(
4801 n = snprintf(buf, bufsize,
4807 if (!determine_size && n > bufsize) {
4816 /* Restore name pointer to its original value */
4829 /*****************************************************
4830 set the ACLs on a file given an ascii description
4831 *******************************************************/
4833 cacl_set(TALLOC_CTX *ctx,
4834 struct cli_state *cli,
4835 struct cli_state *ipc_cli,
4837 const char *filename,
4838 const char *the_acl,
4844 SEC_DESC *sd = NULL, *old;
4845 SEC_ACL *dacl = NULL;
4846 DOM_SID *owner_sid = NULL;
4847 DOM_SID *grp_sid = NULL;
4852 BOOL numeric = True;
4854 /* the_acl will be null for REMOVE_ALL operations */
4856 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4860 /* if this is to set the entire ACL... */
4861 if (*the_acl == '*') {
4862 /* ... then increment past the first colon */
4866 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4867 CONST_DISCARD(char *, the_acl));
4875 /* SMBC_XATTR_MODE_REMOVE_ALL is the only caller
4876 that doesn't deref sd */
4878 if (!sd && (mode != SMBC_XATTR_MODE_REMOVE_ALL)) {
4883 /* The desired access below is the only one I could find that works
4884 with NT4, W2KP and Samba */
4886 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4889 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4890 filename, cli_errstr(cli)));
4895 old = cli_query_secdesc(cli, fnum, ctx);
4898 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4903 cli_close(cli, fnum);
4906 case SMBC_XATTR_MODE_REMOVE_ALL:
4907 old->dacl->num_aces = 0;
4908 SAFE_FREE(old->dacl->ace);
4909 SAFE_FREE(old->dacl);
4914 case SMBC_XATTR_MODE_REMOVE:
4915 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4918 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4919 if (sec_ace_equal(&sd->dacl->ace[i],
4920 &old->dacl->ace[j])) {
4922 for (k=j; k<old->dacl->num_aces-1;k++) {
4924 old->dacl->ace[k+1];
4926 old->dacl->num_aces--;
4927 if (old->dacl->num_aces == 0) {
4928 SAFE_FREE(old->dacl->ace);
4929 SAFE_FREE(old->dacl);
4946 case SMBC_XATTR_MODE_ADD:
4947 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4950 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4951 if (sid_equal(&sd->dacl->ace[i].trustee,
4952 &old->dacl->ace[j].trustee)) {
4953 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4958 old->dacl->ace[j] = sd->dacl->ace[i];
4964 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4970 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4971 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4977 case SMBC_XATTR_MODE_SET:
4979 owner_sid = old->owner_sid;
4980 grp_sid = old->grp_sid;
4984 case SMBC_XATTR_MODE_CHOWN:
4985 owner_sid = sd->owner_sid;
4988 case SMBC_XATTR_MODE_CHGRP:
4989 grp_sid = sd->grp_sid;
4993 /* Denied ACE entries must come before allowed ones */
4994 sort_acl(old->dacl);
4996 /* Create new security descriptor and set it */
4997 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4998 owner_sid, grp_sid, NULL, dacl, &sd_size);
5000 fnum = cli_nt_create(cli, filename,
5001 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
5004 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5005 filename, cli_errstr(cli)));
5010 if (!cli_set_secdesc(cli, fnum, sd)) {
5011 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
5018 cli_close(cli, fnum);
5029 smbc_setxattr_ctx(SMBCCTX *context,
5050 if (!context || !context->internal ||
5051 !context->internal->_initialized) {
5053 errno = EINVAL; /* Best I can think of ... */
5065 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
5066 fname, name, (int) size, (const char*)value));
5068 if (smbc_parse_path(context, fname,
5069 workgroup, sizeof(workgroup),
5070 server, sizeof(server),
5071 share, sizeof(share),
5074 password, sizeof(password),
5080 if (user[0] == (char)0) fstrcpy(user, context->user);
5082 srv = smbc_server(context, True,
5083 server, share, workgroup, user, password);
5085 return -1; /* errno set by smbc_server */
5088 if (! srv->no_nt_session) {
5089 ipc_srv = smbc_attr_server(context, server, share,
5090 workgroup, user, password,
5092 srv->no_nt_session = True;
5097 ctx = talloc_init("smbc_setxattr");
5104 * Are they asking to set the entire set of known attributes?
5106 if (StrCaseCmp(name, "system.*") == 0 ||
5107 StrCaseCmp(name, "system.*+") == 0) {
5110 talloc_asprintf(ctx, "%s:%s",
5111 name+7, (const char *) value);
5119 ret = cacl_set(ctx, srv->cli,
5120 ipc_srv->cli, &pol, path,
5123 ? SMBC_XATTR_MODE_SET
5124 : SMBC_XATTR_MODE_ADD),
5130 /* get a DOS Attribute Descriptor with current attributes */
5131 dad = dos_attr_query(context, ctx, path, srv);
5133 /* Overwrite old with new, using what was provided */
5134 dos_attr_parse(context, dad, srv, namevalue);
5136 /* Set the new DOS attributes */
5137 if (! smbc_setatr(context, srv, path,
5143 /* cause failure if NT failed too */
5148 /* we only fail if both NT and DOS sets failed */
5149 if (ret < 0 && ! dad) {
5150 ret = -1; /* in case dad was null */
5156 talloc_destroy(ctx);
5161 * Are they asking to set an access control element or to set
5162 * the entire access control list?
5164 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5165 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5166 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5167 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5168 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5172 talloc_asprintf(ctx, "%s:%s",
5173 name+19, (const char *) value);
5176 ret = -1; /* errno set by smbc_server() */
5178 else if (! namevalue) {
5182 ret = cacl_set(ctx, srv->cli,
5183 ipc_srv->cli, &pol, path,
5186 ? SMBC_XATTR_MODE_SET
5187 : SMBC_XATTR_MODE_ADD),
5190 talloc_destroy(ctx);
5195 * Are they asking to set the owner?
5197 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5198 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5202 talloc_asprintf(ctx, "%s:%s",
5203 name+19, (const char *) value);
5207 ret = -1; /* errno set by smbc_server() */
5209 else if (! namevalue) {
5213 ret = cacl_set(ctx, srv->cli,
5214 ipc_srv->cli, &pol, path,
5215 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5217 talloc_destroy(ctx);
5222 * Are they asking to set the group?
5224 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5225 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5229 talloc_asprintf(ctx, "%s:%s",
5230 name+19, (const char *) value);
5233 /* errno set by smbc_server() */
5236 else if (! namevalue) {
5240 ret = cacl_set(ctx, srv->cli,
5241 ipc_srv->cli, &pol, path,
5242 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5244 talloc_destroy(ctx);
5249 * Are they asking to set a DOS attribute?
5251 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5252 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5253 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5254 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5255 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
5257 /* get a DOS Attribute Descriptor with current attributes */
5258 dad = dos_attr_query(context, ctx, path, srv);
5261 talloc_asprintf(ctx, "%s:%s",
5262 name+16, (const char *) value);
5267 /* Overwrite old with provided new params */
5268 dos_attr_parse(context, dad, srv, namevalue);
5270 /* Set the new DOS attributes */
5271 ret2 = smbc_setatr(context, srv, path,
5277 /* ret2 has True (success) / False (failure) */
5288 talloc_destroy(ctx);
5292 /* Unsupported attribute name */
5293 talloc_destroy(ctx);
5299 smbc_getxattr_ctx(SMBCCTX *context,
5318 if (!context || !context->internal ||
5319 !context->internal->_initialized) {
5321 errno = EINVAL; /* Best I can think of ... */
5333 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5335 if (smbc_parse_path(context, fname,
5336 workgroup, sizeof(workgroup),
5337 server, sizeof(server),
5338 share, sizeof(share),
5341 password, sizeof(password),
5347 if (user[0] == (char)0) fstrcpy(user, context->user);
5349 srv = smbc_server(context, True,
5350 server, share, workgroup, user, password);
5352 return -1; /* errno set by smbc_server */
5355 if (! srv->no_nt_session) {
5356 ipc_srv = smbc_attr_server(context, server, share,
5357 workgroup, user, password,
5360 srv->no_nt_session = True;
5366 ctx = talloc_init("smbc:getxattr");
5372 /* Are they requesting a supported attribute? */
5373 if (StrCaseCmp(name, "system.*") == 0 ||
5374 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5375 StrCaseCmp(name, "system.*+") == 0 ||
5376 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5377 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5378 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5379 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5380 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5381 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5382 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5383 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5384 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5385 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5386 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5387 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5388 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5389 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5390 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5391 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5392 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5393 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5394 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
5395 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5398 ret = cacl_get(context, ctx, srv,
5399 ipc_srv == NULL ? NULL : ipc_srv->cli,
5401 CONST_DISCARD(char *, name),
5402 CONST_DISCARD(char *, value), size);
5403 if (ret < 0 && errno == 0) {
5404 errno = smbc_errno(context, srv->cli);
5406 talloc_destroy(ctx);
5410 /* Unsupported attribute name */
5411 talloc_destroy(ctx);
5418 smbc_removexattr_ctx(SMBCCTX *context,
5434 if (!context || !context->internal ||
5435 !context->internal->_initialized) {
5437 errno = EINVAL; /* Best I can think of ... */
5449 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5451 if (smbc_parse_path(context, fname,
5452 workgroup, sizeof(workgroup),
5453 server, sizeof(server),
5454 share, sizeof(share),
5457 password, sizeof(password),
5463 if (user[0] == (char)0) fstrcpy(user, context->user);
5465 srv = smbc_server(context, True,
5466 server, share, workgroup, user, password);
5468 return -1; /* errno set by smbc_server */
5471 if (! srv->no_nt_session) {
5472 ipc_srv = smbc_attr_server(context, server, share,
5473 workgroup, user, password,
5475 srv->no_nt_session = True;
5481 return -1; /* errno set by smbc_attr_server */
5484 ctx = talloc_init("smbc_removexattr");
5490 /* Are they asking to set the entire ACL? */
5491 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5492 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5495 ret = cacl_set(ctx, srv->cli,
5496 ipc_srv->cli, &pol, path,
5497 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5498 talloc_destroy(ctx);
5503 * Are they asking to remove one or more spceific security descriptor
5506 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5507 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5508 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5509 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5510 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5511 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5512 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5515 ret = cacl_set(ctx, srv->cli,
5516 ipc_srv->cli, &pol, path,
5517 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5518 talloc_destroy(ctx);
5522 /* Unsupported attribute name */
5523 talloc_destroy(ctx);
5529 smbc_listxattr_ctx(SMBCCTX *context,
5535 * This isn't quite what listxattr() is supposed to do. This returns
5536 * the complete set of attribute names, always, rather than only those
5537 * attribute names which actually exist for a file. Hmmm...
5539 const char supported[] =
5542 "system.nt_sec_desc.revision\0"
5543 "system.nt_sec_desc.owner\0"
5544 "system.nt_sec_desc.owner+\0"
5545 "system.nt_sec_desc.group\0"
5546 "system.nt_sec_desc.group+\0"
5547 "system.nt_sec_desc.acl.*\0"
5548 "system.nt_sec_desc.acl\0"
5549 "system.nt_sec_desc.acl+\0"
5550 "system.nt_sec_desc.*\0"
5551 "system.nt_sec_desc.*+\0"
5552 "system.dos_attr.*\0"
5553 "system.dos_attr.mode\0"
5554 "system.dos_attr.c_time\0"
5555 "system.dos_attr.a_time\0"
5556 "system.dos_attr.m_time\0"
5560 return sizeof(supported);
5563 if (sizeof(supported) > size) {
5568 /* this can't be strcpy() because there are embedded null characters */
5569 memcpy(list, supported, sizeof(supported));
5570 return sizeof(supported);
5575 * Open a print file to be written to by other calls
5579 smbc_open_print_job_ctx(SMBCCTX *context,
5588 if (!context || !context->internal ||
5589 !context->internal->_initialized) {
5603 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5605 if (smbc_parse_path(context, fname,
5607 server, sizeof(server),
5608 share, sizeof(share),
5611 password, sizeof(password),
5617 /* What if the path is empty, or the file exists? */
5619 return context->open(context, fname, O_WRONLY, 666);
5624 * Routine to print a file on a remote server ...
5626 * We open the file, which we assume to be on a remote server, and then
5627 * copy it to a print file on the share specified by printq.
5631 smbc_print_file_ctx(SMBCCTX *c_file,
5643 if (!c_file || !c_file->internal->_initialized || !c_print ||
5644 !c_print->internal->_initialized) {
5651 if (!fname && !printq) {
5658 /* Try to open the file for reading ... */
5660 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5662 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5663 return -1; /* smbc_open sets errno */
5667 /* Now, try to open the printer file for writing */
5669 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5671 saverr = errno; /* Save errno */
5672 c_file->close_fn(c_file, fid1);
5678 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5682 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5685 c_file->close_fn(c_file, fid1);
5686 c_print->close_fn(c_print, fid2);
5695 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5696 c_print->close_fn(c_print, fid2);
5710 * Routine to list print jobs on a printer share ...
5714 smbc_list_print_jobs_ctx(SMBCCTX *context,
5716 smbc_list_print_job_fn fn)
5726 if (!context || !context->internal ||
5727 !context->internal->_initialized) {
5741 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5743 if (smbc_parse_path(context, fname,
5744 workgroup, sizeof(workgroup),
5745 server, sizeof(server),
5746 share, sizeof(share),
5749 password, sizeof(password),
5755 if (user[0] == (char)0) fstrcpy(user, context->user);
5757 srv = smbc_server(context, True,
5758 server, share, workgroup, user, password);
5762 return -1; /* errno set by smbc_server */
5766 if (cli_print_queue(srv->cli,
5767 (void (*)(struct print_job_info *))fn) < 0) {
5769 errno = smbc_errno(context, srv->cli);
5779 * Delete a print job from a remote printer share
5783 smbc_unlink_print_job_ctx(SMBCCTX *context,
5796 if (!context || !context->internal ||
5797 !context->internal->_initialized) {
5811 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5813 if (smbc_parse_path(context, fname,
5814 workgroup, sizeof(workgroup),
5815 server, sizeof(server),
5816 share, sizeof(share),
5819 password, sizeof(password),
5825 if (user[0] == (char)0) fstrcpy(user, context->user);
5827 srv = smbc_server(context, True,
5828 server, share, workgroup, user, password);
5832 return -1; /* errno set by smbc_server */
5836 if ((err = cli_printjob_del(srv->cli, id)) != 0) {
5839 errno = smbc_errno(context, srv->cli);
5840 else if (err == ERRnosuchprintjob)
5851 * Get a new empty handle to fill in with your own info
5854 smbc_new_context(void)
5858 context = SMB_MALLOC_P(SMBCCTX);
5864 ZERO_STRUCTP(context);
5866 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5867 if (!context->internal) {
5873 ZERO_STRUCTP(context->internal);
5876 /* ADD REASONABLE DEFAULTS */
5878 context->timeout = 20000; /* 20 seconds */
5880 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5881 context->options.urlencode_readdir_entries = False;/* backward compat */
5882 context->options.one_share_per_server = False;/* backward compat */
5884 context->open = smbc_open_ctx;
5885 context->creat = smbc_creat_ctx;
5886 context->read = smbc_read_ctx;
5887 context->write = smbc_write_ctx;
5888 context->close_fn = smbc_close_ctx;
5889 context->unlink = smbc_unlink_ctx;
5890 context->rename = smbc_rename_ctx;
5891 context->lseek = smbc_lseek_ctx;
5892 context->stat = smbc_stat_ctx;
5893 context->fstat = smbc_fstat_ctx;
5894 context->opendir = smbc_opendir_ctx;
5895 context->closedir = smbc_closedir_ctx;
5896 context->readdir = smbc_readdir_ctx;
5897 context->getdents = smbc_getdents_ctx;
5898 context->mkdir = smbc_mkdir_ctx;
5899 context->rmdir = smbc_rmdir_ctx;
5900 context->telldir = smbc_telldir_ctx;
5901 context->lseekdir = smbc_lseekdir_ctx;
5902 context->fstatdir = smbc_fstatdir_ctx;
5903 context->chmod = smbc_chmod_ctx;
5904 context->utimes = smbc_utimes_ctx;
5905 context->setxattr = smbc_setxattr_ctx;
5906 context->getxattr = smbc_getxattr_ctx;
5907 context->removexattr = smbc_removexattr_ctx;
5908 context->listxattr = smbc_listxattr_ctx;
5909 context->open_print_job = smbc_open_print_job_ctx;
5910 context->print_file = smbc_print_file_ctx;
5911 context->list_print_jobs = smbc_list_print_jobs_ctx;
5912 context->unlink_print_job = smbc_unlink_print_job_ctx;
5914 context->callbacks.check_server_fn = smbc_check_server;
5915 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5917 smbc_default_cache_functions(context);
5925 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5926 * and thus you'll be leaking memory if not handled properly.
5930 smbc_free_context(SMBCCTX *context,
5940 DEBUG(1,("Performing aggressive shutdown.\n"));
5942 f = context->internal->_files;
5944 context->close_fn(context, f);
5947 context->internal->_files = NULL;
5949 /* First try to remove the servers the nice way. */
5950 if (context->callbacks.purge_cached_fn(context)) {
5953 DEBUG(1, ("Could not purge all servers, "
5954 "Nice way shutdown failed.\n"));
5955 s = context->internal->_servers;
5957 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
5959 cli_shutdown(s->cli);
5960 context->callbacks.remove_cached_srv_fn(context,
5963 DLIST_REMOVE(context->internal->_servers, s);
5967 context->internal->_servers = NULL;
5971 /* This is the polite way */
5972 if (context->callbacks.purge_cached_fn(context)) {
5973 DEBUG(1, ("Could not purge all servers, "
5974 "free_context failed.\n"));
5978 if (context->internal->_servers) {
5979 DEBUG(1, ("Active servers in context, "
5980 "free_context failed.\n"));
5984 if (context->internal->_files) {
5985 DEBUG(1, ("Active files in context, "
5986 "free_context failed.\n"));
5992 /* Things we have to clean up */
5993 SAFE_FREE(context->workgroup);
5994 SAFE_FREE(context->netbios_name);
5995 SAFE_FREE(context->user);
5997 DEBUG(3, ("Context %p succesfully freed\n", context));
5998 SAFE_FREE(context->internal);
6005 * Each time the context structure is changed, we have binary backward
6006 * compatibility issues. Instead of modifying the public portions of the
6007 * context structure to add new options, instead, we put them in the internal
6008 * portion of the context structure and provide a set function for these new
6012 smbc_option_set(SMBCCTX *context,
6014 ... /* option_value */)
6019 smbc_get_auth_data_with_context_fn auth_fn;
6023 va_start(ap, option_name);
6025 if (strcmp(option_name, "debug_to_stderr") == 0) {
6027 * Log to standard error instead of standard output.
6029 option_value.b = (BOOL) va_arg(ap, int);
6030 context->internal->_debug_stderr = option_value.b;
6032 } else if (strcmp(option_name, "debug_to_stderr") == 0) {
6034 * Log to standard error instead of standard output.
6036 * This function used to take a third parameter,
6037 * void *option_value. Since it was a void* and we needed to
6038 * pass a boolean, a boolean value was cast to void* to be
6039 * passed in. Now that we're using a va_list to retrieve the
6040 * parameters, the casting kludge is unnecessary.
6042 * WARNING: DO NOT USE THIS OPTION.
6043 * This option is retained for backward compatibility. New
6044 * applications should use "debug_to_stderr" and properly pass
6045 * in a boolean (int) value.
6047 option_value.v = va_arg(ap, void *);
6048 context->internal->_debug_stderr =
6049 (option_value.v == NULL ? False : True);
6051 } else if (strcmp(option_name, "auth_function") == 0) {
6053 * Use the new-style authentication function which includes
6056 option_value.auth_fn =
6057 va_arg(ap, smbc_get_auth_data_with_context_fn);
6058 context->internal->_auth_fn_with_context =
6059 option_value.auth_fn;
6060 } else if (strcmp(option_name, "user_data") == 0) {
6062 * Save a user data handle which may be retrieved by the user
6063 * with smbc_option_get()
6065 option_value.v = va_arg(ap, void *);
6066 context->internal->_user_data = option_value.v;
6074 * Retrieve the current value of an option
6077 smbc_option_get(SMBCCTX *context,
6080 if (strcmp(option_name, "debug_stderr") == 0) {
6082 * Log to standard error instead of standard output.
6084 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6085 return (void *) (intptr_t) context->internal->_debug_stderr;
6087 return (void *) context->internal->_debug_stderr;
6089 } else if (strcmp(option_name, "auth_function") == 0) {
6091 * Use the new-style authentication function which includes
6094 return (void *) context->internal->_auth_fn_with_context;
6095 } else if (strcmp(option_name, "user_data") == 0) {
6097 * Save a user data handle which may be retrieved by the user
6098 * with smbc_option_get()
6100 return context->internal->_user_data;
6108 * Initialise the library etc
6110 * We accept a struct containing handle information.
6111 * valid values for info->debug from 0 to 100,
6112 * and insist that info->fn must be non-null.
6115 smbc_init_context(SMBCCTX *context)
6122 if (!context || !context->internal) {
6127 /* Do not initialise the same client twice */
6128 if (context->internal->_initialized) {
6132 if ((!context->callbacks.auth_fn &&
6133 !context->internal->_auth_fn_with_context) ||
6134 context->debug < 0 ||
6135 context->debug > 100) {
6142 if (!smbc_initialized) {
6144 * Do some library-wide intializations the first time we get
6147 BOOL conf_loaded = False;
6149 /* Set this to what the user wants */
6150 DEBUGLEVEL = context->debug;
6154 setup_logging("libsmbclient", True);
6155 if (context->internal->_debug_stderr) {
6157 x_setbuf(x_stderr, NULL);
6160 /* Here we would open the smb.conf file if needed ... */
6162 in_client = True; /* FIXME, make a param */
6164 home = getenv("HOME");
6166 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
6167 if (lp_load(conf, True, False, False, True)) {
6170 DEBUG(5, ("Could not load config file: %s\n",
6177 * Well, if that failed, try the dyn_CONFIGFILE
6178 * Which points to the standard locn, and if that
6179 * fails, silently ignore it and use the internal
6183 if (!lp_load(dyn_CONFIGFILE, True, False, False, False)) {
6184 DEBUG(5, ("Could not load config file: %s\n",
6188 * We loaded the global config file. Now lets
6189 * load user-specific modifications to the
6192 slprintf(conf, sizeof(conf),
6193 "%s/.smb/smb.conf.append", home);
6194 if (!lp_load(conf, True, False, False, False)) {
6196 ("Could not append config file: "
6203 load_interfaces(); /* Load the list of interfaces ... */
6205 reopen_logs(); /* Get logging working ... */
6208 * Block SIGPIPE (from lib/util_sock.c: write())
6209 * It is not needed and should not stop execution
6211 BlockSignals(True, SIGPIPE);
6213 /* Done with one-time initialisation */
6214 smbc_initialized = 1;
6218 if (!context->user) {
6220 * FIXME: Is this the best way to get the user info?
6222 user = getenv("USER");
6223 /* walk around as "guest" if no username can be found */
6224 if (!user) context->user = SMB_STRDUP("guest");
6225 else context->user = SMB_STRDUP(user);
6228 if (!context->netbios_name) {
6230 * We try to get our netbios name from the config. If that
6231 * fails we fall back on constructing our netbios name from
6234 if (global_myname()) {
6235 context->netbios_name = SMB_STRDUP(global_myname());
6239 * Hmmm, I want to get hostname as well, but I am too
6240 * lazy for the moment
6243 context->netbios_name = (char *)SMB_MALLOC(17);
6244 if (!context->netbios_name) {
6248 slprintf(context->netbios_name, 16,
6249 "smbc%s%d", context->user, pid);
6253 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
6255 if (!context->workgroup) {
6256 if (lp_workgroup()) {
6257 context->workgroup = SMB_STRDUP(lp_workgroup());
6260 /* TODO: Think about a decent default workgroup */
6261 context->workgroup = SMB_STRDUP("samba");
6265 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
6267 /* shortest timeout is 1 second */
6268 if (context->timeout > 0 && context->timeout < 1000)
6269 context->timeout = 1000;
6272 * FIXME: Should we check the function pointers here?
6275 context->internal->_initialized = True;
6281 /* Return the verion of samba, and thus libsmbclient */
6285 return samba_version_string();