2 Unix SMB/Netbios implementation.
3 SMB client library implementation
4 Copyright (C) Andrew Tridgell 1998
5 Copyright (C) Richard Sharpe 2000, 2002
6 Copyright (C) John Terpstra 2000
7 Copyright (C) Tom Jansen (Ninja ISD) 2002
8 Copyright (C) Derrell Lipman 2003, 2004
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include "include/libsmb_internal.h"
31 * DOS Attribute values (used internally)
33 typedef struct DOS_ATTR_DESC {
44 * Internal flags for extended attributes
47 /* internal mode values */
48 #define SMBC_XATTR_MODE_ADD 1
49 #define SMBC_XATTR_MODE_REMOVE 2
50 #define SMBC_XATTR_MODE_REMOVE_ALL 3
51 #define SMBC_XATTR_MODE_SET 4
52 #define SMBC_XATTR_MODE_CHOWN 5
53 #define SMBC_XATTR_MODE_CHGRP 6
55 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
57 /*We should test for this in configure ... */
59 #define ENOTSUP EOPNOTSUPP
63 * Functions exported by libsmb_cache.c that we need here
65 int smbc_default_cache_functions(SMBCCTX *context);
68 * check if an element is part of the list.
69 * FIXME: Does not belong here !
70 * Can anyone put this in a macro in dlinklist.h ?
73 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
74 if (!p || !list) return False;
76 if (p == list) return True;
83 * Find an lsa pipe handle associated with a cli struct.
86 static struct rpc_pipe_client *find_lsa_pipe_hnd(struct cli_state *ipc_cli)
88 struct rpc_pipe_client *pipe_hnd;
90 for (pipe_hnd = ipc_cli->pipe_list; pipe_hnd; pipe_hnd = pipe_hnd->next) {
91 if (pipe_hnd->pipe_idx == PI_LSARPC) {
99 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file);
100 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence);
102 extern BOOL in_client;
105 * Is the logging working / configfile read ?
107 static int smbc_initialized = 0;
110 hex2int( unsigned int _char )
112 if ( _char >= 'A' && _char <='F')
113 return _char - 'A' + 10;
114 if ( _char >= 'a' && _char <='f')
115 return _char - 'a' + 10;
116 if ( _char >= '0' && _char <='9')
124 * Convert strings of %xx to their single character equivalent. Each 'x' must
125 * be a valid hexadecimal digit, or that % sequence is left undecoded.
127 * dest may, but need not be, the same pointer as src.
129 * Returns the number of % sequences which could not be converted due to lack
130 * of two following hexadecimal digits.
133 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
135 int old_length = strlen(src);
141 if ( old_length == 0 ) {
146 while ( i < old_length ) {
147 unsigned char character = src[ i++ ];
149 if (character == '%') {
150 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
151 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
153 /* Replace valid sequence */
154 if (a != -1 && b != -1) {
156 /* Replace valid %xx sequence with %dd */
157 character = (a * 16) + b;
159 if (character == '\0') {
160 break; /* Stop at %00 */
175 strncpy(dest, temp, max_dest_len);
183 * Convert any characters not specifically allowed in a URL into their %xx
186 * Returns the remaining buffer length.
189 smbc_urlencode(char * dest, char * src, int max_dest_len)
191 char hex[] = "0123456789ABCDEF";
193 for (; *src != '\0' && max_dest_len >= 3; src++) {
205 *dest++ = hex[(*src >> 4) & 0x0f];
206 *dest++ = hex[*src & 0x0f];
221 * Function to parse a path and turn it into components
223 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
224 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
225 * general format ("smb:" only; we do not look for "cifs:").
229 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
233 * smb:// Show all workgroups.
235 * The method of locating the list of workgroups varies
236 * depending upon the setting of the context variable
237 * context->options.browse_max_lmb_count. This value
238 * determine the maximum number of local master browsers to
239 * query for the list of workgroups. In order to ensure that
240 * a complete list of workgroups is obtained, all master
241 * browsers must be queried, but if there are many
242 * workgroups, the time spent querying can begin to add up.
243 * For small networks (not many workgroups), it is suggested
244 * that this variable be set to 0, indicating query all local
245 * master browsers. When the network has many workgroups, a
246 * reasonable setting for this variable might be around 3.
248 * smb://name/ if name<1D> or name<1B> exists, list servers in
249 * workgroup, else, if name<20> exists, list all shares
252 * If "options" are provided, this function returns the entire option list as a
253 * string, for later parsing by the caller. Note that currently, no options
257 static const char *smbc_prefix = "smb:";
260 smbc_parse_path(SMBCCTX *context,
262 char *server, int server_len,
263 char *share, int share_len,
264 char *path, int path_len,
265 char *user, int user_len,
266 char *password, int password_len,
267 char *options, int options_len)
275 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
276 if (options != NULL && options_len > 0) {
277 options[0] = (char)0;
281 /* see if it has the right prefix */
282 len = strlen(smbc_prefix);
283 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
284 return -1; /* What about no smb: ? */
289 /* Watch the test below, we are testing to see if we should exit */
291 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
293 DEBUG(1, ("Invalid path (does not begin with smb://"));
298 p += 2; /* Skip the double slash */
300 /* See if any options were specified */
301 if ((q = strrchr(p, '?')) != NULL ) {
302 /* There are options. Null terminate here and point to them */
305 DEBUG(4, ("Found options '%s'", q));
307 /* Copy the options */
308 if (options != NULL && options_len > 0) {
309 safe_strcpy(options, q, options_len - 1);
318 strncpy(server, context->workgroup,
319 (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
325 * ok, its for us. Now parse out the server, share etc.
327 * However, we want to parse out [[domain;]user[:password]@] if it
331 /* check that '@' occurs before '/', if '/' exists at all */
332 q = strchr_m(p, '@');
333 r = strchr_m(p, '/');
334 if (q && (!r || q < r)) {
335 pstring username, passwd, domain;
336 const char *u = userinfo;
338 next_token(&p, userinfo, "@", sizeof(fstring));
340 username[0] = passwd[0] = domain[0] = 0;
342 if (strchr_m(u, ';')) {
344 next_token(&u, domain, ";", sizeof(fstring));
348 if (strchr_m(u, ':')) {
350 next_token(&u, username, ":", sizeof(fstring));
357 pstrcpy(username, u);
362 strncpy(user, username, user_len); /* FIXME, domain */
365 strncpy(password, passwd, password_len);
369 if (!next_token(&p, server, "/", sizeof(fstring))) {
375 if (*p == (char)0) goto decoding; /* That's it ... */
377 if (!next_token(&p, share, "/", sizeof(fstring))) {
383 safe_strcpy(path, p, path_len - 1);
385 all_string_sub(path, "/", "\\", 0);
388 (void) smbc_urldecode(path, path, path_len);
389 (void) smbc_urldecode(server, server, server_len);
390 (void) smbc_urldecode(share, share, share_len);
391 (void) smbc_urldecode(user, user, user_len);
392 (void) smbc_urldecode(password, password, password_len);
398 * Verify that the options specified in a URL are valid
400 static int smbc_check_options(char *server, char *share, char *path, char *options)
402 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' path='%s' options='%s'\n", server, share, path, options));
404 /* No options at all is always ok */
405 if (! *options) return 0;
407 /* Currently, we don't support any options. */
412 * Convert an SMB error into a UNIX error ...
414 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
416 int ret = cli_errno(c);
418 if (cli_is_dos_error(c)) {
422 cli_dos_error(c, &eclass, &ecode);
424 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
425 (int)eclass, (int)ecode, (int)ecode, ret));
429 status = cli_nt_error(c);
431 DEBUG(3,("smbc errno %s -> %d\n",
432 nt_errstr(status), ret));
439 * Check a server for being alive and well.
440 * returns 0 if the server is in shape. Returns 1 on error
442 * Also useable outside libsmbclient to enable external cache
443 * to do some checks too.
445 int smbc_check_server(SMBCCTX * context, SMBCSRV * server)
447 if ( send_keepalive(server->cli.fd) == False )
450 /* connection is ok */
455 * Remove a server from the cached server list it's unused.
456 * On success, 0 is returned. 1 is returned if the server could not be removed.
458 * Also useable outside libsmbclient
460 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
464 /* are we being fooled ? */
465 if (!context || !context->internal ||
466 !context->internal->_initialized || !srv) return 1;
469 /* Check all open files/directories for a relation with this server */
470 for (file = context->internal->_files; file; file=file->next) {
471 if (file->srv == srv) {
473 DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n",
479 DLIST_REMOVE(context->internal->_servers, srv);
481 cli_shutdown(&srv->cli);
483 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
485 context->callbacks.remove_cached_srv_fn(context, srv);
492 SMBCSRV *find_server(SMBCCTX *context,
504 srv = context->callbacks.get_cached_srv_fn(context, server, share,
505 workgroup, username);
507 if (!auth_called && !srv && (!username[0] || !password[0])) {
508 context->callbacks.auth_fn(server, share,
509 workgroup, sizeof(fstring),
510 username, sizeof(fstring),
511 password, sizeof(fstring));
513 * However, smbc_auth_fn may have picked up info relating to
514 * an existing connection, so try for an existing connection
518 goto check_server_cache;
523 if (context->callbacks.check_server_fn(context, srv)) {
525 * This server is no good anymore
526 * Try to remove it and check for more possible
527 * servers in the cache
529 if (context->callbacks.remove_unused_server_fn(context,
532 * We could not remove the server completely,
533 * remove it from the cache so we will not get
534 * it again. It will be removed when the last
535 * file/dir is closed.
537 context->callbacks.remove_cached_srv_fn(context,
542 * Maybe there are more cached connections to this
545 goto check_server_cache;
555 * Connect to a server, possibly on an existing connection
557 * Here, what we want to do is: If the server and username
558 * match an existing connection, reuse that, otherwise, establish a
561 * If we have to create a new connection, call the auth_fn to get the
562 * info we need, unless the username and password were passed in.
565 SMBCSRV *smbc_server(SMBCCTX *context,
566 const char *server, const char *share,
567 fstring workgroup, fstring username,
572 struct nmb_name called, calling;
573 const char *server_n = server;
576 int tried_reverse = 0;
579 const char *username_used;
584 if (server[0] == 0) {
589 /* Look for a cached connection */
590 srv = find_server(context, server, share,
591 workgroup, username, password);
594 * If we found a connection and we're only allowed one share per
597 if (srv && *share != '\0' && context->options.one_share_per_server) {
600 * ... then if there's no current connection to the share,
601 * connect to it. find_server(), or rather the function
602 * pointed to by context->callbacks.get_cached_srv_fn which
603 * was called by find_server(), will have issued a tree
604 * disconnect if the requested share is not the same as the
605 * one that was already connected.
607 if (srv->cli.cnum == (uint16) -1) {
608 /* Ensure we have accurate auth info */
609 context->callbacks.auth_fn(server, share,
610 workgroup, sizeof(fstring),
611 username, sizeof(fstring),
612 password, sizeof(fstring));
614 if (! cli_send_tconX(&srv->cli, share, "?????",
615 password, strlen(password)+1)) {
617 errno = smbc_errno(context, &srv->cli);
618 cli_shutdown(&srv->cli);
619 context->callbacks.remove_cached_srv_fn(context, srv);
623 /* Regenerate the dev value since it's based on both server and share */
625 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
630 /* If we have a connection... */
633 /* ... then we're done here. Give 'em what they came for. */
637 make_nmb_name(&calling, context->netbios_name, 0x0);
638 make_nmb_name(&called , server, 0x20);
640 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
642 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
645 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
649 /* have to open a new connection */
650 if (!cli_initialise(&c)) {
655 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
656 c.use_kerberos = True;
658 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
659 c.fallback_after_kerberos = True;
662 c.timeout = context->timeout;
665 * Force use of port 139 for first try if share is $IPC, empty, or
666 * null, so browse lists can work
668 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
669 port_try_first = 139;
672 port_try_first = 445;
676 c.port = port_try_first;
678 if (!cli_connect(&c, server_n, &ip)) {
680 /* First connection attempt failed. Try alternate port. */
681 c.port = port_try_next;
683 if (!cli_connect(&c, server_n, &ip)) {
690 if (!cli_session_request(&c, &calling, &called)) {
692 if (strcmp(called.name, "*SMBSERVER")) {
693 make_nmb_name(&called , "*SMBSERVER", 0x20);
696 else { /* Try one more time, but ensure we don't loop */
698 /* Only try this if server is an IP address ... */
700 if (is_ipaddress(server) && !tried_reverse) {
702 struct in_addr rem_ip;
704 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
705 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
710 tried_reverse++; /* Yuck */
712 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
713 make_nmb_name(&called, remote_name, 0x20);
724 DEBUG(4,(" session request ok\n"));
726 if (!cli_negprot(&c)) {
732 username_used = username;
734 if (!cli_session_setup(&c, username_used,
735 password, strlen(password),
736 password, strlen(password),
739 /* Failed. Try an anonymous login, if allowed by flags. */
742 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
743 !cli_session_setup(&c, username_used,
754 DEBUG(4,(" session setup ok\n"));
756 if (!cli_send_tconX(&c, share, "?????",
757 password, strlen(password)+1)) {
758 errno = smbc_errno(context, &c);
763 DEBUG(4,(" tconx ok\n"));
766 * Ok, we have got a nice connection
767 * Let's allocate a server structure.
770 srv = SMB_MALLOC_P(SMBCSRV);
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)));
859 pipe_hnd = cli_rpc_pipe_open_noauth(ipc_cli,
863 DEBUG(1, ("cli_nt_session_open fail!\n"));
865 cli_shutdown(ipc_cli);
870 * Some systems don't support
871 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
872 * so we might as well do it too.
875 nt_status = rpccli_lsa_open_policy(
879 GENERIC_EXECUTE_ACCESS,
882 if (!NT_STATUS_IS_OK(nt_status)) {
883 errno = smbc_errno(context, ipc_cli);
884 cli_shutdown(ipc_cli);
889 ipc_srv = SMB_MALLOC_P(SMBCSRV);
892 cli_shutdown(ipc_cli);
896 ZERO_STRUCTP(ipc_srv);
897 ipc_srv->cli = *ipc_cli;
901 /* now add it to the cache (internal or external) */
903 errno = 0; /* let cache function set errno if it likes */
904 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
909 DEBUG(3, (" Failed to add server to cache\n"));
913 cli_shutdown(&ipc_srv->cli);
918 DLIST_ADD(context->internal->_servers, ipc_srv);
925 * Routine to open() a file ...
928 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
930 fstring server, share, user, password, workgroup;
933 struct cli_state *targetcli;
935 SMBCFILE *file = NULL;
938 if (!context || !context->internal ||
939 !context->internal->_initialized) {
941 errno = EINVAL; /* Best I can think of ... */
953 if (smbc_parse_path(context, fname,
954 server, sizeof(server),
955 share, sizeof(share),
958 password, sizeof(password),
964 if (user[0] == (char)0) fstrcpy(user, context->user);
966 fstrcpy(workgroup, context->workgroup);
968 srv = smbc_server(context, server, share, workgroup, user, password);
972 if (errno == EPERM) errno = EACCES;
973 return NULL; /* smbc_server sets errno */
977 /* Hmmm, the test for a directory is suspect here ... FIXME */
979 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
986 file = SMB_MALLOC_P(SMBCFILE);
997 /*d_printf(">>>open: resolving %s\n", path);*/
998 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1000 d_printf("Could not resolve %s\n", path);
1003 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1005 if ( targetcli->dfsroot )
1008 pstrcpy(temppath, targetpath);
1009 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1012 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1014 /* Handle the error ... */
1017 errno = smbc_errno(context, targetcli);
1022 /* Fill in file struct */
1025 file->fname = SMB_STRDUP(fname);
1030 DLIST_ADD(context->internal->_files, file);
1033 * If the file was opened in O_APPEND mode, all write
1034 * operations should be appended to the file. To do that,
1035 * though, using this protocol, would require a getattrE()
1036 * call for each and every write, to determine where the end
1037 * of the file is. (There does not appear to be an append flag
1038 * in the protocol.) Rather than add all of that overhead of
1039 * retrieving the current end-of-file offset prior to each
1040 * write operation, we'll assume that most append operations
1041 * will continuously write, so we'll just set the offset to
1042 * the end of the file now and hope that's adequate.
1044 * Note to self: If this proves inadequate, and O_APPEND
1045 * should, in some cases, be forced for each write, add a
1046 * field in the context options structure, for
1047 * "strict_append_mode" which would select between the current
1048 * behavior (if FALSE) or issuing a getattrE() prior to each
1049 * write and forcing the write to the end of the file (if
1050 * TRUE). Adding that capability will likely require adding
1051 * an "append" flag into the _SMBCFILE structure to track
1052 * whether a file was opened in O_APPEND mode. -- djl
1054 if (flags & O_APPEND) {
1055 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1056 (void) smbc_close_ctx(context, file);
1066 /* Check if opendir needed ... */
1071 eno = smbc_errno(context, &srv->cli);
1072 file = context->opendir(context, fname);
1073 if (!file) errno = eno;
1078 errno = EINVAL; /* FIXME, correct errno ? */
1084 * Routine to create a file
1087 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1089 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
1092 if (!context || !context->internal ||
1093 !context->internal->_initialized) {
1100 return smbc_open_ctx(context, path, creat_bits, mode);
1104 * Routine to read() a file ...
1107 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1110 fstring server, share, user, password;
1111 pstring path, targetpath;
1112 struct cli_state *targetcli;
1117 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1118 * appears to pass file->offset (which is type off_t) differently than
1119 * a local variable of type off_t. Using local variable "offset" in
1120 * the call to cli_read() instead of file->offset fixes a problem
1121 * retrieving data at an offset greater than 4GB.
1123 off_t offset = file->offset;
1125 if (!context || !context->internal ||
1126 !context->internal->_initialized) {
1133 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1135 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1142 /* Check that the buffer exists ... */
1151 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1152 if (smbc_parse_path(context, file->fname,
1153 server, sizeof(server),
1154 share, sizeof(share),
1157 password, sizeof(password),
1163 /*d_printf(">>>read: resolving %s\n", path);*/
1164 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1166 d_printf("Could not resolve %s\n", path);
1169 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1171 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1175 errno = smbc_errno(context, targetcli);
1180 file->offset += ret;
1182 DEBUG(4, (" --> %d\n", ret));
1184 return ret; /* Success, ret bytes of data ... */
1189 * Routine to write() a file ...
1192 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1195 off_t offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1196 fstring server, share, user, password;
1197 pstring path, targetpath;
1198 struct cli_state *targetcli;
1200 if (!context || !context->internal ||
1201 !context->internal->_initialized) {
1208 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1215 /* Check that the buffer exists ... */
1224 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1225 if (smbc_parse_path(context, file->fname,
1226 server, sizeof(server),
1227 share, sizeof(share),
1230 password, sizeof(password),
1236 /*d_printf(">>>write: resolving %s\n", path);*/
1237 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1239 d_printf("Could not resolve %s\n", path);
1242 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1245 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1249 errno = smbc_errno(context, targetcli);
1254 file->offset += ret;
1256 return ret; /* Success, 0 bytes of data ... */
1260 * Routine to close() a file ...
1263 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1266 fstring server, share, user, password;
1267 pstring path, targetpath;
1268 struct cli_state *targetcli;
1270 if (!context || !context->internal ||
1271 !context->internal->_initialized) {
1278 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1288 return context->closedir(context, file);
1292 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1293 if (smbc_parse_path(context, file->fname,
1294 server, sizeof(server),
1295 share, sizeof(share),
1298 password, sizeof(password),
1304 /*d_printf(">>>close: resolving %s\n", path);*/
1305 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1307 d_printf("Could not resolve %s\n", path);
1310 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1312 if (!cli_close(targetcli, file->cli_fd)) {
1314 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1316 /* Deallocate slot and remove the server
1317 * from the server cache if unused */
1318 errno = smbc_errno(context, targetcli);
1320 DLIST_REMOVE(context->internal->_files, file);
1321 SAFE_FREE(file->fname);
1323 context->callbacks.remove_unused_server_fn(context, srv);
1329 DLIST_REMOVE(context->internal->_files, file);
1330 SAFE_FREE(file->fname);
1337 * Get info from an SMB server on a file. Use a qpathinfo call first
1338 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1340 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1341 uint16 *mode, SMB_OFF_T *size,
1342 time_t *c_time, time_t *a_time, time_t *m_time,
1347 struct cli_state *targetcli;
1348 if (!context || !context->internal ||
1349 !context->internal->_initialized) {
1356 /* path fixup for . and .. */
1357 if (strequal(path, ".") || strequal(path, ".."))
1358 pstrcpy(fixedpath, "\\");
1361 pstrcpy(fixedpath, path);
1362 trim_string(fixedpath, NULL, "\\..");
1363 trim_string(fixedpath, NULL, "\\.");
1365 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1367 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1369 d_printf("Couldn't resolve %s\n", path);
1373 if ( targetcli->dfsroot )
1376 pstrcpy(temppath, targetpath);
1377 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1380 if (!srv->no_pathinfo2 &&
1381 cli_qpathinfo2(targetcli, targetpath, c_time, a_time, m_time, NULL,
1382 size, mode, ino)) return True;
1384 /* if this is NT then don't bother with the getatr */
1385 if (targetcli->capabilities & CAP_NT_SMBS) {
1390 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1391 if (m_time != NULL) {
1392 if (a_time != NULL) *a_time = *m_time;
1393 if (c_time != NULL) *c_time = *m_time;
1395 srv->no_pathinfo2 = True;
1405 * Set file info on an SMB server. Use setpathinfo call first. If that
1406 * fails, use setattrE..
1408 * Access and modification time parameters are always used and must be
1409 * provided. Create time, if zero, will be determined from the actual create
1410 * time of the file. If non-zero, the create time will be set as well.
1412 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1414 static BOOL smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1415 time_t c_time, time_t a_time, time_t m_time,
1422 * Get the create time of the file (if not provided); we'll need it in
1425 if (! srv->no_pathinfo && c_time == 0) {
1426 if (! cli_qpathinfo(&srv->cli, path,
1427 &c_time, NULL, NULL, NULL, NULL)) {
1428 /* qpathinfo not available */
1429 srv->no_pathinfo = True;
1432 * We got a creation time. Some OS versions don't
1433 * return a valid create time, though. If we got an
1434 * invalid time, start with the current time instead.
1436 if (c_time == 0 || c_time == (time_t) -1) {
1437 c_time = time(NULL);
1441 * We got a creation time. For sanity sake, since
1442 * there is no POSIX function to set the create time
1443 * of a file, if the existing create time is greater
1444 * than either of access time or modification time,
1445 * set create time to the smallest of those. This
1446 * ensure that the create time of a file is never
1447 * greater than its last access or modification time.
1449 if (c_time > a_time) c_time = a_time;
1450 if (c_time > m_time) c_time = m_time;
1455 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1456 * modern function for "new code" to be using, and it works given a
1457 * filename rather than requiring that the file be opened to have its
1458 * attributes manipulated.
1460 if (srv->no_pathinfo ||
1461 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1464 * setpathinfo is not supported; go to plan B.
1466 * cli_setatr() does not work on win98, and it also doesn't
1467 * support setting the access time (only the modification
1468 * time), so in all cases, we open the specified file and use
1469 * cli_setattrE() which should work on all OS versions, and
1470 * supports both times.
1473 /* Don't try {q,set}pathinfo() again, with this server */
1474 srv->no_pathinfo = True;
1477 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1479 errno = smbc_errno(context, &srv->cli);
1484 * Get the creat time of the file (if it wasn't provided).
1485 * We'll need it in the set call
1488 ret = cli_getattrE(&srv->cli, fd,
1490 &c_time, NULL, NULL);
1495 /* If we got create time, set times */
1497 /* Some OS versions don't support create time */
1498 if (c_time == 0 || c_time == -1) {
1499 c_time = time(NULL);
1503 * For sanity sake, since there is no POSIX function
1504 * to set the create time of a file, if the existing
1505 * create time is greater than either of access time
1506 * or modification time, set create time to the
1507 * smallest of those. This ensure that the create
1508 * time of a file is never greater than its last
1509 * access or modification time.
1511 if (c_time > a_time) c_time = a_time;
1512 if (c_time > m_time) c_time = m_time;
1514 /* Set the new attributes */
1515 ret = cli_setattrE(&srv->cli, fd,
1516 c_time, a_time, m_time);
1517 cli_close(&srv->cli, fd);
1521 * Unfortunately, setattrE() doesn't have a provision for
1522 * setting the access mode (attributes). We'll have to try
1523 * cli_setatr() for that, and with only this parameter, it
1524 * seems to work on win98.
1526 if (ret && mode != (uint16) -1) {
1527 ret = cli_setatr(&srv->cli, path, mode, 0);
1531 errno = smbc_errno(context, &srv->cli);
1540 * Routine to unlink() a file
1543 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1545 fstring server, share, user, password, workgroup;
1546 pstring path, targetpath;
1547 struct cli_state *targetcli;
1548 SMBCSRV *srv = NULL;
1550 if (!context || !context->internal ||
1551 !context->internal->_initialized) {
1553 errno = EINVAL; /* Best I can think of ... */
1565 if (smbc_parse_path(context, fname,
1566 server, sizeof(server),
1567 share, sizeof(share),
1570 password, sizeof(password),
1576 if (user[0] == (char)0) fstrcpy(user, context->user);
1578 fstrcpy(workgroup, context->workgroup);
1580 srv = smbc_server(context, server, share, workgroup, user, password);
1584 return -1; /* smbc_server sets errno */
1588 /*d_printf(">>>unlink: resolving %s\n", path);*/
1589 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1591 d_printf("Could not resolve %s\n", path);
1594 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1596 if (!cli_unlink(targetcli, targetpath)) {
1598 errno = smbc_errno(context, targetcli);
1600 if (errno == EACCES) { /* Check if the file is a directory */
1605 time_t m_time = 0, a_time = 0, c_time = 0;
1608 if (!smbc_getatr(context, srv, path, &mode, &size,
1609 &c_time, &a_time, &m_time, &ino)) {
1611 /* Hmmm, bad error ... What? */
1613 errno = smbc_errno(context, targetcli);
1619 if (IS_DOS_DIR(mode))
1622 errno = saverr; /* Restore this */
1631 return 0; /* Success ... */
1636 * Routine to rename() a file
1639 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1640 SMBCCTX *ncontext, const char *nname)
1642 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1643 pstring path1, path2, targetpath1, targetpath2;
1644 struct cli_state *targetcli1, *targetcli2;
1645 SMBCSRV *srv = NULL;
1647 if (!ocontext || !ncontext ||
1648 !ocontext->internal || !ncontext->internal ||
1649 !ocontext->internal->_initialized ||
1650 !ncontext->internal->_initialized) {
1652 errno = EINVAL; /* Best I can think of ... */
1657 if (!oname || !nname) {
1664 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1666 smbc_parse_path(ocontext, oname,
1667 server1, sizeof(server1),
1668 share1, sizeof(share1),
1669 path1, sizeof(path1),
1670 user1, sizeof(user1),
1671 password1, sizeof(password1),
1674 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1676 smbc_parse_path(ncontext, nname,
1677 server2, sizeof(server2),
1678 share2, sizeof(share2),
1679 path2, sizeof(path2),
1680 user2, sizeof(user2),
1681 password2, sizeof(password2),
1684 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1686 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1687 strcmp(user1, user2)) {
1689 /* Can't rename across file systems, or users?? */
1696 fstrcpy(workgroup, ocontext->workgroup);
1697 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1698 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1705 /*d_printf(">>>rename: resolving %s\n", path1);*/
1706 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1708 d_printf("Could not resolve %s\n", path1);
1711 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1712 /*d_printf(">>>rename: resolving %s\n", path2);*/
1713 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1715 d_printf("Could not resolve %s\n", path2);
1718 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1720 if (strcmp(targetcli1->desthost, targetcli2->desthost) || strcmp(targetcli1->share, targetcli2->share))
1722 /* can't rename across file systems */
1728 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1729 int eno = smbc_errno(ocontext, targetcli1);
1731 if (eno != EEXIST ||
1732 !cli_unlink(targetcli1, targetpath2) ||
1733 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1741 return 0; /* Success */
1746 * A routine to lseek() a file
1749 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1752 fstring server, share, user, password;
1753 pstring path, targetpath;
1754 struct cli_state *targetcli;
1756 if (!context || !context->internal ||
1757 !context->internal->_initialized) {
1764 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1774 return -1; /* Can't lseek a dir ... */
1780 file->offset = offset;
1784 file->offset += offset;
1788 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1789 if (smbc_parse_path(context, file->fname,
1790 server, sizeof(server),
1791 share, sizeof(share),
1794 password, sizeof(password),
1800 /*d_printf(">>>lseek: resolving %s\n", path);*/
1801 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1803 d_printf("Could not resolve %s\n", path);
1806 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1808 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL, &size, NULL, NULL,
1811 SMB_OFF_T b_size = size;
1812 if (!cli_getattrE(targetcli, file->cli_fd, NULL, &b_size, NULL, NULL,
1820 file->offset = size + offset;
1829 return file->offset;
1834 * Generate an inode number from file name for those things that need it
1838 ino_t smbc_inode(SMBCCTX *context, const char *name)
1841 if (!context || !context->internal ||
1842 !context->internal->_initialized) {
1849 if (!*name) return 2; /* FIXME, why 2 ??? */
1850 return (ino_t)str_checksum(name);
1855 * Routine to put basic stat info into a stat structure ... Used by stat and
1860 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname,
1861 SMB_OFF_T size, int mode)
1866 if (IS_DOS_DIR(mode)) {
1867 st->st_mode = SMBC_DIR_MODE;
1869 st->st_mode = SMBC_FILE_MODE;
1872 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1873 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1874 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1875 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1878 #ifdef HAVE_STAT_ST_BLKSIZE
1879 st->st_blksize = 512;
1881 #ifdef HAVE_STAT_ST_BLOCKS
1882 st->st_blocks = (size+511)/512;
1884 st->st_uid = getuid();
1885 st->st_gid = getgid();
1887 if (IS_DOS_DIR(mode)) {
1893 if (st->st_ino == 0) {
1894 st->st_ino = smbc_inode(context, fname);
1897 return True; /* FIXME: Is this needed ? */
1902 * Routine to stat a file given a name
1905 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1908 fstring server, share, user, password, workgroup;
1910 time_t m_time = 0, a_time = 0, c_time = 0;
1915 if (!context || !context->internal ||
1916 !context->internal->_initialized) {
1918 errno = EINVAL; /* Best I can think of ... */
1930 DEBUG(4, ("smbc_stat(%s)\n", fname));
1932 if (smbc_parse_path(context, fname,
1933 server, sizeof(server),
1934 share, sizeof(share),
1937 password, sizeof(password),
1943 if (user[0] == (char)0) fstrcpy(user, context->user);
1945 fstrcpy(workgroup, context->workgroup);
1947 srv = smbc_server(context, server, share, workgroup, user, password);
1950 return -1; /* errno set by smbc_server */
1953 if (!smbc_getatr(context, srv, path, &mode, &size,
1954 &c_time, &a_time, &m_time, &ino)) {
1956 errno = smbc_errno(context, &srv->cli);
1963 smbc_setup_stat(context, st, path, size, mode);
1965 st->st_atime = a_time;
1966 st->st_ctime = c_time;
1967 st->st_mtime = m_time;
1968 st->st_dev = srv->dev;
1975 * Routine to stat a file given an fd
1978 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1980 time_t c_time, a_time, m_time;
1983 fstring server, share, user, password;
1984 pstring path, targetpath;
1985 struct cli_state *targetcli;
1988 if (!context || !context->internal ||
1989 !context->internal->_initialized) {
1996 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2005 return context->fstatdir(context, file, st);
2009 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2010 if (smbc_parse_path(context, file->fname,
2011 server, sizeof(server),
2012 share, sizeof(share),
2015 password, sizeof(password),
2021 /*d_printf(">>>fstat: resolving %s\n", path);*/
2022 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
2024 d_printf("Could not resolve %s\n", path);
2027 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2029 if (!cli_qfileinfo(targetcli, file->cli_fd,
2030 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
2031 if (!cli_getattrE(targetcli, file->cli_fd,
2032 &mode, &size, &c_time, &a_time, &m_time)) {
2041 smbc_setup_stat(context, st, file->fname, size, mode);
2043 st->st_atime = a_time;
2044 st->st_ctime = c_time;
2045 st->st_mtime = m_time;
2046 st->st_dev = file->srv->dev;
2053 * Routine to open a directory
2054 * We accept the URL syntax explained in smbc_parse_path(), above.
2057 static void smbc_remove_dir(SMBCFILE *dir)
2059 struct smbc_dir_list *d,*f;
2066 SAFE_FREE(f->dirent);
2071 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2075 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
2077 struct smbc_dirent *dirent;
2079 int name_length = (name == NULL ? 0 : strlen(name));
2080 int comment_len = (comment == NULL ? 0 : strlen(comment));
2083 * Allocate space for the dirent, which must be increased by the
2084 * size of the name and the comment and 1 each for the null terminator.
2087 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2089 dirent = SMB_MALLOC(size);
2093 dir->dir_error = ENOMEM;
2098 ZERO_STRUCTP(dirent);
2100 if (dir->dir_list == NULL) {
2102 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2103 if (!dir->dir_list) {
2106 dir->dir_error = ENOMEM;
2110 ZERO_STRUCTP(dir->dir_list);
2112 dir->dir_end = dir->dir_next = dir->dir_list;
2116 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2118 if (!dir->dir_end->next) {
2121 dir->dir_error = ENOMEM;
2125 ZERO_STRUCTP(dir->dir_end->next);
2127 dir->dir_end = dir->dir_end->next;
2130 dir->dir_end->next = NULL;
2131 dir->dir_end->dirent = dirent;
2133 dirent->smbc_type = type;
2134 dirent->namelen = name_length;
2135 dirent->commentlen = comment_len;
2136 dirent->dirlen = size;
2138 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2140 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2141 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2148 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
2150 SMBCFILE *dir = (SMBCFILE *)state;
2151 struct smbc_dir_list *dir_list;
2152 struct smbc_dirent *dirent;
2156 dirent_type = dir->dir_type;
2158 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2160 /* An error occurred, what do we do? */
2161 /* FIXME: Add some code here */
2164 /* Point to the one just added */
2165 dirent = dir->dir_end->dirent;
2167 /* See if this was a duplicate */
2168 for (dir_list = dir->dir_list;
2169 dir_list != dir->dir_end;
2170 dir_list = dir_list->next) {
2172 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2173 /* Duplicate. End end of list need to be removed. */
2177 if (do_remove && dir_list->next == dir->dir_end) {
2178 /* Found the end of the list. Remove it. */
2179 dir->dir_end = dir_list;
2180 free(dir_list->next);
2182 dir_list->next = NULL;
2189 list_fn(const char *name, uint32 type, const char *comment, void *state)
2191 SMBCFILE *dir = (SMBCFILE *)state;
2194 /* We need to process the type a little ... */
2196 if (dir->dir_type == SMBC_FILE_SHARE) {
2199 case 0: /* Directory tree */
2200 dirent_type = SMBC_FILE_SHARE;
2204 dirent_type = SMBC_PRINTER_SHARE;
2208 dirent_type = SMBC_COMMS_SHARE;
2212 dirent_type = SMBC_IPC_SHARE;
2216 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2220 else dirent_type = dir->dir_type;
2222 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2224 /* An error occurred, what do we do? */
2225 /* FIXME: Add some code here */
2231 dir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2234 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2235 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2237 /* Handle an error ... */
2239 /* FIXME: Add some code ... */
2246 net_share_enum_rpc(struct cli_state *cli,
2247 void (*fn)(const char *name,
2249 const char *comment,
2257 uint32 info_level = 1;
2258 uint32 preferred_len = 0xffffffff;
2259 SRV_SHARE_INFO_CTR ctr;
2261 fstring comment = "";
2263 struct rpc_pipe_client *pipe_hnd;
2265 /* Open the server service pipe */
2266 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2268 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2272 /* Allocate a context for parsing and for the entries in "ctr" */
2273 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2274 if (mem_ctx == NULL) {
2275 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2279 /* Issue the NetShareEnum RPC call and retrieve the response */
2280 init_enum_hnd(&enum_hnd, 0);
2281 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2288 /* Was it successful? */
2289 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2290 /* Nope. Go clean up. */
2294 /* For each returned entry... */
2295 for (i = 0; i < ctr.num_entries; i++) {
2297 /* pull out the share name */
2298 rpcstr_pull_unistr2_fstring(
2299 name, &ctr.share.info1[i].info_1_str.uni_netname);
2301 /* pull out the share's comment */
2302 rpcstr_pull_unistr2_fstring(
2303 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2305 /* Add this share to the list */
2306 (*fn)(name, SMBC_FILE_SHARE, comment, state);
2309 /* We're done with the pipe */
2310 cli_rpc_pipe_close(pipe_hnd);
2313 /* Free all memory which was allocated for this request */
2314 talloc_free(mem_ctx);
2316 /* Tell 'em if it worked */
2317 return W_ERROR_IS_OK(result) ? 0 : -1;
2322 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
2324 fstring server, share, user, password, options;
2329 SMBCSRV *srv = NULL;
2330 SMBCFILE *dir = NULL;
2331 struct in_addr rem_ip;
2333 if (!context || !context->internal ||
2334 !context->internal->_initialized) {
2335 DEBUG(4, ("no valid context\n"));
2336 errno = EINVAL + 8192;
2342 DEBUG(4, ("no valid fname\n"));
2343 errno = EINVAL + 8193;
2347 if (smbc_parse_path(context, fname,
2348 server, sizeof(server),
2349 share, sizeof(share),
2352 password, sizeof(password),
2353 options, sizeof(options))) {
2354 DEBUG(4, ("no valid path\n"));
2355 errno = EINVAL + 8194;
2359 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
2361 /* Ensure the options are valid */
2362 if (smbc_check_options(server, share, path, options)) {
2363 DEBUG(4, ("unacceptable options (%s)\n", options));
2364 errno = EINVAL + 8195;
2368 if (user[0] == (char)0) fstrcpy(user, context->user);
2370 pstrcpy(workgroup, context->workgroup);
2372 dir = SMB_MALLOC_P(SMBCFILE);
2384 dir->fname = SMB_STRDUP(fname);
2388 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2390 if (server[0] == (char)0) {
2395 struct ip_service *ip_list;
2396 struct ip_service server_addr;
2397 struct user_auth_info u_info;
2398 struct cli_state *cli;
2400 if (share[0] != (char)0 || path[0] != (char)0) {
2402 errno = EINVAL + 8196;
2404 SAFE_FREE(dir->fname);
2410 /* Determine how many local master browsers to query */
2411 max_lmb_count = (context->options.browse_max_lmb_count == 0
2413 : context->options.browse_max_lmb_count);
2415 pstrcpy(u_info.username, user);
2416 pstrcpy(u_info.password, password);
2419 * We have server and share and path empty but options
2420 * requesting that we scan all master browsers for their list
2421 * of workgroups/domains. This implies that we must first try
2422 * broadcast queries to find all master browsers, and if that
2423 * doesn't work, then try our other methods which return only
2424 * a single master browser.
2428 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2432 if (!find_master_ip(workgroup, &server_addr.ip)) {
2438 ip_list = &server_addr;
2442 for (i = 0; i < count && i < max_lmb_count; i++) {
2443 DEBUG(99, ("Found master browser %d of %d: %s\n", i+1, MAX(count, max_lmb_count), inet_ntoa(ip_list[i].ip)));
2445 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2446 /* cli == NULL is the master browser refused to talk or
2447 could not be found */
2451 fstrcpy(server, cli->desthost);
2454 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2457 * For each returned master browser IP address, get a
2458 * connection to IPC$ on the server if we do not
2459 * already have one, and determine the
2460 * workgroups/domains that it knows about.
2463 srv = smbc_server(context, server,
2464 "IPC$", workgroup, user, password);
2470 dir->dir_type = SMBC_WORKGROUP;
2472 /* Now, list the stuff ... */
2474 if (!cli_NetServerEnum(&srv->cli,
2476 SV_TYPE_DOMAIN_ENUM,
2480 SAFE_FREE(dir->fname);
2491 * Server not an empty string ... Check the rest and see what
2494 if (share[0] == (char)0) {
2496 if (path[0] != (char)0) { /* Should not have empty share with path */
2498 errno = EINVAL + 8197;
2500 SAFE_FREE(dir->fname);
2507 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2508 /* However, we check to see if <server> is an IP address first */
2510 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2511 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2512 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2515 dir->dir_type = SMBC_SERVER;
2518 * Get the backup list ...
2522 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2524 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2525 errno = EPERM; /* FIXME, is this correct */
2531 * Get a connection to IPC$ on the server if we do not already have one
2534 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2537 DEBUG(0, ("got no contact to IPC$\n"));
2539 SAFE_FREE(dir->fname);
2548 /* Now, list the servers ... */
2550 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2554 SAFE_FREE(dir->fname);
2563 if (resolve_name(server, &rem_ip, 0x20)) {
2565 /* Now, list the shares ... */
2567 dir->dir_type = SMBC_FILE_SHARE;
2569 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2574 SAFE_FREE(dir->fname);
2583 /* Now, list the servers ... */
2585 if (net_share_enum_rpc(
2588 (void *) dir) < 0 &&
2594 errno = cli_errno(&srv->cli);
2596 SAFE_FREE(dir->fname);
2606 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2608 SAFE_FREE(dir->fname);
2618 else { /* The server and share are specified ... work from there ... */
2620 struct cli_state *targetcli;
2622 /* Well, we connect to the server and list the directory */
2624 dir->dir_type = SMBC_FILE_SHARE;
2626 srv = smbc_server(context, server, share, workgroup, user, password);
2631 SAFE_FREE(dir->fname);
2640 /* Now, list the files ... */
2642 p = path + strlen(path);
2643 pstrcat(path, "\\*");
2645 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2647 d_printf("Could not resolve %s\n", path);
2651 if (cli_list(targetcli, targetpath, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2655 SAFE_FREE(dir->fname);
2658 errno = smbc_errno(context, targetcli);
2660 if (errno == EINVAL) {
2662 * See if they asked to opendir something
2663 * other than a directory. If so, the
2664 * converted error value we got would have
2665 * been EINVAL rather than ENOTDIR.
2667 *p = '\0'; /* restore original path */
2669 if (smbc_getatr(context, srv, path,
2673 ! IS_DOS_DIR(mode)) {
2675 /* It is. Correct the error value */
2687 DLIST_ADD(context->internal->_files, dir);
2693 * Routine to close a directory
2696 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2699 if (!context || !context->internal ||
2700 !context->internal->_initialized) {
2707 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2714 smbc_remove_dir(dir); /* Clean it up */
2716 DLIST_REMOVE(context->internal->_files, dir);
2720 SAFE_FREE(dir->fname);
2721 SAFE_FREE(dir); /* Free the space too */
2728 static void smbc_readdir_internal(SMBCCTX * context,
2729 struct smbc_dirent *dest,
2730 struct smbc_dirent *src,
2731 int max_namebuf_len)
2733 if (context->options.urlencode_readdir_entries) {
2735 /* url-encode the name. get back remaining buffer space */
2737 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2739 /* We now know the name length */
2740 dest->namelen = strlen(dest->name);
2742 /* Save the pointer to the beginning of the comment */
2743 dest->comment = dest->name + dest->namelen + 1;
2745 /* Copy the comment */
2746 strncpy(dest->comment, src->comment, max_namebuf_len);
2748 /* Ensure the comment is null terminated */
2749 if (max_namebuf_len > src->commentlen) {
2750 dest->comment[src->commentlen] = '\0';
2752 dest->comment[max_namebuf_len - 1] = '\0';
2755 /* Save other fields */
2756 dest->smbc_type = src->smbc_type;
2757 dest->commentlen = strlen(dest->comment);
2758 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2762 /* No encoding. Just copy the entry as is. */
2763 memcpy(dest, src, src->dirlen);
2764 dest->comment = (char *)(&dest->name + src->namelen + 1);
2770 * Routine to get a directory entry
2773 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2776 struct smbc_dirent *dirp, *dirent;
2778 /* Check that all is ok first ... */
2780 if (!context || !context->internal ||
2781 !context->internal->_initialized) {
2784 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2789 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2792 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2797 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2800 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2805 if (!dir->dir_next) {
2809 dirent = dir->dir_next->dirent;
2817 dirp = (struct smbc_dirent *)context->internal->_dirent;
2818 maxlen = (sizeof(context->internal->_dirent) -
2819 sizeof(struct smbc_dirent));
2821 smbc_readdir_internal(context, dirp, dirent, maxlen);
2823 dir->dir_next = dir->dir_next->next;
2829 * Routine to get directory entries
2832 static int smbc_getdents_ctx(SMBCCTX *context,
2834 struct smbc_dirent *dirp,
2840 char *ndir = (char *)dirp;
2841 struct smbc_dir_list *dirlist;
2843 /* Check that all is ok first ... */
2845 if (!context || !context->internal ||
2846 !context->internal->_initialized) {
2853 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2860 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2868 * Now, retrieve the number of entries that will fit in what was passed
2869 * We have to figure out if the info is in the list, or we need to
2870 * send a request to the server to get the info.
2873 while ((dirlist = dir->dir_next)) {
2874 struct smbc_dirent *dirent;
2876 if (!dirlist->dirent) {
2878 errno = ENOENT; /* Bad error */
2883 /* Do urlencoding of next entry, if so selected */
2884 dirent = (struct smbc_dirent *)context->internal->_dirent;
2885 maxlen = (sizeof(context->internal->_dirent) -
2886 sizeof(struct smbc_dirent));
2887 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
2889 reqd = dirent->dirlen;
2893 if (rem < count) { /* We managed to copy something */
2899 else { /* Nothing copied ... */
2901 errno = EINVAL; /* Not enough space ... */
2908 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2910 ((struct smbc_dirent *)ndir)->comment =
2911 (char *)(&((struct smbc_dirent *)ndir)->name +
2919 dir->dir_next = dirlist = dirlist -> next;
2930 * Routine to create a directory ...
2933 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2936 fstring server, share, user, password, workgroup;
2937 pstring path, targetpath;
2938 struct cli_state *targetcli;
2940 if (!context || !context->internal ||
2941 !context->internal->_initialized) {
2955 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2957 if (smbc_parse_path(context, fname,
2958 server, sizeof(server),
2959 share, sizeof(share),
2962 password, sizeof(password),
2968 if (user[0] == (char)0) fstrcpy(user, context->user);
2970 fstrcpy(workgroup, context->workgroup);
2972 srv = smbc_server(context, server, share, workgroup, user, password);
2976 return -1; /* errno set by smbc_server */
2980 /*d_printf(">>>mkdir: resolving %s\n", path);*/
2981 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2983 d_printf("Could not resolve %s\n", path);
2986 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
2988 if (!cli_mkdir(targetcli, targetpath)) {
2990 errno = smbc_errno(context, targetcli);
3000 * Our list function simply checks to see if a directory is not empty
3003 static int smbc_rmdir_dirempty = True;
3005 static void rmdir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
3008 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
3009 smbc_rmdir_dirempty = False;
3014 * Routine to remove a directory
3017 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
3020 fstring server, share, user, password, workgroup;
3021 pstring path, targetpath;
3022 struct cli_state *targetcli;
3024 if (!context || !context->internal ||
3025 !context->internal->_initialized) {
3039 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3041 if (smbc_parse_path(context, fname,
3042 server, sizeof(server),
3043 share, sizeof(share),
3046 password, sizeof(password),
3053 if (user[0] == (char)0) fstrcpy(user, context->user);
3055 fstrcpy(workgroup, context->workgroup);
3057 srv = smbc_server(context, server, share, workgroup, user, password);
3061 return -1; /* errno set by smbc_server */
3065 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
3067 mode = aDIR | aRONLY;
3070 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
3072 if (strcmp(path, "\\") == 0) {
3074 mode = aDIR | aRONLY;
3080 smbc_stat_printjob(srv, path, &size, &m_time);
3081 c_time = a_time = m_time;
3086 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3087 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3089 d_printf("Could not resolve %s\n", path);
3092 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3095 if (!cli_rmdir(targetcli, targetpath)) {
3097 errno = smbc_errno(context, targetcli);
3099 if (errno == EACCES) { /* Check if the dir empty or not */
3101 pstring lpath; /* Local storage to avoid buffer overflows */
3103 smbc_rmdir_dirempty = True; /* Make this so ... */
3105 pstrcpy(lpath, targetpath);
3106 pstrcat(lpath, "\\*");
3108 if (cli_list(targetcli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
3111 /* Fix errno to ignore latest error ... */
3113 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
3114 smbc_errno(context, targetcli)));
3119 if (smbc_rmdir_dirempty)
3135 * Routine to return the current directory position
3138 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
3140 off_t ret_val; /* Squash warnings about cast */
3142 if (!context || !context->internal ||
3143 !context->internal->_initialized) {
3150 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3157 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3165 * We return the pointer here as the offset
3167 ret_val = (off_t)(long)dir->dir_next;
3173 * A routine to run down the list and see if the entry is OK
3176 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
3177 struct smbc_dirent *dirent)
3180 /* Run down the list looking for what we want */
3184 struct smbc_dir_list *tmp = list;
3188 if (tmp->dirent == dirent)
3197 return NULL; /* Not found, or an error */
3203 * Routine to seek on a directory
3206 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
3208 long int l_offset = offset; /* Handle problems of size */
3209 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3210 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3212 if (!context || !context->internal ||
3213 !context->internal->_initialized) {
3220 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3227 /* Now, check what we were passed and see if it is OK ... */
3229 if (dirent == NULL) { /* Seek to the begining of the list */
3231 dir->dir_next = dir->dir_list;
3236 /* Now, run down the list and make sure that the entry is OK */
3237 /* This may need to be changed if we change the format of the list */
3239 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3241 errno = EINVAL; /* Bad entry */
3246 dir->dir_next = list_ent;
3253 * Routine to fstat a dir
3256 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
3259 if (!context || !context->internal ||
3260 !context->internal->_initialized) {
3267 /* No code yet ... */
3273 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
3276 fstring server, share, user, password, workgroup;
3280 if (!context || !context->internal ||
3281 !context->internal->_initialized) {
3283 errno = EINVAL; /* Best I can think of ... */
3295 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3297 if (smbc_parse_path(context, fname,
3298 server, sizeof(server),
3299 share, sizeof(share),
3302 password, sizeof(password),
3308 if (user[0] == (char)0) fstrcpy(user, context->user);
3310 fstrcpy(workgroup, context->workgroup);
3312 srv = smbc_server(context, server, share, workgroup, user, password);
3315 return -1; /* errno set by smbc_server */
3320 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3321 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3322 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3323 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3325 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3326 errno = smbc_errno(context, &srv->cli);
3333 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
3336 fstring server, share, user, password, workgroup;
3341 if (!context || !context->internal ||
3342 !context->internal->_initialized) {
3344 errno = EINVAL; /* Best I can think of ... */
3357 a_time = m_time = time(NULL);
3359 a_time = tbuf[0].tv_sec;
3360 m_time = tbuf[1].tv_sec;
3369 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf));
3370 atimebuf[sizeof(atimebuf) - 1] = '\0';
3371 if ((p = strchr(atimebuf, '\n')) != NULL) {
3375 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf));
3376 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3377 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3381 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3382 fname, atimebuf, mtimebuf);
3385 if (smbc_parse_path(context, fname,
3386 server, sizeof(server),
3387 share, sizeof(share),
3390 password, sizeof(password),
3396 if (user[0] == (char)0) fstrcpy(user, context->user);
3398 fstrcpy(workgroup, context->workgroup);
3400 srv = smbc_server(context, server, share, workgroup, user, password);
3403 return -1; /* errno set by smbc_server */
3406 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3407 return -1; /* errno set by smbc_setatr */
3414 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3415 However NT4 gives a "The information may have been modified by a
3416 computer running Windows NT 5.0" if denied ACEs do not appear before
3419 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
3421 if (sec_ace_equal(ace1, ace2))
3424 if (ace1->type != ace2->type)
3425 return ace2->type - ace1->type;
3427 if (sid_compare(&ace1->trustee, &ace2->trustee))
3428 return sid_compare(&ace1->trustee, &ace2->trustee);
3430 if (ace1->flags != ace2->flags)
3431 return ace1->flags - ace2->flags;
3433 if (ace1->info.mask != ace2->info.mask)
3434 return ace1->info.mask - ace2->info.mask;
3436 if (ace1->size != ace2->size)
3437 return ace1->size - ace2->size;
3439 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3443 static void sort_acl(SEC_ACL *the_acl)
3446 if (!the_acl) return;
3448 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
3450 for (i=1;i<the_acl->num_aces;) {
3451 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3453 for (j=i; j<the_acl->num_aces-1; j++) {
3454 the_acl->ace[j] = the_acl->ace[j+1];
3456 the_acl->num_aces--;
3463 /* convert a SID to a string, either numeric or username/group */
3464 static void convert_sid_to_string(struct cli_state *ipc_cli,
3470 char **domains = NULL;
3471 char **names = NULL;
3472 uint32 *types = NULL;
3473 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3474 sid_to_string(str, sid);
3477 return; /* no lookup desired */
3484 /* Ask LSA to convert the sid to a name */
3486 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3487 pol, 1, sid, &domains,
3489 !domains || !domains[0] || !names || !names[0]) {
3495 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3496 domains[0], lp_winbind_separator(),
3500 /* convert a string to a SID, either numeric or username/group */
3501 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
3507 uint32 *types = NULL;
3508 DOM_SID *sids = NULL;
3510 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3517 if (strncmp(str, "S-", 2) == 0) {
3518 return string_to_sid(sid, str);
3525 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3526 pol, 1, &str, &sids,
3532 sid_copy(sid, &sids[0]);
3539 /* parse an ACE in the same format as print_ace() */
3540 static BOOL parse_ace(struct cli_state *ipc_cli,
3549 unsigned atype, aflags, amask;
3552 const struct perm_value *v;
3558 /* These values discovered by inspection */
3559 static const struct perm_value special_values[] = {
3560 { "R", 0x00120089 },
3561 { "W", 0x00120116 },
3562 { "X", 0x001200a0 },
3563 { "D", 0x00010000 },
3564 { "P", 0x00040000 },
3565 { "O", 0x00080000 },
3569 static const struct perm_value standard_values[] = {
3570 { "READ", 0x001200a9 },
3571 { "CHANGE", 0x001301bf },
3572 { "FULL", 0x001f01ff },
3578 p = strchr_m(str,':');
3579 if (!p) return False;
3582 /* Try to parse numeric form */
3584 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3585 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3589 /* Try to parse text form */
3591 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3596 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3600 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3601 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3602 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3603 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3608 /* Only numeric form accepted for flags at present */
3610 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3611 sscanf(tok, "%i", &aflags))) {
3615 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3619 if (strncmp(tok, "0x", 2) == 0) {
3620 if (sscanf(tok, "%i", &amask) != 1) {
3626 for (v = standard_values; v->perm; v++) {
3627 if (strcmp(tok, v->perm) == 0) {
3638 for (v = special_values; v->perm; v++) {
3639 if (v->perm[0] == *p) {
3645 if (!found) return False;
3655 init_sec_ace(ace, &sid, atype, mask, aflags);
3659 /* add an ACE to a list of ACEs in a SEC_ACL */
3660 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3665 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3669 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3670 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3671 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3672 newacl = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3674 (*the_acl) = newacl;
3679 /* parse a ascii version of a security descriptor */
3680 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3681 struct cli_state *ipc_cli,
3686 const char *p = str;
3690 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3694 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3696 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3697 revision = strtol(tok+9, NULL, 16);
3701 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3702 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3704 !convert_string_to_sid(ipc_cli, pol,
3706 owner_sid, tok+6)) {
3707 DEBUG(5, ("Failed to parse owner sid\n"));
3713 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3714 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3716 !convert_string_to_sid(ipc_cli, pol,
3718 owner_sid, tok+7)) {
3719 DEBUG(5, ("Failed to parse owner sid\n"));
3725 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3726 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3728 !convert_string_to_sid(ipc_cli, pol,
3731 DEBUG(5, ("Failed to parse group sid\n"));
3737 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3738 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3740 !convert_string_to_sid(ipc_cli, pol,
3743 DEBUG(5, ("Failed to parse group sid\n"));
3749 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3751 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3752 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3755 if(!add_ace(&dacl, &ace, ctx)) {
3756 DEBUG(5, ("Failed to add ACL %s\n", tok));
3762 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3764 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3765 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3768 if(!add_ace(&dacl, &ace, ctx)) {
3769 DEBUG(5, ("Failed to add ACL %s\n", tok));
3775 DEBUG(5, ("Failed to parse security descriptor\n"));
3779 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3780 owner_sid, grp_sid, NULL, dacl, &sd_size);
3783 SAFE_FREE(owner_sid);
3789 /* Obtain the current dos attributes */
3790 static DOS_ATTR_DESC *dos_attr_query(SMBCCTX *context,
3792 const char *filename,
3795 time_t m_time = 0, a_time = 0, c_time = 0;
3798 SMB_INO_T inode = 0;
3801 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
3807 /* Obtain the DOS attributes */
3808 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
3810 &c_time, &a_time, &m_time, &inode)) {
3812 errno = smbc_errno(context, &srv->cli);
3813 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
3820 ret->a_time = a_time;
3821 ret->c_time = c_time;
3822 ret->m_time = m_time;
3829 /* parse a ascii version of a security descriptor */
3830 static void dos_attr_parse(SMBCCTX *context,
3835 const char *p = str;
3838 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3840 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
3841 dad->mode = strtol(tok+5, NULL, 16);
3845 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
3846 dad->size = (SMB_OFF_T)atof(tok+5);
3850 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
3851 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
3855 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
3856 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
3860 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
3861 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
3865 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
3866 dad->inode = (SMB_INO_T)atof(tok+6);
3872 /*****************************************************
3873 Retrieve the acls for a file.
3874 *******************************************************/
3876 static int cacl_get(SMBCCTX *context, TALLOC_CTX *ctx, SMBCSRV *srv,
3877 struct cli_state *ipc_cli, POLICY_HND *pol,
3878 char *filename, char *attr_name, char *buf, int bufsize)
3889 BOOL exclude_nt_revision = False;
3890 BOOL exclude_nt_owner = False;
3891 BOOL exclude_nt_group = False;
3892 BOOL exclude_nt_acl = False;
3893 BOOL exclude_dos_mode = False;
3894 BOOL exclude_dos_size = False;
3895 BOOL exclude_dos_ctime = False;
3896 BOOL exclude_dos_atime = False;
3897 BOOL exclude_dos_mtime = False;
3898 BOOL exclude_dos_inode = False;
3899 BOOL numeric = True;
3900 BOOL determine_size = (bufsize == 0);
3904 fstring name_sandbox;
3908 time_t m_time = 0, a_time = 0, c_time = 0;
3912 struct cli_state *cli = &srv->cli;
3914 /* Copy name so we can strip off exclusions (if any are specified) */
3915 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
3917 /* Ensure name is null terminated */
3918 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
3920 /* Play in the sandbox */
3921 name = name_sandbox;
3923 /* If there are any exclusions, point to them and mask them from name */
3924 if ((pExclude = strchr(name, '!')) != NULL)
3929 all = (StrnCaseCmp(name, "system.*", 8) == 0);
3930 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
3931 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
3932 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
3933 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
3934 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
3935 numeric = (* (name + strlen(name) - 1) != '+');
3937 /* Look for exclusions from "all" requests */
3938 if (all || all_nt || all_dos) {
3940 /* Exclusions are delimited by '!' */
3941 for (; pExclude != NULL; pExclude = (p == NULL ? NULL : p + 1)) {
3943 /* Find end of this exclusion name */
3944 if ((p = strchr(pExclude, '!')) != NULL)
3949 /* Which exclusion name is this? */
3950 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
3951 exclude_nt_revision = True;
3953 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
3954 exclude_nt_owner = True;
3956 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
3957 exclude_nt_group = True;
3959 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
3960 exclude_nt_acl = True;
3962 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
3963 exclude_dos_mode = True;
3965 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
3966 exclude_dos_size = True;
3968 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
3969 exclude_dos_ctime = True;
3971 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
3972 exclude_dos_atime = True;
3974 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
3975 exclude_dos_mtime = True;
3977 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
3978 exclude_dos_inode = True;
3981 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
3992 * If we are (possibly) talking to an NT or new system and some NT
3993 * attributes have been requested...
3995 if (ipc_cli && (all || some_nt || all_nt_acls)) {
3996 /* Point to the portion after "system.nt_sec_desc." */
3997 name += 19; /* if (all) this will be invalid but unused */
3999 /* ... then obtain any NT attributes which were requested */
4000 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4003 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4004 filename, cli_errstr(cli)));
4009 sd = cli_query_secdesc(cli, fnum, ctx);
4013 ("cacl_get Failed to query old descriptor\n"));
4018 cli_close(cli, fnum);
4020 if (! exclude_nt_revision) {
4021 if (all || all_nt) {
4022 if (determine_size) {
4023 p = talloc_asprintf(ctx,
4032 n = snprintf(buf, bufsize,
4033 "REVISION:%d", sd->revision);
4035 } else if (StrCaseCmp(name, "revision") == 0) {
4036 if (determine_size) {
4037 p = talloc_asprintf(ctx, "%d",
4045 n = snprintf(buf, bufsize, "%d",
4050 if (!determine_size && n > bufsize) {
4059 if (! exclude_nt_owner) {
4060 /* Get owner and group sid */
4061 if (sd->owner_sid) {
4062 convert_sid_to_string(ipc_cli, pol,
4067 fstrcpy(sidstr, "");
4070 if (all || all_nt) {
4071 if (determine_size) {
4072 p = talloc_asprintf(ctx, ",OWNER:%s",
4080 n = snprintf(buf, bufsize,
4081 ",OWNER:%s", sidstr);
4083 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4084 if (determine_size) {
4085 p = talloc_asprintf(ctx, "%s", sidstr);
4092 n = snprintf(buf, bufsize, "%s",
4097 if (!determine_size && n > bufsize) {
4106 if (! exclude_nt_group) {
4108 convert_sid_to_string(ipc_cli, pol,
4112 fstrcpy(sidstr, "");
4115 if (all || all_nt) {
4116 if (determine_size) {
4117 p = talloc_asprintf(ctx, ",GROUP:%s",
4125 n = snprintf(buf, bufsize,
4126 ",GROUP:%s", sidstr);
4128 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4129 if (determine_size) {
4130 p = talloc_asprintf(ctx, "%s", sidstr);
4137 n = snprintf(buf, bufsize, "%s", sidstr);
4141 if (!determine_size && n > bufsize) {
4150 if (! exclude_nt_acl) {
4151 /* Add aces to value buffer */
4152 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4154 SEC_ACE *ace = &sd->dacl->ace[i];
4155 convert_sid_to_string(ipc_cli, pol,
4159 if (all || all_nt) {
4160 if (determine_size) {
4161 p = talloc_asprintf(
4177 ",ACL:%s:%d/%d/0x%08x",
4183 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4184 StrCaseCmp(name + 3, sidstr) == 0) ||
4185 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4186 StrCaseCmp(name + 4, sidstr) == 0)) {
4187 if (determine_size) {
4188 p = talloc_asprintf(
4200 n = snprintf(buf, bufsize,
4206 } else if (all_nt_acls) {
4207 if (determine_size) {
4208 p = talloc_asprintf(
4210 "%s%s:%d/%d/0x%08x",
4222 n = snprintf(buf, bufsize,
4223 "%s%s:%d/%d/0x%08x",
4241 /* Restore name pointer to its original value */
4245 if (all || some_dos) {
4246 /* Point to the portion after "system.dos_attr." */
4247 name += 16; /* if (all) this will be invalid but unused */
4249 /* Obtain the DOS attributes */
4250 if (!smbc_getatr(context, srv, filename, &mode, &size,
4251 &c_time, &a_time, &m_time, &ino)) {
4253 errno = smbc_errno(context, &srv->cli);
4258 if (! exclude_dos_mode) {
4259 if (all || all_dos) {
4260 if (determine_size) {
4261 p = talloc_asprintf(ctx,
4274 n = snprintf(buf, bufsize,
4282 } else if (StrCaseCmp(name, "mode") == 0) {
4283 if (determine_size) {
4284 p = talloc_asprintf(ctx, "0x%x", mode);
4291 n = snprintf(buf, bufsize, "0x%x", mode);
4295 if (!determine_size && n > bufsize) {
4304 if (! exclude_dos_size) {
4305 if (all || all_dos) {
4306 if (determine_size) {
4307 p = talloc_asprintf(
4317 n = snprintf(buf, bufsize,
4321 } else if (StrCaseCmp(name, "size") == 0) {
4322 if (determine_size) {
4323 p = talloc_asprintf(
4333 n = snprintf(buf, bufsize,
4339 if (!determine_size && n > bufsize) {
4348 if (! exclude_dos_ctime) {
4349 if (all || all_dos) {
4350 if (determine_size) {
4351 p = talloc_asprintf(ctx,
4360 n = snprintf(buf, bufsize,
4361 ",C_TIME:%lu", c_time);
4363 } else if (StrCaseCmp(name, "c_time") == 0) {
4364 if (determine_size) {
4365 p = talloc_asprintf(ctx, "%lu", c_time);
4372 n = snprintf(buf, bufsize, "%lu", c_time);
4376 if (!determine_size && n > bufsize) {
4385 if (! exclude_dos_atime) {
4386 if (all || all_dos) {
4387 if (determine_size) {
4388 p = talloc_asprintf(ctx,
4397 n = snprintf(buf, bufsize,
4398 ",A_TIME:%lu", a_time);
4400 } else if (StrCaseCmp(name, "a_time") == 0) {
4401 if (determine_size) {
4402 p = talloc_asprintf(ctx, "%lu", a_time);
4409 n = snprintf(buf, bufsize, "%lu", a_time);
4413 if (!determine_size && n > bufsize) {
4422 if (! exclude_dos_mtime) {
4423 if (all || all_dos) {
4424 if (determine_size) {
4425 p = talloc_asprintf(ctx,
4434 n = snprintf(buf, bufsize,
4435 ",M_TIME:%lu", m_time);
4437 } else if (StrCaseCmp(name, "m_time") == 0) {
4438 if (determine_size) {
4439 p = talloc_asprintf(ctx, "%lu", m_time);
4446 n = snprintf(buf, bufsize, "%lu", m_time);
4450 if (!determine_size && n > bufsize) {
4459 if (! exclude_dos_inode) {
4460 if (all || all_dos) {
4461 if (determine_size) {
4462 p = talloc_asprintf(
4472 n = snprintf(buf, bufsize,
4476 } else if (StrCaseCmp(name, "inode") == 0) {
4477 if (determine_size) {
4478 p = talloc_asprintf(
4488 n = snprintf(buf, bufsize,
4494 if (!determine_size && n > bufsize) {
4503 /* Restore name pointer to its original value */
4516 /*****************************************************
4517 set the ACLs on a file given an ascii description
4518 *******************************************************/
4519 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
4520 struct cli_state *ipc_cli, POLICY_HND *pol,
4521 const char *filename, const char *the_acl,
4522 int mode, int flags)
4526 SEC_DESC *sd = NULL, *old;
4527 SEC_ACL *dacl = NULL;
4528 DOM_SID *owner_sid = NULL;
4529 DOM_SID *grp_sid = NULL;
4534 BOOL numeric = True;
4536 /* the_acl will be null for REMOVE_ALL operations */
4538 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4542 /* if this is to set the entire ACL... */
4543 if (*the_acl == '*') {
4544 /* ... then increment past the first colon */
4548 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4549 CONST_DISCARD(char *, the_acl));
4557 /* The desired access below is the only one I could find that works
4558 with NT4, W2KP and Samba */
4560 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4563 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4564 filename, cli_errstr(cli)));
4569 old = cli_query_secdesc(cli, fnum, ctx);
4572 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4577 cli_close(cli, fnum);
4580 case SMBC_XATTR_MODE_REMOVE_ALL:
4581 old->dacl->num_aces = 0;
4582 SAFE_FREE(old->dacl->ace);
4583 SAFE_FREE(old->dacl);
4588 case SMBC_XATTR_MODE_REMOVE:
4589 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4592 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4593 if (sec_ace_equal(&sd->dacl->ace[i],
4594 &old->dacl->ace[j])) {
4596 for (k=j; k<old->dacl->num_aces-1;k++) {
4597 old->dacl->ace[k] = old->dacl->ace[k+1];
4599 old->dacl->num_aces--;
4600 if (old->dacl->num_aces == 0) {
4601 SAFE_FREE(old->dacl->ace);
4602 SAFE_FREE(old->dacl);
4619 case SMBC_XATTR_MODE_ADD:
4620 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4623 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4624 if (sid_equal(&sd->dacl->ace[i].trustee,
4625 &old->dacl->ace[j].trustee)) {
4626 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4631 old->dacl->ace[j] = sd->dacl->ace[i];
4637 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4643 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4644 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4650 case SMBC_XATTR_MODE_SET:
4652 owner_sid = old->owner_sid;
4653 grp_sid = old->grp_sid;
4657 case SMBC_XATTR_MODE_CHOWN:
4658 owner_sid = sd->owner_sid;
4661 case SMBC_XATTR_MODE_CHGRP:
4662 grp_sid = sd->grp_sid;
4666 /* Denied ACE entries must come before allowed ones */
4667 sort_acl(old->dacl);
4669 /* Create new security descriptor and set it */
4670 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4671 owner_sid, grp_sid, NULL, dacl, &sd_size);
4673 fnum = cli_nt_create(cli, filename,
4674 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4677 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4678 filename, cli_errstr(cli)));
4683 if (!cli_set_secdesc(cli, fnum, sd)) {
4684 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4691 cli_close(cli, fnum);
4701 int smbc_setxattr_ctx(SMBCCTX *context,
4712 fstring server, share, user, password, workgroup;
4718 if (!context || !context->internal ||
4719 !context->internal->_initialized) {
4721 errno = EINVAL; /* Best I can think of ... */
4733 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n", fname, name, (int) size, (const char*)value));
4735 if (smbc_parse_path(context, fname,
4736 server, sizeof(server),
4737 share, sizeof(share),
4740 password, sizeof(password),
4746 if (user[0] == (char)0) fstrcpy(user, context->user);
4748 fstrcpy(workgroup, context->workgroup);
4750 srv = smbc_server(context, server, share, workgroup, user, password);
4752 return -1; /* errno set by smbc_server */
4755 if (! srv->no_nt_session) {
4756 ipc_srv = smbc_attr_server(context, server, share,
4757 workgroup, user, password,
4759 srv->no_nt_session = True;
4764 ctx = talloc_init("smbc_setxattr");
4771 * Are they asking to set the entire set of known attributes?
4773 if (StrCaseCmp(name, "system.*") == 0 ||
4774 StrCaseCmp(name, "system.*+") == 0) {
4777 talloc_asprintf(ctx, "%s:%s", name+7, (const char *) value);
4785 ret = cacl_set(ctx, &srv->cli,
4786 &ipc_srv->cli, &pol, path,
4789 ? SMBC_XATTR_MODE_SET
4790 : SMBC_XATTR_MODE_ADD),
4796 /* get a DOS Attribute Descriptor with current attributes */
4797 dad = dos_attr_query(context, ctx, path, srv);
4799 /* Overwrite old with new, using what was provided */
4800 dos_attr_parse(context, dad, srv, namevalue);
4802 /* Set the new DOS attributes */
4803 if (! smbc_setatr(context, srv, path,
4809 /* cause failure if NT failed too */
4814 /* we only fail if both NT and DOS sets failed */
4815 if (ret < 0 && ! dad) {
4816 ret = -1; /* in case dad was null */
4822 talloc_destroy(ctx);
4827 * Are they asking to set an access control element or to set
4828 * the entire access control list?
4830 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4831 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4832 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4833 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4834 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4838 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4841 ret = -1; /* errno set by smbc_server() */
4843 else if (! namevalue) {
4847 ret = cacl_set(ctx, &srv->cli,
4848 &ipc_srv->cli, &pol, path,
4851 ? SMBC_XATTR_MODE_SET
4852 : SMBC_XATTR_MODE_ADD),
4855 talloc_destroy(ctx);
4860 * Are they asking to set the owner?
4862 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4863 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
4867 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4871 ret = -1; /* errno set by smbc_server() */
4873 else if (! namevalue) {
4877 ret = cacl_set(ctx, &srv->cli,
4878 &ipc_srv->cli, &pol, path,
4879 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4881 talloc_destroy(ctx);
4886 * Are they asking to set the group?
4888 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4889 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
4893 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4896 /* errno set by smbc_server() */
4899 else if (! namevalue) {
4903 ret = cacl_set(ctx, &srv->cli,
4904 &ipc_srv->cli, &pol, path,
4905 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4907 talloc_destroy(ctx);
4912 * Are they asking to set a DOS attribute?
4914 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4915 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4916 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4917 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4918 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
4920 /* get a DOS Attribute Descriptor with current attributes */
4921 dad = dos_attr_query(context, ctx, path, srv);
4924 talloc_asprintf(ctx, "%s:%s", name+16, (const char *) value);
4929 /* Overwrite old with provided new params */
4930 dos_attr_parse(context, dad, srv, namevalue);
4932 /* Set the new DOS attributes */
4933 ret2 = smbc_setatr(context, srv, path,
4939 /* ret2 has True (success) / False (failure) */
4950 talloc_destroy(ctx);
4954 /* Unsupported attribute name */
4955 talloc_destroy(ctx);
4960 int smbc_getxattr_ctx(SMBCCTX *context,
4969 fstring server, share, user, password, workgroup;
4975 if (!context || !context->internal ||
4976 !context->internal->_initialized) {
4978 errno = EINVAL; /* Best I can think of ... */
4990 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
4992 if (smbc_parse_path(context, fname,
4993 server, sizeof(server),
4994 share, sizeof(share),
4997 password, sizeof(password),
5003 if (user[0] == (char)0) fstrcpy(user, context->user);
5005 fstrcpy(workgroup, context->workgroup);
5007 srv = smbc_server(context, server, share, workgroup, user, password);
5009 return -1; /* errno set by smbc_server */
5012 if (! srv->no_nt_session) {
5013 ipc_srv = smbc_attr_server(context, server, share,
5014 workgroup, user, password,
5017 srv->no_nt_session = True;
5023 ctx = talloc_init("smbc:getxattr");
5029 /* Are they requesting a supported attribute? */
5030 if (StrCaseCmp(name, "system.*") == 0 ||
5031 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5032 StrCaseCmp(name, "system.*+") == 0 ||
5033 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5034 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5035 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5036 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5037 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5038 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5039 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5040 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5041 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5042 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5043 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5044 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5045 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5046 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5047 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5048 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5049 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5050 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5051 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
5052 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5055 ret = cacl_get(context, ctx, srv,
5056 ipc_srv == NULL ? NULL : &ipc_srv->cli,
5058 CONST_DISCARD(char *, name),
5059 CONST_DISCARD(char *, value), size);
5060 if (ret < 0 && errno == 0) {
5061 errno = smbc_errno(context, &srv->cli);
5063 talloc_destroy(ctx);
5067 /* Unsupported attribute name */
5068 talloc_destroy(ctx);
5074 int smbc_removexattr_ctx(SMBCCTX *context,
5081 fstring server, share, user, password, workgroup;
5086 if (!context || !context->internal ||
5087 !context->internal->_initialized) {
5089 errno = EINVAL; /* Best I can think of ... */
5101 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5103 if (smbc_parse_path(context, fname,
5104 server, sizeof(server),
5105 share, sizeof(share),
5108 password, sizeof(password),
5114 if (user[0] == (char)0) fstrcpy(user, context->user);
5116 fstrcpy(workgroup, context->workgroup);
5118 srv = smbc_server(context, server, share, workgroup, user, password);
5120 return -1; /* errno set by smbc_server */
5123 if (! srv->no_nt_session) {
5124 ipc_srv = smbc_attr_server(context, server, share,
5125 workgroup, user, password,
5127 srv->no_nt_session = True;
5133 return -1; /* errno set by smbc_attr_server */
5136 ctx = talloc_init("smbc_removexattr");
5142 /* Are they asking to set the entire ACL? */
5143 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5144 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5147 ret = cacl_set(ctx, &srv->cli,
5148 &ipc_srv->cli, &pol, path,
5149 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5150 talloc_destroy(ctx);
5155 * Are they asking to remove one or more spceific security descriptor
5158 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5159 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5160 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5161 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5162 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5163 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5164 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5167 ret = cacl_set(ctx, &srv->cli,
5168 &ipc_srv->cli, &pol, path,
5169 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5170 talloc_destroy(ctx);
5174 /* Unsupported attribute name */
5175 talloc_destroy(ctx);
5180 int smbc_listxattr_ctx(SMBCCTX *context,
5186 * This isn't quite what listxattr() is supposed to do. This returns
5187 * the complete set of attribute names, always, rather than only those
5188 * attribute names which actually exist for a file. Hmmm...
5190 const char supported[] =
5193 "system.nt_sec_desc.revision\0"
5194 "system.nt_sec_desc.owner\0"
5195 "system.nt_sec_desc.owner+\0"
5196 "system.nt_sec_desc.group\0"
5197 "system.nt_sec_desc.group+\0"
5198 "system.nt_sec_desc.acl.*\0"
5199 "system.nt_sec_desc.acl\0"
5200 "system.nt_sec_desc.acl+\0"
5201 "system.nt_sec_desc.*\0"
5202 "system.nt_sec_desc.*+\0"
5203 "system.dos_attr.*\0"
5204 "system.dos_attr.mode\0"
5205 "system.dos_attr.c_time\0"
5206 "system.dos_attr.a_time\0"
5207 "system.dos_attr.m_time\0"
5211 return sizeof(supported);
5214 if (sizeof(supported) > size) {
5219 /* this can't be strcpy() because there are embedded null characters */
5220 memcpy(list, supported, sizeof(supported));
5221 return sizeof(supported);
5226 * Open a print file to be written to by other calls
5229 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
5231 fstring server, share, user, password;
5234 if (!context || !context->internal ||
5235 !context->internal->_initialized) {
5249 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5251 if (smbc_parse_path(context, fname,
5252 server, sizeof(server),
5253 share, sizeof(share),
5256 password, sizeof(password),
5262 /* What if the path is empty, or the file exists? */
5264 return context->open(context, fname, O_WRONLY, 666);
5269 * Routine to print a file on a remote server ...
5271 * We open the file, which we assume to be on a remote server, and then
5272 * copy it to a print file on the share specified by printq.
5275 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
5277 SMBCFILE *fid1, *fid2;
5278 int bytes, saverr, tot_bytes = 0;
5281 if (!c_file || !c_file->internal->_initialized || !c_print ||
5282 !c_print->internal->_initialized) {
5289 if (!fname && !printq) {
5296 /* Try to open the file for reading ... */
5298 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5300 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5301 return -1; /* smbc_open sets errno */
5305 /* Now, try to open the printer file for writing */
5307 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5309 saverr = errno; /* Save errno */
5310 c_file->close_fn(c_file, fid1);
5316 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5320 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5323 c_file->close_fn(c_file, fid1);
5324 c_print->close_fn(c_print, fid2);
5333 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5334 c_print->close_fn(c_print, fid2);
5348 * Routine to list print jobs on a printer share ...
5351 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
5354 fstring server, share, user, password, workgroup;
5357 if (!context || !context->internal ||
5358 !context->internal->_initialized) {
5372 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5374 if (smbc_parse_path(context, fname,
5375 server, sizeof(server),
5376 share, sizeof(share),
5379 password, sizeof(password),
5385 if (user[0] == (char)0) fstrcpy(user, context->user);
5387 fstrcpy(workgroup, context->workgroup);
5389 srv = smbc_server(context, server, share, workgroup, user, password);
5393 return -1; /* errno set by smbc_server */
5397 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
5399 errno = smbc_errno(context, &srv->cli);
5409 * Delete a print job from a remote printer share
5412 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
5415 fstring server, share, user, password, workgroup;
5419 if (!context || !context->internal ||
5420 !context->internal->_initialized) {
5434 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5436 if (smbc_parse_path(context, fname,
5437 server, sizeof(server),
5438 share, sizeof(share),
5441 password, sizeof(password),
5447 if (user[0] == (char)0) fstrcpy(user, context->user);
5449 fstrcpy(workgroup, context->workgroup);
5451 srv = smbc_server(context, server, share, workgroup, user, password);
5455 return -1; /* errno set by smbc_server */
5459 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5462 errno = smbc_errno(context, &srv->cli);
5463 else if (err == ERRnosuchprintjob)
5474 * Get a new empty handle to fill in with your own info
5476 SMBCCTX * smbc_new_context(void)
5480 context = SMB_MALLOC_P(SMBCCTX);
5486 ZERO_STRUCTP(context);
5488 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5489 if (!context->internal) {
5494 ZERO_STRUCTP(context->internal);
5497 /* ADD REASONABLE DEFAULTS */
5499 context->timeout = 20000; /* 20 seconds */
5501 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5502 context->options.urlencode_readdir_entries = False;/* backward compat */
5503 context->options.one_share_per_server = False;/* backward compat */
5505 context->open = smbc_open_ctx;
5506 context->creat = smbc_creat_ctx;
5507 context->read = smbc_read_ctx;
5508 context->write = smbc_write_ctx;
5509 context->close_fn = smbc_close_ctx;
5510 context->unlink = smbc_unlink_ctx;
5511 context->rename = smbc_rename_ctx;
5512 context->lseek = smbc_lseek_ctx;
5513 context->stat = smbc_stat_ctx;
5514 context->fstat = smbc_fstat_ctx;
5515 context->opendir = smbc_opendir_ctx;
5516 context->closedir = smbc_closedir_ctx;
5517 context->readdir = smbc_readdir_ctx;
5518 context->getdents = smbc_getdents_ctx;
5519 context->mkdir = smbc_mkdir_ctx;
5520 context->rmdir = smbc_rmdir_ctx;
5521 context->telldir = smbc_telldir_ctx;
5522 context->lseekdir = smbc_lseekdir_ctx;
5523 context->fstatdir = smbc_fstatdir_ctx;
5524 context->chmod = smbc_chmod_ctx;
5525 context->utimes = smbc_utimes_ctx;
5526 context->setxattr = smbc_setxattr_ctx;
5527 context->getxattr = smbc_getxattr_ctx;
5528 context->removexattr = smbc_removexattr_ctx;
5529 context->listxattr = smbc_listxattr_ctx;
5530 context->open_print_job = smbc_open_print_job_ctx;
5531 context->print_file = smbc_print_file_ctx;
5532 context->list_print_jobs = smbc_list_print_jobs_ctx;
5533 context->unlink_print_job = smbc_unlink_print_job_ctx;
5535 context->callbacks.check_server_fn = smbc_check_server;
5536 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5538 smbc_default_cache_functions(context);
5546 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5547 * and thus you'll be leaking memory if not handled properly.
5550 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
5559 DEBUG(1,("Performing aggressive shutdown.\n"));
5561 f = context->internal->_files;
5563 context->close_fn(context, f);
5566 context->internal->_files = NULL;
5568 /* First try to remove the servers the nice way. */
5569 if (context->callbacks.purge_cached_fn(context)) {
5572 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
5573 s = context->internal->_servers;
5575 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
5576 cli_shutdown(&s->cli);
5577 context->callbacks.remove_cached_srv_fn(context, s);
5579 DLIST_REMOVE(context->internal->_servers, s);
5583 context->internal->_servers = NULL;
5587 /* This is the polite way */
5588 if (context->callbacks.purge_cached_fn(context)) {
5589 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
5593 if (context->internal->_servers) {
5594 DEBUG(1, ("Active servers in context, free_context failed.\n"));
5598 if (context->internal->_files) {
5599 DEBUG(1, ("Active files in context, free_context failed.\n"));
5605 /* Things we have to clean up */
5606 SAFE_FREE(context->workgroup);
5607 SAFE_FREE(context->netbios_name);
5608 SAFE_FREE(context->user);
5610 DEBUG(3, ("Context %p succesfully freed\n", context));
5611 SAFE_FREE(context->internal);
5618 * Initialise the library etc
5620 * We accept a struct containing handle information.
5621 * valid values for info->debug from 0 to 100,
5622 * and insist that info->fn must be non-null.
5624 SMBCCTX * smbc_init_context(SMBCCTX * context)
5628 char *user = NULL, *home = NULL;
5630 if (!context || !context->internal) {
5635 /* Do not initialise the same client twice */
5636 if (context->internal->_initialized) {
5640 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
5647 if (!smbc_initialized) {
5648 /* Do some library wide intialisations the first time we get called */
5649 BOOL conf_loaded = False;
5651 /* Set this to what the user wants */
5652 DEBUGLEVEL = context->debug;
5654 setup_logging( "libsmbclient", True);
5656 /* Here we would open the smb.conf file if needed ... */
5658 load_interfaces(); /* Load the list of interfaces ... */
5660 in_client = True; /* FIXME, make a param */
5662 home = getenv("HOME");
5664 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5665 if (lp_load(conf, True, False, False)) {
5668 DEBUG(5, ("Could not load config file: %s\n",
5675 * Well, if that failed, try the dyn_CONFIGFILE
5676 * Which points to the standard locn, and if that
5677 * fails, silently ignore it and use the internal
5681 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
5682 DEBUG(5, ("Could not load config file: %s\n",
5686 * We loaded the global config file. Now lets
5687 * load user-specific modifications to the
5690 slprintf(conf, sizeof(conf),
5691 "%s/.smb/smb.conf.append", home);
5692 if (!lp_load(conf, True, False, False)) {
5694 ("Could not append config file: "
5701 reopen_logs(); /* Get logging working ... */
5704 * Block SIGPIPE (from lib/util_sock.c: write())
5705 * It is not needed and should not stop execution
5707 BlockSignals(True, SIGPIPE);
5709 /* Done with one-time initialisation */
5710 smbc_initialized = 1;
5714 if (!context->user) {
5716 * FIXME: Is this the best way to get the user info?
5718 user = getenv("USER");
5719 /* walk around as "guest" if no username can be found */
5720 if (!user) context->user = SMB_STRDUP("guest");
5721 else context->user = SMB_STRDUP(user);
5724 if (!context->netbios_name) {
5726 * We try to get our netbios name from the config. If that fails we fall
5727 * back on constructing our netbios name from our hostname etc
5729 if (global_myname()) {
5730 context->netbios_name = SMB_STRDUP(global_myname());
5734 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
5737 context->netbios_name = SMB_MALLOC(17);
5738 if (!context->netbios_name) {
5742 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
5746 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
5748 if (!context->workgroup) {
5749 if (lp_workgroup()) {
5750 context->workgroup = SMB_STRDUP(lp_workgroup());
5753 /* TODO: Think about a decent default workgroup */
5754 context->workgroup = SMB_STRDUP("samba");
5758 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
5760 /* shortest timeout is 1 second */
5761 if (context->timeout > 0 && context->timeout < 1000)
5762 context->timeout = 1000;
5765 * FIXME: Should we check the function pointers here?
5768 context->internal->_initialized = 1;
5774 /* Return the verion of samba, and thus libsmbclient */
5778 return samba_version_string();