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;
83 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file);
84 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence);
86 extern BOOL in_client;
89 * Is the logging working / configfile read ?
91 static int smbc_initialized = 0;
94 hex2int( unsigned int _char )
96 if ( _char >= 'A' && _char <='F')
97 return _char - 'A' + 10;
98 if ( _char >= 'a' && _char <='f')
99 return _char - 'a' + 10;
100 if ( _char >= '0' && _char <='9')
108 * Convert strings of %xx to their single character equivalent. Each 'x' must
109 * be a valid hexadecimal digit, or that % sequence is left undecoded.
111 * dest may, but need not be, the same pointer as src.
113 * Returns the number of % sequences which could not be converted due to lack
114 * of two following hexadecimal digits.
117 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
119 int old_length = strlen(src);
125 if ( old_length == 0 ) {
130 while ( i < old_length ) {
131 unsigned char character = src[ i++ ];
133 if (character == '%') {
134 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
135 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
137 /* Replace valid sequence */
138 if (a != -1 && b != -1) {
140 /* Replace valid %xx sequence with %dd */
141 character = (a * 16) + b;
143 if (character == '\0') {
144 break; /* Stop at %00 */
159 strncpy(dest, temp, max_dest_len);
167 * Convert any characters not specifically allowed in a URL into their %xx
170 * Returns the remaining buffer length.
173 smbc_urlencode(char * dest, char * src, int max_dest_len)
175 char hex[] = "0123456789ABCDEF";
177 for (; *src != '\0' && max_dest_len >= 3; src++) {
189 *dest++ = hex[(*src >> 4) & 0x0f];
190 *dest++ = hex[*src & 0x0f];
205 * Function to parse a path and turn it into components
207 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
208 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
209 * general format ("smb:" only; we do not look for "cifs:").
213 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
217 * smb:// Show all workgroups.
219 * The method of locating the list of workgroups varies
220 * depending upon the setting of the context variable
221 * context->options.browse_max_lmb_count. This value
222 * determine the maximum number of local master browsers to
223 * query for the list of workgroups. In order to ensure that
224 * a complete list of workgroups is obtained, all master
225 * browsers must be queried, but if there are many
226 * workgroups, the time spent querying can begin to add up.
227 * For small networks (not many workgroups), it is suggested
228 * that this variable be set to 0, indicating query all local
229 * master browsers. When the network has many workgroups, a
230 * reasonable setting for this variable might be around 3.
232 * smb://name/ if name<1D> or name<1B> exists, list servers in
233 * workgroup, else, if name<20> exists, list all shares
236 * If "options" are provided, this function returns the entire option list as a
237 * string, for later parsing by the caller. Note that currently, no options
241 static const char *smbc_prefix = "smb:";
244 smbc_parse_path(SMBCCTX *context,
246 char *server, int server_len,
247 char *share, int share_len,
248 char *path, int path_len,
249 char *user, int user_len,
250 char *password, int password_len,
251 char *options, int options_len)
259 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
260 if (options != NULL && options_len > 0) {
261 options[0] = (char)0;
265 /* see if it has the right prefix */
266 len = strlen(smbc_prefix);
267 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
268 return -1; /* What about no smb: ? */
273 /* Watch the test below, we are testing to see if we should exit */
275 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
277 DEBUG(1, ("Invalid path (does not begin with smb://"));
282 p += 2; /* Skip the double slash */
284 /* See if any options were specified */
285 if ((q = strrchr(p, '?')) != NULL ) {
286 /* There are options. Null terminate here and point to them */
289 DEBUG(4, ("Found options '%s'", q));
291 /* Copy the options */
292 if (options != NULL && options_len > 0) {
293 safe_strcpy(options, q, options_len - 1);
302 strncpy(server, context->workgroup,
303 (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
309 * ok, its for us. Now parse out the server, share etc.
311 * However, we want to parse out [[domain;]user[:password]@] if it
315 /* check that '@' occurs before '/', if '/' exists at all */
316 q = strchr_m(p, '@');
317 r = strchr_m(p, '/');
318 if (q && (!r || q < r)) {
319 pstring username, passwd, domain;
320 const char *u = userinfo;
322 next_token(&p, userinfo, "@", sizeof(fstring));
324 username[0] = passwd[0] = domain[0] = 0;
326 if (strchr_m(u, ';')) {
328 next_token(&u, domain, ";", sizeof(fstring));
332 if (strchr_m(u, ':')) {
334 next_token(&u, username, ":", sizeof(fstring));
341 pstrcpy(username, u);
346 strncpy(user, username, user_len); /* FIXME, domain */
349 strncpy(password, passwd, password_len);
353 if (!next_token(&p, server, "/", sizeof(fstring))) {
359 if (*p == (char)0) goto decoding; /* That's it ... */
361 if (!next_token(&p, share, "/", sizeof(fstring))) {
367 safe_strcpy(path, p, path_len - 1);
369 all_string_sub(path, "/", "\\", 0);
372 (void) smbc_urldecode(path, path, path_len);
373 (void) smbc_urldecode(server, server, server_len);
374 (void) smbc_urldecode(share, share, share_len);
375 (void) smbc_urldecode(user, user, user_len);
376 (void) smbc_urldecode(password, password, password_len);
382 * Verify that the options specified in a URL are valid
384 static int smbc_check_options(char *server, char *share, char *path, char *options)
386 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' path='%s' options='%s'\n", server, share, path, options));
388 /* No options at all is always ok */
389 if (! *options) return 0;
391 /* Currently, we don't support any options. */
396 * Convert an SMB error into a UNIX error ...
398 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
400 int ret = cli_errno(c);
402 if (cli_is_dos_error(c)) {
406 cli_dos_error(c, &eclass, &ecode);
408 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
409 (int)eclass, (int)ecode, (int)ecode, ret));
413 status = cli_nt_error(c);
415 DEBUG(3,("smbc errno %s -> %d\n",
416 nt_errstr(status), ret));
423 * Check a server for being alive and well.
424 * returns 0 if the server is in shape. Returns 1 on error
426 * Also useable outside libsmbclient to enable external cache
427 * to do some checks too.
429 int smbc_check_server(SMBCCTX * context, SMBCSRV * server)
431 if ( send_keepalive(server->cli.fd) == False )
434 /* connection is ok */
439 * Remove a server from the cached server list it's unused.
440 * On success, 0 is returned. 1 is returned if the server could not be removed.
442 * Also useable outside libsmbclient
444 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
448 /* are we being fooled ? */
449 if (!context || !context->internal ||
450 !context->internal->_initialized || !srv) return 1;
453 /* Check all open files/directories for a relation with this server */
454 for (file = context->internal->_files; file; file=file->next) {
455 if (file->srv == srv) {
457 DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n",
463 DLIST_REMOVE(context->internal->_servers, srv);
465 cli_shutdown(&srv->cli);
467 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
469 context->callbacks.remove_cached_srv_fn(context, srv);
474 SMBCSRV *find_server(SMBCCTX *context,
486 srv = context->callbacks.get_cached_srv_fn(context, server, share,
487 workgroup, username);
489 if (!auth_called && !srv && (!username[0] || !password[0])) {
490 context->callbacks.auth_fn(server, share,
491 workgroup, sizeof(fstring),
492 username, sizeof(fstring),
493 password, sizeof(fstring));
495 * However, smbc_auth_fn may have picked up info relating to
496 * an existing connection, so try for an existing connection
500 goto check_server_cache;
505 if (context->callbacks.check_server_fn(context, srv)) {
507 * This server is no good anymore
508 * Try to remove it and check for more possible
509 * servers in the cache
511 if (context->callbacks.remove_unused_server_fn(context,
514 * We could not remove the server completely,
515 * remove it from the cache so we will not get
516 * it again. It will be removed when the last
517 * file/dir is closed.
519 context->callbacks.remove_cached_srv_fn(context,
524 * Maybe there are more cached connections to this
527 goto check_server_cache;
537 * Connect to a server, possibly on an existing connection
539 * Here, what we want to do is: If the server and username
540 * match an existing connection, reuse that, otherwise, establish a
543 * If we have to create a new connection, call the auth_fn to get the
544 * info we need, unless the username and password were passed in.
547 SMBCSRV *smbc_server(SMBCCTX *context,
548 const char *server, const char *share,
549 fstring workgroup, fstring username,
554 struct nmb_name called, calling;
555 const char *server_n = server;
558 int tried_reverse = 0;
561 const char *username_used;
566 if (server[0] == 0) {
571 srv = find_server(context, server, share,
572 workgroup, username, password);
575 * If we found a connection and we're only allowed one share per
578 if (srv && *share != '\0' && context->options.one_share_per_server) {
581 * ... then if there's no current connection to the share,
582 * connect to it. find_server(), or rather the function
583 * pointed to by context->callbacks.get_cached_srv_fn which
584 * was called by find_server(), will have issued a tree
585 * disconnect if the requested share is not the same as the
586 * one that was already connected.
588 if (srv->cli.cnum == (uint16) -1) {
589 /* Ensure we have accurate auth info */
590 context->callbacks.auth_fn(server, share,
591 workgroup, sizeof(fstring),
592 username, sizeof(fstring),
593 password, sizeof(fstring));
595 if (! cli_send_tconX(&srv->cli, share, "?????",
596 password, strlen(password)+1)) {
598 errno = smbc_errno(context, &srv->cli);
599 cli_shutdown(&srv->cli);
600 context->callbacks.remove_cached_srv_fn(context, srv);
604 /* Regenerate the dev value since it's based on both server and share */
606 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
611 /* If we have a connection... */
614 /* ... then we're done here. Give 'em what they came for. */
618 make_nmb_name(&calling, context->netbios_name, 0x0);
619 make_nmb_name(&called , server, 0x20);
621 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
623 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
626 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
630 /* have to open a new connection */
631 if (!cli_initialise(&c)) {
636 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
637 c.use_kerberos = True;
639 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
640 c.fallback_after_kerberos = True;
643 c.timeout = context->timeout;
646 * Force use of port 139 for first try if share is $IPC, empty, or
647 * null, so browse lists can work
649 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
650 port_try_first = 139;
653 port_try_first = 445;
657 c.port = port_try_first;
659 if (!cli_connect(&c, server_n, &ip)) {
661 /* First connection attempt failed. Try alternate port. */
662 c.port = port_try_next;
664 if (!cli_connect(&c, server_n, &ip)) {
671 if (!cli_session_request(&c, &calling, &called)) {
673 if (strcmp(called.name, "*SMBSERVER")) {
674 make_nmb_name(&called , "*SMBSERVER", 0x20);
677 else { /* Try one more time, but ensure we don't loop */
679 /* Only try this if server is an IP address ... */
681 if (is_ipaddress(server) && !tried_reverse) {
683 struct in_addr rem_ip;
685 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
686 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
691 tried_reverse++; /* Yuck */
693 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
694 make_nmb_name(&called, remote_name, 0x20);
705 DEBUG(4,(" session request ok\n"));
707 if (!cli_negprot(&c)) {
713 username_used = username;
715 if (!cli_session_setup(&c, username_used,
716 password, strlen(password),
717 password, strlen(password),
720 /* Failed. Try an anonymous login, if allowed by flags. */
723 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
724 !cli_session_setup(&c, username_used,
735 DEBUG(4,(" session setup ok\n"));
737 if (!cli_send_tconX(&c, share, "?????",
738 password, strlen(password)+1)) {
739 errno = smbc_errno(context, &c);
744 DEBUG(4,(" tconx ok\n"));
747 * Ok, we have got a nice connection
748 * Let's allocate a server structure.
751 srv = SMB_MALLOC_P(SMBCSRV);
759 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
760 srv->no_pathinfo = False;
761 srv->no_pathinfo2 = False;
762 srv->no_nt_session = False;
764 /* now add it to the cache (internal or external) */
765 /* Let the cache function set errno if it wants to */
767 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username_used)) {
768 int saved_errno = errno;
769 DEBUG(3, (" Failed to add server to cache\n"));
777 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
778 server, share, srv));
780 DLIST_ADD(context->internal->_servers, srv);
785 if (!srv) return NULL;
792 * Connect to a server for getting/setting attributes, possibly on an existing
793 * connection. This works similarly to smbc_server().
795 SMBCSRV *smbc_attr_server(SMBCCTX *context,
796 const char *server, const char *share,
798 fstring username, fstring password,
802 struct cli_state *ipc_cli;
804 SMBCSRV *ipc_srv=NULL;
807 * See if we've already created this special connection. Reference our
808 * "special" share name '*IPC$', which is an impossible real share name
809 * due to the leading asterisk.
811 ipc_srv = find_server(context, server, "*IPC$",
812 workgroup, username, password);
815 /* We didn't find a cached connection. Get the password */
816 if (*password == '\0') {
817 /* ... then retrieve it now. */
818 context->callbacks.auth_fn(server, share,
819 workgroup, sizeof(fstring),
820 username, sizeof(fstring),
821 password, sizeof(fstring));
825 nt_status = cli_full_connection(&ipc_cli,
826 global_myname(), server,
827 &ip, 0, "IPC$", "?????",
831 if (! NT_STATUS_IS_OK(nt_status)) {
832 DEBUG(1,("cli_full_connection failed! (%s)\n",
833 nt_errstr(nt_status)));
840 if (!cli_nt_session_open(ipc_cli, PI_LSARPC)) {
841 DEBUG(1, ("cli_nt_session_open fail!\n"));
843 cli_shutdown(ipc_cli);
847 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
848 but NT sends 0x2000000 so we might as well do it too. */
850 nt_status = cli_lsa_open_policy(ipc_cli,
853 GENERIC_EXECUTE_ACCESS,
856 if (!NT_STATUS_IS_OK(nt_status)) {
857 errno = smbc_errno(context, ipc_cli);
858 cli_shutdown(ipc_cli);
863 ipc_srv = SMB_MALLOC_P(SMBCSRV);
866 cli_shutdown(ipc_cli);
870 ZERO_STRUCTP(ipc_srv);
871 ipc_srv->cli = *ipc_cli;
875 /* now add it to the cache (internal or external) */
877 errno = 0; /* let cache function set errno if it likes */
878 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
883 DEBUG(3, (" Failed to add server to cache\n"));
887 cli_shutdown(&ipc_srv->cli);
892 DLIST_ADD(context->internal->_servers, ipc_srv);
899 * Routine to open() a file ...
902 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
904 fstring server, share, user, password, workgroup;
907 struct cli_state *targetcli;
909 SMBCFILE *file = NULL;
912 if (!context || !context->internal ||
913 !context->internal->_initialized) {
915 errno = EINVAL; /* Best I can think of ... */
927 if (smbc_parse_path(context, fname,
928 server, sizeof(server),
929 share, sizeof(share),
932 password, sizeof(password),
938 if (user[0] == (char)0) fstrcpy(user, context->user);
940 fstrcpy(workgroup, context->workgroup);
942 srv = smbc_server(context, server, share, workgroup, user, password);
946 if (errno == EPERM) errno = EACCES;
947 return NULL; /* smbc_server sets errno */
951 /* Hmmm, the test for a directory is suspect here ... FIXME */
953 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
960 file = SMB_MALLOC_P(SMBCFILE);
971 /*d_printf(">>>open: resolving %s\n", path);*/
972 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
974 d_printf("Could not resolve %s\n", path);
977 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
979 if ( targetcli->dfsroot )
982 pstrcpy(temppath, targetpath);
983 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
986 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
988 /* Handle the error ... */
991 errno = smbc_errno(context, targetcli);
996 /* Fill in file struct */
999 file->fname = SMB_STRDUP(fname);
1004 DLIST_ADD(context->internal->_files, file);
1007 * If the file was opened in O_APPEND mode, all write
1008 * operations should be appended to the file. To do that,
1009 * though, using this protocol, would require a getattrE()
1010 * call for each and every write, to determine where the end
1011 * of the file is. (There does not appear to be an append flag
1012 * in the protocol.) Rather than add all of that overhead of
1013 * retrieving the current end-of-file offset prior to each
1014 * write operation, we'll assume that most append operations
1015 * will continuously write, so we'll just set the offset to
1016 * the end of the file now and hope that's adequate.
1018 * Note to self: If this proves inadequate, and O_APPEND
1019 * should, in some cases, be forced for each write, add a
1020 * field in the context options structure, for
1021 * "strict_append_mode" which would select between the current
1022 * behavior (if FALSE) or issuing a getattrE() prior to each
1023 * write and forcing the write to the end of the file (if
1024 * TRUE). Adding that capability will likely require adding
1025 * an "append" flag into the _SMBCFILE structure to track
1026 * whether a file was opened in O_APPEND mode. -- djl
1028 if (flags & O_APPEND) {
1029 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1030 (void) smbc_close_ctx(context, file);
1040 /* Check if opendir needed ... */
1045 eno = smbc_errno(context, &srv->cli);
1046 file = context->opendir(context, fname);
1047 if (!file) errno = eno;
1052 errno = EINVAL; /* FIXME, correct errno ? */
1058 * Routine to create a file
1061 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1063 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
1066 if (!context || !context->internal ||
1067 !context->internal->_initialized) {
1074 return smbc_open_ctx(context, path, creat_bits, mode);
1078 * Routine to read() a file ...
1081 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1084 fstring server, share, user, password;
1085 pstring path, targetpath;
1086 struct cli_state *targetcli;
1091 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1092 * appears to pass file->offset (which is type off_t) differently than
1093 * a local variable of type off_t. Using local variable "offset" in
1094 * the call to cli_read() instead of file->offset fixes a problem
1095 * retrieving data at an offset greater than 4GB.
1097 off_t offset = file->offset;
1099 if (!context || !context->internal ||
1100 !context->internal->_initialized) {
1107 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1109 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1116 /* Check that the buffer exists ... */
1125 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1126 if (smbc_parse_path(context, file->fname,
1127 server, sizeof(server),
1128 share, sizeof(share),
1131 password, sizeof(password),
1137 /*d_printf(">>>read: resolving %s\n", path);*/
1138 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1140 d_printf("Could not resolve %s\n", path);
1143 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1145 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1149 errno = smbc_errno(context, targetcli);
1154 file->offset += ret;
1156 DEBUG(4, (" --> %d\n", ret));
1158 return ret; /* Success, ret bytes of data ... */
1163 * Routine to write() a file ...
1166 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1169 off_t offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1170 fstring server, share, user, password;
1171 pstring path, targetpath;
1172 struct cli_state *targetcli;
1174 if (!context || !context->internal ||
1175 !context->internal->_initialized) {
1182 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1189 /* Check that the buffer exists ... */
1198 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1199 if (smbc_parse_path(context, file->fname,
1200 server, sizeof(server),
1201 share, sizeof(share),
1204 password, sizeof(password),
1210 /*d_printf(">>>write: resolving %s\n", path);*/
1211 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1213 d_printf("Could not resolve %s\n", path);
1216 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1219 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1223 errno = smbc_errno(context, targetcli);
1228 file->offset += ret;
1230 return ret; /* Success, 0 bytes of data ... */
1234 * Routine to close() a file ...
1237 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1240 fstring server, share, user, password;
1241 pstring path, targetpath;
1242 struct cli_state *targetcli;
1244 if (!context || !context->internal ||
1245 !context->internal->_initialized) {
1252 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1262 return context->closedir(context, file);
1266 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1267 if (smbc_parse_path(context, file->fname,
1268 server, sizeof(server),
1269 share, sizeof(share),
1272 password, sizeof(password),
1278 /*d_printf(">>>close: resolving %s\n", path);*/
1279 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1281 d_printf("Could not resolve %s\n", path);
1284 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1286 if (!cli_close(targetcli, file->cli_fd)) {
1288 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1290 /* Deallocate slot and remove the server
1291 * from the server cache if unused */
1292 errno = smbc_errno(context, targetcli);
1294 DLIST_REMOVE(context->internal->_files, file);
1295 SAFE_FREE(file->fname);
1297 context->callbacks.remove_unused_server_fn(context, srv);
1303 DLIST_REMOVE(context->internal->_files, file);
1304 SAFE_FREE(file->fname);
1311 * Get info from an SMB server on a file. Use a qpathinfo call first
1312 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1314 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1315 uint16 *mode, SMB_OFF_T *size,
1316 time_t *c_time, time_t *a_time, time_t *m_time,
1321 struct cli_state *targetcli;
1322 if (!context || !context->internal ||
1323 !context->internal->_initialized) {
1330 /* path fixup for . and .. */
1331 if (strequal(path, ".") || strequal(path, ".."))
1332 pstrcpy(fixedpath, "\\");
1335 pstrcpy(fixedpath, path);
1336 trim_string(fixedpath, NULL, "\\..");
1337 trim_string(fixedpath, NULL, "\\.");
1339 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1341 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1343 d_printf("Couldn't resolve %s\n", path);
1347 if ( targetcli->dfsroot )
1350 pstrcpy(temppath, targetpath);
1351 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1354 if (!srv->no_pathinfo2 &&
1355 cli_qpathinfo2(targetcli, targetpath, c_time, a_time, m_time, NULL,
1356 size, mode, ino)) return True;
1358 /* if this is NT then don't bother with the getatr */
1359 if (targetcli->capabilities & CAP_NT_SMBS) {
1364 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1365 if (m_time != NULL) {
1366 if (a_time != NULL) *a_time = *m_time;
1367 if (c_time != NULL) *c_time = *m_time;
1369 srv->no_pathinfo2 = True;
1379 * Set file info on an SMB server. Use setpathinfo call first. If that
1380 * fails, use setattrE..
1382 * Access and modification time parameters are always used and must be
1383 * provided. Create time, if zero, will be determined from the actual create
1384 * time of the file. If non-zero, the create time will be set as well.
1386 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1388 static BOOL smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1389 time_t c_time, time_t a_time, time_t m_time,
1396 * Get the create time of the file (if not provided); we'll need it in
1399 if (! srv->no_pathinfo && c_time == 0) {
1400 if (! cli_qpathinfo(&srv->cli, path,
1401 &c_time, NULL, NULL, NULL, NULL)) {
1402 /* qpathinfo not available */
1403 srv->no_pathinfo = True;
1406 * We got a creation time. Some OS versions don't
1407 * return a valid create time, though. If we got an
1408 * invalid time, start with the current time instead.
1410 if (c_time == 0 || c_time == (time_t) -1) {
1411 c_time = time(NULL);
1415 * We got a creation time. For sanity sake, since
1416 * there is no POSIX function to set the create time
1417 * of a file, if the existing create time is greater
1418 * than either of access time or modification time,
1419 * set create time to the smallest of those. This
1420 * ensure that the create time of a file is never
1421 * greater than its last access or modification time.
1423 if (c_time > a_time) c_time = a_time;
1424 if (c_time > m_time) c_time = m_time;
1429 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1430 * modern function for "new code" to be using, and it works given a
1431 * filename rather than requiring that the file be opened to have its
1432 * attributes manipulated.
1434 if (srv->no_pathinfo ||
1435 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1438 * setpathinfo is not supported; go to plan B.
1440 * cli_setatr() does not work on win98, and it also doesn't
1441 * support setting the access time (only the modification
1442 * time), so in all cases, we open the specified file and use
1443 * cli_setattrE() which should work on all OS versions, and
1444 * supports both times.
1447 /* Don't try {q,set}pathinfo() again, with this server */
1448 srv->no_pathinfo = True;
1451 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1453 errno = smbc_errno(context, &srv->cli);
1458 * Get the creat time of the file (if it wasn't provided).
1459 * We'll need it in the set call
1462 ret = cli_getattrE(&srv->cli, fd,
1464 &c_time, NULL, NULL);
1469 /* If we got create time, set times */
1471 /* Some OS versions don't support create time */
1472 if (c_time == 0 || c_time == -1) {
1473 c_time = time(NULL);
1477 * For sanity sake, since there is no POSIX function
1478 * to set the create time of a file, if the existing
1479 * create time is greater than either of access time
1480 * or modification time, set create time to the
1481 * smallest of those. This ensure that the create
1482 * time of a file is never greater than its last
1483 * access or modification time.
1485 if (c_time > a_time) c_time = a_time;
1486 if (c_time > m_time) c_time = m_time;
1488 /* Set the new attributes */
1489 ret = cli_setattrE(&srv->cli, fd,
1490 c_time, a_time, m_time);
1491 cli_close(&srv->cli, fd);
1495 * Unfortunately, setattrE() doesn't have a provision for
1496 * setting the access mode (attributes). We'll have to try
1497 * cli_setatr() for that, and with only this parameter, it
1498 * seems to work on win98.
1500 if (ret && mode != (uint16) -1) {
1501 ret = cli_setatr(&srv->cli, path, mode, 0);
1505 errno = smbc_errno(context, &srv->cli);
1514 * Routine to unlink() a file
1517 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1519 fstring server, share, user, password, workgroup;
1520 pstring path, targetpath;
1521 struct cli_state *targetcli;
1522 SMBCSRV *srv = NULL;
1524 if (!context || !context->internal ||
1525 !context->internal->_initialized) {
1527 errno = EINVAL; /* Best I can think of ... */
1539 if (smbc_parse_path(context, fname,
1540 server, sizeof(server),
1541 share, sizeof(share),
1544 password, sizeof(password),
1550 if (user[0] == (char)0) fstrcpy(user, context->user);
1552 fstrcpy(workgroup, context->workgroup);
1554 srv = smbc_server(context, server, share, workgroup, user, password);
1558 return -1; /* smbc_server sets errno */
1562 /*d_printf(">>>unlink: resolving %s\n", path);*/
1563 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1565 d_printf("Could not resolve %s\n", path);
1568 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1570 if (!cli_unlink(targetcli, targetpath)) {
1572 errno = smbc_errno(context, targetcli);
1574 if (errno == EACCES) { /* Check if the file is a directory */
1579 time_t m_time = 0, a_time = 0, c_time = 0;
1582 if (!smbc_getatr(context, srv, path, &mode, &size,
1583 &c_time, &a_time, &m_time, &ino)) {
1585 /* Hmmm, bad error ... What? */
1587 errno = smbc_errno(context, targetcli);
1593 if (IS_DOS_DIR(mode))
1596 errno = saverr; /* Restore this */
1605 return 0; /* Success ... */
1610 * Routine to rename() a file
1613 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1614 SMBCCTX *ncontext, const char *nname)
1616 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1617 pstring path1, path2, targetpath1, targetpath2;
1618 struct cli_state *targetcli1, *targetcli2;
1619 SMBCSRV *srv = NULL;
1621 if (!ocontext || !ncontext ||
1622 !ocontext->internal || !ncontext->internal ||
1623 !ocontext->internal->_initialized ||
1624 !ncontext->internal->_initialized) {
1626 errno = EINVAL; /* Best I can think of ... */
1631 if (!oname || !nname) {
1638 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1640 smbc_parse_path(ocontext, oname,
1641 server1, sizeof(server1),
1642 share1, sizeof(share1),
1643 path1, sizeof(path1),
1644 user1, sizeof(user1),
1645 password1, sizeof(password1),
1648 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1650 smbc_parse_path(ncontext, nname,
1651 server2, sizeof(server2),
1652 share2, sizeof(share2),
1653 path2, sizeof(path2),
1654 user2, sizeof(user2),
1655 password2, sizeof(password2),
1658 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1660 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1661 strcmp(user1, user2)) {
1663 /* Can't rename across file systems, or users?? */
1670 fstrcpy(workgroup, ocontext->workgroup);
1671 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1672 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1679 /*d_printf(">>>rename: resolving %s\n", path1);*/
1680 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1682 d_printf("Could not resolve %s\n", path1);
1685 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1686 /*d_printf(">>>rename: resolving %s\n", path2);*/
1687 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1689 d_printf("Could not resolve %s\n", path2);
1692 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1694 if (strcmp(targetcli1->desthost, targetcli2->desthost) || strcmp(targetcli1->share, targetcli2->share))
1696 /* can't rename across file systems */
1702 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1703 int eno = smbc_errno(ocontext, targetcli1);
1705 if (eno != EEXIST ||
1706 !cli_unlink(targetcli1, targetpath2) ||
1707 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1715 return 0; /* Success */
1720 * A routine to lseek() a file
1723 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1726 fstring server, share, user, password;
1727 pstring path, targetpath;
1728 struct cli_state *targetcli;
1730 if (!context || !context->internal ||
1731 !context->internal->_initialized) {
1738 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1748 return -1; /* Can't lseek a dir ... */
1754 file->offset = offset;
1758 file->offset += offset;
1762 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1763 if (smbc_parse_path(context, file->fname,
1764 server, sizeof(server),
1765 share, sizeof(share),
1768 password, sizeof(password),
1774 /*d_printf(">>>lseek: resolving %s\n", path);*/
1775 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1777 d_printf("Could not resolve %s\n", path);
1780 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1782 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL, &size, NULL, NULL,
1785 SMB_BIG_UINT b_size = size;
1786 if (!cli_getattrE(targetcli, file->cli_fd, NULL, &b_size, NULL, NULL,
1794 file->offset = size + offset;
1803 return file->offset;
1808 * Generate an inode number from file name for those things that need it
1812 ino_t smbc_inode(SMBCCTX *context, const char *name)
1815 if (!context || !context->internal ||
1816 !context->internal->_initialized) {
1823 if (!*name) return 2; /* FIXME, why 2 ??? */
1824 return (ino_t)str_checksum(name);
1829 * Routine to put basic stat info into a stat structure ... Used by stat and
1834 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname,
1835 SMB_OFF_T size, int mode)
1840 if (IS_DOS_DIR(mode)) {
1841 st->st_mode = SMBC_DIR_MODE;
1843 st->st_mode = SMBC_FILE_MODE;
1846 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1847 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1848 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1849 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1852 #ifdef HAVE_STAT_ST_BLKSIZE
1853 st->st_blksize = 512;
1855 #ifdef HAVE_STAT_ST_BLOCKS
1856 st->st_blocks = (size+511)/512;
1858 st->st_uid = getuid();
1859 st->st_gid = getgid();
1861 if (IS_DOS_DIR(mode)) {
1867 if (st->st_ino == 0) {
1868 st->st_ino = smbc_inode(context, fname);
1871 return True; /* FIXME: Is this needed ? */
1876 * Routine to stat a file given a name
1879 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1882 fstring server, share, user, password, workgroup;
1884 time_t m_time = 0, a_time = 0, c_time = 0;
1889 if (!context || !context->internal ||
1890 !context->internal->_initialized) {
1892 errno = EINVAL; /* Best I can think of ... */
1904 DEBUG(4, ("smbc_stat(%s)\n", fname));
1906 if (smbc_parse_path(context, fname,
1907 server, sizeof(server),
1908 share, sizeof(share),
1911 password, sizeof(password),
1917 if (user[0] == (char)0) fstrcpy(user, context->user);
1919 fstrcpy(workgroup, context->workgroup);
1921 srv = smbc_server(context, server, share, workgroup, user, password);
1924 return -1; /* errno set by smbc_server */
1927 if (!smbc_getatr(context, srv, path, &mode, &size,
1928 &c_time, &a_time, &m_time, &ino)) {
1930 errno = smbc_errno(context, &srv->cli);
1937 smbc_setup_stat(context, st, path, size, mode);
1939 st->st_atime = a_time;
1940 st->st_ctime = c_time;
1941 st->st_mtime = m_time;
1942 st->st_dev = srv->dev;
1949 * Routine to stat a file given an fd
1952 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1954 time_t c_time, a_time, m_time;
1957 fstring server, share, user, password;
1958 pstring path, targetpath;
1959 struct cli_state *targetcli;
1962 if (!context || !context->internal ||
1963 !context->internal->_initialized) {
1970 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1979 return context->fstatdir(context, file, st);
1983 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
1984 if (smbc_parse_path(context, file->fname,
1985 server, sizeof(server),
1986 share, sizeof(share),
1989 password, sizeof(password),
1995 /*d_printf(">>>fstat: resolving %s\n", path);*/
1996 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1998 d_printf("Could not resolve %s\n", path);
2001 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2003 if (!cli_qfileinfo(targetcli, file->cli_fd,
2004 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
2005 if (!cli_getattrE(targetcli, file->cli_fd,
2006 &mode, &size, &c_time, &a_time, &m_time)) {
2015 smbc_setup_stat(context, st, file->fname, size, mode);
2017 st->st_atime = a_time;
2018 st->st_ctime = c_time;
2019 st->st_mtime = m_time;
2020 st->st_dev = file->srv->dev;
2027 * Routine to open a directory
2028 * We accept the URL syntax explained in smbc_parse_path(), above.
2031 static void smbc_remove_dir(SMBCFILE *dir)
2033 struct smbc_dir_list *d,*f;
2040 SAFE_FREE(f->dirent);
2045 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2049 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
2051 struct smbc_dirent *dirent;
2053 int name_length = (name == NULL ? 0 : strlen(name));
2054 int comment_len = (comment == NULL ? 0 : strlen(comment));
2057 * Allocate space for the dirent, which must be increased by the
2058 * size of the name and the comment and 1 each for the null terminator.
2061 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2063 dirent = SMB_MALLOC(size);
2067 dir->dir_error = ENOMEM;
2072 ZERO_STRUCTP(dirent);
2074 if (dir->dir_list == NULL) {
2076 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2077 if (!dir->dir_list) {
2080 dir->dir_error = ENOMEM;
2084 ZERO_STRUCTP(dir->dir_list);
2086 dir->dir_end = dir->dir_next = dir->dir_list;
2090 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2092 if (!dir->dir_end->next) {
2095 dir->dir_error = ENOMEM;
2099 ZERO_STRUCTP(dir->dir_end->next);
2101 dir->dir_end = dir->dir_end->next;
2104 dir->dir_end->next = NULL;
2105 dir->dir_end->dirent = dirent;
2107 dirent->smbc_type = type;
2108 dirent->namelen = name_length;
2109 dirent->commentlen = comment_len;
2110 dirent->dirlen = size;
2112 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2114 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2115 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2122 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
2124 SMBCFILE *dir = (SMBCFILE *)state;
2125 struct smbc_dir_list *dir_list;
2126 struct smbc_dirent *dirent;
2130 dirent_type = dir->dir_type;
2132 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2134 /* An error occurred, what do we do? */
2135 /* FIXME: Add some code here */
2138 /* Point to the one just added */
2139 dirent = dir->dir_end->dirent;
2141 /* See if this was a duplicate */
2142 for (dir_list = dir->dir_list;
2143 dir_list != dir->dir_end;
2144 dir_list = dir_list->next) {
2146 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2147 /* Duplicate. End end of list need to be removed. */
2151 if (do_remove && dir_list->next == dir->dir_end) {
2152 /* Found the end of the list. Remove it. */
2153 dir->dir_end = dir_list;
2154 free(dir_list->next);
2155 dir_list->next = NULL;
2162 list_fn(const char *name, uint32 type, const char *comment, void *state)
2164 SMBCFILE *dir = (SMBCFILE *)state;
2167 /* We need to process the type a little ... */
2169 if (dir->dir_type == SMBC_FILE_SHARE) {
2172 case 0: /* Directory tree */
2173 dirent_type = SMBC_FILE_SHARE;
2177 dirent_type = SMBC_PRINTER_SHARE;
2181 dirent_type = SMBC_COMMS_SHARE;
2185 dirent_type = SMBC_IPC_SHARE;
2189 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2193 else dirent_type = dir->dir_type;
2195 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2197 /* An error occurred, what do we do? */
2198 /* FIXME: Add some code here */
2204 dir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2207 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2208 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2210 /* Handle an error ... */
2212 /* FIXME: Add some code ... */
2218 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
2220 fstring server, share, user, password, options;
2225 SMBCSRV *srv = NULL;
2226 SMBCFILE *dir = NULL;
2227 struct in_addr rem_ip;
2229 if (!context || !context->internal ||
2230 !context->internal->_initialized) {
2231 DEBUG(4, ("no valid context\n"));
2232 errno = EINVAL + 8192;
2238 DEBUG(4, ("no valid fname\n"));
2239 errno = EINVAL + 8193;
2243 if (smbc_parse_path(context, fname,
2244 server, sizeof(server),
2245 share, sizeof(share),
2248 password, sizeof(password),
2249 options, sizeof(options))) {
2250 DEBUG(4, ("no valid path\n"));
2251 errno = EINVAL + 8194;
2255 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
2257 /* Ensure the options are valid */
2258 if (smbc_check_options(server, share, path, options)) {
2259 DEBUG(4, ("unacceptable options (%s)\n", options));
2260 errno = EINVAL + 8195;
2264 if (user[0] == (char)0) fstrcpy(user, context->user);
2266 pstrcpy(workgroup, context->workgroup);
2268 dir = SMB_MALLOC_P(SMBCFILE);
2280 dir->fname = SMB_STRDUP(fname);
2284 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2286 if (server[0] == (char)0) {
2291 struct ip_service *ip_list;
2292 struct ip_service server_addr;
2293 struct user_auth_info u_info;
2294 struct cli_state *cli;
2296 if (share[0] != (char)0 || path[0] != (char)0) {
2298 errno = EINVAL + 8196;
2300 SAFE_FREE(dir->fname);
2306 /* Determine how many local master browsers to query */
2307 max_lmb_count = (context->options.browse_max_lmb_count == 0
2309 : context->options.browse_max_lmb_count);
2311 pstrcpy(u_info.username, user);
2312 pstrcpy(u_info.password, password);
2315 * We have server and share and path empty but options
2316 * requesting that we scan all master browsers for their list
2317 * of workgroups/domains. This implies that we must first try
2318 * broadcast queries to find all master browsers, and if that
2319 * doesn't work, then try our other methods which return only
2320 * a single master browser.
2323 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2324 if (!find_master_ip(workgroup, &server_addr.ip)) {
2330 ip_list = &server_addr;
2334 for (i = 0; i < count && i < max_lmb_count; i++) {
2335 DEBUG(99, ("Found master browser %d of %d: %s\n", i+1, MAX(count, max_lmb_count), inet_ntoa(ip_list[i].ip)));
2337 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2338 /* cli == NULL is the master browser refused to talk or
2339 could not be found */
2343 fstrcpy(server, cli->desthost);
2346 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2349 * For each returned master browser IP address, get a
2350 * connection to IPC$ on the server if we do not
2351 * already have one, and determine the
2352 * workgroups/domains that it knows about.
2355 srv = smbc_server(context, server,
2356 "IPC$", workgroup, user, password);
2362 dir->dir_type = SMBC_WORKGROUP;
2364 /* Now, list the stuff ... */
2366 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2374 * Server not an empty string ... Check the rest and see what
2377 if (share[0] == (char)0) {
2379 if (path[0] != (char)0) { /* Should not have empty share with path */
2381 errno = EINVAL + 8197;
2383 SAFE_FREE(dir->fname);
2390 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2391 /* However, we check to see if <server> is an IP address first */
2393 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2394 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2395 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2398 dir->dir_type = SMBC_SERVER;
2401 * Get the backup list ...
2405 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2407 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2408 errno = EPERM; /* FIXME, is this correct */
2414 * Get a connection to IPC$ on the server if we do not already have one
2417 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2420 DEBUG(0, ("got no contact to IPC$\n"));
2422 SAFE_FREE(dir->fname);
2431 /* Now, list the servers ... */
2433 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2437 SAFE_FREE(dir->fname);
2446 if (resolve_name(server, &rem_ip, 0x20)) {
2448 /* Now, list the shares ... */
2450 dir->dir_type = SMBC_FILE_SHARE;
2452 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2457 SAFE_FREE(dir->fname);
2466 /* Now, list the servers ... */
2468 if (cli_RNetShareEnum(&srv->cli, list_fn,
2471 errno = cli_errno(&srv->cli);
2473 SAFE_FREE(dir->fname);
2483 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2485 SAFE_FREE(dir->fname);
2495 else { /* The server and share are specified ... work from there ... */
2497 struct cli_state *targetcli;
2499 /* Well, we connect to the server and list the directory */
2501 dir->dir_type = SMBC_FILE_SHARE;
2503 srv = smbc_server(context, server, share, workgroup, user, password);
2508 SAFE_FREE(dir->fname);
2517 /* Now, list the files ... */
2519 p = path + strlen(path);
2520 pstrcat(path, "\\*");
2522 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2524 d_printf("Could not resolve %s\n", path);
2528 if (cli_list(targetcli, targetpath, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2532 SAFE_FREE(dir->fname);
2535 errno = smbc_errno(context, targetcli);
2537 if (errno == EINVAL) {
2539 * See if they asked to opendir something
2540 * other than a directory. If so, the
2541 * converted error value we got would have
2542 * been EINVAL rather than ENOTDIR.
2544 *p = '\0'; /* restore original path */
2546 if (smbc_getatr(context, srv, path,
2550 ! IS_DOS_DIR(mode)) {
2552 /* It is. Correct the error value */
2564 DLIST_ADD(context->internal->_files, dir);
2570 * Routine to close a directory
2573 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2576 if (!context || !context->internal ||
2577 !context->internal->_initialized) {
2584 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2591 smbc_remove_dir(dir); /* Clean it up */
2593 DLIST_REMOVE(context->internal->_files, dir);
2597 SAFE_FREE(dir->fname);
2598 SAFE_FREE(dir); /* Free the space too */
2605 static void smbc_readdir_internal(SMBCCTX * context,
2606 struct smbc_dirent *dest,
2607 struct smbc_dirent *src,
2608 int max_namebuf_len)
2610 if (context->options.urlencode_readdir_entries) {
2612 /* url-encode the name. get back remaining buffer space */
2614 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2616 /* We now know the name length */
2617 dest->namelen = strlen(dest->name);
2619 /* Save the pointer to the beginning of the comment */
2620 dest->comment = dest->name + dest->namelen + 1;
2622 /* Copy the comment */
2623 strncpy(dest->comment, src->comment, max_namebuf_len);
2625 /* Ensure the comment is null terminated */
2626 if (max_namebuf_len > src->commentlen) {
2627 dest->comment[src->commentlen] = '\0';
2629 dest->comment[max_namebuf_len - 1] = '\0';
2632 /* Save other fields */
2633 dest->smbc_type = src->smbc_type;
2634 dest->commentlen = strlen(dest->comment);
2635 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2639 /* No encoding. Just copy the entry as is. */
2640 memcpy(dest, src, src->dirlen);
2641 dest->comment = (char *)(&dest->name + src->namelen + 1);
2647 * Routine to get a directory entry
2650 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2653 struct smbc_dirent *dirp, *dirent;
2655 /* Check that all is ok first ... */
2657 if (!context || !context->internal ||
2658 !context->internal->_initialized) {
2661 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2666 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2669 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2674 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2677 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2682 if (!dir->dir_next) {
2686 dirent = dir->dir_next->dirent;
2694 dirp = (struct smbc_dirent *)context->internal->_dirent;
2695 maxlen = (sizeof(context->internal->_dirent) -
2696 sizeof(struct smbc_dirent));
2698 smbc_readdir_internal(context, dirp, dirent, maxlen);
2700 dir->dir_next = dir->dir_next->next;
2706 * Routine to get directory entries
2709 static int smbc_getdents_ctx(SMBCCTX *context,
2711 struct smbc_dirent *dirp,
2717 char *ndir = (char *)dirp;
2718 struct smbc_dir_list *dirlist;
2720 /* Check that all is ok first ... */
2722 if (!context || !context->internal ||
2723 !context->internal->_initialized) {
2730 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2737 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2745 * Now, retrieve the number of entries that will fit in what was passed
2746 * We have to figure out if the info is in the list, or we need to
2747 * send a request to the server to get the info.
2750 while ((dirlist = dir->dir_next)) {
2751 struct smbc_dirent *dirent;
2753 if (!dirlist->dirent) {
2755 errno = ENOENT; /* Bad error */
2760 /* Do urlencoding of next entry, if so selected */
2761 dirent = (struct smbc_dirent *)context->internal->_dirent;
2762 maxlen = (sizeof(context->internal->_dirent) -
2763 sizeof(struct smbc_dirent));
2764 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
2766 reqd = dirent->dirlen;
2770 if (rem < count) { /* We managed to copy something */
2776 else { /* Nothing copied ... */
2778 errno = EINVAL; /* Not enough space ... */
2785 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2787 ((struct smbc_dirent *)ndir)->comment =
2788 (char *)(&((struct smbc_dirent *)ndir)->name +
2796 dir->dir_next = dirlist = dirlist -> next;
2807 * Routine to create a directory ...
2810 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2813 fstring server, share, user, password, workgroup;
2814 pstring path, targetpath;
2815 struct cli_state *targetcli;
2817 if (!context || !context->internal ||
2818 !context->internal->_initialized) {
2832 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2834 if (smbc_parse_path(context, fname,
2835 server, sizeof(server),
2836 share, sizeof(share),
2839 password, sizeof(password),
2845 if (user[0] == (char)0) fstrcpy(user, context->user);
2847 fstrcpy(workgroup, context->workgroup);
2849 srv = smbc_server(context, server, share, workgroup, user, password);
2853 return -1; /* errno set by smbc_server */
2857 /*d_printf(">>>mkdir: resolving %s\n", path);*/
2858 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2860 d_printf("Could not resolve %s\n", path);
2863 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
2865 if (!cli_mkdir(targetcli, targetpath)) {
2867 errno = smbc_errno(context, targetcli);
2877 * Our list function simply checks to see if a directory is not empty
2880 static int smbc_rmdir_dirempty = True;
2882 static void rmdir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2885 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2886 smbc_rmdir_dirempty = False;
2891 * Routine to remove a directory
2894 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2897 fstring server, share, user, password, workgroup;
2898 pstring path, targetpath;
2899 struct cli_state *targetcli;
2901 if (!context || !context->internal ||
2902 !context->internal->_initialized) {
2916 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2918 if (smbc_parse_path(context, fname,
2919 server, sizeof(server),
2920 share, sizeof(share),
2923 password, sizeof(password),
2930 if (user[0] == (char)0) fstrcpy(user, context->user);
2932 fstrcpy(workgroup, context->workgroup);
2934 srv = smbc_server(context, server, share, workgroup, user, password);
2938 return -1; /* errno set by smbc_server */
2942 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2944 mode = aDIR | aRONLY;
2947 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2949 if (strcmp(path, "\\") == 0) {
2951 mode = aDIR | aRONLY;
2957 smbc_stat_printjob(srv, path, &size, &m_time);
2958 c_time = a_time = m_time;
2963 /*d_printf(">>>rmdir: resolving %s\n", path);*/
2964 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2966 d_printf("Could not resolve %s\n", path);
2969 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
2972 if (!cli_rmdir(targetcli, targetpath)) {
2974 errno = smbc_errno(context, targetcli);
2976 if (errno == EACCES) { /* Check if the dir empty or not */
2978 pstring lpath; /* Local storage to avoid buffer overflows */
2980 smbc_rmdir_dirempty = True; /* Make this so ... */
2982 pstrcpy(lpath, targetpath);
2983 pstrcat(lpath, "\\*");
2985 if (cli_list(targetcli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2988 /* Fix errno to ignore latest error ... */
2990 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
2991 smbc_errno(context, targetcli)));
2996 if (smbc_rmdir_dirempty)
3012 * Routine to return the current directory position
3015 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
3017 off_t ret_val; /* Squash warnings about cast */
3019 if (!context || !context->internal ||
3020 !context->internal->_initialized) {
3027 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3034 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3042 * We return the pointer here as the offset
3044 ret_val = (int)dir->dir_next;
3050 * A routine to run down the list and see if the entry is OK
3053 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
3054 struct smbc_dirent *dirent)
3057 /* Run down the list looking for what we want */
3061 struct smbc_dir_list *tmp = list;
3065 if (tmp->dirent == dirent)
3074 return NULL; /* Not found, or an error */
3080 * Routine to seek on a directory
3083 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
3085 long int l_offset = offset; /* Handle problems of size */
3086 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3087 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3089 if (!context || !context->internal ||
3090 !context->internal->_initialized) {
3097 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3104 /* Now, check what we were passed and see if it is OK ... */
3106 if (dirent == NULL) { /* Seek to the begining of the list */
3108 dir->dir_next = dir->dir_list;
3113 /* Now, run down the list and make sure that the entry is OK */
3114 /* This may need to be changed if we change the format of the list */
3116 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3118 errno = EINVAL; /* Bad entry */
3123 dir->dir_next = list_ent;
3130 * Routine to fstat a dir
3133 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
3136 if (!context || !context->internal ||
3137 !context->internal->_initialized) {
3144 /* No code yet ... */
3150 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
3153 fstring server, share, user, password, workgroup;
3157 if (!context || !context->internal ||
3158 !context->internal->_initialized) {
3160 errno = EINVAL; /* Best I can think of ... */
3172 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3174 if (smbc_parse_path(context, fname,
3175 server, sizeof(server),
3176 share, sizeof(share),
3179 password, sizeof(password),
3185 if (user[0] == (char)0) fstrcpy(user, context->user);
3187 fstrcpy(workgroup, context->workgroup);
3189 srv = smbc_server(context, server, share, workgroup, user, password);
3192 return -1; /* errno set by smbc_server */
3197 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3198 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3199 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3200 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3202 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3203 errno = smbc_errno(context, &srv->cli);
3210 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
3213 fstring server, share, user, password, workgroup;
3218 if (!context || !context->internal ||
3219 !context->internal->_initialized) {
3221 errno = EINVAL; /* Best I can think of ... */
3234 a_time = m_time = time(NULL);
3236 a_time = tbuf[0].tv_sec;
3237 m_time = tbuf[1].tv_sec;
3246 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf));
3247 atimebuf[sizeof(atimebuf) - 1] = '\0';
3248 if ((p = strchr(atimebuf, '\n')) != NULL) {
3252 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf));
3253 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3254 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3258 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3259 fname, atimebuf, mtimebuf);
3262 if (smbc_parse_path(context, fname,
3263 server, sizeof(server),
3264 share, sizeof(share),
3267 password, sizeof(password),
3273 if (user[0] == (char)0) fstrcpy(user, context->user);
3275 fstrcpy(workgroup, context->workgroup);
3277 srv = smbc_server(context, server, share, workgroup, user, password);
3280 return -1; /* errno set by smbc_server */
3283 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3284 return -1; /* errno set by smbc_setatr */
3291 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3292 However NT4 gives a "The information may have been modified by a
3293 computer running Windows NT 5.0" if denied ACEs do not appear before
3296 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
3298 if (sec_ace_equal(ace1, ace2))
3301 if (ace1->type != ace2->type)
3302 return ace2->type - ace1->type;
3304 if (sid_compare(&ace1->trustee, &ace2->trustee))
3305 return sid_compare(&ace1->trustee, &ace2->trustee);
3307 if (ace1->flags != ace2->flags)
3308 return ace1->flags - ace2->flags;
3310 if (ace1->info.mask != ace2->info.mask)
3311 return ace1->info.mask - ace2->info.mask;
3313 if (ace1->size != ace2->size)
3314 return ace1->size - ace2->size;
3316 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3320 static void sort_acl(SEC_ACL *the_acl)
3323 if (!the_acl) return;
3325 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
3327 for (i=1;i<the_acl->num_aces;) {
3328 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3330 for (j=i; j<the_acl->num_aces-1; j++) {
3331 the_acl->ace[j] = the_acl->ace[j+1];
3333 the_acl->num_aces--;
3340 /* convert a SID to a string, either numeric or username/group */
3341 static void convert_sid_to_string(struct cli_state *ipc_cli,
3347 char **domains = NULL;
3348 char **names = NULL;
3349 uint32 *types = NULL;
3351 sid_to_string(str, sid);
3353 if (numeric) return; /* no lookup desired */
3355 /* Ask LSA to convert the sid to a name */
3357 if (!NT_STATUS_IS_OK(cli_lsa_lookup_sids(ipc_cli, ipc_cli->mem_ctx,
3358 pol, 1, sid, &domains,
3360 !domains || !domains[0] || !names || !names[0]) {
3366 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3367 domains[0], lp_winbind_separator(),
3371 /* convert a string to a SID, either numeric or username/group */
3372 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
3378 uint32 *types = NULL;
3379 DOM_SID *sids = NULL;
3383 if (strncmp(str, "S-", 2) == 0) {
3384 return string_to_sid(sid, str);
3391 if (!NT_STATUS_IS_OK(cli_lsa_lookup_names(ipc_cli, ipc_cli->mem_ctx,
3392 pol, 1, &str, &sids,
3398 sid_copy(sid, &sids[0]);
3405 /* parse an ACE in the same format as print_ace() */
3406 static BOOL parse_ace(struct cli_state *ipc_cli,
3415 unsigned atype, aflags, amask;
3418 const struct perm_value *v;
3424 /* These values discovered by inspection */
3425 static const struct perm_value special_values[] = {
3426 { "R", 0x00120089 },
3427 { "W", 0x00120116 },
3428 { "X", 0x001200a0 },
3429 { "D", 0x00010000 },
3430 { "P", 0x00040000 },
3431 { "O", 0x00080000 },
3435 static const struct perm_value standard_values[] = {
3436 { "READ", 0x001200a9 },
3437 { "CHANGE", 0x001301bf },
3438 { "FULL", 0x001f01ff },
3444 p = strchr_m(str,':');
3445 if (!p) return False;
3448 /* Try to parse numeric form */
3450 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3451 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3455 /* Try to parse text form */
3457 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3462 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3466 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3467 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3468 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3469 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3474 /* Only numeric form accepted for flags at present */
3476 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3477 sscanf(tok, "%i", &aflags))) {
3481 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3485 if (strncmp(tok, "0x", 2) == 0) {
3486 if (sscanf(tok, "%i", &amask) != 1) {
3492 for (v = standard_values; v->perm; v++) {
3493 if (strcmp(tok, v->perm) == 0) {
3504 for (v = special_values; v->perm; v++) {
3505 if (v->perm[0] == *p) {
3511 if (!found) return False;
3521 init_sec_ace(ace, &sid, atype, mask, aflags);
3525 /* add an ACE to a list of ACEs in a SEC_ACL */
3526 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3531 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3535 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3536 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3537 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3538 newacl = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3540 (*the_acl) = newacl;
3545 /* parse a ascii version of a security descriptor */
3546 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3547 struct cli_state *ipc_cli,
3552 const char *p = str;
3556 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3560 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3562 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3563 revision = strtol(tok+9, NULL, 16);
3567 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3568 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3570 !convert_string_to_sid(ipc_cli, pol,
3572 owner_sid, tok+6)) {
3573 DEBUG(5, ("Failed to parse owner sid\n"));
3579 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3580 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3582 !convert_string_to_sid(ipc_cli, pol,
3584 owner_sid, tok+7)) {
3585 DEBUG(5, ("Failed to parse owner sid\n"));
3591 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3592 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3594 !convert_string_to_sid(ipc_cli, pol,
3597 DEBUG(5, ("Failed to parse group sid\n"));
3603 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3604 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3606 !convert_string_to_sid(ipc_cli, pol,
3609 DEBUG(5, ("Failed to parse group sid\n"));
3615 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3617 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3618 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3621 if(!add_ace(&dacl, &ace, ctx)) {
3622 DEBUG(5, ("Failed to add ACL %s\n", tok));
3628 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3630 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3631 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3634 if(!add_ace(&dacl, &ace, ctx)) {
3635 DEBUG(5, ("Failed to add ACL %s\n", tok));
3641 DEBUG(5, ("Failed to parse security descriptor\n"));
3645 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3646 owner_sid, grp_sid, NULL, dacl, &sd_size);
3649 SAFE_FREE(owner_sid);
3655 /* Obtain the current dos attributes */
3656 static DOS_ATTR_DESC *dos_attr_query(SMBCCTX *context,
3658 const char *filename,
3661 time_t m_time = 0, a_time = 0, c_time = 0;
3664 SMB_INO_T inode = 0;
3667 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
3673 /* Obtain the DOS attributes */
3674 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
3676 &c_time, &a_time, &m_time, &inode)) {
3678 errno = smbc_errno(context, &srv->cli);
3679 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
3686 ret->a_time = a_time;
3687 ret->c_time = c_time;
3688 ret->m_time = m_time;
3695 /* parse a ascii version of a security descriptor */
3696 static void dos_attr_parse(SMBCCTX *context,
3701 const char *p = str;
3704 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3706 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
3707 dad->mode = strtol(tok+5, NULL, 16);
3711 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
3712 dad->size = strtoll(tok+5, NULL, 10);
3716 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
3717 dad->a_time = strtoll(tok+7, NULL, 10);
3721 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
3722 dad->c_time = strtoll(tok+7, NULL, 10);
3726 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
3727 dad->m_time = strtoll(tok+7, NULL, 10);
3731 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
3732 dad->inode = strtoll(tok+6, NULL, 10);
3739 /*****************************************************
3740 retrieve the acls for a file
3741 *******************************************************/
3742 static int cacl_get(SMBCCTX *context, TALLOC_CTX *ctx, SMBCSRV *srv,
3743 struct cli_state *ipc_cli, POLICY_HND *pol,
3744 char *filename, char *attr_name, char *buf, int bufsize)
3755 BOOL exclude_nt_revision = False;
3756 BOOL exclude_nt_owner = False;
3757 BOOL exclude_nt_group = False;
3758 BOOL exclude_nt_acl = False;
3759 BOOL exclude_dos_mode = False;
3760 BOOL exclude_dos_size = False;
3761 BOOL exclude_dos_ctime = False;
3762 BOOL exclude_dos_atime = False;
3763 BOOL exclude_dos_mtime = False;
3764 BOOL exclude_dos_inode = False;
3765 BOOL numeric = True;
3766 BOOL determine_size = (bufsize == 0);
3770 fstring name_sandbox;
3774 time_t m_time = 0, a_time = 0, c_time = 0;
3778 struct cli_state *cli = &srv->cli;
3780 /* Copy name so we can strip off exclusions (if any are specified) */
3781 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
3783 /* Ensure name is null terminated */
3784 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
3786 /* Play in the sandbox */
3787 name = name_sandbox;
3789 /* If there are any exclusions, point to them and mask them from name */
3790 if ((pExclude = strchr(name, '!')) != NULL)
3795 all = (StrnCaseCmp(name, "system.*", 8) == 0);
3796 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
3797 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
3798 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
3799 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
3800 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
3801 numeric = (* (name + strlen(name) - 1) != '+');
3803 /* Look for exclusions from "all" requests */
3804 if (all || all_nt || all_dos) {
3806 /* Exclusions are delimited by '!' */
3807 for (; pExclude != NULL; pExclude = (p == NULL ? NULL : p + 1)) {
3809 /* Find end of this exclusion name */
3810 if ((p = strchr(pExclude, '!')) != NULL)
3815 /* Which exclusion name is this? */
3816 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
3817 exclude_nt_revision = True;
3819 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
3820 exclude_nt_owner = True;
3822 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
3823 exclude_nt_group = True;
3825 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
3826 exclude_nt_acl = True;
3828 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
3829 exclude_dos_mode = True;
3831 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
3832 exclude_dos_size = True;
3834 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
3835 exclude_dos_ctime = True;
3837 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
3838 exclude_dos_atime = True;
3840 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
3841 exclude_dos_mtime = True;
3843 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
3844 exclude_dos_inode = True;
3847 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
3858 * If we are (possibly) talking to an NT or new system and some NT
3859 * attributes have been requested...
3861 if (ipc_cli && (all || some_nt || all_nt_acls)) {
3862 /* Point to the portion after "system.nt_sec_desc." */
3863 name += 19; /* if (all) this will be invalid but unused */
3865 /* ... then obtain any NT attributes which were requested */
3866 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3869 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3870 filename, cli_errstr(cli)));
3875 sd = cli_query_secdesc(cli, fnum, ctx);
3879 ("cacl_get Failed to query old descriptor\n"));
3884 cli_close(cli, fnum);
3886 if (! exclude_nt_revision) {
3887 if (all || all_nt) {
3888 if (determine_size) {
3889 p = talloc_asprintf(ctx,
3898 n = snprintf(buf, bufsize,
3899 "REVISION:%d", sd->revision);
3901 } else if (StrCaseCmp(name, "revision") == 0) {
3902 if (determine_size) {
3903 p = talloc_asprintf(ctx, "%d",
3911 n = snprintf(buf, bufsize, "%d",
3916 if (!determine_size && n > bufsize) {
3925 if (! exclude_nt_owner) {
3926 /* Get owner and group sid */
3927 if (sd->owner_sid) {
3928 convert_sid_to_string(ipc_cli, pol,
3933 fstrcpy(sidstr, "");
3936 if (all || all_nt) {
3937 if (determine_size) {
3938 p = talloc_asprintf(ctx, ",OWNER:%s",
3946 n = snprintf(buf, bufsize,
3947 ",OWNER:%s", sidstr);
3949 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3950 if (determine_size) {
3951 p = talloc_asprintf(ctx, "%s", sidstr);
3958 n = snprintf(buf, bufsize, "%s",
3963 if (!determine_size && n > bufsize) {
3972 if (! exclude_nt_group) {
3974 convert_sid_to_string(ipc_cli, pol,
3978 fstrcpy(sidstr, "");
3981 if (all || all_nt) {
3982 if (determine_size) {
3983 p = talloc_asprintf(ctx, ",GROUP:%s",
3991 n = snprintf(buf, bufsize,
3992 ",GROUP:%s", sidstr);
3994 } else if (StrnCaseCmp(name, "group", 5) == 0) {
3995 if (determine_size) {
3996 p = talloc_asprintf(ctx, "%s", sidstr);
4003 n = snprintf(buf, bufsize, "%s", sidstr);
4007 if (!determine_size && n > bufsize) {
4016 if (! exclude_nt_acl) {
4017 /* Add aces to value buffer */
4018 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4020 SEC_ACE *ace = &sd->dacl->ace[i];
4021 convert_sid_to_string(ipc_cli, pol,
4025 if (all || all_nt) {
4026 if (determine_size) {
4027 p = talloc_asprintf(
4043 ",ACL:%s:%d/%d/0x%08x",
4049 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4050 StrCaseCmp(name + 3, sidstr) == 0) ||
4051 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4052 StrCaseCmp(name + 4, sidstr) == 0)) {
4053 if (determine_size) {
4054 p = talloc_asprintf(
4066 n = snprintf(buf, bufsize,
4072 } else if (all_nt_acls) {
4073 if (determine_size) {
4074 p = talloc_asprintf(
4076 "%s%s:%d/%d/0x%08x",
4088 n = snprintf(buf, bufsize,
4089 "%s%s:%d/%d/0x%08x",
4107 /* Restore name pointer to its original value */
4111 if (all || some_dos) {
4112 /* Point to the portion after "system.dos_attr." */
4113 name += 16; /* if (all) this will be invalid but unused */
4115 /* Obtain the DOS attributes */
4116 if (!smbc_getatr(context, srv, filename, &mode, &size,
4117 &c_time, &a_time, &m_time, &ino)) {
4119 errno = smbc_errno(context, &srv->cli);
4124 if (! exclude_dos_mode) {
4125 if (all || all_dos) {
4126 if (determine_size) {
4127 p = talloc_asprintf(ctx,
4140 n = snprintf(buf, bufsize,
4148 } else if (StrCaseCmp(name, "mode") == 0) {
4149 if (determine_size) {
4150 p = talloc_asprintf(ctx, "0x%x", mode);
4157 n = snprintf(buf, bufsize, "0x%x", mode);
4161 if (!determine_size && n > bufsize) {
4170 if (! exclude_dos_size) {
4171 if (all || all_dos) {
4172 if (determine_size) {
4173 p = talloc_asprintf(
4176 (unsigned long long) size);
4183 n = snprintf(buf, bufsize,
4185 (unsigned long long) size);
4187 } else if (StrCaseCmp(name, "size") == 0) {
4188 if (determine_size) {
4189 p = talloc_asprintf(
4192 (unsigned long long) size);
4199 n = snprintf(buf, bufsize,
4201 (unsigned long long) size);
4205 if (!determine_size && n > bufsize) {
4214 if (! exclude_dos_ctime) {
4215 if (all || all_dos) {
4216 if (determine_size) {
4217 p = talloc_asprintf(ctx,
4226 n = snprintf(buf, bufsize,
4227 ",C_TIME:%lu", c_time);
4229 } else if (StrCaseCmp(name, "c_time") == 0) {
4230 if (determine_size) {
4231 p = talloc_asprintf(ctx, "%lu", c_time);
4238 n = snprintf(buf, bufsize, "%lu", c_time);
4242 if (!determine_size && n > bufsize) {
4251 if (! exclude_dos_atime) {
4252 if (all || all_dos) {
4253 if (determine_size) {
4254 p = talloc_asprintf(ctx,
4263 n = snprintf(buf, bufsize,
4264 ",A_TIME:%lu", a_time);
4266 } else if (StrCaseCmp(name, "a_time") == 0) {
4267 if (determine_size) {
4268 p = talloc_asprintf(ctx, "%lu", a_time);
4275 n = snprintf(buf, bufsize, "%lu", a_time);
4279 if (!determine_size && n > bufsize) {
4288 if (! exclude_dos_mtime) {
4289 if (all || all_dos) {
4290 if (determine_size) {
4291 p = talloc_asprintf(ctx,
4300 n = snprintf(buf, bufsize,
4301 ",M_TIME:%lu", m_time);
4303 } else if (StrCaseCmp(name, "m_time") == 0) {
4304 if (determine_size) {
4305 p = talloc_asprintf(ctx, "%lu", m_time);
4312 n = snprintf(buf, bufsize, "%lu", m_time);
4316 if (!determine_size && n > bufsize) {
4325 if (! exclude_dos_inode) {
4326 if (all || all_dos) {
4327 if (determine_size) {
4328 p = talloc_asprintf(
4331 (unsigned long long) ino);
4338 n = snprintf(buf, bufsize,
4340 (unsigned long long) ino);
4342 } else if (StrCaseCmp(name, "inode") == 0) {
4343 if (determine_size) {
4344 p = talloc_asprintf(
4347 (unsigned long long) ino);
4354 n = snprintf(buf, bufsize,
4356 (unsigned long long) ino);
4360 if (!determine_size && n > bufsize) {
4369 /* Restore name pointer to its original value */
4382 /*****************************************************
4383 set the ACLs on a file given an ascii description
4384 *******************************************************/
4385 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
4386 struct cli_state *ipc_cli, POLICY_HND *pol,
4387 const char *filename, const char *the_acl,
4388 int mode, int flags)
4392 SEC_DESC *sd = NULL, *old;
4393 SEC_ACL *dacl = NULL;
4394 DOM_SID *owner_sid = NULL;
4395 DOM_SID *grp_sid = NULL;
4400 BOOL numeric = True;
4402 /* the_acl will be null for REMOVE_ALL operations */
4404 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4408 /* if this is to set the entire ACL... */
4409 if (*the_acl == '*') {
4410 /* ... then increment past the first colon */
4414 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4415 CONST_DISCARD(char *, the_acl));
4423 /* The desired access below is the only one I could find that works
4424 with NT4, W2KP and Samba */
4426 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4429 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4430 filename, cli_errstr(cli)));
4435 old = cli_query_secdesc(cli, fnum, ctx);
4438 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4443 cli_close(cli, fnum);
4446 case SMBC_XATTR_MODE_REMOVE_ALL:
4447 old->dacl->num_aces = 0;
4448 SAFE_FREE(old->dacl->ace);
4449 SAFE_FREE(old->dacl);
4454 case SMBC_XATTR_MODE_REMOVE:
4455 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4458 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4459 if (sec_ace_equal(&sd->dacl->ace[i],
4460 &old->dacl->ace[j])) {
4462 for (k=j; k<old->dacl->num_aces-1;k++) {
4463 old->dacl->ace[k] = old->dacl->ace[k+1];
4465 old->dacl->num_aces--;
4466 if (old->dacl->num_aces == 0) {
4467 SAFE_FREE(old->dacl->ace);
4468 SAFE_FREE(old->dacl);
4485 case SMBC_XATTR_MODE_ADD:
4486 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4489 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4490 if (sid_equal(&sd->dacl->ace[i].trustee,
4491 &old->dacl->ace[j].trustee)) {
4492 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4497 old->dacl->ace[j] = sd->dacl->ace[i];
4503 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4509 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4510 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4516 case SMBC_XATTR_MODE_SET:
4518 owner_sid = old->owner_sid;
4519 grp_sid = old->grp_sid;
4523 case SMBC_XATTR_MODE_CHOWN:
4524 owner_sid = sd->owner_sid;
4527 case SMBC_XATTR_MODE_CHGRP:
4528 grp_sid = sd->grp_sid;
4532 /* Denied ACE entries must come before allowed ones */
4533 sort_acl(old->dacl);
4535 /* Create new security descriptor and set it */
4536 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4537 owner_sid, grp_sid, NULL, dacl, &sd_size);
4539 fnum = cli_nt_create(cli, filename,
4540 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4543 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4544 filename, cli_errstr(cli)));
4549 if (!cli_set_secdesc(cli, fnum, sd)) {
4550 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4557 cli_close(cli, fnum);
4567 int smbc_setxattr_ctx(SMBCCTX *context,
4578 fstring server, share, user, password, workgroup;
4584 if (!context || !context->internal ||
4585 !context->internal->_initialized) {
4587 errno = EINVAL; /* Best I can think of ... */
4599 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n", fname, name, (int) size, (const char*)value));
4601 if (smbc_parse_path(context, fname,
4602 server, sizeof(server),
4603 share, sizeof(share),
4606 password, sizeof(password),
4612 if (user[0] == (char)0) fstrcpy(user, context->user);
4614 fstrcpy(workgroup, context->workgroup);
4616 srv = smbc_server(context, server, share, workgroup, user, password);
4618 return -1; /* errno set by smbc_server */
4621 if (! srv->no_nt_session) {
4622 ipc_srv = smbc_attr_server(context, server, share,
4623 workgroup, user, password,
4625 srv->no_nt_session = True;
4630 ctx = talloc_init("smbc_setxattr");
4637 * Are they asking to set the entire set of known attributes?
4639 if (StrCaseCmp(name, "system.*") == 0 ||
4640 StrCaseCmp(name, "system.*+") == 0) {
4643 talloc_asprintf(ctx, "%s:%s", name+7, (const char *) value);
4651 ret = cacl_set(ctx, &srv->cli,
4652 &ipc_srv->cli, &pol, path,
4655 ? SMBC_XATTR_MODE_SET
4656 : SMBC_XATTR_MODE_ADD),
4662 /* get a DOS Attribute Descriptor with current attributes */
4663 dad = dos_attr_query(context, ctx, path, srv);
4665 /* Overwrite old with new, using what was provided */
4666 dos_attr_parse(context, dad, srv, namevalue);
4668 /* Set the new DOS attributes */
4669 if (! smbc_setatr(context, srv, path,
4675 /* cause failure if NT failed too */
4680 /* we only fail if both NT and DOS sets failed */
4681 if (ret < 0 && ! dad) {
4682 ret = -1; /* in case dad was null */
4688 talloc_destroy(ctx);
4693 * Are they asking to set an access control element or to set
4694 * the entire access control list?
4696 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4697 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4698 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4699 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4700 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4704 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4707 ret = -1; /* errno set by smbc_server() */
4709 else if (! namevalue) {
4713 ret = cacl_set(ctx, &srv->cli,
4714 &ipc_srv->cli, &pol, path,
4717 ? SMBC_XATTR_MODE_SET
4718 : SMBC_XATTR_MODE_ADD),
4721 talloc_destroy(ctx);
4726 * Are they asking to set the owner?
4728 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4729 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
4733 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4737 ret = -1; /* errno set by smbc_server() */
4739 else if (! namevalue) {
4743 ret = cacl_set(ctx, &srv->cli,
4744 &ipc_srv->cli, &pol, path,
4745 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4747 talloc_destroy(ctx);
4752 * Are they asking to set the group?
4754 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4755 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
4759 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4762 /* errno set by smbc_server() */
4765 else if (! namevalue) {
4769 ret = cacl_set(ctx, &srv->cli,
4770 &ipc_srv->cli, &pol, path,
4771 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4773 talloc_destroy(ctx);
4778 * Are they asking to set a DOS attribute?
4780 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4781 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4782 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4783 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4784 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
4786 /* get a DOS Attribute Descriptor with current attributes */
4787 dad = dos_attr_query(context, ctx, path, srv);
4790 talloc_asprintf(ctx, "%s:%s", name+16, (const char *) value);
4795 /* Overwrite old with provided new params */
4796 dos_attr_parse(context, dad, srv, namevalue);
4798 /* Set the new DOS attributes */
4799 ret2 = smbc_setatr(context, srv, path,
4805 /* ret2 has True (success) / False (failure) */
4816 talloc_destroy(ctx);
4820 /* Unsupported attribute name */
4821 talloc_destroy(ctx);
4826 int smbc_getxattr_ctx(SMBCCTX *context,
4835 fstring server, share, user, password, workgroup;
4841 if (!context || !context->internal ||
4842 !context->internal->_initialized) {
4844 errno = EINVAL; /* Best I can think of ... */
4856 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
4858 if (smbc_parse_path(context, fname,
4859 server, sizeof(server),
4860 share, sizeof(share),
4863 password, sizeof(password),
4869 if (user[0] == (char)0) fstrcpy(user, context->user);
4871 fstrcpy(workgroup, context->workgroup);
4873 srv = smbc_server(context, server, share, workgroup, user, password);
4875 return -1; /* errno set by smbc_server */
4878 if (! srv->no_nt_session) {
4879 ipc_srv = smbc_attr_server(context, server, share,
4880 workgroup, user, password,
4883 srv->no_nt_session = True;
4889 ctx = talloc_init("smbc:getxattr");
4895 /* Are they requesting a supported attribute? */
4896 if (StrCaseCmp(name, "system.*") == 0 ||
4897 StrnCaseCmp(name, "system.*!", 9) == 0 ||
4898 StrCaseCmp(name, "system.*+") == 0 ||
4899 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
4900 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4901 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
4902 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4903 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
4904 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4905 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4906 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
4907 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4908 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
4909 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4910 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
4911 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4912 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
4913 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4914 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
4915 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4916 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4917 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
4918 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
4921 ret = cacl_get(context, ctx, srv,
4922 ipc_srv == NULL ? NULL : &ipc_srv->cli,
4924 CONST_DISCARD(char *, name),
4925 CONST_DISCARD(char *, value), size);
4926 if (ret < 0 && errno == 0) {
4927 errno = smbc_errno(context, &srv->cli);
4929 talloc_destroy(ctx);
4933 /* Unsupported attribute name */
4934 talloc_destroy(ctx);
4940 int smbc_removexattr_ctx(SMBCCTX *context,
4947 fstring server, share, user, password, workgroup;
4952 if (!context || !context->internal ||
4953 !context->internal->_initialized) {
4955 errno = EINVAL; /* Best I can think of ... */
4967 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
4969 if (smbc_parse_path(context, fname,
4970 server, sizeof(server),
4971 share, sizeof(share),
4974 password, sizeof(password),
4980 if (user[0] == (char)0) fstrcpy(user, context->user);
4982 fstrcpy(workgroup, context->workgroup);
4984 srv = smbc_server(context, server, share, workgroup, user, password);
4986 return -1; /* errno set by smbc_server */
4989 if (! srv->no_nt_session) {
4990 ipc_srv = smbc_attr_server(context, server, share,
4991 workgroup, user, password,
4993 srv->no_nt_session = True;
4999 return -1; /* errno set by smbc_attr_server */
5002 ctx = talloc_init("smbc_removexattr");
5008 /* Are they asking to set the entire ACL? */
5009 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5010 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5013 ret = cacl_set(ctx, &srv->cli,
5014 &ipc_srv->cli, &pol, path,
5015 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5016 talloc_destroy(ctx);
5021 * Are they asking to remove one or more spceific security descriptor
5024 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5025 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5026 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5027 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5028 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5029 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5030 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5033 ret = cacl_set(ctx, &srv->cli,
5034 &ipc_srv->cli, &pol, path,
5035 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5036 talloc_destroy(ctx);
5040 /* Unsupported attribute name */
5041 talloc_destroy(ctx);
5046 int smbc_listxattr_ctx(SMBCCTX *context,
5052 * This isn't quite what listxattr() is supposed to do. This returns
5053 * the complete set of attribute names, always, rather than only those
5054 * attribute names which actually exist for a file. Hmmm...
5056 const char supported[] =
5059 "system.nt_sec_desc.revision\0"
5060 "system.nt_sec_desc.owner\0"
5061 "system.nt_sec_desc.owner+\0"
5062 "system.nt_sec_desc.group\0"
5063 "system.nt_sec_desc.group+\0"
5064 "system.nt_sec_desc.acl.*\0"
5065 "system.nt_sec_desc.acl\0"
5066 "system.nt_sec_desc.acl+\0"
5067 "system.nt_sec_desc.*\0"
5068 "system.nt_sec_desc.*+\0"
5069 "system.dos_attr.*\0"
5070 "system.dos_attr.mode\0"
5071 "system.dos_attr.c_time\0"
5072 "system.dos_attr.a_time\0"
5073 "system.dos_attr.m_time\0"
5077 return sizeof(supported);
5080 if (sizeof(supported) > size) {
5085 /* this can't be strcpy() because there are embedded null characters */
5086 memcpy(list, supported, sizeof(supported));
5087 return sizeof(supported);
5092 * Open a print file to be written to by other calls
5095 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
5097 fstring server, share, user, password;
5100 if (!context || !context->internal ||
5101 !context->internal->_initialized) {
5115 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5117 if (smbc_parse_path(context, fname,
5118 server, sizeof(server),
5119 share, sizeof(share),
5122 password, sizeof(password),
5128 /* What if the path is empty, or the file exists? */
5130 return context->open(context, fname, O_WRONLY, 666);
5135 * Routine to print a file on a remote server ...
5137 * We open the file, which we assume to be on a remote server, and then
5138 * copy it to a print file on the share specified by printq.
5141 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
5143 SMBCFILE *fid1, *fid2;
5144 int bytes, saverr, tot_bytes = 0;
5147 if (!c_file || !c_file->internal->_initialized || !c_print ||
5148 !c_print->internal->_initialized) {
5155 if (!fname && !printq) {
5162 /* Try to open the file for reading ... */
5164 if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5166 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5167 return -1; /* smbc_open sets errno */
5171 /* Now, try to open the printer file for writing */
5173 if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5175 saverr = errno; /* Save errno */
5176 c_file->close_fn(c_file, fid1);
5182 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5186 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5189 c_file->close_fn(c_file, fid1);
5190 c_print->close_fn(c_print, fid2);
5199 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5200 c_print->close_fn(c_print, fid2);
5214 * Routine to list print jobs on a printer share ...
5217 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
5220 fstring server, share, user, password, workgroup;
5223 if (!context || !context->internal ||
5224 !context->internal->_initialized) {
5238 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5240 if (smbc_parse_path(context, fname,
5241 server, sizeof(server),
5242 share, sizeof(share),
5245 password, sizeof(password),
5251 if (user[0] == (char)0) fstrcpy(user, context->user);
5253 fstrcpy(workgroup, context->workgroup);
5255 srv = smbc_server(context, server, share, workgroup, user, password);
5259 return -1; /* errno set by smbc_server */
5263 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
5265 errno = smbc_errno(context, &srv->cli);
5275 * Delete a print job from a remote printer share
5278 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
5281 fstring server, share, user, password, workgroup;
5285 if (!context || !context->internal ||
5286 !context->internal->_initialized) {
5300 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5302 if (smbc_parse_path(context, fname,
5303 server, sizeof(server),
5304 share, sizeof(share),
5307 password, sizeof(password),
5313 if (user[0] == (char)0) fstrcpy(user, context->user);
5315 fstrcpy(workgroup, context->workgroup);
5317 srv = smbc_server(context, server, share, workgroup, user, password);
5321 return -1; /* errno set by smbc_server */
5325 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5328 errno = smbc_errno(context, &srv->cli);
5329 else if (err == ERRnosuchprintjob)
5340 * Get a new empty handle to fill in with your own info
5342 SMBCCTX * smbc_new_context(void)
5346 context = SMB_MALLOC_P(SMBCCTX);
5352 ZERO_STRUCTP(context);
5354 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5355 if (!context->internal) {
5360 ZERO_STRUCTP(context->internal);
5363 /* ADD REASONABLE DEFAULTS */
5365 context->timeout = 20000; /* 20 seconds */
5367 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5368 context->options.urlencode_readdir_entries = False;/* backward compat */
5369 context->options.one_share_per_server = False;/* backward compat */
5371 context->open = smbc_open_ctx;
5372 context->creat = smbc_creat_ctx;
5373 context->read = smbc_read_ctx;
5374 context->write = smbc_write_ctx;
5375 context->close_fn = smbc_close_ctx;
5376 context->unlink = smbc_unlink_ctx;
5377 context->rename = smbc_rename_ctx;
5378 context->lseek = smbc_lseek_ctx;
5379 context->stat = smbc_stat_ctx;
5380 context->fstat = smbc_fstat_ctx;
5381 context->opendir = smbc_opendir_ctx;
5382 context->closedir = smbc_closedir_ctx;
5383 context->readdir = smbc_readdir_ctx;
5384 context->getdents = smbc_getdents_ctx;
5385 context->mkdir = smbc_mkdir_ctx;
5386 context->rmdir = smbc_rmdir_ctx;
5387 context->telldir = smbc_telldir_ctx;
5388 context->lseekdir = smbc_lseekdir_ctx;
5389 context->fstatdir = smbc_fstatdir_ctx;
5390 context->chmod = smbc_chmod_ctx;
5391 context->utimes = smbc_utimes_ctx;
5392 context->setxattr = smbc_setxattr_ctx;
5393 context->getxattr = smbc_getxattr_ctx;
5394 context->removexattr = smbc_removexattr_ctx;
5395 context->listxattr = smbc_listxattr_ctx;
5396 context->open_print_job = smbc_open_print_job_ctx;
5397 context->print_file = smbc_print_file_ctx;
5398 context->list_print_jobs = smbc_list_print_jobs_ctx;
5399 context->unlink_print_job = smbc_unlink_print_job_ctx;
5401 context->callbacks.check_server_fn = smbc_check_server;
5402 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5404 smbc_default_cache_functions(context);
5412 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5413 * and thus you'll be leaking memory if not handled properly.
5416 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
5425 DEBUG(1,("Performing aggressive shutdown.\n"));
5427 f = context->internal->_files;
5429 context->close_fn(context, f);
5432 context->internal->_files = NULL;
5434 /* First try to remove the servers the nice way. */
5435 if (context->callbacks.purge_cached_fn(context)) {
5438 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
5439 s = context->internal->_servers;
5441 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
5442 cli_shutdown(&s->cli);
5443 context->callbacks.remove_cached_srv_fn(context, s);
5445 DLIST_REMOVE(context->internal->_servers, s);
5449 context->internal->_servers = NULL;
5453 /* This is the polite way */
5454 if (context->callbacks.purge_cached_fn(context)) {
5455 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
5459 if (context->internal->_servers) {
5460 DEBUG(1, ("Active servers in context, free_context failed.\n"));
5464 if (context->internal->_files) {
5465 DEBUG(1, ("Active files in context, free_context failed.\n"));
5471 /* Things we have to clean up */
5472 SAFE_FREE(context->workgroup);
5473 SAFE_FREE(context->netbios_name);
5474 SAFE_FREE(context->user);
5476 DEBUG(3, ("Context %p succesfully freed\n", context));
5477 SAFE_FREE(context->internal);
5484 * Initialise the library etc
5486 * We accept a struct containing handle information.
5487 * valid values for info->debug from 0 to 100,
5488 * and insist that info->fn must be non-null.
5490 SMBCCTX * smbc_init_context(SMBCCTX * context)
5494 char *user = NULL, *home = NULL;
5496 if (!context || !context->internal) {
5501 /* Do not initialise the same client twice */
5502 if (context->internal->_initialized) {
5506 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
5513 if (!smbc_initialized) {
5514 /* Do some library wide intialisations the first time we get called */
5516 /* Set this to what the user wants */
5517 DEBUGLEVEL = context->debug;
5519 setup_logging( "libsmbclient", True);
5521 /* Here we would open the smb.conf file if needed ... */
5523 home = getenv("HOME");
5525 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5527 load_interfaces(); /* Load the list of interfaces ... */
5529 in_client = True; /* FIXME, make a param */
5531 if (!lp_load(conf, True, False, False)) {
5534 * Well, if that failed, try the dyn_CONFIGFILE
5535 * Which points to the standard locn, and if that
5536 * fails, silently ignore it and use the internal
5540 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
5541 DEBUG(5, ("Could not load either config file: "
5543 conf, dyn_CONFIGFILE));
5546 * We loaded the global config file. Now lets
5547 * load user-specific modifications to the
5550 slprintf(conf, sizeof(conf),
5551 "%s/.smb/smb.conf.append", home);
5552 if (!lp_load(conf, True, False, False)) {
5554 ("Could not append config file: "
5561 reopen_logs(); /* Get logging working ... */
5564 * Block SIGPIPE (from lib/util_sock.c: write())
5565 * It is not needed and should not stop execution
5567 BlockSignals(True, SIGPIPE);
5569 /* Done with one-time initialisation */
5570 smbc_initialized = 1;
5574 if (!context->user) {
5576 * FIXME: Is this the best way to get the user info?
5578 user = getenv("USER");
5579 /* walk around as "guest" if no username can be found */
5580 if (!user) context->user = SMB_STRDUP("guest");
5581 else context->user = SMB_STRDUP(user);
5584 if (!context->netbios_name) {
5586 * We try to get our netbios name from the config. If that fails we fall
5587 * back on constructing our netbios name from our hostname etc
5589 if (global_myname()) {
5590 context->netbios_name = SMB_STRDUP(global_myname());
5594 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
5597 context->netbios_name = SMB_MALLOC(17);
5598 if (!context->netbios_name) {
5602 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
5606 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
5608 if (!context->workgroup) {
5609 if (lp_workgroup()) {
5610 context->workgroup = SMB_STRDUP(lp_workgroup());
5613 /* TODO: Think about a decent default workgroup */
5614 context->workgroup = SMB_STRDUP("samba");
5618 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
5620 /* shortest timeout is 1 second */
5621 if (context->timeout > 0 && context->timeout < 1000)
5622 context->timeout = 1000;
5625 * FIXME: Should we check the function pointers here?
5628 context->internal->_initialized = 1;
5634 /* Return the verion of samba, and thus libsmbclient */
5638 return samba_version_string();