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(&p, userinfo, "@", sizeof(fstring));
364 username[0] = passwd[0] = domain[0] = 0;
366 if (strchr_m(u, ';')) {
368 next_token(&u, domain, ";", sizeof(fstring));
372 if (strchr_m(u, ':')) {
374 next_token(&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);
529 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
531 context->callbacks.remove_cached_srv_fn(context, srv);
539 find_server(SMBCCTX *context,
551 srv = context->callbacks.get_cached_srv_fn(context, server, share,
552 workgroup, username);
554 if (!auth_called && !srv && (!username[0] || !password[0])) {
555 context->callbacks.auth_fn(server, share,
556 workgroup, sizeof(fstring),
557 username, sizeof(fstring),
558 password, sizeof(fstring));
560 * However, smbc_auth_fn may have picked up info relating to
561 * an existing connection, so try for an existing connection
565 goto check_server_cache;
570 if (context->callbacks.check_server_fn(context, srv)) {
572 * This server is no good anymore
573 * Try to remove it and check for more possible
574 * servers in the cache
576 if (context->callbacks.remove_unused_server_fn(context,
579 * We could not remove the server completely,
580 * remove it from the cache so we will not get
581 * it again. It will be removed when the last
582 * file/dir is closed.
584 context->callbacks.remove_cached_srv_fn(context,
589 * Maybe there are more cached connections to this
592 goto check_server_cache;
602 * Connect to a server, possibly on an existing connection
604 * Here, what we want to do is: If the server and username
605 * match an existing connection, reuse that, otherwise, establish a
608 * If we have to create a new connection, call the auth_fn to get the
609 * info we need, unless the username and password were passed in.
613 smbc_server(SMBCCTX *context,
614 BOOL connect_if_not_found,
623 struct nmb_name called, calling;
624 const char *server_n = server;
627 int tried_reverse = 0;
630 const char *username_used;
635 if (server[0] == 0) {
640 /* Look for a cached connection */
641 srv = find_server(context, server, share,
642 workgroup, username, password);
645 * If we found a connection and we're only allowed one share per
648 if (srv && *share != '\0' && context->options.one_share_per_server) {
651 * ... then if there's no current connection to the share,
652 * connect to it. find_server(), or rather the function
653 * pointed to by context->callbacks.get_cached_srv_fn which
654 * was called by find_server(), will have issued a tree
655 * disconnect if the requested share is not the same as the
656 * one that was already connected.
658 if (srv->cli.cnum == (uint16) -1) {
659 /* Ensure we have accurate auth info */
660 context->callbacks.auth_fn(server, share,
661 workgroup, sizeof(fstring),
662 username, sizeof(fstring),
663 password, sizeof(fstring));
665 if (! cli_send_tconX(&srv->cli, share, "?????",
666 password, strlen(password)+1)) {
668 errno = smbc_errno(context, &srv->cli);
669 cli_shutdown(&srv->cli);
670 context->callbacks.remove_cached_srv_fn(context,
676 * Regenerate the dev value since it's based on both
680 srv->dev = (dev_t)(str_checksum(server) ^
681 str_checksum(share));
686 /* If we have a connection... */
689 /* ... then we're done here. Give 'em what they came for. */
693 /* If we're not asked to connect when a connection doesn't exist... */
694 if (! connect_if_not_found) {
695 /* ... then we're done here. */
699 make_nmb_name(&calling, context->netbios_name, 0x0);
700 make_nmb_name(&called , server, 0x20);
702 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
704 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
707 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
711 /* have to open a new connection */
712 if (!cli_initialise(&c)) {
717 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
718 c.use_kerberos = True;
720 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
721 c.fallback_after_kerberos = True;
724 c.timeout = context->timeout;
727 * Force use of port 139 for first try if share is $IPC, empty, or
728 * null, so browse lists can work
730 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
731 port_try_first = 139;
734 port_try_first = 445;
738 c.port = port_try_first;
740 if (!cli_connect(&c, server_n, &ip)) {
742 /* First connection attempt failed. Try alternate port. */
743 c.port = port_try_next;
745 if (!cli_connect(&c, server_n, &ip)) {
752 if (!cli_session_request(&c, &calling, &called)) {
754 if (strcmp(called.name, "*SMBSERVER")) {
755 make_nmb_name(&called , "*SMBSERVER", 0x20);
758 else { /* Try one more time, but ensure we don't loop */
760 /* Only try this if server is an IP address ... */
762 if (is_ipaddress(server) && !tried_reverse) {
764 struct in_addr rem_ip;
766 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
767 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
772 tried_reverse++; /* Yuck */
774 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
775 make_nmb_name(&called, remote_name, 0x20);
786 DEBUG(4,(" session request ok\n"));
788 if (!cli_negprot(&c)) {
794 username_used = username;
796 if (!cli_session_setup(&c, username_used,
797 password, strlen(password),
798 password, strlen(password),
801 /* Failed. Try an anonymous login, if allowed by flags. */
804 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
805 !cli_session_setup(&c, username_used,
816 DEBUG(4,(" session setup ok\n"));
818 if (!cli_send_tconX(&c, share, "?????",
819 password, strlen(password)+1)) {
820 errno = smbc_errno(context, &c);
825 DEBUG(4,(" tconx ok\n"));
828 * Ok, we have got a nice connection
829 * Let's allocate a server structure.
832 srv = SMB_MALLOC_P(SMBCSRV);
840 srv->cli.allocated = False;
841 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
842 srv->no_pathinfo = False;
843 srv->no_pathinfo2 = False;
844 srv->no_nt_session = False;
846 /* now add it to the cache (internal or external) */
847 /* Let the cache function set errno if it wants to */
849 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
850 int saved_errno = errno;
851 DEBUG(3, (" Failed to add server to cache\n"));
859 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
860 server, share, srv));
862 DLIST_ADD(context->internal->_servers, srv);
867 if (!srv) return NULL;
874 * Connect to a server for getting/setting attributes, possibly on an existing
875 * connection. This works similarly to smbc_server().
878 smbc_attr_server(SMBCCTX *context,
887 struct cli_state *ipc_cli;
888 struct rpc_pipe_client *pipe_hnd;
890 SMBCSRV *ipc_srv=NULL;
893 * See if we've already created this special connection. Reference
894 * our "special" share name '*IPC$', which is an impossible real share
895 * name due to the leading asterisk.
897 ipc_srv = find_server(context, server, "*IPC$",
898 workgroup, username, password);
901 /* We didn't find a cached connection. Get the password */
902 if (*password == '\0') {
903 /* ... then retrieve it now. */
904 context->callbacks.auth_fn(server, share,
905 workgroup, sizeof(fstring),
906 username, sizeof(fstring),
907 password, sizeof(fstring));
911 nt_status = cli_full_connection(&ipc_cli,
912 global_myname(), server,
913 &ip, 0, "IPC$", "?????",
917 if (! NT_STATUS_IS_OK(nt_status)) {
918 DEBUG(1,("cli_full_connection failed! (%s)\n",
919 nt_errstr(nt_status)));
924 ipc_srv = SMB_MALLOC_P(SMBCSRV);
927 cli_shutdown(ipc_cli);
931 ZERO_STRUCTP(ipc_srv);
932 ipc_srv->cli = *ipc_cli;
933 ipc_srv->cli.allocated = False;
938 pipe_hnd = cli_rpc_pipe_open_noauth(&ipc_srv->cli,
942 DEBUG(1, ("cli_nt_session_open fail!\n"));
944 cli_shutdown(&ipc_srv->cli);
950 * Some systems don't support
951 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
952 * so we might as well do it too.
955 nt_status = rpccli_lsa_open_policy(
957 ipc_srv->cli.mem_ctx,
959 GENERIC_EXECUTE_ACCESS,
962 if (!NT_STATUS_IS_OK(nt_status)) {
963 errno = smbc_errno(context, &ipc_srv->cli);
964 cli_shutdown(&ipc_srv->cli);
969 /* now add it to the cache (internal or external) */
971 errno = 0; /* let cache function set errno if it likes */
972 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
977 DEBUG(3, (" Failed to add server to cache\n"));
981 cli_shutdown(&ipc_srv->cli);
986 DLIST_ADD(context->internal->_servers, ipc_srv);
993 * Routine to open() a file ...
997 smbc_open_ctx(SMBCCTX *context,
1002 fstring server, share, user, password, workgroup;
1005 struct cli_state *targetcli;
1006 SMBCSRV *srv = NULL;
1007 SMBCFILE *file = NULL;
1010 if (!context || !context->internal ||
1011 !context->internal->_initialized) {
1013 errno = EINVAL; /* Best I can think of ... */
1025 if (smbc_parse_path(context, fname,
1026 workgroup, sizeof(workgroup),
1027 server, sizeof(server),
1028 share, sizeof(share),
1031 password, sizeof(password),
1037 if (user[0] == (char)0) fstrcpy(user, context->user);
1039 srv = smbc_server(context, True,
1040 server, share, workgroup, user, password);
1044 if (errno == EPERM) errno = EACCES;
1045 return NULL; /* smbc_server sets errno */
1049 /* Hmmm, the test for a directory is suspect here ... FIXME */
1051 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1058 file = SMB_MALLOC_P(SMBCFILE);
1069 /*d_printf(">>>open: resolving %s\n", path);*/
1070 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1072 d_printf("Could not resolve %s\n", path);
1075 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1077 if ( targetcli->dfsroot )
1080 pstrcpy(temppath, targetpath);
1081 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1084 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1086 /* Handle the error ... */
1089 errno = smbc_errno(context, targetcli);
1094 /* Fill in file struct */
1097 file->fname = SMB_STRDUP(fname);
1102 DLIST_ADD(context->internal->_files, file);
1105 * If the file was opened in O_APPEND mode, all write
1106 * operations should be appended to the file. To do that,
1107 * though, using this protocol, would require a getattrE()
1108 * call for each and every write, to determine where the end
1109 * of the file is. (There does not appear to be an append flag
1110 * in the protocol.) Rather than add all of that overhead of
1111 * retrieving the current end-of-file offset prior to each
1112 * write operation, we'll assume that most append operations
1113 * will continuously write, so we'll just set the offset to
1114 * the end of the file now and hope that's adequate.
1116 * Note to self: If this proves inadequate, and O_APPEND
1117 * should, in some cases, be forced for each write, add a
1118 * field in the context options structure, for
1119 * "strict_append_mode" which would select between the current
1120 * behavior (if FALSE) or issuing a getattrE() prior to each
1121 * write and forcing the write to the end of the file (if
1122 * TRUE). Adding that capability will likely require adding
1123 * an "append" flag into the _SMBCFILE structure to track
1124 * whether a file was opened in O_APPEND mode. -- djl
1126 if (flags & O_APPEND) {
1127 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1128 (void) smbc_close_ctx(context, file);
1138 /* Check if opendir needed ... */
1143 eno = smbc_errno(context, &srv->cli);
1144 file = context->opendir(context, fname);
1145 if (!file) errno = eno;
1150 errno = EINVAL; /* FIXME, correct errno ? */
1156 * Routine to create a file
1159 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1162 smbc_creat_ctx(SMBCCTX *context,
1167 if (!context || !context->internal ||
1168 !context->internal->_initialized) {
1175 return smbc_open_ctx(context, path, creat_bits, mode);
1179 * Routine to read() a file ...
1183 smbc_read_ctx(SMBCCTX *context,
1189 fstring server, share, user, password;
1190 pstring path, targetpath;
1191 struct cli_state *targetcli;
1196 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1197 * appears to pass file->offset (which is type off_t) differently than
1198 * a local variable of type off_t. Using local variable "offset" in
1199 * the call to cli_read() instead of file->offset fixes a problem
1200 * retrieving data at an offset greater than 4GB.
1202 off_t offset = file->offset;
1204 if (!context || !context->internal ||
1205 !context->internal->_initialized) {
1212 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1214 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1221 /* Check that the buffer exists ... */
1230 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1231 if (smbc_parse_path(context, file->fname,
1233 server, sizeof(server),
1234 share, sizeof(share),
1237 password, sizeof(password),
1243 /*d_printf(">>>read: resolving %s\n", path);*/
1244 if (!cli_resolve_path("", &file->srv->cli, path,
1245 &targetcli, targetpath))
1247 d_printf("Could not resolve %s\n", path);
1250 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1252 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1256 errno = smbc_errno(context, targetcli);
1261 file->offset += ret;
1263 DEBUG(4, (" --> %d\n", ret));
1265 return ret; /* Success, ret bytes of data ... */
1270 * Routine to write() a file ...
1274 smbc_write_ctx(SMBCCTX *context,
1281 fstring server, share, user, password;
1282 pstring path, targetpath;
1283 struct cli_state *targetcli;
1285 /* First check all pointers before dereferencing them */
1287 if (!context || !context->internal ||
1288 !context->internal->_initialized) {
1295 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1302 /* Check that the buffer exists ... */
1311 offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1313 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1314 if (smbc_parse_path(context, file->fname,
1316 server, sizeof(server),
1317 share, sizeof(share),
1320 password, sizeof(password),
1326 /*d_printf(">>>write: resolving %s\n", path);*/
1327 if (!cli_resolve_path("", &file->srv->cli, path,
1328 &targetcli, targetpath))
1330 d_printf("Could not resolve %s\n", path);
1333 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1336 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1340 errno = smbc_errno(context, targetcli);
1345 file->offset += ret;
1347 return ret; /* Success, 0 bytes of data ... */
1351 * Routine to close() a file ...
1355 smbc_close_ctx(SMBCCTX *context,
1359 fstring server, share, user, password;
1360 pstring path, targetpath;
1361 struct cli_state *targetcli;
1363 if (!context || !context->internal ||
1364 !context->internal->_initialized) {
1371 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1381 return context->closedir(context, file);
1385 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1386 if (smbc_parse_path(context, file->fname,
1388 server, sizeof(server),
1389 share, sizeof(share),
1392 password, sizeof(password),
1398 /*d_printf(">>>close: resolving %s\n", path);*/
1399 if (!cli_resolve_path("", &file->srv->cli, path,
1400 &targetcli, targetpath))
1402 d_printf("Could not resolve %s\n", path);
1405 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1407 if (!cli_close(targetcli, file->cli_fd)) {
1409 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1411 /* Deallocate slot and remove the server
1412 * from the server cache if unused */
1413 errno = smbc_errno(context, targetcli);
1415 DLIST_REMOVE(context->internal->_files, file);
1416 SAFE_FREE(file->fname);
1418 context->callbacks.remove_unused_server_fn(context, srv);
1424 DLIST_REMOVE(context->internal->_files, file);
1425 SAFE_FREE(file->fname);
1432 * Get info from an SMB server on a file. Use a qpathinfo call first
1433 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1436 smbc_getatr(SMBCCTX * context,
1448 struct cli_state *targetcli;
1450 if (!context || !context->internal ||
1451 !context->internal->_initialized) {
1458 /* path fixup for . and .. */
1459 if (strequal(path, ".") || strequal(path, ".."))
1460 pstrcpy(fixedpath, "\\");
1463 pstrcpy(fixedpath, path);
1464 trim_string(fixedpath, NULL, "\\..");
1465 trim_string(fixedpath, NULL, "\\.");
1467 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1469 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1471 d_printf("Couldn't resolve %s\n", path);
1475 if ( targetcli->dfsroot )
1478 pstrcpy(temppath, targetpath);
1479 cli_dfs_make_full_path(targetpath, targetcli->desthost,
1480 targetcli->share, temppath);
1483 if (!srv->no_pathinfo2 &&
1484 cli_qpathinfo2(targetcli, targetpath,
1485 c_time, a_time, m_time, NULL, size, mode, ino)) {
1489 /* if this is NT then don't bother with the getatr */
1490 if (targetcli->capabilities & CAP_NT_SMBS) {
1495 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1496 if (m_time != NULL) {
1497 if (a_time != NULL) *a_time = *m_time;
1498 if (c_time != NULL) *c_time = *m_time;
1500 srv->no_pathinfo2 = True;
1510 * Set file info on an SMB server. Use setpathinfo call first. If that
1511 * fails, use setattrE..
1513 * Access and modification time parameters are always used and must be
1514 * provided. Create time, if zero, will be determined from the actual create
1515 * time of the file. If non-zero, the create time will be set as well.
1517 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1520 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1521 time_t c_time, time_t a_time, time_t m_time,
1528 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1529 * modern function for "new code" to be using, and it works given a
1530 * filename rather than requiring that the file be opened to have its
1531 * attributes manipulated.
1533 if (srv->no_pathinfo ||
1534 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1537 * setpathinfo is not supported; go to plan B.
1539 * cli_setatr() does not work on win98, and it also doesn't
1540 * support setting the access time (only the modification
1541 * time), so in all cases, we open the specified file and use
1542 * cli_setattrE() which should work on all OS versions, and
1543 * supports both times.
1546 /* Don't try {q,set}pathinfo() again, with this server */
1547 srv->no_pathinfo = True;
1550 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1552 errno = smbc_errno(context, &srv->cli);
1557 * Get the creat time of the file (if it wasn't provided).
1558 * We'll need it in the set call
1561 ret = cli_getattrE(&srv->cli, fd,
1563 &c_time, NULL, NULL);
1568 /* If we got create time, set times */
1570 /* Some OS versions don't support create time */
1571 if (c_time == 0 || c_time == -1) {
1572 c_time = time(NULL);
1576 * For sanity sake, since there is no POSIX function
1577 * to set the create time of a file, if the existing
1578 * create time is greater than either of access time
1579 * or modification time, set create time to the
1580 * smallest of those. This ensure that the create
1581 * time of a file is never greater than its last
1582 * access or modification time.
1584 if (c_time > a_time) c_time = a_time;
1585 if (c_time > m_time) c_time = m_time;
1587 /* Set the new attributes */
1588 ret = cli_setattrE(&srv->cli, fd,
1589 c_time, a_time, m_time);
1590 cli_close(&srv->cli, fd);
1594 * Unfortunately, setattrE() doesn't have a provision for
1595 * setting the access mode (attributes). We'll have to try
1596 * cli_setatr() for that, and with only this parameter, it
1597 * seems to work on win98.
1599 if (ret && mode != (uint16) -1) {
1600 ret = cli_setatr(&srv->cli, path, mode, 0);
1604 errno = smbc_errno(context, &srv->cli);
1613 * Routine to unlink() a file
1617 smbc_unlink_ctx(SMBCCTX *context,
1620 fstring server, share, user, password, workgroup;
1621 pstring path, targetpath;
1622 struct cli_state *targetcli;
1623 SMBCSRV *srv = NULL;
1625 if (!context || !context->internal ||
1626 !context->internal->_initialized) {
1628 errno = EINVAL; /* Best I can think of ... */
1640 if (smbc_parse_path(context, fname,
1641 workgroup, sizeof(workgroup),
1642 server, sizeof(server),
1643 share, sizeof(share),
1646 password, sizeof(password),
1652 if (user[0] == (char)0) fstrcpy(user, context->user);
1654 srv = smbc_server(context, True,
1655 server, share, workgroup, user, password);
1659 return -1; /* smbc_server sets errno */
1663 /*d_printf(">>>unlink: resolving %s\n", path);*/
1664 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1666 d_printf("Could not resolve %s\n", path);
1669 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1671 if (!cli_unlink(targetcli, targetpath)) {
1673 errno = smbc_errno(context, targetcli);
1675 if (errno == EACCES) { /* Check if the file is a directory */
1680 time_t m_time = 0, a_time = 0, c_time = 0;
1683 if (!smbc_getatr(context, srv, path, &mode, &size,
1684 &c_time, &a_time, &m_time, &ino)) {
1686 /* Hmmm, bad error ... What? */
1688 errno = smbc_errno(context, targetcli);
1694 if (IS_DOS_DIR(mode))
1697 errno = saverr; /* Restore this */
1706 return 0; /* Success ... */
1711 * Routine to rename() a file
1715 smbc_rename_ctx(SMBCCTX *ocontext,
1731 pstring targetpath1;
1732 pstring targetpath2;
1733 struct cli_state *targetcli1;
1734 struct cli_state *targetcli2;
1735 SMBCSRV *srv = NULL;
1737 if (!ocontext || !ncontext ||
1738 !ocontext->internal || !ncontext->internal ||
1739 !ocontext->internal->_initialized ||
1740 !ncontext->internal->_initialized) {
1742 errno = EINVAL; /* Best I can think of ... */
1747 if (!oname || !nname) {
1754 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1756 smbc_parse_path(ocontext, oname,
1757 workgroup, sizeof(workgroup),
1758 server1, sizeof(server1),
1759 share1, sizeof(share1),
1760 path1, sizeof(path1),
1761 user1, sizeof(user1),
1762 password1, sizeof(password1),
1765 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1767 smbc_parse_path(ncontext, nname,
1769 server2, sizeof(server2),
1770 share2, sizeof(share2),
1771 path2, sizeof(path2),
1772 user2, sizeof(user2),
1773 password2, sizeof(password2),
1776 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1778 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1779 strcmp(user1, user2)) {
1781 /* Can't rename across file systems, or users?? */
1788 srv = smbc_server(ocontext, True,
1789 server1, share1, workgroup, user1, password1);
1796 /*d_printf(">>>rename: resolving %s\n", path1);*/
1797 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1799 d_printf("Could not resolve %s\n", path1);
1802 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1803 /*d_printf(">>>rename: resolving %s\n", path2);*/
1804 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1806 d_printf("Could not resolve %s\n", path2);
1809 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1811 if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1812 strcmp(targetcli1->share, targetcli2->share))
1814 /* can't rename across file systems */
1820 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1821 int eno = smbc_errno(ocontext, targetcli1);
1823 if (eno != EEXIST ||
1824 !cli_unlink(targetcli1, targetpath2) ||
1825 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1833 return 0; /* Success */
1838 * A routine to lseek() a file
1842 smbc_lseek_ctx(SMBCCTX *context,
1848 fstring server, share, user, password;
1849 pstring path, targetpath;
1850 struct cli_state *targetcli;
1852 if (!context || !context->internal ||
1853 !context->internal->_initialized) {
1860 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1870 return -1; /* Can't lseek a dir ... */
1876 file->offset = offset;
1880 file->offset += offset;
1884 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1885 if (smbc_parse_path(context, file->fname,
1887 server, sizeof(server),
1888 share, sizeof(share),
1891 password, sizeof(password),
1898 /*d_printf(">>>lseek: resolving %s\n", path);*/
1899 if (!cli_resolve_path("", &file->srv->cli, path,
1900 &targetcli, targetpath))
1902 d_printf("Could not resolve %s\n", path);
1905 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1907 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1908 &size, NULL, NULL, NULL, NULL, NULL))
1910 SMB_OFF_T b_size = size;
1911 if (!cli_getattrE(targetcli, file->cli_fd,
1912 NULL, &b_size, NULL, NULL, NULL))
1919 file->offset = size + offset;
1928 return file->offset;
1933 * Generate an inode number from file name for those things that need it
1937 smbc_inode(SMBCCTX *context,
1941 if (!context || !context->internal ||
1942 !context->internal->_initialized) {
1949 if (!*name) return 2; /* FIXME, why 2 ??? */
1950 return (ino_t)str_checksum(name);
1955 * Routine to put basic stat info into a stat structure ... Used by stat and
1960 smbc_setup_stat(SMBCCTX *context,
1969 if (IS_DOS_DIR(mode)) {
1970 st->st_mode = SMBC_DIR_MODE;
1972 st->st_mode = SMBC_FILE_MODE;
1975 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1976 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1977 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1978 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1981 #ifdef HAVE_STAT_ST_BLKSIZE
1982 st->st_blksize = 512;
1984 #ifdef HAVE_STAT_ST_BLOCKS
1985 st->st_blocks = (size+511)/512;
1987 st->st_uid = getuid();
1988 st->st_gid = getgid();
1990 if (IS_DOS_DIR(mode)) {
1996 if (st->st_ino == 0) {
1997 st->st_ino = smbc_inode(context, fname);
2000 return True; /* FIXME: Is this needed ? */
2005 * Routine to stat a file given a name
2009 smbc_stat_ctx(SMBCCTX *context,
2027 if (!context || !context->internal ||
2028 !context->internal->_initialized) {
2030 errno = EINVAL; /* Best I can think of ... */
2042 DEBUG(4, ("smbc_stat(%s)\n", fname));
2044 if (smbc_parse_path(context, fname,
2045 workgroup, sizeof(workgroup),
2046 server, sizeof(server),
2047 share, sizeof(share),
2050 password, sizeof(password),
2056 if (user[0] == (char)0) fstrcpy(user, context->user);
2058 srv = smbc_server(context, True,
2059 server, share, workgroup, user, password);
2062 return -1; /* errno set by smbc_server */
2065 if (!smbc_getatr(context, srv, path, &mode, &size,
2066 &c_time, &a_time, &m_time, &ino)) {
2068 errno = smbc_errno(context, &srv->cli);
2075 smbc_setup_stat(context, st, path, size, mode);
2077 st->st_atime = a_time;
2078 st->st_ctime = c_time;
2079 st->st_mtime = m_time;
2080 st->st_dev = srv->dev;
2087 * Routine to stat a file given an fd
2091 smbc_fstat_ctx(SMBCCTX *context,
2106 struct cli_state *targetcli;
2109 if (!context || !context->internal ||
2110 !context->internal->_initialized) {
2117 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2126 return context->fstatdir(context, file, st);
2130 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2131 if (smbc_parse_path(context, file->fname,
2133 server, sizeof(server),
2134 share, sizeof(share),
2137 password, sizeof(password),
2143 /*d_printf(">>>fstat: resolving %s\n", path);*/
2144 if (!cli_resolve_path("", &file->srv->cli, path,
2145 &targetcli, targetpath))
2147 d_printf("Could not resolve %s\n", path);
2150 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2152 if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2153 &c_time, &a_time, &m_time, NULL, &ino)) {
2154 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2155 &c_time, &a_time, &m_time)) {
2164 smbc_setup_stat(context, st, file->fname, size, mode);
2166 st->st_atime = a_time;
2167 st->st_ctime = c_time;
2168 st->st_mtime = m_time;
2169 st->st_dev = file->srv->dev;
2176 * Routine to open a directory
2177 * We accept the URL syntax explained in smbc_parse_path(), above.
2181 smbc_remove_dir(SMBCFILE *dir)
2183 struct smbc_dir_list *d,*f;
2190 SAFE_FREE(f->dirent);
2195 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2200 add_dirent(SMBCFILE *dir,
2202 const char *comment,
2205 struct smbc_dirent *dirent;
2207 int name_length = (name == NULL ? 0 : strlen(name));
2208 int comment_len = (comment == NULL ? 0 : strlen(comment));
2211 * Allocate space for the dirent, which must be increased by the
2212 * size of the name and the comment and 1 each for the null terminator.
2215 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2217 dirent = SMB_MALLOC(size);
2221 dir->dir_error = ENOMEM;
2226 ZERO_STRUCTP(dirent);
2228 if (dir->dir_list == NULL) {
2230 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2231 if (!dir->dir_list) {
2234 dir->dir_error = ENOMEM;
2238 ZERO_STRUCTP(dir->dir_list);
2240 dir->dir_end = dir->dir_next = dir->dir_list;
2244 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2246 if (!dir->dir_end->next) {
2249 dir->dir_error = ENOMEM;
2253 ZERO_STRUCTP(dir->dir_end->next);
2255 dir->dir_end = dir->dir_end->next;
2258 dir->dir_end->next = NULL;
2259 dir->dir_end->dirent = dirent;
2261 dirent->smbc_type = type;
2262 dirent->namelen = name_length;
2263 dirent->commentlen = comment_len;
2264 dirent->dirlen = size;
2267 * dirent->namelen + 1 includes the null (no null termination needed)
2268 * Ditto for dirent->commentlen.
2269 * The space for the two null bytes was allocated.
2271 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2272 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2273 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2280 list_unique_wg_fn(const char *name,
2282 const char *comment,
2285 SMBCFILE *dir = (SMBCFILE *)state;
2286 struct smbc_dir_list *dir_list;
2287 struct smbc_dirent *dirent;
2291 dirent_type = dir->dir_type;
2293 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2295 /* An error occurred, what do we do? */
2296 /* FIXME: Add some code here */
2299 /* Point to the one just added */
2300 dirent = dir->dir_end->dirent;
2302 /* See if this was a duplicate */
2303 for (dir_list = dir->dir_list;
2304 dir_list != dir->dir_end;
2305 dir_list = dir_list->next) {
2307 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2308 /* Duplicate. End end of list need to be removed. */
2312 if (do_remove && dir_list->next == dir->dir_end) {
2313 /* Found the end of the list. Remove it. */
2314 dir->dir_end = dir_list;
2315 free(dir_list->next);
2317 dir_list->next = NULL;
2324 list_fn(const char *name,
2326 const char *comment,
2329 SMBCFILE *dir = (SMBCFILE *)state;
2333 * We need to process the type a little ...
2335 * Disk share = 0x00000000
2336 * Print share = 0x00000001
2337 * Comms share = 0x00000002 (obsolete?)
2338 * IPC$ share = 0x00000003
2340 * administrative shares:
2341 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2344 if (dir->dir_type == SMBC_FILE_SHARE) {
2347 case 0 | 0x80000000:
2349 dirent_type = SMBC_FILE_SHARE;
2353 dirent_type = SMBC_PRINTER_SHARE;
2357 dirent_type = SMBC_COMMS_SHARE;
2360 case 3 | 0x80000000:
2362 dirent_type = SMBC_IPC_SHARE;
2366 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2371 dirent_type = dir->dir_type;
2374 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2376 /* An error occurred, what do we do? */
2377 /* FIXME: Add some code here */
2383 dir_list_fn(const char *mnt,
2389 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2390 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2392 /* Handle an error ... */
2394 /* FIXME: Add some code ... */
2401 net_share_enum_rpc(struct cli_state *cli,
2402 void (*fn)(const char *name,
2404 const char *comment,
2411 uint32 info_level = 1;
2412 uint32 preferred_len = 0xffffffff;
2414 SRV_SHARE_INFO_CTR ctr;
2416 fstring comment = "";
2418 struct rpc_pipe_client *pipe_hnd;
2421 /* Open the server service pipe */
2422 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2424 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2428 /* Allocate a context for parsing and for the entries in "ctr" */
2429 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2430 if (mem_ctx == NULL) {
2431 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2432 cli_rpc_pipe_close(pipe_hnd);
2436 /* Issue the NetShareEnum RPC call and retrieve the response */
2437 init_enum_hnd(&enum_hnd, 0);
2438 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2445 /* Was it successful? */
2446 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2447 /* Nope. Go clean up. */
2451 /* For each returned entry... */
2452 for (i = 0; i < ctr.num_entries; i++) {
2454 /* pull out the share name */
2455 rpcstr_pull_unistr2_fstring(
2456 name, &ctr.share.info1[i].info_1_str.uni_netname);
2458 /* pull out the share's comment */
2459 rpcstr_pull_unistr2_fstring(
2460 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2462 /* Get the type value */
2463 type = ctr.share.info1[i].info_1.type;
2465 /* Add this share to the list */
2466 (*fn)(name, type, comment, state);
2470 /* Close the server service pipe */
2471 cli_rpc_pipe_close(pipe_hnd);
2473 /* Free all memory which was allocated for this request */
2474 TALLOC_FREE(mem_ctx);
2476 /* Tell 'em if it worked */
2477 return W_ERROR_IS_OK(result) ? 0 : -1;
2483 smbc_opendir_ctx(SMBCCTX *context,
2486 fstring server, share, user, password, options;
2491 SMBCSRV *srv = NULL;
2492 SMBCFILE *dir = NULL;
2493 struct in_addr rem_ip;
2495 if (!context || !context->internal ||
2496 !context->internal->_initialized) {
2497 DEBUG(4, ("no valid context\n"));
2498 errno = EINVAL + 8192;
2504 DEBUG(4, ("no valid fname\n"));
2505 errno = EINVAL + 8193;
2509 if (smbc_parse_path(context, fname,
2510 workgroup, sizeof(workgroup),
2511 server, sizeof(server),
2512 share, sizeof(share),
2515 password, sizeof(password),
2516 options, sizeof(options))) {
2517 DEBUG(4, ("no valid path\n"));
2518 errno = EINVAL + 8194;
2522 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2523 "path='%s' options='%s'\n",
2524 fname, server, share, path, options));
2526 /* Ensure the options are valid */
2527 if (smbc_check_options(server, share, path, options)) {
2528 DEBUG(4, ("unacceptable options (%s)\n", options));
2529 errno = EINVAL + 8195;
2533 if (user[0] == (char)0) fstrcpy(user, context->user);
2535 dir = SMB_MALLOC_P(SMBCFILE);
2547 dir->fname = SMB_STRDUP(fname);
2551 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2553 if (server[0] == (char)0) {
2558 struct ip_service *ip_list;
2559 struct ip_service server_addr;
2560 struct user_auth_info u_info;
2561 struct cli_state *cli;
2563 if (share[0] != (char)0 || path[0] != (char)0) {
2565 errno = EINVAL + 8196;
2567 SAFE_FREE(dir->fname);
2573 /* Determine how many local master browsers to query */
2574 max_lmb_count = (context->options.browse_max_lmb_count == 0
2576 : context->options.browse_max_lmb_count);
2578 pstrcpy(u_info.username, user);
2579 pstrcpy(u_info.password, password);
2582 * We have server and share and path empty but options
2583 * requesting that we scan all master browsers for their list
2584 * of workgroups/domains. This implies that we must first try
2585 * broadcast queries to find all master browsers, and if that
2586 * doesn't work, then try our other methods which return only
2587 * a single master browser.
2591 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2595 if (!find_master_ip(workgroup, &server_addr.ip)) {
2601 ip_list = &server_addr;
2605 for (i = 0; i < count && i < max_lmb_count; i++) {
2606 DEBUG(99, ("Found master browser %d of %d: %s\n",
2607 i+1, MAX(count, max_lmb_count),
2608 inet_ntoa(ip_list[i].ip)));
2610 cli = get_ipc_connect_master_ip(&ip_list[i],
2611 workgroup, &u_info);
2612 /* cli == NULL is the master browser refused to talk or
2613 could not be found */
2617 fstrcpy(server, cli->desthost);
2620 DEBUG(4, ("using workgroup %s %s\n",
2621 workgroup, server));
2624 * For each returned master browser IP address, get a
2625 * connection to IPC$ on the server if we do not
2626 * already have one, and determine the
2627 * workgroups/domains that it knows about.
2630 srv = smbc_server(context, True, server, "IPC$",
2631 workgroup, user, password);
2637 dir->dir_type = SMBC_WORKGROUP;
2639 /* Now, list the stuff ... */
2641 if (!cli_NetServerEnum(&srv->cli,
2643 SV_TYPE_DOMAIN_ENUM,
2653 * Server not an empty string ... Check the rest and see what
2656 if (*share == '\0') {
2657 if (*path != '\0') {
2659 /* Should not have empty share with path */
2660 errno = EINVAL + 8197;
2662 SAFE_FREE(dir->fname);
2670 * We don't know if <server> is really a server name
2671 * or is a workgroup/domain name. If we already have
2672 * a server structure for it, we'll use it.
2673 * Otherwise, check to see if <server><1D>,
2674 * <server><1B>, or <server><20> translates. We check
2675 * to see if <server> is an IP address first.
2679 * See if we have an existing server. Do not
2680 * establish a connection if one does not already
2683 srv = smbc_server(context, False, server, "IPC$",
2684 workgroup, user, password);
2687 * If no existing server and not an IP addr, look for
2691 !is_ipaddress(server) &&
2692 (resolve_name(server, &rem_ip, 0x1d) || /* LMB */
2693 resolve_name(server, &rem_ip, 0x1b) )) { /* DMB */
2697 dir->dir_type = SMBC_SERVER;
2700 * Get the backup list ...
2702 if (!name_status_find(server, 0, 0,
2703 rem_ip, buserver)) {
2705 DEBUG(0, ("Could not get name of "
2706 "local/domain master browser "
2707 "for server %s\n", server));
2714 * Get a connection to IPC$ on the server if
2715 * we do not already have one
2717 srv = smbc_server(context, True,
2719 workgroup, user, password);
2721 DEBUG(0, ("got no contact to IPC$\n"));
2723 SAFE_FREE(dir->fname);
2732 /* Now, list the servers ... */
2733 if (!cli_NetServerEnum(&srv->cli, server,
2734 0x0000FFFE, list_fn,
2738 SAFE_FREE(dir->fname);
2744 (resolve_name(server, &rem_ip, 0x20))) {
2746 /* If we hadn't found the server, get one now */
2748 srv = smbc_server(context, True,
2756 SAFE_FREE(dir->fname);
2763 dir->dir_type = SMBC_FILE_SHARE;
2766 /* List the shares ... */
2768 if (net_share_enum_rpc(
2771 (void *) dir) < 0 &&
2777 errno = cli_errno(&srv->cli);
2779 SAFE_FREE(dir->fname);
2786 /* Neither the workgroup nor server exists */
2787 errno = ECONNREFUSED;
2789 SAFE_FREE(dir->fname);
2798 * The server and share are specified ... work from
2802 struct cli_state *targetcli;
2804 /* We connect to the server and list the directory */
2805 dir->dir_type = SMBC_FILE_SHARE;
2807 srv = smbc_server(context, True, server, share,
2808 workgroup, user, password);
2813 SAFE_FREE(dir->fname);
2822 /* Now, list the files ... */
2824 p = path + strlen(path);
2825 pstrcat(path, "\\*");
2827 if (!cli_resolve_path("", &srv->cli, path,
2828 &targetcli, targetpath))
2830 d_printf("Could not resolve %s\n", path);
2834 if (cli_list(targetcli, targetpath,
2835 aDIR | aSYSTEM | aHIDDEN,
2836 dir_list_fn, (void *)dir) < 0) {
2839 SAFE_FREE(dir->fname);
2842 errno = smbc_errno(context, targetcli);
2844 if (errno == EINVAL) {
2846 * See if they asked to opendir something
2847 * other than a directory. If so, the
2848 * converted error value we got would have
2849 * been EINVAL rather than ENOTDIR.
2851 *p = '\0'; /* restore original path */
2853 if (smbc_getatr(context, srv, path,
2857 ! IS_DOS_DIR(mode)) {
2859 /* It is. Correct the error value */
2871 DLIST_ADD(context->internal->_files, dir);
2877 * Routine to close a directory
2881 smbc_closedir_ctx(SMBCCTX *context,
2885 if (!context || !context->internal ||
2886 !context->internal->_initialized) {
2893 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2900 smbc_remove_dir(dir); /* Clean it up */
2902 DLIST_REMOVE(context->internal->_files, dir);
2906 SAFE_FREE(dir->fname);
2907 SAFE_FREE(dir); /* Free the space too */
2915 smbc_readdir_internal(SMBCCTX * context,
2916 struct smbc_dirent *dest,
2917 struct smbc_dirent *src,
2918 int max_namebuf_len)
2920 if (context->options.urlencode_readdir_entries) {
2922 /* url-encode the name. get back remaining buffer space */
2924 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2926 /* We now know the name length */
2927 dest->namelen = strlen(dest->name);
2929 /* Save the pointer to the beginning of the comment */
2930 dest->comment = dest->name + dest->namelen + 1;
2932 /* Copy the comment */
2933 strncpy(dest->comment, src->comment, max_namebuf_len - 1);
2934 dest->comment[max_namebuf_len - 1] = '\0';
2936 /* Save other fields */
2937 dest->smbc_type = src->smbc_type;
2938 dest->commentlen = strlen(dest->comment);
2939 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2943 /* No encoding. Just copy the entry as is. */
2944 memcpy(dest, src, src->dirlen);
2945 dest->comment = (char *)(&dest->name + src->namelen + 1);
2951 * Routine to get a directory entry
2954 struct smbc_dirent *
2955 smbc_readdir_ctx(SMBCCTX *context,
2959 struct smbc_dirent *dirp, *dirent;
2961 /* Check that all is ok first ... */
2963 if (!context || !context->internal ||
2964 !context->internal->_initialized) {
2967 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2972 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2975 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2980 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2983 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2988 if (!dir->dir_next) {
2992 dirent = dir->dir_next->dirent;
3000 dirp = (struct smbc_dirent *)context->internal->_dirent;
3001 maxlen = (sizeof(context->internal->_dirent) -
3002 sizeof(struct smbc_dirent));
3004 smbc_readdir_internal(context, dirp, dirent, maxlen);
3006 dir->dir_next = dir->dir_next->next;
3012 * Routine to get directory entries
3016 smbc_getdents_ctx(SMBCCTX *context,
3018 struct smbc_dirent *dirp,
3024 char *ndir = (char *)dirp;
3025 struct smbc_dir_list *dirlist;
3027 /* Check that all is ok first ... */
3029 if (!context || !context->internal ||
3030 !context->internal->_initialized) {
3037 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3044 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3052 * Now, retrieve the number of entries that will fit in what was passed
3053 * We have to figure out if the info is in the list, or we need to
3054 * send a request to the server to get the info.
3057 while ((dirlist = dir->dir_next)) {
3058 struct smbc_dirent *dirent;
3060 if (!dirlist->dirent) {
3062 errno = ENOENT; /* Bad error */
3067 /* Do urlencoding of next entry, if so selected */
3068 dirent = (struct smbc_dirent *)context->internal->_dirent;
3069 maxlen = (sizeof(context->internal->_dirent) -
3070 sizeof(struct smbc_dirent));
3071 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3073 reqd = dirent->dirlen;
3077 if (rem < count) { /* We managed to copy something */
3083 else { /* Nothing copied ... */
3085 errno = EINVAL; /* Not enough space ... */
3092 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3094 ((struct smbc_dirent *)ndir)->comment =
3095 (char *)(&((struct smbc_dirent *)ndir)->name +
3103 dir->dir_next = dirlist = dirlist -> next;
3114 * Routine to create a directory ...
3118 smbc_mkdir_ctx(SMBCCTX *context,
3128 pstring path, targetpath;
3129 struct cli_state *targetcli;
3131 if (!context || !context->internal ||
3132 !context->internal->_initialized) {
3146 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3148 if (smbc_parse_path(context, fname,
3149 workgroup, sizeof(workgroup),
3150 server, sizeof(server),
3151 share, sizeof(share),
3154 password, sizeof(password),
3160 if (user[0] == (char)0) fstrcpy(user, context->user);
3162 srv = smbc_server(context, True,
3163 server, share, workgroup, user, password);
3167 return -1; /* errno set by smbc_server */
3171 /*d_printf(">>>mkdir: resolving %s\n", path);*/
3172 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3174 d_printf("Could not resolve %s\n", path);
3177 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3179 if (!cli_mkdir(targetcli, targetpath)) {
3181 errno = smbc_errno(context, targetcli);
3191 * Our list function simply checks to see if a directory is not empty
3194 static int smbc_rmdir_dirempty = True;
3197 rmdir_list_fn(const char *mnt,
3202 if (strncmp(finfo->name, ".", 1) != 0 &&
3203 strncmp(finfo->name, "..", 2) != 0) {
3205 smbc_rmdir_dirempty = False;
3210 * Routine to remove a directory
3214 smbc_rmdir_ctx(SMBCCTX *context,
3225 struct cli_state *targetcli;
3227 if (!context || !context->internal ||
3228 !context->internal->_initialized) {
3242 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3244 if (smbc_parse_path(context, fname,
3245 workgroup, sizeof(workgroup),
3246 server, sizeof(server),
3247 share, sizeof(share),
3250 password, sizeof(password),
3257 if (user[0] == (char)0) fstrcpy(user, context->user);
3259 srv = smbc_server(context, True,
3260 server, share, workgroup, user, password);
3264 return -1; /* errno set by smbc_server */
3268 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3269 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3271 d_printf("Could not resolve %s\n", path);
3274 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3277 if (!cli_rmdir(targetcli, targetpath)) {
3279 errno = smbc_errno(context, targetcli);
3281 if (errno == EACCES) { /* Check if the dir empty or not */
3283 /* Local storage to avoid buffer overflows */
3286 smbc_rmdir_dirempty = True; /* Make this so ... */
3288 pstrcpy(lpath, targetpath);
3289 pstrcat(lpath, "\\*");
3291 if (cli_list(targetcli, lpath,
3292 aDIR | aSYSTEM | aHIDDEN,
3293 rmdir_list_fn, NULL) < 0) {
3295 /* Fix errno to ignore latest error ... */
3296 DEBUG(5, ("smbc_rmdir: "
3297 "cli_list returned an error: %d\n",
3298 smbc_errno(context, targetcli)));
3303 if (smbc_rmdir_dirempty)
3319 * Routine to return the current directory position
3323 smbc_telldir_ctx(SMBCCTX *context,
3326 off_t ret_val; /* Squash warnings about cast */
3328 if (!context || !context->internal ||
3329 !context->internal->_initialized) {
3336 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3343 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3351 * We return the pointer here as the offset
3353 ret_val = (off_t)(long)dir->dir_next;
3359 * A routine to run down the list and see if the entry is OK
3362 struct smbc_dir_list *
3363 smbc_check_dir_ent(struct smbc_dir_list *list,
3364 struct smbc_dirent *dirent)
3367 /* Run down the list looking for what we want */
3371 struct smbc_dir_list *tmp = list;
3375 if (tmp->dirent == dirent)
3384 return NULL; /* Not found, or an error */
3390 * Routine to seek on a directory
3394 smbc_lseekdir_ctx(SMBCCTX *context,
3398 long int l_offset = offset; /* Handle problems of size */
3399 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3400 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3402 if (!context || !context->internal ||
3403 !context->internal->_initialized) {
3410 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3417 /* Now, check what we were passed and see if it is OK ... */
3419 if (dirent == NULL) { /* Seek to the begining of the list */
3421 dir->dir_next = dir->dir_list;
3426 /* Now, run down the list and make sure that the entry is OK */
3427 /* This may need to be changed if we change the format of the list */
3429 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3431 errno = EINVAL; /* Bad entry */
3436 dir->dir_next = list_ent;
3443 * Routine to fstat a dir
3447 smbc_fstatdir_ctx(SMBCCTX *context,
3452 if (!context || !context->internal ||
3453 !context->internal->_initialized) {
3460 /* No code yet ... */
3467 smbc_chmod_ctx(SMBCCTX *context,
3480 if (!context || !context->internal ||
3481 !context->internal->_initialized) {
3483 errno = EINVAL; /* Best I can think of ... */
3495 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3497 if (smbc_parse_path(context, fname,
3498 workgroup, sizeof(workgroup),
3499 server, sizeof(server),
3500 share, sizeof(share),
3503 password, sizeof(password),
3509 if (user[0] == (char)0) fstrcpy(user, context->user);
3511 srv = smbc_server(context, True,
3512 server, share, workgroup, user, password);
3515 return -1; /* errno set by smbc_server */
3520 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3521 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3522 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3523 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3525 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3526 errno = smbc_errno(context, &srv->cli);
3534 smbc_utimes_ctx(SMBCCTX *context,
3536 struct timeval *tbuf)
3548 if (!context || !context->internal ||
3549 !context->internal->_initialized) {
3551 errno = EINVAL; /* Best I can think of ... */
3564 a_time = m_time = time(NULL);
3566 a_time = tbuf[0].tv_sec;
3567 m_time = tbuf[1].tv_sec;
3576 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf) - 1);
3577 atimebuf[sizeof(atimebuf) - 1] = '\0';
3578 if ((p = strchr(atimebuf, '\n')) != NULL) {
3582 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf) - 1);
3583 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3584 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3588 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3589 fname, atimebuf, mtimebuf);
3592 if (smbc_parse_path(context, fname,
3593 workgroup, sizeof(workgroup),
3594 server, sizeof(server),
3595 share, sizeof(share),
3598 password, sizeof(password),
3604 if (user[0] == (char)0) fstrcpy(user, context->user);
3606 srv = smbc_server(context, True,
3607 server, share, workgroup, user, password);
3610 return -1; /* errno set by smbc_server */
3613 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3614 return -1; /* errno set by smbc_setatr */
3621 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3622 However NT4 gives a "The information may have been modified by a
3623 computer running Windows NT 5.0" if denied ACEs do not appear before
3627 ace_compare(SEC_ACE *ace1,
3630 if (sec_ace_equal(ace1, ace2))
3633 if (ace1->type != ace2->type)
3634 return ace2->type - ace1->type;
3636 if (sid_compare(&ace1->trustee, &ace2->trustee))
3637 return sid_compare(&ace1->trustee, &ace2->trustee);
3639 if (ace1->flags != ace2->flags)
3640 return ace1->flags - ace2->flags;
3642 if (ace1->info.mask != ace2->info.mask)
3643 return ace1->info.mask - ace2->info.mask;
3645 if (ace1->size != ace2->size)
3646 return ace1->size - ace2->size;
3648 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3653 sort_acl(SEC_ACL *the_acl)
3656 if (!the_acl) return;
3658 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]),
3659 QSORT_CAST ace_compare);
3661 for (i=1;i<the_acl->num_aces;) {
3662 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3664 for (j=i; j<the_acl->num_aces-1; j++) {
3665 the_acl->ace[j] = the_acl->ace[j+1];
3667 the_acl->num_aces--;
3674 /* convert a SID to a string, either numeric or username/group */
3676 convert_sid_to_string(struct cli_state *ipc_cli,
3682 char **domains = NULL;
3683 char **names = NULL;
3684 uint32 *types = NULL;
3685 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3686 sid_to_string(str, sid);
3689 return; /* no lookup desired */
3696 /* Ask LSA to convert the sid to a name */
3698 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3699 pol, 1, sid, &domains,
3701 !domains || !domains[0] || !names || !names[0]) {
3707 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3708 domains[0], lp_winbind_separator(),
3712 /* convert a string to a SID, either numeric or username/group */
3714 convert_string_to_sid(struct cli_state *ipc_cli,
3720 uint32 *types = NULL;
3721 DOM_SID *sids = NULL;
3723 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3730 if (strncmp(str, "S-", 2) == 0) {
3731 return string_to_sid(sid, str);
3738 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3739 pol, 1, &str, NULL, &sids,
3745 sid_copy(sid, &sids[0]);
3752 /* parse an ACE in the same format as print_ace() */
3754 parse_ace(struct cli_state *ipc_cli,
3764 unsigned int aflags;
3768 const struct perm_value *v;
3774 /* These values discovered by inspection */
3775 static const struct perm_value special_values[] = {
3776 { "R", 0x00120089 },
3777 { "W", 0x00120116 },
3778 { "X", 0x001200a0 },
3779 { "D", 0x00010000 },
3780 { "P", 0x00040000 },
3781 { "O", 0x00080000 },
3785 static const struct perm_value standard_values[] = {
3786 { "READ", 0x001200a9 },
3787 { "CHANGE", 0x001301bf },
3788 { "FULL", 0x001f01ff },
3794 p = strchr_m(str,':');
3795 if (!p) return False;
3798 /* Try to parse numeric form */
3800 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3801 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3805 /* Try to parse text form */
3807 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3812 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3816 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3817 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3818 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3819 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3824 /* Only numeric form accepted for flags at present */
3826 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3827 sscanf(tok, "%i", &aflags))) {
3831 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3835 if (strncmp(tok, "0x", 2) == 0) {
3836 if (sscanf(tok, "%i", &amask) != 1) {
3842 for (v = standard_values; v->perm; v++) {
3843 if (strcmp(tok, v->perm) == 0) {
3854 for (v = special_values; v->perm; v++) {
3855 if (v->perm[0] == *p) {
3861 if (!found) return False;
3871 init_sec_ace(ace, &sid, atype, mask, aflags);
3875 /* add an ACE to a list of ACEs in a SEC_ACL */
3877 add_ace(SEC_ACL **the_acl,
3885 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3889 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3890 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3891 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3892 newacl = make_sec_acl(ctx, (*the_acl)->revision,
3893 1+(*the_acl)->num_aces, aces);
3895 (*the_acl) = newacl;
3900 /* parse a ascii version of a security descriptor */
3902 sec_desc_parse(TALLOC_CTX *ctx,
3903 struct cli_state *ipc_cli,
3908 const char *p = str;
3912 DOM_SID *grp_sid=NULL;
3913 DOM_SID *owner_sid=NULL;
3917 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3919 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3920 revision = strtol(tok+9, NULL, 16);
3924 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3925 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3927 !convert_string_to_sid(ipc_cli, pol,
3929 owner_sid, tok+6)) {
3930 DEBUG(5, ("Failed to parse owner sid\n"));
3936 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3937 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3939 !convert_string_to_sid(ipc_cli, pol,
3941 owner_sid, tok+7)) {
3942 DEBUG(5, ("Failed to parse owner sid\n"));
3948 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3949 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3951 !convert_string_to_sid(ipc_cli, pol,
3954 DEBUG(5, ("Failed to parse group sid\n"));
3960 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3961 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3963 !convert_string_to_sid(ipc_cli, pol,
3966 DEBUG(5, ("Failed to parse group sid\n"));
3972 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3974 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3975 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3978 if(!add_ace(&dacl, &ace, ctx)) {
3979 DEBUG(5, ("Failed to add ACL %s\n", tok));
3985 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3987 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3988 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3991 if(!add_ace(&dacl, &ace, ctx)) {
3992 DEBUG(5, ("Failed to add ACL %s\n", tok));
3998 DEBUG(5, ("Failed to parse security descriptor\n"));
4002 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
4003 owner_sid, grp_sid, NULL, dacl, &sd_size);
4006 SAFE_FREE(owner_sid);
4012 /* Obtain the current dos attributes */
4013 static DOS_ATTR_DESC *
4014 dos_attr_query(SMBCCTX *context,
4016 const char *filename,
4019 time_t m_time = 0, a_time = 0, c_time = 0;
4022 SMB_INO_T inode = 0;
4025 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
4031 /* Obtain the DOS attributes */
4032 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
4034 &c_time, &a_time, &m_time, &inode)) {
4036 errno = smbc_errno(context, &srv->cli);
4037 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
4044 ret->a_time = a_time;
4045 ret->c_time = c_time;
4046 ret->m_time = m_time;
4053 /* parse a ascii version of a security descriptor */
4055 dos_attr_parse(SMBCCTX *context,
4060 const char *p = str;
4063 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4065 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
4066 dad->mode = strtol(tok+5, NULL, 16);
4070 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4071 dad->size = (SMB_OFF_T)atof(tok+5);
4075 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
4076 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
4080 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
4081 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
4085 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
4086 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
4090 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4091 dad->inode = (SMB_INO_T)atof(tok+6);
4097 /*****************************************************
4098 Retrieve the acls for a file.
4099 *******************************************************/
4102 cacl_get(SMBCCTX *context,
4105 struct cli_state *ipc_cli,
4121 BOOL exclude_nt_revision = False;
4122 BOOL exclude_nt_owner = False;
4123 BOOL exclude_nt_group = False;
4124 BOOL exclude_nt_acl = False;
4125 BOOL exclude_dos_mode = False;
4126 BOOL exclude_dos_size = False;
4127 BOOL exclude_dos_ctime = False;
4128 BOOL exclude_dos_atime = False;
4129 BOOL exclude_dos_mtime = False;
4130 BOOL exclude_dos_inode = False;
4131 BOOL numeric = True;
4132 BOOL determine_size = (bufsize == 0);
4136 fstring name_sandbox;
4140 time_t m_time = 0, a_time = 0, c_time = 0;
4144 struct cli_state *cli = &srv->cli;
4146 /* Copy name so we can strip off exclusions (if any are specified) */
4147 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4149 /* Ensure name is null terminated */
4150 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4152 /* Play in the sandbox */
4153 name = name_sandbox;
4155 /* If there are any exclusions, point to them and mask them from name */
4156 if ((pExclude = strchr(name, '!')) != NULL)
4161 all = (StrnCaseCmp(name, "system.*", 8) == 0);
4162 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4163 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4164 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4165 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4166 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4167 numeric = (* (name + strlen(name) - 1) != '+');
4169 /* Look for exclusions from "all" requests */
4170 if (all || all_nt || all_dos) {
4172 /* Exclusions are delimited by '!' */
4175 pExclude = (p == NULL ? NULL : p + 1)) {
4177 /* Find end of this exclusion name */
4178 if ((p = strchr(pExclude, '!')) != NULL)
4183 /* Which exclusion name is this? */
4184 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4185 exclude_nt_revision = True;
4187 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4188 exclude_nt_owner = True;
4190 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4191 exclude_nt_group = True;
4193 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4194 exclude_nt_acl = True;
4196 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4197 exclude_dos_mode = True;
4199 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4200 exclude_dos_size = True;
4202 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
4203 exclude_dos_ctime = True;
4205 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
4206 exclude_dos_atime = True;
4208 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
4209 exclude_dos_mtime = True;
4211 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4212 exclude_dos_inode = True;
4215 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4226 * If we are (possibly) talking to an NT or new system and some NT
4227 * attributes have been requested...
4229 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4230 /* Point to the portion after "system.nt_sec_desc." */
4231 name += 19; /* if (all) this will be invalid but unused */
4233 /* ... then obtain any NT attributes which were requested */
4234 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4237 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4238 filename, cli_errstr(cli)));
4243 sd = cli_query_secdesc(cli, fnum, ctx);
4247 ("cacl_get Failed to query old descriptor\n"));
4252 cli_close(cli, fnum);
4254 if (! exclude_nt_revision) {
4255 if (all || all_nt) {
4256 if (determine_size) {
4257 p = talloc_asprintf(ctx,
4266 n = snprintf(buf, bufsize,
4270 } else if (StrCaseCmp(name, "revision") == 0) {
4271 if (determine_size) {
4272 p = talloc_asprintf(ctx, "%d",
4280 n = snprintf(buf, bufsize, "%d",
4285 if (!determine_size && n > bufsize) {
4294 if (! exclude_nt_owner) {
4295 /* Get owner and group sid */
4296 if (sd->owner_sid) {
4297 convert_sid_to_string(ipc_cli, pol,
4302 fstrcpy(sidstr, "");
4305 if (all || all_nt) {
4306 if (determine_size) {
4307 p = talloc_asprintf(ctx, ",OWNER:%s",
4315 n = snprintf(buf, bufsize,
4316 ",OWNER:%s", sidstr);
4318 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4319 if (determine_size) {
4320 p = talloc_asprintf(ctx, "%s", sidstr);
4327 n = snprintf(buf, bufsize, "%s",
4332 if (!determine_size && n > bufsize) {
4341 if (! exclude_nt_group) {
4343 convert_sid_to_string(ipc_cli, pol,
4347 fstrcpy(sidstr, "");
4350 if (all || all_nt) {
4351 if (determine_size) {
4352 p = talloc_asprintf(ctx, ",GROUP:%s",
4360 n = snprintf(buf, bufsize,
4361 ",GROUP:%s", sidstr);
4363 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4364 if (determine_size) {
4365 p = talloc_asprintf(ctx, "%s", sidstr);
4372 n = snprintf(buf, bufsize,
4377 if (!determine_size && n > bufsize) {
4386 if (! exclude_nt_acl) {
4387 /* Add aces to value buffer */
4388 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4390 SEC_ACE *ace = &sd->dacl->ace[i];
4391 convert_sid_to_string(ipc_cli, pol,
4395 if (all || all_nt) {
4396 if (determine_size) {
4397 p = talloc_asprintf(
4413 ",ACL:%s:%d/%d/0x%08x",
4419 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4420 StrCaseCmp(name+3, sidstr) == 0) ||
4421 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4422 StrCaseCmp(name+4, sidstr) == 0)) {
4423 if (determine_size) {
4424 p = talloc_asprintf(
4436 n = snprintf(buf, bufsize,
4442 } else if (all_nt_acls) {
4443 if (determine_size) {
4444 p = talloc_asprintf(
4446 "%s%s:%d/%d/0x%08x",
4458 n = snprintf(buf, bufsize,
4459 "%s%s:%d/%d/0x%08x",
4477 /* Restore name pointer to its original value */
4481 if (all || some_dos) {
4482 /* Point to the portion after "system.dos_attr." */
4483 name += 16; /* if (all) this will be invalid but unused */
4485 /* Obtain the DOS attributes */
4486 if (!smbc_getatr(context, srv, filename, &mode, &size,
4487 &c_time, &a_time, &m_time, &ino)) {
4489 errno = smbc_errno(context, &srv->cli);
4494 if (! exclude_dos_mode) {
4495 if (all || all_dos) {
4496 if (determine_size) {
4497 p = talloc_asprintf(ctx,
4510 n = snprintf(buf, bufsize,
4518 } else if (StrCaseCmp(name, "mode") == 0) {
4519 if (determine_size) {
4520 p = talloc_asprintf(ctx, "0x%x", mode);
4527 n = snprintf(buf, bufsize,
4532 if (!determine_size && n > bufsize) {
4541 if (! exclude_dos_size) {
4542 if (all || all_dos) {
4543 if (determine_size) {
4544 p = talloc_asprintf(
4554 n = snprintf(buf, bufsize,
4558 } else if (StrCaseCmp(name, "size") == 0) {
4559 if (determine_size) {
4560 p = talloc_asprintf(
4570 n = snprintf(buf, bufsize,
4576 if (!determine_size && n > bufsize) {
4585 if (! exclude_dos_ctime) {
4586 if (all || all_dos) {
4587 if (determine_size) {
4588 p = talloc_asprintf(ctx,
4597 n = snprintf(buf, bufsize,
4598 ",C_TIME:%lu", c_time);
4600 } else if (StrCaseCmp(name, "c_time") == 0) {
4601 if (determine_size) {
4602 p = talloc_asprintf(ctx, "%lu", c_time);
4609 n = snprintf(buf, bufsize,
4614 if (!determine_size && n > bufsize) {
4623 if (! exclude_dos_atime) {
4624 if (all || all_dos) {
4625 if (determine_size) {
4626 p = talloc_asprintf(ctx,
4635 n = snprintf(buf, bufsize,
4636 ",A_TIME:%lu", a_time);
4638 } else if (StrCaseCmp(name, "a_time") == 0) {
4639 if (determine_size) {
4640 p = talloc_asprintf(ctx, "%lu", a_time);
4647 n = snprintf(buf, bufsize,
4652 if (!determine_size && n > bufsize) {
4661 if (! exclude_dos_mtime) {
4662 if (all || all_dos) {
4663 if (determine_size) {
4664 p = talloc_asprintf(ctx,
4673 n = snprintf(buf, bufsize,
4674 ",M_TIME:%lu", m_time);
4676 } else if (StrCaseCmp(name, "m_time") == 0) {
4677 if (determine_size) {
4678 p = talloc_asprintf(ctx, "%lu", m_time);
4685 n = snprintf(buf, bufsize,
4690 if (!determine_size && n > bufsize) {
4699 if (! exclude_dos_inode) {
4700 if (all || all_dos) {
4701 if (determine_size) {
4702 p = talloc_asprintf(
4712 n = snprintf(buf, bufsize,
4716 } else if (StrCaseCmp(name, "inode") == 0) {
4717 if (determine_size) {
4718 p = talloc_asprintf(
4728 n = snprintf(buf, bufsize,
4734 if (!determine_size && n > bufsize) {
4743 /* Restore name pointer to its original value */
4756 /*****************************************************
4757 set the ACLs on a file given an ascii description
4758 *******************************************************/
4760 cacl_set(TALLOC_CTX *ctx,
4761 struct cli_state *cli,
4762 struct cli_state *ipc_cli,
4764 const char *filename,
4765 const char *the_acl,
4771 SEC_DESC *sd = NULL, *old;
4772 SEC_ACL *dacl = NULL;
4773 DOM_SID *owner_sid = NULL;
4774 DOM_SID *grp_sid = NULL;
4779 BOOL numeric = True;
4781 /* the_acl will be null for REMOVE_ALL operations */
4783 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4787 /* if this is to set the entire ACL... */
4788 if (*the_acl == '*') {
4789 /* ... then increment past the first colon */
4793 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4794 CONST_DISCARD(char *, the_acl));
4802 /* The desired access below is the only one I could find that works
4803 with NT4, W2KP and Samba */
4805 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4808 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4809 filename, cli_errstr(cli)));
4814 old = cli_query_secdesc(cli, fnum, ctx);
4817 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4822 cli_close(cli, fnum);
4825 case SMBC_XATTR_MODE_REMOVE_ALL:
4826 old->dacl->num_aces = 0;
4827 SAFE_FREE(old->dacl->ace);
4828 SAFE_FREE(old->dacl);
4833 case SMBC_XATTR_MODE_REMOVE:
4834 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4837 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4838 if (sec_ace_equal(&sd->dacl->ace[i],
4839 &old->dacl->ace[j])) {
4841 for (k=j; k<old->dacl->num_aces-1;k++) {
4843 old->dacl->ace[k+1];
4845 old->dacl->num_aces--;
4846 if (old->dacl->num_aces == 0) {
4847 SAFE_FREE(old->dacl->ace);
4848 SAFE_FREE(old->dacl);
4865 case SMBC_XATTR_MODE_ADD:
4866 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4869 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4870 if (sid_equal(&sd->dacl->ace[i].trustee,
4871 &old->dacl->ace[j].trustee)) {
4872 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4877 old->dacl->ace[j] = sd->dacl->ace[i];
4883 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4889 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4890 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4896 case SMBC_XATTR_MODE_SET:
4898 owner_sid = old->owner_sid;
4899 grp_sid = old->grp_sid;
4903 case SMBC_XATTR_MODE_CHOWN:
4904 owner_sid = sd->owner_sid;
4907 case SMBC_XATTR_MODE_CHGRP:
4908 grp_sid = sd->grp_sid;
4912 /* Denied ACE entries must come before allowed ones */
4913 sort_acl(old->dacl);
4915 /* Create new security descriptor and set it */
4916 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4917 owner_sid, grp_sid, NULL, dacl, &sd_size);
4919 fnum = cli_nt_create(cli, filename,
4920 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4923 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4924 filename, cli_errstr(cli)));
4929 if (!cli_set_secdesc(cli, fnum, sd)) {
4930 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4937 cli_close(cli, fnum);
4948 smbc_setxattr_ctx(SMBCCTX *context,
4969 if (!context || !context->internal ||
4970 !context->internal->_initialized) {
4972 errno = EINVAL; /* Best I can think of ... */
4984 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
4985 fname, name, (int) size, (const char*)value));
4987 if (smbc_parse_path(context, fname,
4988 workgroup, sizeof(workgroup),
4989 server, sizeof(server),
4990 share, sizeof(share),
4993 password, sizeof(password),
4999 if (user[0] == (char)0) fstrcpy(user, context->user);
5001 srv = smbc_server(context, True,
5002 server, share, workgroup, user, password);
5004 return -1; /* errno set by smbc_server */
5007 if (! srv->no_nt_session) {
5008 ipc_srv = smbc_attr_server(context, server, share,
5009 workgroup, user, password,
5011 srv->no_nt_session = True;
5016 ctx = talloc_init("smbc_setxattr");
5023 * Are they asking to set the entire set of known attributes?
5025 if (StrCaseCmp(name, "system.*") == 0 ||
5026 StrCaseCmp(name, "system.*+") == 0) {
5029 talloc_asprintf(ctx, "%s:%s",
5030 name+7, (const char *) value);
5038 ret = cacl_set(ctx, &srv->cli,
5039 &ipc_srv->cli, &pol, path,
5042 ? SMBC_XATTR_MODE_SET
5043 : SMBC_XATTR_MODE_ADD),
5049 /* get a DOS Attribute Descriptor with current attributes */
5050 dad = dos_attr_query(context, ctx, path, srv);
5052 /* Overwrite old with new, using what was provided */
5053 dos_attr_parse(context, dad, srv, namevalue);
5055 /* Set the new DOS attributes */
5056 if (! smbc_setatr(context, srv, path,
5062 /* cause failure if NT failed too */
5067 /* we only fail if both NT and DOS sets failed */
5068 if (ret < 0 && ! dad) {
5069 ret = -1; /* in case dad was null */
5075 talloc_destroy(ctx);
5080 * Are they asking to set an access control element or to set
5081 * the entire access control list?
5083 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5084 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5085 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5086 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5087 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5091 talloc_asprintf(ctx, "%s:%s",
5092 name+19, (const char *) value);
5095 ret = -1; /* errno set by smbc_server() */
5097 else if (! namevalue) {
5101 ret = cacl_set(ctx, &srv->cli,
5102 &ipc_srv->cli, &pol, path,
5105 ? SMBC_XATTR_MODE_SET
5106 : SMBC_XATTR_MODE_ADD),
5109 talloc_destroy(ctx);
5114 * Are they asking to set the owner?
5116 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5117 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5121 talloc_asprintf(ctx, "%s:%s",
5122 name+19, (const char *) value);
5126 ret = -1; /* errno set by smbc_server() */
5128 else if (! namevalue) {
5132 ret = cacl_set(ctx, &srv->cli,
5133 &ipc_srv->cli, &pol, path,
5134 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5136 talloc_destroy(ctx);
5141 * Are they asking to set the group?
5143 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5144 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5148 talloc_asprintf(ctx, "%s:%s",
5149 name+19, (const char *) value);
5152 /* errno set by smbc_server() */
5155 else if (! namevalue) {
5159 ret = cacl_set(ctx, &srv->cli,
5160 &ipc_srv->cli, &pol, path,
5161 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5163 talloc_destroy(ctx);
5168 * Are they asking to set a DOS attribute?
5170 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5171 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5172 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5173 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5174 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
5176 /* get a DOS Attribute Descriptor with current attributes */
5177 dad = dos_attr_query(context, ctx, path, srv);
5180 talloc_asprintf(ctx, "%s:%s",
5181 name+16, (const char *) value);
5186 /* Overwrite old with provided new params */
5187 dos_attr_parse(context, dad, srv, namevalue);
5189 /* Set the new DOS attributes */
5190 ret2 = smbc_setatr(context, srv, path,
5196 /* ret2 has True (success) / False (failure) */
5207 talloc_destroy(ctx);
5211 /* Unsupported attribute name */
5212 talloc_destroy(ctx);
5218 smbc_getxattr_ctx(SMBCCTX *context,
5237 if (!context || !context->internal ||
5238 !context->internal->_initialized) {
5240 errno = EINVAL; /* Best I can think of ... */
5252 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5254 if (smbc_parse_path(context, fname,
5255 workgroup, sizeof(workgroup),
5256 server, sizeof(server),
5257 share, sizeof(share),
5260 password, sizeof(password),
5266 if (user[0] == (char)0) fstrcpy(user, context->user);
5268 srv = smbc_server(context, True,
5269 server, share, workgroup, user, password);
5271 return -1; /* errno set by smbc_server */
5274 if (! srv->no_nt_session) {
5275 ipc_srv = smbc_attr_server(context, server, share,
5276 workgroup, user, password,
5279 srv->no_nt_session = True;
5285 ctx = talloc_init("smbc:getxattr");
5291 /* Are they requesting a supported attribute? */
5292 if (StrCaseCmp(name, "system.*") == 0 ||
5293 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5294 StrCaseCmp(name, "system.*+") == 0 ||
5295 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5296 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5297 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5298 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5299 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5300 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5301 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5302 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5303 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5304 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5305 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5306 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5307 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5308 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5309 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5310 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5311 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5312 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5313 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
5314 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5317 ret = cacl_get(context, ctx, srv,
5318 ipc_srv == NULL ? NULL : &ipc_srv->cli,
5320 CONST_DISCARD(char *, name),
5321 CONST_DISCARD(char *, value), size);
5322 if (ret < 0 && errno == 0) {
5323 errno = smbc_errno(context, &srv->cli);
5325 talloc_destroy(ctx);
5329 /* Unsupported attribute name */
5330 talloc_destroy(ctx);
5337 smbc_removexattr_ctx(SMBCCTX *context,
5353 if (!context || !context->internal ||
5354 !context->internal->_initialized) {
5356 errno = EINVAL; /* Best I can think of ... */
5368 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5370 if (smbc_parse_path(context, fname,
5371 workgroup, sizeof(workgroup),
5372 server, sizeof(server),
5373 share, sizeof(share),
5376 password, sizeof(password),
5382 if (user[0] == (char)0) fstrcpy(user, context->user);
5384 srv = smbc_server(context, True,
5385 server, share, workgroup, user, password);
5387 return -1; /* errno set by smbc_server */
5390 if (! srv->no_nt_session) {
5391 ipc_srv = smbc_attr_server(context, server, share,
5392 workgroup, user, password,
5394 srv->no_nt_session = True;
5400 return -1; /* errno set by smbc_attr_server */
5403 ctx = talloc_init("smbc_removexattr");
5409 /* Are they asking to set the entire ACL? */
5410 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5411 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5414 ret = cacl_set(ctx, &srv->cli,
5415 &ipc_srv->cli, &pol, path,
5416 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5417 talloc_destroy(ctx);
5422 * Are they asking to remove one or more spceific security descriptor
5425 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5426 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5427 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5428 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5429 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5430 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5431 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5434 ret = cacl_set(ctx, &srv->cli,
5435 &ipc_srv->cli, &pol, path,
5436 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5437 talloc_destroy(ctx);
5441 /* Unsupported attribute name */
5442 talloc_destroy(ctx);
5448 smbc_listxattr_ctx(SMBCCTX *context,
5454 * This isn't quite what listxattr() is supposed to do. This returns
5455 * the complete set of attribute names, always, rather than only those
5456 * attribute names which actually exist for a file. Hmmm...
5458 const char supported[] =
5461 "system.nt_sec_desc.revision\0"
5462 "system.nt_sec_desc.owner\0"
5463 "system.nt_sec_desc.owner+\0"
5464 "system.nt_sec_desc.group\0"
5465 "system.nt_sec_desc.group+\0"
5466 "system.nt_sec_desc.acl.*\0"
5467 "system.nt_sec_desc.acl\0"
5468 "system.nt_sec_desc.acl+\0"
5469 "system.nt_sec_desc.*\0"
5470 "system.nt_sec_desc.*+\0"
5471 "system.dos_attr.*\0"
5472 "system.dos_attr.mode\0"
5473 "system.dos_attr.c_time\0"
5474 "system.dos_attr.a_time\0"
5475 "system.dos_attr.m_time\0"
5479 return sizeof(supported);
5482 if (sizeof(supported) > size) {
5487 /* this can't be strcpy() because there are embedded null characters */
5488 memcpy(list, supported, sizeof(supported));
5489 return sizeof(supported);
5494 * Open a print file to be written to by other calls
5498 smbc_open_print_job_ctx(SMBCCTX *context,
5507 if (!context || !context->internal ||
5508 !context->internal->_initialized) {
5522 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5524 if (smbc_parse_path(context, fname,
5526 server, sizeof(server),
5527 share, sizeof(share),
5530 password, sizeof(password),
5536 /* What if the path is empty, or the file exists? */
5538 return context->open(context, fname, O_WRONLY, 666);
5543 * Routine to print a file on a remote server ...
5545 * We open the file, which we assume to be on a remote server, and then
5546 * copy it to a print file on the share specified by printq.
5550 smbc_print_file_ctx(SMBCCTX *c_file,
5562 if (!c_file || !c_file->internal->_initialized || !c_print ||
5563 !c_print->internal->_initialized) {
5570 if (!fname && !printq) {
5577 /* Try to open the file for reading ... */
5579 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5581 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5582 return -1; /* smbc_open sets errno */
5586 /* Now, try to open the printer file for writing */
5588 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5590 saverr = errno; /* Save errno */
5591 c_file->close_fn(c_file, fid1);
5597 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5601 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5604 c_file->close_fn(c_file, fid1);
5605 c_print->close_fn(c_print, fid2);
5614 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5615 c_print->close_fn(c_print, fid2);
5629 * Routine to list print jobs on a printer share ...
5633 smbc_list_print_jobs_ctx(SMBCCTX *context,
5635 smbc_list_print_job_fn fn)
5645 if (!context || !context->internal ||
5646 !context->internal->_initialized) {
5660 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5662 if (smbc_parse_path(context, fname,
5663 workgroup, sizeof(workgroup),
5664 server, sizeof(server),
5665 share, sizeof(share),
5668 password, sizeof(password),
5674 if (user[0] == (char)0) fstrcpy(user, context->user);
5676 srv = smbc_server(context, True,
5677 server, share, workgroup, user, password);
5681 return -1; /* errno set by smbc_server */
5685 if (cli_print_queue(&srv->cli,
5686 (void (*)(struct print_job_info *))fn) < 0) {
5688 errno = smbc_errno(context, &srv->cli);
5698 * Delete a print job from a remote printer share
5702 smbc_unlink_print_job_ctx(SMBCCTX *context,
5715 if (!context || !context->internal ||
5716 !context->internal->_initialized) {
5730 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5732 if (smbc_parse_path(context, fname,
5733 workgroup, sizeof(workgroup),
5734 server, sizeof(server),
5735 share, sizeof(share),
5738 password, sizeof(password),
5744 if (user[0] == (char)0) fstrcpy(user, context->user);
5746 srv = smbc_server(context, True,
5747 server, share, workgroup, user, password);
5751 return -1; /* errno set by smbc_server */
5755 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5758 errno = smbc_errno(context, &srv->cli);
5759 else if (err == ERRnosuchprintjob)
5770 * Get a new empty handle to fill in with your own info
5773 smbc_new_context(void)
5777 context = SMB_MALLOC_P(SMBCCTX);
5783 ZERO_STRUCTP(context);
5785 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5786 if (!context->internal) {
5791 ZERO_STRUCTP(context->internal);
5794 /* ADD REASONABLE DEFAULTS */
5796 context->timeout = 20000; /* 20 seconds */
5798 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5799 context->options.urlencode_readdir_entries = False;/* backward compat */
5800 context->options.one_share_per_server = False;/* backward compat */
5802 context->open = smbc_open_ctx;
5803 context->creat = smbc_creat_ctx;
5804 context->read = smbc_read_ctx;
5805 context->write = smbc_write_ctx;
5806 context->close_fn = smbc_close_ctx;
5807 context->unlink = smbc_unlink_ctx;
5808 context->rename = smbc_rename_ctx;
5809 context->lseek = smbc_lseek_ctx;
5810 context->stat = smbc_stat_ctx;
5811 context->fstat = smbc_fstat_ctx;
5812 context->opendir = smbc_opendir_ctx;
5813 context->closedir = smbc_closedir_ctx;
5814 context->readdir = smbc_readdir_ctx;
5815 context->getdents = smbc_getdents_ctx;
5816 context->mkdir = smbc_mkdir_ctx;
5817 context->rmdir = smbc_rmdir_ctx;
5818 context->telldir = smbc_telldir_ctx;
5819 context->lseekdir = smbc_lseekdir_ctx;
5820 context->fstatdir = smbc_fstatdir_ctx;
5821 context->chmod = smbc_chmod_ctx;
5822 context->utimes = smbc_utimes_ctx;
5823 context->setxattr = smbc_setxattr_ctx;
5824 context->getxattr = smbc_getxattr_ctx;
5825 context->removexattr = smbc_removexattr_ctx;
5826 context->listxattr = smbc_listxattr_ctx;
5827 context->open_print_job = smbc_open_print_job_ctx;
5828 context->print_file = smbc_print_file_ctx;
5829 context->list_print_jobs = smbc_list_print_jobs_ctx;
5830 context->unlink_print_job = smbc_unlink_print_job_ctx;
5832 context->callbacks.check_server_fn = smbc_check_server;
5833 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5835 smbc_default_cache_functions(context);
5843 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5844 * and thus you'll be leaking memory if not handled properly.
5848 smbc_free_context(SMBCCTX *context,
5858 DEBUG(1,("Performing aggressive shutdown.\n"));
5860 f = context->internal->_files;
5862 context->close_fn(context, f);
5865 context->internal->_files = NULL;
5867 /* First try to remove the servers the nice way. */
5868 if (context->callbacks.purge_cached_fn(context)) {
5871 DEBUG(1, ("Could not purge all servers, "
5872 "Nice way shutdown failed.\n"));
5873 s = context->internal->_servers;
5875 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
5877 cli_shutdown(&s->cli);
5878 context->callbacks.remove_cached_srv_fn(context,
5881 DLIST_REMOVE(context->internal->_servers, s);
5885 context->internal->_servers = NULL;
5889 /* This is the polite way */
5890 if (context->callbacks.purge_cached_fn(context)) {
5891 DEBUG(1, ("Could not purge all servers, "
5892 "free_context failed.\n"));
5896 if (context->internal->_servers) {
5897 DEBUG(1, ("Active servers in context, "
5898 "free_context failed.\n"));
5902 if (context->internal->_files) {
5903 DEBUG(1, ("Active files in context, "
5904 "free_context failed.\n"));
5910 /* Things we have to clean up */
5911 SAFE_FREE(context->workgroup);
5912 SAFE_FREE(context->netbios_name);
5913 SAFE_FREE(context->user);
5915 DEBUG(3, ("Context %p succesfully freed\n", context));
5916 SAFE_FREE(context->internal);
5923 * Each time the context structure is changed, we have binary backward
5924 * compatibility issues. Instead of modifying the public portions of the
5925 * context structure to add new options, instead, we put them in the internal
5926 * portion of the context structure and provide a set function for these new
5930 smbc_option_set(SMBCCTX *context,
5934 if (strcmp(option_name, "debug_stderr") == 0) {
5936 * Log to standard error instead of standard output.
5938 context->internal->_debug_stderr = True;
5944 * Initialise the library etc
5946 * We accept a struct containing handle information.
5947 * valid values for info->debug from 0 to 100,
5948 * and insist that info->fn must be non-null.
5951 smbc_init_context(SMBCCTX *context)
5958 if (!context || !context->internal) {
5963 /* Do not initialise the same client twice */
5964 if (context->internal->_initialized) {
5968 if (!context->callbacks.auth_fn ||
5969 context->debug < 0 ||
5970 context->debug > 100) {
5977 if (!smbc_initialized) {
5979 * Do some library-wide intializations the first time we get
5982 BOOL conf_loaded = False;
5984 /* Set this to what the user wants */
5985 DEBUGLEVEL = context->debug;
5989 setup_logging("libsmbclient", True);
5990 if (context->internal->_debug_stderr) {
5992 x_setbuf(x_stderr, NULL);
5995 /* Here we would open the smb.conf file if needed ... */
5997 in_client = True; /* FIXME, make a param */
5999 home = getenv("HOME");
6001 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
6002 if (lp_load(conf, True, False, False, True)) {
6005 DEBUG(5, ("Could not load config file: %s\n",
6012 * Well, if that failed, try the dyn_CONFIGFILE
6013 * Which points to the standard locn, and if that
6014 * fails, silently ignore it and use the internal
6018 if (!lp_load(dyn_CONFIGFILE, True, False, False, False)) {
6019 DEBUG(5, ("Could not load config file: %s\n",
6023 * We loaded the global config file. Now lets
6024 * load user-specific modifications to the
6027 slprintf(conf, sizeof(conf),
6028 "%s/.smb/smb.conf.append", home);
6029 if (!lp_load(conf, True, False, False, False)) {
6031 ("Could not append config file: "
6038 load_interfaces(); /* Load the list of interfaces ... */
6040 reopen_logs(); /* Get logging working ... */
6043 * Block SIGPIPE (from lib/util_sock.c: write())
6044 * It is not needed and should not stop execution
6046 BlockSignals(True, SIGPIPE);
6048 /* Done with one-time initialisation */
6049 smbc_initialized = 1;
6053 if (!context->user) {
6055 * FIXME: Is this the best way to get the user info?
6057 user = getenv("USER");
6058 /* walk around as "guest" if no username can be found */
6059 if (!user) context->user = SMB_STRDUP("guest");
6060 else context->user = SMB_STRDUP(user);
6063 if (!context->netbios_name) {
6065 * We try to get our netbios name from the config. If that
6066 * fails we fall back on constructing our netbios name from
6069 if (global_myname()) {
6070 context->netbios_name = SMB_STRDUP(global_myname());
6074 * Hmmm, I want to get hostname as well, but I am too
6075 * lazy for the moment
6078 context->netbios_name = SMB_MALLOC(17);
6079 if (!context->netbios_name) {
6083 slprintf(context->netbios_name, 16,
6084 "smbc%s%d", context->user, pid);
6088 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
6090 if (!context->workgroup) {
6091 if (lp_workgroup()) {
6092 context->workgroup = SMB_STRDUP(lp_workgroup());
6095 /* TODO: Think about a decent default workgroup */
6096 context->workgroup = SMB_STRDUP("samba");
6100 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
6102 /* shortest timeout is 1 second */
6103 if (context->timeout > 0 && context->timeout < 1000)
6104 context->timeout = 1000;
6107 * FIXME: Should we check the function pointers here?
6110 context->internal->_initialized = True;
6116 /* Return the verion of samba, and thus libsmbclient */
6120 return samba_version_string();