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);
1076 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1078 if ( targetcli->dfsroot )
1081 pstrcpy(temppath, targetpath);
1082 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1085 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1087 /* Handle the error ... */
1090 errno = smbc_errno(context, targetcli);
1095 /* Fill in file struct */
1098 file->fname = SMB_STRDUP(fname);
1103 DLIST_ADD(context->internal->_files, file);
1106 * If the file was opened in O_APPEND mode, all write
1107 * operations should be appended to the file. To do that,
1108 * though, using this protocol, would require a getattrE()
1109 * call for each and every write, to determine where the end
1110 * of the file is. (There does not appear to be an append flag
1111 * in the protocol.) Rather than add all of that overhead of
1112 * retrieving the current end-of-file offset prior to each
1113 * write operation, we'll assume that most append operations
1114 * will continuously write, so we'll just set the offset to
1115 * the end of the file now and hope that's adequate.
1117 * Note to self: If this proves inadequate, and O_APPEND
1118 * should, in some cases, be forced for each write, add a
1119 * field in the context options structure, for
1120 * "strict_append_mode" which would select between the current
1121 * behavior (if FALSE) or issuing a getattrE() prior to each
1122 * write and forcing the write to the end of the file (if
1123 * TRUE). Adding that capability will likely require adding
1124 * an "append" flag into the _SMBCFILE structure to track
1125 * whether a file was opened in O_APPEND mode. -- djl
1127 if (flags & O_APPEND) {
1128 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1129 (void) smbc_close_ctx(context, file);
1139 /* Check if opendir needed ... */
1144 eno = smbc_errno(context, &srv->cli);
1145 file = context->opendir(context, fname);
1146 if (!file) errno = eno;
1151 errno = EINVAL; /* FIXME, correct errno ? */
1157 * Routine to create a file
1160 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1163 smbc_creat_ctx(SMBCCTX *context,
1168 if (!context || !context->internal ||
1169 !context->internal->_initialized) {
1176 return smbc_open_ctx(context, path, creat_bits, mode);
1180 * Routine to read() a file ...
1184 smbc_read_ctx(SMBCCTX *context,
1190 fstring server, share, user, password;
1191 pstring path, targetpath;
1192 struct cli_state *targetcli;
1197 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1198 * appears to pass file->offset (which is type off_t) differently than
1199 * a local variable of type off_t. Using local variable "offset" in
1200 * the call to cli_read() instead of file->offset fixes a problem
1201 * retrieving data at an offset greater than 4GB.
1205 if (!context || !context->internal ||
1206 !context->internal->_initialized) {
1213 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1215 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1222 offset = file->offset;
1224 /* Check that the buffer exists ... */
1233 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1234 if (smbc_parse_path(context, file->fname,
1236 server, sizeof(server),
1237 share, sizeof(share),
1240 password, sizeof(password),
1246 /*d_printf(">>>read: resolving %s\n", path);*/
1247 if (!cli_resolve_path("", &file->srv->cli, path,
1248 &targetcli, targetpath))
1250 d_printf("Could not resolve %s\n", path);
1253 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1255 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1259 errno = smbc_errno(context, targetcli);
1264 file->offset += ret;
1266 DEBUG(4, (" --> %d\n", ret));
1268 return ret; /* Success, ret bytes of data ... */
1273 * Routine to write() a file ...
1277 smbc_write_ctx(SMBCCTX *context,
1284 fstring server, share, user, password;
1285 pstring path, targetpath;
1286 struct cli_state *targetcli;
1288 /* First check all pointers before dereferencing them */
1290 if (!context || !context->internal ||
1291 !context->internal->_initialized) {
1298 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1305 /* Check that the buffer exists ... */
1314 offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1316 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1317 if (smbc_parse_path(context, file->fname,
1319 server, sizeof(server),
1320 share, sizeof(share),
1323 password, sizeof(password),
1329 /*d_printf(">>>write: resolving %s\n", path);*/
1330 if (!cli_resolve_path("", &file->srv->cli, path,
1331 &targetcli, targetpath))
1333 d_printf("Could not resolve %s\n", path);
1336 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1339 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1343 errno = smbc_errno(context, targetcli);
1348 file->offset += ret;
1350 return ret; /* Success, 0 bytes of data ... */
1354 * Routine to close() a file ...
1358 smbc_close_ctx(SMBCCTX *context,
1362 fstring server, share, user, password;
1363 pstring path, targetpath;
1364 struct cli_state *targetcli;
1366 if (!context || !context->internal ||
1367 !context->internal->_initialized) {
1374 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1384 return context->closedir(context, file);
1388 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1389 if (smbc_parse_path(context, file->fname,
1391 server, sizeof(server),
1392 share, sizeof(share),
1395 password, sizeof(password),
1401 /*d_printf(">>>close: resolving %s\n", path);*/
1402 if (!cli_resolve_path("", &file->srv->cli, path,
1403 &targetcli, targetpath))
1405 d_printf("Could not resolve %s\n", path);
1408 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1410 if (!cli_close(targetcli, file->cli_fd)) {
1412 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1414 /* Deallocate slot and remove the server
1415 * from the server cache if unused */
1416 errno = smbc_errno(context, targetcli);
1418 DLIST_REMOVE(context->internal->_files, file);
1419 SAFE_FREE(file->fname);
1421 context->callbacks.remove_unused_server_fn(context, srv);
1427 DLIST_REMOVE(context->internal->_files, file);
1428 SAFE_FREE(file->fname);
1435 * Get info from an SMB server on a file. Use a qpathinfo call first
1436 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1439 smbc_getatr(SMBCCTX * context,
1451 struct cli_state *targetcli;
1453 if (!context || !context->internal ||
1454 !context->internal->_initialized) {
1461 /* path fixup for . and .. */
1462 if (strequal(path, ".") || strequal(path, ".."))
1463 pstrcpy(fixedpath, "\\");
1466 pstrcpy(fixedpath, path);
1467 trim_string(fixedpath, NULL, "\\..");
1468 trim_string(fixedpath, NULL, "\\.");
1470 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1472 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1474 d_printf("Couldn't resolve %s\n", path);
1478 if ( targetcli->dfsroot )
1481 pstrcpy(temppath, targetpath);
1482 cli_dfs_make_full_path(targetpath, targetcli->desthost,
1483 targetcli->share, temppath);
1486 if (!srv->no_pathinfo2 &&
1487 cli_qpathinfo2(targetcli, targetpath,
1488 c_time, a_time, m_time, NULL, size, mode, ino)) {
1492 /* if this is NT then don't bother with the getatr */
1493 if (targetcli->capabilities & CAP_NT_SMBS) {
1498 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1499 if (m_time != NULL) {
1500 if (a_time != NULL) *a_time = *m_time;
1501 if (c_time != NULL) *c_time = *m_time;
1503 srv->no_pathinfo2 = True;
1513 * Set file info on an SMB server. Use setpathinfo call first. If that
1514 * fails, use setattrE..
1516 * Access and modification time parameters are always used and must be
1517 * provided. Create time, if zero, will be determined from the actual create
1518 * time of the file. If non-zero, the create time will be set as well.
1520 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1523 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1524 time_t c_time, time_t a_time, time_t m_time,
1531 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1532 * modern function for "new code" to be using, and it works given a
1533 * filename rather than requiring that the file be opened to have its
1534 * attributes manipulated.
1536 if (srv->no_pathinfo ||
1537 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1540 * setpathinfo is not supported; go to plan B.
1542 * cli_setatr() does not work on win98, and it also doesn't
1543 * support setting the access time (only the modification
1544 * time), so in all cases, we open the specified file and use
1545 * cli_setattrE() which should work on all OS versions, and
1546 * supports both times.
1549 /* Don't try {q,set}pathinfo() again, with this server */
1550 srv->no_pathinfo = True;
1553 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1555 errno = smbc_errno(context, &srv->cli);
1560 * Get the creat time of the file (if it wasn't provided).
1561 * We'll need it in the set call
1564 ret = cli_getattrE(&srv->cli, fd,
1566 &c_time, NULL, NULL);
1571 /* If we got create time, set times */
1573 /* Some OS versions don't support create time */
1574 if (c_time == 0 || c_time == -1) {
1575 c_time = time(NULL);
1579 * For sanity sake, since there is no POSIX function
1580 * to set the create time of a file, if the existing
1581 * create time is greater than either of access time
1582 * or modification time, set create time to the
1583 * smallest of those. This ensure that the create
1584 * time of a file is never greater than its last
1585 * access or modification time.
1587 if (c_time > a_time) c_time = a_time;
1588 if (c_time > m_time) c_time = m_time;
1590 /* Set the new attributes */
1591 ret = cli_setattrE(&srv->cli, fd,
1592 c_time, a_time, m_time);
1593 cli_close(&srv->cli, fd);
1597 * Unfortunately, setattrE() doesn't have a provision for
1598 * setting the access mode (attributes). We'll have to try
1599 * cli_setatr() for that, and with only this parameter, it
1600 * seems to work on win98.
1602 if (ret && mode != (uint16) -1) {
1603 ret = cli_setatr(&srv->cli, path, mode, 0);
1607 errno = smbc_errno(context, &srv->cli);
1616 * Routine to unlink() a file
1620 smbc_unlink_ctx(SMBCCTX *context,
1623 fstring server, share, user, password, workgroup;
1624 pstring path, targetpath;
1625 struct cli_state *targetcli;
1626 SMBCSRV *srv = NULL;
1628 if (!context || !context->internal ||
1629 !context->internal->_initialized) {
1631 errno = EINVAL; /* Best I can think of ... */
1643 if (smbc_parse_path(context, fname,
1644 workgroup, sizeof(workgroup),
1645 server, sizeof(server),
1646 share, sizeof(share),
1649 password, sizeof(password),
1655 if (user[0] == (char)0) fstrcpy(user, context->user);
1657 srv = smbc_server(context, True,
1658 server, share, workgroup, user, password);
1662 return -1; /* smbc_server sets errno */
1666 /*d_printf(">>>unlink: resolving %s\n", path);*/
1667 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1669 d_printf("Could not resolve %s\n", path);
1672 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1674 if (!cli_unlink(targetcli, targetpath)) {
1676 errno = smbc_errno(context, targetcli);
1678 if (errno == EACCES) { /* Check if the file is a directory */
1683 time_t m_time = 0, a_time = 0, c_time = 0;
1686 if (!smbc_getatr(context, srv, path, &mode, &size,
1687 &c_time, &a_time, &m_time, &ino)) {
1689 /* Hmmm, bad error ... What? */
1691 errno = smbc_errno(context, targetcli);
1697 if (IS_DOS_DIR(mode))
1700 errno = saverr; /* Restore this */
1709 return 0; /* Success ... */
1714 * Routine to rename() a file
1718 smbc_rename_ctx(SMBCCTX *ocontext,
1734 pstring targetpath1;
1735 pstring targetpath2;
1736 struct cli_state *targetcli1;
1737 struct cli_state *targetcli2;
1738 SMBCSRV *srv = NULL;
1740 if (!ocontext || !ncontext ||
1741 !ocontext->internal || !ncontext->internal ||
1742 !ocontext->internal->_initialized ||
1743 !ncontext->internal->_initialized) {
1745 errno = EINVAL; /* Best I can think of ... */
1750 if (!oname || !nname) {
1757 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1759 smbc_parse_path(ocontext, oname,
1760 workgroup, sizeof(workgroup),
1761 server1, sizeof(server1),
1762 share1, sizeof(share1),
1763 path1, sizeof(path1),
1764 user1, sizeof(user1),
1765 password1, sizeof(password1),
1768 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1770 smbc_parse_path(ncontext, nname,
1772 server2, sizeof(server2),
1773 share2, sizeof(share2),
1774 path2, sizeof(path2),
1775 user2, sizeof(user2),
1776 password2, sizeof(password2),
1779 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1781 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1782 strcmp(user1, user2)) {
1784 /* Can't rename across file systems, or users?? */
1791 srv = smbc_server(ocontext, True,
1792 server1, share1, workgroup, user1, password1);
1799 /*d_printf(">>>rename: resolving %s\n", path1);*/
1800 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1802 d_printf("Could not resolve %s\n", path1);
1805 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1806 /*d_printf(">>>rename: resolving %s\n", path2);*/
1807 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1809 d_printf("Could not resolve %s\n", path2);
1812 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1814 if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1815 strcmp(targetcli1->share, targetcli2->share))
1817 /* can't rename across file systems */
1823 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1824 int eno = smbc_errno(ocontext, targetcli1);
1826 if (eno != EEXIST ||
1827 !cli_unlink(targetcli1, targetpath2) ||
1828 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1836 return 0; /* Success */
1841 * A routine to lseek() a file
1845 smbc_lseek_ctx(SMBCCTX *context,
1851 fstring server, share, user, password;
1852 pstring path, targetpath;
1853 struct cli_state *targetcli;
1855 if (!context || !context->internal ||
1856 !context->internal->_initialized) {
1863 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1873 return -1; /* Can't lseek a dir ... */
1879 file->offset = offset;
1883 file->offset += offset;
1887 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1888 if (smbc_parse_path(context, file->fname,
1890 server, sizeof(server),
1891 share, sizeof(share),
1894 password, sizeof(password),
1901 /*d_printf(">>>lseek: resolving %s\n", path);*/
1902 if (!cli_resolve_path("", &file->srv->cli, path,
1903 &targetcli, targetpath))
1905 d_printf("Could not resolve %s\n", path);
1908 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1910 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1911 &size, NULL, NULL, NULL, NULL, NULL))
1913 SMB_OFF_T b_size = size;
1914 if (!cli_getattrE(targetcli, file->cli_fd,
1915 NULL, &b_size, NULL, NULL, NULL))
1922 file->offset = size + offset;
1931 return file->offset;
1936 * Generate an inode number from file name for those things that need it
1940 smbc_inode(SMBCCTX *context,
1944 if (!context || !context->internal ||
1945 !context->internal->_initialized) {
1952 if (!*name) return 2; /* FIXME, why 2 ??? */
1953 return (ino_t)str_checksum(name);
1958 * Routine to put basic stat info into a stat structure ... Used by stat and
1963 smbc_setup_stat(SMBCCTX *context,
1972 if (IS_DOS_DIR(mode)) {
1973 st->st_mode = SMBC_DIR_MODE;
1975 st->st_mode = SMBC_FILE_MODE;
1978 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1979 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1980 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1981 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1984 #ifdef HAVE_STAT_ST_BLKSIZE
1985 st->st_blksize = 512;
1987 #ifdef HAVE_STAT_ST_BLOCKS
1988 st->st_blocks = (size+511)/512;
1990 st->st_uid = getuid();
1991 st->st_gid = getgid();
1993 if (IS_DOS_DIR(mode)) {
1999 if (st->st_ino == 0) {
2000 st->st_ino = smbc_inode(context, fname);
2003 return True; /* FIXME: Is this needed ? */
2008 * Routine to stat a file given a name
2012 smbc_stat_ctx(SMBCCTX *context,
2030 if (!context || !context->internal ||
2031 !context->internal->_initialized) {
2033 errno = EINVAL; /* Best I can think of ... */
2045 DEBUG(4, ("smbc_stat(%s)\n", fname));
2047 if (smbc_parse_path(context, fname,
2048 workgroup, sizeof(workgroup),
2049 server, sizeof(server),
2050 share, sizeof(share),
2053 password, sizeof(password),
2059 if (user[0] == (char)0) fstrcpy(user, context->user);
2061 srv = smbc_server(context, True,
2062 server, share, workgroup, user, password);
2065 return -1; /* errno set by smbc_server */
2068 if (!smbc_getatr(context, srv, path, &mode, &size,
2069 &c_time, &a_time, &m_time, &ino)) {
2071 errno = smbc_errno(context, &srv->cli);
2078 smbc_setup_stat(context, st, path, size, mode);
2080 st->st_atime = a_time;
2081 st->st_ctime = c_time;
2082 st->st_mtime = m_time;
2083 st->st_dev = srv->dev;
2090 * Routine to stat a file given an fd
2094 smbc_fstat_ctx(SMBCCTX *context,
2109 struct cli_state *targetcli;
2112 if (!context || !context->internal ||
2113 !context->internal->_initialized) {
2120 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2129 return context->fstatdir(context, file, st);
2133 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2134 if (smbc_parse_path(context, file->fname,
2136 server, sizeof(server),
2137 share, sizeof(share),
2140 password, sizeof(password),
2146 /*d_printf(">>>fstat: resolving %s\n", path);*/
2147 if (!cli_resolve_path("", &file->srv->cli, path,
2148 &targetcli, targetpath))
2150 d_printf("Could not resolve %s\n", path);
2153 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2155 if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2156 &c_time, &a_time, &m_time, NULL, &ino)) {
2157 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2158 &c_time, &a_time, &m_time)) {
2167 smbc_setup_stat(context, st, file->fname, size, mode);
2169 st->st_atime = a_time;
2170 st->st_ctime = c_time;
2171 st->st_mtime = m_time;
2172 st->st_dev = file->srv->dev;
2179 * Routine to open a directory
2180 * We accept the URL syntax explained in smbc_parse_path(), above.
2184 smbc_remove_dir(SMBCFILE *dir)
2186 struct smbc_dir_list *d,*f;
2193 SAFE_FREE(f->dirent);
2198 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2203 add_dirent(SMBCFILE *dir,
2205 const char *comment,
2208 struct smbc_dirent *dirent;
2210 int name_length = (name == NULL ? 0 : strlen(name));
2211 int comment_len = (comment == NULL ? 0 : strlen(comment));
2214 * Allocate space for the dirent, which must be increased by the
2215 * size of the name and the comment and 1 each for the null terminator.
2218 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2220 dirent = SMB_MALLOC(size);
2224 dir->dir_error = ENOMEM;
2229 ZERO_STRUCTP(dirent);
2231 if (dir->dir_list == NULL) {
2233 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2234 if (!dir->dir_list) {
2237 dir->dir_error = ENOMEM;
2241 ZERO_STRUCTP(dir->dir_list);
2243 dir->dir_end = dir->dir_next = dir->dir_list;
2247 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2249 if (!dir->dir_end->next) {
2252 dir->dir_error = ENOMEM;
2256 ZERO_STRUCTP(dir->dir_end->next);
2258 dir->dir_end = dir->dir_end->next;
2261 dir->dir_end->next = NULL;
2262 dir->dir_end->dirent = dirent;
2264 dirent->smbc_type = type;
2265 dirent->namelen = name_length;
2266 dirent->commentlen = comment_len;
2267 dirent->dirlen = size;
2270 * dirent->namelen + 1 includes the null (no null termination needed)
2271 * Ditto for dirent->commentlen.
2272 * The space for the two null bytes was allocated.
2274 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2275 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2276 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2283 list_unique_wg_fn(const char *name,
2285 const char *comment,
2288 SMBCFILE *dir = (SMBCFILE *)state;
2289 struct smbc_dir_list *dir_list;
2290 struct smbc_dirent *dirent;
2294 dirent_type = dir->dir_type;
2296 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2298 /* An error occurred, what do we do? */
2299 /* FIXME: Add some code here */
2302 /* Point to the one just added */
2303 dirent = dir->dir_end->dirent;
2305 /* See if this was a duplicate */
2306 for (dir_list = dir->dir_list;
2307 dir_list != dir->dir_end;
2308 dir_list = dir_list->next) {
2310 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2311 /* Duplicate. End end of list need to be removed. */
2315 if (do_remove && dir_list->next == dir->dir_end) {
2316 /* Found the end of the list. Remove it. */
2317 dir->dir_end = dir_list;
2318 free(dir_list->next);
2320 dir_list->next = NULL;
2327 list_fn(const char *name,
2329 const char *comment,
2332 SMBCFILE *dir = (SMBCFILE *)state;
2336 * We need to process the type a little ...
2338 * Disk share = 0x00000000
2339 * Print share = 0x00000001
2340 * Comms share = 0x00000002 (obsolete?)
2341 * IPC$ share = 0x00000003
2343 * administrative shares:
2344 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2347 if (dir->dir_type == SMBC_FILE_SHARE) {
2350 case 0 | 0x80000000:
2352 dirent_type = SMBC_FILE_SHARE;
2356 dirent_type = SMBC_PRINTER_SHARE;
2360 dirent_type = SMBC_COMMS_SHARE;
2363 case 3 | 0x80000000:
2365 dirent_type = SMBC_IPC_SHARE;
2369 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2374 dirent_type = dir->dir_type;
2377 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2379 /* An error occurred, what do we do? */
2380 /* FIXME: Add some code here */
2386 dir_list_fn(const char *mnt,
2392 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2393 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2395 /* Handle an error ... */
2397 /* FIXME: Add some code ... */
2404 net_share_enum_rpc(struct cli_state *cli,
2405 void (*fn)(const char *name,
2407 const char *comment,
2414 uint32 info_level = 1;
2415 uint32 preferred_len = 0xffffffff;
2417 SRV_SHARE_INFO_CTR ctr;
2419 fstring comment = "";
2421 struct rpc_pipe_client *pipe_hnd;
2424 /* Open the server service pipe */
2425 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2427 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2431 /* Allocate a context for parsing and for the entries in "ctr" */
2432 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2433 if (mem_ctx == NULL) {
2434 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2435 cli_rpc_pipe_close(pipe_hnd);
2439 /* Issue the NetShareEnum RPC call and retrieve the response */
2440 init_enum_hnd(&enum_hnd, 0);
2441 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2448 /* Was it successful? */
2449 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2450 /* Nope. Go clean up. */
2454 /* For each returned entry... */
2455 for (i = 0; i < ctr.num_entries; i++) {
2457 /* pull out the share name */
2458 rpcstr_pull_unistr2_fstring(
2459 name, &ctr.share.info1[i].info_1_str.uni_netname);
2461 /* pull out the share's comment */
2462 rpcstr_pull_unistr2_fstring(
2463 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2465 /* Get the type value */
2466 type = ctr.share.info1[i].info_1.type;
2468 /* Add this share to the list */
2469 (*fn)(name, type, comment, state);
2473 /* Close the server service pipe */
2474 cli_rpc_pipe_close(pipe_hnd);
2476 /* Free all memory which was allocated for this request */
2477 TALLOC_FREE(mem_ctx);
2479 /* Tell 'em if it worked */
2480 return W_ERROR_IS_OK(result) ? 0 : -1;
2486 smbc_opendir_ctx(SMBCCTX *context,
2489 fstring server, share, user, password, options;
2494 SMBCSRV *srv = NULL;
2495 SMBCFILE *dir = NULL;
2496 struct in_addr rem_ip;
2498 if (!context || !context->internal ||
2499 !context->internal->_initialized) {
2500 DEBUG(4, ("no valid context\n"));
2501 errno = EINVAL + 8192;
2507 DEBUG(4, ("no valid fname\n"));
2508 errno = EINVAL + 8193;
2512 if (smbc_parse_path(context, fname,
2513 workgroup, sizeof(workgroup),
2514 server, sizeof(server),
2515 share, sizeof(share),
2518 password, sizeof(password),
2519 options, sizeof(options))) {
2520 DEBUG(4, ("no valid path\n"));
2521 errno = EINVAL + 8194;
2525 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2526 "path='%s' options='%s'\n",
2527 fname, server, share, path, options));
2529 /* Ensure the options are valid */
2530 if (smbc_check_options(server, share, path, options)) {
2531 DEBUG(4, ("unacceptable options (%s)\n", options));
2532 errno = EINVAL + 8195;
2536 if (user[0] == (char)0) fstrcpy(user, context->user);
2538 dir = SMB_MALLOC_P(SMBCFILE);
2550 dir->fname = SMB_STRDUP(fname);
2554 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2556 if (server[0] == (char)0) {
2561 struct ip_service *ip_list;
2562 struct ip_service server_addr;
2563 struct user_auth_info u_info;
2564 struct cli_state *cli;
2566 if (share[0] != (char)0 || path[0] != (char)0) {
2568 errno = EINVAL + 8196;
2570 SAFE_FREE(dir->fname);
2576 /* Determine how many local master browsers to query */
2577 max_lmb_count = (context->options.browse_max_lmb_count == 0
2579 : context->options.browse_max_lmb_count);
2581 pstrcpy(u_info.username, user);
2582 pstrcpy(u_info.password, password);
2585 * We have server and share and path empty but options
2586 * requesting that we scan all master browsers for their list
2587 * of workgroups/domains. This implies that we must first try
2588 * broadcast queries to find all master browsers, and if that
2589 * doesn't work, then try our other methods which return only
2590 * a single master browser.
2594 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2598 if (!find_master_ip(workgroup, &server_addr.ip)) {
2601 SAFE_FREE(dir->fname);
2608 ip_list = &server_addr;
2612 for (i = 0; i < count && i < max_lmb_count; i++) {
2613 DEBUG(99, ("Found master browser %d of %d: %s\n",
2614 i+1, MAX(count, max_lmb_count),
2615 inet_ntoa(ip_list[i].ip)));
2617 cli = get_ipc_connect_master_ip(&ip_list[i],
2618 workgroup, &u_info);
2619 /* cli == NULL is the master browser refused to talk or
2620 could not be found */
2624 fstrcpy(server, cli->desthost);
2627 DEBUG(4, ("using workgroup %s %s\n",
2628 workgroup, server));
2631 * For each returned master browser IP address, get a
2632 * connection to IPC$ on the server if we do not
2633 * already have one, and determine the
2634 * workgroups/domains that it knows about.
2637 srv = smbc_server(context, True, server, "IPC$",
2638 workgroup, user, password);
2644 dir->dir_type = SMBC_WORKGROUP;
2646 /* Now, list the stuff ... */
2648 if (!cli_NetServerEnum(&srv->cli,
2650 SV_TYPE_DOMAIN_ENUM,
2660 * Server not an empty string ... Check the rest and see what
2663 if (*share == '\0') {
2664 if (*path != '\0') {
2666 /* Should not have empty share with path */
2667 errno = EINVAL + 8197;
2669 SAFE_FREE(dir->fname);
2677 * We don't know if <server> is really a server name
2678 * or is a workgroup/domain name. If we already have
2679 * a server structure for it, we'll use it.
2680 * Otherwise, check to see if <server><1D>,
2681 * <server><1B>, or <server><20> translates. We check
2682 * to see if <server> is an IP address first.
2686 * See if we have an existing server. Do not
2687 * establish a connection if one does not already
2690 srv = smbc_server(context, False, server, "IPC$",
2691 workgroup, user, password);
2694 * If no existing server and not an IP addr, look for
2698 !is_ipaddress(server) &&
2699 (resolve_name(server, &rem_ip, 0x1d) || /* LMB */
2700 resolve_name(server, &rem_ip, 0x1b) )) { /* DMB */
2704 dir->dir_type = SMBC_SERVER;
2707 * Get the backup list ...
2709 if (!name_status_find(server, 0, 0,
2710 rem_ip, buserver)) {
2712 DEBUG(0, ("Could not get name of "
2713 "local/domain master browser "
2714 "for server %s\n", server));
2716 SAFE_FREE(dir->fname);
2725 * Get a connection to IPC$ on the server if
2726 * we do not already have one
2728 srv = smbc_server(context, True,
2730 workgroup, user, password);
2732 DEBUG(0, ("got no contact to IPC$\n"));
2734 SAFE_FREE(dir->fname);
2743 /* Now, list the servers ... */
2744 if (!cli_NetServerEnum(&srv->cli, server,
2745 0x0000FFFE, list_fn,
2749 SAFE_FREE(dir->fname);
2755 (resolve_name(server, &rem_ip, 0x20))) {
2757 /* If we hadn't found the server, get one now */
2759 srv = smbc_server(context, True,
2767 SAFE_FREE(dir->fname);
2774 dir->dir_type = SMBC_FILE_SHARE;
2777 /* List the shares ... */
2779 if (net_share_enum_rpc(
2782 (void *) dir) < 0 &&
2788 errno = cli_errno(&srv->cli);
2790 SAFE_FREE(dir->fname);
2797 /* Neither the workgroup nor server exists */
2798 errno = ECONNREFUSED;
2800 SAFE_FREE(dir->fname);
2809 * The server and share are specified ... work from
2813 struct cli_state *targetcli;
2815 /* We connect to the server and list the directory */
2816 dir->dir_type = SMBC_FILE_SHARE;
2818 srv = smbc_server(context, True, server, share,
2819 workgroup, user, password);
2824 SAFE_FREE(dir->fname);
2833 /* Now, list the files ... */
2835 p = path + strlen(path);
2836 pstrcat(path, "\\*");
2838 if (!cli_resolve_path("", &srv->cli, path,
2839 &targetcli, targetpath))
2841 d_printf("Could not resolve %s\n", path);
2843 SAFE_FREE(dir->fname);
2849 if (cli_list(targetcli, targetpath,
2850 aDIR | aSYSTEM | aHIDDEN,
2851 dir_list_fn, (void *)dir) < 0) {
2854 SAFE_FREE(dir->fname);
2857 errno = smbc_errno(context, targetcli);
2859 if (errno == EINVAL) {
2861 * See if they asked to opendir something
2862 * other than a directory. If so, the
2863 * converted error value we got would have
2864 * been EINVAL rather than ENOTDIR.
2866 *p = '\0'; /* restore original path */
2868 if (smbc_getatr(context, srv, path,
2872 ! IS_DOS_DIR(mode)) {
2874 /* It is. Correct the error value */
2886 DLIST_ADD(context->internal->_files, dir);
2892 * Routine to close a directory
2896 smbc_closedir_ctx(SMBCCTX *context,
2900 if (!context || !context->internal ||
2901 !context->internal->_initialized) {
2908 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2915 smbc_remove_dir(dir); /* Clean it up */
2917 DLIST_REMOVE(context->internal->_files, dir);
2921 SAFE_FREE(dir->fname);
2922 SAFE_FREE(dir); /* Free the space too */
2930 smbc_readdir_internal(SMBCCTX * context,
2931 struct smbc_dirent *dest,
2932 struct smbc_dirent *src,
2933 int max_namebuf_len)
2935 if (context->options.urlencode_readdir_entries) {
2937 /* url-encode the name. get back remaining buffer space */
2939 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2941 /* We now know the name length */
2942 dest->namelen = strlen(dest->name);
2944 /* Save the pointer to the beginning of the comment */
2945 dest->comment = dest->name + dest->namelen + 1;
2947 /* Copy the comment */
2948 strncpy(dest->comment, src->comment, max_namebuf_len - 1);
2949 dest->comment[max_namebuf_len - 1] = '\0';
2951 /* Save other fields */
2952 dest->smbc_type = src->smbc_type;
2953 dest->commentlen = strlen(dest->comment);
2954 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2958 /* No encoding. Just copy the entry as is. */
2959 memcpy(dest, src, src->dirlen);
2960 dest->comment = (char *)(&dest->name + src->namelen + 1);
2966 * Routine to get a directory entry
2969 struct smbc_dirent *
2970 smbc_readdir_ctx(SMBCCTX *context,
2974 struct smbc_dirent *dirp, *dirent;
2976 /* Check that all is ok first ... */
2978 if (!context || !context->internal ||
2979 !context->internal->_initialized) {
2982 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2987 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2990 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2995 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2998 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
3003 if (!dir->dir_next) {
3007 dirent = dir->dir_next->dirent;
3015 dirp = (struct smbc_dirent *)context->internal->_dirent;
3016 maxlen = (sizeof(context->internal->_dirent) -
3017 sizeof(struct smbc_dirent));
3019 smbc_readdir_internal(context, dirp, dirent, maxlen);
3021 dir->dir_next = dir->dir_next->next;
3027 * Routine to get directory entries
3031 smbc_getdents_ctx(SMBCCTX *context,
3033 struct smbc_dirent *dirp,
3039 char *ndir = (char *)dirp;
3040 struct smbc_dir_list *dirlist;
3042 /* Check that all is ok first ... */
3044 if (!context || !context->internal ||
3045 !context->internal->_initialized) {
3052 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3059 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3067 * Now, retrieve the number of entries that will fit in what was passed
3068 * We have to figure out if the info is in the list, or we need to
3069 * send a request to the server to get the info.
3072 while ((dirlist = dir->dir_next)) {
3073 struct smbc_dirent *dirent;
3075 if (!dirlist->dirent) {
3077 errno = ENOENT; /* Bad error */
3082 /* Do urlencoding of next entry, if so selected */
3083 dirent = (struct smbc_dirent *)context->internal->_dirent;
3084 maxlen = (sizeof(context->internal->_dirent) -
3085 sizeof(struct smbc_dirent));
3086 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3088 reqd = dirent->dirlen;
3092 if (rem < count) { /* We managed to copy something */
3098 else { /* Nothing copied ... */
3100 errno = EINVAL; /* Not enough space ... */
3107 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3109 ((struct smbc_dirent *)ndir)->comment =
3110 (char *)(&((struct smbc_dirent *)ndir)->name +
3118 dir->dir_next = dirlist = dirlist -> next;
3129 * Routine to create a directory ...
3133 smbc_mkdir_ctx(SMBCCTX *context,
3143 pstring path, targetpath;
3144 struct cli_state *targetcli;
3146 if (!context || !context->internal ||
3147 !context->internal->_initialized) {
3161 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3163 if (smbc_parse_path(context, fname,
3164 workgroup, sizeof(workgroup),
3165 server, sizeof(server),
3166 share, sizeof(share),
3169 password, sizeof(password),
3175 if (user[0] == (char)0) fstrcpy(user, context->user);
3177 srv = smbc_server(context, True,
3178 server, share, workgroup, user, password);
3182 return -1; /* errno set by smbc_server */
3186 /*d_printf(">>>mkdir: resolving %s\n", path);*/
3187 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3189 d_printf("Could not resolve %s\n", path);
3192 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3194 if (!cli_mkdir(targetcli, targetpath)) {
3196 errno = smbc_errno(context, targetcli);
3206 * Our list function simply checks to see if a directory is not empty
3209 static int smbc_rmdir_dirempty = True;
3212 rmdir_list_fn(const char *mnt,
3217 if (strncmp(finfo->name, ".", 1) != 0 &&
3218 strncmp(finfo->name, "..", 2) != 0) {
3220 smbc_rmdir_dirempty = False;
3225 * Routine to remove a directory
3229 smbc_rmdir_ctx(SMBCCTX *context,
3240 struct cli_state *targetcli;
3242 if (!context || !context->internal ||
3243 !context->internal->_initialized) {
3257 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3259 if (smbc_parse_path(context, fname,
3260 workgroup, sizeof(workgroup),
3261 server, sizeof(server),
3262 share, sizeof(share),
3265 password, sizeof(password),
3272 if (user[0] == (char)0) fstrcpy(user, context->user);
3274 srv = smbc_server(context, True,
3275 server, share, workgroup, user, password);
3279 return -1; /* errno set by smbc_server */
3283 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3284 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3286 d_printf("Could not resolve %s\n", path);
3289 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3292 if (!cli_rmdir(targetcli, targetpath)) {
3294 errno = smbc_errno(context, targetcli);
3296 if (errno == EACCES) { /* Check if the dir empty or not */
3298 /* Local storage to avoid buffer overflows */
3301 smbc_rmdir_dirempty = True; /* Make this so ... */
3303 pstrcpy(lpath, targetpath);
3304 pstrcat(lpath, "\\*");
3306 if (cli_list(targetcli, lpath,
3307 aDIR | aSYSTEM | aHIDDEN,
3308 rmdir_list_fn, NULL) < 0) {
3310 /* Fix errno to ignore latest error ... */
3311 DEBUG(5, ("smbc_rmdir: "
3312 "cli_list returned an error: %d\n",
3313 smbc_errno(context, targetcli)));
3318 if (smbc_rmdir_dirempty)
3334 * Routine to return the current directory position
3338 smbc_telldir_ctx(SMBCCTX *context,
3341 off_t ret_val; /* Squash warnings about cast */
3343 if (!context || !context->internal ||
3344 !context->internal->_initialized) {
3351 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3358 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3366 * We return the pointer here as the offset
3368 ret_val = (off_t)(long)dir->dir_next;
3374 * A routine to run down the list and see if the entry is OK
3377 struct smbc_dir_list *
3378 smbc_check_dir_ent(struct smbc_dir_list *list,
3379 struct smbc_dirent *dirent)
3382 /* Run down the list looking for what we want */
3386 struct smbc_dir_list *tmp = list;
3390 if (tmp->dirent == dirent)
3399 return NULL; /* Not found, or an error */
3405 * Routine to seek on a directory
3409 smbc_lseekdir_ctx(SMBCCTX *context,
3413 long int l_offset = offset; /* Handle problems of size */
3414 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3415 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3417 if (!context || !context->internal ||
3418 !context->internal->_initialized) {
3425 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3432 /* Now, check what we were passed and see if it is OK ... */
3434 if (dirent == NULL) { /* Seek to the begining of the list */
3436 dir->dir_next = dir->dir_list;
3441 /* Now, run down the list and make sure that the entry is OK */
3442 /* This may need to be changed if we change the format of the list */
3444 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3446 errno = EINVAL; /* Bad entry */
3451 dir->dir_next = list_ent;
3458 * Routine to fstat a dir
3462 smbc_fstatdir_ctx(SMBCCTX *context,
3467 if (!context || !context->internal ||
3468 !context->internal->_initialized) {
3475 /* No code yet ... */
3482 smbc_chmod_ctx(SMBCCTX *context,
3495 if (!context || !context->internal ||
3496 !context->internal->_initialized) {
3498 errno = EINVAL; /* Best I can think of ... */
3510 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3512 if (smbc_parse_path(context, fname,
3513 workgroup, sizeof(workgroup),
3514 server, sizeof(server),
3515 share, sizeof(share),
3518 password, sizeof(password),
3524 if (user[0] == (char)0) fstrcpy(user, context->user);
3526 srv = smbc_server(context, True,
3527 server, share, workgroup, user, password);
3530 return -1; /* errno set by smbc_server */
3535 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3536 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3537 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3538 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3540 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3541 errno = smbc_errno(context, &srv->cli);
3549 smbc_utimes_ctx(SMBCCTX *context,
3551 struct timeval *tbuf)
3563 if (!context || !context->internal ||
3564 !context->internal->_initialized) {
3566 errno = EINVAL; /* Best I can think of ... */
3579 a_time = m_time = time(NULL);
3581 a_time = tbuf[0].tv_sec;
3582 m_time = tbuf[1].tv_sec;
3591 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf) - 1);
3592 atimebuf[sizeof(atimebuf) - 1] = '\0';
3593 if ((p = strchr(atimebuf, '\n')) != NULL) {
3597 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf) - 1);
3598 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3599 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3603 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3604 fname, atimebuf, mtimebuf);
3607 if (smbc_parse_path(context, fname,
3608 workgroup, sizeof(workgroup),
3609 server, sizeof(server),
3610 share, sizeof(share),
3613 password, sizeof(password),
3619 if (user[0] == (char)0) fstrcpy(user, context->user);
3621 srv = smbc_server(context, True,
3622 server, share, workgroup, user, password);
3625 return -1; /* errno set by smbc_server */
3628 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3629 return -1; /* errno set by smbc_setatr */
3636 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3637 However NT4 gives a "The information may have been modified by a
3638 computer running Windows NT 5.0" if denied ACEs do not appear before
3642 ace_compare(SEC_ACE *ace1,
3645 if (sec_ace_equal(ace1, ace2))
3648 if (ace1->type != ace2->type)
3649 return ace2->type - ace1->type;
3651 if (sid_compare(&ace1->trustee, &ace2->trustee))
3652 return sid_compare(&ace1->trustee, &ace2->trustee);
3654 if (ace1->flags != ace2->flags)
3655 return ace1->flags - ace2->flags;
3657 if (ace1->info.mask != ace2->info.mask)
3658 return ace1->info.mask - ace2->info.mask;
3660 if (ace1->size != ace2->size)
3661 return ace1->size - ace2->size;
3663 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3668 sort_acl(SEC_ACL *the_acl)
3671 if (!the_acl) return;
3673 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]),
3674 QSORT_CAST ace_compare);
3676 for (i=1;i<the_acl->num_aces;) {
3677 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3679 for (j=i; j<the_acl->num_aces-1; j++) {
3680 the_acl->ace[j] = the_acl->ace[j+1];
3682 the_acl->num_aces--;
3689 /* convert a SID to a string, either numeric or username/group */
3691 convert_sid_to_string(struct cli_state *ipc_cli,
3697 char **domains = NULL;
3698 char **names = NULL;
3699 uint32 *types = NULL;
3700 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3701 sid_to_string(str, sid);
3704 return; /* no lookup desired */
3711 /* Ask LSA to convert the sid to a name */
3713 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3714 pol, 1, sid, &domains,
3716 !domains || !domains[0] || !names || !names[0]) {
3722 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3723 domains[0], lp_winbind_separator(),
3727 /* convert a string to a SID, either numeric or username/group */
3729 convert_string_to_sid(struct cli_state *ipc_cli,
3735 uint32 *types = NULL;
3736 DOM_SID *sids = NULL;
3738 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3745 if (strncmp(str, "S-", 2) == 0) {
3746 return string_to_sid(sid, str);
3753 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3754 pol, 1, &str, NULL, &sids,
3760 sid_copy(sid, &sids[0]);
3767 /* parse an ACE in the same format as print_ace() */
3769 parse_ace(struct cli_state *ipc_cli,
3779 unsigned int aflags;
3783 const struct perm_value *v;
3789 /* These values discovered by inspection */
3790 static const struct perm_value special_values[] = {
3791 { "R", 0x00120089 },
3792 { "W", 0x00120116 },
3793 { "X", 0x001200a0 },
3794 { "D", 0x00010000 },
3795 { "P", 0x00040000 },
3796 { "O", 0x00080000 },
3800 static const struct perm_value standard_values[] = {
3801 { "READ", 0x001200a9 },
3802 { "CHANGE", 0x001301bf },
3803 { "FULL", 0x001f01ff },
3809 p = strchr_m(str,':');
3810 if (!p) return False;
3813 /* Try to parse numeric form */
3815 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3816 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3820 /* Try to parse text form */
3822 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3827 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3831 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3832 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3833 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3834 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3839 /* Only numeric form accepted for flags at present */
3841 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3842 sscanf(tok, "%i", &aflags))) {
3846 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3850 if (strncmp(tok, "0x", 2) == 0) {
3851 if (sscanf(tok, "%i", &amask) != 1) {
3857 for (v = standard_values; v->perm; v++) {
3858 if (strcmp(tok, v->perm) == 0) {
3869 for (v = special_values; v->perm; v++) {
3870 if (v->perm[0] == *p) {
3876 if (!found) return False;
3886 init_sec_ace(ace, &sid, atype, mask, aflags);
3890 /* add an ACE to a list of ACEs in a SEC_ACL */
3892 add_ace(SEC_ACL **the_acl,
3900 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3904 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3905 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3906 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3907 newacl = make_sec_acl(ctx, (*the_acl)->revision,
3908 1+(*the_acl)->num_aces, aces);
3910 (*the_acl) = newacl;
3915 /* parse a ascii version of a security descriptor */
3917 sec_desc_parse(TALLOC_CTX *ctx,
3918 struct cli_state *ipc_cli,
3923 const char *p = str;
3925 SEC_DESC *ret = NULL;
3927 DOM_SID *grp_sid=NULL;
3928 DOM_SID *owner_sid=NULL;
3932 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3934 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3935 revision = strtol(tok+9, NULL, 16);
3939 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3941 DEBUG(5, ("OWNER specified more than once!\n"));
3944 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3946 !convert_string_to_sid(ipc_cli, pol,
3948 owner_sid, tok+6)) {
3949 DEBUG(5, ("Failed to parse owner sid\n"));
3955 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3957 DEBUG(5, ("OWNER specified more than once!\n"));
3960 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3962 !convert_string_to_sid(ipc_cli, pol,
3964 owner_sid, tok+7)) {
3965 DEBUG(5, ("Failed to parse owner sid\n"));
3971 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3973 DEBUG(5, ("GROUP specified more than once!\n"));
3976 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3978 !convert_string_to_sid(ipc_cli, pol,
3981 DEBUG(5, ("Failed to parse group sid\n"));
3987 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3989 DEBUG(5, ("GROUP specified more than once!\n"));
3992 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3994 !convert_string_to_sid(ipc_cli, pol,
3997 DEBUG(5, ("Failed to parse group sid\n"));
4003 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
4005 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
4006 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4009 if(!add_ace(&dacl, &ace, ctx)) {
4010 DEBUG(5, ("Failed to add ACL %s\n", tok));
4016 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
4018 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
4019 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4022 if(!add_ace(&dacl, &ace, ctx)) {
4023 DEBUG(5, ("Failed to add ACL %s\n", tok));
4029 DEBUG(5, ("Failed to parse security descriptor\n"));
4033 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
4034 owner_sid, grp_sid, NULL, dacl, &sd_size);
4038 SAFE_FREE(owner_sid);
4044 /* Obtain the current dos attributes */
4045 static DOS_ATTR_DESC *
4046 dos_attr_query(SMBCCTX *context,
4048 const char *filename,
4051 time_t m_time = 0, a_time = 0, c_time = 0;
4054 SMB_INO_T inode = 0;
4057 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
4063 /* Obtain the DOS attributes */
4064 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
4066 &c_time, &a_time, &m_time, &inode)) {
4068 errno = smbc_errno(context, &srv->cli);
4069 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
4076 ret->a_time = a_time;
4077 ret->c_time = c_time;
4078 ret->m_time = m_time;
4085 /* parse a ascii version of a security descriptor */
4087 dos_attr_parse(SMBCCTX *context,
4092 const char *p = str;
4095 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4097 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
4098 dad->mode = strtol(tok+5, NULL, 16);
4102 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4103 dad->size = (SMB_OFF_T)atof(tok+5);
4107 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
4108 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
4112 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
4113 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
4117 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
4118 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
4122 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4123 dad->inode = (SMB_INO_T)atof(tok+6);
4129 /*****************************************************
4130 Retrieve the acls for a file.
4131 *******************************************************/
4134 cacl_get(SMBCCTX *context,
4137 struct cli_state *ipc_cli,
4153 BOOL exclude_nt_revision = False;
4154 BOOL exclude_nt_owner = False;
4155 BOOL exclude_nt_group = False;
4156 BOOL exclude_nt_acl = False;
4157 BOOL exclude_dos_mode = False;
4158 BOOL exclude_dos_size = False;
4159 BOOL exclude_dos_ctime = False;
4160 BOOL exclude_dos_atime = False;
4161 BOOL exclude_dos_mtime = False;
4162 BOOL exclude_dos_inode = False;
4163 BOOL numeric = True;
4164 BOOL determine_size = (bufsize == 0);
4168 fstring name_sandbox;
4172 time_t m_time = 0, a_time = 0, c_time = 0;
4176 struct cli_state *cli = &srv->cli;
4178 /* Copy name so we can strip off exclusions (if any are specified) */
4179 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4181 /* Ensure name is null terminated */
4182 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4184 /* Play in the sandbox */
4185 name = name_sandbox;
4187 /* If there are any exclusions, point to them and mask them from name */
4188 if ((pExclude = strchr(name, '!')) != NULL)
4193 all = (StrnCaseCmp(name, "system.*", 8) == 0);
4194 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4195 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4196 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4197 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4198 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4199 numeric = (* (name + strlen(name) - 1) != '+');
4201 /* Look for exclusions from "all" requests */
4202 if (all || all_nt || all_dos) {
4204 /* Exclusions are delimited by '!' */
4207 pExclude = (p == NULL ? NULL : p + 1)) {
4209 /* Find end of this exclusion name */
4210 if ((p = strchr(pExclude, '!')) != NULL)
4215 /* Which exclusion name is this? */
4216 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4217 exclude_nt_revision = True;
4219 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4220 exclude_nt_owner = True;
4222 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4223 exclude_nt_group = True;
4225 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4226 exclude_nt_acl = True;
4228 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4229 exclude_dos_mode = True;
4231 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4232 exclude_dos_size = True;
4234 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
4235 exclude_dos_ctime = True;
4237 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
4238 exclude_dos_atime = True;
4240 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
4241 exclude_dos_mtime = True;
4243 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4244 exclude_dos_inode = True;
4247 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4258 * If we are (possibly) talking to an NT or new system and some NT
4259 * attributes have been requested...
4261 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4262 /* Point to the portion after "system.nt_sec_desc." */
4263 name += 19; /* if (all) this will be invalid but unused */
4265 /* ... then obtain any NT attributes which were requested */
4266 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4269 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4270 filename, cli_errstr(cli)));
4275 sd = cli_query_secdesc(cli, fnum, ctx);
4279 ("cacl_get Failed to query old descriptor\n"));
4284 cli_close(cli, fnum);
4286 if (! exclude_nt_revision) {
4287 if (all || all_nt) {
4288 if (determine_size) {
4289 p = talloc_asprintf(ctx,
4298 n = snprintf(buf, bufsize,
4302 } else if (StrCaseCmp(name, "revision") == 0) {
4303 if (determine_size) {
4304 p = talloc_asprintf(ctx, "%d",
4312 n = snprintf(buf, bufsize, "%d",
4317 if (!determine_size && n > bufsize) {
4326 if (! exclude_nt_owner) {
4327 /* Get owner and group sid */
4328 if (sd->owner_sid) {
4329 convert_sid_to_string(ipc_cli, pol,
4334 fstrcpy(sidstr, "");
4337 if (all || all_nt) {
4338 if (determine_size) {
4339 p = talloc_asprintf(ctx, ",OWNER:%s",
4347 n = snprintf(buf, bufsize,
4348 ",OWNER:%s", sidstr);
4350 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4351 if (determine_size) {
4352 p = talloc_asprintf(ctx, "%s", sidstr);
4359 n = snprintf(buf, bufsize, "%s",
4364 if (!determine_size && n > bufsize) {
4373 if (! exclude_nt_group) {
4375 convert_sid_to_string(ipc_cli, pol,
4379 fstrcpy(sidstr, "");
4382 if (all || all_nt) {
4383 if (determine_size) {
4384 p = talloc_asprintf(ctx, ",GROUP:%s",
4392 n = snprintf(buf, bufsize,
4393 ",GROUP:%s", sidstr);
4395 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4396 if (determine_size) {
4397 p = talloc_asprintf(ctx, "%s", sidstr);
4404 n = snprintf(buf, bufsize,
4409 if (!determine_size && n > bufsize) {
4418 if (! exclude_nt_acl) {
4419 /* Add aces to value buffer */
4420 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4422 SEC_ACE *ace = &sd->dacl->ace[i];
4423 convert_sid_to_string(ipc_cli, pol,
4427 if (all || all_nt) {
4428 if (determine_size) {
4429 p = talloc_asprintf(
4445 ",ACL:%s:%d/%d/0x%08x",
4451 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4452 StrCaseCmp(name+3, sidstr) == 0) ||
4453 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4454 StrCaseCmp(name+4, sidstr) == 0)) {
4455 if (determine_size) {
4456 p = talloc_asprintf(
4468 n = snprintf(buf, bufsize,
4474 } else if (all_nt_acls) {
4475 if (determine_size) {
4476 p = talloc_asprintf(
4478 "%s%s:%d/%d/0x%08x",
4490 n = snprintf(buf, bufsize,
4491 "%s%s:%d/%d/0x%08x",
4509 /* Restore name pointer to its original value */
4513 if (all || some_dos) {
4514 /* Point to the portion after "system.dos_attr." */
4515 name += 16; /* if (all) this will be invalid but unused */
4517 /* Obtain the DOS attributes */
4518 if (!smbc_getatr(context, srv, filename, &mode, &size,
4519 &c_time, &a_time, &m_time, &ino)) {
4521 errno = smbc_errno(context, &srv->cli);
4526 if (! exclude_dos_mode) {
4527 if (all || all_dos) {
4528 if (determine_size) {
4529 p = talloc_asprintf(ctx,
4542 n = snprintf(buf, bufsize,
4550 } else if (StrCaseCmp(name, "mode") == 0) {
4551 if (determine_size) {
4552 p = talloc_asprintf(ctx, "0x%x", mode);
4559 n = snprintf(buf, bufsize,
4564 if (!determine_size && n > bufsize) {
4573 if (! exclude_dos_size) {
4574 if (all || all_dos) {
4575 if (determine_size) {
4576 p = talloc_asprintf(
4586 n = snprintf(buf, bufsize,
4590 } else if (StrCaseCmp(name, "size") == 0) {
4591 if (determine_size) {
4592 p = talloc_asprintf(
4602 n = snprintf(buf, bufsize,
4608 if (!determine_size && n > bufsize) {
4617 if (! exclude_dos_ctime) {
4618 if (all || all_dos) {
4619 if (determine_size) {
4620 p = talloc_asprintf(ctx,
4629 n = snprintf(buf, bufsize,
4630 ",C_TIME:%lu", c_time);
4632 } else if (StrCaseCmp(name, "c_time") == 0) {
4633 if (determine_size) {
4634 p = talloc_asprintf(ctx, "%lu", c_time);
4641 n = snprintf(buf, bufsize,
4646 if (!determine_size && n > bufsize) {
4655 if (! exclude_dos_atime) {
4656 if (all || all_dos) {
4657 if (determine_size) {
4658 p = talloc_asprintf(ctx,
4667 n = snprintf(buf, bufsize,
4668 ",A_TIME:%lu", a_time);
4670 } else if (StrCaseCmp(name, "a_time") == 0) {
4671 if (determine_size) {
4672 p = talloc_asprintf(ctx, "%lu", a_time);
4679 n = snprintf(buf, bufsize,
4684 if (!determine_size && n > bufsize) {
4693 if (! exclude_dos_mtime) {
4694 if (all || all_dos) {
4695 if (determine_size) {
4696 p = talloc_asprintf(ctx,
4705 n = snprintf(buf, bufsize,
4706 ",M_TIME:%lu", m_time);
4708 } else if (StrCaseCmp(name, "m_time") == 0) {
4709 if (determine_size) {
4710 p = talloc_asprintf(ctx, "%lu", m_time);
4717 n = snprintf(buf, bufsize,
4722 if (!determine_size && n > bufsize) {
4731 if (! exclude_dos_inode) {
4732 if (all || all_dos) {
4733 if (determine_size) {
4734 p = talloc_asprintf(
4744 n = snprintf(buf, bufsize,
4748 } else if (StrCaseCmp(name, "inode") == 0) {
4749 if (determine_size) {
4750 p = talloc_asprintf(
4760 n = snprintf(buf, bufsize,
4766 if (!determine_size && n > bufsize) {
4775 /* Restore name pointer to its original value */
4788 /*****************************************************
4789 set the ACLs on a file given an ascii description
4790 *******************************************************/
4792 cacl_set(TALLOC_CTX *ctx,
4793 struct cli_state *cli,
4794 struct cli_state *ipc_cli,
4796 const char *filename,
4797 const char *the_acl,
4803 SEC_DESC *sd = NULL, *old;
4804 SEC_ACL *dacl = NULL;
4805 DOM_SID *owner_sid = NULL;
4806 DOM_SID *grp_sid = NULL;
4811 BOOL numeric = True;
4813 /* the_acl will be null for REMOVE_ALL operations */
4815 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4819 /* if this is to set the entire ACL... */
4820 if (*the_acl == '*') {
4821 /* ... then increment past the first colon */
4825 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4826 CONST_DISCARD(char *, the_acl));
4834 /* SMBC_XATTR_MODE_REMOVE_ALL is the only caller
4835 that doesn't deref sd */
4837 if (!sd && (mode != SMBC_XATTR_MODE_REMOVE_ALL)) {
4842 /* The desired access below is the only one I could find that works
4843 with NT4, W2KP and Samba */
4845 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4848 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4849 filename, cli_errstr(cli)));
4854 old = cli_query_secdesc(cli, fnum, ctx);
4857 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4862 cli_close(cli, fnum);
4865 case SMBC_XATTR_MODE_REMOVE_ALL:
4866 old->dacl->num_aces = 0;
4867 SAFE_FREE(old->dacl->ace);
4868 SAFE_FREE(old->dacl);
4873 case SMBC_XATTR_MODE_REMOVE:
4874 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4877 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4878 if (sec_ace_equal(&sd->dacl->ace[i],
4879 &old->dacl->ace[j])) {
4881 for (k=j; k<old->dacl->num_aces-1;k++) {
4883 old->dacl->ace[k+1];
4885 old->dacl->num_aces--;
4886 if (old->dacl->num_aces == 0) {
4887 SAFE_FREE(old->dacl->ace);
4888 SAFE_FREE(old->dacl);
4905 case SMBC_XATTR_MODE_ADD:
4906 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4909 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4910 if (sid_equal(&sd->dacl->ace[i].trustee,
4911 &old->dacl->ace[j].trustee)) {
4912 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4917 old->dacl->ace[j] = sd->dacl->ace[i];
4923 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4929 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4930 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4936 case SMBC_XATTR_MODE_SET:
4938 owner_sid = old->owner_sid;
4939 grp_sid = old->grp_sid;
4943 case SMBC_XATTR_MODE_CHOWN:
4944 owner_sid = sd->owner_sid;
4947 case SMBC_XATTR_MODE_CHGRP:
4948 grp_sid = sd->grp_sid;
4952 /* Denied ACE entries must come before allowed ones */
4953 sort_acl(old->dacl);
4955 /* Create new security descriptor and set it */
4956 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4957 owner_sid, grp_sid, NULL, dacl, &sd_size);
4959 fnum = cli_nt_create(cli, filename,
4960 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4963 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4964 filename, cli_errstr(cli)));
4969 if (!cli_set_secdesc(cli, fnum, sd)) {
4970 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4977 cli_close(cli, fnum);
4988 smbc_setxattr_ctx(SMBCCTX *context,
5009 if (!context || !context->internal ||
5010 !context->internal->_initialized) {
5012 errno = EINVAL; /* Best I can think of ... */
5024 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
5025 fname, name, (int) size, (const char*)value));
5027 if (smbc_parse_path(context, fname,
5028 workgroup, sizeof(workgroup),
5029 server, sizeof(server),
5030 share, sizeof(share),
5033 password, sizeof(password),
5039 if (user[0] == (char)0) fstrcpy(user, context->user);
5041 srv = smbc_server(context, True,
5042 server, share, workgroup, user, password);
5044 return -1; /* errno set by smbc_server */
5047 if (! srv->no_nt_session) {
5048 ipc_srv = smbc_attr_server(context, server, share,
5049 workgroup, user, password,
5051 srv->no_nt_session = True;
5056 ctx = talloc_init("smbc_setxattr");
5063 * Are they asking to set the entire set of known attributes?
5065 if (StrCaseCmp(name, "system.*") == 0 ||
5066 StrCaseCmp(name, "system.*+") == 0) {
5069 talloc_asprintf(ctx, "%s:%s",
5070 name+7, (const char *) value);
5078 ret = cacl_set(ctx, &srv->cli,
5079 &ipc_srv->cli, &pol, path,
5082 ? SMBC_XATTR_MODE_SET
5083 : SMBC_XATTR_MODE_ADD),
5089 /* get a DOS Attribute Descriptor with current attributes */
5090 dad = dos_attr_query(context, ctx, path, srv);
5092 /* Overwrite old with new, using what was provided */
5093 dos_attr_parse(context, dad, srv, namevalue);
5095 /* Set the new DOS attributes */
5096 if (! smbc_setatr(context, srv, path,
5102 /* cause failure if NT failed too */
5107 /* we only fail if both NT and DOS sets failed */
5108 if (ret < 0 && ! dad) {
5109 ret = -1; /* in case dad was null */
5115 talloc_destroy(ctx);
5120 * Are they asking to set an access control element or to set
5121 * the entire access control list?
5123 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5124 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5125 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5126 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5127 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5131 talloc_asprintf(ctx, "%s:%s",
5132 name+19, (const char *) value);
5135 ret = -1; /* errno set by smbc_server() */
5137 else if (! namevalue) {
5141 ret = cacl_set(ctx, &srv->cli,
5142 &ipc_srv->cli, &pol, path,
5145 ? SMBC_XATTR_MODE_SET
5146 : SMBC_XATTR_MODE_ADD),
5149 talloc_destroy(ctx);
5154 * Are they asking to set the owner?
5156 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5157 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5161 talloc_asprintf(ctx, "%s:%s",
5162 name+19, (const char *) value);
5166 ret = -1; /* errno set by smbc_server() */
5168 else if (! namevalue) {
5172 ret = cacl_set(ctx, &srv->cli,
5173 &ipc_srv->cli, &pol, path,
5174 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5176 talloc_destroy(ctx);
5181 * Are they asking to set the group?
5183 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5184 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5188 talloc_asprintf(ctx, "%s:%s",
5189 name+19, (const char *) value);
5192 /* errno set by smbc_server() */
5195 else if (! namevalue) {
5199 ret = cacl_set(ctx, &srv->cli,
5200 &ipc_srv->cli, &pol, path,
5201 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5203 talloc_destroy(ctx);
5208 * Are they asking to set a DOS attribute?
5210 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5211 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5212 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5213 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5214 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
5216 /* get a DOS Attribute Descriptor with current attributes */
5217 dad = dos_attr_query(context, ctx, path, srv);
5220 talloc_asprintf(ctx, "%s:%s",
5221 name+16, (const char *) value);
5226 /* Overwrite old with provided new params */
5227 dos_attr_parse(context, dad, srv, namevalue);
5229 /* Set the new DOS attributes */
5230 ret2 = smbc_setatr(context, srv, path,
5236 /* ret2 has True (success) / False (failure) */
5247 talloc_destroy(ctx);
5251 /* Unsupported attribute name */
5252 talloc_destroy(ctx);
5258 smbc_getxattr_ctx(SMBCCTX *context,
5277 if (!context || !context->internal ||
5278 !context->internal->_initialized) {
5280 errno = EINVAL; /* Best I can think of ... */
5292 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5294 if (smbc_parse_path(context, fname,
5295 workgroup, sizeof(workgroup),
5296 server, sizeof(server),
5297 share, sizeof(share),
5300 password, sizeof(password),
5306 if (user[0] == (char)0) fstrcpy(user, context->user);
5308 srv = smbc_server(context, True,
5309 server, share, workgroup, user, password);
5311 return -1; /* errno set by smbc_server */
5314 if (! srv->no_nt_session) {
5315 ipc_srv = smbc_attr_server(context, server, share,
5316 workgroup, user, password,
5319 srv->no_nt_session = True;
5325 ctx = talloc_init("smbc:getxattr");
5331 /* Are they requesting a supported attribute? */
5332 if (StrCaseCmp(name, "system.*") == 0 ||
5333 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5334 StrCaseCmp(name, "system.*+") == 0 ||
5335 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5336 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5337 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5338 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5339 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5340 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5341 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5342 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5343 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5344 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5345 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5346 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5347 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5348 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5349 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5350 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5351 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5352 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5353 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
5354 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5357 ret = cacl_get(context, ctx, srv,
5358 ipc_srv == NULL ? NULL : &ipc_srv->cli,
5360 CONST_DISCARD(char *, name),
5361 CONST_DISCARD(char *, value), size);
5362 if (ret < 0 && errno == 0) {
5363 errno = smbc_errno(context, &srv->cli);
5365 talloc_destroy(ctx);
5369 /* Unsupported attribute name */
5370 talloc_destroy(ctx);
5377 smbc_removexattr_ctx(SMBCCTX *context,
5393 if (!context || !context->internal ||
5394 !context->internal->_initialized) {
5396 errno = EINVAL; /* Best I can think of ... */
5408 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5410 if (smbc_parse_path(context, fname,
5411 workgroup, sizeof(workgroup),
5412 server, sizeof(server),
5413 share, sizeof(share),
5416 password, sizeof(password),
5422 if (user[0] == (char)0) fstrcpy(user, context->user);
5424 srv = smbc_server(context, True,
5425 server, share, workgroup, user, password);
5427 return -1; /* errno set by smbc_server */
5430 if (! srv->no_nt_session) {
5431 ipc_srv = smbc_attr_server(context, server, share,
5432 workgroup, user, password,
5434 srv->no_nt_session = True;
5440 return -1; /* errno set by smbc_attr_server */
5443 ctx = talloc_init("smbc_removexattr");
5449 /* Are they asking to set the entire ACL? */
5450 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5451 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5454 ret = cacl_set(ctx, &srv->cli,
5455 &ipc_srv->cli, &pol, path,
5456 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5457 talloc_destroy(ctx);
5462 * Are they asking to remove one or more spceific security descriptor
5465 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5466 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5467 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5468 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5469 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5470 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5471 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5474 ret = cacl_set(ctx, &srv->cli,
5475 &ipc_srv->cli, &pol, path,
5476 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5477 talloc_destroy(ctx);
5481 /* Unsupported attribute name */
5482 talloc_destroy(ctx);
5488 smbc_listxattr_ctx(SMBCCTX *context,
5494 * This isn't quite what listxattr() is supposed to do. This returns
5495 * the complete set of attribute names, always, rather than only those
5496 * attribute names which actually exist for a file. Hmmm...
5498 const char supported[] =
5501 "system.nt_sec_desc.revision\0"
5502 "system.nt_sec_desc.owner\0"
5503 "system.nt_sec_desc.owner+\0"
5504 "system.nt_sec_desc.group\0"
5505 "system.nt_sec_desc.group+\0"
5506 "system.nt_sec_desc.acl.*\0"
5507 "system.nt_sec_desc.acl\0"
5508 "system.nt_sec_desc.acl+\0"
5509 "system.nt_sec_desc.*\0"
5510 "system.nt_sec_desc.*+\0"
5511 "system.dos_attr.*\0"
5512 "system.dos_attr.mode\0"
5513 "system.dos_attr.c_time\0"
5514 "system.dos_attr.a_time\0"
5515 "system.dos_attr.m_time\0"
5519 return sizeof(supported);
5522 if (sizeof(supported) > size) {
5527 /* this can't be strcpy() because there are embedded null characters */
5528 memcpy(list, supported, sizeof(supported));
5529 return sizeof(supported);
5534 * Open a print file to be written to by other calls
5538 smbc_open_print_job_ctx(SMBCCTX *context,
5547 if (!context || !context->internal ||
5548 !context->internal->_initialized) {
5562 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5564 if (smbc_parse_path(context, fname,
5566 server, sizeof(server),
5567 share, sizeof(share),
5570 password, sizeof(password),
5576 /* What if the path is empty, or the file exists? */
5578 return context->open(context, fname, O_WRONLY, 666);
5583 * Routine to print a file on a remote server ...
5585 * We open the file, which we assume to be on a remote server, and then
5586 * copy it to a print file on the share specified by printq.
5590 smbc_print_file_ctx(SMBCCTX *c_file,
5602 if (!c_file || !c_file->internal->_initialized || !c_print ||
5603 !c_print->internal->_initialized) {
5610 if (!fname && !printq) {
5617 /* Try to open the file for reading ... */
5619 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5621 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5622 return -1; /* smbc_open sets errno */
5626 /* Now, try to open the printer file for writing */
5628 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5630 saverr = errno; /* Save errno */
5631 c_file->close_fn(c_file, fid1);
5637 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5641 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5644 c_file->close_fn(c_file, fid1);
5645 c_print->close_fn(c_print, fid2);
5654 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5655 c_print->close_fn(c_print, fid2);
5669 * Routine to list print jobs on a printer share ...
5673 smbc_list_print_jobs_ctx(SMBCCTX *context,
5675 smbc_list_print_job_fn fn)
5685 if (!context || !context->internal ||
5686 !context->internal->_initialized) {
5700 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5702 if (smbc_parse_path(context, fname,
5703 workgroup, sizeof(workgroup),
5704 server, sizeof(server),
5705 share, sizeof(share),
5708 password, sizeof(password),
5714 if (user[0] == (char)0) fstrcpy(user, context->user);
5716 srv = smbc_server(context, True,
5717 server, share, workgroup, user, password);
5721 return -1; /* errno set by smbc_server */
5725 if (cli_print_queue(&srv->cli,
5726 (void (*)(struct print_job_info *))fn) < 0) {
5728 errno = smbc_errno(context, &srv->cli);
5738 * Delete a print job from a remote printer share
5742 smbc_unlink_print_job_ctx(SMBCCTX *context,
5755 if (!context || !context->internal ||
5756 !context->internal->_initialized) {
5770 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5772 if (smbc_parse_path(context, fname,
5773 workgroup, sizeof(workgroup),
5774 server, sizeof(server),
5775 share, sizeof(share),
5778 password, sizeof(password),
5784 if (user[0] == (char)0) fstrcpy(user, context->user);
5786 srv = smbc_server(context, True,
5787 server, share, workgroup, user, password);
5791 return -1; /* errno set by smbc_server */
5795 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5798 errno = smbc_errno(context, &srv->cli);
5799 else if (err == ERRnosuchprintjob)
5810 * Get a new empty handle to fill in with your own info
5813 smbc_new_context(void)
5817 context = SMB_MALLOC_P(SMBCCTX);
5823 ZERO_STRUCTP(context);
5825 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5826 if (!context->internal) {
5832 ZERO_STRUCTP(context->internal);
5835 /* ADD REASONABLE DEFAULTS */
5837 context->timeout = 20000; /* 20 seconds */
5839 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5840 context->options.urlencode_readdir_entries = False;/* backward compat */
5841 context->options.one_share_per_server = False;/* backward compat */
5843 context->open = smbc_open_ctx;
5844 context->creat = smbc_creat_ctx;
5845 context->read = smbc_read_ctx;
5846 context->write = smbc_write_ctx;
5847 context->close_fn = smbc_close_ctx;
5848 context->unlink = smbc_unlink_ctx;
5849 context->rename = smbc_rename_ctx;
5850 context->lseek = smbc_lseek_ctx;
5851 context->stat = smbc_stat_ctx;
5852 context->fstat = smbc_fstat_ctx;
5853 context->opendir = smbc_opendir_ctx;
5854 context->closedir = smbc_closedir_ctx;
5855 context->readdir = smbc_readdir_ctx;
5856 context->getdents = smbc_getdents_ctx;
5857 context->mkdir = smbc_mkdir_ctx;
5858 context->rmdir = smbc_rmdir_ctx;
5859 context->telldir = smbc_telldir_ctx;
5860 context->lseekdir = smbc_lseekdir_ctx;
5861 context->fstatdir = smbc_fstatdir_ctx;
5862 context->chmod = smbc_chmod_ctx;
5863 context->utimes = smbc_utimes_ctx;
5864 context->setxattr = smbc_setxattr_ctx;
5865 context->getxattr = smbc_getxattr_ctx;
5866 context->removexattr = smbc_removexattr_ctx;
5867 context->listxattr = smbc_listxattr_ctx;
5868 context->open_print_job = smbc_open_print_job_ctx;
5869 context->print_file = smbc_print_file_ctx;
5870 context->list_print_jobs = smbc_list_print_jobs_ctx;
5871 context->unlink_print_job = smbc_unlink_print_job_ctx;
5873 context->callbacks.check_server_fn = smbc_check_server;
5874 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5876 smbc_default_cache_functions(context);
5884 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5885 * and thus you'll be leaking memory if not handled properly.
5889 smbc_free_context(SMBCCTX *context,
5899 DEBUG(1,("Performing aggressive shutdown.\n"));
5901 f = context->internal->_files;
5903 context->close_fn(context, f);
5906 context->internal->_files = NULL;
5908 /* First try to remove the servers the nice way. */
5909 if (context->callbacks.purge_cached_fn(context)) {
5912 DEBUG(1, ("Could not purge all servers, "
5913 "Nice way shutdown failed.\n"));
5914 s = context->internal->_servers;
5916 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
5918 cli_shutdown(&s->cli);
5919 context->callbacks.remove_cached_srv_fn(context,
5922 DLIST_REMOVE(context->internal->_servers, s);
5926 context->internal->_servers = NULL;
5930 /* This is the polite way */
5931 if (context->callbacks.purge_cached_fn(context)) {
5932 DEBUG(1, ("Could not purge all servers, "
5933 "free_context failed.\n"));
5937 if (context->internal->_servers) {
5938 DEBUG(1, ("Active servers in context, "
5939 "free_context failed.\n"));
5943 if (context->internal->_files) {
5944 DEBUG(1, ("Active files in context, "
5945 "free_context failed.\n"));
5951 /* Things we have to clean up */
5952 SAFE_FREE(context->workgroup);
5953 SAFE_FREE(context->netbios_name);
5954 SAFE_FREE(context->user);
5956 DEBUG(3, ("Context %p succesfully freed\n", context));
5957 SAFE_FREE(context->internal);
5964 * Each time the context structure is changed, we have binary backward
5965 * compatibility issues. Instead of modifying the public portions of the
5966 * context structure to add new options, instead, we put them in the internal
5967 * portion of the context structure and provide a set function for these new
5971 smbc_option_set(SMBCCTX *context,
5975 if (strcmp(option_name, "debug_stderr") == 0) {
5977 * Log to standard error instead of standard output.
5979 context->internal->_debug_stderr = True;
5985 * Initialise the library etc
5987 * We accept a struct containing handle information.
5988 * valid values for info->debug from 0 to 100,
5989 * and insist that info->fn must be non-null.
5992 smbc_init_context(SMBCCTX *context)
5999 if (!context || !context->internal) {
6004 /* Do not initialise the same client twice */
6005 if (context->internal->_initialized) {
6009 if (!context->callbacks.auth_fn ||
6010 context->debug < 0 ||
6011 context->debug > 100) {
6018 if (!smbc_initialized) {
6020 * Do some library-wide intializations the first time we get
6023 BOOL conf_loaded = False;
6025 /* Set this to what the user wants */
6026 DEBUGLEVEL = context->debug;
6030 setup_logging("libsmbclient", True);
6031 if (context->internal->_debug_stderr) {
6033 x_setbuf(x_stderr, NULL);
6036 /* Here we would open the smb.conf file if needed ... */
6038 in_client = True; /* FIXME, make a param */
6040 home = getenv("HOME");
6042 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
6043 if (lp_load(conf, True, False, False, True)) {
6046 DEBUG(5, ("Could not load config file: %s\n",
6053 * Well, if that failed, try the dyn_CONFIGFILE
6054 * Which points to the standard locn, and if that
6055 * fails, silently ignore it and use the internal
6059 if (!lp_load(dyn_CONFIGFILE, True, False, False, False)) {
6060 DEBUG(5, ("Could not load config file: %s\n",
6064 * We loaded the global config file. Now lets
6065 * load user-specific modifications to the
6068 slprintf(conf, sizeof(conf),
6069 "%s/.smb/smb.conf.append", home);
6070 if (!lp_load(conf, True, False, False, False)) {
6072 ("Could not append config file: "
6079 load_interfaces(); /* Load the list of interfaces ... */
6081 reopen_logs(); /* Get logging working ... */
6084 * Block SIGPIPE (from lib/util_sock.c: write())
6085 * It is not needed and should not stop execution
6087 BlockSignals(True, SIGPIPE);
6089 /* Done with one-time initialisation */
6090 smbc_initialized = 1;
6094 if (!context->user) {
6096 * FIXME: Is this the best way to get the user info?
6098 user = getenv("USER");
6099 /* walk around as "guest" if no username can be found */
6100 if (!user) context->user = SMB_STRDUP("guest");
6101 else context->user = SMB_STRDUP(user);
6104 if (!context->netbios_name) {
6106 * We try to get our netbios name from the config. If that
6107 * fails we fall back on constructing our netbios name from
6110 if (global_myname()) {
6111 context->netbios_name = SMB_STRDUP(global_myname());
6115 * Hmmm, I want to get hostname as well, but I am too
6116 * lazy for the moment
6119 context->netbios_name = SMB_MALLOC(17);
6120 if (!context->netbios_name) {
6124 slprintf(context->netbios_name, 16,
6125 "smbc%s%d", context->user, pid);
6129 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
6131 if (!context->workgroup) {
6132 if (lp_workgroup()) {
6133 context->workgroup = SMB_STRDUP(lp_workgroup());
6136 /* TODO: Think about a decent default workgroup */
6137 context->workgroup = SMB_STRDUP("samba");
6141 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
6143 /* shortest timeout is 1 second */
6144 if (context->timeout > 0 && context->timeout < 1000)
6145 context->timeout = 1000;
6148 * FIXME: Should we check the function pointers here?
6151 context->internal->_initialized = True;
6157 /* Return the verion of samba, and thus libsmbclient */
6161 return samba_version_string();