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 *find_lsa_pipe_hnd(struct cli_state *ipc_cli)
87 struct rpc_pipe_client *pipe_hnd;
89 for (pipe_hnd = ipc_cli->pipe_list; pipe_hnd; pipe_hnd = pipe_hnd->next) {
90 if (pipe_hnd->pipe_idx == PI_LSARPC) {
98 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file);
99 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence);
101 extern BOOL in_client;
104 * Is the logging working / configfile read ?
106 static int smbc_initialized = 0;
109 hex2int( unsigned int _char )
111 if ( _char >= 'A' && _char <='F')
112 return _char - 'A' + 10;
113 if ( _char >= 'a' && _char <='f')
114 return _char - 'a' + 10;
115 if ( _char >= '0' && _char <='9')
123 * Convert strings of %xx to their single character equivalent. Each 'x' must
124 * be a valid hexadecimal digit, or that % sequence is left undecoded.
126 * dest may, but need not be, the same pointer as src.
128 * Returns the number of % sequences which could not be converted due to lack
129 * of two following hexadecimal digits.
132 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
134 int old_length = strlen(src);
140 if ( old_length == 0 ) {
145 while ( i < old_length ) {
146 unsigned char character = src[ i++ ];
148 if (character == '%') {
149 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
150 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
152 /* Replace valid sequence */
153 if (a != -1 && b != -1) {
155 /* Replace valid %xx sequence with %dd */
156 character = (a * 16) + b;
158 if (character == '\0') {
159 break; /* Stop at %00 */
174 strncpy(dest, temp, max_dest_len);
182 * Convert any characters not specifically allowed in a URL into their %xx
185 * Returns the remaining buffer length.
188 smbc_urlencode(char * dest, char * src, int max_dest_len)
190 char hex[] = "0123456789ABCDEF";
192 for (; *src != '\0' && max_dest_len >= 3; src++) {
204 *dest++ = hex[(*src >> 4) & 0x0f];
205 *dest++ = hex[*src & 0x0f];
220 * Function to parse a path and turn it into components
222 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
223 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
224 * general format ("smb:" only; we do not look for "cifs:").
228 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
232 * smb:// Show all workgroups.
234 * The method of locating the list of workgroups varies
235 * depending upon the setting of the context variable
236 * context->options.browse_max_lmb_count. This value
237 * determine the maximum number of local master browsers to
238 * query for the list of workgroups. In order to ensure that
239 * a complete list of workgroups is obtained, all master
240 * browsers must be queried, but if there are many
241 * workgroups, the time spent querying can begin to add up.
242 * For small networks (not many workgroups), it is suggested
243 * that this variable be set to 0, indicating query all local
244 * master browsers. When the network has many workgroups, a
245 * reasonable setting for this variable might be around 3.
247 * smb://name/ if name<1D> or name<1B> exists, list servers in
248 * workgroup, else, if name<20> exists, list all shares
251 * If "options" are provided, this function returns the entire option list as a
252 * string, for later parsing by the caller. Note that currently, no options
256 static const char *smbc_prefix = "smb:";
259 smbc_parse_path(SMBCCTX *context,
261 char *server, int server_len,
262 char *share, int share_len,
263 char *path, int path_len,
264 char *user, int user_len,
265 char *password, int password_len,
266 char *options, int options_len)
274 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
275 if (options != NULL && options_len > 0) {
276 options[0] = (char)0;
280 /* see if it has the right prefix */
281 len = strlen(smbc_prefix);
282 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
283 return -1; /* What about no smb: ? */
288 /* Watch the test below, we are testing to see if we should exit */
290 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
292 DEBUG(1, ("Invalid path (does not begin with smb://"));
297 p += 2; /* Skip the double slash */
299 /* See if any options were specified */
300 if ((q = strrchr(p, '?')) != NULL ) {
301 /* There are options. Null terminate here and point to them */
304 DEBUG(4, ("Found options '%s'", q));
306 /* Copy the options */
307 if (options != NULL && options_len > 0) {
308 safe_strcpy(options, q, options_len - 1);
317 strncpy(server, context->workgroup,
318 (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
324 * ok, its for us. Now parse out the server, share etc.
326 * However, we want to parse out [[domain;]user[:password]@] if it
330 /* check that '@' occurs before '/', if '/' exists at all */
331 q = strchr_m(p, '@');
332 r = strchr_m(p, '/');
333 if (q && (!r || q < r)) {
334 pstring username, passwd, domain;
335 const char *u = userinfo;
337 next_token(&p, userinfo, "@", sizeof(fstring));
339 username[0] = passwd[0] = domain[0] = 0;
341 if (strchr_m(u, ';')) {
343 next_token(&u, domain, ";", sizeof(fstring));
347 if (strchr_m(u, ':')) {
349 next_token(&u, username, ":", sizeof(fstring));
356 pstrcpy(username, u);
361 strncpy(user, username, user_len); /* FIXME, domain */
364 strncpy(password, passwd, password_len);
368 if (!next_token(&p, server, "/", sizeof(fstring))) {
374 if (*p == (char)0) goto decoding; /* That's it ... */
376 if (!next_token(&p, share, "/", sizeof(fstring))) {
382 safe_strcpy(path, p, path_len - 1);
384 all_string_sub(path, "/", "\\", 0);
387 (void) smbc_urldecode(path, path, path_len);
388 (void) smbc_urldecode(server, server, server_len);
389 (void) smbc_urldecode(share, share, share_len);
390 (void) smbc_urldecode(user, user, user_len);
391 (void) smbc_urldecode(password, password, password_len);
397 * Verify that the options specified in a URL are valid
399 static int smbc_check_options(char *server, char *share, char *path, char *options)
401 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' path='%s' options='%s'\n", server, share, path, options));
403 /* No options at all is always ok */
404 if (! *options) return 0;
406 /* Currently, we don't support any options. */
411 * Convert an SMB error into a UNIX error ...
413 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
415 int ret = cli_errno(c);
417 if (cli_is_dos_error(c)) {
421 cli_dos_error(c, &eclass, &ecode);
423 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
424 (int)eclass, (int)ecode, (int)ecode, ret));
428 status = cli_nt_error(c);
430 DEBUG(3,("smbc errno %s -> %d\n",
431 nt_errstr(status), ret));
438 * Check a server for being alive and well.
439 * returns 0 if the server is in shape. Returns 1 on error
441 * Also useable outside libsmbclient to enable external cache
442 * to do some checks too.
444 int smbc_check_server(SMBCCTX * context, SMBCSRV * server)
446 if ( send_keepalive(server->cli.fd) == False )
449 /* connection is ok */
454 * Remove a server from the cached server list it's unused.
455 * On success, 0 is returned. 1 is returned if the server could not be removed.
457 * Also useable outside libsmbclient
459 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
463 /* are we being fooled ? */
464 if (!context || !context->internal ||
465 !context->internal->_initialized || !srv) return 1;
468 /* Check all open files/directories for a relation with this server */
469 for (file = context->internal->_files; file; file=file->next) {
470 if (file->srv == srv) {
472 DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n",
478 DLIST_REMOVE(context->internal->_servers, srv);
480 cli_shutdown(&srv->cli);
482 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
484 context->callbacks.remove_cached_srv_fn(context, srv);
491 SMBCSRV *find_server(SMBCCTX *context,
503 srv = context->callbacks.get_cached_srv_fn(context, server, share,
504 workgroup, username);
506 if (!auth_called && !srv && (!username[0] || !password[0])) {
507 context->callbacks.auth_fn(server, share,
508 workgroup, sizeof(fstring),
509 username, sizeof(fstring),
510 password, sizeof(fstring));
512 * However, smbc_auth_fn may have picked up info relating to
513 * an existing connection, so try for an existing connection
517 goto check_server_cache;
522 if (context->callbacks.check_server_fn(context, srv)) {
524 * This server is no good anymore
525 * Try to remove it and check for more possible
526 * servers in the cache
528 if (context->callbacks.remove_unused_server_fn(context,
531 * We could not remove the server completely,
532 * remove it from the cache so we will not get
533 * it again. It will be removed when the last
534 * file/dir is closed.
536 context->callbacks.remove_cached_srv_fn(context,
541 * Maybe there are more cached connections to this
544 goto check_server_cache;
554 * Connect to a server, possibly on an existing connection
556 * Here, what we want to do is: If the server and username
557 * match an existing connection, reuse that, otherwise, establish a
560 * If we have to create a new connection, call the auth_fn to get the
561 * info we need, unless the username and password were passed in.
564 SMBCSRV *smbc_server(SMBCCTX *context,
565 const char *server, const char *share,
566 fstring workgroup, fstring username,
571 struct nmb_name called, calling;
572 const char *server_n = server;
575 int tried_reverse = 0;
578 const char *username_used;
583 if (server[0] == 0) {
588 /* Look for a cached connection */
589 srv = find_server(context, server, share,
590 workgroup, username, password);
593 * If we found a connection and we're only allowed one share per
596 if (srv && *share != '\0' && context->options.one_share_per_server) {
599 * ... then if there's no current connection to the share,
600 * connect to it. find_server(), or rather the function
601 * pointed to by context->callbacks.get_cached_srv_fn which
602 * was called by find_server(), will have issued a tree
603 * disconnect if the requested share is not the same as the
604 * one that was already connected.
606 if (srv->cli.cnum == (uint16) -1) {
607 /* Ensure we have accurate auth info */
608 context->callbacks.auth_fn(server, share,
609 workgroup, sizeof(fstring),
610 username, sizeof(fstring),
611 password, sizeof(fstring));
613 if (! cli_send_tconX(&srv->cli, share, "?????",
614 password, strlen(password)+1)) {
616 errno = smbc_errno(context, &srv->cli);
617 cli_shutdown(&srv->cli);
618 context->callbacks.remove_cached_srv_fn(context, srv);
622 /* Regenerate the dev value since it's based on both server and share */
624 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
629 /* If we have a connection... */
632 /* ... then we're done here. Give 'em what they came for. */
636 make_nmb_name(&calling, context->netbios_name, 0x0);
637 make_nmb_name(&called , server, 0x20);
639 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
641 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
644 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
648 /* have to open a new connection */
649 if (!cli_initialise(&c)) {
654 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
655 c.use_kerberos = True;
657 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
658 c.fallback_after_kerberos = True;
661 c.timeout = context->timeout;
664 * Force use of port 139 for first try if share is $IPC, empty, or
665 * null, so browse lists can work
667 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
668 port_try_first = 139;
671 port_try_first = 445;
675 c.port = port_try_first;
677 if (!cli_connect(&c, server_n, &ip)) {
679 /* First connection attempt failed. Try alternate port. */
680 c.port = port_try_next;
682 if (!cli_connect(&c, server_n, &ip)) {
689 if (!cli_session_request(&c, &calling, &called)) {
691 if (strcmp(called.name, "*SMBSERVER")) {
692 make_nmb_name(&called , "*SMBSERVER", 0x20);
695 else { /* Try one more time, but ensure we don't loop */
697 /* Only try this if server is an IP address ... */
699 if (is_ipaddress(server) && !tried_reverse) {
701 struct in_addr rem_ip;
703 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
704 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
709 tried_reverse++; /* Yuck */
711 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
712 make_nmb_name(&called, remote_name, 0x20);
723 DEBUG(4,(" session request ok\n"));
725 if (!cli_negprot(&c)) {
731 username_used = username;
733 if (!cli_session_setup(&c, username_used,
734 password, strlen(password),
735 password, strlen(password),
738 /* Failed. Try an anonymous login, if allowed by flags. */
741 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
742 !cli_session_setup(&c, username_used,
753 DEBUG(4,(" session setup ok\n"));
755 if (!cli_send_tconX(&c, share, "?????",
756 password, strlen(password)+1)) {
757 errno = smbc_errno(context, &c);
762 DEBUG(4,(" tconx ok\n"));
765 * Ok, we have got a nice connection
766 * Let's allocate a server structure.
769 srv = SMB_MALLOC_P(SMBCSRV);
777 srv->cli.allocated = False;
778 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
779 srv->no_pathinfo = False;
780 srv->no_pathinfo2 = False;
781 srv->no_nt_session = False;
783 /* now add it to the cache (internal or external) */
784 /* Let the cache function set errno if it wants to */
786 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
787 int saved_errno = errno;
788 DEBUG(3, (" Failed to add server to cache\n"));
796 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
797 server, share, srv));
799 DLIST_ADD(context->internal->_servers, srv);
804 if (!srv) return NULL;
811 * Connect to a server for getting/setting attributes, possibly on an existing
812 * connection. This works similarly to smbc_server().
814 SMBCSRV *smbc_attr_server(SMBCCTX *context,
815 const char *server, const char *share,
817 fstring username, fstring password,
821 struct cli_state *ipc_cli;
822 struct rpc_pipe_client *pipe_hnd;
824 SMBCSRV *ipc_srv=NULL;
827 * See if we've already created this special connection. Reference
828 * our "special" share name '*IPC$', which is an impossible real share
829 * name due to the leading asterisk.
831 ipc_srv = find_server(context, server, "*IPC$",
832 workgroup, username, password);
835 /* We didn't find a cached connection. Get the password */
836 if (*password == '\0') {
837 /* ... then retrieve it now. */
838 context->callbacks.auth_fn(server, share,
839 workgroup, sizeof(fstring),
840 username, sizeof(fstring),
841 password, sizeof(fstring));
845 nt_status = cli_full_connection(&ipc_cli,
846 global_myname(), server,
847 &ip, 0, "IPC$", "?????",
851 if (! NT_STATUS_IS_OK(nt_status)) {
852 DEBUG(1,("cli_full_connection failed! (%s)\n",
853 nt_errstr(nt_status)));
858 ipc_srv = SMB_MALLOC_P(SMBCSRV);
861 cli_shutdown(ipc_cli);
865 ZERO_STRUCTP(ipc_srv);
866 ipc_srv->cli = *ipc_cli;
867 ipc_srv->cli.allocated = False;
872 pipe_hnd = cli_rpc_pipe_open_noauth(&ipc_srv->cli,
876 DEBUG(1, ("cli_nt_session_open fail!\n"));
878 cli_shutdown(&ipc_srv->cli);
884 * Some systems don't support
885 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
886 * so we might as well do it too.
889 nt_status = rpccli_lsa_open_policy(
891 ipc_srv->cli.mem_ctx,
893 GENERIC_EXECUTE_ACCESS,
896 if (!NT_STATUS_IS_OK(nt_status)) {
897 errno = smbc_errno(context, &ipc_srv->cli);
898 cli_shutdown(&ipc_srv->cli);
903 /* now add it to the cache (internal or external) */
905 errno = 0; /* let cache function set errno if it likes */
906 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
911 DEBUG(3, (" Failed to add server to cache\n"));
915 cli_shutdown(&ipc_srv->cli);
920 DLIST_ADD(context->internal->_servers, ipc_srv);
927 * Routine to open() a file ...
930 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
932 fstring server, share, user, password, workgroup;
935 struct cli_state *targetcli;
937 SMBCFILE *file = NULL;
940 if (!context || !context->internal ||
941 !context->internal->_initialized) {
943 errno = EINVAL; /* Best I can think of ... */
955 if (smbc_parse_path(context, fname,
956 server, sizeof(server),
957 share, sizeof(share),
960 password, sizeof(password),
966 if (user[0] == (char)0) fstrcpy(user, context->user);
968 fstrcpy(workgroup, context->workgroup);
970 srv = smbc_server(context, server, share, workgroup, user, password);
974 if (errno == EPERM) errno = EACCES;
975 return NULL; /* smbc_server sets errno */
979 /* Hmmm, the test for a directory is suspect here ... FIXME */
981 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
988 file = SMB_MALLOC_P(SMBCFILE);
999 /*d_printf(">>>open: resolving %s\n", path);*/
1000 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1002 d_printf("Could not resolve %s\n", path);
1005 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1007 if ( targetcli->dfsroot )
1010 pstrcpy(temppath, targetpath);
1011 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1014 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1016 /* Handle the error ... */
1019 errno = smbc_errno(context, targetcli);
1024 /* Fill in file struct */
1027 file->fname = SMB_STRDUP(fname);
1032 DLIST_ADD(context->internal->_files, file);
1035 * If the file was opened in O_APPEND mode, all write
1036 * operations should be appended to the file. To do that,
1037 * though, using this protocol, would require a getattrE()
1038 * call for each and every write, to determine where the end
1039 * of the file is. (There does not appear to be an append flag
1040 * in the protocol.) Rather than add all of that overhead of
1041 * retrieving the current end-of-file offset prior to each
1042 * write operation, we'll assume that most append operations
1043 * will continuously write, so we'll just set the offset to
1044 * the end of the file now and hope that's adequate.
1046 * Note to self: If this proves inadequate, and O_APPEND
1047 * should, in some cases, be forced for each write, add a
1048 * field in the context options structure, for
1049 * "strict_append_mode" which would select between the current
1050 * behavior (if FALSE) or issuing a getattrE() prior to each
1051 * write and forcing the write to the end of the file (if
1052 * TRUE). Adding that capability will likely require adding
1053 * an "append" flag into the _SMBCFILE structure to track
1054 * whether a file was opened in O_APPEND mode. -- djl
1056 if (flags & O_APPEND) {
1057 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1058 (void) smbc_close_ctx(context, file);
1068 /* Check if opendir needed ... */
1073 eno = smbc_errno(context, &srv->cli);
1074 file = context->opendir(context, fname);
1075 if (!file) errno = eno;
1080 errno = EINVAL; /* FIXME, correct errno ? */
1086 * Routine to create a file
1089 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1091 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
1094 if (!context || !context->internal ||
1095 !context->internal->_initialized) {
1102 return smbc_open_ctx(context, path, creat_bits, mode);
1106 * Routine to read() a file ...
1109 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1112 fstring server, share, user, password;
1113 pstring path, targetpath;
1114 struct cli_state *targetcli;
1119 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1120 * appears to pass file->offset (which is type off_t) differently than
1121 * a local variable of type off_t. Using local variable "offset" in
1122 * the call to cli_read() instead of file->offset fixes a problem
1123 * retrieving data at an offset greater than 4GB.
1125 off_t offset = file->offset;
1127 if (!context || !context->internal ||
1128 !context->internal->_initialized) {
1135 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1137 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1144 /* Check that the buffer exists ... */
1153 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1154 if (smbc_parse_path(context, file->fname,
1155 server, sizeof(server),
1156 share, sizeof(share),
1159 password, sizeof(password),
1165 /*d_printf(">>>read: resolving %s\n", path);*/
1166 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1168 d_printf("Could not resolve %s\n", path);
1171 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1173 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1177 errno = smbc_errno(context, targetcli);
1182 file->offset += ret;
1184 DEBUG(4, (" --> %d\n", ret));
1186 return ret; /* Success, ret bytes of data ... */
1191 * Routine to write() a file ...
1194 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1197 off_t offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1198 fstring server, share, user, password;
1199 pstring path, targetpath;
1200 struct cli_state *targetcli;
1202 if (!context || !context->internal ||
1203 !context->internal->_initialized) {
1210 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1217 /* Check that the buffer exists ... */
1226 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1227 if (smbc_parse_path(context, file->fname,
1228 server, sizeof(server),
1229 share, sizeof(share),
1232 password, sizeof(password),
1238 /*d_printf(">>>write: resolving %s\n", path);*/
1239 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1241 d_printf("Could not resolve %s\n", path);
1244 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1247 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1251 errno = smbc_errno(context, targetcli);
1256 file->offset += ret;
1258 return ret; /* Success, 0 bytes of data ... */
1262 * Routine to close() a file ...
1265 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1268 fstring server, share, user, password;
1269 pstring path, targetpath;
1270 struct cli_state *targetcli;
1272 if (!context || !context->internal ||
1273 !context->internal->_initialized) {
1280 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1290 return context->closedir(context, file);
1294 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1295 if (smbc_parse_path(context, file->fname,
1296 server, sizeof(server),
1297 share, sizeof(share),
1300 password, sizeof(password),
1306 /*d_printf(">>>close: resolving %s\n", path);*/
1307 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1309 d_printf("Could not resolve %s\n", path);
1312 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1314 if (!cli_close(targetcli, file->cli_fd)) {
1316 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1318 /* Deallocate slot and remove the server
1319 * from the server cache if unused */
1320 errno = smbc_errno(context, targetcli);
1322 DLIST_REMOVE(context->internal->_files, file);
1323 SAFE_FREE(file->fname);
1325 context->callbacks.remove_unused_server_fn(context, srv);
1331 DLIST_REMOVE(context->internal->_files, file);
1332 SAFE_FREE(file->fname);
1339 * Get info from an SMB server on a file. Use a qpathinfo call first
1340 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1342 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1343 uint16 *mode, SMB_OFF_T *size,
1344 time_t *c_time, time_t *a_time, time_t *m_time,
1349 struct cli_state *targetcli;
1350 if (!context || !context->internal ||
1351 !context->internal->_initialized) {
1358 /* path fixup for . and .. */
1359 if (strequal(path, ".") || strequal(path, ".."))
1360 pstrcpy(fixedpath, "\\");
1363 pstrcpy(fixedpath, path);
1364 trim_string(fixedpath, NULL, "\\..");
1365 trim_string(fixedpath, NULL, "\\.");
1367 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1369 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1371 d_printf("Couldn't resolve %s\n", path);
1375 if ( targetcli->dfsroot )
1378 pstrcpy(temppath, targetpath);
1379 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1382 if (!srv->no_pathinfo2 &&
1383 cli_qpathinfo2(targetcli, targetpath,
1384 c_time, a_time, m_time, NULL, size, mode, ino)) {
1388 /* if this is NT then don't bother with the getatr */
1389 if (targetcli->capabilities & CAP_NT_SMBS) {
1394 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1395 if (m_time != NULL) {
1396 if (a_time != NULL) *a_time = *m_time;
1397 if (c_time != NULL) *c_time = *m_time;
1399 srv->no_pathinfo2 = True;
1409 * Set file info on an SMB server. Use setpathinfo call first. If that
1410 * fails, use setattrE..
1412 * Access and modification time parameters are always used and must be
1413 * provided. Create time, if zero, will be determined from the actual create
1414 * time of the file. If non-zero, the create time will be set as well.
1416 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1418 static BOOL smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1419 time_t c_time, time_t a_time, time_t m_time,
1426 * Get the create time of the file (if not provided); we'll need it in
1429 if (! srv->no_pathinfo && c_time == 0) {
1430 if (! cli_qpathinfo(&srv->cli, path,
1431 &c_time, NULL, NULL, NULL, NULL)) {
1432 /* qpathinfo not available */
1433 srv->no_pathinfo = True;
1436 * We got a creation time. Some OS versions don't
1437 * return a valid create time, though. If we got an
1438 * invalid time, start with the current time instead.
1440 if (c_time == 0 || c_time == (time_t) -1) {
1441 c_time = time(NULL);
1445 * We got a creation time. For sanity sake, since
1446 * there is no POSIX function to set the create time
1447 * of a file, if the existing create time is greater
1448 * than either of access time or modification time,
1449 * set create time to the smallest of those. This
1450 * ensure that the create time of a file is never
1451 * greater than its last access or modification time.
1453 if (c_time > a_time) c_time = a_time;
1454 if (c_time > m_time) c_time = m_time;
1459 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1460 * modern function for "new code" to be using, and it works given a
1461 * filename rather than requiring that the file be opened to have its
1462 * attributes manipulated.
1464 if (srv->no_pathinfo ||
1465 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1468 * setpathinfo is not supported; go to plan B.
1470 * cli_setatr() does not work on win98, and it also doesn't
1471 * support setting the access time (only the modification
1472 * time), so in all cases, we open the specified file and use
1473 * cli_setattrE() which should work on all OS versions, and
1474 * supports both times.
1477 /* Don't try {q,set}pathinfo() again, with this server */
1478 srv->no_pathinfo = True;
1481 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1483 errno = smbc_errno(context, &srv->cli);
1488 * Get the creat time of the file (if it wasn't provided).
1489 * We'll need it in the set call
1492 ret = cli_getattrE(&srv->cli, fd,
1494 &c_time, NULL, NULL);
1499 /* If we got create time, set times */
1501 /* Some OS versions don't support create time */
1502 if (c_time == 0 || c_time == -1) {
1503 c_time = time(NULL);
1507 * For sanity sake, since there is no POSIX function
1508 * to set the create time of a file, if the existing
1509 * create time is greater than either of access time
1510 * or modification time, set create time to the
1511 * smallest of those. This ensure that the create
1512 * time of a file is never greater than its last
1513 * access or modification time.
1515 if (c_time > a_time) c_time = a_time;
1516 if (c_time > m_time) c_time = m_time;
1518 /* Set the new attributes */
1519 ret = cli_setattrE(&srv->cli, fd,
1520 c_time, a_time, m_time);
1521 cli_close(&srv->cli, fd);
1525 * Unfortunately, setattrE() doesn't have a provision for
1526 * setting the access mode (attributes). We'll have to try
1527 * cli_setatr() for that, and with only this parameter, it
1528 * seems to work on win98.
1530 if (ret && mode != (uint16) -1) {
1531 ret = cli_setatr(&srv->cli, path, mode, 0);
1535 errno = smbc_errno(context, &srv->cli);
1544 * Routine to unlink() a file
1547 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1549 fstring server, share, user, password, workgroup;
1550 pstring path, targetpath;
1551 struct cli_state *targetcli;
1552 SMBCSRV *srv = NULL;
1554 if (!context || !context->internal ||
1555 !context->internal->_initialized) {
1557 errno = EINVAL; /* Best I can think of ... */
1569 if (smbc_parse_path(context, fname,
1570 server, sizeof(server),
1571 share, sizeof(share),
1574 password, sizeof(password),
1580 if (user[0] == (char)0) fstrcpy(user, context->user);
1582 fstrcpy(workgroup, context->workgroup);
1584 srv = smbc_server(context, server, share, workgroup, user, password);
1588 return -1; /* smbc_server sets errno */
1592 /*d_printf(">>>unlink: resolving %s\n", path);*/
1593 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1595 d_printf("Could not resolve %s\n", path);
1598 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1600 if (!cli_unlink(targetcli, targetpath)) {
1602 errno = smbc_errno(context, targetcli);
1604 if (errno == EACCES) { /* Check if the file is a directory */
1609 time_t m_time = 0, a_time = 0, c_time = 0;
1612 if (!smbc_getatr(context, srv, path, &mode, &size,
1613 &c_time, &a_time, &m_time, &ino)) {
1615 /* Hmmm, bad error ... What? */
1617 errno = smbc_errno(context, targetcli);
1623 if (IS_DOS_DIR(mode))
1626 errno = saverr; /* Restore this */
1635 return 0; /* Success ... */
1640 * Routine to rename() a file
1643 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1644 SMBCCTX *ncontext, const char *nname)
1646 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1647 pstring path1, path2, targetpath1, targetpath2;
1648 struct cli_state *targetcli1, *targetcli2;
1649 SMBCSRV *srv = NULL;
1651 if (!ocontext || !ncontext ||
1652 !ocontext->internal || !ncontext->internal ||
1653 !ocontext->internal->_initialized ||
1654 !ncontext->internal->_initialized) {
1656 errno = EINVAL; /* Best I can think of ... */
1661 if (!oname || !nname) {
1668 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1670 smbc_parse_path(ocontext, oname,
1671 server1, sizeof(server1),
1672 share1, sizeof(share1),
1673 path1, sizeof(path1),
1674 user1, sizeof(user1),
1675 password1, sizeof(password1),
1678 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1680 smbc_parse_path(ncontext, nname,
1681 server2, sizeof(server2),
1682 share2, sizeof(share2),
1683 path2, sizeof(path2),
1684 user2, sizeof(user2),
1685 password2, sizeof(password2),
1688 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1690 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1691 strcmp(user1, user2)) {
1693 /* Can't rename across file systems, or users?? */
1700 fstrcpy(workgroup, ocontext->workgroup);
1701 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1702 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1709 /*d_printf(">>>rename: resolving %s\n", path1);*/
1710 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1712 d_printf("Could not resolve %s\n", path1);
1715 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1716 /*d_printf(">>>rename: resolving %s\n", path2);*/
1717 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1719 d_printf("Could not resolve %s\n", path2);
1722 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1724 if (strcmp(targetcli1->desthost, targetcli2->desthost) || strcmp(targetcli1->share, targetcli2->share))
1726 /* can't rename across file systems */
1732 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1733 int eno = smbc_errno(ocontext, targetcli1);
1735 if (eno != EEXIST ||
1736 !cli_unlink(targetcli1, targetpath2) ||
1737 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1745 return 0; /* Success */
1750 * A routine to lseek() a file
1753 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1756 fstring server, share, user, password;
1757 pstring path, targetpath;
1758 struct cli_state *targetcli;
1760 if (!context || !context->internal ||
1761 !context->internal->_initialized) {
1768 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1778 return -1; /* Can't lseek a dir ... */
1784 file->offset = offset;
1788 file->offset += offset;
1792 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1793 if (smbc_parse_path(context, file->fname,
1794 server, sizeof(server),
1795 share, sizeof(share),
1798 password, sizeof(password),
1804 /*d_printf(">>>lseek: resolving %s\n", path);*/
1805 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1807 d_printf("Could not resolve %s\n", path);
1810 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1812 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL, &size, NULL, NULL,
1815 SMB_OFF_T b_size = size;
1816 if (!cli_getattrE(targetcli, file->cli_fd, NULL, &b_size, NULL, NULL,
1824 file->offset = size + offset;
1833 return file->offset;
1838 * Generate an inode number from file name for those things that need it
1842 ino_t smbc_inode(SMBCCTX *context, const char *name)
1845 if (!context || !context->internal ||
1846 !context->internal->_initialized) {
1853 if (!*name) return 2; /* FIXME, why 2 ??? */
1854 return (ino_t)str_checksum(name);
1859 * Routine to put basic stat info into a stat structure ... Used by stat and
1864 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname,
1865 SMB_OFF_T size, int mode)
1870 if (IS_DOS_DIR(mode)) {
1871 st->st_mode = SMBC_DIR_MODE;
1873 st->st_mode = SMBC_FILE_MODE;
1876 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1877 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1878 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1879 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1882 #ifdef HAVE_STAT_ST_BLKSIZE
1883 st->st_blksize = 512;
1885 #ifdef HAVE_STAT_ST_BLOCKS
1886 st->st_blocks = (size+511)/512;
1888 st->st_uid = getuid();
1889 st->st_gid = getgid();
1891 if (IS_DOS_DIR(mode)) {
1897 if (st->st_ino == 0) {
1898 st->st_ino = smbc_inode(context, fname);
1901 return True; /* FIXME: Is this needed ? */
1906 * Routine to stat a file given a name
1909 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1912 fstring server, share, user, password, workgroup;
1914 time_t m_time = 0, a_time = 0, c_time = 0;
1919 if (!context || !context->internal ||
1920 !context->internal->_initialized) {
1922 errno = EINVAL; /* Best I can think of ... */
1934 DEBUG(4, ("smbc_stat(%s)\n", fname));
1936 if (smbc_parse_path(context, fname,
1937 server, sizeof(server),
1938 share, sizeof(share),
1941 password, sizeof(password),
1947 if (user[0] == (char)0) fstrcpy(user, context->user);
1949 fstrcpy(workgroup, context->workgroup);
1951 srv = smbc_server(context, server, share, workgroup, user, password);
1954 return -1; /* errno set by smbc_server */
1957 if (!smbc_getatr(context, srv, path, &mode, &size,
1958 &c_time, &a_time, &m_time, &ino)) {
1960 errno = smbc_errno(context, &srv->cli);
1967 smbc_setup_stat(context, st, path, size, mode);
1969 st->st_atime = a_time;
1970 st->st_ctime = c_time;
1971 st->st_mtime = m_time;
1972 st->st_dev = srv->dev;
1979 * Routine to stat a file given an fd
1982 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1984 time_t c_time, a_time, m_time;
1987 fstring server, share, user, password;
1988 pstring path, targetpath;
1989 struct cli_state *targetcli;
1992 if (!context || !context->internal ||
1993 !context->internal->_initialized) {
2000 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2009 return context->fstatdir(context, file, st);
2013 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2014 if (smbc_parse_path(context, file->fname,
2015 server, sizeof(server),
2016 share, sizeof(share),
2019 password, sizeof(password),
2025 /*d_printf(">>>fstat: resolving %s\n", path);*/
2026 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
2028 d_printf("Could not resolve %s\n", path);
2031 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2033 if (!cli_qfileinfo(targetcli, file->cli_fd,
2034 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
2035 if (!cli_getattrE(targetcli, file->cli_fd,
2036 &mode, &size, &c_time, &a_time, &m_time)) {
2045 smbc_setup_stat(context, st, file->fname, size, mode);
2047 st->st_atime = a_time;
2048 st->st_ctime = c_time;
2049 st->st_mtime = m_time;
2050 st->st_dev = file->srv->dev;
2057 * Routine to open a directory
2058 * We accept the URL syntax explained in smbc_parse_path(), above.
2061 static void smbc_remove_dir(SMBCFILE *dir)
2063 struct smbc_dir_list *d,*f;
2070 SAFE_FREE(f->dirent);
2075 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2079 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
2081 struct smbc_dirent *dirent;
2083 int name_length = (name == NULL ? 0 : strlen(name));
2084 int comment_len = (comment == NULL ? 0 : strlen(comment));
2087 * Allocate space for the dirent, which must be increased by the
2088 * size of the name and the comment and 1 each for the null terminator.
2091 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2093 dirent = SMB_MALLOC(size);
2097 dir->dir_error = ENOMEM;
2102 ZERO_STRUCTP(dirent);
2104 if (dir->dir_list == NULL) {
2106 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2107 if (!dir->dir_list) {
2110 dir->dir_error = ENOMEM;
2114 ZERO_STRUCTP(dir->dir_list);
2116 dir->dir_end = dir->dir_next = dir->dir_list;
2120 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2122 if (!dir->dir_end->next) {
2125 dir->dir_error = ENOMEM;
2129 ZERO_STRUCTP(dir->dir_end->next);
2131 dir->dir_end = dir->dir_end->next;
2134 dir->dir_end->next = NULL;
2135 dir->dir_end->dirent = dirent;
2137 dirent->smbc_type = type;
2138 dirent->namelen = name_length;
2139 dirent->commentlen = comment_len;
2140 dirent->dirlen = size;
2142 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2144 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2145 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2152 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
2154 SMBCFILE *dir = (SMBCFILE *)state;
2155 struct smbc_dir_list *dir_list;
2156 struct smbc_dirent *dirent;
2160 dirent_type = dir->dir_type;
2162 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2164 /* An error occurred, what do we do? */
2165 /* FIXME: Add some code here */
2168 /* Point to the one just added */
2169 dirent = dir->dir_end->dirent;
2171 /* See if this was a duplicate */
2172 for (dir_list = dir->dir_list;
2173 dir_list != dir->dir_end;
2174 dir_list = dir_list->next) {
2176 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2177 /* Duplicate. End end of list need to be removed. */
2181 if (do_remove && dir_list->next == dir->dir_end) {
2182 /* Found the end of the list. Remove it. */
2183 dir->dir_end = dir_list;
2184 free(dir_list->next);
2186 dir_list->next = NULL;
2193 list_fn(const char *name, uint32 type, const char *comment, void *state)
2195 SMBCFILE *dir = (SMBCFILE *)state;
2199 * We need to process the type a little ...
2201 * Disk share = 0x00000000
2202 * Print share = 0x00000001
2203 * Comms share = 0x00000002 (obsolete?)
2204 * IPC$ share = 0x00000003
2206 * administrative shares:
2207 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2210 if (dir->dir_type == SMBC_FILE_SHARE) {
2213 case 0 | 0x80000000:
2215 dirent_type = SMBC_FILE_SHARE;
2219 dirent_type = SMBC_PRINTER_SHARE;
2223 dirent_type = SMBC_COMMS_SHARE;
2226 case 3 | 0x80000000:
2228 dirent_type = SMBC_IPC_SHARE;
2232 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2237 dirent_type = dir->dir_type;
2240 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2242 /* An error occurred, what do we do? */
2243 /* FIXME: Add some code here */
2249 dir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2252 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2253 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2255 /* Handle an error ... */
2257 /* FIXME: Add some code ... */
2264 net_share_enum_rpc(struct cli_state *cli,
2265 void (*fn)(const char *name,
2267 const char *comment,
2274 uint32 info_level = 1;
2275 uint32 preferred_len = 0xffffffff;
2277 SRV_SHARE_INFO_CTR ctr;
2279 fstring comment = "";
2281 struct rpc_pipe_client *pipe_hnd;
2284 /* Open the server service pipe */
2285 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2287 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2291 /* Allocate a context for parsing and for the entries in "ctr" */
2292 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2293 if (mem_ctx == NULL) {
2294 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2295 cli_rpc_pipe_close(pipe_hnd);
2299 /* Issue the NetShareEnum RPC call and retrieve the response */
2300 init_enum_hnd(&enum_hnd, 0);
2301 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2308 /* Was it successful? */
2309 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2310 /* Nope. Go clean up. */
2314 /* For each returned entry... */
2315 for (i = 0; i < ctr.num_entries; i++) {
2317 /* pull out the share name */
2318 rpcstr_pull_unistr2_fstring(
2319 name, &ctr.share.info1[i].info_1_str.uni_netname);
2321 /* pull out the share's comment */
2322 rpcstr_pull_unistr2_fstring(
2323 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2325 /* Get the type value */
2326 type = ctr.share.info1[i].info_1.type;
2328 /* Add this share to the list */
2329 (*fn)(name, type, comment, state);
2333 /* Close the server service pipe */
2334 cli_rpc_pipe_close(pipe_hnd);
2336 /* Free all memory which was allocated for this request */
2337 talloc_free(mem_ctx);
2339 /* Tell 'em if it worked */
2340 return W_ERROR_IS_OK(result) ? 0 : -1;
2345 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
2347 fstring server, share, user, password, options;
2352 SMBCSRV *srv = NULL;
2353 SMBCFILE *dir = NULL;
2354 struct in_addr rem_ip;
2356 if (!context || !context->internal ||
2357 !context->internal->_initialized) {
2358 DEBUG(4, ("no valid context\n"));
2359 errno = EINVAL + 8192;
2365 DEBUG(4, ("no valid fname\n"));
2366 errno = EINVAL + 8193;
2370 if (smbc_parse_path(context, fname,
2371 server, sizeof(server),
2372 share, sizeof(share),
2375 password, sizeof(password),
2376 options, sizeof(options))) {
2377 DEBUG(4, ("no valid path\n"));
2378 errno = EINVAL + 8194;
2382 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
2384 /* Ensure the options are valid */
2385 if (smbc_check_options(server, share, path, options)) {
2386 DEBUG(4, ("unacceptable options (%s)\n", options));
2387 errno = EINVAL + 8195;
2391 if (user[0] == (char)0) fstrcpy(user, context->user);
2393 pstrcpy(workgroup, context->workgroup);
2395 dir = SMB_MALLOC_P(SMBCFILE);
2407 dir->fname = SMB_STRDUP(fname);
2411 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2413 if (server[0] == (char)0) {
2418 struct ip_service *ip_list;
2419 struct ip_service server_addr;
2420 struct user_auth_info u_info;
2421 struct cli_state *cli;
2423 if (share[0] != (char)0 || path[0] != (char)0) {
2425 errno = EINVAL + 8196;
2427 SAFE_FREE(dir->fname);
2433 /* Determine how many local master browsers to query */
2434 max_lmb_count = (context->options.browse_max_lmb_count == 0
2436 : context->options.browse_max_lmb_count);
2438 pstrcpy(u_info.username, user);
2439 pstrcpy(u_info.password, password);
2442 * We have server and share and path empty but options
2443 * requesting that we scan all master browsers for their list
2444 * of workgroups/domains. This implies that we must first try
2445 * broadcast queries to find all master browsers, and if that
2446 * doesn't work, then try our other methods which return only
2447 * a single master browser.
2451 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2455 if (!find_master_ip(workgroup, &server_addr.ip)) {
2461 ip_list = &server_addr;
2465 for (i = 0; i < count && i < max_lmb_count; i++) {
2466 DEBUG(99, ("Found master browser %d of %d: %s\n", i+1, MAX(count, max_lmb_count), inet_ntoa(ip_list[i].ip)));
2468 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2469 /* cli == NULL is the master browser refused to talk or
2470 could not be found */
2474 fstrcpy(server, cli->desthost);
2477 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2480 * For each returned master browser IP address, get a
2481 * connection to IPC$ on the server if we do not
2482 * already have one, and determine the
2483 * workgroups/domains that it knows about.
2486 srv = smbc_server(context, server,
2487 "IPC$", workgroup, user, password);
2493 dir->dir_type = SMBC_WORKGROUP;
2495 /* Now, list the stuff ... */
2497 if (!cli_NetServerEnum(&srv->cli,
2499 SV_TYPE_DOMAIN_ENUM,
2509 * Server not an empty string ... Check the rest and see what
2512 if (share[0] == (char)0) {
2514 if (path[0] != (char)0) { /* Should not have empty share with path */
2516 errno = EINVAL + 8197;
2518 SAFE_FREE(dir->fname);
2525 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2526 /* However, we check to see if <server> is an IP address first */
2528 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2529 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2530 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2533 dir->dir_type = SMBC_SERVER;
2536 * Get the backup list ...
2540 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2542 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2543 errno = EPERM; /* FIXME, is this correct */
2549 * Get a connection to IPC$ on the server if we do not already have one
2552 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2555 DEBUG(0, ("got no contact to IPC$\n"));
2557 SAFE_FREE(dir->fname);
2566 /* Now, list the servers ... */
2568 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2572 SAFE_FREE(dir->fname);
2581 if (resolve_name(server, &rem_ip, 0x20)) {
2583 /* Now, list the shares ... */
2585 dir->dir_type = SMBC_FILE_SHARE;
2587 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2592 SAFE_FREE(dir->fname);
2601 /* Now, list the servers ... */
2603 if (net_share_enum_rpc(
2606 (void *) dir) < 0 &&
2612 errno = cli_errno(&srv->cli);
2614 SAFE_FREE(dir->fname);
2624 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2626 SAFE_FREE(dir->fname);
2636 else { /* The server and share are specified ... work from there ... */
2638 struct cli_state *targetcli;
2640 /* Well, we connect to the server and list the directory */
2642 dir->dir_type = SMBC_FILE_SHARE;
2644 srv = smbc_server(context, server, share, workgroup, user, password);
2649 SAFE_FREE(dir->fname);
2658 /* Now, list the files ... */
2660 p = path + strlen(path);
2661 pstrcat(path, "\\*");
2663 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2665 d_printf("Could not resolve %s\n", path);
2669 if (cli_list(targetcli, targetpath, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2673 SAFE_FREE(dir->fname);
2676 errno = smbc_errno(context, targetcli);
2678 if (errno == EINVAL) {
2680 * See if they asked to opendir something
2681 * other than a directory. If so, the
2682 * converted error value we got would have
2683 * been EINVAL rather than ENOTDIR.
2685 *p = '\0'; /* restore original path */
2687 if (smbc_getatr(context, srv, path,
2691 ! IS_DOS_DIR(mode)) {
2693 /* It is. Correct the error value */
2705 DLIST_ADD(context->internal->_files, dir);
2711 * Routine to close a directory
2714 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2717 if (!context || !context->internal ||
2718 !context->internal->_initialized) {
2725 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2732 smbc_remove_dir(dir); /* Clean it up */
2734 DLIST_REMOVE(context->internal->_files, dir);
2738 SAFE_FREE(dir->fname);
2739 SAFE_FREE(dir); /* Free the space too */
2746 static void smbc_readdir_internal(SMBCCTX * context,
2747 struct smbc_dirent *dest,
2748 struct smbc_dirent *src,
2749 int max_namebuf_len)
2751 if (context->options.urlencode_readdir_entries) {
2753 /* url-encode the name. get back remaining buffer space */
2755 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2757 /* We now know the name length */
2758 dest->namelen = strlen(dest->name);
2760 /* Save the pointer to the beginning of the comment */
2761 dest->comment = dest->name + dest->namelen + 1;
2763 /* Copy the comment */
2764 strncpy(dest->comment, src->comment, max_namebuf_len);
2766 /* Ensure the comment is null terminated */
2767 if (max_namebuf_len > src->commentlen) {
2768 dest->comment[src->commentlen] = '\0';
2770 dest->comment[max_namebuf_len - 1] = '\0';
2773 /* Save other fields */
2774 dest->smbc_type = src->smbc_type;
2775 dest->commentlen = strlen(dest->comment);
2776 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2780 /* No encoding. Just copy the entry as is. */
2781 memcpy(dest, src, src->dirlen);
2782 dest->comment = (char *)(&dest->name + src->namelen + 1);
2788 * Routine to get a directory entry
2791 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2794 struct smbc_dirent *dirp, *dirent;
2796 /* Check that all is ok first ... */
2798 if (!context || !context->internal ||
2799 !context->internal->_initialized) {
2802 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2807 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2810 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2815 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2818 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2823 if (!dir->dir_next) {
2827 dirent = dir->dir_next->dirent;
2835 dirp = (struct smbc_dirent *)context->internal->_dirent;
2836 maxlen = (sizeof(context->internal->_dirent) -
2837 sizeof(struct smbc_dirent));
2839 smbc_readdir_internal(context, dirp, dirent, maxlen);
2841 dir->dir_next = dir->dir_next->next;
2847 * Routine to get directory entries
2850 static int smbc_getdents_ctx(SMBCCTX *context,
2852 struct smbc_dirent *dirp,
2858 char *ndir = (char *)dirp;
2859 struct smbc_dir_list *dirlist;
2861 /* Check that all is ok first ... */
2863 if (!context || !context->internal ||
2864 !context->internal->_initialized) {
2871 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2878 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2886 * Now, retrieve the number of entries that will fit in what was passed
2887 * We have to figure out if the info is in the list, or we need to
2888 * send a request to the server to get the info.
2891 while ((dirlist = dir->dir_next)) {
2892 struct smbc_dirent *dirent;
2894 if (!dirlist->dirent) {
2896 errno = ENOENT; /* Bad error */
2901 /* Do urlencoding of next entry, if so selected */
2902 dirent = (struct smbc_dirent *)context->internal->_dirent;
2903 maxlen = (sizeof(context->internal->_dirent) -
2904 sizeof(struct smbc_dirent));
2905 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
2907 reqd = dirent->dirlen;
2911 if (rem < count) { /* We managed to copy something */
2917 else { /* Nothing copied ... */
2919 errno = EINVAL; /* Not enough space ... */
2926 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2928 ((struct smbc_dirent *)ndir)->comment =
2929 (char *)(&((struct smbc_dirent *)ndir)->name +
2937 dir->dir_next = dirlist = dirlist -> next;
2948 * Routine to create a directory ...
2951 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2954 fstring server, share, user, password, workgroup;
2955 pstring path, targetpath;
2956 struct cli_state *targetcli;
2958 if (!context || !context->internal ||
2959 !context->internal->_initialized) {
2973 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2975 if (smbc_parse_path(context, fname,
2976 server, sizeof(server),
2977 share, sizeof(share),
2980 password, sizeof(password),
2986 if (user[0] == (char)0) fstrcpy(user, context->user);
2988 fstrcpy(workgroup, context->workgroup);
2990 srv = smbc_server(context, server, share, workgroup, user, password);
2994 return -1; /* errno set by smbc_server */
2998 /*d_printf(">>>mkdir: resolving %s\n", path);*/
2999 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3001 d_printf("Could not resolve %s\n", path);
3004 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3006 if (!cli_mkdir(targetcli, targetpath)) {
3008 errno = smbc_errno(context, targetcli);
3018 * Our list function simply checks to see if a directory is not empty
3021 static int smbc_rmdir_dirempty = True;
3023 static void rmdir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
3026 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
3027 smbc_rmdir_dirempty = False;
3032 * Routine to remove a directory
3035 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
3038 fstring server, share, user, password, workgroup;
3039 pstring path, targetpath;
3040 struct cli_state *targetcli;
3042 if (!context || !context->internal ||
3043 !context->internal->_initialized) {
3057 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3059 if (smbc_parse_path(context, fname,
3060 server, sizeof(server),
3061 share, sizeof(share),
3064 password, sizeof(password),
3071 if (user[0] == (char)0) fstrcpy(user, context->user);
3073 fstrcpy(workgroup, context->workgroup);
3075 srv = smbc_server(context, server, share, workgroup, user, password);
3079 return -1; /* errno set by smbc_server */
3083 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
3085 mode = aDIR | aRONLY;
3088 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
3090 if (strcmp(path, "\\") == 0) {
3092 mode = aDIR | aRONLY;
3098 smbc_stat_printjob(srv, path, &size, &m_time);
3099 c_time = a_time = m_time;
3104 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3105 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3107 d_printf("Could not resolve %s\n", path);
3110 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3113 if (!cli_rmdir(targetcli, targetpath)) {
3115 errno = smbc_errno(context, targetcli);
3117 if (errno == EACCES) { /* Check if the dir empty or not */
3119 pstring lpath; /* Local storage to avoid buffer overflows */
3121 smbc_rmdir_dirempty = True; /* Make this so ... */
3123 pstrcpy(lpath, targetpath);
3124 pstrcat(lpath, "\\*");
3126 if (cli_list(targetcli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
3129 /* Fix errno to ignore latest error ... */
3131 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
3132 smbc_errno(context, targetcli)));
3137 if (smbc_rmdir_dirempty)
3153 * Routine to return the current directory position
3156 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
3158 off_t ret_val; /* Squash warnings about cast */
3160 if (!context || !context->internal ||
3161 !context->internal->_initialized) {
3168 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3175 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3183 * We return the pointer here as the offset
3185 ret_val = (off_t)(long)dir->dir_next;
3191 * A routine to run down the list and see if the entry is OK
3194 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
3195 struct smbc_dirent *dirent)
3198 /* Run down the list looking for what we want */
3202 struct smbc_dir_list *tmp = list;
3206 if (tmp->dirent == dirent)
3215 return NULL; /* Not found, or an error */
3221 * Routine to seek on a directory
3224 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
3226 long int l_offset = offset; /* Handle problems of size */
3227 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3228 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3230 if (!context || !context->internal ||
3231 !context->internal->_initialized) {
3238 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3245 /* Now, check what we were passed and see if it is OK ... */
3247 if (dirent == NULL) { /* Seek to the begining of the list */
3249 dir->dir_next = dir->dir_list;
3254 /* Now, run down the list and make sure that the entry is OK */
3255 /* This may need to be changed if we change the format of the list */
3257 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3259 errno = EINVAL; /* Bad entry */
3264 dir->dir_next = list_ent;
3271 * Routine to fstat a dir
3274 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
3277 if (!context || !context->internal ||
3278 !context->internal->_initialized) {
3285 /* No code yet ... */
3291 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
3294 fstring server, share, user, password, workgroup;
3298 if (!context || !context->internal ||
3299 !context->internal->_initialized) {
3301 errno = EINVAL; /* Best I can think of ... */
3313 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3315 if (smbc_parse_path(context, fname,
3316 server, sizeof(server),
3317 share, sizeof(share),
3320 password, sizeof(password),
3326 if (user[0] == (char)0) fstrcpy(user, context->user);
3328 fstrcpy(workgroup, context->workgroup);
3330 srv = smbc_server(context, server, share, workgroup, user, password);
3333 return -1; /* errno set by smbc_server */
3338 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3339 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3340 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3341 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3343 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3344 errno = smbc_errno(context, &srv->cli);
3351 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
3354 fstring server, share, user, password, workgroup;
3359 if (!context || !context->internal ||
3360 !context->internal->_initialized) {
3362 errno = EINVAL; /* Best I can think of ... */
3375 a_time = m_time = time(NULL);
3377 a_time = tbuf[0].tv_sec;
3378 m_time = tbuf[1].tv_sec;
3387 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf));
3388 atimebuf[sizeof(atimebuf) - 1] = '\0';
3389 if ((p = strchr(atimebuf, '\n')) != NULL) {
3393 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf));
3394 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3395 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3399 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3400 fname, atimebuf, mtimebuf);
3403 if (smbc_parse_path(context, fname,
3404 server, sizeof(server),
3405 share, sizeof(share),
3408 password, sizeof(password),
3414 if (user[0] == (char)0) fstrcpy(user, context->user);
3416 fstrcpy(workgroup, context->workgroup);
3418 srv = smbc_server(context, server, share, workgroup, user, password);
3421 return -1; /* errno set by smbc_server */
3424 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3425 return -1; /* errno set by smbc_setatr */
3432 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3433 However NT4 gives a "The information may have been modified by a
3434 computer running Windows NT 5.0" if denied ACEs do not appear before
3437 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
3439 if (sec_ace_equal(ace1, ace2))
3442 if (ace1->type != ace2->type)
3443 return ace2->type - ace1->type;
3445 if (sid_compare(&ace1->trustee, &ace2->trustee))
3446 return sid_compare(&ace1->trustee, &ace2->trustee);
3448 if (ace1->flags != ace2->flags)
3449 return ace1->flags - ace2->flags;
3451 if (ace1->info.mask != ace2->info.mask)
3452 return ace1->info.mask - ace2->info.mask;
3454 if (ace1->size != ace2->size)
3455 return ace1->size - ace2->size;
3457 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3461 static void sort_acl(SEC_ACL *the_acl)
3464 if (!the_acl) return;
3466 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
3468 for (i=1;i<the_acl->num_aces;) {
3469 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3471 for (j=i; j<the_acl->num_aces-1; j++) {
3472 the_acl->ace[j] = the_acl->ace[j+1];
3474 the_acl->num_aces--;
3481 /* convert a SID to a string, either numeric or username/group */
3482 static void convert_sid_to_string(struct cli_state *ipc_cli,
3488 char **domains = NULL;
3489 char **names = NULL;
3490 uint32 *types = NULL;
3491 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3492 sid_to_string(str, sid);
3495 return; /* no lookup desired */
3502 /* Ask LSA to convert the sid to a name */
3504 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3505 pol, 1, sid, &domains,
3507 !domains || !domains[0] || !names || !names[0]) {
3513 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3514 domains[0], lp_winbind_separator(),
3518 /* convert a string to a SID, either numeric or username/group */
3519 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
3525 uint32 *types = NULL;
3526 DOM_SID *sids = NULL;
3528 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3535 if (strncmp(str, "S-", 2) == 0) {
3536 return string_to_sid(sid, str);
3543 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3544 pol, 1, &str, &sids,
3550 sid_copy(sid, &sids[0]);
3557 /* parse an ACE in the same format as print_ace() */
3558 static BOOL parse_ace(struct cli_state *ipc_cli,
3567 unsigned atype, aflags, amask;
3570 const struct perm_value *v;
3576 /* These values discovered by inspection */
3577 static const struct perm_value special_values[] = {
3578 { "R", 0x00120089 },
3579 { "W", 0x00120116 },
3580 { "X", 0x001200a0 },
3581 { "D", 0x00010000 },
3582 { "P", 0x00040000 },
3583 { "O", 0x00080000 },
3587 static const struct perm_value standard_values[] = {
3588 { "READ", 0x001200a9 },
3589 { "CHANGE", 0x001301bf },
3590 { "FULL", 0x001f01ff },
3596 p = strchr_m(str,':');
3597 if (!p) return False;
3600 /* Try to parse numeric form */
3602 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3603 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3607 /* Try to parse text form */
3609 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3614 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3618 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3619 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3620 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3621 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3626 /* Only numeric form accepted for flags at present */
3628 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3629 sscanf(tok, "%i", &aflags))) {
3633 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3637 if (strncmp(tok, "0x", 2) == 0) {
3638 if (sscanf(tok, "%i", &amask) != 1) {
3644 for (v = standard_values; v->perm; v++) {
3645 if (strcmp(tok, v->perm) == 0) {
3656 for (v = special_values; v->perm; v++) {
3657 if (v->perm[0] == *p) {
3663 if (!found) return False;
3673 init_sec_ace(ace, &sid, atype, mask, aflags);
3677 /* add an ACE to a list of ACEs in a SEC_ACL */
3678 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3683 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3687 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3688 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3689 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3690 newacl = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3692 (*the_acl) = newacl;
3697 /* parse a ascii version of a security descriptor */
3698 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3699 struct cli_state *ipc_cli,
3704 const char *p = str;
3708 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3712 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3714 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3715 revision = strtol(tok+9, NULL, 16);
3719 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3720 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3722 !convert_string_to_sid(ipc_cli, pol,
3724 owner_sid, tok+6)) {
3725 DEBUG(5, ("Failed to parse owner sid\n"));
3731 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3732 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3734 !convert_string_to_sid(ipc_cli, pol,
3736 owner_sid, tok+7)) {
3737 DEBUG(5, ("Failed to parse owner sid\n"));
3743 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3744 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3746 !convert_string_to_sid(ipc_cli, pol,
3749 DEBUG(5, ("Failed to parse group sid\n"));
3755 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3756 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3758 !convert_string_to_sid(ipc_cli, pol,
3761 DEBUG(5, ("Failed to parse group sid\n"));
3767 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3769 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3770 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3773 if(!add_ace(&dacl, &ace, ctx)) {
3774 DEBUG(5, ("Failed to add ACL %s\n", tok));
3780 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3782 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3783 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3786 if(!add_ace(&dacl, &ace, ctx)) {
3787 DEBUG(5, ("Failed to add ACL %s\n", tok));
3793 DEBUG(5, ("Failed to parse security descriptor\n"));
3797 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3798 owner_sid, grp_sid, NULL, dacl, &sd_size);
3801 SAFE_FREE(owner_sid);
3807 /* Obtain the current dos attributes */
3808 static DOS_ATTR_DESC *dos_attr_query(SMBCCTX *context,
3810 const char *filename,
3813 time_t m_time = 0, a_time = 0, c_time = 0;
3816 SMB_INO_T inode = 0;
3819 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
3825 /* Obtain the DOS attributes */
3826 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
3828 &c_time, &a_time, &m_time, &inode)) {
3830 errno = smbc_errno(context, &srv->cli);
3831 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
3838 ret->a_time = a_time;
3839 ret->c_time = c_time;
3840 ret->m_time = m_time;
3847 /* parse a ascii version of a security descriptor */
3848 static void dos_attr_parse(SMBCCTX *context,
3853 const char *p = str;
3856 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3858 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
3859 dad->mode = strtol(tok+5, NULL, 16);
3863 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
3864 dad->size = (SMB_OFF_T)atof(tok+5);
3868 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
3869 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
3873 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
3874 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
3878 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
3879 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
3883 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
3884 dad->inode = (SMB_INO_T)atof(tok+6);
3890 /*****************************************************
3891 Retrieve the acls for a file.
3892 *******************************************************/
3894 static int cacl_get(SMBCCTX *context, TALLOC_CTX *ctx, SMBCSRV *srv,
3895 struct cli_state *ipc_cli, POLICY_HND *pol,
3896 char *filename, char *attr_name, char *buf, int bufsize)
3907 BOOL exclude_nt_revision = False;
3908 BOOL exclude_nt_owner = False;
3909 BOOL exclude_nt_group = False;
3910 BOOL exclude_nt_acl = False;
3911 BOOL exclude_dos_mode = False;
3912 BOOL exclude_dos_size = False;
3913 BOOL exclude_dos_ctime = False;
3914 BOOL exclude_dos_atime = False;
3915 BOOL exclude_dos_mtime = False;
3916 BOOL exclude_dos_inode = False;
3917 BOOL numeric = True;
3918 BOOL determine_size = (bufsize == 0);
3922 fstring name_sandbox;
3926 time_t m_time = 0, a_time = 0, c_time = 0;
3930 struct cli_state *cli = &srv->cli;
3932 /* Copy name so we can strip off exclusions (if any are specified) */
3933 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
3935 /* Ensure name is null terminated */
3936 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
3938 /* Play in the sandbox */
3939 name = name_sandbox;
3941 /* If there are any exclusions, point to them and mask them from name */
3942 if ((pExclude = strchr(name, '!')) != NULL)
3947 all = (StrnCaseCmp(name, "system.*", 8) == 0);
3948 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
3949 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
3950 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
3951 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
3952 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
3953 numeric = (* (name + strlen(name) - 1) != '+');
3955 /* Look for exclusions from "all" requests */
3956 if (all || all_nt || all_dos) {
3958 /* Exclusions are delimited by '!' */
3959 for (; pExclude != NULL; pExclude = (p == NULL ? NULL : p + 1)) {
3961 /* Find end of this exclusion name */
3962 if ((p = strchr(pExclude, '!')) != NULL)
3967 /* Which exclusion name is this? */
3968 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
3969 exclude_nt_revision = True;
3971 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
3972 exclude_nt_owner = True;
3974 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
3975 exclude_nt_group = True;
3977 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
3978 exclude_nt_acl = True;
3980 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
3981 exclude_dos_mode = True;
3983 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
3984 exclude_dos_size = True;
3986 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
3987 exclude_dos_ctime = True;
3989 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
3990 exclude_dos_atime = True;
3992 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
3993 exclude_dos_mtime = True;
3995 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
3996 exclude_dos_inode = True;
3999 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4010 * If we are (possibly) talking to an NT or new system and some NT
4011 * attributes have been requested...
4013 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4014 /* Point to the portion after "system.nt_sec_desc." */
4015 name += 19; /* if (all) this will be invalid but unused */
4017 /* ... then obtain any NT attributes which were requested */
4018 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4021 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4022 filename, cli_errstr(cli)));
4027 sd = cli_query_secdesc(cli, fnum, ctx);
4031 ("cacl_get Failed to query old descriptor\n"));
4036 cli_close(cli, fnum);
4038 if (! exclude_nt_revision) {
4039 if (all || all_nt) {
4040 if (determine_size) {
4041 p = talloc_asprintf(ctx,
4050 n = snprintf(buf, bufsize,
4051 "REVISION:%d", sd->revision);
4053 } else if (StrCaseCmp(name, "revision") == 0) {
4054 if (determine_size) {
4055 p = talloc_asprintf(ctx, "%d",
4063 n = snprintf(buf, bufsize, "%d",
4068 if (!determine_size && n > bufsize) {
4077 if (! exclude_nt_owner) {
4078 /* Get owner and group sid */
4079 if (sd->owner_sid) {
4080 convert_sid_to_string(ipc_cli, pol,
4085 fstrcpy(sidstr, "");
4088 if (all || all_nt) {
4089 if (determine_size) {
4090 p = talloc_asprintf(ctx, ",OWNER:%s",
4098 n = snprintf(buf, bufsize,
4099 ",OWNER:%s", sidstr);
4101 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4102 if (determine_size) {
4103 p = talloc_asprintf(ctx, "%s", sidstr);
4110 n = snprintf(buf, bufsize, "%s",
4115 if (!determine_size && n > bufsize) {
4124 if (! exclude_nt_group) {
4126 convert_sid_to_string(ipc_cli, pol,
4130 fstrcpy(sidstr, "");
4133 if (all || all_nt) {
4134 if (determine_size) {
4135 p = talloc_asprintf(ctx, ",GROUP:%s",
4143 n = snprintf(buf, bufsize,
4144 ",GROUP:%s", sidstr);
4146 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4147 if (determine_size) {
4148 p = talloc_asprintf(ctx, "%s", sidstr);
4155 n = snprintf(buf, bufsize, "%s", sidstr);
4159 if (!determine_size && n > bufsize) {
4168 if (! exclude_nt_acl) {
4169 /* Add aces to value buffer */
4170 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4172 SEC_ACE *ace = &sd->dacl->ace[i];
4173 convert_sid_to_string(ipc_cli, pol,
4177 if (all || all_nt) {
4178 if (determine_size) {
4179 p = talloc_asprintf(
4195 ",ACL:%s:%d/%d/0x%08x",
4201 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4202 StrCaseCmp(name + 3, sidstr) == 0) ||
4203 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4204 StrCaseCmp(name + 4, sidstr) == 0)) {
4205 if (determine_size) {
4206 p = talloc_asprintf(
4218 n = snprintf(buf, bufsize,
4224 } else if (all_nt_acls) {
4225 if (determine_size) {
4226 p = talloc_asprintf(
4228 "%s%s:%d/%d/0x%08x",
4240 n = snprintf(buf, bufsize,
4241 "%s%s:%d/%d/0x%08x",
4259 /* Restore name pointer to its original value */
4263 if (all || some_dos) {
4264 /* Point to the portion after "system.dos_attr." */
4265 name += 16; /* if (all) this will be invalid but unused */
4267 /* Obtain the DOS attributes */
4268 if (!smbc_getatr(context, srv, filename, &mode, &size,
4269 &c_time, &a_time, &m_time, &ino)) {
4271 errno = smbc_errno(context, &srv->cli);
4276 if (! exclude_dos_mode) {
4277 if (all || all_dos) {
4278 if (determine_size) {
4279 p = talloc_asprintf(ctx,
4292 n = snprintf(buf, bufsize,
4300 } else if (StrCaseCmp(name, "mode") == 0) {
4301 if (determine_size) {
4302 p = talloc_asprintf(ctx, "0x%x", mode);
4309 n = snprintf(buf, bufsize, "0x%x", mode);
4313 if (!determine_size && n > bufsize) {
4322 if (! exclude_dos_size) {
4323 if (all || all_dos) {
4324 if (determine_size) {
4325 p = talloc_asprintf(
4335 n = snprintf(buf, bufsize,
4339 } else if (StrCaseCmp(name, "size") == 0) {
4340 if (determine_size) {
4341 p = talloc_asprintf(
4351 n = snprintf(buf, bufsize,
4357 if (!determine_size && n > bufsize) {
4366 if (! exclude_dos_ctime) {
4367 if (all || all_dos) {
4368 if (determine_size) {
4369 p = talloc_asprintf(ctx,
4378 n = snprintf(buf, bufsize,
4379 ",C_TIME:%lu", c_time);
4381 } else if (StrCaseCmp(name, "c_time") == 0) {
4382 if (determine_size) {
4383 p = talloc_asprintf(ctx, "%lu", c_time);
4390 n = snprintf(buf, bufsize, "%lu", c_time);
4394 if (!determine_size && n > bufsize) {
4403 if (! exclude_dos_atime) {
4404 if (all || all_dos) {
4405 if (determine_size) {
4406 p = talloc_asprintf(ctx,
4415 n = snprintf(buf, bufsize,
4416 ",A_TIME:%lu", a_time);
4418 } else if (StrCaseCmp(name, "a_time") == 0) {
4419 if (determine_size) {
4420 p = talloc_asprintf(ctx, "%lu", a_time);
4427 n = snprintf(buf, bufsize, "%lu", a_time);
4431 if (!determine_size && n > bufsize) {
4440 if (! exclude_dos_mtime) {
4441 if (all || all_dos) {
4442 if (determine_size) {
4443 p = talloc_asprintf(ctx,
4452 n = snprintf(buf, bufsize,
4453 ",M_TIME:%lu", m_time);
4455 } else if (StrCaseCmp(name, "m_time") == 0) {
4456 if (determine_size) {
4457 p = talloc_asprintf(ctx, "%lu", m_time);
4464 n = snprintf(buf, bufsize, "%lu", m_time);
4468 if (!determine_size && n > bufsize) {
4477 if (! exclude_dos_inode) {
4478 if (all || all_dos) {
4479 if (determine_size) {
4480 p = talloc_asprintf(
4490 n = snprintf(buf, bufsize,
4494 } else if (StrCaseCmp(name, "inode") == 0) {
4495 if (determine_size) {
4496 p = talloc_asprintf(
4506 n = snprintf(buf, bufsize,
4512 if (!determine_size && n > bufsize) {
4521 /* Restore name pointer to its original value */
4534 /*****************************************************
4535 set the ACLs on a file given an ascii description
4536 *******************************************************/
4537 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
4538 struct cli_state *ipc_cli, POLICY_HND *pol,
4539 const char *filename, const char *the_acl,
4540 int mode, int flags)
4544 SEC_DESC *sd = NULL, *old;
4545 SEC_ACL *dacl = NULL;
4546 DOM_SID *owner_sid = NULL;
4547 DOM_SID *grp_sid = NULL;
4552 BOOL numeric = True;
4554 /* the_acl will be null for REMOVE_ALL operations */
4556 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4560 /* if this is to set the entire ACL... */
4561 if (*the_acl == '*') {
4562 /* ... then increment past the first colon */
4566 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4567 CONST_DISCARD(char *, the_acl));
4575 /* The desired access below is the only one I could find that works
4576 with NT4, W2KP and Samba */
4578 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4581 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4582 filename, cli_errstr(cli)));
4587 old = cli_query_secdesc(cli, fnum, ctx);
4590 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4595 cli_close(cli, fnum);
4598 case SMBC_XATTR_MODE_REMOVE_ALL:
4599 old->dacl->num_aces = 0;
4600 SAFE_FREE(old->dacl->ace);
4601 SAFE_FREE(old->dacl);
4606 case SMBC_XATTR_MODE_REMOVE:
4607 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4610 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4611 if (sec_ace_equal(&sd->dacl->ace[i],
4612 &old->dacl->ace[j])) {
4614 for (k=j; k<old->dacl->num_aces-1;k++) {
4615 old->dacl->ace[k] = old->dacl->ace[k+1];
4617 old->dacl->num_aces--;
4618 if (old->dacl->num_aces == 0) {
4619 SAFE_FREE(old->dacl->ace);
4620 SAFE_FREE(old->dacl);
4637 case SMBC_XATTR_MODE_ADD:
4638 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4641 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4642 if (sid_equal(&sd->dacl->ace[i].trustee,
4643 &old->dacl->ace[j].trustee)) {
4644 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4649 old->dacl->ace[j] = sd->dacl->ace[i];
4655 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4661 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4662 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4668 case SMBC_XATTR_MODE_SET:
4670 owner_sid = old->owner_sid;
4671 grp_sid = old->grp_sid;
4675 case SMBC_XATTR_MODE_CHOWN:
4676 owner_sid = sd->owner_sid;
4679 case SMBC_XATTR_MODE_CHGRP:
4680 grp_sid = sd->grp_sid;
4684 /* Denied ACE entries must come before allowed ones */
4685 sort_acl(old->dacl);
4687 /* Create new security descriptor and set it */
4688 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4689 owner_sid, grp_sid, NULL, dacl, &sd_size);
4691 fnum = cli_nt_create(cli, filename,
4692 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4695 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4696 filename, cli_errstr(cli)));
4701 if (!cli_set_secdesc(cli, fnum, sd)) {
4702 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4709 cli_close(cli, fnum);
4719 int smbc_setxattr_ctx(SMBCCTX *context,
4730 fstring server, share, user, password, workgroup;
4736 if (!context || !context->internal ||
4737 !context->internal->_initialized) {
4739 errno = EINVAL; /* Best I can think of ... */
4751 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n", fname, name, (int) size, (const char*)value));
4753 if (smbc_parse_path(context, fname,
4754 server, sizeof(server),
4755 share, sizeof(share),
4758 password, sizeof(password),
4764 if (user[0] == (char)0) fstrcpy(user, context->user);
4766 fstrcpy(workgroup, context->workgroup);
4768 srv = smbc_server(context, server, share, workgroup, user, password);
4770 return -1; /* errno set by smbc_server */
4773 if (! srv->no_nt_session) {
4774 ipc_srv = smbc_attr_server(context, server, share,
4775 workgroup, user, password,
4777 srv->no_nt_session = True;
4782 ctx = talloc_init("smbc_setxattr");
4789 * Are they asking to set the entire set of known attributes?
4791 if (StrCaseCmp(name, "system.*") == 0 ||
4792 StrCaseCmp(name, "system.*+") == 0) {
4795 talloc_asprintf(ctx, "%s:%s", name+7, (const char *) value);
4803 ret = cacl_set(ctx, &srv->cli,
4804 &ipc_srv->cli, &pol, path,
4807 ? SMBC_XATTR_MODE_SET
4808 : SMBC_XATTR_MODE_ADD),
4814 /* get a DOS Attribute Descriptor with current attributes */
4815 dad = dos_attr_query(context, ctx, path, srv);
4817 /* Overwrite old with new, using what was provided */
4818 dos_attr_parse(context, dad, srv, namevalue);
4820 /* Set the new DOS attributes */
4821 if (! smbc_setatr(context, srv, path,
4827 /* cause failure if NT failed too */
4832 /* we only fail if both NT and DOS sets failed */
4833 if (ret < 0 && ! dad) {
4834 ret = -1; /* in case dad was null */
4840 talloc_destroy(ctx);
4845 * Are they asking to set an access control element or to set
4846 * the entire access control list?
4848 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4849 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4850 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4851 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4852 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4856 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4859 ret = -1; /* errno set by smbc_server() */
4861 else if (! namevalue) {
4865 ret = cacl_set(ctx, &srv->cli,
4866 &ipc_srv->cli, &pol, path,
4869 ? SMBC_XATTR_MODE_SET
4870 : SMBC_XATTR_MODE_ADD),
4873 talloc_destroy(ctx);
4878 * Are they asking to set the owner?
4880 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4881 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
4885 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4889 ret = -1; /* errno set by smbc_server() */
4891 else if (! namevalue) {
4895 ret = cacl_set(ctx, &srv->cli,
4896 &ipc_srv->cli, &pol, path,
4897 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4899 talloc_destroy(ctx);
4904 * Are they asking to set the group?
4906 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4907 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
4911 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4914 /* errno set by smbc_server() */
4917 else if (! namevalue) {
4921 ret = cacl_set(ctx, &srv->cli,
4922 &ipc_srv->cli, &pol, path,
4923 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4925 talloc_destroy(ctx);
4930 * Are they asking to set a DOS attribute?
4932 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4933 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4934 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4935 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4936 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
4938 /* get a DOS Attribute Descriptor with current attributes */
4939 dad = dos_attr_query(context, ctx, path, srv);
4942 talloc_asprintf(ctx, "%s:%s", name+16, (const char *) value);
4947 /* Overwrite old with provided new params */
4948 dos_attr_parse(context, dad, srv, namevalue);
4950 /* Set the new DOS attributes */
4951 ret2 = smbc_setatr(context, srv, path,
4957 /* ret2 has True (success) / False (failure) */
4968 talloc_destroy(ctx);
4972 /* Unsupported attribute name */
4973 talloc_destroy(ctx);
4978 int smbc_getxattr_ctx(SMBCCTX *context,
4987 fstring server, share, user, password, workgroup;
4993 if (!context || !context->internal ||
4994 !context->internal->_initialized) {
4996 errno = EINVAL; /* Best I can think of ... */
5008 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5010 if (smbc_parse_path(context, fname,
5011 server, sizeof(server),
5012 share, sizeof(share),
5015 password, sizeof(password),
5021 if (user[0] == (char)0) fstrcpy(user, context->user);
5023 fstrcpy(workgroup, context->workgroup);
5025 srv = smbc_server(context, server, share, workgroup, user, password);
5027 return -1; /* errno set by smbc_server */
5030 if (! srv->no_nt_session) {
5031 ipc_srv = smbc_attr_server(context, server, share,
5032 workgroup, user, password,
5035 srv->no_nt_session = True;
5041 ctx = talloc_init("smbc:getxattr");
5047 /* Are they requesting a supported attribute? */
5048 if (StrCaseCmp(name, "system.*") == 0 ||
5049 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5050 StrCaseCmp(name, "system.*+") == 0 ||
5051 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5052 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5053 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5054 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5055 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5056 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5057 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5058 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5059 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5060 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5061 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5062 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5063 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5064 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5065 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5066 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5067 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5068 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5069 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
5070 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5073 ret = cacl_get(context, ctx, srv,
5074 ipc_srv == NULL ? NULL : &ipc_srv->cli,
5076 CONST_DISCARD(char *, name),
5077 CONST_DISCARD(char *, value), size);
5078 if (ret < 0 && errno == 0) {
5079 errno = smbc_errno(context, &srv->cli);
5081 talloc_destroy(ctx);
5085 /* Unsupported attribute name */
5086 talloc_destroy(ctx);
5092 int smbc_removexattr_ctx(SMBCCTX *context,
5099 fstring server, share, user, password, workgroup;
5104 if (!context || !context->internal ||
5105 !context->internal->_initialized) {
5107 errno = EINVAL; /* Best I can think of ... */
5119 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5121 if (smbc_parse_path(context, fname,
5122 server, sizeof(server),
5123 share, sizeof(share),
5126 password, sizeof(password),
5132 if (user[0] == (char)0) fstrcpy(user, context->user);
5134 fstrcpy(workgroup, context->workgroup);
5136 srv = smbc_server(context, server, share, workgroup, user, password);
5138 return -1; /* errno set by smbc_server */
5141 if (! srv->no_nt_session) {
5142 ipc_srv = smbc_attr_server(context, server, share,
5143 workgroup, user, password,
5145 srv->no_nt_session = True;
5151 return -1; /* errno set by smbc_attr_server */
5154 ctx = talloc_init("smbc_removexattr");
5160 /* Are they asking to set the entire ACL? */
5161 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5162 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5165 ret = cacl_set(ctx, &srv->cli,
5166 &ipc_srv->cli, &pol, path,
5167 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5168 talloc_destroy(ctx);
5173 * Are they asking to remove one or more spceific security descriptor
5176 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5177 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5178 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5179 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5180 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5181 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5182 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5185 ret = cacl_set(ctx, &srv->cli,
5186 &ipc_srv->cli, &pol, path,
5187 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5188 talloc_destroy(ctx);
5192 /* Unsupported attribute name */
5193 talloc_destroy(ctx);
5198 int smbc_listxattr_ctx(SMBCCTX *context,
5204 * This isn't quite what listxattr() is supposed to do. This returns
5205 * the complete set of attribute names, always, rather than only those
5206 * attribute names which actually exist for a file. Hmmm...
5208 const char supported[] =
5211 "system.nt_sec_desc.revision\0"
5212 "system.nt_sec_desc.owner\0"
5213 "system.nt_sec_desc.owner+\0"
5214 "system.nt_sec_desc.group\0"
5215 "system.nt_sec_desc.group+\0"
5216 "system.nt_sec_desc.acl.*\0"
5217 "system.nt_sec_desc.acl\0"
5218 "system.nt_sec_desc.acl+\0"
5219 "system.nt_sec_desc.*\0"
5220 "system.nt_sec_desc.*+\0"
5221 "system.dos_attr.*\0"
5222 "system.dos_attr.mode\0"
5223 "system.dos_attr.c_time\0"
5224 "system.dos_attr.a_time\0"
5225 "system.dos_attr.m_time\0"
5229 return sizeof(supported);
5232 if (sizeof(supported) > size) {
5237 /* this can't be strcpy() because there are embedded null characters */
5238 memcpy(list, supported, sizeof(supported));
5239 return sizeof(supported);
5244 * Open a print file to be written to by other calls
5247 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
5249 fstring server, share, user, password;
5252 if (!context || !context->internal ||
5253 !context->internal->_initialized) {
5267 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5269 if (smbc_parse_path(context, fname,
5270 server, sizeof(server),
5271 share, sizeof(share),
5274 password, sizeof(password),
5280 /* What if the path is empty, or the file exists? */
5282 return context->open(context, fname, O_WRONLY, 666);
5287 * Routine to print a file on a remote server ...
5289 * We open the file, which we assume to be on a remote server, and then
5290 * copy it to a print file on the share specified by printq.
5293 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
5295 SMBCFILE *fid1, *fid2;
5296 int bytes, saverr, tot_bytes = 0;
5299 if (!c_file || !c_file->internal->_initialized || !c_print ||
5300 !c_print->internal->_initialized) {
5307 if (!fname && !printq) {
5314 /* Try to open the file for reading ... */
5316 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5318 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5319 return -1; /* smbc_open sets errno */
5323 /* Now, try to open the printer file for writing */
5325 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5327 saverr = errno; /* Save errno */
5328 c_file->close_fn(c_file, fid1);
5334 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5338 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5341 c_file->close_fn(c_file, fid1);
5342 c_print->close_fn(c_print, fid2);
5351 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5352 c_print->close_fn(c_print, fid2);
5366 * Routine to list print jobs on a printer share ...
5369 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
5372 fstring server, share, user, password, workgroup;
5375 if (!context || !context->internal ||
5376 !context->internal->_initialized) {
5390 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5392 if (smbc_parse_path(context, fname,
5393 server, sizeof(server),
5394 share, sizeof(share),
5397 password, sizeof(password),
5403 if (user[0] == (char)0) fstrcpy(user, context->user);
5405 fstrcpy(workgroup, context->workgroup);
5407 srv = smbc_server(context, server, share, workgroup, user, password);
5411 return -1; /* errno set by smbc_server */
5415 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
5417 errno = smbc_errno(context, &srv->cli);
5427 * Delete a print job from a remote printer share
5430 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
5433 fstring server, share, user, password, workgroup;
5437 if (!context || !context->internal ||
5438 !context->internal->_initialized) {
5452 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5454 if (smbc_parse_path(context, fname,
5455 server, sizeof(server),
5456 share, sizeof(share),
5459 password, sizeof(password),
5465 if (user[0] == (char)0) fstrcpy(user, context->user);
5467 fstrcpy(workgroup, context->workgroup);
5469 srv = smbc_server(context, server, share, workgroup, user, password);
5473 return -1; /* errno set by smbc_server */
5477 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5480 errno = smbc_errno(context, &srv->cli);
5481 else if (err == ERRnosuchprintjob)
5492 * Get a new empty handle to fill in with your own info
5494 SMBCCTX * smbc_new_context(void)
5498 context = SMB_MALLOC_P(SMBCCTX);
5504 ZERO_STRUCTP(context);
5506 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5507 if (!context->internal) {
5512 ZERO_STRUCTP(context->internal);
5515 /* ADD REASONABLE DEFAULTS */
5517 context->timeout = 20000; /* 20 seconds */
5519 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5520 context->options.urlencode_readdir_entries = False;/* backward compat */
5521 context->options.one_share_per_server = False;/* backward compat */
5523 context->open = smbc_open_ctx;
5524 context->creat = smbc_creat_ctx;
5525 context->read = smbc_read_ctx;
5526 context->write = smbc_write_ctx;
5527 context->close_fn = smbc_close_ctx;
5528 context->unlink = smbc_unlink_ctx;
5529 context->rename = smbc_rename_ctx;
5530 context->lseek = smbc_lseek_ctx;
5531 context->stat = smbc_stat_ctx;
5532 context->fstat = smbc_fstat_ctx;
5533 context->opendir = smbc_opendir_ctx;
5534 context->closedir = smbc_closedir_ctx;
5535 context->readdir = smbc_readdir_ctx;
5536 context->getdents = smbc_getdents_ctx;
5537 context->mkdir = smbc_mkdir_ctx;
5538 context->rmdir = smbc_rmdir_ctx;
5539 context->telldir = smbc_telldir_ctx;
5540 context->lseekdir = smbc_lseekdir_ctx;
5541 context->fstatdir = smbc_fstatdir_ctx;
5542 context->chmod = smbc_chmod_ctx;
5543 context->utimes = smbc_utimes_ctx;
5544 context->setxattr = smbc_setxattr_ctx;
5545 context->getxattr = smbc_getxattr_ctx;
5546 context->removexattr = smbc_removexattr_ctx;
5547 context->listxattr = smbc_listxattr_ctx;
5548 context->open_print_job = smbc_open_print_job_ctx;
5549 context->print_file = smbc_print_file_ctx;
5550 context->list_print_jobs = smbc_list_print_jobs_ctx;
5551 context->unlink_print_job = smbc_unlink_print_job_ctx;
5553 context->callbacks.check_server_fn = smbc_check_server;
5554 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5556 smbc_default_cache_functions(context);
5564 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5565 * and thus you'll be leaking memory if not handled properly.
5568 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
5577 DEBUG(1,("Performing aggressive shutdown.\n"));
5579 f = context->internal->_files;
5581 context->close_fn(context, f);
5584 context->internal->_files = NULL;
5586 /* First try to remove the servers the nice way. */
5587 if (context->callbacks.purge_cached_fn(context)) {
5590 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
5591 s = context->internal->_servers;
5593 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
5594 cli_shutdown(&s->cli);
5595 context->callbacks.remove_cached_srv_fn(context, s);
5597 DLIST_REMOVE(context->internal->_servers, s);
5601 context->internal->_servers = NULL;
5605 /* This is the polite way */
5606 if (context->callbacks.purge_cached_fn(context)) {
5607 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
5611 if (context->internal->_servers) {
5612 DEBUG(1, ("Active servers in context, free_context failed.\n"));
5616 if (context->internal->_files) {
5617 DEBUG(1, ("Active files in context, free_context failed.\n"));
5623 /* Things we have to clean up */
5624 SAFE_FREE(context->workgroup);
5625 SAFE_FREE(context->netbios_name);
5626 SAFE_FREE(context->user);
5628 DEBUG(3, ("Context %p succesfully freed\n", context));
5629 SAFE_FREE(context->internal);
5636 * Initialise the library etc
5638 * We accept a struct containing handle information.
5639 * valid values for info->debug from 0 to 100,
5640 * and insist that info->fn must be non-null.
5642 SMBCCTX * smbc_init_context(SMBCCTX * context)
5646 char *user = NULL, *home = NULL;
5648 if (!context || !context->internal) {
5653 /* Do not initialise the same client twice */
5654 if (context->internal->_initialized) {
5658 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
5665 if (!smbc_initialized) {
5666 /* Do some library wide intialisations the first time we get called */
5667 BOOL conf_loaded = False;
5669 /* Set this to what the user wants */
5670 DEBUGLEVEL = context->debug;
5672 setup_logging( "libsmbclient", True);
5674 /* Here we would open the smb.conf file if needed ... */
5676 load_interfaces(); /* Load the list of interfaces ... */
5678 in_client = True; /* FIXME, make a param */
5680 home = getenv("HOME");
5682 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5683 if (lp_load(conf, True, False, False)) {
5686 DEBUG(5, ("Could not load config file: %s\n",
5693 * Well, if that failed, try the dyn_CONFIGFILE
5694 * Which points to the standard locn, and if that
5695 * fails, silently ignore it and use the internal
5699 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
5700 DEBUG(5, ("Could not load config file: %s\n",
5704 * We loaded the global config file. Now lets
5705 * load user-specific modifications to the
5708 slprintf(conf, sizeof(conf),
5709 "%s/.smb/smb.conf.append", home);
5710 if (!lp_load(conf, True, False, False)) {
5712 ("Could not append config file: "
5719 reopen_logs(); /* Get logging working ... */
5722 * Block SIGPIPE (from lib/util_sock.c: write())
5723 * It is not needed and should not stop execution
5725 BlockSignals(True, SIGPIPE);
5727 /* Done with one-time initialisation */
5728 smbc_initialized = 1;
5732 if (!context->user) {
5734 * FIXME: Is this the best way to get the user info?
5736 user = getenv("USER");
5737 /* walk around as "guest" if no username can be found */
5738 if (!user) context->user = SMB_STRDUP("guest");
5739 else context->user = SMB_STRDUP(user);
5742 if (!context->netbios_name) {
5744 * We try to get our netbios name from the config. If that fails we fall
5745 * back on constructing our netbios name from our hostname etc
5747 if (global_myname()) {
5748 context->netbios_name = SMB_STRDUP(global_myname());
5752 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
5755 context->netbios_name = SMB_MALLOC(17);
5756 if (!context->netbios_name) {
5760 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
5764 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
5766 if (!context->workgroup) {
5767 if (lp_workgroup()) {
5768 context->workgroup = SMB_STRDUP(lp_workgroup());
5771 /* TODO: Think about a decent default workgroup */
5772 context->workgroup = SMB_STRDUP("samba");
5776 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
5778 /* shortest timeout is 1 second */
5779 if (context->timeout > 0 && context->timeout < 1000)
5780 context->timeout = 1000;
5783 * FIXME: Should we check the function pointers here?
5786 context->internal->_initialized = 1;
5792 /* Return the verion of samba, and thus libsmbclient */
5796 return samba_version_string();