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
36 unsigned long long size;
40 unsigned long long inode;
45 * Internal flags for extended attributes
48 /* internal mode values */
49 #define SMBC_XATTR_MODE_ADD 1
50 #define SMBC_XATTR_MODE_REMOVE 2
51 #define SMBC_XATTR_MODE_REMOVE_ALL 3
52 #define SMBC_XATTR_MODE_SET 4
53 #define SMBC_XATTR_MODE_CHOWN 5
54 #define SMBC_XATTR_MODE_CHGRP 6
56 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
58 /*We should test for this in configure ... */
60 #define ENOTSUP EOPNOTSUPP
64 * Functions exported by libsmb_cache.c that we need here
66 int smbc_default_cache_functions(SMBCCTX *context);
69 * check if an element is part of the list.
70 * FIXME: Does not belong here !
71 * Can anyone put this in a macro in dlinklist.h ?
74 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
75 if (!p || !list) return False;
77 if (p == list) return True;
84 * Find an lsa pipe handle associated with a cli struct.
87 static struct rpc_pipe_client *find_lsa_pipe_hnd(struct cli_state *ipc_cli)
89 struct rpc_pipe_client *pipe_hnd;
91 for (pipe_hnd = ipc_cli->pipe_list; pipe_hnd; pipe_hnd = pipe_hnd->next) {
92 if (pipe_hnd->pipe_idx == PI_LSARPC) {
100 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file);
101 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence);
103 extern BOOL in_client;
106 * Is the logging working / configfile read ?
108 static int smbc_initialized = 0;
111 hex2int( unsigned int _char )
113 if ( _char >= 'A' && _char <='F')
114 return _char - 'A' + 10;
115 if ( _char >= 'a' && _char <='f')
116 return _char - 'a' + 10;
117 if ( _char >= '0' && _char <='9')
125 * Convert strings of %xx to their single character equivalent. Each 'x' must
126 * be a valid hexadecimal digit, or that % sequence is left undecoded.
128 * dest may, but need not be, the same pointer as src.
130 * Returns the number of % sequences which could not be converted due to lack
131 * of two following hexadecimal digits.
134 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
136 int old_length = strlen(src);
142 if ( old_length == 0 ) {
147 while ( i < old_length ) {
148 unsigned char character = src[ i++ ];
150 if (character == '%') {
151 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
152 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
154 /* Replace valid sequence */
155 if (a != -1 && b != -1) {
157 /* Replace valid %xx sequence with %dd */
158 character = (a * 16) + b;
160 if (character == '\0') {
161 break; /* Stop at %00 */
176 strncpy(dest, temp, max_dest_len);
184 * Convert any characters not specifically allowed in a URL into their %xx
187 * Returns the remaining buffer length.
190 smbc_urlencode(char * dest, char * src, int max_dest_len)
192 char hex[] = "0123456789ABCDEF";
194 for (; *src != '\0' && max_dest_len >= 3; src++) {
206 *dest++ = hex[(*src >> 4) & 0x0f];
207 *dest++ = hex[*src & 0x0f];
222 * Function to parse a path and turn it into components
224 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
225 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
226 * general format ("smb:" only; we do not look for "cifs:").
230 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
234 * smb:// Show all workgroups.
236 * The method of locating the list of workgroups varies
237 * depending upon the setting of the context variable
238 * context->options.browse_max_lmb_count. This value
239 * determine the maximum number of local master browsers to
240 * query for the list of workgroups. In order to ensure that
241 * a complete list of workgroups is obtained, all master
242 * browsers must be queried, but if there are many
243 * workgroups, the time spent querying can begin to add up.
244 * For small networks (not many workgroups), it is suggested
245 * that this variable be set to 0, indicating query all local
246 * master browsers. When the network has many workgroups, a
247 * reasonable setting for this variable might be around 3.
249 * smb://name/ if name<1D> or name<1B> exists, list servers in
250 * workgroup, else, if name<20> exists, list all shares
253 * If "options" are provided, this function returns the entire option list as a
254 * string, for later parsing by the caller. Note that currently, no options
258 static const char *smbc_prefix = "smb:";
261 smbc_parse_path(SMBCCTX *context,
263 char *server, int server_len,
264 char *share, int share_len,
265 char *path, int path_len,
266 char *user, int user_len,
267 char *password, int password_len,
268 char *options, int options_len)
276 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
277 if (options != NULL && options_len > 0) {
278 options[0] = (char)0;
282 /* see if it has the right prefix */
283 len = strlen(smbc_prefix);
284 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
285 return -1; /* What about no smb: ? */
290 /* Watch the test below, we are testing to see if we should exit */
292 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
294 DEBUG(1, ("Invalid path (does not begin with smb://"));
299 p += 2; /* Skip the double slash */
301 /* See if any options were specified */
302 if ((q = strrchr(p, '?')) != NULL ) {
303 /* There are options. Null terminate here and point to them */
306 DEBUG(4, ("Found options '%s'", q));
308 /* Copy the options */
309 if (options != NULL && options_len > 0) {
310 safe_strcpy(options, q, options_len - 1);
319 strncpy(server, context->workgroup,
320 (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
326 * ok, its for us. Now parse out the server, share etc.
328 * However, we want to parse out [[domain;]user[:password]@] if it
332 /* check that '@' occurs before '/', if '/' exists at all */
333 q = strchr_m(p, '@');
334 r = strchr_m(p, '/');
335 if (q && (!r || q < r)) {
336 pstring username, passwd, domain;
337 const char *u = userinfo;
339 next_token(&p, userinfo, "@", sizeof(fstring));
341 username[0] = passwd[0] = domain[0] = 0;
343 if (strchr_m(u, ';')) {
345 next_token(&u, domain, ";", sizeof(fstring));
349 if (strchr_m(u, ':')) {
351 next_token(&u, username, ":", sizeof(fstring));
358 pstrcpy(username, u);
363 strncpy(user, username, user_len); /* FIXME, domain */
366 strncpy(password, passwd, password_len);
370 if (!next_token(&p, server, "/", sizeof(fstring))) {
376 if (*p == (char)0) goto decoding; /* That's it ... */
378 if (!next_token(&p, share, "/", sizeof(fstring))) {
384 safe_strcpy(path, p, path_len - 1);
386 all_string_sub(path, "/", "\\", 0);
389 (void) smbc_urldecode(path, path, path_len);
390 (void) smbc_urldecode(server, server, server_len);
391 (void) smbc_urldecode(share, share, share_len);
392 (void) smbc_urldecode(user, user, user_len);
393 (void) smbc_urldecode(password, password, password_len);
399 * Verify that the options specified in a URL are valid
401 static int smbc_check_options(char *server, char *share, char *path, char *options)
403 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' path='%s' options='%s'\n", server, share, path, options));
405 /* No options at all is always ok */
406 if (! *options) return 0;
408 /* Currently, we don't support any options. */
413 * Convert an SMB error into a UNIX error ...
415 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
417 int ret = cli_errno(c);
419 if (cli_is_dos_error(c)) {
423 cli_dos_error(c, &eclass, &ecode);
425 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
426 (int)eclass, (int)ecode, (int)ecode, ret));
430 status = cli_nt_error(c);
432 DEBUG(3,("smbc errno %s -> %d\n",
433 nt_errstr(status), ret));
440 * Check a server for being alive and well.
441 * returns 0 if the server is in shape. Returns 1 on error
443 * Also useable outside libsmbclient to enable external cache
444 * to do some checks too.
446 int smbc_check_server(SMBCCTX * context, SMBCSRV * server)
448 if ( send_keepalive(server->cli.fd) == False )
451 /* connection is ok */
456 * Remove a server from the cached server list it's unused.
457 * On success, 0 is returned. 1 is returned if the server could not be removed.
459 * Also useable outside libsmbclient
461 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
465 /* are we being fooled ? */
466 if (!context || !context->internal ||
467 !context->internal->_initialized || !srv) return 1;
470 /* Check all open files/directories for a relation with this server */
471 for (file = context->internal->_files; file; file=file->next) {
472 if (file->srv == srv) {
474 DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n",
480 DLIST_REMOVE(context->internal->_servers, srv);
482 cli_shutdown(&srv->cli);
484 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
486 context->callbacks.remove_cached_srv_fn(context, srv);
491 SMBCSRV *find_server(SMBCCTX *context,
503 srv = context->callbacks.get_cached_srv_fn(context, server, share,
504 workgroup, username);
506 if (!auth_called && !srv && (!username[0] || !password[0])) {
507 context->callbacks.auth_fn(server, share,
508 workgroup, sizeof(fstring),
509 username, sizeof(fstring),
510 password, sizeof(fstring));
512 * However, smbc_auth_fn may have picked up info relating to
513 * an existing connection, so try for an existing connection
517 goto check_server_cache;
522 if (context->callbacks.check_server_fn(context, srv)) {
524 * This server is no good anymore
525 * Try to remove it and check for more possible
526 * servers in the cache
528 if (context->callbacks.remove_unused_server_fn(context,
531 * We could not remove the server completely,
532 * remove it from the cache so we will not get
533 * it again. It will be removed when the last
534 * file/dir is closed.
536 context->callbacks.remove_cached_srv_fn(context,
541 * Maybe there are more cached connections to this
544 goto check_server_cache;
554 * Connect to a server, possibly on an existing connection
556 * Here, what we want to do is: If the server and username
557 * match an existing connection, reuse that, otherwise, establish a
560 * If we have to create a new connection, call the auth_fn to get the
561 * info we need, unless the username and password were passed in.
564 SMBCSRV *smbc_server(SMBCCTX *context,
565 const char *server, const char *share,
566 fstring workgroup, fstring username,
571 struct nmb_name called, calling;
572 const char *server_n = server;
575 int tried_reverse = 0;
578 const char *username_used;
583 if (server[0] == 0) {
588 srv = find_server(context, server, share,
589 workgroup, username, password);
592 * If we found a connection and we're only allowed one share per
595 if (srv && *share != '\0' && context->options.one_share_per_server) {
598 * ... then if there's no current connection to the share,
599 * connect to it. find_server(), or rather the function
600 * pointed to by context->callbacks.get_cached_srv_fn which
601 * was called by find_server(), will have issued a tree
602 * disconnect if the requested share is not the same as the
603 * one that was already connected.
605 if (srv->cli.cnum == (uint16) -1) {
606 /* Ensure we have accurate auth info */
607 context->callbacks.auth_fn(server, share,
608 workgroup, sizeof(fstring),
609 username, sizeof(fstring),
610 password, sizeof(fstring));
612 if (! cli_send_tconX(&srv->cli, share, "?????",
613 password, strlen(password)+1)) {
615 errno = smbc_errno(context, &srv->cli);
616 cli_shutdown(&srv->cli);
617 context->callbacks.remove_cached_srv_fn(context, srv);
621 /* Regenerate the dev value since it's based on both server and share */
623 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
628 /* If we have a connection... */
631 /* ... then we're done here. Give 'em what they came for. */
635 make_nmb_name(&calling, context->netbios_name, 0x0);
636 make_nmb_name(&called , server, 0x20);
638 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
640 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
643 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
647 /* have to open a new connection */
648 if (!cli_initialise(&c)) {
653 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
654 c.use_kerberos = True;
656 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
657 c.fallback_after_kerberos = True;
660 c.timeout = context->timeout;
663 * Force use of port 139 for first try if share is $IPC, empty, or
664 * null, so browse lists can work
666 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
667 port_try_first = 139;
670 port_try_first = 445;
674 c.port = port_try_first;
676 if (!cli_connect(&c, server_n, &ip)) {
678 /* First connection attempt failed. Try alternate port. */
679 c.port = port_try_next;
681 if (!cli_connect(&c, server_n, &ip)) {
688 if (!cli_session_request(&c, &calling, &called)) {
690 if (strcmp(called.name, "*SMBSERVER")) {
691 make_nmb_name(&called , "*SMBSERVER", 0x20);
694 else { /* Try one more time, but ensure we don't loop */
696 /* Only try this if server is an IP address ... */
698 if (is_ipaddress(server) && !tried_reverse) {
700 struct in_addr rem_ip;
702 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
703 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
708 tried_reverse++; /* Yuck */
710 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
711 make_nmb_name(&called, remote_name, 0x20);
722 DEBUG(4,(" session request ok\n"));
724 if (!cli_negprot(&c)) {
730 username_used = username;
732 if (!cli_session_setup(&c, username_used,
733 password, strlen(password),
734 password, strlen(password),
737 /* Failed. Try an anonymous login, if allowed by flags. */
740 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
741 !cli_session_setup(&c, username_used,
752 DEBUG(4,(" session setup ok\n"));
754 if (!cli_send_tconX(&c, share, "?????",
755 password, strlen(password)+1)) {
756 errno = smbc_errno(context, &c);
761 DEBUG(4,(" tconx ok\n"));
764 * Ok, we have got a nice connection
765 * Let's allocate a server structure.
768 srv = SMB_MALLOC_P(SMBCSRV);
776 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
777 srv->no_pathinfo = False;
778 srv->no_pathinfo2 = False;
779 srv->no_nt_session = False;
781 /* now add it to the cache (internal or external) */
782 /* Let the cache function set errno if it wants to */
784 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username_used)) {
785 int saved_errno = errno;
786 DEBUG(3, (" Failed to add server to cache\n"));
794 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
795 server, share, srv));
797 DLIST_ADD(context->internal->_servers, srv);
802 if (!srv) return NULL;
809 * Connect to a server for getting/setting attributes, possibly on an existing
810 * connection. This works similarly to smbc_server().
812 SMBCSRV *smbc_attr_server(SMBCCTX *context,
813 const char *server, const char *share,
815 fstring username, fstring password,
819 struct cli_state *ipc_cli;
820 struct rpc_pipe_client *pipe_hnd;
822 SMBCSRV *ipc_srv=NULL;
825 * See if we've already created this special connection. Reference our
826 * "special" share name '*IPC$', which is an impossible real share name
827 * due to the leading asterisk.
829 ipc_srv = find_server(context, server, "*IPC$",
830 workgroup, username, password);
833 /* We didn't find a cached connection. Get the password */
834 if (*password == '\0') {
835 /* ... then retrieve it now. */
836 context->callbacks.auth_fn(server, share,
837 workgroup, sizeof(fstring),
838 username, sizeof(fstring),
839 password, sizeof(fstring));
843 nt_status = cli_full_connection(&ipc_cli,
844 global_myname(), server,
845 &ip, 0, "IPC$", "?????",
849 if (! NT_STATUS_IS_OK(nt_status)) {
850 DEBUG(1,("cli_full_connection failed! (%s)\n",
851 nt_errstr(nt_status)));
857 pipe_hnd = cli_rpc_pipe_open_noauth(ipc_cli, PI_LSARPC, &nt_status);
859 DEBUG(1, ("cli_nt_session_open fail!\n"));
861 cli_shutdown(ipc_cli);
865 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
866 but NT sends 0x2000000 so we might as well do it too. */
868 nt_status = rpccli_lsa_open_policy(pipe_hnd,
871 GENERIC_EXECUTE_ACCESS,
874 if (!NT_STATUS_IS_OK(nt_status)) {
875 errno = smbc_errno(context, ipc_cli);
876 cli_shutdown(ipc_cli);
881 ipc_srv = SMB_MALLOC_P(SMBCSRV);
884 cli_shutdown(ipc_cli);
888 ZERO_STRUCTP(ipc_srv);
889 ipc_srv->cli = *ipc_cli;
893 /* now add it to the cache (internal or external) */
895 errno = 0; /* let cache function set errno if it likes */
896 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
901 DEBUG(3, (" Failed to add server to cache\n"));
905 cli_shutdown(&ipc_srv->cli);
910 DLIST_ADD(context->internal->_servers, ipc_srv);
917 * Routine to open() a file ...
920 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
922 fstring server, share, user, password, workgroup;
925 struct cli_state *targetcli;
927 SMBCFILE *file = NULL;
930 if (!context || !context->internal ||
931 !context->internal->_initialized) {
933 errno = EINVAL; /* Best I can think of ... */
945 if (smbc_parse_path(context, fname,
946 server, sizeof(server),
947 share, sizeof(share),
950 password, sizeof(password),
956 if (user[0] == (char)0) fstrcpy(user, context->user);
958 fstrcpy(workgroup, context->workgroup);
960 srv = smbc_server(context, server, share, workgroup, user, password);
964 if (errno == EPERM) errno = EACCES;
965 return NULL; /* smbc_server sets errno */
969 /* Hmmm, the test for a directory is suspect here ... FIXME */
971 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
978 file = SMB_MALLOC_P(SMBCFILE);
989 /*d_printf(">>>open: resolving %s\n", path);*/
990 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
992 d_printf("Could not resolve %s\n", path);
995 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
997 if ( targetcli->dfsroot )
1000 pstrcpy(temppath, targetpath);
1001 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1004 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1006 /* Handle the error ... */
1009 errno = smbc_errno(context, targetcli);
1014 /* Fill in file struct */
1017 file->fname = SMB_STRDUP(fname);
1022 DLIST_ADD(context->internal->_files, file);
1025 * If the file was opened in O_APPEND mode, all write
1026 * operations should be appended to the file. To do that,
1027 * though, using this protocol, would require a getattrE()
1028 * call for each and every write, to determine where the end
1029 * of the file is. (There does not appear to be an append flag
1030 * in the protocol.) Rather than add all of that overhead of
1031 * retrieving the current end-of-file offset prior to each
1032 * write operation, we'll assume that most append operations
1033 * will continuously write, so we'll just set the offset to
1034 * the end of the file now and hope that's adequate.
1036 * Note to self: If this proves inadequate, and O_APPEND
1037 * should, in some cases, be forced for each write, add a
1038 * field in the context options structure, for
1039 * "strict_append_mode" which would select between the current
1040 * behavior (if FALSE) or issuing a getattrE() prior to each
1041 * write and forcing the write to the end of the file (if
1042 * TRUE). Adding that capability will likely require adding
1043 * an "append" flag into the _SMBCFILE structure to track
1044 * whether a file was opened in O_APPEND mode. -- djl
1046 if (flags & O_APPEND) {
1047 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1048 (void) smbc_close_ctx(context, file);
1058 /* Check if opendir needed ... */
1063 eno = smbc_errno(context, &srv->cli);
1064 file = context->opendir(context, fname);
1065 if (!file) errno = eno;
1070 errno = EINVAL; /* FIXME, correct errno ? */
1076 * Routine to create a file
1079 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1081 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
1084 if (!context || !context->internal ||
1085 !context->internal->_initialized) {
1092 return smbc_open_ctx(context, path, creat_bits, mode);
1096 * Routine to read() a file ...
1099 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1102 fstring server, share, user, password;
1103 pstring path, targetpath;
1104 struct cli_state *targetcli;
1109 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1110 * appears to pass file->offset (which is type off_t) differently than
1111 * a local variable of type off_t. Using local variable "offset" in
1112 * the call to cli_read() instead of file->offset fixes a problem
1113 * retrieving data at an offset greater than 4GB.
1115 off_t offset = file->offset;
1117 if (!context || !context->internal ||
1118 !context->internal->_initialized) {
1125 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1127 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1134 /* Check that the buffer exists ... */
1143 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1144 if (smbc_parse_path(context, file->fname,
1145 server, sizeof(server),
1146 share, sizeof(share),
1149 password, sizeof(password),
1155 /*d_printf(">>>read: resolving %s\n", path);*/
1156 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1158 d_printf("Could not resolve %s\n", path);
1161 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1163 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1167 errno = smbc_errno(context, targetcli);
1172 file->offset += ret;
1174 DEBUG(4, (" --> %d\n", ret));
1176 return ret; /* Success, ret bytes of data ... */
1181 * Routine to write() a file ...
1184 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1187 off_t offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1188 fstring server, share, user, password;
1189 pstring path, targetpath;
1190 struct cli_state *targetcli;
1192 if (!context || !context->internal ||
1193 !context->internal->_initialized) {
1200 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1207 /* Check that the buffer exists ... */
1216 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1217 if (smbc_parse_path(context, file->fname,
1218 server, sizeof(server),
1219 share, sizeof(share),
1222 password, sizeof(password),
1228 /*d_printf(">>>write: resolving %s\n", path);*/
1229 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1231 d_printf("Could not resolve %s\n", path);
1234 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1237 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1241 errno = smbc_errno(context, targetcli);
1246 file->offset += ret;
1248 return ret; /* Success, 0 bytes of data ... */
1252 * Routine to close() a file ...
1255 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1258 fstring server, share, user, password;
1259 pstring path, targetpath;
1260 struct cli_state *targetcli;
1262 if (!context || !context->internal ||
1263 !context->internal->_initialized) {
1270 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1280 return context->closedir(context, file);
1284 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1285 if (smbc_parse_path(context, file->fname,
1286 server, sizeof(server),
1287 share, sizeof(share),
1290 password, sizeof(password),
1296 /*d_printf(">>>close: resolving %s\n", path);*/
1297 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1299 d_printf("Could not resolve %s\n", path);
1302 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1304 if (!cli_close(targetcli, file->cli_fd)) {
1306 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1308 /* Deallocate slot and remove the server
1309 * from the server cache if unused */
1310 errno = smbc_errno(context, targetcli);
1312 DLIST_REMOVE(context->internal->_files, file);
1313 SAFE_FREE(file->fname);
1315 context->callbacks.remove_unused_server_fn(context, srv);
1321 DLIST_REMOVE(context->internal->_files, file);
1322 SAFE_FREE(file->fname);
1329 * Get info from an SMB server on a file. Use a qpathinfo call first
1330 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1332 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1333 uint16 *mode, SMB_OFF_T *size,
1334 time_t *c_time, time_t *a_time, time_t *m_time,
1339 struct cli_state *targetcli;
1340 if (!context || !context->internal ||
1341 !context->internal->_initialized) {
1348 /* path fixup for . and .. */
1349 if (strequal(path, ".") || strequal(path, ".."))
1350 pstrcpy(fixedpath, "\\");
1353 pstrcpy(fixedpath, path);
1354 trim_string(fixedpath, NULL, "\\..");
1355 trim_string(fixedpath, NULL, "\\.");
1357 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1359 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1361 d_printf("Couldn't resolve %s\n", path);
1365 if ( targetcli->dfsroot )
1368 pstrcpy(temppath, targetpath);
1369 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1372 if (!srv->no_pathinfo2 &&
1373 cli_qpathinfo2(targetcli, targetpath, c_time, a_time, m_time, NULL,
1374 size, mode, ino)) return True;
1376 /* if this is NT then don't bother with the getatr */
1377 if (targetcli->capabilities & CAP_NT_SMBS) {
1382 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1383 if (m_time != NULL) {
1384 if (a_time != NULL) *a_time = *m_time;
1385 if (c_time != NULL) *c_time = *m_time;
1387 srv->no_pathinfo2 = True;
1397 * Set file info on an SMB server. Use setpathinfo call first. If that
1398 * fails, use setattrE..
1400 * Access and modification time parameters are always used and must be
1401 * provided. Create time, if zero, will be determined from the actual create
1402 * time of the file. If non-zero, the create time will be set as well.
1404 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1406 static BOOL smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1407 time_t c_time, time_t a_time, time_t m_time,
1414 * Get the create time of the file (if not provided); we'll need it in
1417 if (! srv->no_pathinfo && c_time == 0) {
1418 if (! cli_qpathinfo(&srv->cli, path,
1419 &c_time, NULL, NULL, NULL, NULL)) {
1420 /* qpathinfo not available */
1421 srv->no_pathinfo = True;
1424 * We got a creation time. Some OS versions don't
1425 * return a valid create time, though. If we got an
1426 * invalid time, start with the current time instead.
1428 if (c_time == 0 || c_time == (time_t) -1) {
1429 c_time = time(NULL);
1433 * We got a creation time. For sanity sake, since
1434 * there is no POSIX function to set the create time
1435 * of a file, if the existing create time is greater
1436 * than either of access time or modification time,
1437 * set create time to the smallest of those. This
1438 * ensure that the create time of a file is never
1439 * greater than its last access or modification time.
1441 if (c_time > a_time) c_time = a_time;
1442 if (c_time > m_time) c_time = m_time;
1447 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1448 * modern function for "new code" to be using, and it works given a
1449 * filename rather than requiring that the file be opened to have its
1450 * attributes manipulated.
1452 if (srv->no_pathinfo ||
1453 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1456 * setpathinfo is not supported; go to plan B.
1458 * cli_setatr() does not work on win98, and it also doesn't
1459 * support setting the access time (only the modification
1460 * time), so in all cases, we open the specified file and use
1461 * cli_setattrE() which should work on all OS versions, and
1462 * supports both times.
1465 /* Don't try {q,set}pathinfo() again, with this server */
1466 srv->no_pathinfo = True;
1469 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1471 errno = smbc_errno(context, &srv->cli);
1476 * Get the creat time of the file (if it wasn't provided).
1477 * We'll need it in the set call
1480 ret = cli_getattrE(&srv->cli, fd,
1482 &c_time, NULL, NULL);
1487 /* If we got create time, set times */
1489 /* Some OS versions don't support create time */
1490 if (c_time == 0 || c_time == -1) {
1491 c_time = time(NULL);
1495 * For sanity sake, since there is no POSIX function
1496 * to set the create time of a file, if the existing
1497 * create time is greater than either of access time
1498 * or modification time, set create time to the
1499 * smallest of those. This ensure that the create
1500 * time of a file is never greater than its last
1501 * access or modification time.
1503 if (c_time > a_time) c_time = a_time;
1504 if (c_time > m_time) c_time = m_time;
1506 /* Set the new attributes */
1507 ret = cli_setattrE(&srv->cli, fd,
1508 c_time, a_time, m_time);
1509 cli_close(&srv->cli, fd);
1513 * Unfortunately, setattrE() doesn't have a provision for
1514 * setting the access mode (attributes). We'll have to try
1515 * cli_setatr() for that, and with only this parameter, it
1516 * seems to work on win98.
1518 if (ret && mode != (uint16) -1) {
1519 ret = cli_setatr(&srv->cli, path, mode, 0);
1523 errno = smbc_errno(context, &srv->cli);
1532 * Routine to unlink() a file
1535 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1537 fstring server, share, user, password, workgroup;
1538 pstring path, targetpath;
1539 struct cli_state *targetcli;
1540 SMBCSRV *srv = NULL;
1542 if (!context || !context->internal ||
1543 !context->internal->_initialized) {
1545 errno = EINVAL; /* Best I can think of ... */
1557 if (smbc_parse_path(context, fname,
1558 server, sizeof(server),
1559 share, sizeof(share),
1562 password, sizeof(password),
1568 if (user[0] == (char)0) fstrcpy(user, context->user);
1570 fstrcpy(workgroup, context->workgroup);
1572 srv = smbc_server(context, server, share, workgroup, user, password);
1576 return -1; /* smbc_server sets errno */
1580 /*d_printf(">>>unlink: resolving %s\n", path);*/
1581 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1583 d_printf("Could not resolve %s\n", path);
1586 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1588 if (!cli_unlink(targetcli, targetpath)) {
1590 errno = smbc_errno(context, targetcli);
1592 if (errno == EACCES) { /* Check if the file is a directory */
1597 time_t m_time = 0, a_time = 0, c_time = 0;
1600 if (!smbc_getatr(context, srv, path, &mode, &size,
1601 &c_time, &a_time, &m_time, &ino)) {
1603 /* Hmmm, bad error ... What? */
1605 errno = smbc_errno(context, targetcli);
1611 if (IS_DOS_DIR(mode))
1614 errno = saverr; /* Restore this */
1623 return 0; /* Success ... */
1628 * Routine to rename() a file
1631 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1632 SMBCCTX *ncontext, const char *nname)
1634 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1635 pstring path1, path2, targetpath1, targetpath2;
1636 struct cli_state *targetcli1, *targetcli2;
1637 SMBCSRV *srv = NULL;
1639 if (!ocontext || !ncontext ||
1640 !ocontext->internal || !ncontext->internal ||
1641 !ocontext->internal->_initialized ||
1642 !ncontext->internal->_initialized) {
1644 errno = EINVAL; /* Best I can think of ... */
1649 if (!oname || !nname) {
1656 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1658 smbc_parse_path(ocontext, oname,
1659 server1, sizeof(server1),
1660 share1, sizeof(share1),
1661 path1, sizeof(path1),
1662 user1, sizeof(user1),
1663 password1, sizeof(password1),
1666 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1668 smbc_parse_path(ncontext, nname,
1669 server2, sizeof(server2),
1670 share2, sizeof(share2),
1671 path2, sizeof(path2),
1672 user2, sizeof(user2),
1673 password2, sizeof(password2),
1676 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1678 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1679 strcmp(user1, user2)) {
1681 /* Can't rename across file systems, or users?? */
1688 fstrcpy(workgroup, ocontext->workgroup);
1689 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1690 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1697 /*d_printf(">>>rename: resolving %s\n", path1);*/
1698 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1700 d_printf("Could not resolve %s\n", path1);
1703 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1704 /*d_printf(">>>rename: resolving %s\n", path2);*/
1705 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1707 d_printf("Could not resolve %s\n", path2);
1710 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1712 if (strcmp(targetcli1->desthost, targetcli2->desthost) || strcmp(targetcli1->share, targetcli2->share))
1714 /* can't rename across file systems */
1720 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1721 int eno = smbc_errno(ocontext, targetcli1);
1723 if (eno != EEXIST ||
1724 !cli_unlink(targetcli1, targetpath2) ||
1725 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1733 return 0; /* Success */
1738 * A routine to lseek() a file
1741 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1744 fstring server, share, user, password;
1745 pstring path, targetpath;
1746 struct cli_state *targetcli;
1748 if (!context || !context->internal ||
1749 !context->internal->_initialized) {
1756 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1766 return -1; /* Can't lseek a dir ... */
1772 file->offset = offset;
1776 file->offset += offset;
1780 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1781 if (smbc_parse_path(context, file->fname,
1782 server, sizeof(server),
1783 share, sizeof(share),
1786 password, sizeof(password),
1792 /*d_printf(">>>lseek: resolving %s\n", path);*/
1793 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1795 d_printf("Could not resolve %s\n", path);
1798 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1800 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL, &size, NULL, NULL,
1803 SMB_OFF_T b_size = size;
1804 if (!cli_getattrE(targetcli, file->cli_fd, NULL, &b_size, NULL, NULL,
1812 file->offset = size + offset;
1821 return file->offset;
1826 * Generate an inode number from file name for those things that need it
1830 ino_t smbc_inode(SMBCCTX *context, const char *name)
1833 if (!context || !context->internal ||
1834 !context->internal->_initialized) {
1841 if (!*name) return 2; /* FIXME, why 2 ??? */
1842 return (ino_t)str_checksum(name);
1847 * Routine to put basic stat info into a stat structure ... Used by stat and
1852 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname,
1853 SMB_OFF_T size, int mode)
1858 if (IS_DOS_DIR(mode)) {
1859 st->st_mode = SMBC_DIR_MODE;
1861 st->st_mode = SMBC_FILE_MODE;
1864 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1865 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1866 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1867 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1870 #ifdef HAVE_STAT_ST_BLKSIZE
1871 st->st_blksize = 512;
1873 #ifdef HAVE_STAT_ST_BLOCKS
1874 st->st_blocks = (size+511)/512;
1876 st->st_uid = getuid();
1877 st->st_gid = getgid();
1879 if (IS_DOS_DIR(mode)) {
1885 if (st->st_ino == 0) {
1886 st->st_ino = smbc_inode(context, fname);
1889 return True; /* FIXME: Is this needed ? */
1894 * Routine to stat a file given a name
1897 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1900 fstring server, share, user, password, workgroup;
1902 time_t m_time = 0, a_time = 0, c_time = 0;
1907 if (!context || !context->internal ||
1908 !context->internal->_initialized) {
1910 errno = EINVAL; /* Best I can think of ... */
1922 DEBUG(4, ("smbc_stat(%s)\n", fname));
1924 if (smbc_parse_path(context, fname,
1925 server, sizeof(server),
1926 share, sizeof(share),
1929 password, sizeof(password),
1935 if (user[0] == (char)0) fstrcpy(user, context->user);
1937 fstrcpy(workgroup, context->workgroup);
1939 srv = smbc_server(context, server, share, workgroup, user, password);
1942 return -1; /* errno set by smbc_server */
1945 if (!smbc_getatr(context, srv, path, &mode, &size,
1946 &c_time, &a_time, &m_time, &ino)) {
1948 errno = smbc_errno(context, &srv->cli);
1955 smbc_setup_stat(context, st, path, size, mode);
1957 st->st_atime = a_time;
1958 st->st_ctime = c_time;
1959 st->st_mtime = m_time;
1960 st->st_dev = srv->dev;
1967 * Routine to stat a file given an fd
1970 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1972 time_t c_time, a_time, m_time;
1975 fstring server, share, user, password;
1976 pstring path, targetpath;
1977 struct cli_state *targetcli;
1980 if (!context || !context->internal ||
1981 !context->internal->_initialized) {
1988 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1997 return context->fstatdir(context, file, st);
2001 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2002 if (smbc_parse_path(context, file->fname,
2003 server, sizeof(server),
2004 share, sizeof(share),
2007 password, sizeof(password),
2013 /*d_printf(">>>fstat: resolving %s\n", path);*/
2014 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
2016 d_printf("Could not resolve %s\n", path);
2019 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2021 if (!cli_qfileinfo(targetcli, file->cli_fd,
2022 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
2023 if (!cli_getattrE(targetcli, file->cli_fd,
2024 &mode, &size, &c_time, &a_time, &m_time)) {
2033 smbc_setup_stat(context, st, file->fname, size, mode);
2035 st->st_atime = a_time;
2036 st->st_ctime = c_time;
2037 st->st_mtime = m_time;
2038 st->st_dev = file->srv->dev;
2045 * Routine to open a directory
2046 * We accept the URL syntax explained in smbc_parse_path(), above.
2049 static void smbc_remove_dir(SMBCFILE *dir)
2051 struct smbc_dir_list *d,*f;
2058 SAFE_FREE(f->dirent);
2063 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2067 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
2069 struct smbc_dirent *dirent;
2071 int name_length = (name == NULL ? 0 : strlen(name));
2072 int comment_len = (comment == NULL ? 0 : strlen(comment));
2075 * Allocate space for the dirent, which must be increased by the
2076 * size of the name and the comment and 1 each for the null terminator.
2079 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2081 dirent = SMB_MALLOC(size);
2085 dir->dir_error = ENOMEM;
2090 ZERO_STRUCTP(dirent);
2092 if (dir->dir_list == NULL) {
2094 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2095 if (!dir->dir_list) {
2098 dir->dir_error = ENOMEM;
2102 ZERO_STRUCTP(dir->dir_list);
2104 dir->dir_end = dir->dir_next = dir->dir_list;
2108 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2110 if (!dir->dir_end->next) {
2113 dir->dir_error = ENOMEM;
2117 ZERO_STRUCTP(dir->dir_end->next);
2119 dir->dir_end = dir->dir_end->next;
2122 dir->dir_end->next = NULL;
2123 dir->dir_end->dirent = dirent;
2125 dirent->smbc_type = type;
2126 dirent->namelen = name_length;
2127 dirent->commentlen = comment_len;
2128 dirent->dirlen = size;
2130 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2132 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2133 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2140 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
2142 SMBCFILE *dir = (SMBCFILE *)state;
2143 struct smbc_dir_list *dir_list;
2144 struct smbc_dirent *dirent;
2148 dirent_type = dir->dir_type;
2150 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2152 /* An error occurred, what do we do? */
2153 /* FIXME: Add some code here */
2156 /* Point to the one just added */
2157 dirent = dir->dir_end->dirent;
2159 /* See if this was a duplicate */
2160 for (dir_list = dir->dir_list;
2161 dir_list != dir->dir_end;
2162 dir_list = dir_list->next) {
2164 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2165 /* Duplicate. End end of list need to be removed. */
2169 if (do_remove && dir_list->next == dir->dir_end) {
2170 /* Found the end of the list. Remove it. */
2171 dir->dir_end = dir_list;
2172 free(dir_list->next);
2173 dir_list->next = NULL;
2180 list_fn(const char *name, uint32 type, const char *comment, void *state)
2182 SMBCFILE *dir = (SMBCFILE *)state;
2185 /* We need to process the type a little ... */
2187 if (dir->dir_type == SMBC_FILE_SHARE) {
2190 case 0: /* Directory tree */
2191 dirent_type = SMBC_FILE_SHARE;
2195 dirent_type = SMBC_PRINTER_SHARE;
2199 dirent_type = SMBC_COMMS_SHARE;
2203 dirent_type = SMBC_IPC_SHARE;
2207 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2211 else dirent_type = dir->dir_type;
2213 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2215 /* An error occurred, what do we do? */
2216 /* FIXME: Add some code here */
2222 dir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2225 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2226 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2228 /* Handle an error ... */
2230 /* FIXME: Add some code ... */
2236 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
2238 fstring server, share, user, password, options;
2243 SMBCSRV *srv = NULL;
2244 SMBCFILE *dir = NULL;
2245 struct in_addr rem_ip;
2247 if (!context || !context->internal ||
2248 !context->internal->_initialized) {
2249 DEBUG(4, ("no valid context\n"));
2250 errno = EINVAL + 8192;
2256 DEBUG(4, ("no valid fname\n"));
2257 errno = EINVAL + 8193;
2261 if (smbc_parse_path(context, fname,
2262 server, sizeof(server),
2263 share, sizeof(share),
2266 password, sizeof(password),
2267 options, sizeof(options))) {
2268 DEBUG(4, ("no valid path\n"));
2269 errno = EINVAL + 8194;
2273 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
2275 /* Ensure the options are valid */
2276 if (smbc_check_options(server, share, path, options)) {
2277 DEBUG(4, ("unacceptable options (%s)\n", options));
2278 errno = EINVAL + 8195;
2282 if (user[0] == (char)0) fstrcpy(user, context->user);
2284 pstrcpy(workgroup, context->workgroup);
2286 dir = SMB_MALLOC_P(SMBCFILE);
2298 dir->fname = SMB_STRDUP(fname);
2302 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2304 if (server[0] == (char)0) {
2309 struct ip_service *ip_list;
2310 struct ip_service server_addr;
2311 struct user_auth_info u_info;
2312 struct cli_state *cli;
2314 if (share[0] != (char)0 || path[0] != (char)0) {
2316 errno = EINVAL + 8196;
2318 SAFE_FREE(dir->fname);
2324 /* Determine how many local master browsers to query */
2325 max_lmb_count = (context->options.browse_max_lmb_count == 0
2327 : context->options.browse_max_lmb_count);
2329 pstrcpy(u_info.username, user);
2330 pstrcpy(u_info.password, password);
2333 * We have server and share and path empty but options
2334 * requesting that we scan all master browsers for their list
2335 * of workgroups/domains. This implies that we must first try
2336 * broadcast queries to find all master browsers, and if that
2337 * doesn't work, then try our other methods which return only
2338 * a single master browser.
2341 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2342 if (!find_master_ip(workgroup, &server_addr.ip)) {
2348 ip_list = &server_addr;
2352 for (i = 0; i < count && i < max_lmb_count; i++) {
2353 DEBUG(99, ("Found master browser %d of %d: %s\n", i+1, MAX(count, max_lmb_count), inet_ntoa(ip_list[i].ip)));
2355 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2356 /* cli == NULL is the master browser refused to talk or
2357 could not be found */
2361 fstrcpy(server, cli->desthost);
2364 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2367 * For each returned master browser IP address, get a
2368 * connection to IPC$ on the server if we do not
2369 * already have one, and determine the
2370 * workgroups/domains that it knows about.
2373 srv = smbc_server(context, server,
2374 "IPC$", workgroup, user, password);
2380 dir->dir_type = SMBC_WORKGROUP;
2382 /* Now, list the stuff ... */
2384 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2392 * Server not an empty string ... Check the rest and see what
2395 if (share[0] == (char)0) {
2397 if (path[0] != (char)0) { /* Should not have empty share with path */
2399 errno = EINVAL + 8197;
2401 SAFE_FREE(dir->fname);
2408 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2409 /* However, we check to see if <server> is an IP address first */
2411 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2412 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2413 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2416 dir->dir_type = SMBC_SERVER;
2419 * Get the backup list ...
2423 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2425 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2426 errno = EPERM; /* FIXME, is this correct */
2432 * Get a connection to IPC$ on the server if we do not already have one
2435 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2438 DEBUG(0, ("got no contact to IPC$\n"));
2440 SAFE_FREE(dir->fname);
2449 /* Now, list the servers ... */
2451 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2455 SAFE_FREE(dir->fname);
2464 if (resolve_name(server, &rem_ip, 0x20)) {
2466 /* Now, list the shares ... */
2468 dir->dir_type = SMBC_FILE_SHARE;
2470 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2475 SAFE_FREE(dir->fname);
2484 /* Now, list the servers ... */
2486 if (cli_RNetShareEnum(&srv->cli, list_fn,
2489 errno = cli_errno(&srv->cli);
2491 SAFE_FREE(dir->fname);
2501 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2503 SAFE_FREE(dir->fname);
2513 else { /* The server and share are specified ... work from there ... */
2515 struct cli_state *targetcli;
2517 /* Well, we connect to the server and list the directory */
2519 dir->dir_type = SMBC_FILE_SHARE;
2521 srv = smbc_server(context, server, share, workgroup, user, password);
2526 SAFE_FREE(dir->fname);
2535 /* Now, list the files ... */
2537 p = path + strlen(path);
2538 pstrcat(path, "\\*");
2540 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2542 d_printf("Could not resolve %s\n", path);
2546 if (cli_list(targetcli, targetpath, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2550 SAFE_FREE(dir->fname);
2553 errno = smbc_errno(context, targetcli);
2555 if (errno == EINVAL) {
2557 * See if they asked to opendir something
2558 * other than a directory. If so, the
2559 * converted error value we got would have
2560 * been EINVAL rather than ENOTDIR.
2562 *p = '\0'; /* restore original path */
2564 if (smbc_getatr(context, srv, path,
2568 ! IS_DOS_DIR(mode)) {
2570 /* It is. Correct the error value */
2582 DLIST_ADD(context->internal->_files, dir);
2588 * Routine to close a directory
2591 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2594 if (!context || !context->internal ||
2595 !context->internal->_initialized) {
2602 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2609 smbc_remove_dir(dir); /* Clean it up */
2611 DLIST_REMOVE(context->internal->_files, dir);
2615 SAFE_FREE(dir->fname);
2616 SAFE_FREE(dir); /* Free the space too */
2623 static void smbc_readdir_internal(SMBCCTX * context,
2624 struct smbc_dirent *dest,
2625 struct smbc_dirent *src,
2626 int max_namebuf_len)
2628 if (context->options.urlencode_readdir_entries) {
2630 /* url-encode the name. get back remaining buffer space */
2632 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2634 /* We now know the name length */
2635 dest->namelen = strlen(dest->name);
2637 /* Save the pointer to the beginning of the comment */
2638 dest->comment = dest->name + dest->namelen + 1;
2640 /* Copy the comment */
2641 strncpy(dest->comment, src->comment, max_namebuf_len);
2643 /* Ensure the comment is null terminated */
2644 if (max_namebuf_len > src->commentlen) {
2645 dest->comment[src->commentlen] = '\0';
2647 dest->comment[max_namebuf_len - 1] = '\0';
2650 /* Save other fields */
2651 dest->smbc_type = src->smbc_type;
2652 dest->commentlen = strlen(dest->comment);
2653 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2657 /* No encoding. Just copy the entry as is. */
2658 memcpy(dest, src, src->dirlen);
2659 dest->comment = (char *)(&dest->name + src->namelen + 1);
2665 * Routine to get a directory entry
2668 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2671 struct smbc_dirent *dirp, *dirent;
2673 /* Check that all is ok first ... */
2675 if (!context || !context->internal ||
2676 !context->internal->_initialized) {
2679 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2684 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2687 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2692 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2695 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2700 if (!dir->dir_next) {
2704 dirent = dir->dir_next->dirent;
2712 dirp = (struct smbc_dirent *)context->internal->_dirent;
2713 maxlen = (sizeof(context->internal->_dirent) -
2714 sizeof(struct smbc_dirent));
2716 smbc_readdir_internal(context, dirp, dirent, maxlen);
2718 dir->dir_next = dir->dir_next->next;
2724 * Routine to get directory entries
2727 static int smbc_getdents_ctx(SMBCCTX *context,
2729 struct smbc_dirent *dirp,
2735 char *ndir = (char *)dirp;
2736 struct smbc_dir_list *dirlist;
2738 /* Check that all is ok first ... */
2740 if (!context || !context->internal ||
2741 !context->internal->_initialized) {
2748 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2755 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2763 * Now, retrieve the number of entries that will fit in what was passed
2764 * We have to figure out if the info is in the list, or we need to
2765 * send a request to the server to get the info.
2768 while ((dirlist = dir->dir_next)) {
2769 struct smbc_dirent *dirent;
2771 if (!dirlist->dirent) {
2773 errno = ENOENT; /* Bad error */
2778 /* Do urlencoding of next entry, if so selected */
2779 dirent = (struct smbc_dirent *)context->internal->_dirent;
2780 maxlen = (sizeof(context->internal->_dirent) -
2781 sizeof(struct smbc_dirent));
2782 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
2784 reqd = dirent->dirlen;
2788 if (rem < count) { /* We managed to copy something */
2794 else { /* Nothing copied ... */
2796 errno = EINVAL; /* Not enough space ... */
2803 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2805 ((struct smbc_dirent *)ndir)->comment =
2806 (char *)(&((struct smbc_dirent *)ndir)->name +
2814 dir->dir_next = dirlist = dirlist -> next;
2825 * Routine to create a directory ...
2828 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2831 fstring server, share, user, password, workgroup;
2832 pstring path, targetpath;
2833 struct cli_state *targetcli;
2835 if (!context || !context->internal ||
2836 !context->internal->_initialized) {
2850 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2852 if (smbc_parse_path(context, fname,
2853 server, sizeof(server),
2854 share, sizeof(share),
2857 password, sizeof(password),
2863 if (user[0] == (char)0) fstrcpy(user, context->user);
2865 fstrcpy(workgroup, context->workgroup);
2867 srv = smbc_server(context, server, share, workgroup, user, password);
2871 return -1; /* errno set by smbc_server */
2875 /*d_printf(">>>mkdir: resolving %s\n", path);*/
2876 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2878 d_printf("Could not resolve %s\n", path);
2881 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
2883 if (!cli_mkdir(targetcli, targetpath)) {
2885 errno = smbc_errno(context, targetcli);
2895 * Our list function simply checks to see if a directory is not empty
2898 static int smbc_rmdir_dirempty = True;
2900 static void rmdir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2903 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2904 smbc_rmdir_dirempty = False;
2909 * Routine to remove a directory
2912 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2915 fstring server, share, user, password, workgroup;
2916 pstring path, targetpath;
2917 struct cli_state *targetcli;
2919 if (!context || !context->internal ||
2920 !context->internal->_initialized) {
2934 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2936 if (smbc_parse_path(context, fname,
2937 server, sizeof(server),
2938 share, sizeof(share),
2941 password, sizeof(password),
2948 if (user[0] == (char)0) fstrcpy(user, context->user);
2950 fstrcpy(workgroup, context->workgroup);
2952 srv = smbc_server(context, server, share, workgroup, user, password);
2956 return -1; /* errno set by smbc_server */
2960 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2962 mode = aDIR | aRONLY;
2965 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2967 if (strcmp(path, "\\") == 0) {
2969 mode = aDIR | aRONLY;
2975 smbc_stat_printjob(srv, path, &size, &m_time);
2976 c_time = a_time = m_time;
2981 /*d_printf(">>>rmdir: resolving %s\n", path);*/
2982 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2984 d_printf("Could not resolve %s\n", path);
2987 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
2990 if (!cli_rmdir(targetcli, targetpath)) {
2992 errno = smbc_errno(context, targetcli);
2994 if (errno == EACCES) { /* Check if the dir empty or not */
2996 pstring lpath; /* Local storage to avoid buffer overflows */
2998 smbc_rmdir_dirempty = True; /* Make this so ... */
3000 pstrcpy(lpath, targetpath);
3001 pstrcat(lpath, "\\*");
3003 if (cli_list(targetcli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
3006 /* Fix errno to ignore latest error ... */
3008 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
3009 smbc_errno(context, targetcli)));
3014 if (smbc_rmdir_dirempty)
3030 * Routine to return the current directory position
3033 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
3035 off_t ret_val; /* Squash warnings about cast */
3037 if (!context || !context->internal ||
3038 !context->internal->_initialized) {
3045 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3052 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3060 * We return the pointer here as the offset
3062 ret_val = (off_t)(long)dir->dir_next;
3068 * A routine to run down the list and see if the entry is OK
3071 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
3072 struct smbc_dirent *dirent)
3075 /* Run down the list looking for what we want */
3079 struct smbc_dir_list *tmp = list;
3083 if (tmp->dirent == dirent)
3092 return NULL; /* Not found, or an error */
3098 * Routine to seek on a directory
3101 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
3103 long int l_offset = offset; /* Handle problems of size */
3104 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3105 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3107 if (!context || !context->internal ||
3108 !context->internal->_initialized) {
3115 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3122 /* Now, check what we were passed and see if it is OK ... */
3124 if (dirent == NULL) { /* Seek to the begining of the list */
3126 dir->dir_next = dir->dir_list;
3131 /* Now, run down the list and make sure that the entry is OK */
3132 /* This may need to be changed if we change the format of the list */
3134 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3136 errno = EINVAL; /* Bad entry */
3141 dir->dir_next = list_ent;
3148 * Routine to fstat a dir
3151 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
3154 if (!context || !context->internal ||
3155 !context->internal->_initialized) {
3162 /* No code yet ... */
3168 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
3171 fstring server, share, user, password, workgroup;
3175 if (!context || !context->internal ||
3176 !context->internal->_initialized) {
3178 errno = EINVAL; /* Best I can think of ... */
3190 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3192 if (smbc_parse_path(context, fname,
3193 server, sizeof(server),
3194 share, sizeof(share),
3197 password, sizeof(password),
3203 if (user[0] == (char)0) fstrcpy(user, context->user);
3205 fstrcpy(workgroup, context->workgroup);
3207 srv = smbc_server(context, server, share, workgroup, user, password);
3210 return -1; /* errno set by smbc_server */
3215 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3216 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3217 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3218 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3220 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3221 errno = smbc_errno(context, &srv->cli);
3228 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
3231 fstring server, share, user, password, workgroup;
3236 if (!context || !context->internal ||
3237 !context->internal->_initialized) {
3239 errno = EINVAL; /* Best I can think of ... */
3252 a_time = m_time = time(NULL);
3254 a_time = tbuf[0].tv_sec;
3255 m_time = tbuf[1].tv_sec;
3264 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf));
3265 atimebuf[sizeof(atimebuf) - 1] = '\0';
3266 if ((p = strchr(atimebuf, '\n')) != NULL) {
3270 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf));
3271 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3272 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3276 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3277 fname, atimebuf, mtimebuf);
3280 if (smbc_parse_path(context, fname,
3281 server, sizeof(server),
3282 share, sizeof(share),
3285 password, sizeof(password),
3291 if (user[0] == (char)0) fstrcpy(user, context->user);
3293 fstrcpy(workgroup, context->workgroup);
3295 srv = smbc_server(context, server, share, workgroup, user, password);
3298 return -1; /* errno set by smbc_server */
3301 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3302 return -1; /* errno set by smbc_setatr */
3309 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3310 However NT4 gives a "The information may have been modified by a
3311 computer running Windows NT 5.0" if denied ACEs do not appear before
3314 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
3316 if (sec_ace_equal(ace1, ace2))
3319 if (ace1->type != ace2->type)
3320 return ace2->type - ace1->type;
3322 if (sid_compare(&ace1->trustee, &ace2->trustee))
3323 return sid_compare(&ace1->trustee, &ace2->trustee);
3325 if (ace1->flags != ace2->flags)
3326 return ace1->flags - ace2->flags;
3328 if (ace1->info.mask != ace2->info.mask)
3329 return ace1->info.mask - ace2->info.mask;
3331 if (ace1->size != ace2->size)
3332 return ace1->size - ace2->size;
3334 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3338 static void sort_acl(SEC_ACL *the_acl)
3341 if (!the_acl) return;
3343 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
3345 for (i=1;i<the_acl->num_aces;) {
3346 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3348 for (j=i; j<the_acl->num_aces-1; j++) {
3349 the_acl->ace[j] = the_acl->ace[j+1];
3351 the_acl->num_aces--;
3358 /* convert a SID to a string, either numeric or username/group */
3359 static void convert_sid_to_string(struct cli_state *ipc_cli,
3365 char **domains = NULL;
3366 char **names = NULL;
3367 uint32 *types = NULL;
3368 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3369 sid_to_string(str, sid);
3372 return; /* no lookup desired */
3379 /* Ask LSA to convert the sid to a name */
3381 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3382 pol, 1, sid, &domains,
3384 !domains || !domains[0] || !names || !names[0]) {
3390 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3391 domains[0], lp_winbind_separator(),
3395 /* convert a string to a SID, either numeric or username/group */
3396 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
3402 uint32 *types = NULL;
3403 DOM_SID *sids = NULL;
3405 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3412 if (strncmp(str, "S-", 2) == 0) {
3413 return string_to_sid(sid, str);
3420 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3421 pol, 1, &str, &sids,
3427 sid_copy(sid, &sids[0]);
3434 /* parse an ACE in the same format as print_ace() */
3435 static BOOL parse_ace(struct cli_state *ipc_cli,
3444 unsigned atype, aflags, amask;
3447 const struct perm_value *v;
3453 /* These values discovered by inspection */
3454 static const struct perm_value special_values[] = {
3455 { "R", 0x00120089 },
3456 { "W", 0x00120116 },
3457 { "X", 0x001200a0 },
3458 { "D", 0x00010000 },
3459 { "P", 0x00040000 },
3460 { "O", 0x00080000 },
3464 static const struct perm_value standard_values[] = {
3465 { "READ", 0x001200a9 },
3466 { "CHANGE", 0x001301bf },
3467 { "FULL", 0x001f01ff },
3473 p = strchr_m(str,':');
3474 if (!p) return False;
3477 /* Try to parse numeric form */
3479 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3480 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3484 /* Try to parse text form */
3486 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3491 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3495 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3496 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3497 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3498 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3503 /* Only numeric form accepted for flags at present */
3505 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3506 sscanf(tok, "%i", &aflags))) {
3510 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3514 if (strncmp(tok, "0x", 2) == 0) {
3515 if (sscanf(tok, "%i", &amask) != 1) {
3521 for (v = standard_values; v->perm; v++) {
3522 if (strcmp(tok, v->perm) == 0) {
3533 for (v = special_values; v->perm; v++) {
3534 if (v->perm[0] == *p) {
3540 if (!found) return False;
3550 init_sec_ace(ace, &sid, atype, mask, aflags);
3554 /* add an ACE to a list of ACEs in a SEC_ACL */
3555 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3560 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3564 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3565 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3566 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3567 newacl = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3569 (*the_acl) = newacl;
3574 /* parse a ascii version of a security descriptor */
3575 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3576 struct cli_state *ipc_cli,
3581 const char *p = str;
3585 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3589 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3591 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3592 revision = strtol(tok+9, NULL, 16);
3596 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3597 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3599 !convert_string_to_sid(ipc_cli, pol,
3601 owner_sid, tok+6)) {
3602 DEBUG(5, ("Failed to parse owner sid\n"));
3608 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3609 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3611 !convert_string_to_sid(ipc_cli, pol,
3613 owner_sid, tok+7)) {
3614 DEBUG(5, ("Failed to parse owner sid\n"));
3620 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3621 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3623 !convert_string_to_sid(ipc_cli, pol,
3626 DEBUG(5, ("Failed to parse group sid\n"));
3632 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3633 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3635 !convert_string_to_sid(ipc_cli, pol,
3638 DEBUG(5, ("Failed to parse group sid\n"));
3644 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3646 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3647 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3650 if(!add_ace(&dacl, &ace, ctx)) {
3651 DEBUG(5, ("Failed to add ACL %s\n", tok));
3657 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3659 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3660 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3663 if(!add_ace(&dacl, &ace, ctx)) {
3664 DEBUG(5, ("Failed to add ACL %s\n", tok));
3670 DEBUG(5, ("Failed to parse security descriptor\n"));
3674 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3675 owner_sid, grp_sid, NULL, dacl, &sd_size);
3678 SAFE_FREE(owner_sid);
3684 /* Obtain the current dos attributes */
3685 static DOS_ATTR_DESC *dos_attr_query(SMBCCTX *context,
3687 const char *filename,
3690 time_t m_time = 0, a_time = 0, c_time = 0;
3693 SMB_INO_T inode = 0;
3696 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
3702 /* Obtain the DOS attributes */
3703 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
3705 &c_time, &a_time, &m_time, &inode)) {
3707 errno = smbc_errno(context, &srv->cli);
3708 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
3715 ret->a_time = a_time;
3716 ret->c_time = c_time;
3717 ret->m_time = m_time;
3724 /* parse a ascii version of a security descriptor */
3725 static void dos_attr_parse(SMBCCTX *context,
3730 const char *p = str;
3733 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3735 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
3736 dad->mode = strtol(tok+5, NULL, 16);
3740 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
3741 dad->size = strtoll(tok+5, NULL, 10);
3745 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
3746 dad->a_time = strtoll(tok+7, NULL, 10);
3750 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
3751 dad->c_time = strtoll(tok+7, NULL, 10);
3755 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
3756 dad->m_time = strtoll(tok+7, NULL, 10);
3760 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
3761 dad->inode = strtoll(tok+6, NULL, 10);
3768 /*****************************************************
3769 retrieve the acls for a file
3770 *******************************************************/
3771 static int cacl_get(SMBCCTX *context, TALLOC_CTX *ctx, SMBCSRV *srv,
3772 struct cli_state *ipc_cli, POLICY_HND *pol,
3773 char *filename, char *attr_name, char *buf, int bufsize)
3784 BOOL exclude_nt_revision = False;
3785 BOOL exclude_nt_owner = False;
3786 BOOL exclude_nt_group = False;
3787 BOOL exclude_nt_acl = False;
3788 BOOL exclude_dos_mode = False;
3789 BOOL exclude_dos_size = False;
3790 BOOL exclude_dos_ctime = False;
3791 BOOL exclude_dos_atime = False;
3792 BOOL exclude_dos_mtime = False;
3793 BOOL exclude_dos_inode = False;
3794 BOOL numeric = True;
3795 BOOL determine_size = (bufsize == 0);
3799 fstring name_sandbox;
3803 time_t m_time = 0, a_time = 0, c_time = 0;
3807 struct cli_state *cli = &srv->cli;
3809 /* Copy name so we can strip off exclusions (if any are specified) */
3810 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
3812 /* Ensure name is null terminated */
3813 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
3815 /* Play in the sandbox */
3816 name = name_sandbox;
3818 /* If there are any exclusions, point to them and mask them from name */
3819 if ((pExclude = strchr(name, '!')) != NULL)
3824 all = (StrnCaseCmp(name, "system.*", 8) == 0);
3825 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
3826 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
3827 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
3828 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
3829 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
3830 numeric = (* (name + strlen(name) - 1) != '+');
3832 /* Look for exclusions from "all" requests */
3833 if (all || all_nt || all_dos) {
3835 /* Exclusions are delimited by '!' */
3836 for (; pExclude != NULL; pExclude = (p == NULL ? NULL : p + 1)) {
3838 /* Find end of this exclusion name */
3839 if ((p = strchr(pExclude, '!')) != NULL)
3844 /* Which exclusion name is this? */
3845 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
3846 exclude_nt_revision = True;
3848 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
3849 exclude_nt_owner = True;
3851 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
3852 exclude_nt_group = True;
3854 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
3855 exclude_nt_acl = True;
3857 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
3858 exclude_dos_mode = True;
3860 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
3861 exclude_dos_size = True;
3863 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
3864 exclude_dos_ctime = True;
3866 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
3867 exclude_dos_atime = True;
3869 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
3870 exclude_dos_mtime = True;
3872 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
3873 exclude_dos_inode = True;
3876 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
3887 * If we are (possibly) talking to an NT or new system and some NT
3888 * attributes have been requested...
3890 if (ipc_cli && (all || some_nt || all_nt_acls)) {
3891 /* Point to the portion after "system.nt_sec_desc." */
3892 name += 19; /* if (all) this will be invalid but unused */
3894 /* ... then obtain any NT attributes which were requested */
3895 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3898 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3899 filename, cli_errstr(cli)));
3904 sd = cli_query_secdesc(cli, fnum, ctx);
3908 ("cacl_get Failed to query old descriptor\n"));
3913 cli_close(cli, fnum);
3915 if (! exclude_nt_revision) {
3916 if (all || all_nt) {
3917 if (determine_size) {
3918 p = talloc_asprintf(ctx,
3927 n = snprintf(buf, bufsize,
3928 "REVISION:%d", sd->revision);
3930 } else if (StrCaseCmp(name, "revision") == 0) {
3931 if (determine_size) {
3932 p = talloc_asprintf(ctx, "%d",
3940 n = snprintf(buf, bufsize, "%d",
3945 if (!determine_size && n > bufsize) {
3954 if (! exclude_nt_owner) {
3955 /* Get owner and group sid */
3956 if (sd->owner_sid) {
3957 convert_sid_to_string(ipc_cli, pol,
3962 fstrcpy(sidstr, "");
3965 if (all || all_nt) {
3966 if (determine_size) {
3967 p = talloc_asprintf(ctx, ",OWNER:%s",
3975 n = snprintf(buf, bufsize,
3976 ",OWNER:%s", sidstr);
3978 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3979 if (determine_size) {
3980 p = talloc_asprintf(ctx, "%s", sidstr);
3987 n = snprintf(buf, bufsize, "%s",
3992 if (!determine_size && n > bufsize) {
4001 if (! exclude_nt_group) {
4003 convert_sid_to_string(ipc_cli, pol,
4007 fstrcpy(sidstr, "");
4010 if (all || all_nt) {
4011 if (determine_size) {
4012 p = talloc_asprintf(ctx, ",GROUP:%s",
4020 n = snprintf(buf, bufsize,
4021 ",GROUP:%s", sidstr);
4023 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4024 if (determine_size) {
4025 p = talloc_asprintf(ctx, "%s", sidstr);
4032 n = snprintf(buf, bufsize, "%s", sidstr);
4036 if (!determine_size && n > bufsize) {
4045 if (! exclude_nt_acl) {
4046 /* Add aces to value buffer */
4047 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4049 SEC_ACE *ace = &sd->dacl->ace[i];
4050 convert_sid_to_string(ipc_cli, pol,
4054 if (all || all_nt) {
4055 if (determine_size) {
4056 p = talloc_asprintf(
4072 ",ACL:%s:%d/%d/0x%08x",
4078 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4079 StrCaseCmp(name + 3, sidstr) == 0) ||
4080 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4081 StrCaseCmp(name + 4, sidstr) == 0)) {
4082 if (determine_size) {
4083 p = talloc_asprintf(
4095 n = snprintf(buf, bufsize,
4101 } else if (all_nt_acls) {
4102 if (determine_size) {
4103 p = talloc_asprintf(
4105 "%s%s:%d/%d/0x%08x",
4117 n = snprintf(buf, bufsize,
4118 "%s%s:%d/%d/0x%08x",
4136 /* Restore name pointer to its original value */
4140 if (all || some_dos) {
4141 /* Point to the portion after "system.dos_attr." */
4142 name += 16; /* if (all) this will be invalid but unused */
4144 /* Obtain the DOS attributes */
4145 if (!smbc_getatr(context, srv, filename, &mode, &size,
4146 &c_time, &a_time, &m_time, &ino)) {
4148 errno = smbc_errno(context, &srv->cli);
4153 if (! exclude_dos_mode) {
4154 if (all || all_dos) {
4155 if (determine_size) {
4156 p = talloc_asprintf(ctx,
4169 n = snprintf(buf, bufsize,
4177 } else if (StrCaseCmp(name, "mode") == 0) {
4178 if (determine_size) {
4179 p = talloc_asprintf(ctx, "0x%x", mode);
4186 n = snprintf(buf, bufsize, "0x%x", mode);
4190 if (!determine_size && n > bufsize) {
4199 if (! exclude_dos_size) {
4200 if (all || all_dos) {
4201 if (determine_size) {
4202 p = talloc_asprintf(
4205 (unsigned long long) size);
4212 n = snprintf(buf, bufsize,
4214 (unsigned long long) size);
4216 } else if (StrCaseCmp(name, "size") == 0) {
4217 if (determine_size) {
4218 p = talloc_asprintf(
4221 (unsigned long long) size);
4228 n = snprintf(buf, bufsize,
4230 (unsigned long long) size);
4234 if (!determine_size && n > bufsize) {
4243 if (! exclude_dos_ctime) {
4244 if (all || all_dos) {
4245 if (determine_size) {
4246 p = talloc_asprintf(ctx,
4255 n = snprintf(buf, bufsize,
4256 ",C_TIME:%lu", c_time);
4258 } else if (StrCaseCmp(name, "c_time") == 0) {
4259 if (determine_size) {
4260 p = talloc_asprintf(ctx, "%lu", c_time);
4267 n = snprintf(buf, bufsize, "%lu", c_time);
4271 if (!determine_size && n > bufsize) {
4280 if (! exclude_dos_atime) {
4281 if (all || all_dos) {
4282 if (determine_size) {
4283 p = talloc_asprintf(ctx,
4292 n = snprintf(buf, bufsize,
4293 ",A_TIME:%lu", a_time);
4295 } else if (StrCaseCmp(name, "a_time") == 0) {
4296 if (determine_size) {
4297 p = talloc_asprintf(ctx, "%lu", a_time);
4304 n = snprintf(buf, bufsize, "%lu", a_time);
4308 if (!determine_size && n > bufsize) {
4317 if (! exclude_dos_mtime) {
4318 if (all || all_dos) {
4319 if (determine_size) {
4320 p = talloc_asprintf(ctx,
4329 n = snprintf(buf, bufsize,
4330 ",M_TIME:%lu", m_time);
4332 } else if (StrCaseCmp(name, "m_time") == 0) {
4333 if (determine_size) {
4334 p = talloc_asprintf(ctx, "%lu", m_time);
4341 n = snprintf(buf, bufsize, "%lu", m_time);
4345 if (!determine_size && n > bufsize) {
4354 if (! exclude_dos_inode) {
4355 if (all || all_dos) {
4356 if (determine_size) {
4357 p = talloc_asprintf(
4360 (unsigned long long) ino);
4367 n = snprintf(buf, bufsize,
4369 (unsigned long long) ino);
4371 } else if (StrCaseCmp(name, "inode") == 0) {
4372 if (determine_size) {
4373 p = talloc_asprintf(
4376 (unsigned long long) ino);
4383 n = snprintf(buf, bufsize,
4385 (unsigned long long) ino);
4389 if (!determine_size && n > bufsize) {
4398 /* Restore name pointer to its original value */
4411 /*****************************************************
4412 set the ACLs on a file given an ascii description
4413 *******************************************************/
4414 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
4415 struct cli_state *ipc_cli, POLICY_HND *pol,
4416 const char *filename, const char *the_acl,
4417 int mode, int flags)
4421 SEC_DESC *sd = NULL, *old;
4422 SEC_ACL *dacl = NULL;
4423 DOM_SID *owner_sid = NULL;
4424 DOM_SID *grp_sid = NULL;
4429 BOOL numeric = True;
4431 /* the_acl will be null for REMOVE_ALL operations */
4433 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4437 /* if this is to set the entire ACL... */
4438 if (*the_acl == '*') {
4439 /* ... then increment past the first colon */
4443 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4444 CONST_DISCARD(char *, the_acl));
4452 /* The desired access below is the only one I could find that works
4453 with NT4, W2KP and Samba */
4455 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4458 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4459 filename, cli_errstr(cli)));
4464 old = cli_query_secdesc(cli, fnum, ctx);
4467 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4472 cli_close(cli, fnum);
4475 case SMBC_XATTR_MODE_REMOVE_ALL:
4476 old->dacl->num_aces = 0;
4477 SAFE_FREE(old->dacl->ace);
4478 SAFE_FREE(old->dacl);
4483 case SMBC_XATTR_MODE_REMOVE:
4484 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4487 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4488 if (sec_ace_equal(&sd->dacl->ace[i],
4489 &old->dacl->ace[j])) {
4491 for (k=j; k<old->dacl->num_aces-1;k++) {
4492 old->dacl->ace[k] = old->dacl->ace[k+1];
4494 old->dacl->num_aces--;
4495 if (old->dacl->num_aces == 0) {
4496 SAFE_FREE(old->dacl->ace);
4497 SAFE_FREE(old->dacl);
4514 case SMBC_XATTR_MODE_ADD:
4515 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4518 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4519 if (sid_equal(&sd->dacl->ace[i].trustee,
4520 &old->dacl->ace[j].trustee)) {
4521 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4526 old->dacl->ace[j] = sd->dacl->ace[i];
4532 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4538 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4539 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4545 case SMBC_XATTR_MODE_SET:
4547 owner_sid = old->owner_sid;
4548 grp_sid = old->grp_sid;
4552 case SMBC_XATTR_MODE_CHOWN:
4553 owner_sid = sd->owner_sid;
4556 case SMBC_XATTR_MODE_CHGRP:
4557 grp_sid = sd->grp_sid;
4561 /* Denied ACE entries must come before allowed ones */
4562 sort_acl(old->dacl);
4564 /* Create new security descriptor and set it */
4565 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4566 owner_sid, grp_sid, NULL, dacl, &sd_size);
4568 fnum = cli_nt_create(cli, filename,
4569 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4572 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4573 filename, cli_errstr(cli)));
4578 if (!cli_set_secdesc(cli, fnum, sd)) {
4579 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4586 cli_close(cli, fnum);
4596 int smbc_setxattr_ctx(SMBCCTX *context,
4607 fstring server, share, user, password, workgroup;
4613 if (!context || !context->internal ||
4614 !context->internal->_initialized) {
4616 errno = EINVAL; /* Best I can think of ... */
4628 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n", fname, name, (int) size, (const char*)value));
4630 if (smbc_parse_path(context, fname,
4631 server, sizeof(server),
4632 share, sizeof(share),
4635 password, sizeof(password),
4641 if (user[0] == (char)0) fstrcpy(user, context->user);
4643 fstrcpy(workgroup, context->workgroup);
4645 srv = smbc_server(context, server, share, workgroup, user, password);
4647 return -1; /* errno set by smbc_server */
4650 if (! srv->no_nt_session) {
4651 ipc_srv = smbc_attr_server(context, server, share,
4652 workgroup, user, password,
4654 srv->no_nt_session = True;
4659 ctx = talloc_init("smbc_setxattr");
4666 * Are they asking to set the entire set of known attributes?
4668 if (StrCaseCmp(name, "system.*") == 0 ||
4669 StrCaseCmp(name, "system.*+") == 0) {
4672 talloc_asprintf(ctx, "%s:%s", name+7, (const char *) value);
4680 ret = cacl_set(ctx, &srv->cli,
4681 &ipc_srv->cli, &pol, path,
4684 ? SMBC_XATTR_MODE_SET
4685 : SMBC_XATTR_MODE_ADD),
4691 /* get a DOS Attribute Descriptor with current attributes */
4692 dad = dos_attr_query(context, ctx, path, srv);
4694 /* Overwrite old with new, using what was provided */
4695 dos_attr_parse(context, dad, srv, namevalue);
4697 /* Set the new DOS attributes */
4698 if (! smbc_setatr(context, srv, path,
4704 /* cause failure if NT failed too */
4709 /* we only fail if both NT and DOS sets failed */
4710 if (ret < 0 && ! dad) {
4711 ret = -1; /* in case dad was null */
4717 talloc_destroy(ctx);
4722 * Are they asking to set an access control element or to set
4723 * the entire access control list?
4725 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4726 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4727 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4728 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4729 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4733 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4736 ret = -1; /* errno set by smbc_server() */
4738 else if (! namevalue) {
4742 ret = cacl_set(ctx, &srv->cli,
4743 &ipc_srv->cli, &pol, path,
4746 ? SMBC_XATTR_MODE_SET
4747 : SMBC_XATTR_MODE_ADD),
4750 talloc_destroy(ctx);
4755 * Are they asking to set the owner?
4757 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4758 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
4762 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4766 ret = -1; /* errno set by smbc_server() */
4768 else if (! namevalue) {
4772 ret = cacl_set(ctx, &srv->cli,
4773 &ipc_srv->cli, &pol, path,
4774 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4776 talloc_destroy(ctx);
4781 * Are they asking to set the group?
4783 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4784 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
4788 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4791 /* errno set by smbc_server() */
4794 else if (! namevalue) {
4798 ret = cacl_set(ctx, &srv->cli,
4799 &ipc_srv->cli, &pol, path,
4800 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4802 talloc_destroy(ctx);
4807 * Are they asking to set a DOS attribute?
4809 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4810 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4811 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4812 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4813 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
4815 /* get a DOS Attribute Descriptor with current attributes */
4816 dad = dos_attr_query(context, ctx, path, srv);
4819 talloc_asprintf(ctx, "%s:%s", name+16, (const char *) value);
4824 /* Overwrite old with provided new params */
4825 dos_attr_parse(context, dad, srv, namevalue);
4827 /* Set the new DOS attributes */
4828 ret2 = smbc_setatr(context, srv, path,
4834 /* ret2 has True (success) / False (failure) */
4845 talloc_destroy(ctx);
4849 /* Unsupported attribute name */
4850 talloc_destroy(ctx);
4855 int smbc_getxattr_ctx(SMBCCTX *context,
4864 fstring server, share, user, password, workgroup;
4870 if (!context || !context->internal ||
4871 !context->internal->_initialized) {
4873 errno = EINVAL; /* Best I can think of ... */
4885 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
4887 if (smbc_parse_path(context, fname,
4888 server, sizeof(server),
4889 share, sizeof(share),
4892 password, sizeof(password),
4898 if (user[0] == (char)0) fstrcpy(user, context->user);
4900 fstrcpy(workgroup, context->workgroup);
4902 srv = smbc_server(context, server, share, workgroup, user, password);
4904 return -1; /* errno set by smbc_server */
4907 if (! srv->no_nt_session) {
4908 ipc_srv = smbc_attr_server(context, server, share,
4909 workgroup, user, password,
4912 srv->no_nt_session = True;
4918 ctx = talloc_init("smbc:getxattr");
4924 /* Are they requesting a supported attribute? */
4925 if (StrCaseCmp(name, "system.*") == 0 ||
4926 StrnCaseCmp(name, "system.*!", 9) == 0 ||
4927 StrCaseCmp(name, "system.*+") == 0 ||
4928 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
4929 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4930 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
4931 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4932 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
4933 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4934 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4935 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
4936 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4937 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
4938 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4939 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
4940 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4941 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
4942 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4943 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
4944 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4945 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4946 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
4947 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
4950 ret = cacl_get(context, ctx, srv,
4951 ipc_srv == NULL ? NULL : &ipc_srv->cli,
4953 CONST_DISCARD(char *, name),
4954 CONST_DISCARD(char *, value), size);
4955 if (ret < 0 && errno == 0) {
4956 errno = smbc_errno(context, &srv->cli);
4958 talloc_destroy(ctx);
4962 /* Unsupported attribute name */
4963 talloc_destroy(ctx);
4969 int smbc_removexattr_ctx(SMBCCTX *context,
4976 fstring server, share, user, password, workgroup;
4981 if (!context || !context->internal ||
4982 !context->internal->_initialized) {
4984 errno = EINVAL; /* Best I can think of ... */
4996 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
4998 if (smbc_parse_path(context, fname,
4999 server, sizeof(server),
5000 share, sizeof(share),
5003 password, sizeof(password),
5009 if (user[0] == (char)0) fstrcpy(user, context->user);
5011 fstrcpy(workgroup, context->workgroup);
5013 srv = smbc_server(context, server, share, workgroup, user, password);
5015 return -1; /* errno set by smbc_server */
5018 if (! srv->no_nt_session) {
5019 ipc_srv = smbc_attr_server(context, server, share,
5020 workgroup, user, password,
5022 srv->no_nt_session = True;
5028 return -1; /* errno set by smbc_attr_server */
5031 ctx = talloc_init("smbc_removexattr");
5037 /* Are they asking to set the entire ACL? */
5038 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5039 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5042 ret = cacl_set(ctx, &srv->cli,
5043 &ipc_srv->cli, &pol, path,
5044 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5045 talloc_destroy(ctx);
5050 * Are they asking to remove one or more spceific security descriptor
5053 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5054 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5055 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5056 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5057 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5058 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5059 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5062 ret = cacl_set(ctx, &srv->cli,
5063 &ipc_srv->cli, &pol, path,
5064 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5065 talloc_destroy(ctx);
5069 /* Unsupported attribute name */
5070 talloc_destroy(ctx);
5075 int smbc_listxattr_ctx(SMBCCTX *context,
5081 * This isn't quite what listxattr() is supposed to do. This returns
5082 * the complete set of attribute names, always, rather than only those
5083 * attribute names which actually exist for a file. Hmmm...
5085 const char supported[] =
5088 "system.nt_sec_desc.revision\0"
5089 "system.nt_sec_desc.owner\0"
5090 "system.nt_sec_desc.owner+\0"
5091 "system.nt_sec_desc.group\0"
5092 "system.nt_sec_desc.group+\0"
5093 "system.nt_sec_desc.acl.*\0"
5094 "system.nt_sec_desc.acl\0"
5095 "system.nt_sec_desc.acl+\0"
5096 "system.nt_sec_desc.*\0"
5097 "system.nt_sec_desc.*+\0"
5098 "system.dos_attr.*\0"
5099 "system.dos_attr.mode\0"
5100 "system.dos_attr.c_time\0"
5101 "system.dos_attr.a_time\0"
5102 "system.dos_attr.m_time\0"
5106 return sizeof(supported);
5109 if (sizeof(supported) > size) {
5114 /* this can't be strcpy() because there are embedded null characters */
5115 memcpy(list, supported, sizeof(supported));
5116 return sizeof(supported);
5121 * Open a print file to be written to by other calls
5124 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
5126 fstring server, share, user, password;
5129 if (!context || !context->internal ||
5130 !context->internal->_initialized) {
5144 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5146 if (smbc_parse_path(context, fname,
5147 server, sizeof(server),
5148 share, sizeof(share),
5151 password, sizeof(password),
5157 /* What if the path is empty, or the file exists? */
5159 return context->open(context, fname, O_WRONLY, 666);
5164 * Routine to print a file on a remote server ...
5166 * We open the file, which we assume to be on a remote server, and then
5167 * copy it to a print file on the share specified by printq.
5170 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
5172 SMBCFILE *fid1, *fid2;
5173 int bytes, saverr, tot_bytes = 0;
5176 if (!c_file || !c_file->internal->_initialized || !c_print ||
5177 !c_print->internal->_initialized) {
5184 if (!fname && !printq) {
5191 /* Try to open the file for reading ... */
5193 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5195 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5196 return -1; /* smbc_open sets errno */
5200 /* Now, try to open the printer file for writing */
5202 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5204 saverr = errno; /* Save errno */
5205 c_file->close_fn(c_file, fid1);
5211 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5215 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5218 c_file->close_fn(c_file, fid1);
5219 c_print->close_fn(c_print, fid2);
5228 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5229 c_print->close_fn(c_print, fid2);
5243 * Routine to list print jobs on a printer share ...
5246 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
5249 fstring server, share, user, password, workgroup;
5252 if (!context || !context->internal ||
5253 !context->internal->_initialized) {
5267 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5269 if (smbc_parse_path(context, fname,
5270 server, sizeof(server),
5271 share, sizeof(share),
5274 password, sizeof(password),
5280 if (user[0] == (char)0) fstrcpy(user, context->user);
5282 fstrcpy(workgroup, context->workgroup);
5284 srv = smbc_server(context, server, share, workgroup, user, password);
5288 return -1; /* errno set by smbc_server */
5292 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
5294 errno = smbc_errno(context, &srv->cli);
5304 * Delete a print job from a remote printer share
5307 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
5310 fstring server, share, user, password, workgroup;
5314 if (!context || !context->internal ||
5315 !context->internal->_initialized) {
5329 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5331 if (smbc_parse_path(context, fname,
5332 server, sizeof(server),
5333 share, sizeof(share),
5336 password, sizeof(password),
5342 if (user[0] == (char)0) fstrcpy(user, context->user);
5344 fstrcpy(workgroup, context->workgroup);
5346 srv = smbc_server(context, server, share, workgroup, user, password);
5350 return -1; /* errno set by smbc_server */
5354 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5357 errno = smbc_errno(context, &srv->cli);
5358 else if (err == ERRnosuchprintjob)
5369 * Get a new empty handle to fill in with your own info
5371 SMBCCTX * smbc_new_context(void)
5375 context = SMB_MALLOC_P(SMBCCTX);
5381 ZERO_STRUCTP(context);
5383 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5384 if (!context->internal) {
5389 ZERO_STRUCTP(context->internal);
5392 /* ADD REASONABLE DEFAULTS */
5394 context->timeout = 20000; /* 20 seconds */
5396 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5397 context->options.urlencode_readdir_entries = False;/* backward compat */
5398 context->options.one_share_per_server = False;/* backward compat */
5400 context->open = smbc_open_ctx;
5401 context->creat = smbc_creat_ctx;
5402 context->read = smbc_read_ctx;
5403 context->write = smbc_write_ctx;
5404 context->close_fn = smbc_close_ctx;
5405 context->unlink = smbc_unlink_ctx;
5406 context->rename = smbc_rename_ctx;
5407 context->lseek = smbc_lseek_ctx;
5408 context->stat = smbc_stat_ctx;
5409 context->fstat = smbc_fstat_ctx;
5410 context->opendir = smbc_opendir_ctx;
5411 context->closedir = smbc_closedir_ctx;
5412 context->readdir = smbc_readdir_ctx;
5413 context->getdents = smbc_getdents_ctx;
5414 context->mkdir = smbc_mkdir_ctx;
5415 context->rmdir = smbc_rmdir_ctx;
5416 context->telldir = smbc_telldir_ctx;
5417 context->lseekdir = smbc_lseekdir_ctx;
5418 context->fstatdir = smbc_fstatdir_ctx;
5419 context->chmod = smbc_chmod_ctx;
5420 context->utimes = smbc_utimes_ctx;
5421 context->setxattr = smbc_setxattr_ctx;
5422 context->getxattr = smbc_getxattr_ctx;
5423 context->removexattr = smbc_removexattr_ctx;
5424 context->listxattr = smbc_listxattr_ctx;
5425 context->open_print_job = smbc_open_print_job_ctx;
5426 context->print_file = smbc_print_file_ctx;
5427 context->list_print_jobs = smbc_list_print_jobs_ctx;
5428 context->unlink_print_job = smbc_unlink_print_job_ctx;
5430 context->callbacks.check_server_fn = smbc_check_server;
5431 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5433 smbc_default_cache_functions(context);
5441 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5442 * and thus you'll be leaking memory if not handled properly.
5445 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
5454 DEBUG(1,("Performing aggressive shutdown.\n"));
5456 f = context->internal->_files;
5458 context->close_fn(context, f);
5461 context->internal->_files = NULL;
5463 /* First try to remove the servers the nice way. */
5464 if (context->callbacks.purge_cached_fn(context)) {
5467 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
5468 s = context->internal->_servers;
5470 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
5471 cli_shutdown(&s->cli);
5472 context->callbacks.remove_cached_srv_fn(context, s);
5474 DLIST_REMOVE(context->internal->_servers, s);
5478 context->internal->_servers = NULL;
5482 /* This is the polite way */
5483 if (context->callbacks.purge_cached_fn(context)) {
5484 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
5488 if (context->internal->_servers) {
5489 DEBUG(1, ("Active servers in context, free_context failed.\n"));
5493 if (context->internal->_files) {
5494 DEBUG(1, ("Active files in context, free_context failed.\n"));
5500 /* Things we have to clean up */
5501 SAFE_FREE(context->workgroup);
5502 SAFE_FREE(context->netbios_name);
5503 SAFE_FREE(context->user);
5505 DEBUG(3, ("Context %p succesfully freed\n", context));
5506 SAFE_FREE(context->internal);
5513 * Initialise the library etc
5515 * We accept a struct containing handle information.
5516 * valid values for info->debug from 0 to 100,
5517 * and insist that info->fn must be non-null.
5519 SMBCCTX * smbc_init_context(SMBCCTX * context)
5523 char *user = NULL, *home = NULL;
5525 if (!context || !context->internal) {
5530 /* Do not initialise the same client twice */
5531 if (context->internal->_initialized) {
5535 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
5542 if (!smbc_initialized) {
5543 /* Do some library wide intialisations the first time we get called */
5544 BOOL conf_loaded = False;
5546 /* Set this to what the user wants */
5547 DEBUGLEVEL = context->debug;
5549 setup_logging( "libsmbclient", True);
5551 /* Here we would open the smb.conf file if needed ... */
5553 load_interfaces(); /* Load the list of interfaces ... */
5555 in_client = True; /* FIXME, make a param */
5557 home = getenv("HOME");
5559 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5560 if (lp_load(conf, True, False, False)) {
5563 DEBUG(5, ("Could not load config file: %s\n",
5570 * Well, if that failed, try the dyn_CONFIGFILE
5571 * Which points to the standard locn, and if that
5572 * fails, silently ignore it and use the internal
5576 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
5577 DEBUG(5, ("Could not load config file: %s\n",
5581 * We loaded the global config file. Now lets
5582 * load user-specific modifications to the
5585 slprintf(conf, sizeof(conf),
5586 "%s/.smb/smb.conf.append", home);
5587 if (!lp_load(conf, True, False, False)) {
5589 ("Could not append config file: "
5596 reopen_logs(); /* Get logging working ... */
5599 * Block SIGPIPE (from lib/util_sock.c: write())
5600 * It is not needed and should not stop execution
5602 BlockSignals(True, SIGPIPE);
5604 /* Done with one-time initialisation */
5605 smbc_initialized = 1;
5609 if (!context->user) {
5611 * FIXME: Is this the best way to get the user info?
5613 user = getenv("USER");
5614 /* walk around as "guest" if no username can be found */
5615 if (!user) context->user = SMB_STRDUP("guest");
5616 else context->user = SMB_STRDUP(user);
5619 if (!context->netbios_name) {
5621 * We try to get our netbios name from the config. If that fails we fall
5622 * back on constructing our netbios name from our hostname etc
5624 if (global_myname()) {
5625 context->netbios_name = SMB_STRDUP(global_myname());
5629 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
5632 context->netbios_name = SMB_MALLOC(17);
5633 if (!context->netbios_name) {
5637 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
5641 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
5643 if (!context->workgroup) {
5644 if (lp_workgroup()) {
5645 context->workgroup = SMB_STRDUP(lp_workgroup());
5648 /* TODO: Think about a decent default workgroup */
5649 context->workgroup = SMB_STRDUP("samba");
5653 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
5655 /* shortest timeout is 1 second */
5656 if (context->timeout > 0 && context->timeout < 1000)
5657 context->timeout = 1000;
5660 * FIXME: Should we check the function pointers here?
5663 context->internal->_initialized = 1;
5669 /* Return the verion of samba, and thus libsmbclient */
5673 return samba_version_string();