2 Unix SMB/Netbios implementation.
3 SMB client library implementation
4 Copyright (C) Andrew Tridgell 1998
5 Copyright (C) Richard Sharpe 2000, 2002
6 Copyright (C) John Terpstra 2000
7 Copyright (C) Tom Jansen (Ninja ISD) 2002
8 Copyright (C) Derrell Lipman 2003, 2004
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include "include/libsmb_internal.h"
31 * DOS Attribute values (used internally)
33 typedef struct DOS_ATTR_DESC {
44 * Internal flags for extended attributes
47 /* internal mode values */
48 #define SMBC_XATTR_MODE_ADD 1
49 #define SMBC_XATTR_MODE_REMOVE 2
50 #define SMBC_XATTR_MODE_REMOVE_ALL 3
51 #define SMBC_XATTR_MODE_SET 4
52 #define SMBC_XATTR_MODE_CHOWN 5
53 #define SMBC_XATTR_MODE_CHGRP 6
55 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
57 /*We should test for this in configure ... */
59 #define ENOTSUP EOPNOTSUPP
63 * Functions exported by libsmb_cache.c that we need here
65 int smbc_default_cache_functions(SMBCCTX *context);
68 * check if an element is part of the list.
69 * FIXME: Does not belong here !
70 * Can anyone put this in a macro in dlinklist.h ?
73 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
74 if (!p || !list) return False;
76 if (p == list) return True;
83 * Find an lsa pipe handle associated with a cli struct.
85 static struct rpc_pipe_client *
86 find_lsa_pipe_hnd(struct cli_state *ipc_cli)
88 struct rpc_pipe_client *pipe_hnd;
90 for (pipe_hnd = ipc_cli->pipe_list;
92 pipe_hnd = pipe_hnd->next) {
94 if (pipe_hnd->pipe_idx == PI_LSARPC) {
103 smbc_close_ctx(SMBCCTX *context,
106 smbc_lseek_ctx(SMBCCTX *context,
111 extern BOOL in_client;
114 * Is the logging working / configfile read ?
116 static int smbc_initialized = 0;
119 hex2int( unsigned int _char )
121 if ( _char >= 'A' && _char <='F')
122 return _char - 'A' + 10;
123 if ( _char >= 'a' && _char <='f')
124 return _char - 'a' + 10;
125 if ( _char >= '0' && _char <='9')
133 * Convert strings of %xx to their single character equivalent. Each 'x' must
134 * be a valid hexadecimal digit, or that % sequence is left undecoded.
136 * dest may, but need not be, the same pointer as src.
138 * Returns the number of % sequences which could not be converted due to lack
139 * of two following hexadecimal digits.
142 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
144 int old_length = strlen(src);
150 if ( old_length == 0 ) {
155 while ( i < old_length ) {
156 unsigned char character = src[ i++ ];
158 if (character == '%') {
159 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
160 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
162 /* Replace valid sequence */
163 if (a != -1 && b != -1) {
165 /* Replace valid %xx sequence with %dd */
166 character = (a * 16) + b;
168 if (character == '\0') {
169 break; /* Stop at %00 */
184 strncpy(dest, temp, max_dest_len);
192 * Convert any characters not specifically allowed in a URL into their %xx
195 * Returns the remaining buffer length.
198 smbc_urlencode(char * dest, char * src, int max_dest_len)
200 char hex[] = "0123456789ABCDEF";
202 for (; *src != '\0' && max_dest_len >= 3; src++) {
214 *dest++ = hex[(*src >> 4) & 0x0f];
215 *dest++ = hex[*src & 0x0f];
230 * Function to parse a path and turn it into components
232 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
233 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
234 * general format ("smb:" only; we do not look for "cifs:").
238 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
242 * smb:// Show all workgroups.
244 * The method of locating the list of workgroups varies
245 * depending upon the setting of the context variable
246 * context->options.browse_max_lmb_count. This value
247 * determine the maximum number of local master browsers to
248 * query for the list of workgroups. In order to ensure that
249 * a complete list of workgroups is obtained, all master
250 * browsers must be queried, but if there are many
251 * workgroups, the time spent querying can begin to add up.
252 * For small networks (not many workgroups), it is suggested
253 * that this variable be set to 0, indicating query all local
254 * master browsers. When the network has many workgroups, a
255 * reasonable setting for this variable might be around 3.
257 * smb://name/ if name<1D> or name<1B> exists, list servers in
258 * workgroup, else, if name<20> exists, list all shares
261 * If "options" are provided, this function returns the entire option list as a
262 * string, for later parsing by the caller. Note that currently, no options
266 static const char *smbc_prefix = "smb:";
269 smbc_parse_path(SMBCCTX *context,
271 char *server, int server_len,
272 char *share, int share_len,
273 char *path, int path_len,
274 char *user, int user_len,
275 char *password, int password_len,
276 char *options, int options_len)
284 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
285 if (options != NULL && options_len > 0) {
286 options[0] = (char)0;
290 /* see if it has the right prefix */
291 len = strlen(smbc_prefix);
292 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
293 return -1; /* What about no smb: ? */
298 /* Watch the test below, we are testing to see if we should exit */
300 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
302 DEBUG(1, ("Invalid path (does not begin with smb://"));
307 p += 2; /* Skip the double slash */
309 /* See if any options were specified */
310 if ((q = strrchr(p, '?')) != NULL ) {
311 /* There are options. Null terminate here and point to them */
314 DEBUG(4, ("Found options '%s'", q));
316 /* Copy the options */
317 if (options != NULL && options_len > 0) {
318 safe_strcpy(options, q, options_len - 1);
327 strncpy(server, context->workgroup,
328 ((strlen(context->workgroup) < 16)
329 ? strlen(context->workgroup)
336 * ok, its for us. Now parse out the server, share etc.
338 * However, we want to parse out [[domain;]user[:password]@] if it
342 /* check that '@' occurs before '/', if '/' exists at all */
343 q = strchr_m(p, '@');
344 r = strchr_m(p, '/');
345 if (q && (!r || q < r)) {
346 pstring username, passwd, domain;
347 const char *u = userinfo;
349 next_token(&p, userinfo, "@", sizeof(fstring));
351 username[0] = passwd[0] = domain[0] = 0;
353 if (strchr_m(u, ';')) {
355 next_token(&u, domain, ";", sizeof(fstring));
359 if (strchr_m(u, ':')) {
361 next_token(&u, username, ":", sizeof(fstring));
368 pstrcpy(username, u);
373 strncpy(user, username, user_len); /* FIXME, domain */
376 strncpy(password, passwd, password_len);
380 if (!next_token(&p, server, "/", sizeof(fstring))) {
386 if (*p == (char)0) goto decoding; /* That's it ... */
388 if (!next_token(&p, share, "/", sizeof(fstring))) {
394 safe_strcpy(path, p, path_len - 1);
396 all_string_sub(path, "/", "\\", 0);
399 (void) smbc_urldecode(path, path, path_len);
400 (void) smbc_urldecode(server, server, server_len);
401 (void) smbc_urldecode(share, share, share_len);
402 (void) smbc_urldecode(user, user, user_len);
403 (void) smbc_urldecode(password, password, password_len);
409 * Verify that the options specified in a URL are valid
412 smbc_check_options(char *server,
417 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' "
418 "path='%s' options='%s'\n",
419 server, share, path, options));
421 /* No options at all is always ok */
422 if (! *options) return 0;
424 /* Currently, we don't support any options. */
429 * Convert an SMB error into a UNIX error ...
432 smbc_errno(SMBCCTX *context,
435 int ret = cli_errno(c);
437 if (cli_is_dos_error(c)) {
441 cli_dos_error(c, &eclass, &ecode);
443 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
444 (int)eclass, (int)ecode, (int)ecode, ret));
448 status = cli_nt_error(c);
450 DEBUG(3,("smbc errno %s -> %d\n",
451 nt_errstr(status), ret));
458 * Check a server for being alive and well.
459 * returns 0 if the server is in shape. Returns 1 on error
461 * Also useable outside libsmbclient to enable external cache
462 * to do some checks too.
465 smbc_check_server(SMBCCTX * context,
468 if ( send_keepalive(server->cli.fd) == False )
471 /* connection is ok */
476 * Remove a server from the cached server list it's unused.
477 * On success, 0 is returned. 1 is returned if the server could not be removed.
479 * Also useable outside libsmbclient
482 smbc_remove_unused_server(SMBCCTX * context,
487 /* are we being fooled ? */
488 if (!context || !context->internal ||
489 !context->internal->_initialized || !srv) return 1;
492 /* Check all open files/directories for a relation with this server */
493 for (file = context->internal->_files; file; file=file->next) {
494 if (file->srv == srv) {
496 DEBUG(3, ("smbc_remove_usused_server: "
497 "%p still used by %p.\n",
503 DLIST_REMOVE(context->internal->_servers, srv);
505 cli_shutdown(&srv->cli);
507 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
509 context->callbacks.remove_cached_srv_fn(context, srv);
517 find_server(SMBCCTX *context,
529 srv = context->callbacks.get_cached_srv_fn(context, server, share,
530 workgroup, username);
532 if (!auth_called && !srv && (!username[0] || !password[0])) {
533 context->callbacks.auth_fn(server, share,
534 workgroup, sizeof(fstring),
535 username, sizeof(fstring),
536 password, sizeof(fstring));
538 * However, smbc_auth_fn may have picked up info relating to
539 * an existing connection, so try for an existing connection
543 goto check_server_cache;
548 if (context->callbacks.check_server_fn(context, srv)) {
550 * This server is no good anymore
551 * Try to remove it and check for more possible
552 * servers in the cache
554 if (context->callbacks.remove_unused_server_fn(context,
557 * We could not remove the server completely,
558 * remove it from the cache so we will not get
559 * it again. It will be removed when the last
560 * file/dir is closed.
562 context->callbacks.remove_cached_srv_fn(context,
567 * Maybe there are more cached connections to this
570 goto check_server_cache;
580 * Connect to a server, possibly on an existing connection
582 * Here, what we want to do is: If the server and username
583 * match an existing connection, reuse that, otherwise, establish a
586 * If we have to create a new connection, call the auth_fn to get the
587 * info we need, unless the username and password were passed in.
591 smbc_server(SMBCCTX *context,
592 BOOL connect_if_not_found,
601 struct nmb_name called, calling;
602 const char *server_n = server;
605 int tried_reverse = 0;
608 const char *username_used;
613 if (server[0] == 0) {
618 /* Look for a cached connection */
619 srv = find_server(context, server, share,
620 workgroup, username, password);
623 * If we found a connection and we're only allowed one share per
626 if (srv && *share != '\0' && context->options.one_share_per_server) {
629 * ... then if there's no current connection to the share,
630 * connect to it. find_server(), or rather the function
631 * pointed to by context->callbacks.get_cached_srv_fn which
632 * was called by find_server(), will have issued a tree
633 * disconnect if the requested share is not the same as the
634 * one that was already connected.
636 if (srv->cli.cnum == (uint16) -1) {
637 /* Ensure we have accurate auth info */
638 context->callbacks.auth_fn(server, share,
639 workgroup, sizeof(fstring),
640 username, sizeof(fstring),
641 password, sizeof(fstring));
643 if (! cli_send_tconX(&srv->cli, share, "?????",
644 password, strlen(password)+1)) {
646 errno = smbc_errno(context, &srv->cli);
647 cli_shutdown(&srv->cli);
648 context->callbacks.remove_cached_srv_fn(context,
654 * Regenerate the dev value since it's based on both
658 srv->dev = (dev_t)(str_checksum(server) ^
659 str_checksum(share));
664 /* If we have a connection... */
667 /* ... then we're done here. Give 'em what they came for. */
671 /* If we're not asked to connect when a connection doesn't exist... */
672 if (! connect_if_not_found) {
673 /* ... then we're done here. */
677 make_nmb_name(&calling, context->netbios_name, 0x0);
678 make_nmb_name(&called , server, 0x20);
680 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
682 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
685 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
689 /* have to open a new connection */
690 if (!cli_initialise(&c)) {
695 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
696 c.use_kerberos = True;
698 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
699 c.fallback_after_kerberos = True;
702 c.timeout = context->timeout;
705 * Force use of port 139 for first try if share is $IPC, empty, or
706 * null, so browse lists can work
708 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
709 port_try_first = 139;
712 port_try_first = 445;
716 c.port = port_try_first;
718 if (!cli_connect(&c, server_n, &ip)) {
720 /* First connection attempt failed. Try alternate port. */
721 c.port = port_try_next;
723 if (!cli_connect(&c, server_n, &ip)) {
730 if (!cli_session_request(&c, &calling, &called)) {
732 if (strcmp(called.name, "*SMBSERVER")) {
733 make_nmb_name(&called , "*SMBSERVER", 0x20);
736 else { /* Try one more time, but ensure we don't loop */
738 /* Only try this if server is an IP address ... */
740 if (is_ipaddress(server) && !tried_reverse) {
742 struct in_addr rem_ip;
744 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
745 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
750 tried_reverse++; /* Yuck */
752 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
753 make_nmb_name(&called, remote_name, 0x20);
764 DEBUG(4,(" session request ok\n"));
766 if (!cli_negprot(&c)) {
772 username_used = username;
774 if (!cli_session_setup(&c, username_used,
775 password, strlen(password),
776 password, strlen(password),
779 /* Failed. Try an anonymous login, if allowed by flags. */
782 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
783 !cli_session_setup(&c, username_used,
794 DEBUG(4,(" session setup ok\n"));
796 if (!cli_send_tconX(&c, share, "?????",
797 password, strlen(password)+1)) {
798 errno = smbc_errno(context, &c);
803 DEBUG(4,(" tconx ok\n"));
806 * Ok, we have got a nice connection
807 * Let's allocate a server structure.
810 srv = SMB_MALLOC_P(SMBCSRV);
818 srv->cli.allocated = False;
819 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
820 srv->no_pathinfo = False;
821 srv->no_pathinfo2 = False;
822 srv->no_nt_session = False;
824 /* now add it to the cache (internal or external) */
825 /* Let the cache function set errno if it wants to */
827 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
828 int saved_errno = errno;
829 DEBUG(3, (" Failed to add server to cache\n"));
837 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
838 server, share, srv));
840 DLIST_ADD(context->internal->_servers, srv);
845 if (!srv) return NULL;
852 * Connect to a server for getting/setting attributes, possibly on an existing
853 * connection. This works similarly to smbc_server().
856 smbc_attr_server(SMBCCTX *context,
865 struct cli_state *ipc_cli;
866 struct rpc_pipe_client *pipe_hnd;
868 SMBCSRV *ipc_srv=NULL;
871 * See if we've already created this special connection. Reference
872 * our "special" share name '*IPC$', which is an impossible real share
873 * name due to the leading asterisk.
875 ipc_srv = find_server(context, server, "*IPC$",
876 workgroup, username, password);
879 /* We didn't find a cached connection. Get the password */
880 if (*password == '\0') {
881 /* ... then retrieve it now. */
882 context->callbacks.auth_fn(server, share,
883 workgroup, sizeof(fstring),
884 username, sizeof(fstring),
885 password, sizeof(fstring));
889 nt_status = cli_full_connection(&ipc_cli,
890 global_myname(), server,
891 &ip, 0, "IPC$", "?????",
895 if (! NT_STATUS_IS_OK(nt_status)) {
896 DEBUG(1,("cli_full_connection failed! (%s)\n",
897 nt_errstr(nt_status)));
902 ipc_srv = SMB_MALLOC_P(SMBCSRV);
905 cli_shutdown(ipc_cli);
909 ZERO_STRUCTP(ipc_srv);
910 ipc_srv->cli = *ipc_cli;
911 ipc_srv->cli.allocated = False;
916 pipe_hnd = cli_rpc_pipe_open_noauth(&ipc_srv->cli,
920 DEBUG(1, ("cli_nt_session_open fail!\n"));
922 cli_shutdown(&ipc_srv->cli);
928 * Some systems don't support
929 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
930 * so we might as well do it too.
933 nt_status = rpccli_lsa_open_policy(
935 ipc_srv->cli.mem_ctx,
937 GENERIC_EXECUTE_ACCESS,
940 if (!NT_STATUS_IS_OK(nt_status)) {
941 errno = smbc_errno(context, &ipc_srv->cli);
942 cli_shutdown(&ipc_srv->cli);
947 /* now add it to the cache (internal or external) */
949 errno = 0; /* let cache function set errno if it likes */
950 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
955 DEBUG(3, (" Failed to add server to cache\n"));
959 cli_shutdown(&ipc_srv->cli);
964 DLIST_ADD(context->internal->_servers, ipc_srv);
971 * Routine to open() a file ...
975 smbc_open_ctx(SMBCCTX *context,
980 fstring server, share, user, password, workgroup;
983 struct cli_state *targetcli;
985 SMBCFILE *file = NULL;
988 if (!context || !context->internal ||
989 !context->internal->_initialized) {
991 errno = EINVAL; /* Best I can think of ... */
1003 if (smbc_parse_path(context, fname,
1004 server, sizeof(server),
1005 share, sizeof(share),
1008 password, sizeof(password),
1014 if (user[0] == (char)0) fstrcpy(user, context->user);
1016 fstrcpy(workgroup, context->workgroup);
1018 srv = smbc_server(context, True,
1019 server, share, workgroup, user, password);
1023 if (errno == EPERM) errno = EACCES;
1024 return NULL; /* smbc_server sets errno */
1028 /* Hmmm, the test for a directory is suspect here ... FIXME */
1030 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1037 file = SMB_MALLOC_P(SMBCFILE);
1048 /*d_printf(">>>open: resolving %s\n", path);*/
1049 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1051 d_printf("Could not resolve %s\n", path);
1054 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1056 if ( targetcli->dfsroot )
1059 pstrcpy(temppath, targetpath);
1060 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1063 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1065 /* Handle the error ... */
1068 errno = smbc_errno(context, targetcli);
1073 /* Fill in file struct */
1076 file->fname = SMB_STRDUP(fname);
1081 DLIST_ADD(context->internal->_files, file);
1084 * If the file was opened in O_APPEND mode, all write
1085 * operations should be appended to the file. To do that,
1086 * though, using this protocol, would require a getattrE()
1087 * call for each and every write, to determine where the end
1088 * of the file is. (There does not appear to be an append flag
1089 * in the protocol.) Rather than add all of that overhead of
1090 * retrieving the current end-of-file offset prior to each
1091 * write operation, we'll assume that most append operations
1092 * will continuously write, so we'll just set the offset to
1093 * the end of the file now and hope that's adequate.
1095 * Note to self: If this proves inadequate, and O_APPEND
1096 * should, in some cases, be forced for each write, add a
1097 * field in the context options structure, for
1098 * "strict_append_mode" which would select between the current
1099 * behavior (if FALSE) or issuing a getattrE() prior to each
1100 * write and forcing the write to the end of the file (if
1101 * TRUE). Adding that capability will likely require adding
1102 * an "append" flag into the _SMBCFILE structure to track
1103 * whether a file was opened in O_APPEND mode. -- djl
1105 if (flags & O_APPEND) {
1106 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1107 (void) smbc_close_ctx(context, file);
1117 /* Check if opendir needed ... */
1122 eno = smbc_errno(context, &srv->cli);
1123 file = context->opendir(context, fname);
1124 if (!file) errno = eno;
1129 errno = EINVAL; /* FIXME, correct errno ? */
1135 * Routine to create a file
1138 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1141 smbc_creat_ctx(SMBCCTX *context,
1146 if (!context || !context->internal ||
1147 !context->internal->_initialized) {
1154 return smbc_open_ctx(context, path, creat_bits, mode);
1158 * Routine to read() a file ...
1162 smbc_read_ctx(SMBCCTX *context,
1168 fstring server, share, user, password;
1169 pstring path, targetpath;
1170 struct cli_state *targetcli;
1175 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1176 * appears to pass file->offset (which is type off_t) differently than
1177 * a local variable of type off_t. Using local variable "offset" in
1178 * the call to cli_read() instead of file->offset fixes a problem
1179 * retrieving data at an offset greater than 4GB.
1181 off_t offset = file->offset;
1183 if (!context || !context->internal ||
1184 !context->internal->_initialized) {
1191 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1193 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1200 /* Check that the buffer exists ... */
1209 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1210 if (smbc_parse_path(context, file->fname,
1211 server, sizeof(server),
1212 share, sizeof(share),
1215 password, sizeof(password),
1221 /*d_printf(">>>read: resolving %s\n", path);*/
1222 if (!cli_resolve_path("", &file->srv->cli, path,
1223 &targetcli, targetpath))
1225 d_printf("Could not resolve %s\n", path);
1228 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1230 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1234 errno = smbc_errno(context, targetcli);
1239 file->offset += ret;
1241 DEBUG(4, (" --> %d\n", ret));
1243 return ret; /* Success, ret bytes of data ... */
1248 * Routine to write() a file ...
1252 smbc_write_ctx(SMBCCTX *context,
1259 fstring server, share, user, password;
1260 pstring path, targetpath;
1261 struct cli_state *targetcli;
1263 offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1265 if (!context || !context->internal ||
1266 !context->internal->_initialized) {
1273 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1280 /* Check that the buffer exists ... */
1289 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1290 if (smbc_parse_path(context, file->fname,
1291 server, sizeof(server),
1292 share, sizeof(share),
1295 password, sizeof(password),
1301 /*d_printf(">>>write: resolving %s\n", path);*/
1302 if (!cli_resolve_path("", &file->srv->cli, path,
1303 &targetcli, targetpath))
1305 d_printf("Could not resolve %s\n", path);
1308 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1311 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1315 errno = smbc_errno(context, targetcli);
1320 file->offset += ret;
1322 return ret; /* Success, 0 bytes of data ... */
1326 * Routine to close() a file ...
1330 smbc_close_ctx(SMBCCTX *context,
1334 fstring server, share, user, password;
1335 pstring path, targetpath;
1336 struct cli_state *targetcli;
1338 if (!context || !context->internal ||
1339 !context->internal->_initialized) {
1346 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1356 return context->closedir(context, file);
1360 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1361 if (smbc_parse_path(context, file->fname,
1362 server, sizeof(server),
1363 share, sizeof(share),
1366 password, sizeof(password),
1372 /*d_printf(">>>close: resolving %s\n", path);*/
1373 if (!cli_resolve_path("", &file->srv->cli, path,
1374 &targetcli, targetpath))
1376 d_printf("Could not resolve %s\n", path);
1379 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1381 if (!cli_close(targetcli, file->cli_fd)) {
1383 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1385 /* Deallocate slot and remove the server
1386 * from the server cache if unused */
1387 errno = smbc_errno(context, targetcli);
1389 DLIST_REMOVE(context->internal->_files, file);
1390 SAFE_FREE(file->fname);
1392 context->callbacks.remove_unused_server_fn(context, srv);
1398 DLIST_REMOVE(context->internal->_files, file);
1399 SAFE_FREE(file->fname);
1406 * Get info from an SMB server on a file. Use a qpathinfo call first
1407 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1410 smbc_getatr(SMBCCTX * context,
1422 struct cli_state *targetcli;
1424 if (!context || !context->internal ||
1425 !context->internal->_initialized) {
1432 /* path fixup for . and .. */
1433 if (strequal(path, ".") || strequal(path, ".."))
1434 pstrcpy(fixedpath, "\\");
1437 pstrcpy(fixedpath, path);
1438 trim_string(fixedpath, NULL, "\\..");
1439 trim_string(fixedpath, NULL, "\\.");
1441 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1443 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1445 d_printf("Couldn't resolve %s\n", path);
1449 if ( targetcli->dfsroot )
1452 pstrcpy(temppath, targetpath);
1453 cli_dfs_make_full_path(targetpath, targetcli->desthost,
1454 targetcli->share, temppath);
1457 if (!srv->no_pathinfo2 &&
1458 cli_qpathinfo2(targetcli, targetpath,
1459 c_time, a_time, m_time, NULL, size, mode, ino)) {
1463 /* if this is NT then don't bother with the getatr */
1464 if (targetcli->capabilities & CAP_NT_SMBS) {
1469 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1470 if (m_time != NULL) {
1471 if (a_time != NULL) *a_time = *m_time;
1472 if (c_time != NULL) *c_time = *m_time;
1474 srv->no_pathinfo2 = True;
1484 * Set file info on an SMB server. Use setpathinfo call first. If that
1485 * fails, use setattrE..
1487 * Access and modification time parameters are always used and must be
1488 * provided. Create time, if zero, will be determined from the actual create
1489 * time of the file. If non-zero, the create time will be set as well.
1491 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1494 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1495 time_t c_time, time_t a_time, time_t m_time,
1502 * Get the create time of the file (if not provided); we'll need it in
1505 if (! srv->no_pathinfo && c_time == 0) {
1506 if (! cli_qpathinfo(&srv->cli, path,
1507 &c_time, NULL, NULL, NULL, NULL)) {
1508 /* qpathinfo not available */
1509 srv->no_pathinfo = True;
1512 * We got a creation time. Some OS versions don't
1513 * return a valid create time, though. If we got an
1514 * invalid time, start with the current time instead.
1516 if (c_time == 0 || c_time == (time_t) -1) {
1517 c_time = time(NULL);
1521 * We got a creation time. For sanity sake, since
1522 * there is no POSIX function to set the create time
1523 * of a file, if the existing create time is greater
1524 * than either of access time or modification time,
1525 * set create time to the smallest of those. This
1526 * ensure that the create time of a file is never
1527 * greater than its last access or modification time.
1529 if (c_time > a_time) c_time = a_time;
1530 if (c_time > m_time) c_time = m_time;
1535 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1536 * modern function for "new code" to be using, and it works given a
1537 * filename rather than requiring that the file be opened to have its
1538 * attributes manipulated.
1540 if (srv->no_pathinfo ||
1541 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1544 * setpathinfo is not supported; go to plan B.
1546 * cli_setatr() does not work on win98, and it also doesn't
1547 * support setting the access time (only the modification
1548 * time), so in all cases, we open the specified file and use
1549 * cli_setattrE() which should work on all OS versions, and
1550 * supports both times.
1553 /* Don't try {q,set}pathinfo() again, with this server */
1554 srv->no_pathinfo = True;
1557 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1559 errno = smbc_errno(context, &srv->cli);
1564 * Get the creat time of the file (if it wasn't provided).
1565 * We'll need it in the set call
1568 ret = cli_getattrE(&srv->cli, fd,
1570 &c_time, NULL, NULL);
1575 /* If we got create time, set times */
1577 /* Some OS versions don't support create time */
1578 if (c_time == 0 || c_time == -1) {
1579 c_time = time(NULL);
1583 * For sanity sake, since there is no POSIX function
1584 * to set the create time of a file, if the existing
1585 * create time is greater than either of access time
1586 * or modification time, set create time to the
1587 * smallest of those. This ensure that the create
1588 * time of a file is never greater than its last
1589 * access or modification time.
1591 if (c_time > a_time) c_time = a_time;
1592 if (c_time > m_time) c_time = m_time;
1594 /* Set the new attributes */
1595 ret = cli_setattrE(&srv->cli, fd,
1596 c_time, a_time, m_time);
1597 cli_close(&srv->cli, fd);
1601 * Unfortunately, setattrE() doesn't have a provision for
1602 * setting the access mode (attributes). We'll have to try
1603 * cli_setatr() for that, and with only this parameter, it
1604 * seems to work on win98.
1606 if (ret && mode != (uint16) -1) {
1607 ret = cli_setatr(&srv->cli, path, mode, 0);
1611 errno = smbc_errno(context, &srv->cli);
1620 * Routine to unlink() a file
1624 smbc_unlink_ctx(SMBCCTX *context,
1627 fstring server, share, user, password, workgroup;
1628 pstring path, targetpath;
1629 struct cli_state *targetcli;
1630 SMBCSRV *srv = NULL;
1632 if (!context || !context->internal ||
1633 !context->internal->_initialized) {
1635 errno = EINVAL; /* Best I can think of ... */
1647 if (smbc_parse_path(context, fname,
1648 server, sizeof(server),
1649 share, sizeof(share),
1652 password, sizeof(password),
1658 if (user[0] == (char)0) fstrcpy(user, context->user);
1660 fstrcpy(workgroup, context->workgroup);
1662 srv = smbc_server(context, True,
1663 server, share, workgroup, user, password);
1667 return -1; /* smbc_server sets errno */
1671 /*d_printf(">>>unlink: resolving %s\n", path);*/
1672 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1674 d_printf("Could not resolve %s\n", path);
1677 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1679 if (!cli_unlink(targetcli, targetpath)) {
1681 errno = smbc_errno(context, targetcli);
1683 if (errno == EACCES) { /* Check if the file is a directory */
1688 time_t m_time = 0, a_time = 0, c_time = 0;
1691 if (!smbc_getatr(context, srv, path, &mode, &size,
1692 &c_time, &a_time, &m_time, &ino)) {
1694 /* Hmmm, bad error ... What? */
1696 errno = smbc_errno(context, targetcli);
1702 if (IS_DOS_DIR(mode))
1705 errno = saverr; /* Restore this */
1714 return 0; /* Success ... */
1719 * Routine to rename() a file
1723 smbc_rename_ctx(SMBCCTX *ocontext,
1739 pstring targetpath1;
1740 pstring targetpath2;
1741 struct cli_state *targetcli1;
1742 struct cli_state *targetcli2;
1743 SMBCSRV *srv = NULL;
1745 if (!ocontext || !ncontext ||
1746 !ocontext->internal || !ncontext->internal ||
1747 !ocontext->internal->_initialized ||
1748 !ncontext->internal->_initialized) {
1750 errno = EINVAL; /* Best I can think of ... */
1755 if (!oname || !nname) {
1762 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1764 smbc_parse_path(ocontext, oname,
1765 server1, sizeof(server1),
1766 share1, sizeof(share1),
1767 path1, sizeof(path1),
1768 user1, sizeof(user1),
1769 password1, sizeof(password1),
1772 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1774 smbc_parse_path(ncontext, nname,
1775 server2, sizeof(server2),
1776 share2, sizeof(share2),
1777 path2, sizeof(path2),
1778 user2, sizeof(user2),
1779 password2, sizeof(password2),
1782 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1784 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1785 strcmp(user1, user2)) {
1787 /* Can't rename across file systems, or users?? */
1794 fstrcpy(workgroup, ocontext->workgroup);
1796 srv = smbc_server(ocontext, True,
1797 server1, share1, workgroup, user1, password1);
1804 /*d_printf(">>>rename: resolving %s\n", path1);*/
1805 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1807 d_printf("Could not resolve %s\n", path1);
1810 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1811 /*d_printf(">>>rename: resolving %s\n", path2);*/
1812 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1814 d_printf("Could not resolve %s\n", path2);
1817 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1819 if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1820 strcmp(targetcli1->share, targetcli2->share))
1822 /* can't rename across file systems */
1828 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1829 int eno = smbc_errno(ocontext, targetcli1);
1831 if (eno != EEXIST ||
1832 !cli_unlink(targetcli1, targetpath2) ||
1833 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1841 return 0; /* Success */
1846 * A routine to lseek() a file
1850 smbc_lseek_ctx(SMBCCTX *context,
1856 fstring server, share, user, password;
1857 pstring path, targetpath;
1858 struct cli_state *targetcli;
1860 if (!context || !context->internal ||
1861 !context->internal->_initialized) {
1868 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1878 return -1; /* Can't lseek a dir ... */
1884 file->offset = offset;
1888 file->offset += offset;
1892 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1893 if (smbc_parse_path(context, file->fname,
1894 server, sizeof(server),
1895 share, sizeof(share),
1898 password, sizeof(password),
1905 /*d_printf(">>>lseek: resolving %s\n", path);*/
1906 if (!cli_resolve_path("", &file->srv->cli, path,
1907 &targetcli, targetpath))
1909 d_printf("Could not resolve %s\n", path);
1912 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1914 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1915 &size, NULL, NULL, NULL, NULL, NULL))
1917 SMB_OFF_T b_size = size;
1918 if (!cli_getattrE(targetcli, file->cli_fd,
1919 NULL, &b_size, NULL, NULL, NULL))
1926 file->offset = size + offset;
1935 return file->offset;
1940 * Generate an inode number from file name for those things that need it
1944 smbc_inode(SMBCCTX *context,
1948 if (!context || !context->internal ||
1949 !context->internal->_initialized) {
1956 if (!*name) return 2; /* FIXME, why 2 ??? */
1957 return (ino_t)str_checksum(name);
1962 * Routine to put basic stat info into a stat structure ... Used by stat and
1967 smbc_setup_stat(SMBCCTX *context,
1976 if (IS_DOS_DIR(mode)) {
1977 st->st_mode = SMBC_DIR_MODE;
1979 st->st_mode = SMBC_FILE_MODE;
1982 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1983 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1984 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1985 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1988 #ifdef HAVE_STAT_ST_BLKSIZE
1989 st->st_blksize = 512;
1991 #ifdef HAVE_STAT_ST_BLOCKS
1992 st->st_blocks = (size+511)/512;
1994 st->st_uid = getuid();
1995 st->st_gid = getgid();
1997 if (IS_DOS_DIR(mode)) {
2003 if (st->st_ino == 0) {
2004 st->st_ino = smbc_inode(context, fname);
2007 return True; /* FIXME: Is this needed ? */
2012 * Routine to stat a file given a name
2016 smbc_stat_ctx(SMBCCTX *context,
2034 if (!context || !context->internal ||
2035 !context->internal->_initialized) {
2037 errno = EINVAL; /* Best I can think of ... */
2049 DEBUG(4, ("smbc_stat(%s)\n", fname));
2051 if (smbc_parse_path(context, fname,
2052 server, sizeof(server),
2053 share, sizeof(share),
2056 password, sizeof(password),
2062 if (user[0] == (char)0) fstrcpy(user, context->user);
2064 fstrcpy(workgroup, context->workgroup);
2066 srv = smbc_server(context, True,
2067 server, share, workgroup, user, password);
2070 return -1; /* errno set by smbc_server */
2073 if (!smbc_getatr(context, srv, path, &mode, &size,
2074 &c_time, &a_time, &m_time, &ino)) {
2076 errno = smbc_errno(context, &srv->cli);
2083 smbc_setup_stat(context, st, path, size, mode);
2085 st->st_atime = a_time;
2086 st->st_ctime = c_time;
2087 st->st_mtime = m_time;
2088 st->st_dev = srv->dev;
2095 * Routine to stat a file given an fd
2099 smbc_fstat_ctx(SMBCCTX *context,
2114 struct cli_state *targetcli;
2117 if (!context || !context->internal ||
2118 !context->internal->_initialized) {
2125 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2134 return context->fstatdir(context, file, st);
2138 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2139 if (smbc_parse_path(context, file->fname,
2140 server, sizeof(server),
2141 share, sizeof(share),
2144 password, sizeof(password),
2150 /*d_printf(">>>fstat: resolving %s\n", path);*/
2151 if (!cli_resolve_path("", &file->srv->cli, path,
2152 &targetcli, targetpath))
2154 d_printf("Could not resolve %s\n", path);
2157 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2159 if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2160 &c_time, &a_time, &m_time, NULL, &ino)) {
2161 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2162 &c_time, &a_time, &m_time)) {
2171 smbc_setup_stat(context, st, file->fname, size, mode);
2173 st->st_atime = a_time;
2174 st->st_ctime = c_time;
2175 st->st_mtime = m_time;
2176 st->st_dev = file->srv->dev;
2183 * Routine to open a directory
2184 * We accept the URL syntax explained in smbc_parse_path(), above.
2188 smbc_remove_dir(SMBCFILE *dir)
2190 struct smbc_dir_list *d,*f;
2197 SAFE_FREE(f->dirent);
2202 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2207 add_dirent(SMBCFILE *dir,
2209 const char *comment,
2212 struct smbc_dirent *dirent;
2214 int name_length = (name == NULL ? 0 : strlen(name));
2215 int comment_len = (comment == NULL ? 0 : strlen(comment));
2218 * Allocate space for the dirent, which must be increased by the
2219 * size of the name and the comment and 1 each for the null terminator.
2222 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2224 dirent = SMB_MALLOC(size);
2228 dir->dir_error = ENOMEM;
2233 ZERO_STRUCTP(dirent);
2235 if (dir->dir_list == NULL) {
2237 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2238 if (!dir->dir_list) {
2241 dir->dir_error = ENOMEM;
2245 ZERO_STRUCTP(dir->dir_list);
2247 dir->dir_end = dir->dir_next = dir->dir_list;
2251 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2253 if (!dir->dir_end->next) {
2256 dir->dir_error = ENOMEM;
2260 ZERO_STRUCTP(dir->dir_end->next);
2262 dir->dir_end = dir->dir_end->next;
2265 dir->dir_end->next = NULL;
2266 dir->dir_end->dirent = dirent;
2268 dirent->smbc_type = type;
2269 dirent->namelen = name_length;
2270 dirent->commentlen = comment_len;
2271 dirent->dirlen = size;
2273 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2275 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2276 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2283 list_unique_wg_fn(const char *name,
2285 const char *comment,
2288 SMBCFILE *dir = (SMBCFILE *)state;
2289 struct smbc_dir_list *dir_list;
2290 struct smbc_dirent *dirent;
2294 dirent_type = dir->dir_type;
2296 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2298 /* An error occurred, what do we do? */
2299 /* FIXME: Add some code here */
2302 /* Point to the one just added */
2303 dirent = dir->dir_end->dirent;
2305 /* See if this was a duplicate */
2306 for (dir_list = dir->dir_list;
2307 dir_list != dir->dir_end;
2308 dir_list = dir_list->next) {
2310 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2311 /* Duplicate. End end of list need to be removed. */
2315 if (do_remove && dir_list->next == dir->dir_end) {
2316 /* Found the end of the list. Remove it. */
2317 dir->dir_end = dir_list;
2318 free(dir_list->next);
2320 dir_list->next = NULL;
2327 list_fn(const char *name,
2329 const char *comment,
2332 SMBCFILE *dir = (SMBCFILE *)state;
2336 * We need to process the type a little ...
2338 * Disk share = 0x00000000
2339 * Print share = 0x00000001
2340 * Comms share = 0x00000002 (obsolete?)
2341 * IPC$ share = 0x00000003
2343 * administrative shares:
2344 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2347 if (dir->dir_type == SMBC_FILE_SHARE) {
2350 case 0 | 0x80000000:
2352 dirent_type = SMBC_FILE_SHARE;
2356 dirent_type = SMBC_PRINTER_SHARE;
2360 dirent_type = SMBC_COMMS_SHARE;
2363 case 3 | 0x80000000:
2365 dirent_type = SMBC_IPC_SHARE;
2369 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2374 dirent_type = dir->dir_type;
2377 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2379 /* An error occurred, what do we do? */
2380 /* FIXME: Add some code here */
2386 dir_list_fn(const char *mnt,
2392 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2393 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2395 /* Handle an error ... */
2397 /* FIXME: Add some code ... */
2404 net_share_enum_rpc(struct cli_state *cli,
2405 void (*fn)(const char *name,
2407 const char *comment,
2414 uint32 info_level = 1;
2415 uint32 preferred_len = 0xffffffff;
2417 SRV_SHARE_INFO_CTR ctr;
2419 fstring comment = "";
2421 struct rpc_pipe_client *pipe_hnd;
2424 /* Open the server service pipe */
2425 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2427 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2431 /* Allocate a context for parsing and for the entries in "ctr" */
2432 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2433 if (mem_ctx == NULL) {
2434 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2435 cli_rpc_pipe_close(pipe_hnd);
2439 /* Issue the NetShareEnum RPC call and retrieve the response */
2440 init_enum_hnd(&enum_hnd, 0);
2441 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2448 /* Was it successful? */
2449 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2450 /* Nope. Go clean up. */
2454 /* For each returned entry... */
2455 for (i = 0; i < ctr.num_entries; i++) {
2457 /* pull out the share name */
2458 rpcstr_pull_unistr2_fstring(
2459 name, &ctr.share.info1[i].info_1_str.uni_netname);
2461 /* pull out the share's comment */
2462 rpcstr_pull_unistr2_fstring(
2463 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2465 /* Get the type value */
2466 type = ctr.share.info1[i].info_1.type;
2468 /* Add this share to the list */
2469 (*fn)(name, type, comment, state);
2473 /* Close the server service pipe */
2474 cli_rpc_pipe_close(pipe_hnd);
2476 /* Free all memory which was allocated for this request */
2477 talloc_free(mem_ctx);
2479 /* Tell 'em if it worked */
2480 return W_ERROR_IS_OK(result) ? 0 : -1;
2486 smbc_opendir_ctx(SMBCCTX *context,
2489 fstring server, share, user, password, options;
2494 SMBCSRV *srv = NULL;
2495 SMBCFILE *dir = NULL;
2496 struct in_addr rem_ip;
2498 if (!context || !context->internal ||
2499 !context->internal->_initialized) {
2500 DEBUG(4, ("no valid context\n"));
2501 errno = EINVAL + 8192;
2507 DEBUG(4, ("no valid fname\n"));
2508 errno = EINVAL + 8193;
2512 if (smbc_parse_path(context, fname,
2513 server, sizeof(server),
2514 share, sizeof(share),
2517 password, sizeof(password),
2518 options, sizeof(options))) {
2519 DEBUG(4, ("no valid path\n"));
2520 errno = EINVAL + 8194;
2524 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2525 "path='%s' options='%s'\n",
2526 fname, server, share, path, options));
2528 /* Ensure the options are valid */
2529 if (smbc_check_options(server, share, path, options)) {
2530 DEBUG(4, ("unacceptable options (%s)\n", options));
2531 errno = EINVAL + 8195;
2535 if (user[0] == (char)0) fstrcpy(user, context->user);
2537 pstrcpy(workgroup, context->workgroup);
2539 dir = SMB_MALLOC_P(SMBCFILE);
2551 dir->fname = SMB_STRDUP(fname);
2555 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2557 if (server[0] == (char)0) {
2562 struct ip_service *ip_list;
2563 struct ip_service server_addr;
2564 struct user_auth_info u_info;
2565 struct cli_state *cli;
2567 if (share[0] != (char)0 || path[0] != (char)0) {
2569 errno = EINVAL + 8196;
2571 SAFE_FREE(dir->fname);
2577 /* Determine how many local master browsers to query */
2578 max_lmb_count = (context->options.browse_max_lmb_count == 0
2580 : context->options.browse_max_lmb_count);
2582 pstrcpy(u_info.username, user);
2583 pstrcpy(u_info.password, password);
2586 * We have server and share and path empty but options
2587 * requesting that we scan all master browsers for their list
2588 * of workgroups/domains. This implies that we must first try
2589 * broadcast queries to find all master browsers, and if that
2590 * doesn't work, then try our other methods which return only
2591 * a single master browser.
2595 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2599 if (!find_master_ip(workgroup, &server_addr.ip)) {
2605 ip_list = &server_addr;
2609 for (i = 0; i < count && i < max_lmb_count; i++) {
2610 DEBUG(99, ("Found master browser %d of %d: %s\n",
2611 i+1, MAX(count, max_lmb_count),
2612 inet_ntoa(ip_list[i].ip)));
2614 cli = get_ipc_connect_master_ip(&ip_list[i],
2615 workgroup, &u_info);
2616 /* cli == NULL is the master browser refused to talk or
2617 could not be found */
2621 fstrcpy(server, cli->desthost);
2624 DEBUG(4, ("using workgroup %s %s\n",
2625 workgroup, server));
2628 * For each returned master browser IP address, get a
2629 * connection to IPC$ on the server if we do not
2630 * already have one, and determine the
2631 * workgroups/domains that it knows about.
2634 srv = smbc_server(context, True, server, "IPC$",
2635 workgroup, user, password);
2641 dir->dir_type = SMBC_WORKGROUP;
2643 /* Now, list the stuff ... */
2645 if (!cli_NetServerEnum(&srv->cli,
2647 SV_TYPE_DOMAIN_ENUM,
2657 * Server not an empty string ... Check the rest and see what
2660 if (*share == '\0') {
2661 if (*path != '\0') {
2663 /* Should not have empty share with path */
2664 errno = EINVAL + 8197;
2666 SAFE_FREE(dir->fname);
2674 * We don't know if <server> is really a server name
2675 * or is a workgroup/domain name. If we already have
2676 * a server structure for it, we'll use it.
2677 * Otherwise, check to see if <server><1D>,
2678 * <server><1B>, or <server><20> translates. We check
2679 * to see if <server> is an IP address first.
2683 * See if we have an existing server. Do not
2684 * establish a connection if one does not already
2687 srv = smbc_server(context, False, server, "IPC$",
2688 workgroup, user, password);
2691 * If no existing server and not an IP addr, look for
2695 !is_ipaddress(server) &&
2696 (resolve_name(server, &rem_ip, 0x1d) || /* LMB */
2697 resolve_name(server, &rem_ip, 0x1b) )) { /* DMB */
2701 dir->dir_type = SMBC_SERVER;
2704 * Get the backup list ...
2706 if (!name_status_find(server, 0, 0,
2707 rem_ip, buserver)) {
2709 DEBUG(0, ("Could not get name of "
2710 "local/domain master browser "
2711 "for server %s\n", server));
2718 * Get a connection to IPC$ on the server if
2719 * we do not already have one
2721 srv = smbc_server(context, True,
2723 workgroup, user, password);
2725 DEBUG(0, ("got no contact to IPC$\n"));
2727 SAFE_FREE(dir->fname);
2736 /* Now, list the servers ... */
2737 if (!cli_NetServerEnum(&srv->cli, server,
2738 0x0000FFFE, list_fn,
2742 SAFE_FREE(dir->fname);
2748 (resolve_name(server, &rem_ip, 0x20))) {
2750 /* If we hadn't found the server, get one now */
2752 srv = smbc_server(context, True,
2760 SAFE_FREE(dir->fname);
2767 dir->dir_type = SMBC_FILE_SHARE;
2770 /* List the shares ... */
2772 if (net_share_enum_rpc(
2775 (void *) dir) < 0 &&
2781 errno = cli_errno(&srv->cli);
2783 SAFE_FREE(dir->fname);
2790 /* Neither the workgroup nor server exists */
2791 errno = ECONNREFUSED;
2793 SAFE_FREE(dir->fname);
2802 * The server and share are specified ... work from
2806 struct cli_state *targetcli;
2808 /* We connect to the server and list the directory */
2809 dir->dir_type = SMBC_FILE_SHARE;
2811 srv = smbc_server(context, True, server, share,
2812 workgroup, user, password);
2817 SAFE_FREE(dir->fname);
2826 /* Now, list the files ... */
2828 p = path + strlen(path);
2829 pstrcat(path, "\\*");
2831 if (!cli_resolve_path("", &srv->cli, path,
2832 &targetcli, targetpath))
2834 d_printf("Could not resolve %s\n", path);
2838 if (cli_list(targetcli, targetpath,
2839 aDIR | aSYSTEM | aHIDDEN,
2840 dir_list_fn, (void *)dir) < 0) {
2843 SAFE_FREE(dir->fname);
2846 errno = smbc_errno(context, targetcli);
2848 if (errno == EINVAL) {
2850 * See if they asked to opendir something
2851 * other than a directory. If so, the
2852 * converted error value we got would have
2853 * been EINVAL rather than ENOTDIR.
2855 *p = '\0'; /* restore original path */
2857 if (smbc_getatr(context, srv, path,
2861 ! IS_DOS_DIR(mode)) {
2863 /* It is. Correct the error value */
2875 DLIST_ADD(context->internal->_files, dir);
2881 * Routine to close a directory
2885 smbc_closedir_ctx(SMBCCTX *context,
2889 if (!context || !context->internal ||
2890 !context->internal->_initialized) {
2897 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2904 smbc_remove_dir(dir); /* Clean it up */
2906 DLIST_REMOVE(context->internal->_files, dir);
2910 SAFE_FREE(dir->fname);
2911 SAFE_FREE(dir); /* Free the space too */
2919 smbc_readdir_internal(SMBCCTX * context,
2920 struct smbc_dirent *dest,
2921 struct smbc_dirent *src,
2922 int max_namebuf_len)
2924 if (context->options.urlencode_readdir_entries) {
2926 /* url-encode the name. get back remaining buffer space */
2928 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2930 /* We now know the name length */
2931 dest->namelen = strlen(dest->name);
2933 /* Save the pointer to the beginning of the comment */
2934 dest->comment = dest->name + dest->namelen + 1;
2936 /* Copy the comment */
2937 strncpy(dest->comment, src->comment, max_namebuf_len);
2939 /* Ensure the comment is null terminated */
2940 if (max_namebuf_len > src->commentlen) {
2941 dest->comment[src->commentlen] = '\0';
2943 dest->comment[max_namebuf_len - 1] = '\0';
2946 /* Save other fields */
2947 dest->smbc_type = src->smbc_type;
2948 dest->commentlen = strlen(dest->comment);
2949 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2953 /* No encoding. Just copy the entry as is. */
2954 memcpy(dest, src, src->dirlen);
2955 dest->comment = (char *)(&dest->name + src->namelen + 1);
2961 * Routine to get a directory entry
2964 struct smbc_dirent *
2965 smbc_readdir_ctx(SMBCCTX *context,
2969 struct smbc_dirent *dirp, *dirent;
2971 /* Check that all is ok first ... */
2973 if (!context || !context->internal ||
2974 !context->internal->_initialized) {
2977 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2982 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2985 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2990 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2993 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2998 if (!dir->dir_next) {
3002 dirent = dir->dir_next->dirent;
3010 dirp = (struct smbc_dirent *)context->internal->_dirent;
3011 maxlen = (sizeof(context->internal->_dirent) -
3012 sizeof(struct smbc_dirent));
3014 smbc_readdir_internal(context, dirp, dirent, maxlen);
3016 dir->dir_next = dir->dir_next->next;
3022 * Routine to get directory entries
3026 smbc_getdents_ctx(SMBCCTX *context,
3028 struct smbc_dirent *dirp,
3034 char *ndir = (char *)dirp;
3035 struct smbc_dir_list *dirlist;
3037 /* Check that all is ok first ... */
3039 if (!context || !context->internal ||
3040 !context->internal->_initialized) {
3047 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3054 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3062 * Now, retrieve the number of entries that will fit in what was passed
3063 * We have to figure out if the info is in the list, or we need to
3064 * send a request to the server to get the info.
3067 while ((dirlist = dir->dir_next)) {
3068 struct smbc_dirent *dirent;
3070 if (!dirlist->dirent) {
3072 errno = ENOENT; /* Bad error */
3077 /* Do urlencoding of next entry, if so selected */
3078 dirent = (struct smbc_dirent *)context->internal->_dirent;
3079 maxlen = (sizeof(context->internal->_dirent) -
3080 sizeof(struct smbc_dirent));
3081 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3083 reqd = dirent->dirlen;
3087 if (rem < count) { /* We managed to copy something */
3093 else { /* Nothing copied ... */
3095 errno = EINVAL; /* Not enough space ... */
3102 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3104 ((struct smbc_dirent *)ndir)->comment =
3105 (char *)(&((struct smbc_dirent *)ndir)->name +
3113 dir->dir_next = dirlist = dirlist -> next;
3124 * Routine to create a directory ...
3128 smbc_mkdir_ctx(SMBCCTX *context,
3138 pstring path, targetpath;
3139 struct cli_state *targetcli;
3141 if (!context || !context->internal ||
3142 !context->internal->_initialized) {
3156 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3158 if (smbc_parse_path(context, fname,
3159 server, sizeof(server),
3160 share, sizeof(share),
3163 password, sizeof(password),
3169 if (user[0] == (char)0) fstrcpy(user, context->user);
3171 fstrcpy(workgroup, context->workgroup);
3173 srv = smbc_server(context, True,
3174 server, share, workgroup, user, password);
3178 return -1; /* errno set by smbc_server */
3182 /*d_printf(">>>mkdir: resolving %s\n", path);*/
3183 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3185 d_printf("Could not resolve %s\n", path);
3188 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3190 if (!cli_mkdir(targetcli, targetpath)) {
3192 errno = smbc_errno(context, targetcli);
3202 * Our list function simply checks to see if a directory is not empty
3205 static int smbc_rmdir_dirempty = True;
3208 rmdir_list_fn(const char *mnt,
3213 if (strncmp(finfo->name, ".", 1) != 0 &&
3214 strncmp(finfo->name, "..", 2) != 0) {
3216 smbc_rmdir_dirempty = False;
3221 * Routine to remove a directory
3225 smbc_rmdir_ctx(SMBCCTX *context,
3236 struct cli_state *targetcli;
3238 if (!context || !context->internal ||
3239 !context->internal->_initialized) {
3253 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3255 if (smbc_parse_path(context, fname,
3256 server, sizeof(server),
3257 share, sizeof(share),
3260 password, sizeof(password),
3267 if (user[0] == (char)0) fstrcpy(user, context->user);
3269 fstrcpy(workgroup, context->workgroup);
3271 srv = smbc_server(context, True,
3272 server, share, workgroup, user, password);
3276 return -1; /* errno set by smbc_server */
3280 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3281 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3283 d_printf("Could not resolve %s\n", path);
3286 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3289 if (!cli_rmdir(targetcli, targetpath)) {
3291 errno = smbc_errno(context, targetcli);
3293 if (errno == EACCES) { /* Check if the dir empty or not */
3295 /* Local storage to avoid buffer overflows */
3298 smbc_rmdir_dirempty = True; /* Make this so ... */
3300 pstrcpy(lpath, targetpath);
3301 pstrcat(lpath, "\\*");
3303 if (cli_list(targetcli, lpath,
3304 aDIR | aSYSTEM | aHIDDEN,
3305 rmdir_list_fn, NULL) < 0) {
3307 /* Fix errno to ignore latest error ... */
3308 DEBUG(5, ("smbc_rmdir: "
3309 "cli_list returned an error: %d\n",
3310 smbc_errno(context, targetcli)));
3315 if (smbc_rmdir_dirempty)
3331 * Routine to return the current directory position
3335 smbc_telldir_ctx(SMBCCTX *context,
3338 off_t ret_val; /* Squash warnings about cast */
3340 if (!context || !context->internal ||
3341 !context->internal->_initialized) {
3348 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3355 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3363 * We return the pointer here as the offset
3365 ret_val = (off_t)(long)dir->dir_next;
3371 * A routine to run down the list and see if the entry is OK
3374 struct smbc_dir_list *
3375 smbc_check_dir_ent(struct smbc_dir_list *list,
3376 struct smbc_dirent *dirent)
3379 /* Run down the list looking for what we want */
3383 struct smbc_dir_list *tmp = list;
3387 if (tmp->dirent == dirent)
3396 return NULL; /* Not found, or an error */
3402 * Routine to seek on a directory
3406 smbc_lseekdir_ctx(SMBCCTX *context,
3410 long int l_offset = offset; /* Handle problems of size */
3411 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3412 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3414 if (!context || !context->internal ||
3415 !context->internal->_initialized) {
3422 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3429 /* Now, check what we were passed and see if it is OK ... */
3431 if (dirent == NULL) { /* Seek to the begining of the list */
3433 dir->dir_next = dir->dir_list;
3438 /* Now, run down the list and make sure that the entry is OK */
3439 /* This may need to be changed if we change the format of the list */
3441 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3443 errno = EINVAL; /* Bad entry */
3448 dir->dir_next = list_ent;
3455 * Routine to fstat a dir
3459 smbc_fstatdir_ctx(SMBCCTX *context,
3464 if (!context || !context->internal ||
3465 !context->internal->_initialized) {
3472 /* No code yet ... */
3479 smbc_chmod_ctx(SMBCCTX *context,
3492 if (!context || !context->internal ||
3493 !context->internal->_initialized) {
3495 errno = EINVAL; /* Best I can think of ... */
3507 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3509 if (smbc_parse_path(context, fname,
3510 server, sizeof(server),
3511 share, sizeof(share),
3514 password, sizeof(password),
3520 if (user[0] == (char)0) fstrcpy(user, context->user);
3522 fstrcpy(workgroup, context->workgroup);
3524 srv = smbc_server(context, True,
3525 server, share, workgroup, user, password);
3528 return -1; /* errno set by smbc_server */
3533 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3534 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3535 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3536 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3538 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3539 errno = smbc_errno(context, &srv->cli);
3547 smbc_utimes_ctx(SMBCCTX *context,
3549 struct timeval *tbuf)
3561 if (!context || !context->internal ||
3562 !context->internal->_initialized) {
3564 errno = EINVAL; /* Best I can think of ... */
3577 a_time = m_time = time(NULL);
3579 a_time = tbuf[0].tv_sec;
3580 m_time = tbuf[1].tv_sec;
3589 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf));
3590 atimebuf[sizeof(atimebuf) - 1] = '\0';
3591 if ((p = strchr(atimebuf, '\n')) != NULL) {
3595 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf));
3596 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3597 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3601 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3602 fname, atimebuf, mtimebuf);
3605 if (smbc_parse_path(context, fname,
3606 server, sizeof(server),
3607 share, sizeof(share),
3610 password, sizeof(password),
3616 if (user[0] == (char)0) fstrcpy(user, context->user);
3618 fstrcpy(workgroup, context->workgroup);
3620 srv = smbc_server(context, True,
3621 server, share, workgroup, user, password);
3624 return -1; /* errno set by smbc_server */
3627 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3628 return -1; /* errno set by smbc_setatr */
3635 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3636 However NT4 gives a "The information may have been modified by a
3637 computer running Windows NT 5.0" if denied ACEs do not appear before
3641 ace_compare(SEC_ACE *ace1,
3644 if (sec_ace_equal(ace1, ace2))
3647 if (ace1->type != ace2->type)
3648 return ace2->type - ace1->type;
3650 if (sid_compare(&ace1->trustee, &ace2->trustee))
3651 return sid_compare(&ace1->trustee, &ace2->trustee);
3653 if (ace1->flags != ace2->flags)
3654 return ace1->flags - ace2->flags;
3656 if (ace1->info.mask != ace2->info.mask)
3657 return ace1->info.mask - ace2->info.mask;
3659 if (ace1->size != ace2->size)
3660 return ace1->size - ace2->size;
3662 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3667 sort_acl(SEC_ACL *the_acl)
3670 if (!the_acl) return;
3672 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]),
3673 QSORT_CAST ace_compare);
3675 for (i=1;i<the_acl->num_aces;) {
3676 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3678 for (j=i; j<the_acl->num_aces-1; j++) {
3679 the_acl->ace[j] = the_acl->ace[j+1];
3681 the_acl->num_aces--;
3688 /* convert a SID to a string, either numeric or username/group */
3690 convert_sid_to_string(struct cli_state *ipc_cli,
3696 char **domains = NULL;
3697 char **names = NULL;
3698 uint32 *types = NULL;
3699 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3700 sid_to_string(str, sid);
3703 return; /* no lookup desired */
3710 /* Ask LSA to convert the sid to a name */
3712 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3713 pol, 1, sid, &domains,
3715 !domains || !domains[0] || !names || !names[0]) {
3721 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3722 domains[0], lp_winbind_separator(),
3726 /* convert a string to a SID, either numeric or username/group */
3728 convert_string_to_sid(struct cli_state *ipc_cli,
3734 uint32 *types = NULL;
3735 DOM_SID *sids = NULL;
3737 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3744 if (strncmp(str, "S-", 2) == 0) {
3745 return string_to_sid(sid, str);
3752 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3753 pol, 1, &str, &sids,
3759 sid_copy(sid, &sids[0]);
3766 /* parse an ACE in the same format as print_ace() */
3768 parse_ace(struct cli_state *ipc_cli,
3778 unsigned int aflags;
3782 const struct perm_value *v;
3788 /* These values discovered by inspection */
3789 static const struct perm_value special_values[] = {
3790 { "R", 0x00120089 },
3791 { "W", 0x00120116 },
3792 { "X", 0x001200a0 },
3793 { "D", 0x00010000 },
3794 { "P", 0x00040000 },
3795 { "O", 0x00080000 },
3799 static const struct perm_value standard_values[] = {
3800 { "READ", 0x001200a9 },
3801 { "CHANGE", 0x001301bf },
3802 { "FULL", 0x001f01ff },
3808 p = strchr_m(str,':');
3809 if (!p) return False;
3812 /* Try to parse numeric form */
3814 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3815 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3819 /* Try to parse text form */
3821 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3826 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3830 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3831 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3832 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3833 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3838 /* Only numeric form accepted for flags at present */
3840 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3841 sscanf(tok, "%i", &aflags))) {
3845 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3849 if (strncmp(tok, "0x", 2) == 0) {
3850 if (sscanf(tok, "%i", &amask) != 1) {
3856 for (v = standard_values; v->perm; v++) {
3857 if (strcmp(tok, v->perm) == 0) {
3868 for (v = special_values; v->perm; v++) {
3869 if (v->perm[0] == *p) {
3875 if (!found) return False;
3885 init_sec_ace(ace, &sid, atype, mask, aflags);
3889 /* add an ACE to a list of ACEs in a SEC_ACL */
3891 add_ace(SEC_ACL **the_acl,
3899 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3903 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3904 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3905 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3906 newacl = make_sec_acl(ctx, (*the_acl)->revision,
3907 1+(*the_acl)->num_aces, aces);
3909 (*the_acl) = newacl;
3914 /* parse a ascii version of a security descriptor */
3916 sec_desc_parse(TALLOC_CTX *ctx,
3917 struct cli_state *ipc_cli,
3922 const char *p = str;
3926 DOM_SID *grp_sid=NULL;
3927 DOM_SID *owner_sid=NULL;
3931 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3933 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3934 revision = strtol(tok+9, NULL, 16);
3938 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3939 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3941 !convert_string_to_sid(ipc_cli, pol,
3943 owner_sid, tok+6)) {
3944 DEBUG(5, ("Failed to parse owner sid\n"));
3950 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3951 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3953 !convert_string_to_sid(ipc_cli, pol,
3955 owner_sid, tok+7)) {
3956 DEBUG(5, ("Failed to parse owner sid\n"));
3962 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3963 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3965 !convert_string_to_sid(ipc_cli, pol,
3968 DEBUG(5, ("Failed to parse group sid\n"));
3974 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3975 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3977 !convert_string_to_sid(ipc_cli, pol,
3980 DEBUG(5, ("Failed to parse group sid\n"));
3986 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3988 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3989 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3992 if(!add_ace(&dacl, &ace, ctx)) {
3993 DEBUG(5, ("Failed to add ACL %s\n", tok));
3999 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
4001 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
4002 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4005 if(!add_ace(&dacl, &ace, ctx)) {
4006 DEBUG(5, ("Failed to add ACL %s\n", tok));
4012 DEBUG(5, ("Failed to parse security descriptor\n"));
4016 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
4017 owner_sid, grp_sid, NULL, dacl, &sd_size);
4020 SAFE_FREE(owner_sid);
4026 /* Obtain the current dos attributes */
4027 static DOS_ATTR_DESC *
4028 dos_attr_query(SMBCCTX *context,
4030 const char *filename,
4033 time_t m_time = 0, a_time = 0, c_time = 0;
4036 SMB_INO_T inode = 0;
4039 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
4045 /* Obtain the DOS attributes */
4046 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
4048 &c_time, &a_time, &m_time, &inode)) {
4050 errno = smbc_errno(context, &srv->cli);
4051 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
4058 ret->a_time = a_time;
4059 ret->c_time = c_time;
4060 ret->m_time = m_time;
4067 /* parse a ascii version of a security descriptor */
4069 dos_attr_parse(SMBCCTX *context,
4074 const char *p = str;
4077 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4079 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
4080 dad->mode = strtol(tok+5, NULL, 16);
4084 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4085 dad->size = (SMB_OFF_T)atof(tok+5);
4089 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
4090 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
4094 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
4095 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
4099 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
4100 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
4104 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4105 dad->inode = (SMB_INO_T)atof(tok+6);
4111 /*****************************************************
4112 Retrieve the acls for a file.
4113 *******************************************************/
4116 cacl_get(SMBCCTX *context,
4119 struct cli_state *ipc_cli,
4135 BOOL exclude_nt_revision = False;
4136 BOOL exclude_nt_owner = False;
4137 BOOL exclude_nt_group = False;
4138 BOOL exclude_nt_acl = False;
4139 BOOL exclude_dos_mode = False;
4140 BOOL exclude_dos_size = False;
4141 BOOL exclude_dos_ctime = False;
4142 BOOL exclude_dos_atime = False;
4143 BOOL exclude_dos_mtime = False;
4144 BOOL exclude_dos_inode = False;
4145 BOOL numeric = True;
4146 BOOL determine_size = (bufsize == 0);
4150 fstring name_sandbox;
4154 time_t m_time = 0, a_time = 0, c_time = 0;
4158 struct cli_state *cli = &srv->cli;
4160 /* Copy name so we can strip off exclusions (if any are specified) */
4161 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4163 /* Ensure name is null terminated */
4164 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4166 /* Play in the sandbox */
4167 name = name_sandbox;
4169 /* If there are any exclusions, point to them and mask them from name */
4170 if ((pExclude = strchr(name, '!')) != NULL)
4175 all = (StrnCaseCmp(name, "system.*", 8) == 0);
4176 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4177 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4178 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4179 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4180 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4181 numeric = (* (name + strlen(name) - 1) != '+');
4183 /* Look for exclusions from "all" requests */
4184 if (all || all_nt || all_dos) {
4186 /* Exclusions are delimited by '!' */
4189 pExclude = (p == NULL ? NULL : p + 1)) {
4191 /* Find end of this exclusion name */
4192 if ((p = strchr(pExclude, '!')) != NULL)
4197 /* Which exclusion name is this? */
4198 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4199 exclude_nt_revision = True;
4201 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4202 exclude_nt_owner = True;
4204 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4205 exclude_nt_group = True;
4207 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4208 exclude_nt_acl = True;
4210 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4211 exclude_dos_mode = True;
4213 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4214 exclude_dos_size = True;
4216 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
4217 exclude_dos_ctime = True;
4219 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
4220 exclude_dos_atime = True;
4222 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
4223 exclude_dos_mtime = True;
4225 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4226 exclude_dos_inode = True;
4229 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4240 * If we are (possibly) talking to an NT or new system and some NT
4241 * attributes have been requested...
4243 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4244 /* Point to the portion after "system.nt_sec_desc." */
4245 name += 19; /* if (all) this will be invalid but unused */
4247 /* ... then obtain any NT attributes which were requested */
4248 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4251 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4252 filename, cli_errstr(cli)));
4257 sd = cli_query_secdesc(cli, fnum, ctx);
4261 ("cacl_get Failed to query old descriptor\n"));
4266 cli_close(cli, fnum);
4268 if (! exclude_nt_revision) {
4269 if (all || all_nt) {
4270 if (determine_size) {
4271 p = talloc_asprintf(ctx,
4280 n = snprintf(buf, bufsize,
4284 } else if (StrCaseCmp(name, "revision") == 0) {
4285 if (determine_size) {
4286 p = talloc_asprintf(ctx, "%d",
4294 n = snprintf(buf, bufsize, "%d",
4299 if (!determine_size && n > bufsize) {
4308 if (! exclude_nt_owner) {
4309 /* Get owner and group sid */
4310 if (sd->owner_sid) {
4311 convert_sid_to_string(ipc_cli, pol,
4316 fstrcpy(sidstr, "");
4319 if (all || all_nt) {
4320 if (determine_size) {
4321 p = talloc_asprintf(ctx, ",OWNER:%s",
4329 n = snprintf(buf, bufsize,
4330 ",OWNER:%s", sidstr);
4332 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4333 if (determine_size) {
4334 p = talloc_asprintf(ctx, "%s", sidstr);
4341 n = snprintf(buf, bufsize, "%s",
4346 if (!determine_size && n > bufsize) {
4355 if (! exclude_nt_group) {
4357 convert_sid_to_string(ipc_cli, pol,
4361 fstrcpy(sidstr, "");
4364 if (all || all_nt) {
4365 if (determine_size) {
4366 p = talloc_asprintf(ctx, ",GROUP:%s",
4374 n = snprintf(buf, bufsize,
4375 ",GROUP:%s", sidstr);
4377 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4378 if (determine_size) {
4379 p = talloc_asprintf(ctx, "%s", sidstr);
4386 n = snprintf(buf, bufsize,
4391 if (!determine_size && n > bufsize) {
4400 if (! exclude_nt_acl) {
4401 /* Add aces to value buffer */
4402 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4404 SEC_ACE *ace = &sd->dacl->ace[i];
4405 convert_sid_to_string(ipc_cli, pol,
4409 if (all || all_nt) {
4410 if (determine_size) {
4411 p = talloc_asprintf(
4427 ",ACL:%s:%d/%d/0x%08x",
4433 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4434 StrCaseCmp(name+3, sidstr) == 0) ||
4435 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4436 StrCaseCmp(name+4, sidstr) == 0)) {
4437 if (determine_size) {
4438 p = talloc_asprintf(
4450 n = snprintf(buf, bufsize,
4456 } else if (all_nt_acls) {
4457 if (determine_size) {
4458 p = talloc_asprintf(
4460 "%s%s:%d/%d/0x%08x",
4472 n = snprintf(buf, bufsize,
4473 "%s%s:%d/%d/0x%08x",
4491 /* Restore name pointer to its original value */
4495 if (all || some_dos) {
4496 /* Point to the portion after "system.dos_attr." */
4497 name += 16; /* if (all) this will be invalid but unused */
4499 /* Obtain the DOS attributes */
4500 if (!smbc_getatr(context, srv, filename, &mode, &size,
4501 &c_time, &a_time, &m_time, &ino)) {
4503 errno = smbc_errno(context, &srv->cli);
4508 if (! exclude_dos_mode) {
4509 if (all || all_dos) {
4510 if (determine_size) {
4511 p = talloc_asprintf(ctx,
4524 n = snprintf(buf, bufsize,
4532 } else if (StrCaseCmp(name, "mode") == 0) {
4533 if (determine_size) {
4534 p = talloc_asprintf(ctx, "0x%x", mode);
4541 n = snprintf(buf, bufsize,
4546 if (!determine_size && n > bufsize) {
4555 if (! exclude_dos_size) {
4556 if (all || all_dos) {
4557 if (determine_size) {
4558 p = talloc_asprintf(
4568 n = snprintf(buf, bufsize,
4572 } else if (StrCaseCmp(name, "size") == 0) {
4573 if (determine_size) {
4574 p = talloc_asprintf(
4584 n = snprintf(buf, bufsize,
4590 if (!determine_size && n > bufsize) {
4599 if (! exclude_dos_ctime) {
4600 if (all || all_dos) {
4601 if (determine_size) {
4602 p = talloc_asprintf(ctx,
4611 n = snprintf(buf, bufsize,
4612 ",C_TIME:%lu", c_time);
4614 } else if (StrCaseCmp(name, "c_time") == 0) {
4615 if (determine_size) {
4616 p = talloc_asprintf(ctx, "%lu", c_time);
4623 n = snprintf(buf, bufsize,
4628 if (!determine_size && n > bufsize) {
4637 if (! exclude_dos_atime) {
4638 if (all || all_dos) {
4639 if (determine_size) {
4640 p = talloc_asprintf(ctx,
4649 n = snprintf(buf, bufsize,
4650 ",A_TIME:%lu", a_time);
4652 } else if (StrCaseCmp(name, "a_time") == 0) {
4653 if (determine_size) {
4654 p = talloc_asprintf(ctx, "%lu", a_time);
4661 n = snprintf(buf, bufsize,
4666 if (!determine_size && n > bufsize) {
4675 if (! exclude_dos_mtime) {
4676 if (all || all_dos) {
4677 if (determine_size) {
4678 p = talloc_asprintf(ctx,
4687 n = snprintf(buf, bufsize,
4688 ",M_TIME:%lu", m_time);
4690 } else if (StrCaseCmp(name, "m_time") == 0) {
4691 if (determine_size) {
4692 p = talloc_asprintf(ctx, "%lu", m_time);
4699 n = snprintf(buf, bufsize,
4704 if (!determine_size && n > bufsize) {
4713 if (! exclude_dos_inode) {
4714 if (all || all_dos) {
4715 if (determine_size) {
4716 p = talloc_asprintf(
4726 n = snprintf(buf, bufsize,
4730 } else if (StrCaseCmp(name, "inode") == 0) {
4731 if (determine_size) {
4732 p = talloc_asprintf(
4742 n = snprintf(buf, bufsize,
4748 if (!determine_size && n > bufsize) {
4757 /* Restore name pointer to its original value */
4770 /*****************************************************
4771 set the ACLs on a file given an ascii description
4772 *******************************************************/
4774 cacl_set(TALLOC_CTX *ctx,
4775 struct cli_state *cli,
4776 struct cli_state *ipc_cli,
4778 const char *filename,
4779 const char *the_acl,
4785 SEC_DESC *sd = NULL, *old;
4786 SEC_ACL *dacl = NULL;
4787 DOM_SID *owner_sid = NULL;
4788 DOM_SID *grp_sid = NULL;
4793 BOOL numeric = True;
4795 /* the_acl will be null for REMOVE_ALL operations */
4797 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4801 /* if this is to set the entire ACL... */
4802 if (*the_acl == '*') {
4803 /* ... then increment past the first colon */
4807 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4808 CONST_DISCARD(char *, the_acl));
4816 /* The desired access below is the only one I could find that works
4817 with NT4, W2KP and Samba */
4819 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4822 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4823 filename, cli_errstr(cli)));
4828 old = cli_query_secdesc(cli, fnum, ctx);
4831 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4836 cli_close(cli, fnum);
4839 case SMBC_XATTR_MODE_REMOVE_ALL:
4840 old->dacl->num_aces = 0;
4841 SAFE_FREE(old->dacl->ace);
4842 SAFE_FREE(old->dacl);
4847 case SMBC_XATTR_MODE_REMOVE:
4848 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4851 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4852 if (sec_ace_equal(&sd->dacl->ace[i],
4853 &old->dacl->ace[j])) {
4855 for (k=j; k<old->dacl->num_aces-1;k++) {
4857 old->dacl->ace[k+1];
4859 old->dacl->num_aces--;
4860 if (old->dacl->num_aces == 0) {
4861 SAFE_FREE(old->dacl->ace);
4862 SAFE_FREE(old->dacl);
4879 case SMBC_XATTR_MODE_ADD:
4880 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4883 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4884 if (sid_equal(&sd->dacl->ace[i].trustee,
4885 &old->dacl->ace[j].trustee)) {
4886 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4891 old->dacl->ace[j] = sd->dacl->ace[i];
4897 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4903 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4904 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4910 case SMBC_XATTR_MODE_SET:
4912 owner_sid = old->owner_sid;
4913 grp_sid = old->grp_sid;
4917 case SMBC_XATTR_MODE_CHOWN:
4918 owner_sid = sd->owner_sid;
4921 case SMBC_XATTR_MODE_CHGRP:
4922 grp_sid = sd->grp_sid;
4926 /* Denied ACE entries must come before allowed ones */
4927 sort_acl(old->dacl);
4929 /* Create new security descriptor and set it */
4930 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4931 owner_sid, grp_sid, NULL, dacl, &sd_size);
4933 fnum = cli_nt_create(cli, filename,
4934 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4937 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4938 filename, cli_errstr(cli)));
4943 if (!cli_set_secdesc(cli, fnum, sd)) {
4944 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4951 cli_close(cli, fnum);
4962 smbc_setxattr_ctx(SMBCCTX *context,
4983 if (!context || !context->internal ||
4984 !context->internal->_initialized) {
4986 errno = EINVAL; /* Best I can think of ... */
4998 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
4999 fname, name, (int) size, (const char*)value));
5001 if (smbc_parse_path(context, fname,
5002 server, sizeof(server),
5003 share, sizeof(share),
5006 password, sizeof(password),
5012 if (user[0] == (char)0) fstrcpy(user, context->user);
5014 fstrcpy(workgroup, context->workgroup);
5016 srv = smbc_server(context, True,
5017 server, share, workgroup, user, password);
5019 return -1; /* errno set by smbc_server */
5022 if (! srv->no_nt_session) {
5023 ipc_srv = smbc_attr_server(context, server, share,
5024 workgroup, user, password,
5026 srv->no_nt_session = True;
5031 ctx = talloc_init("smbc_setxattr");
5038 * Are they asking to set the entire set of known attributes?
5040 if (StrCaseCmp(name, "system.*") == 0 ||
5041 StrCaseCmp(name, "system.*+") == 0) {
5044 talloc_asprintf(ctx, "%s:%s",
5045 name+7, (const char *) value);
5053 ret = cacl_set(ctx, &srv->cli,
5054 &ipc_srv->cli, &pol, path,
5057 ? SMBC_XATTR_MODE_SET
5058 : SMBC_XATTR_MODE_ADD),
5064 /* get a DOS Attribute Descriptor with current attributes */
5065 dad = dos_attr_query(context, ctx, path, srv);
5067 /* Overwrite old with new, using what was provided */
5068 dos_attr_parse(context, dad, srv, namevalue);
5070 /* Set the new DOS attributes */
5071 if (! smbc_setatr(context, srv, path,
5077 /* cause failure if NT failed too */
5082 /* we only fail if both NT and DOS sets failed */
5083 if (ret < 0 && ! dad) {
5084 ret = -1; /* in case dad was null */
5090 talloc_destroy(ctx);
5095 * Are they asking to set an access control element or to set
5096 * the entire access control list?
5098 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5099 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5100 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5101 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5102 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5106 talloc_asprintf(ctx, "%s:%s",
5107 name+19, (const char *) value);
5110 ret = -1; /* errno set by smbc_server() */
5112 else if (! namevalue) {
5116 ret = cacl_set(ctx, &srv->cli,
5117 &ipc_srv->cli, &pol, path,
5120 ? SMBC_XATTR_MODE_SET
5121 : SMBC_XATTR_MODE_ADD),
5124 talloc_destroy(ctx);
5129 * Are they asking to set the owner?
5131 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5132 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5136 talloc_asprintf(ctx, "%s:%s",
5137 name+19, (const char *) value);
5141 ret = -1; /* errno set by smbc_server() */
5143 else if (! namevalue) {
5147 ret = cacl_set(ctx, &srv->cli,
5148 &ipc_srv->cli, &pol, path,
5149 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5151 talloc_destroy(ctx);
5156 * Are they asking to set the group?
5158 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5159 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5163 talloc_asprintf(ctx, "%s:%s",
5164 name+19, (const char *) value);
5167 /* errno set by smbc_server() */
5170 else if (! namevalue) {
5174 ret = cacl_set(ctx, &srv->cli,
5175 &ipc_srv->cli, &pol, path,
5176 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5178 talloc_destroy(ctx);
5183 * Are they asking to set a DOS attribute?
5185 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5186 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5187 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5188 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5189 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
5191 /* get a DOS Attribute Descriptor with current attributes */
5192 dad = dos_attr_query(context, ctx, path, srv);
5195 talloc_asprintf(ctx, "%s:%s",
5196 name+16, (const char *) value);
5201 /* Overwrite old with provided new params */
5202 dos_attr_parse(context, dad, srv, namevalue);
5204 /* Set the new DOS attributes */
5205 ret2 = smbc_setatr(context, srv, path,
5211 /* ret2 has True (success) / False (failure) */
5222 talloc_destroy(ctx);
5226 /* Unsupported attribute name */
5227 talloc_destroy(ctx);
5233 smbc_getxattr_ctx(SMBCCTX *context,
5252 if (!context || !context->internal ||
5253 !context->internal->_initialized) {
5255 errno = EINVAL; /* Best I can think of ... */
5267 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5269 if (smbc_parse_path(context, fname,
5270 server, sizeof(server),
5271 share, sizeof(share),
5274 password, sizeof(password),
5280 if (user[0] == (char)0) fstrcpy(user, context->user);
5282 fstrcpy(workgroup, context->workgroup);
5284 srv = smbc_server(context, True,
5285 server, share, workgroup, user, password);
5287 return -1; /* errno set by smbc_server */
5290 if (! srv->no_nt_session) {
5291 ipc_srv = smbc_attr_server(context, server, share,
5292 workgroup, user, password,
5295 srv->no_nt_session = True;
5301 ctx = talloc_init("smbc:getxattr");
5307 /* Are they requesting a supported attribute? */
5308 if (StrCaseCmp(name, "system.*") == 0 ||
5309 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5310 StrCaseCmp(name, "system.*+") == 0 ||
5311 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5312 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5313 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5314 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5315 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5316 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5317 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5318 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5319 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5320 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5321 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5322 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5323 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5324 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5325 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5326 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5327 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5328 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5329 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
5330 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5333 ret = cacl_get(context, ctx, srv,
5334 ipc_srv == NULL ? NULL : &ipc_srv->cli,
5336 CONST_DISCARD(char *, name),
5337 CONST_DISCARD(char *, value), size);
5338 if (ret < 0 && errno == 0) {
5339 errno = smbc_errno(context, &srv->cli);
5341 talloc_destroy(ctx);
5345 /* Unsupported attribute name */
5346 talloc_destroy(ctx);
5353 smbc_removexattr_ctx(SMBCCTX *context,
5369 if (!context || !context->internal ||
5370 !context->internal->_initialized) {
5372 errno = EINVAL; /* Best I can think of ... */
5384 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5386 if (smbc_parse_path(context, fname,
5387 server, sizeof(server),
5388 share, sizeof(share),
5391 password, sizeof(password),
5397 if (user[0] == (char)0) fstrcpy(user, context->user);
5399 fstrcpy(workgroup, context->workgroup);
5401 srv = smbc_server(context, True,
5402 server, share, workgroup, user, password);
5404 return -1; /* errno set by smbc_server */
5407 if (! srv->no_nt_session) {
5408 ipc_srv = smbc_attr_server(context, server, share,
5409 workgroup, user, password,
5411 srv->no_nt_session = True;
5417 return -1; /* errno set by smbc_attr_server */
5420 ctx = talloc_init("smbc_removexattr");
5426 /* Are they asking to set the entire ACL? */
5427 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5428 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5431 ret = cacl_set(ctx, &srv->cli,
5432 &ipc_srv->cli, &pol, path,
5433 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5434 talloc_destroy(ctx);
5439 * Are they asking to remove one or more spceific security descriptor
5442 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5443 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5444 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5445 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5446 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5447 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5448 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5451 ret = cacl_set(ctx, &srv->cli,
5452 &ipc_srv->cli, &pol, path,
5453 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5454 talloc_destroy(ctx);
5458 /* Unsupported attribute name */
5459 talloc_destroy(ctx);
5465 smbc_listxattr_ctx(SMBCCTX *context,
5471 * This isn't quite what listxattr() is supposed to do. This returns
5472 * the complete set of attribute names, always, rather than only those
5473 * attribute names which actually exist for a file. Hmmm...
5475 const char supported[] =
5478 "system.nt_sec_desc.revision\0"
5479 "system.nt_sec_desc.owner\0"
5480 "system.nt_sec_desc.owner+\0"
5481 "system.nt_sec_desc.group\0"
5482 "system.nt_sec_desc.group+\0"
5483 "system.nt_sec_desc.acl.*\0"
5484 "system.nt_sec_desc.acl\0"
5485 "system.nt_sec_desc.acl+\0"
5486 "system.nt_sec_desc.*\0"
5487 "system.nt_sec_desc.*+\0"
5488 "system.dos_attr.*\0"
5489 "system.dos_attr.mode\0"
5490 "system.dos_attr.c_time\0"
5491 "system.dos_attr.a_time\0"
5492 "system.dos_attr.m_time\0"
5496 return sizeof(supported);
5499 if (sizeof(supported) > size) {
5504 /* this can't be strcpy() because there are embedded null characters */
5505 memcpy(list, supported, sizeof(supported));
5506 return sizeof(supported);
5511 * Open a print file to be written to by other calls
5515 smbc_open_print_job_ctx(SMBCCTX *context,
5524 if (!context || !context->internal ||
5525 !context->internal->_initialized) {
5539 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5541 if (smbc_parse_path(context, fname,
5542 server, sizeof(server),
5543 share, sizeof(share),
5546 password, sizeof(password),
5552 /* What if the path is empty, or the file exists? */
5554 return context->open(context, fname, O_WRONLY, 666);
5559 * Routine to print a file on a remote server ...
5561 * We open the file, which we assume to be on a remote server, and then
5562 * copy it to a print file on the share specified by printq.
5566 smbc_print_file_ctx(SMBCCTX *c_file,
5578 if (!c_file || !c_file->internal->_initialized || !c_print ||
5579 !c_print->internal->_initialized) {
5586 if (!fname && !printq) {
5593 /* Try to open the file for reading ... */
5595 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5597 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5598 return -1; /* smbc_open sets errno */
5602 /* Now, try to open the printer file for writing */
5604 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5606 saverr = errno; /* Save errno */
5607 c_file->close_fn(c_file, fid1);
5613 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5617 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5620 c_file->close_fn(c_file, fid1);
5621 c_print->close_fn(c_print, fid2);
5630 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5631 c_print->close_fn(c_print, fid2);
5645 * Routine to list print jobs on a printer share ...
5649 smbc_list_print_jobs_ctx(SMBCCTX *context,
5651 smbc_list_print_job_fn fn)
5661 if (!context || !context->internal ||
5662 !context->internal->_initialized) {
5676 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5678 if (smbc_parse_path(context, fname,
5679 server, sizeof(server),
5680 share, sizeof(share),
5683 password, sizeof(password),
5689 if (user[0] == (char)0) fstrcpy(user, context->user);
5691 fstrcpy(workgroup, context->workgroup);
5693 srv = smbc_server(context, True,
5694 server, share, workgroup, user, password);
5698 return -1; /* errno set by smbc_server */
5702 if (cli_print_queue(&srv->cli,
5703 (void (*)(struct print_job_info *))fn) < 0) {
5705 errno = smbc_errno(context, &srv->cli);
5715 * Delete a print job from a remote printer share
5719 smbc_unlink_print_job_ctx(SMBCCTX *context,
5732 if (!context || !context->internal ||
5733 !context->internal->_initialized) {
5747 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5749 if (smbc_parse_path(context, fname,
5750 server, sizeof(server),
5751 share, sizeof(share),
5754 password, sizeof(password),
5760 if (user[0] == (char)0) fstrcpy(user, context->user);
5762 fstrcpy(workgroup, context->workgroup);
5764 srv = smbc_server(context, True,
5765 server, share, workgroup, user, password);
5769 return -1; /* errno set by smbc_server */
5773 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5776 errno = smbc_errno(context, &srv->cli);
5777 else if (err == ERRnosuchprintjob)
5788 * Get a new empty handle to fill in with your own info
5791 smbc_new_context(void)
5795 context = SMB_MALLOC_P(SMBCCTX);
5801 ZERO_STRUCTP(context);
5803 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5804 if (!context->internal) {
5809 ZERO_STRUCTP(context->internal);
5812 /* ADD REASONABLE DEFAULTS */
5814 context->timeout = 20000; /* 20 seconds */
5816 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5817 context->options.urlencode_readdir_entries = False;/* backward compat */
5818 context->options.one_share_per_server = False;/* backward compat */
5820 context->open = smbc_open_ctx;
5821 context->creat = smbc_creat_ctx;
5822 context->read = smbc_read_ctx;
5823 context->write = smbc_write_ctx;
5824 context->close_fn = smbc_close_ctx;
5825 context->unlink = smbc_unlink_ctx;
5826 context->rename = smbc_rename_ctx;
5827 context->lseek = smbc_lseek_ctx;
5828 context->stat = smbc_stat_ctx;
5829 context->fstat = smbc_fstat_ctx;
5830 context->opendir = smbc_opendir_ctx;
5831 context->closedir = smbc_closedir_ctx;
5832 context->readdir = smbc_readdir_ctx;
5833 context->getdents = smbc_getdents_ctx;
5834 context->mkdir = smbc_mkdir_ctx;
5835 context->rmdir = smbc_rmdir_ctx;
5836 context->telldir = smbc_telldir_ctx;
5837 context->lseekdir = smbc_lseekdir_ctx;
5838 context->fstatdir = smbc_fstatdir_ctx;
5839 context->chmod = smbc_chmod_ctx;
5840 context->utimes = smbc_utimes_ctx;
5841 context->setxattr = smbc_setxattr_ctx;
5842 context->getxattr = smbc_getxattr_ctx;
5843 context->removexattr = smbc_removexattr_ctx;
5844 context->listxattr = smbc_listxattr_ctx;
5845 context->open_print_job = smbc_open_print_job_ctx;
5846 context->print_file = smbc_print_file_ctx;
5847 context->list_print_jobs = smbc_list_print_jobs_ctx;
5848 context->unlink_print_job = smbc_unlink_print_job_ctx;
5850 context->callbacks.check_server_fn = smbc_check_server;
5851 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5853 smbc_default_cache_functions(context);
5861 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5862 * and thus you'll be leaking memory if not handled properly.
5866 smbc_free_context(SMBCCTX *context,
5876 DEBUG(1,("Performing aggressive shutdown.\n"));
5878 f = context->internal->_files;
5880 context->close_fn(context, f);
5883 context->internal->_files = NULL;
5885 /* First try to remove the servers the nice way. */
5886 if (context->callbacks.purge_cached_fn(context)) {
5889 DEBUG(1, ("Could not purge all servers, "
5890 "Nice way shutdown failed.\n"));
5891 s = context->internal->_servers;
5893 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
5895 cli_shutdown(&s->cli);
5896 context->callbacks.remove_cached_srv_fn(context,
5899 DLIST_REMOVE(context->internal->_servers, s);
5903 context->internal->_servers = NULL;
5907 /* This is the polite way */
5908 if (context->callbacks.purge_cached_fn(context)) {
5909 DEBUG(1, ("Could not purge all servers, "
5910 "free_context failed.\n"));
5914 if (context->internal->_servers) {
5915 DEBUG(1, ("Active servers in context, "
5916 "free_context failed.\n"));
5920 if (context->internal->_files) {
5921 DEBUG(1, ("Active files in context, "
5922 "free_context failed.\n"));
5928 /* Things we have to clean up */
5929 SAFE_FREE(context->workgroup);
5930 SAFE_FREE(context->netbios_name);
5931 SAFE_FREE(context->user);
5933 DEBUG(3, ("Context %p succesfully freed\n", context));
5934 SAFE_FREE(context->internal);
5941 * Initialise the library etc
5943 * We accept a struct containing handle information.
5944 * valid values for info->debug from 0 to 100,
5945 * and insist that info->fn must be non-null.
5948 smbc_init_context(SMBCCTX *context)
5955 if (!context || !context->internal) {
5960 /* Do not initialise the same client twice */
5961 if (context->internal->_initialized) {
5965 if (!context->callbacks.auth_fn ||
5966 context->debug < 0 ||
5967 context->debug > 100) {
5974 if (!smbc_initialized) {
5976 * Do some library-wide intializations the first time we get
5979 BOOL conf_loaded = False;
5981 /* Set this to what the user wants */
5982 DEBUGLEVEL = context->debug;
5985 setup_logging( "libsmbclient", True);
5987 /* Here we would open the smb.conf file if needed ... */
5989 in_client = True; /* FIXME, make a param */
5991 home = getenv("HOME");
5993 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5994 if (lp_load(conf, True, False, False)) {
5997 DEBUG(5, ("Could not load config file: %s\n",
6004 * Well, if that failed, try the dyn_CONFIGFILE
6005 * Which points to the standard locn, and if that
6006 * fails, silently ignore it and use the internal
6010 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
6011 DEBUG(5, ("Could not load config file: %s\n",
6015 * We loaded the global config file. Now lets
6016 * load user-specific modifications to the
6019 slprintf(conf, sizeof(conf),
6020 "%s/.smb/smb.conf.append", home);
6021 if (!lp_load(conf, True, False, False)) {
6023 ("Could not append config file: "
6030 load_interfaces(); /* Load the list of interfaces ... */
6032 reopen_logs(); /* Get logging working ... */
6035 * Block SIGPIPE (from lib/util_sock.c: write())
6036 * It is not needed and should not stop execution
6038 BlockSignals(True, SIGPIPE);
6040 /* Done with one-time initialisation */
6041 smbc_initialized = 1;
6045 if (!context->user) {
6047 * FIXME: Is this the best way to get the user info?
6049 user = getenv("USER");
6050 /* walk around as "guest" if no username can be found */
6051 if (!user) context->user = SMB_STRDUP("guest");
6052 else context->user = SMB_STRDUP(user);
6055 if (!context->netbios_name) {
6057 * We try to get our netbios name from the config. If that
6058 * fails we fall back on constructing our netbios name from
6061 if (global_myname()) {
6062 context->netbios_name = SMB_STRDUP(global_myname());
6066 * Hmmm, I want to get hostname as well, but I am too
6067 * lazy for the moment
6070 context->netbios_name = SMB_MALLOC(17);
6071 if (!context->netbios_name) {
6075 slprintf(context->netbios_name, 16,
6076 "smbc%s%d", context->user, pid);
6080 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
6082 if (!context->workgroup) {
6083 if (lp_workgroup()) {
6084 context->workgroup = SMB_STRDUP(lp_workgroup());
6087 /* TODO: Think about a decent default workgroup */
6088 context->workgroup = SMB_STRDUP("samba");
6092 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
6094 /* shortest timeout is 1 second */
6095 if (context->timeout > 0 && context->timeout < 1000)
6096 context->timeout = 1000;
6099 * FIXME: Should we check the function pointers here?
6102 context->internal->_initialized = 1;
6108 /* Return the verion of samba, and thus libsmbclient */
6112 return samba_version_string();