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
9 Copyright (C) Jeremy Allison 2007, 2008
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 3 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program. If not, see <http://www.gnu.org/licenses/>.
27 #include "include/libsmb_internal.h"
29 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir);
30 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
31 struct smbc_dirent *dirent);
34 * DOS Attribute values (used internally)
36 typedef struct DOS_ATTR_DESC {
48 * Internal flags for extended attributes
51 /* internal mode values */
52 #define SMBC_XATTR_MODE_ADD 1
53 #define SMBC_XATTR_MODE_REMOVE 2
54 #define SMBC_XATTR_MODE_REMOVE_ALL 3
55 #define SMBC_XATTR_MODE_SET 4
56 #define SMBC_XATTR_MODE_CHOWN 5
57 #define SMBC_XATTR_MODE_CHGRP 6
59 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
61 /*We should test for this in configure ... */
63 #define ENOTSUP EOPNOTSUPP
67 * Functions exported by libsmb_cache.c that we need here
69 int smbc_default_cache_functions(SMBCCTX *context);
72 * check if an element is part of the list.
73 * FIXME: Does not belong here !
74 * Can anyone put this in a macro in dlinklist.h ?
77 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
78 if (!p || !list) return False;
80 if (p == list) return True;
87 * Find an lsa pipe handle associated with a cli struct.
89 static struct rpc_pipe_client *
90 find_lsa_pipe_hnd(struct cli_state *ipc_cli)
92 struct rpc_pipe_client *pipe_hnd;
94 for (pipe_hnd = ipc_cli->pipe_list;
96 pipe_hnd = pipe_hnd->next) {
98 if (pipe_hnd->pipe_idx == PI_LSARPC) {
107 smbc_close_ctx(SMBCCTX *context,
110 smbc_lseek_ctx(SMBCCTX *context,
115 extern bool in_client;
118 * Is the logging working / configfile read ?
120 static int smbc_initialized = 0;
123 hex2int( unsigned int _char )
125 if ( _char >= 'A' && _char <='F')
126 return _char - 'A' + 10;
127 if ( _char >= 'a' && _char <='f')
128 return _char - 'a' + 10;
129 if ( _char >= '0' && _char <='9')
136 * and smbc_urldecode_talloc() (internal fn.)
138 * Convert strings of %xx to their single character equivalent. Each 'x' must
139 * be a valid hexadecimal digit, or that % sequence is left undecoded.
141 * dest may, but need not be, the same pointer as src.
143 * Returns the number of % sequences which could not be converted due to lack
144 * of two following hexadecimal digits.
147 smbc_urldecode_talloc(TALLOC_CTX *ctx, char **pp_dest, const char *src)
149 int old_length = strlen(src);
155 if (old_length == 0) {
160 for (i = 0; i < old_length; ) {
161 unsigned char character = src[i++];
163 if (character == '%') {
164 int a = i+1 < old_length ? hex2int(src[i]) : -1;
165 int b = i+1 < old_length ? hex2int(src[i+1]) : -1;
167 /* Replace valid sequence */
168 if (a != -1 && b != -1) {
169 /* Replace valid %xx sequence with %dd */
170 character = (a * 16) + b;
171 if (character == '\0') {
172 break; /* Stop at %00 */
182 dest = TALLOC_ARRAY(ctx, char, newlen);
188 for (p = dest, i = 0; i < old_length; ) {
189 unsigned char character = src[i++];
191 if (character == '%') {
192 int a = i+1 < old_length ? hex2int(src[i]) : -1;
193 int b = i+1 < old_length ? hex2int(src[i+1]) : -1;
195 /* Replace valid sequence */
196 if (a != -1 && b != -1) {
197 /* Replace valid %xx sequence with %dd */
198 character = (a * 16) + b;
199 if (character == '\0') {
200 break; /* Stop at %00 */
216 smbc_urldecode(char *dest, char *src, size_t max_dest_len)
218 TALLOC_CTX *frame = talloc_stackframe();
220 int ret = smbc_urldecode_talloc(frame, &pdest, src);
223 strlcpy(dest, pdest, max_dest_len);
232 * Convert any characters not specifically allowed in a URL into their %xx
235 * Returns the remaining buffer length.
238 smbc_urlencode(char *dest, char *src, int max_dest_len)
240 char hex[] = "0123456789ABCDEF";
242 for (; *src != '\0' && max_dest_len >= 3; src++) {
254 *dest++ = hex[(*src >> 4) & 0x0f];
255 *dest++ = hex[*src & 0x0f];
270 * Function to parse a path and turn it into components
272 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
273 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
274 * general format ("smb:" only; we do not look for "cifs:").
278 * smb://[[[domain;]user[:password]@]server[/share[/path[/file]]]][?options]
282 * smb:// Show all workgroups.
284 * The method of locating the list of workgroups varies
285 * depending upon the setting of the context variable
286 * context->options.browse_max_lmb_count. This value
287 * determine the maximum number of local master browsers to
288 * query for the list of workgroups. In order to ensure that
289 * a complete list of workgroups is obtained, all master
290 * browsers must be queried, but if there are many
291 * workgroups, the time spent querying can begin to add up.
292 * For small networks (not many workgroups), it is suggested
293 * that this variable be set to 0, indicating query all local
294 * master browsers. When the network has many workgroups, a
295 * reasonable setting for this variable might be around 3.
297 * smb://name/ if name<1D> or name<1B> exists, list servers in
298 * workgroup, else, if name<20> exists, list all shares
301 * If "options" are provided, this function returns the entire option list as a
302 * string, for later parsing by the caller. Note that currently, no options
306 static const char *smbc_prefix = "smb:";
309 smbc_parse_path(TALLOC_CTX *ctx,
325 /* Ensure these returns are at least valid pointers. */
326 *pp_server = talloc_strdup(ctx, "");
327 *pp_share = talloc_strdup(ctx, "");
328 *pp_path = talloc_strdup(ctx, "");
329 *pp_user = talloc_strdup(ctx, "");
330 *pp_password = talloc_strdup(ctx, "");
332 if (!*pp_server || !*pp_share || !*pp_path ||
333 !*pp_user || !*pp_password) {
338 * Assume we wont find an authentication domain to parse, so default
339 * to the workgroup in the provided context.
341 if (pp_workgroup != NULL) {
342 *pp_workgroup = talloc_strdup(ctx, context->workgroup);
346 *pp_options = talloc_strdup(ctx, "");
348 s = talloc_strdup(ctx, fname);
350 /* see if it has the right prefix */
351 len = strlen(smbc_prefix);
352 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
353 return -1; /* What about no smb: ? */
358 /* Watch the test below, we are testing to see if we should exit */
360 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
361 DEBUG(1, ("Invalid path (does not begin with smb://"));
365 p += 2; /* Skip the double slash */
367 /* See if any options were specified */
368 if ((q = strrchr(p, '?')) != NULL ) {
369 /* There are options. Null terminate here and point to them */
372 DEBUG(4, ("Found options '%s'", q));
374 /* Copy the options */
375 if (*pp_options != NULL) {
376 TALLOC_FREE(*pp_options);
377 *pp_options = talloc_strdup(ctx, q);
386 int wl = strlen(context->workgroup);
392 *pp_server = talloc_strdup(ctx, context->workgroup);
396 *pp_server[wl] = '\0';
401 * ok, its for us. Now parse out the server, share etc.
403 * However, we want to parse out [[domain;]user[:password]@] if it
407 /* check that '@' occurs before '/', if '/' exists at all */
408 q = strchr_m(p, '@');
409 r = strchr_m(p, '/');
410 if (q && (!r || q < r)) {
411 char *userinfo = NULL;
414 next_token_no_ltrim_talloc(ctx, &p, &userinfo, "@");
420 if (strchr_m(u, ';')) {
422 next_token_no_ltrim_talloc(ctx, &u, &workgroup, ";");
427 *pp_workgroup = workgroup;
431 if (strchr_m(u, ':')) {
432 next_token_no_ltrim_talloc(ctx, &u, pp_user, ":");
436 *pp_password = talloc_strdup(ctx, u);
441 *pp_user = talloc_strdup(ctx, u);
448 if (!next_token_talloc(ctx, &p, pp_server, "/")) {
453 goto decoding; /* That's it ... */
456 if (!next_token_talloc(ctx, &p, pp_share, "/")) {
461 * Prepend a leading slash if there's a file path, as required by
465 *pp_path = talloc_asprintf(ctx,
469 *pp_path = talloc_strdup(ctx, "");
474 string_replace(*pp_path, '/', '\\');
478 (void) smbc_urldecode_talloc(ctx, pp_path, *pp_path);
479 (void) smbc_urldecode_talloc(ctx, pp_server, *pp_server);
480 (void) smbc_urldecode_talloc(ctx, pp_share, *pp_share);
481 (void) smbc_urldecode_talloc(ctx, pp_user, *pp_user);
482 (void) smbc_urldecode_talloc(ctx, pp_password, *pp_password);
488 * Verify that the options specified in a URL are valid
491 smbc_check_options(char *server,
496 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' "
497 "path='%s' options='%s'\n",
498 server, share, path, options));
500 /* No options at all is always ok */
501 if (! *options) return 0;
503 /* Currently, we don't support any options. */
508 * Convert an SMB error into a UNIX error ...
511 smbc_errno(SMBCCTX *context,
514 int ret = cli_errno(c);
516 if (cli_is_dos_error(c)) {
520 cli_dos_error(c, &eclass, &ecode);
522 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
523 (int)eclass, (int)ecode, (int)ecode, ret));
527 status = cli_nt_error(c);
529 DEBUG(3,("smbc errno %s -> %d\n",
530 nt_errstr(status), ret));
537 * Check a server for being alive and well.
538 * returns 0 if the server is in shape. Returns 1 on error
540 * Also useable outside libsmbclient to enable external cache
541 * to do some checks too.
544 smbc_check_server(SMBCCTX * context,
548 struct sockaddr addr;
551 return (getpeername(server->cli->fd, &addr, &size) == -1);
555 * Remove a server from the cached server list it's unused.
556 * On success, 0 is returned. 1 is returned if the server could not be removed.
558 * Also useable outside libsmbclient
561 smbc_remove_unused_server(SMBCCTX * context,
566 /* are we being fooled ? */
567 if (!context || !context->internal ||
568 !context->internal->_initialized || !srv) return 1;
571 /* Check all open files/directories for a relation with this server */
572 for (file = context->internal->_files; file; file=file->next) {
573 if (file->srv == srv) {
575 DEBUG(3, ("smbc_remove_usused_server: "
576 "%p still used by %p.\n",
582 DLIST_REMOVE(context->internal->_servers, srv);
584 cli_shutdown(srv->cli);
587 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
589 (context->callbacks.remove_cached_srv_fn)(context, srv);
595 /****************************************************************
596 * Call the auth_fn with fixed size (fstring) buffers.
597 ***************************************************************/
599 static void call_auth_fn(TALLOC_CTX *ctx,
611 strlcpy(workgroup, *pp_workgroup, sizeof(workgroup));
612 strlcpy(username, *pp_username, sizeof(username));
613 strlcpy(password, *pp_password, sizeof(password));
615 if (context->internal->_auth_fn_with_context != NULL) {
616 (context->internal->_auth_fn_with_context)(
619 workgroup, sizeof(workgroup),
620 username, sizeof(username),
621 password, sizeof(password));
623 (context->callbacks.auth_fn)(
625 workgroup, sizeof(workgroup),
626 username, sizeof(username),
627 password, sizeof(password));
630 TALLOC_FREE(*pp_workgroup);
631 TALLOC_FREE(*pp_username);
632 TALLOC_FREE(*pp_password);
634 *pp_workgroup = talloc_strdup(ctx, workgroup);
635 *pp_username = talloc_strdup(ctx, username);
636 *pp_password = talloc_strdup(ctx, password);
640 find_server(TALLOC_CTX *ctx,
653 srv = (context->callbacks.get_cached_srv_fn)(context, server, share,
654 *pp_workgroup, *pp_username);
656 if (!auth_called && !srv && (!*pp_username || !(*pp_username)[0] ||
657 !*pp_password || !(*pp_password)[0])) {
658 call_auth_fn(ctx, context, server, share,
659 pp_workgroup, pp_username, pp_password);
661 if (!pp_workgroup || !pp_username || !pp_password) {
666 * However, smbc_auth_fn may have picked up info relating to
667 * an existing connection, so try for an existing connection
671 goto check_server_cache;
676 if ((context->callbacks.check_server_fn)(context, srv)) {
678 * This server is no good anymore
679 * Try to remove it and check for more possible
680 * servers in the cache
682 if ((context->callbacks.remove_unused_server_fn)(context,
685 * We could not remove the server completely,
686 * remove it from the cache so we will not get
687 * it again. It will be removed when the last
688 * file/dir is closed.
690 (context->callbacks.remove_cached_srv_fn)(context,
695 * Maybe there are more cached connections to this
698 goto check_server_cache;
708 * Connect to a server, possibly on an existing connection
710 * Here, what we want to do is: If the server and username
711 * match an existing connection, reuse that, otherwise, establish a
714 * If we have to create a new connection, call the auth_fn to get the
715 * info we need, unless the username and password were passed in.
719 smbc_server(TALLOC_CTX *ctx,
721 bool connect_if_not_found,
730 struct nmb_name called, calling;
731 const char *server_n = server;
732 struct sockaddr_storage ss;
733 int tried_reverse = 0;
736 const char *username_used;
742 if (server[0] == 0) {
747 /* Look for a cached connection */
748 srv = find_server(ctx, context, server, share,
749 pp_workgroup, pp_username, pp_password);
752 * If we found a connection and we're only allowed one share per
755 if (srv && *share != '\0' && context->options.one_share_per_server) {
758 * ... then if there's no current connection to the share,
759 * connect to it. find_server(), or rather the function
760 * pointed to by context->callbacks.get_cached_srv_fn which
761 * was called by find_server(), will have issued a tree
762 * disconnect if the requested share is not the same as the
763 * one that was already connected.
765 if (srv->cli->cnum == (uint16) -1) {
766 /* Ensure we have accurate auth info */
767 call_auth_fn(ctx, context, server, share,
768 pp_workgroup, pp_username, pp_password);
770 if (!*pp_workgroup || !*pp_username || !*pp_password) {
772 cli_shutdown(srv->cli);
774 (context->callbacks.remove_cached_srv_fn)(context,
780 * We don't need to renegotiate encryption
781 * here as the encryption context is not per
785 if (!cli_send_tconX(srv->cli, share, "?????",
787 strlen(*pp_password)+1)) {
789 errno = smbc_errno(context, srv->cli);
790 cli_shutdown(srv->cli);
792 (context->callbacks.remove_cached_srv_fn)(context,
798 * Regenerate the dev value since it's based on both
802 srv->dev = (dev_t)(str_checksum(server) ^
803 str_checksum(share));
808 /* If we have a connection... */
811 /* ... then we're done here. Give 'em what they came for. */
815 /* If we're not asked to connect when a connection doesn't exist... */
816 if (! connect_if_not_found) {
817 /* ... then we're done here. */
821 if (!*pp_workgroup || !*pp_username || !*pp_password) {
826 make_nmb_name(&calling, context->netbios_name, 0x0);
827 make_nmb_name(&called , server, 0x20);
829 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
831 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
837 /* have to open a new connection */
838 if ((c = cli_initialise()) == NULL) {
843 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
844 c->use_kerberos = True;
846 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
847 c->fallback_after_kerberos = True;
850 c->timeout = context->timeout;
853 * Force use of port 139 for first try if share is $IPC, empty, or
854 * null, so browse lists can work
856 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
857 port_try_first = 139;
860 port_try_first = 445;
864 c->port = port_try_first;
866 status = cli_connect(c, server_n, &ss);
867 if (!NT_STATUS_IS_OK(status)) {
869 /* First connection attempt failed. Try alternate port. */
870 c->port = port_try_next;
872 status = cli_connect(c, server_n, &ss);
873 if (!NT_STATUS_IS_OK(status)) {
880 if (!cli_session_request(c, &calling, &called)) {
882 if (strcmp(called.name, "*SMBSERVER")) {
883 make_nmb_name(&called , "*SMBSERVER", 0x20);
885 } else { /* Try one more time, but ensure we don't loop */
887 /* Only try this if server is an IP address ... */
889 if (is_ipaddress(server) && !tried_reverse) {
891 struct sockaddr_storage rem_ss;
893 if (!interpret_string_addr(&rem_ss, server,
895 DEBUG(4, ("Could not convert IP address "
896 "%s to struct sockaddr_storage\n",
902 tried_reverse++; /* Yuck */
904 if (name_status_find("*", 0, 0, &rem_ss, remote_name)) {
905 make_nmb_name(&called, remote_name, 0x20);
914 DEBUG(4,(" session request ok\n"));
916 if (!cli_negprot(c)) {
922 username_used = *pp_username;
924 if (!NT_STATUS_IS_OK(cli_session_setup(c, username_used,
925 *pp_password, strlen(*pp_password),
926 *pp_password, strlen(*pp_password),
929 /* Failed. Try an anonymous login, if allowed by flags. */
932 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
933 !NT_STATUS_IS_OK(cli_session_setup(c, username_used,
944 DEBUG(4,(" session setup ok\n"));
946 if (!cli_send_tconX(c, share, "?????",
947 *pp_password, strlen(*pp_password)+1)) {
948 errno = smbc_errno(context, c);
953 DEBUG(4,(" tconx ok\n"));
955 if (context->internal->_smb_encryption_level) {
956 /* Attempt UNIX smb encryption. */
957 if (!NT_STATUS_IS_OK(cli_force_encryption(c,
963 * context->internal->_smb_encryption_level == 1
964 * means don't fail if encryption can't be negotiated,
965 * == 2 means fail if encryption can't be negotiated.
968 DEBUG(4,(" SMB encrypt failed\n"));
970 if (context->internal->_smb_encryption_level == 2) {
976 DEBUG(4,(" SMB encrypt ok\n"));
980 * Ok, we have got a nice connection
981 * Let's allocate a server structure.
984 srv = SMB_MALLOC_P(SMBCSRV);
992 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
993 srv->no_pathinfo = False;
994 srv->no_pathinfo2 = False;
995 srv->no_nt_session = False;
997 /* now add it to the cache (internal or external) */
998 /* Let the cache function set errno if it wants to */
1000 if ((context->callbacks.add_cached_srv_fn)(context, srv,
1004 int saved_errno = errno;
1005 DEBUG(3, (" Failed to add server to cache\n"));
1006 errno = saved_errno;
1013 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
1014 server, share, srv));
1016 DLIST_ADD(context->internal->_servers, srv);
1030 * Connect to a server for getting/setting attributes, possibly on an existing
1031 * connection. This works similarly to smbc_server().
1034 smbc_attr_server(TALLOC_CTX *ctx,
1038 char **pp_workgroup,
1044 struct sockaddr_storage ss;
1045 struct cli_state *ipc_cli;
1046 struct rpc_pipe_client *pipe_hnd;
1048 SMBCSRV *ipc_srv=NULL;
1051 * See if we've already created this special connection. Reference
1052 * our "special" share name '*IPC$', which is an impossible real share
1053 * name due to the leading asterisk.
1055 ipc_srv = find_server(ctx, context, server, "*IPC$",
1056 pp_workgroup, pp_username, pp_password);
1059 /* We didn't find a cached connection. Get the password */
1060 if (!*pp_password || (*pp_password)[0] == '\0') {
1061 /* ... then retrieve it now. */
1062 call_auth_fn(ctx, context, server, share,
1063 pp_workgroup, pp_username, pp_password);
1064 if (!*pp_workgroup || !*pp_username || !*pp_password) {
1071 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
1072 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
1076 nt_status = cli_full_connection(&ipc_cli,
1077 global_myname(), server,
1078 &ss, 0, "IPC$", "?????",
1084 if (! NT_STATUS_IS_OK(nt_status)) {
1085 DEBUG(1,("cli_full_connection failed! (%s)\n",
1086 nt_errstr(nt_status)));
1091 if (context->internal->_smb_encryption_level) {
1092 /* Attempt UNIX smb encryption. */
1093 if (!NT_STATUS_IS_OK(cli_force_encryption(ipc_cli,
1099 * context->internal->_smb_encryption_level == 1
1100 * means don't fail if encryption can't be negotiated,
1101 * == 2 means fail if encryption can't be negotiated.
1104 DEBUG(4,(" SMB encrypt failed on IPC$\n"));
1106 if (context->internal->_smb_encryption_level == 2) {
1107 cli_shutdown(ipc_cli);
1112 DEBUG(4,(" SMB encrypt ok on IPC$\n"));
1115 ipc_srv = SMB_MALLOC_P(SMBCSRV);
1118 cli_shutdown(ipc_cli);
1122 ZERO_STRUCTP(ipc_srv);
1123 ipc_srv->cli = ipc_cli;
1126 pipe_hnd = cli_rpc_pipe_open_noauth(ipc_srv->cli,
1130 DEBUG(1, ("cli_nt_session_open fail!\n"));
1132 cli_shutdown(ipc_srv->cli);
1138 * Some systems don't support
1139 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
1140 * so we might as well do it too.
1143 nt_status = rpccli_lsa_open_policy(
1147 GENERIC_EXECUTE_ACCESS,
1150 if (!NT_STATUS_IS_OK(nt_status)) {
1151 errno = smbc_errno(context, ipc_srv->cli);
1152 cli_shutdown(ipc_srv->cli);
1157 /* now add it to the cache (internal or external) */
1159 errno = 0; /* let cache function set errno if it likes */
1160 if ((context->callbacks.add_cached_srv_fn)(context, ipc_srv,
1165 DEBUG(3, (" Failed to add server to cache\n"));
1169 cli_shutdown(ipc_srv->cli);
1174 DLIST_ADD(context->internal->_servers, ipc_srv);
1181 * Routine to open() a file ...
1185 smbc_open_ctx(SMBCCTX *context,
1190 char *server = NULL, *share = NULL, *user = NULL, *password = NULL, *workgroup = NULL;
1192 char *targetpath = NULL;
1193 struct cli_state *targetcli = NULL;
1194 SMBCSRV *srv = NULL;
1195 SMBCFILE *file = NULL;
1197 TALLOC_CTX *frame = talloc_stackframe();
1199 if (!context || !context->internal ||
1200 !context->internal->_initialized) {
1202 errno = EINVAL; /* Best I can think of ... */
1216 if (smbc_parse_path(frame,
1231 if (!user || user[0] == (char)0) {
1232 user = talloc_strdup(frame, context->user);
1240 srv = smbc_server(frame, context, True,
1241 server, share, &workgroup, &user, &password);
1244 if (errno == EPERM) errno = EACCES;
1246 return NULL; /* smbc_server sets errno */
1249 /* Hmmm, the test for a directory is suspect here ... FIXME */
1251 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1254 file = SMB_MALLOC_P(SMBCFILE);
1264 /*d_printf(">>>open: resolving %s\n", path);*/
1265 if (!cli_resolve_path(frame, "", srv->cli, path, &targetcli, &targetpath)) {
1266 d_printf("Could not resolve %s\n", path);
1271 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1273 if ((fd = cli_open(targetcli, targetpath, flags,
1274 context->internal->_share_mode)) < 0) {
1276 /* Handle the error ... */
1279 errno = smbc_errno(context, targetcli);
1285 /* Fill in file struct */
1288 file->fname = SMB_STRDUP(fname);
1293 DLIST_ADD(context->internal->_files, file);
1296 * If the file was opened in O_APPEND mode, all write
1297 * operations should be appended to the file. To do that,
1298 * though, using this protocol, would require a getattrE()
1299 * call for each and every write, to determine where the end
1300 * of the file is. (There does not appear to be an append flag
1301 * in the protocol.) Rather than add all of that overhead of
1302 * retrieving the current end-of-file offset prior to each
1303 * write operation, we'll assume that most append operations
1304 * will continuously write, so we'll just set the offset to
1305 * the end of the file now and hope that's adequate.
1307 * Note to self: If this proves inadequate, and O_APPEND
1308 * should, in some cases, be forced for each write, add a
1309 * field in the context options structure, for
1310 * "strict_append_mode" which would select between the current
1311 * behavior (if FALSE) or issuing a getattrE() prior to each
1312 * write and forcing the write to the end of the file (if
1313 * TRUE). Adding that capability will likely require adding
1314 * an "append" flag into the _SMBCFILE structure to track
1315 * whether a file was opened in O_APPEND mode. -- djl
1317 if (flags & O_APPEND) {
1318 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1319 (void) smbc_close_ctx(context, file);
1331 /* Check if opendir needed ... */
1336 eno = smbc_errno(context, srv->cli);
1337 file = (context->opendir)(context, fname);
1338 if (!file) errno = eno;
1344 errno = EINVAL; /* FIXME, correct errno ? */
1351 * Routine to create a file
1354 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1357 smbc_creat_ctx(SMBCCTX *context,
1362 if (!context || !context->internal ||
1363 !context->internal->_initialized) {
1370 return smbc_open_ctx(context, path, creat_bits, mode);
1374 * Routine to read() a file ...
1378 smbc_read_ctx(SMBCCTX *context,
1384 char *server = NULL, *share = NULL, *user = NULL, *password = NULL;
1386 char *targetpath = NULL;
1387 struct cli_state *targetcli = NULL;
1388 TALLOC_CTX *frame = talloc_stackframe();
1393 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1394 * appears to pass file->offset (which is type off_t) differently than
1395 * a local variable of type off_t. Using local variable "offset" in
1396 * the call to cli_read() instead of file->offset fixes a problem
1397 * retrieving data at an offset greater than 4GB.
1401 if (!context || !context->internal ||
1402 !context->internal->_initialized) {
1409 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1411 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1418 offset = file->offset;
1420 /* Check that the buffer exists ... */
1429 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1430 if (smbc_parse_path(frame,
1445 /*d_printf(">>>read: resolving %s\n", path);*/
1446 if (!cli_resolve_path(frame, "", file->srv->cli, path,
1447 &targetcli, &targetpath)) {
1448 d_printf("Could not resolve %s\n", path);
1452 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1454 ret = cli_read(targetcli, file->cli_fd, (char *)buf, offset, count);
1458 errno = smbc_errno(context, targetcli);
1464 file->offset += ret;
1466 DEBUG(4, (" --> %d\n", ret));
1469 return ret; /* Success, ret bytes of data ... */
1474 * Routine to write() a file ...
1478 smbc_write_ctx(SMBCCTX *context,
1485 char *server = NULL, *share = NULL, *user = NULL, *password = NULL;
1487 char *targetpath = NULL;
1488 struct cli_state *targetcli = NULL;
1489 TALLOC_CTX *frame = talloc_stackframe();
1491 /* First check all pointers before dereferencing them */
1493 if (!context || !context->internal ||
1494 !context->internal->_initialized) {
1501 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1507 /* Check that the buffer exists ... */
1516 offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1518 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1519 if (smbc_parse_path(frame,
1534 /*d_printf(">>>write: resolving %s\n", path);*/
1535 if (!cli_resolve_path(frame, "", file->srv->cli, path,
1536 &targetcli, &targetpath)) {
1537 d_printf("Could not resolve %s\n", path);
1541 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1543 ret = cli_write(targetcli, file->cli_fd, 0, (char *)buf, offset, count);
1546 errno = smbc_errno(context, targetcli);
1552 file->offset += ret;
1555 return ret; /* Success, 0 bytes of data ... */
1559 * Routine to close() a file ...
1563 smbc_close_ctx(SMBCCTX *context,
1567 char *server = NULL, *share = NULL, *user = NULL, *password = NULL;
1569 char *targetpath = NULL;
1570 struct cli_state *targetcli = NULL;
1571 TALLOC_CTX *frame = talloc_stackframe();
1573 if (!context || !context->internal ||
1574 !context->internal->_initialized) {
1581 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1590 return (context->closedir)(context, file);
1593 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1594 if (smbc_parse_path(frame,
1609 /*d_printf(">>>close: resolving %s\n", path);*/
1610 if (!cli_resolve_path(frame, "", file->srv->cli, path,
1611 &targetcli, &targetpath)) {
1612 d_printf("Could not resolve %s\n", path);
1616 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1618 if (!cli_close(targetcli, file->cli_fd)) {
1620 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1622 /* Deallocate slot and remove the server
1623 * from the server cache if unused */
1624 errno = smbc_errno(context, targetcli);
1626 DLIST_REMOVE(context->internal->_files, file);
1627 SAFE_FREE(file->fname);
1629 (context->callbacks.remove_unused_server_fn)(context, srv);
1635 DLIST_REMOVE(context->internal->_files, file);
1636 SAFE_FREE(file->fname);
1644 * Get info from an SMB server on a file. Use a qpathinfo call first
1645 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1648 smbc_getatr(SMBCCTX * context,
1653 struct timespec *create_time_ts,
1654 struct timespec *access_time_ts,
1655 struct timespec *write_time_ts,
1656 struct timespec *change_time_ts,
1659 char *fixedpath = NULL;
1660 char *targetpath = NULL;
1661 struct cli_state *targetcli = NULL;
1663 TALLOC_CTX *frame = talloc_stackframe();
1665 if (!context || !context->internal ||
1666 !context->internal->_initialized) {
1672 /* path fixup for . and .. */
1673 if (strequal(path, ".") || strequal(path, "..")) {
1674 fixedpath = talloc_strdup(frame, "\\");
1681 fixedpath = talloc_strdup(frame, path);
1687 trim_string(fixedpath, NULL, "\\..");
1688 trim_string(fixedpath, NULL, "\\.");
1690 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1692 if (!cli_resolve_path(frame, "", srv->cli, fixedpath,
1693 &targetcli, &targetpath)) {
1694 d_printf("Couldn't resolve %s\n", path);
1699 if (!srv->no_pathinfo2 &&
1700 cli_qpathinfo2(targetcli, targetpath,
1710 /* if this is NT then don't bother with the getatr */
1711 if (targetcli->capabilities & CAP_NT_SMBS) {
1717 if (cli_getatr(targetcli, targetpath, mode, size, &write_time)) {
1719 struct timespec w_time_ts;
1721 w_time_ts = convert_time_t_to_timespec(write_time);
1723 if (write_time_ts != NULL) {
1724 *write_time_ts = w_time_ts;
1727 if (create_time_ts != NULL) {
1728 *create_time_ts = w_time_ts;
1731 if (access_time_ts != NULL) {
1732 *access_time_ts = w_time_ts;
1735 if (change_time_ts != NULL) {
1736 *change_time_ts = w_time_ts;
1739 srv->no_pathinfo2 = True;
1751 * Set file info on an SMB server. Use setpathinfo call first. If that
1752 * fails, use setattrE..
1754 * Access and modification time parameters are always used and must be
1755 * provided. Create time, if zero, will be determined from the actual create
1756 * time of the file. If non-zero, the create time will be set as well.
1758 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1761 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1770 TALLOC_CTX *frame = talloc_stackframe();
1773 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1774 * modern function for "new code" to be using, and it works given a
1775 * filename rather than requiring that the file be opened to have its
1776 * attributes manipulated.
1778 if (srv->no_pathinfo ||
1779 ! cli_setpathinfo(srv->cli, path,
1787 * setpathinfo is not supported; go to plan B.
1789 * cli_setatr() does not work on win98, and it also doesn't
1790 * support setting the access time (only the modification
1791 * time), so in all cases, we open the specified file and use
1792 * cli_setattrE() which should work on all OS versions, and
1793 * supports both times.
1796 /* Don't try {q,set}pathinfo() again, with this server */
1797 srv->no_pathinfo = True;
1800 if ((fd = cli_open(srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1802 errno = smbc_errno(context, srv->cli);
1807 /* Set the new attributes */
1808 ret = cli_setattrE(srv->cli, fd,
1813 /* Close the file */
1814 cli_close(srv->cli, fd);
1817 * Unfortunately, setattrE() doesn't have a provision for
1818 * setting the access mode (attributes). We'll have to try
1819 * cli_setatr() for that, and with only this parameter, it
1820 * seems to work on win98.
1822 if (ret && mode != (uint16) -1) {
1823 ret = cli_setatr(srv->cli, path, mode, 0);
1827 errno = smbc_errno(context, srv->cli);
1838 * Routine to unlink() a file
1842 smbc_unlink_ctx(SMBCCTX *context,
1845 char *server = NULL, *share = NULL, *user = NULL, *password = NULL, *workgroup = NULL;
1847 char *targetpath = NULL;
1848 struct cli_state *targetcli = NULL;
1849 SMBCSRV *srv = NULL;
1850 TALLOC_CTX *frame = talloc_stackframe();
1852 if (!context || !context->internal ||
1853 !context->internal->_initialized) {
1854 errno = EINVAL; /* Best I can think of ... */
1867 if (smbc_parse_path(frame,
1882 if (!user || user[0] == (char)0) {
1883 user = talloc_strdup(frame, context->user);
1891 srv = smbc_server(frame, context, True,
1892 server, share, &workgroup, &user, &password);
1896 return -1; /* smbc_server sets errno */
1900 /*d_printf(">>>unlink: resolving %s\n", path);*/
1901 if (!cli_resolve_path(frame, "", srv->cli, path,
1902 &targetcli, &targetpath)) {
1903 d_printf("Could not resolve %s\n", path);
1907 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1909 if (!cli_unlink(targetcli, targetpath)) {
1911 errno = smbc_errno(context, targetcli);
1913 if (errno == EACCES) { /* Check if the file is a directory */
1918 struct timespec write_time_ts;
1919 struct timespec access_time_ts;
1920 struct timespec change_time_ts;
1923 if (!smbc_getatr(context, srv, path, &mode, &size,
1930 /* Hmmm, bad error ... What? */
1932 errno = smbc_errno(context, targetcli);
1939 if (IS_DOS_DIR(mode))
1942 errno = saverr; /* Restore this */
1953 return 0; /* Success ... */
1958 * Routine to rename() a file
1962 smbc_rename_ctx(SMBCCTX *ocontext,
1967 char *server1 = NULL;
1968 char *share1 = NULL;
1969 char *server2 = NULL;
1970 char *share2 = NULL;
1973 char *password1 = NULL;
1974 char *password2 = NULL;
1975 char *workgroup = NULL;
1978 char *targetpath1 = NULL;
1979 char *targetpath2 = NULL;
1980 struct cli_state *targetcli1 = NULL;
1981 struct cli_state *targetcli2 = NULL;
1982 SMBCSRV *srv = NULL;
1983 TALLOC_CTX *frame = talloc_stackframe();
1985 if (!ocontext || !ncontext ||
1986 !ocontext->internal || !ncontext->internal ||
1987 !ocontext->internal->_initialized ||
1988 !ncontext->internal->_initialized) {
1989 errno = EINVAL; /* Best I can think of ... */
1994 if (!oname || !nname) {
2000 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
2002 if (smbc_parse_path(frame,
2017 if (!user1 || user1[0] == (char)0) {
2018 user1 = talloc_strdup(frame, ocontext->user);
2026 if (smbc_parse_path(frame,
2041 if (!user2 || user2[0] == (char)0) {
2042 user2 = talloc_strdup(frame, ncontext->user);
2050 if (strcmp(server1, server2) || strcmp(share1, share2) ||
2051 strcmp(user1, user2)) {
2052 /* Can't rename across file systems, or users?? */
2058 srv = smbc_server(frame, ocontext, True,
2059 server1, share1, &workgroup, &user1, &password1);
2066 /*d_printf(">>>rename: resolving %s\n", path1);*/
2067 if (!cli_resolve_path(frame, "", srv->cli, path1,
2068 &targetcli1, &targetpath1)) {
2069 d_printf("Could not resolve %s\n", path1);
2073 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
2074 /*d_printf(">>>rename: resolving %s\n", path2);*/
2075 if (!cli_resolve_path(frame, "", srv->cli, path2,
2076 &targetcli2, &targetpath2)) {
2077 d_printf("Could not resolve %s\n", path2);
2081 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
2083 if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
2084 strcmp(targetcli1->share, targetcli2->share))
2086 /* can't rename across file systems */
2092 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
2093 int eno = smbc_errno(ocontext, targetcli1);
2095 if (eno != EEXIST ||
2096 !cli_unlink(targetcli1, targetpath2) ||
2097 !cli_rename(targetcli1, targetpath1, targetpath2)) {
2107 return 0; /* Success */
2111 * A routine to lseek() a file
2115 smbc_lseek_ctx(SMBCCTX *context,
2121 char *server = NULL, *share = NULL, *user = NULL, *password = NULL;
2123 char *targetpath = NULL;
2124 struct cli_state *targetcli = NULL;
2125 TALLOC_CTX *frame = talloc_stackframe();
2127 if (!context || !context->internal ||
2128 !context->internal->_initialized) {
2134 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2146 return -1; /* Can't lseek a dir ... */
2152 file->offset = offset;
2156 file->offset += offset;
2160 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
2161 if (smbc_parse_path(frame,
2176 /*d_printf(">>>lseek: resolving %s\n", path);*/
2177 if (!cli_resolve_path(frame, "", file->srv->cli, path,
2178 &targetcli, &targetpath)) {
2179 d_printf("Could not resolve %s\n", path);
2183 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
2185 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
2186 &size, NULL, NULL, NULL, NULL, NULL))
2188 SMB_OFF_T b_size = size;
2189 if (!cli_getattrE(targetcli, file->cli_fd,
2190 NULL, &b_size, NULL, NULL, NULL))
2198 file->offset = size + offset;
2208 return file->offset;
2213 * Generate an inode number from file name for those things that need it
2217 smbc_inode(SMBCCTX *context,
2220 if (!context || !context->internal ||
2221 !context->internal->_initialized) {
2228 if (!*name) return 2; /* FIXME, why 2 ??? */
2229 return (ino_t)str_checksum(name);
2234 * Routine to put basic stat info into a stat structure ... Used by stat and
2239 smbc_setup_stat(SMBCCTX *context,
2245 TALLOC_CTX *frame = talloc_stackframe();
2249 if (IS_DOS_DIR(mode)) {
2250 st->st_mode = SMBC_DIR_MODE;
2252 st->st_mode = SMBC_FILE_MODE;
2255 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
2256 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
2257 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
2258 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
2261 #ifdef HAVE_STAT_ST_BLKSIZE
2262 st->st_blksize = 512;
2264 #ifdef HAVE_STAT_ST_BLOCKS
2265 st->st_blocks = (size+511)/512;
2267 #ifdef HAVE_STRUCT_STAT_ST_RDEV
2270 st->st_uid = getuid();
2271 st->st_gid = getgid();
2273 if (IS_DOS_DIR(mode)) {
2279 if (st->st_ino == 0) {
2280 st->st_ino = smbc_inode(context, fname);
2284 return True; /* FIXME: Is this needed ? */
2289 * Routine to stat a file given a name
2293 smbc_stat_ctx(SMBCCTX *context,
2297 SMBCSRV *srv = NULL;
2298 char *server = NULL;
2301 char *password = NULL;
2302 char *workgroup = NULL;
2304 struct timespec write_time_ts;
2305 struct timespec access_time_ts;
2306 struct timespec change_time_ts;
2310 TALLOC_CTX *frame = talloc_stackframe();
2312 if (!context || !context->internal ||
2313 !context->internal->_initialized) {
2315 errno = EINVAL; /* Best I can think of ... */
2326 DEBUG(4, ("smbc_stat(%s)\n", fname));
2328 if (smbc_parse_path(frame,
2343 if (!user || user[0] == (char)0) {
2344 user = talloc_strdup(frame,context->user);
2352 srv = smbc_server(frame, context, True,
2353 server, share, &workgroup, &user, &password);
2357 return -1; /* errno set by smbc_server */
2360 if (!smbc_getatr(context, srv, path, &mode, &size,
2366 errno = smbc_errno(context, srv->cli);
2373 smbc_setup_stat(context, st, (char *) fname, size, mode);
2375 set_atimespec(st, access_time_ts);
2376 set_ctimespec(st, change_time_ts);
2377 set_mtimespec(st, write_time_ts);
2378 st->st_dev = srv->dev;
2386 * Routine to stat a file given an fd
2390 smbc_fstat_ctx(SMBCCTX *context,
2394 struct timespec change_time_ts;
2395 struct timespec access_time_ts;
2396 struct timespec write_time_ts;
2399 char *server = NULL;
2402 char *password = NULL;
2404 char *targetpath = NULL;
2405 struct cli_state *targetcli = NULL;
2407 TALLOC_CTX *frame = talloc_stackframe();
2409 if (!context || !context->internal ||
2410 !context->internal->_initialized) {
2416 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2424 return (context->fstatdir)(context, file, st);
2427 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2428 if (smbc_parse_path(frame,
2443 /*d_printf(">>>fstat: resolving %s\n", path);*/
2444 if (!cli_resolve_path(frame, "", file->srv->cli, path,
2445 &targetcli, &targetpath)) {
2446 d_printf("Could not resolve %s\n", path);
2450 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2452 if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2459 time_t change_time, access_time, write_time;
2461 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2462 &change_time, &access_time, &write_time)) {
2469 change_time_ts = convert_time_t_to_timespec(change_time);
2470 access_time_ts = convert_time_t_to_timespec(access_time);
2471 write_time_ts = convert_time_t_to_timespec(write_time);
2476 smbc_setup_stat(context, st, file->fname, size, mode);
2478 set_atimespec(st, access_time_ts);
2479 set_ctimespec(st, change_time_ts);
2480 set_mtimespec(st, write_time_ts);
2481 st->st_dev = file->srv->dev;
2489 * Routine to open a directory
2490 * We accept the URL syntax explained in smbc_parse_path(), above.
2494 smbc_remove_dir(SMBCFILE *dir)
2496 struct smbc_dir_list *d,*f;
2503 SAFE_FREE(f->dirent);
2508 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2513 add_dirent(SMBCFILE *dir,
2515 const char *comment,
2518 struct smbc_dirent *dirent;
2520 int name_length = (name == NULL ? 0 : strlen(name));
2521 int comment_len = (comment == NULL ? 0 : strlen(comment));
2524 * Allocate space for the dirent, which must be increased by the
2525 * size of the name and the comment and 1 each for the null terminator.
2528 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2530 dirent = (struct smbc_dirent *)SMB_MALLOC(size);
2534 dir->dir_error = ENOMEM;
2539 ZERO_STRUCTP(dirent);
2541 if (dir->dir_list == NULL) {
2543 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2544 if (!dir->dir_list) {
2547 dir->dir_error = ENOMEM;
2551 ZERO_STRUCTP(dir->dir_list);
2553 dir->dir_end = dir->dir_next = dir->dir_list;
2557 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2559 if (!dir->dir_end->next) {
2562 dir->dir_error = ENOMEM;
2566 ZERO_STRUCTP(dir->dir_end->next);
2568 dir->dir_end = dir->dir_end->next;
2571 dir->dir_end->next = NULL;
2572 dir->dir_end->dirent = dirent;
2574 dirent->smbc_type = type;
2575 dirent->namelen = name_length;
2576 dirent->commentlen = comment_len;
2577 dirent->dirlen = size;
2580 * dirent->namelen + 1 includes the null (no null termination needed)
2581 * Ditto for dirent->commentlen.
2582 * The space for the two null bytes was allocated.
2584 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2585 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2586 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2593 list_unique_wg_fn(const char *name,
2595 const char *comment,
2598 SMBCFILE *dir = (SMBCFILE *)state;
2599 struct smbc_dir_list *dir_list;
2600 struct smbc_dirent *dirent;
2604 dirent_type = dir->dir_type;
2606 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2608 /* An error occurred, what do we do? */
2609 /* FIXME: Add some code here */
2612 /* Point to the one just added */
2613 dirent = dir->dir_end->dirent;
2615 /* See if this was a duplicate */
2616 for (dir_list = dir->dir_list;
2617 dir_list != dir->dir_end;
2618 dir_list = dir_list->next) {
2620 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2621 /* Duplicate. End end of list need to be removed. */
2625 if (do_remove && dir_list->next == dir->dir_end) {
2626 /* Found the end of the list. Remove it. */
2627 dir->dir_end = dir_list;
2628 free(dir_list->next);
2630 dir_list->next = NULL;
2637 list_fn(const char *name,
2639 const char *comment,
2642 SMBCFILE *dir = (SMBCFILE *)state;
2646 * We need to process the type a little ...
2648 * Disk share = 0x00000000
2649 * Print share = 0x00000001
2650 * Comms share = 0x00000002 (obsolete?)
2651 * IPC$ share = 0x00000003
2653 * administrative shares:
2654 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2657 if (dir->dir_type == SMBC_FILE_SHARE) {
2659 case 0 | 0x80000000:
2661 dirent_type = SMBC_FILE_SHARE;
2665 dirent_type = SMBC_PRINTER_SHARE;
2669 dirent_type = SMBC_COMMS_SHARE;
2672 case 3 | 0x80000000:
2674 dirent_type = SMBC_IPC_SHARE;
2678 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2683 dirent_type = dir->dir_type;
2686 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2688 /* An error occurred, what do we do? */
2689 /* FIXME: Add some code here */
2695 dir_list_fn(const char *mnt,
2701 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2702 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2704 /* Handle an error ... */
2706 /* FIXME: Add some code ... */
2713 net_share_enum_rpc(struct cli_state *cli,
2714 void (*fn)(const char *name,
2716 const char *comment,
2723 uint32 info_level = 1;
2724 uint32 preferred_len = 0xffffffff;
2726 SRV_SHARE_INFO_CTR ctr;
2728 fstring comment = "";
2729 struct rpc_pipe_client *pipe_hnd;
2732 /* Open the server service pipe */
2733 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2735 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2739 /* Issue the NetShareEnum RPC call and retrieve the response */
2740 init_enum_hnd(&enum_hnd, 0);
2741 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2748 /* Was it successful? */
2749 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2750 /* Nope. Go clean up. */
2754 /* For each returned entry... */
2755 for (i = 0; i < ctr.num_entries; i++) {
2757 /* pull out the share name */
2758 rpcstr_pull_unistr2_fstring(
2759 name, &ctr.share.info1[i].info_1_str.uni_netname);
2761 /* pull out the share's comment */
2762 rpcstr_pull_unistr2_fstring(
2763 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2765 /* Get the type value */
2766 type = ctr.share.info1[i].info_1.type;
2768 /* Add this share to the list */
2769 (*fn)(name, type, comment, state);
2773 /* Close the server service pipe */
2774 cli_rpc_pipe_close(pipe_hnd);
2776 /* Tell 'em if it worked */
2777 return W_ERROR_IS_OK(result) ? 0 : -1;
2783 smbc_opendir_ctx(SMBCCTX *context,
2787 char *server = NULL, *share = NULL, *user = NULL, *password = NULL, *options = NULL;
2788 char *workgroup = NULL;
2792 SMBCSRV *srv = NULL;
2793 SMBCFILE *dir = NULL;
2794 struct _smbc_callbacks *cb = NULL;
2795 struct sockaddr_storage rem_ss;
2796 TALLOC_CTX *frame = talloc_stackframe();
2798 if (!context || !context->internal ||
2799 !context->internal->_initialized) {
2800 DEBUG(4, ("no valid context\n"));
2801 errno = EINVAL + 8192;
2808 DEBUG(4, ("no valid fname\n"));
2809 errno = EINVAL + 8193;
2814 if (smbc_parse_path(frame,
2824 DEBUG(4, ("no valid path\n"));
2825 errno = EINVAL + 8194;
2830 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2831 "path='%s' options='%s'\n",
2832 fname, server, share, path, options));
2834 /* Ensure the options are valid */
2835 if (smbc_check_options(server, share, path, options)) {
2836 DEBUG(4, ("unacceptable options (%s)\n", options));
2837 errno = EINVAL + 8195;
2842 if (!user || user[0] == (char)0) {
2843 user = talloc_strdup(frame, context->user);
2851 dir = SMB_MALLOC_P(SMBCFILE);
2862 dir->fname = SMB_STRDUP(fname);
2866 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2868 if (server[0] == (char)0) {
2873 struct ip_service *ip_list;
2874 struct ip_service server_addr;
2875 struct user_auth_info u_info;
2877 if (share[0] != (char)0 || path[0] != (char)0) {
2879 errno = EINVAL + 8196;
2881 SAFE_FREE(dir->fname);
2888 /* Determine how many local master browsers to query */
2889 max_lmb_count = (context->options.browse_max_lmb_count == 0
2891 : context->options.browse_max_lmb_count);
2893 memset(&u_info, '\0', sizeof(u_info));
2894 u_info.username = talloc_strdup(frame,user);
2895 u_info.password = talloc_strdup(frame,password);
2896 if (!u_info.username || !u_info.password) {
2898 SAFE_FREE(dir->fname);
2906 * We have server and share and path empty but options
2907 * requesting that we scan all master browsers for their list
2908 * of workgroups/domains. This implies that we must first try
2909 * broadcast queries to find all master browsers, and if that
2910 * doesn't work, then try our other methods which return only
2911 * a single master browser.
2915 if (!NT_STATUS_IS_OK(name_resolve_bcast(MSBROWSE, 1, &ip_list,
2921 if (!find_master_ip(workgroup, &server_addr.ss)) {
2924 SAFE_FREE(dir->fname);
2932 ip_list = (struct ip_service *)memdup(
2933 &server_addr, sizeof(server_addr));
2934 if (ip_list == NULL) {
2942 for (i = 0; i < count && i < max_lmb_count; i++) {
2943 char addr[INET6_ADDRSTRLEN];
2944 char *wg_ptr = NULL;
2945 struct cli_state *cli = NULL;
2947 print_sockaddr(addr, sizeof(addr), &ip_list[i].ss);
2948 DEBUG(99, ("Found master browser %d of %d: %s\n",
2949 i+1, MAX(count, max_lmb_count),
2952 cli = get_ipc_connect_master_ip(talloc_tos(),
2956 /* cli == NULL is the master browser refused to talk or
2957 could not be found */
2962 workgroup = talloc_strdup(frame, wg_ptr);
2963 server = talloc_strdup(frame, cli->desthost);
2967 if (!workgroup || !server) {
2973 DEBUG(4, ("using workgroup %s %s\n",
2974 workgroup, server));
2977 * For each returned master browser IP address, get a
2978 * connection to IPC$ on the server if we do not
2979 * already have one, and determine the
2980 * workgroups/domains that it knows about.
2983 srv = smbc_server(frame, context, True, server, "IPC$",
2984 &workgroup, &user, &password);
2990 dir->dir_type = SMBC_WORKGROUP;
2992 /* Now, list the stuff ... */
2994 if (!cli_NetServerEnum(srv->cli,
2996 SV_TYPE_DOMAIN_ENUM,
3006 * Server not an empty string ... Check the rest and see what
3009 if (*share == '\0') {
3010 if (*path != '\0') {
3012 /* Should not have empty share with path */
3013 errno = EINVAL + 8197;
3015 SAFE_FREE(dir->fname);
3024 * We don't know if <server> is really a server name
3025 * or is a workgroup/domain name. If we already have
3026 * a server structure for it, we'll use it.
3027 * Otherwise, check to see if <server><1D>,
3028 * <server><1B>, or <server><20> translates. We check
3029 * to see if <server> is an IP address first.
3033 * See if we have an existing server. Do not
3034 * establish a connection if one does not already
3037 srv = smbc_server(frame, context, False, server, "IPC$",
3038 &workgroup, &user, &password);
3041 * If no existing server and not an IP addr, look for
3045 !is_ipaddress(server) &&
3046 (resolve_name(server, &rem_ss, 0x1d) || /* LMB */
3047 resolve_name(server, &rem_ss, 0x1b) )) { /* DMB */
3051 dir->dir_type = SMBC_SERVER;
3054 * Get the backup list ...
3056 if (!name_status_find(server, 0, 0,
3057 &rem_ss, buserver)) {
3059 DEBUG(0, ("Could not get name of "
3060 "local/domain master browser "
3061 "for server %s\n", server));
3063 SAFE_FREE(dir->fname);
3073 * Get a connection to IPC$ on the server if
3074 * we do not already have one
3076 srv = smbc_server(frame, context, True,
3078 &workgroup, &user, &password);
3080 DEBUG(0, ("got no contact to IPC$\n"));
3082 SAFE_FREE(dir->fname);
3092 /* Now, list the servers ... */
3093 if (!cli_NetServerEnum(srv->cli, server,
3094 0x0000FFFE, list_fn,
3098 SAFE_FREE(dir->fname);
3105 (resolve_name(server, &rem_ss, 0x20))) {
3107 /* If we hadn't found the server, get one now */
3109 srv = smbc_server(frame, context, True,
3117 SAFE_FREE(dir->fname);
3125 dir->dir_type = SMBC_FILE_SHARE;
3128 /* List the shares ... */
3130 if (net_share_enum_rpc(
3133 (void *) dir) < 0 &&
3139 errno = cli_errno(srv->cli);
3141 SAFE_FREE(dir->fname);
3149 /* Neither the workgroup nor server exists */
3150 errno = ECONNREFUSED;
3152 SAFE_FREE(dir->fname);
3162 * The server and share are specified ... work from
3166 struct cli_state *targetcli;
3168 /* We connect to the server and list the directory */
3169 dir->dir_type = SMBC_FILE_SHARE;
3171 srv = smbc_server(frame, context, True, server, share,
3172 &workgroup, &user, &password);
3176 SAFE_FREE(dir->fname);
3185 /* Now, list the files ... */
3187 p = path + strlen(path);
3188 path = talloc_asprintf_append(path, "\\*");
3191 SAFE_FREE(dir->fname);
3198 if (!cli_resolve_path(frame, "", srv->cli, path,
3199 &targetcli, &targetpath)) {
3200 d_printf("Could not resolve %s\n", path);
3202 SAFE_FREE(dir->fname);
3209 if (cli_list(targetcli, targetpath,
3210 aDIR | aSYSTEM | aHIDDEN,
3211 dir_list_fn, (void *)dir) < 0) {
3214 SAFE_FREE(dir->fname);
3217 saved_errno = smbc_errno(context, targetcli);
3219 if (saved_errno == EINVAL) {
3221 * See if they asked to opendir something
3222 * other than a directory. If so, the
3223 * converted error value we got would have
3224 * been EINVAL rather than ENOTDIR.
3226 *p = '\0'; /* restore original path */
3228 if (smbc_getatr(context, srv, path,
3230 NULL, NULL, NULL, NULL,
3232 ! IS_DOS_DIR(mode)) {
3234 /* It is. Correct the error value */
3235 saved_errno = ENOTDIR;
3240 * If there was an error and the server is no
3243 cb = &context->callbacks;
3244 if (cli_is_error(targetcli) &&
3245 (cb->check_server_fn)(context, srv)) {
3247 /* ... then remove it. */
3248 if ((cb->remove_unused_server_fn)(context,
3251 * We could not remove the
3252 * server completely, remove
3253 * it from the cache so we
3254 * will not get it again. It
3255 * will be removed when the
3256 * last file/dir is closed.
3258 (cb->remove_cached_srv_fn)(context,
3263 errno = saved_errno;
3271 DLIST_ADD(context->internal->_files, dir);
3278 * Routine to close a directory
3282 smbc_closedir_ctx(SMBCCTX *context,
3285 TALLOC_CTX *frame = talloc_stackframe();
3287 if (!context || !context->internal ||
3288 !context->internal->_initialized) {
3294 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3300 smbc_remove_dir(dir); /* Clean it up */
3302 DLIST_REMOVE(context->internal->_files, dir);
3306 SAFE_FREE(dir->fname);
3307 SAFE_FREE(dir); /* Free the space too */
3316 smbc_readdir_internal(SMBCCTX * context,
3317 struct smbc_dirent *dest,
3318 struct smbc_dirent *src,
3319 int max_namebuf_len)
3321 if (context->options.urlencode_readdir_entries) {
3323 /* url-encode the name. get back remaining buffer space */
3325 smbc_urlencode(dest->name, src->name, max_namebuf_len);
3327 /* We now know the name length */
3328 dest->namelen = strlen(dest->name);
3330 /* Save the pointer to the beginning of the comment */
3331 dest->comment = dest->name + dest->namelen + 1;
3333 /* Copy the comment */
3334 strncpy(dest->comment, src->comment, max_namebuf_len - 1);
3335 dest->comment[max_namebuf_len - 1] = '\0';
3337 /* Save other fields */
3338 dest->smbc_type = src->smbc_type;
3339 dest->commentlen = strlen(dest->comment);
3340 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
3344 /* No encoding. Just copy the entry as is. */
3345 memcpy(dest, src, src->dirlen);
3346 dest->comment = (char *)(&dest->name + src->namelen + 1);
3352 * Routine to get a directory entry
3355 struct smbc_dirent *
3356 smbc_readdir_ctx(SMBCCTX *context,
3360 struct smbc_dirent *dirp, *dirent;
3361 TALLOC_CTX *frame = talloc_stackframe();
3363 /* Check that all is ok first ... */
3365 if (!context || !context->internal ||
3366 !context->internal->_initialized) {
3369 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
3375 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3378 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
3384 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3387 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
3393 if (!dir->dir_next) {
3398 dirent = dir->dir_next->dirent;
3407 dirp = (struct smbc_dirent *)context->internal->_dirent;
3408 maxlen = (sizeof(context->internal->_dirent) -
3409 sizeof(struct smbc_dirent));
3411 smbc_readdir_internal(context, dirp, dirent, maxlen);
3413 dir->dir_next = dir->dir_next->next;
3420 * Routine to get directory entries
3424 smbc_getdents_ctx(SMBCCTX *context,
3426 struct smbc_dirent *dirp,
3432 char *ndir = (char *)dirp;
3433 struct smbc_dir_list *dirlist;
3434 TALLOC_CTX *frame = talloc_stackframe();
3436 /* Check that all is ok first ... */
3438 if (!context || !context->internal ||
3439 !context->internal->_initialized) {
3447 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3455 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3464 * Now, retrieve the number of entries that will fit in what was passed
3465 * We have to figure out if the info is in the list, or we need to
3466 * send a request to the server to get the info.
3469 while ((dirlist = dir->dir_next)) {
3470 struct smbc_dirent *dirent;
3472 if (!dirlist->dirent) {
3474 errno = ENOENT; /* Bad error */
3480 /* Do urlencoding of next entry, if so selected */
3481 dirent = (struct smbc_dirent *)context->internal->_dirent;
3482 maxlen = (sizeof(context->internal->_dirent) -
3483 sizeof(struct smbc_dirent));
3484 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3486 reqd = dirent->dirlen;
3490 if (rem < count) { /* We managed to copy something */
3497 else { /* Nothing copied ... */
3499 errno = EINVAL; /* Not enough space ... */
3507 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3509 ((struct smbc_dirent *)ndir)->comment =
3510 (char *)(&((struct smbc_dirent *)ndir)->name +
3518 dir->dir_next = dirlist = dirlist -> next;
3531 * Routine to create a directory ...
3535 smbc_mkdir_ctx(SMBCCTX *context,
3539 SMBCSRV *srv = NULL;
3540 char *server = NULL;
3543 char *password = NULL;
3544 char *workgroup = NULL;
3546 char *targetpath = NULL;
3547 struct cli_state *targetcli = NULL;
3548 TALLOC_CTX *frame = talloc_stackframe();
3550 if (!context || !context->internal ||
3551 !context->internal->_initialized) {
3563 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3565 if (smbc_parse_path(frame,