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,
600 struct nmb_name called, calling;
601 const char *server_n = server;
604 int tried_reverse = 0;
607 const char *username_used;
612 if (server[0] == 0) {
617 /* Look for a cached connection */
618 srv = find_server(context, server, share,
619 workgroup, username, password);
622 * If we found a connection and we're only allowed one share per
625 if (srv && *share != '\0' && context->options.one_share_per_server) {
628 * ... then if there's no current connection to the share,
629 * connect to it. find_server(), or rather the function
630 * pointed to by context->callbacks.get_cached_srv_fn which
631 * was called by find_server(), will have issued a tree
632 * disconnect if the requested share is not the same as the
633 * one that was already connected.
635 if (srv->cli.cnum == (uint16) -1) {
636 /* Ensure we have accurate auth info */
637 context->callbacks.auth_fn(server, share,
638 workgroup, sizeof(fstring),
639 username, sizeof(fstring),
640 password, sizeof(fstring));
642 if (! cli_send_tconX(&srv->cli, share, "?????",
643 password, strlen(password)+1)) {
645 errno = smbc_errno(context, &srv->cli);
646 cli_shutdown(&srv->cli);
647 context->callbacks.remove_cached_srv_fn(context, srv);
651 /* Regenerate the dev value since it's based on both server and share */
653 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
658 /* If we have a connection... */
661 /* ... then we're done here. Give 'em what they came for. */
665 make_nmb_name(&calling, context->netbios_name, 0x0);
666 make_nmb_name(&called , server, 0x20);
668 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
670 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
673 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
677 /* have to open a new connection */
678 if (!cli_initialise(&c)) {
683 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
684 c.use_kerberos = True;
686 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
687 c.fallback_after_kerberos = True;
690 c.timeout = context->timeout;
693 * Force use of port 139 for first try if share is $IPC, empty, or
694 * null, so browse lists can work
696 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
697 port_try_first = 139;
700 port_try_first = 445;
704 c.port = port_try_first;
706 if (!cli_connect(&c, server_n, &ip)) {
708 /* First connection attempt failed. Try alternate port. */
709 c.port = port_try_next;
711 if (!cli_connect(&c, server_n, &ip)) {
718 if (!cli_session_request(&c, &calling, &called)) {
720 if (strcmp(called.name, "*SMBSERVER")) {
721 make_nmb_name(&called , "*SMBSERVER", 0x20);
724 else { /* Try one more time, but ensure we don't loop */
726 /* Only try this if server is an IP address ... */
728 if (is_ipaddress(server) && !tried_reverse) {
730 struct in_addr rem_ip;
732 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
733 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
738 tried_reverse++; /* Yuck */
740 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
741 make_nmb_name(&called, remote_name, 0x20);
752 DEBUG(4,(" session request ok\n"));
754 if (!cli_negprot(&c)) {
760 username_used = username;
762 if (!cli_session_setup(&c, username_used,
763 password, strlen(password),
764 password, strlen(password),
767 /* Failed. Try an anonymous login, if allowed by flags. */
770 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
771 !cli_session_setup(&c, username_used,
782 DEBUG(4,(" session setup ok\n"));
784 if (!cli_send_tconX(&c, share, "?????",
785 password, strlen(password)+1)) {
786 errno = smbc_errno(context, &c);
791 DEBUG(4,(" tconx ok\n"));
794 * Ok, we have got a nice connection
795 * Let's allocate a server structure.
798 srv = SMB_MALLOC_P(SMBCSRV);
806 srv->cli.allocated = False;
807 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
808 srv->no_pathinfo = False;
809 srv->no_pathinfo2 = False;
810 srv->no_nt_session = False;
812 /* now add it to the cache (internal or external) */
813 /* Let the cache function set errno if it wants to */
815 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
816 int saved_errno = errno;
817 DEBUG(3, (" Failed to add server to cache\n"));
825 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
826 server, share, srv));
828 DLIST_ADD(context->internal->_servers, srv);
833 if (!srv) return NULL;
840 * Connect to a server for getting/setting attributes, possibly on an existing
841 * connection. This works similarly to smbc_server().
844 smbc_attr_server(SMBCCTX *context,
853 struct cli_state *ipc_cli;
854 struct rpc_pipe_client *pipe_hnd;
856 SMBCSRV *ipc_srv=NULL;
859 * See if we've already created this special connection. Reference
860 * our "special" share name '*IPC$', which is an impossible real share
861 * name due to the leading asterisk.
863 ipc_srv = find_server(context, server, "*IPC$",
864 workgroup, username, password);
867 /* We didn't find a cached connection. Get the password */
868 if (*password == '\0') {
869 /* ... then retrieve it now. */
870 context->callbacks.auth_fn(server, share,
871 workgroup, sizeof(fstring),
872 username, sizeof(fstring),
873 password, sizeof(fstring));
877 nt_status = cli_full_connection(&ipc_cli,
878 global_myname(), server,
879 &ip, 0, "IPC$", "?????",
883 if (! NT_STATUS_IS_OK(nt_status)) {
884 DEBUG(1,("cli_full_connection failed! (%s)\n",
885 nt_errstr(nt_status)));
890 ipc_srv = SMB_MALLOC_P(SMBCSRV);
893 cli_shutdown(ipc_cli);
897 ZERO_STRUCTP(ipc_srv);
898 ipc_srv->cli = *ipc_cli;
899 ipc_srv->cli.allocated = False;
904 pipe_hnd = cli_rpc_pipe_open_noauth(&ipc_srv->cli,
908 DEBUG(1, ("cli_nt_session_open fail!\n"));
910 cli_shutdown(&ipc_srv->cli);
916 * Some systems don't support
917 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
918 * so we might as well do it too.
921 nt_status = rpccli_lsa_open_policy(
923 ipc_srv->cli.mem_ctx,
925 GENERIC_EXECUTE_ACCESS,
928 if (!NT_STATUS_IS_OK(nt_status)) {
929 errno = smbc_errno(context, &ipc_srv->cli);
930 cli_shutdown(&ipc_srv->cli);
935 /* now add it to the cache (internal or external) */
937 errno = 0; /* let cache function set errno if it likes */
938 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
943 DEBUG(3, (" Failed to add server to cache\n"));
947 cli_shutdown(&ipc_srv->cli);
952 DLIST_ADD(context->internal->_servers, ipc_srv);
959 * Routine to open() a file ...
963 smbc_open_ctx(SMBCCTX *context,
968 fstring server, share, user, password, workgroup;
971 struct cli_state *targetcli;
973 SMBCFILE *file = NULL;
976 if (!context || !context->internal ||
977 !context->internal->_initialized) {
979 errno = EINVAL; /* Best I can think of ... */
991 if (smbc_parse_path(context, fname,
992 server, sizeof(server),
993 share, sizeof(share),
996 password, sizeof(password),
1002 if (user[0] == (char)0) fstrcpy(user, context->user);
1004 fstrcpy(workgroup, context->workgroup);
1006 srv = smbc_server(context, server, share, workgroup, user, password);
1010 if (errno == EPERM) errno = EACCES;
1011 return NULL; /* smbc_server sets errno */
1015 /* Hmmm, the test for a directory is suspect here ... FIXME */
1017 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1024 file = SMB_MALLOC_P(SMBCFILE);
1035 /*d_printf(">>>open: resolving %s\n", path);*/
1036 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1038 d_printf("Could not resolve %s\n", path);
1041 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1043 if ( targetcli->dfsroot )
1046 pstrcpy(temppath, targetpath);
1047 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1050 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1052 /* Handle the error ... */
1055 errno = smbc_errno(context, targetcli);
1060 /* Fill in file struct */
1063 file->fname = SMB_STRDUP(fname);
1068 DLIST_ADD(context->internal->_files, file);
1071 * If the file was opened in O_APPEND mode, all write
1072 * operations should be appended to the file. To do that,
1073 * though, using this protocol, would require a getattrE()
1074 * call for each and every write, to determine where the end
1075 * of the file is. (There does not appear to be an append flag
1076 * in the protocol.) Rather than add all of that overhead of
1077 * retrieving the current end-of-file offset prior to each
1078 * write operation, we'll assume that most append operations
1079 * will continuously write, so we'll just set the offset to
1080 * the end of the file now and hope that's adequate.
1082 * Note to self: If this proves inadequate, and O_APPEND
1083 * should, in some cases, be forced for each write, add a
1084 * field in the context options structure, for
1085 * "strict_append_mode" which would select between the current
1086 * behavior (if FALSE) or issuing a getattrE() prior to each
1087 * write and forcing the write to the end of the file (if
1088 * TRUE). Adding that capability will likely require adding
1089 * an "append" flag into the _SMBCFILE structure to track
1090 * whether a file was opened in O_APPEND mode. -- djl
1092 if (flags & O_APPEND) {
1093 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1094 (void) smbc_close_ctx(context, file);
1104 /* Check if opendir needed ... */
1109 eno = smbc_errno(context, &srv->cli);
1110 file = context->opendir(context, fname);
1111 if (!file) errno = eno;
1116 errno = EINVAL; /* FIXME, correct errno ? */
1122 * Routine to create a file
1125 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1128 smbc_creat_ctx(SMBCCTX *context,
1133 if (!context || !context->internal ||
1134 !context->internal->_initialized) {
1141 return smbc_open_ctx(context, path, creat_bits, mode);
1145 * Routine to read() a file ...
1149 smbc_read_ctx(SMBCCTX *context,
1155 fstring server, share, user, password;
1156 pstring path, targetpath;
1157 struct cli_state *targetcli;
1162 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1163 * appears to pass file->offset (which is type off_t) differently than
1164 * a local variable of type off_t. Using local variable "offset" in
1165 * the call to cli_read() instead of file->offset fixes a problem
1166 * retrieving data at an offset greater than 4GB.
1168 off_t offset = file->offset;
1170 if (!context || !context->internal ||
1171 !context->internal->_initialized) {
1178 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1180 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1187 /* Check that the buffer exists ... */
1196 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1197 if (smbc_parse_path(context, file->fname,
1198 server, sizeof(server),
1199 share, sizeof(share),
1202 password, sizeof(password),
1208 /*d_printf(">>>read: resolving %s\n", path);*/
1209 if (!cli_resolve_path("", &file->srv->cli, path,
1210 &targetcli, targetpath))
1212 d_printf("Could not resolve %s\n", path);
1215 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1217 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1221 errno = smbc_errno(context, targetcli);
1226 file->offset += ret;
1228 DEBUG(4, (" --> %d\n", ret));
1230 return ret; /* Success, ret bytes of data ... */
1235 * Routine to write() a file ...
1239 smbc_write_ctx(SMBCCTX *context,
1246 fstring server, share, user, password;
1247 pstring path, targetpath;
1248 struct cli_state *targetcli;
1250 offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1252 if (!context || !context->internal ||
1253 !context->internal->_initialized) {
1260 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1267 /* Check that the buffer exists ... */
1276 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1277 if (smbc_parse_path(context, file->fname,
1278 server, sizeof(server),
1279 share, sizeof(share),
1282 password, sizeof(password),
1288 /*d_printf(">>>write: resolving %s\n", path);*/
1289 if (!cli_resolve_path("", &file->srv->cli, path,
1290 &targetcli, targetpath))
1292 d_printf("Could not resolve %s\n", path);
1295 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1298 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1302 errno = smbc_errno(context, targetcli);
1307 file->offset += ret;
1309 return ret; /* Success, 0 bytes of data ... */
1313 * Routine to close() a file ...
1317 smbc_close_ctx(SMBCCTX *context,
1321 fstring server, share, user, password;
1322 pstring path, targetpath;
1323 struct cli_state *targetcli;
1325 if (!context || !context->internal ||
1326 !context->internal->_initialized) {
1333 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1343 return context->closedir(context, file);
1347 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1348 if (smbc_parse_path(context, file->fname,
1349 server, sizeof(server),
1350 share, sizeof(share),
1353 password, sizeof(password),
1359 /*d_printf(">>>close: resolving %s\n", path);*/
1360 if (!cli_resolve_path("", &file->srv->cli, path,
1361 &targetcli, targetpath))
1363 d_printf("Could not resolve %s\n", path);
1366 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1368 if (!cli_close(targetcli, file->cli_fd)) {
1370 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1372 /* Deallocate slot and remove the server
1373 * from the server cache if unused */
1374 errno = smbc_errno(context, targetcli);
1376 DLIST_REMOVE(context->internal->_files, file);
1377 SAFE_FREE(file->fname);
1379 context->callbacks.remove_unused_server_fn(context, srv);
1385 DLIST_REMOVE(context->internal->_files, file);
1386 SAFE_FREE(file->fname);
1393 * Get info from an SMB server on a file. Use a qpathinfo call first
1394 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1397 smbc_getatr(SMBCCTX * context,
1409 struct cli_state *targetcli;
1411 if (!context || !context->internal ||
1412 !context->internal->_initialized) {
1419 /* path fixup for . and .. */
1420 if (strequal(path, ".") || strequal(path, ".."))
1421 pstrcpy(fixedpath, "\\");
1424 pstrcpy(fixedpath, path);
1425 trim_string(fixedpath, NULL, "\\..");
1426 trim_string(fixedpath, NULL, "\\.");
1428 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1430 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1432 d_printf("Couldn't resolve %s\n", path);
1436 if ( targetcli->dfsroot )
1439 pstrcpy(temppath, targetpath);
1440 cli_dfs_make_full_path(targetpath, targetcli->desthost,
1441 targetcli->share, temppath);
1444 if (!srv->no_pathinfo2 &&
1445 cli_qpathinfo2(targetcli, targetpath,
1446 c_time, a_time, m_time, NULL, size, mode, ino)) {
1450 /* if this is NT then don't bother with the getatr */
1451 if (targetcli->capabilities & CAP_NT_SMBS) {
1456 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1457 if (m_time != NULL) {
1458 if (a_time != NULL) *a_time = *m_time;
1459 if (c_time != NULL) *c_time = *m_time;
1461 srv->no_pathinfo2 = True;
1471 * Set file info on an SMB server. Use setpathinfo call first. If that
1472 * fails, use setattrE..
1474 * Access and modification time parameters are always used and must be
1475 * provided. Create time, if zero, will be determined from the actual create
1476 * time of the file. If non-zero, the create time will be set as well.
1478 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1481 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1482 time_t c_time, time_t a_time, time_t m_time,
1489 * Get the create time of the file (if not provided); we'll need it in
1492 if (! srv->no_pathinfo && c_time == 0) {
1493 if (! cli_qpathinfo(&srv->cli, path,
1494 &c_time, NULL, NULL, NULL, NULL)) {
1495 /* qpathinfo not available */
1496 srv->no_pathinfo = True;
1499 * We got a creation time. Some OS versions don't
1500 * return a valid create time, though. If we got an
1501 * invalid time, start with the current time instead.
1503 if (c_time == 0 || c_time == (time_t) -1) {
1504 c_time = time(NULL);
1508 * We got a creation time. For sanity sake, since
1509 * there is no POSIX function to set the create time
1510 * of a file, if the existing create time is greater
1511 * than either of access time or modification time,
1512 * set create time to the smallest of those. This
1513 * ensure that the create time of a file is never
1514 * greater than its last access or modification time.
1516 if (c_time > a_time) c_time = a_time;
1517 if (c_time > m_time) c_time = m_time;
1522 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1523 * modern function for "new code" to be using, and it works given a
1524 * filename rather than requiring that the file be opened to have its
1525 * attributes manipulated.
1527 if (srv->no_pathinfo ||
1528 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1531 * setpathinfo is not supported; go to plan B.
1533 * cli_setatr() does not work on win98, and it also doesn't
1534 * support setting the access time (only the modification
1535 * time), so in all cases, we open the specified file and use
1536 * cli_setattrE() which should work on all OS versions, and
1537 * supports both times.
1540 /* Don't try {q,set}pathinfo() again, with this server */
1541 srv->no_pathinfo = True;
1544 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1546 errno = smbc_errno(context, &srv->cli);
1551 * Get the creat time of the file (if it wasn't provided).
1552 * We'll need it in the set call
1555 ret = cli_getattrE(&srv->cli, fd,
1557 &c_time, NULL, NULL);
1562 /* If we got create time, set times */
1564 /* Some OS versions don't support create time */
1565 if (c_time == 0 || c_time == -1) {
1566 c_time = time(NULL);
1570 * For sanity sake, since there is no POSIX function
1571 * to set the create time of a file, if the existing
1572 * create time is greater than either of access time
1573 * or modification time, set create time to the
1574 * smallest of those. This ensure that the create
1575 * time of a file is never greater than its last
1576 * access or modification time.
1578 if (c_time > a_time) c_time = a_time;
1579 if (c_time > m_time) c_time = m_time;
1581 /* Set the new attributes */
1582 ret = cli_setattrE(&srv->cli, fd,
1583 c_time, a_time, m_time);
1584 cli_close(&srv->cli, fd);
1588 * Unfortunately, setattrE() doesn't have a provision for
1589 * setting the access mode (attributes). We'll have to try
1590 * cli_setatr() for that, and with only this parameter, it
1591 * seems to work on win98.
1593 if (ret && mode != (uint16) -1) {
1594 ret = cli_setatr(&srv->cli, path, mode, 0);
1598 errno = smbc_errno(context, &srv->cli);
1607 * Routine to unlink() a file
1611 smbc_unlink_ctx(SMBCCTX *context,
1614 fstring server, share, user, password, workgroup;
1615 pstring path, targetpath;
1616 struct cli_state *targetcli;
1617 SMBCSRV *srv = NULL;
1619 if (!context || !context->internal ||
1620 !context->internal->_initialized) {
1622 errno = EINVAL; /* Best I can think of ... */
1634 if (smbc_parse_path(context, fname,
1635 server, sizeof(server),
1636 share, sizeof(share),
1639 password, sizeof(password),
1645 if (user[0] == (char)0) fstrcpy(user, context->user);
1647 fstrcpy(workgroup, context->workgroup);
1649 srv = smbc_server(context, server, share, workgroup, user, password);
1653 return -1; /* smbc_server sets errno */
1657 /*d_printf(">>>unlink: resolving %s\n", path);*/
1658 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1660 d_printf("Could not resolve %s\n", path);
1663 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1665 if (!cli_unlink(targetcli, targetpath)) {
1667 errno = smbc_errno(context, targetcli);
1669 if (errno == EACCES) { /* Check if the file is a directory */
1674 time_t m_time = 0, a_time = 0, c_time = 0;
1677 if (!smbc_getatr(context, srv, path, &mode, &size,
1678 &c_time, &a_time, &m_time, &ino)) {
1680 /* Hmmm, bad error ... What? */
1682 errno = smbc_errno(context, targetcli);
1688 if (IS_DOS_DIR(mode))
1691 errno = saverr; /* Restore this */
1700 return 0; /* Success ... */
1705 * Routine to rename() a file
1709 smbc_rename_ctx(SMBCCTX *ocontext,
1725 pstring targetpath1;
1726 pstring targetpath2;
1727 struct cli_state *targetcli1;
1728 struct cli_state *targetcli2;
1729 SMBCSRV *srv = NULL;
1731 if (!ocontext || !ncontext ||
1732 !ocontext->internal || !ncontext->internal ||
1733 !ocontext->internal->_initialized ||
1734 !ncontext->internal->_initialized) {
1736 errno = EINVAL; /* Best I can think of ... */
1741 if (!oname || !nname) {
1748 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1750 smbc_parse_path(ocontext, oname,
1751 server1, sizeof(server1),
1752 share1, sizeof(share1),
1753 path1, sizeof(path1),
1754 user1, sizeof(user1),
1755 password1, sizeof(password1),
1758 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1760 smbc_parse_path(ncontext, nname,
1761 server2, sizeof(server2),
1762 share2, sizeof(share2),
1763 path2, sizeof(path2),
1764 user2, sizeof(user2),
1765 password2, sizeof(password2),
1768 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1770 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1771 strcmp(user1, user2)) {
1773 /* Can't rename across file systems, or users?? */
1780 fstrcpy(workgroup, ocontext->workgroup);
1782 srv = smbc_server(ocontext, server1, share1, workgroup,
1790 /*d_printf(">>>rename: resolving %s\n", path1);*/
1791 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1793 d_printf("Could not resolve %s\n", path1);
1796 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1797 /*d_printf(">>>rename: resolving %s\n", path2);*/
1798 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1800 d_printf("Could not resolve %s\n", path2);
1803 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1805 if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1806 strcmp(targetcli1->share, targetcli2->share))
1808 /* can't rename across file systems */
1814 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1815 int eno = smbc_errno(ocontext, targetcli1);
1817 if (eno != EEXIST ||
1818 !cli_unlink(targetcli1, targetpath2) ||
1819 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1827 return 0; /* Success */
1832 * A routine to lseek() a file
1836 smbc_lseek_ctx(SMBCCTX *context,
1842 fstring server, share, user, password;
1843 pstring path, targetpath;
1844 struct cli_state *targetcli;
1846 if (!context || !context->internal ||
1847 !context->internal->_initialized) {
1854 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1864 return -1; /* Can't lseek a dir ... */
1870 file->offset = offset;
1874 file->offset += offset;
1878 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1879 if (smbc_parse_path(context, file->fname,
1880 server, sizeof(server),
1881 share, sizeof(share),
1884 password, sizeof(password),
1891 /*d_printf(">>>lseek: resolving %s\n", path);*/
1892 if (!cli_resolve_path("", &file->srv->cli, path,
1893 &targetcli, targetpath))
1895 d_printf("Could not resolve %s\n", path);
1898 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1900 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1901 &size, NULL, NULL, NULL, NULL, NULL))
1903 SMB_OFF_T b_size = size;
1904 if (!cli_getattrE(targetcli, file->cli_fd,
1905 NULL, &b_size, NULL, NULL, NULL))
1912 file->offset = size + offset;
1921 return file->offset;
1926 * Generate an inode number from file name for those things that need it
1930 smbc_inode(SMBCCTX *context,
1934 if (!context || !context->internal ||
1935 !context->internal->_initialized) {
1942 if (!*name) return 2; /* FIXME, why 2 ??? */
1943 return (ino_t)str_checksum(name);
1948 * Routine to put basic stat info into a stat structure ... Used by stat and
1953 smbc_setup_stat(SMBCCTX *context,
1962 if (IS_DOS_DIR(mode)) {
1963 st->st_mode = SMBC_DIR_MODE;
1965 st->st_mode = SMBC_FILE_MODE;
1968 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1969 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1970 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1971 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1974 #ifdef HAVE_STAT_ST_BLKSIZE
1975 st->st_blksize = 512;
1977 #ifdef HAVE_STAT_ST_BLOCKS
1978 st->st_blocks = (size+511)/512;
1980 st->st_uid = getuid();
1981 st->st_gid = getgid();
1983 if (IS_DOS_DIR(mode)) {
1989 if (st->st_ino == 0) {
1990 st->st_ino = smbc_inode(context, fname);
1993 return True; /* FIXME: Is this needed ? */
1998 * Routine to stat a file given a name
2002 smbc_stat_ctx(SMBCCTX *context,
2020 if (!context || !context->internal ||
2021 !context->internal->_initialized) {
2023 errno = EINVAL; /* Best I can think of ... */
2035 DEBUG(4, ("smbc_stat(%s)\n", fname));
2037 if (smbc_parse_path(context, fname,
2038 server, sizeof(server),
2039 share, sizeof(share),
2042 password, sizeof(password),
2048 if (user[0] == (char)0) fstrcpy(user, context->user);
2050 fstrcpy(workgroup, context->workgroup);
2052 srv = smbc_server(context, server, share, workgroup, user, password);
2055 return -1; /* errno set by smbc_server */
2058 if (!smbc_getatr(context, srv, path, &mode, &size,
2059 &c_time, &a_time, &m_time, &ino)) {
2061 errno = smbc_errno(context, &srv->cli);
2068 smbc_setup_stat(context, st, path, size, mode);
2070 st->st_atime = a_time;
2071 st->st_ctime = c_time;
2072 st->st_mtime = m_time;
2073 st->st_dev = srv->dev;
2080 * Routine to stat a file given an fd
2084 smbc_fstat_ctx(SMBCCTX *context,
2099 struct cli_state *targetcli;
2102 if (!context || !context->internal ||
2103 !context->internal->_initialized) {
2110 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2119 return context->fstatdir(context, file, st);
2123 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2124 if (smbc_parse_path(context, file->fname,
2125 server, sizeof(server),
2126 share, sizeof(share),
2129 password, sizeof(password),
2135 /*d_printf(">>>fstat: resolving %s\n", path);*/
2136 if (!cli_resolve_path("", &file->srv->cli, path,
2137 &targetcli, targetpath))
2139 d_printf("Could not resolve %s\n", path);
2142 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2144 if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2145 &c_time, &a_time, &m_time, NULL, &ino)) {
2146 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2147 &c_time, &a_time, &m_time)) {
2156 smbc_setup_stat(context, st, file->fname, size, mode);
2158 st->st_atime = a_time;
2159 st->st_ctime = c_time;
2160 st->st_mtime = m_time;
2161 st->st_dev = file->srv->dev;
2168 * Routine to open a directory
2169 * We accept the URL syntax explained in smbc_parse_path(), above.
2173 smbc_remove_dir(SMBCFILE *dir)
2175 struct smbc_dir_list *d,*f;
2182 SAFE_FREE(f->dirent);
2187 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2192 add_dirent(SMBCFILE *dir,
2194 const char *comment,
2197 struct smbc_dirent *dirent;
2199 int name_length = (name == NULL ? 0 : strlen(name));
2200 int comment_len = (comment == NULL ? 0 : strlen(comment));
2203 * Allocate space for the dirent, which must be increased by the
2204 * size of the name and the comment and 1 each for the null terminator.
2207 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2209 dirent = SMB_MALLOC(size);
2213 dir->dir_error = ENOMEM;
2218 ZERO_STRUCTP(dirent);
2220 if (dir->dir_list == NULL) {
2222 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2223 if (!dir->dir_list) {
2226 dir->dir_error = ENOMEM;
2230 ZERO_STRUCTP(dir->dir_list);
2232 dir->dir_end = dir->dir_next = dir->dir_list;
2236 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2238 if (!dir->dir_end->next) {
2241 dir->dir_error = ENOMEM;
2245 ZERO_STRUCTP(dir->dir_end->next);
2247 dir->dir_end = dir->dir_end->next;
2250 dir->dir_end->next = NULL;
2251 dir->dir_end->dirent = dirent;
2253 dirent->smbc_type = type;
2254 dirent->namelen = name_length;
2255 dirent->commentlen = comment_len;
2256 dirent->dirlen = size;
2258 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2260 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2261 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2268 list_unique_wg_fn(const char *name,
2270 const char *comment,
2273 SMBCFILE *dir = (SMBCFILE *)state;
2274 struct smbc_dir_list *dir_list;
2275 struct smbc_dirent *dirent;
2279 dirent_type = dir->dir_type;
2281 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2283 /* An error occurred, what do we do? */
2284 /* FIXME: Add some code here */
2287 /* Point to the one just added */
2288 dirent = dir->dir_end->dirent;
2290 /* See if this was a duplicate */
2291 for (dir_list = dir->dir_list;
2292 dir_list != dir->dir_end;
2293 dir_list = dir_list->next) {
2295 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2296 /* Duplicate. End end of list need to be removed. */
2300 if (do_remove && dir_list->next == dir->dir_end) {
2301 /* Found the end of the list. Remove it. */
2302 dir->dir_end = dir_list;
2303 free(dir_list->next);
2305 dir_list->next = NULL;
2312 list_fn(const char *name,
2314 const char *comment,
2317 SMBCFILE *dir = (SMBCFILE *)state;
2321 * We need to process the type a little ...
2323 * Disk share = 0x00000000
2324 * Print share = 0x00000001
2325 * Comms share = 0x00000002 (obsolete?)
2326 * IPC$ share = 0x00000003
2328 * administrative shares:
2329 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2332 if (dir->dir_type == SMBC_FILE_SHARE) {
2335 case 0 | 0x80000000:
2337 dirent_type = SMBC_FILE_SHARE;
2341 dirent_type = SMBC_PRINTER_SHARE;
2345 dirent_type = SMBC_COMMS_SHARE;
2348 case 3 | 0x80000000:
2350 dirent_type = SMBC_IPC_SHARE;
2354 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2359 dirent_type = dir->dir_type;
2362 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2364 /* An error occurred, what do we do? */
2365 /* FIXME: Add some code here */
2371 dir_list_fn(const char *mnt,
2377 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2378 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2380 /* Handle an error ... */
2382 /* FIXME: Add some code ... */
2389 net_share_enum_rpc(struct cli_state *cli,
2390 void (*fn)(const char *name,
2392 const char *comment,
2399 uint32 info_level = 1;
2400 uint32 preferred_len = 0xffffffff;
2402 SRV_SHARE_INFO_CTR ctr;
2404 fstring comment = "";
2406 struct rpc_pipe_client *pipe_hnd;
2409 /* Open the server service pipe */
2410 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2412 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2416 /* Allocate a context for parsing and for the entries in "ctr" */
2417 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2418 if (mem_ctx == NULL) {
2419 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2420 cli_rpc_pipe_close(pipe_hnd);
2424 /* Issue the NetShareEnum RPC call and retrieve the response */
2425 init_enum_hnd(&enum_hnd, 0);
2426 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2433 /* Was it successful? */
2434 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2435 /* Nope. Go clean up. */
2439 /* For each returned entry... */
2440 for (i = 0; i < ctr.num_entries; i++) {
2442 /* pull out the share name */
2443 rpcstr_pull_unistr2_fstring(
2444 name, &ctr.share.info1[i].info_1_str.uni_netname);
2446 /* pull out the share's comment */
2447 rpcstr_pull_unistr2_fstring(
2448 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2450 /* Get the type value */
2451 type = ctr.share.info1[i].info_1.type;
2453 /* Add this share to the list */
2454 (*fn)(name, type, comment, state);
2458 /* Close the server service pipe */
2459 cli_rpc_pipe_close(pipe_hnd);
2461 /* Free all memory which was allocated for this request */
2462 talloc_free(mem_ctx);
2464 /* Tell 'em if it worked */
2465 return W_ERROR_IS_OK(result) ? 0 : -1;
2471 smbc_opendir_ctx(SMBCCTX *context,
2474 fstring server, share, user, password, options;
2479 SMBCSRV *srv = NULL;
2480 SMBCFILE *dir = NULL;
2481 struct in_addr rem_ip;
2483 if (!context || !context->internal ||
2484 !context->internal->_initialized) {
2485 DEBUG(4, ("no valid context\n"));
2486 errno = EINVAL + 8192;
2492 DEBUG(4, ("no valid fname\n"));
2493 errno = EINVAL + 8193;
2497 if (smbc_parse_path(context, fname,
2498 server, sizeof(server),
2499 share, sizeof(share),
2502 password, sizeof(password),
2503 options, sizeof(options))) {
2504 DEBUG(4, ("no valid path\n"));
2505 errno = EINVAL + 8194;
2509 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2510 "path='%s' options='%s'\n",
2511 fname, server, share, path, options));
2513 /* Ensure the options are valid */
2514 if (smbc_check_options(server, share, path, options)) {
2515 DEBUG(4, ("unacceptable options (%s)\n", options));
2516 errno = EINVAL + 8195;
2520 if (user[0] == (char)0) fstrcpy(user, context->user);
2522 pstrcpy(workgroup, context->workgroup);
2524 dir = SMB_MALLOC_P(SMBCFILE);
2536 dir->fname = SMB_STRDUP(fname);
2540 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2542 if (server[0] == (char)0) {
2547 struct ip_service *ip_list;
2548 struct ip_service server_addr;
2549 struct user_auth_info u_info;
2550 struct cli_state *cli;
2552 if (share[0] != (char)0 || path[0] != (char)0) {
2554 errno = EINVAL + 8196;
2556 SAFE_FREE(dir->fname);
2562 /* Determine how many local master browsers to query */
2563 max_lmb_count = (context->options.browse_max_lmb_count == 0
2565 : context->options.browse_max_lmb_count);
2567 pstrcpy(u_info.username, user);
2568 pstrcpy(u_info.password, password);
2571 * We have server and share and path empty but options
2572 * requesting that we scan all master browsers for their list
2573 * of workgroups/domains. This implies that we must first try
2574 * broadcast queries to find all master browsers, and if that
2575 * doesn't work, then try our other methods which return only
2576 * a single master browser.
2580 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2584 if (!find_master_ip(workgroup, &server_addr.ip)) {
2590 ip_list = &server_addr;
2594 for (i = 0; i < count && i < max_lmb_count; i++) {
2595 DEBUG(99, ("Found master browser %d of %d: %s\n",
2596 i+1, MAX(count, max_lmb_count),
2597 inet_ntoa(ip_list[i].ip)));
2599 cli = get_ipc_connect_master_ip(&ip_list[i],
2600 workgroup, &u_info);
2601 /* cli == NULL is the master browser refused to talk or
2602 could not be found */
2606 fstrcpy(server, cli->desthost);
2609 DEBUG(4, ("using workgroup %s %s\n",
2610 workgroup, server));
2613 * For each returned master browser IP address, get a
2614 * connection to IPC$ on the server if we do not
2615 * already have one, and determine the
2616 * workgroups/domains that it knows about.
2619 srv = smbc_server(context, server,
2620 "IPC$", workgroup, user, password);
2626 dir->dir_type = SMBC_WORKGROUP;
2628 /* Now, list the stuff ... */
2630 if (!cli_NetServerEnum(&srv->cli,
2632 SV_TYPE_DOMAIN_ENUM,
2642 * Server not an empty string ... Check the rest and see what
2645 if (*share == '\0') {
2646 if (*path != '\0') {
2648 /* Should not have empty share with path */
2649 errno = EINVAL + 8197;
2651 SAFE_FREE(dir->fname);
2659 * We don't know if <server> is really a server name
2660 * or is a workgroup/domain name. If we already have
2661 * a server structure for it, we'll use it.
2662 * Otherwise, check to see if <server><1D>,
2663 * <server><1B>, or <server><20> translates. We check
2664 * to see if <server> is an IP address first.
2667 /* See if we have an existing server */
2668 srv = smbc_server(context, server, "IPC$",
2669 workgroup, user, password);
2672 * If no existing server and not an IP addr, look for
2676 !is_ipaddress(server) &&
2677 (resolve_name(server, &rem_ip, 0x1d) || /* LMB */
2678 resolve_name(server, &rem_ip, 0x1b) )) { /* DMB */
2682 dir->dir_type = SMBC_SERVER;
2685 * Get the backup list ...
2687 if (!name_status_find(server, 0, 0,
2688 rem_ip, buserver)) {
2690 DEBUG(0, ("Could not get name of "
2691 "local/domain master browser "
2692 "for server %s\n", server));
2699 * Get a connection to IPC$ on the server if
2700 * we do not already have one
2702 srv = smbc_server(context, buserver, "IPC$",
2703 workgroup, user, password);
2705 DEBUG(0, ("got no contact to IPC$\n"));
2707 SAFE_FREE(dir->fname);
2716 /* Now, list the servers ... */
2717 if (!cli_NetServerEnum(&srv->cli, server,
2718 0x0000FFFE, list_fn,
2722 SAFE_FREE(dir->fname);
2728 (resolve_name(server, &rem_ip, 0x20))) {
2730 /* If we hadn't found the server, get one now */
2732 srv = smbc_server(context, server,
2739 SAFE_FREE(dir->fname);
2746 dir->dir_type = SMBC_FILE_SHARE;
2749 /* List the shares ... */
2751 if (net_share_enum_rpc(
2754 (void *) dir) < 0 &&
2760 errno = cli_errno(&srv->cli);
2762 SAFE_FREE(dir->fname);
2769 /* Neither the workgroup nor server exists */
2770 errno = ECONNREFUSED;
2772 SAFE_FREE(dir->fname);
2781 * The server and share are specified ... work from
2785 struct cli_state *targetcli;
2787 /* We connect to the server and list the directory */
2788 dir->dir_type = SMBC_FILE_SHARE;
2790 srv = smbc_server(context, server, share,
2791 workgroup, user, password);
2796 SAFE_FREE(dir->fname);
2805 /* Now, list the files ... */
2807 p = path + strlen(path);
2808 pstrcat(path, "\\*");
2810 if (!cli_resolve_path("", &srv->cli, path,
2811 &targetcli, targetpath))
2813 d_printf("Could not resolve %s\n", path);
2817 if (cli_list(targetcli, targetpath,
2818 aDIR | aSYSTEM | aHIDDEN,
2819 dir_list_fn, (void *)dir) < 0) {
2822 SAFE_FREE(dir->fname);
2825 errno = smbc_errno(context, targetcli);
2827 if (errno == EINVAL) {
2829 * See if they asked to opendir something
2830 * other than a directory. If so, the
2831 * converted error value we got would have
2832 * been EINVAL rather than ENOTDIR.
2834 *p = '\0'; /* restore original path */
2836 if (smbc_getatr(context, srv, path,
2840 ! IS_DOS_DIR(mode)) {
2842 /* It is. Correct the error value */
2854 DLIST_ADD(context->internal->_files, dir);
2860 * Routine to close a directory
2864 smbc_closedir_ctx(SMBCCTX *context,
2868 if (!context || !context->internal ||
2869 !context->internal->_initialized) {
2876 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2883 smbc_remove_dir(dir); /* Clean it up */
2885 DLIST_REMOVE(context->internal->_files, dir);
2889 SAFE_FREE(dir->fname);
2890 SAFE_FREE(dir); /* Free the space too */
2898 smbc_readdir_internal(SMBCCTX * context,
2899 struct smbc_dirent *dest,
2900 struct smbc_dirent *src,
2901 int max_namebuf_len)
2903 if (context->options.urlencode_readdir_entries) {
2905 /* url-encode the name. get back remaining buffer space */
2907 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2909 /* We now know the name length */
2910 dest->namelen = strlen(dest->name);
2912 /* Save the pointer to the beginning of the comment */
2913 dest->comment = dest->name + dest->namelen + 1;
2915 /* Copy the comment */
2916 strncpy(dest->comment, src->comment, max_namebuf_len);
2918 /* Ensure the comment is null terminated */
2919 if (max_namebuf_len > src->commentlen) {
2920 dest->comment[src->commentlen] = '\0';
2922 dest->comment[max_namebuf_len - 1] = '\0';
2925 /* Save other fields */
2926 dest->smbc_type = src->smbc_type;
2927 dest->commentlen = strlen(dest->comment);
2928 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2932 /* No encoding. Just copy the entry as is. */
2933 memcpy(dest, src, src->dirlen);
2934 dest->comment = (char *)(&dest->name + src->namelen + 1);
2940 * Routine to get a directory entry
2943 struct smbc_dirent *
2944 smbc_readdir_ctx(SMBCCTX *context,
2948 struct smbc_dirent *dirp, *dirent;
2950 /* Check that all is ok first ... */
2952 if (!context || !context->internal ||
2953 !context->internal->_initialized) {
2956 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2961 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2964 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2969 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2972 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2977 if (!dir->dir_next) {
2981 dirent = dir->dir_next->dirent;
2989 dirp = (struct smbc_dirent *)context->internal->_dirent;
2990 maxlen = (sizeof(context->internal->_dirent) -
2991 sizeof(struct smbc_dirent));
2993 smbc_readdir_internal(context, dirp, dirent, maxlen);
2995 dir->dir_next = dir->dir_next->next;
3001 * Routine to get directory entries
3005 smbc_getdents_ctx(SMBCCTX *context,
3007 struct smbc_dirent *dirp,
3013 char *ndir = (char *)dirp;
3014 struct smbc_dir_list *dirlist;
3016 /* Check that all is ok first ... */
3018 if (!context || !context->internal ||
3019 !context->internal->_initialized) {
3026 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3033 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3041 * Now, retrieve the number of entries that will fit in what was passed
3042 * We have to figure out if the info is in the list, or we need to
3043 * send a request to the server to get the info.
3046 while ((dirlist = dir->dir_next)) {
3047 struct smbc_dirent *dirent;
3049 if (!dirlist->dirent) {
3051 errno = ENOENT; /* Bad error */
3056 /* Do urlencoding of next entry, if so selected */
3057 dirent = (struct smbc_dirent *)context->internal->_dirent;
3058 maxlen = (sizeof(context->internal->_dirent) -
3059 sizeof(struct smbc_dirent));
3060 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3062 reqd = dirent->dirlen;
3066 if (rem < count) { /* We managed to copy something */
3072 else { /* Nothing copied ... */
3074 errno = EINVAL; /* Not enough space ... */
3081 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3083 ((struct smbc_dirent *)ndir)->comment =
3084 (char *)(&((struct smbc_dirent *)ndir)->name +
3092 dir->dir_next = dirlist = dirlist -> next;
3103 * Routine to create a directory ...
3107 smbc_mkdir_ctx(SMBCCTX *context,
3117 pstring path, targetpath;
3118 struct cli_state *targetcli;
3120 if (!context || !context->internal ||
3121 !context->internal->_initialized) {
3135 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3137 if (smbc_parse_path(context, fname,
3138 server, sizeof(server),
3139 share, sizeof(share),
3142 password, sizeof(password),
3148 if (user[0] == (char)0) fstrcpy(user, context->user);
3150 fstrcpy(workgroup, context->workgroup);
3152 srv = smbc_server(context, server, share, workgroup, user, password);
3156 return -1; /* errno set by smbc_server */
3160 /*d_printf(">>>mkdir: resolving %s\n", path);*/
3161 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3163 d_printf("Could not resolve %s\n", path);
3166 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3168 if (!cli_mkdir(targetcli, targetpath)) {
3170 errno = smbc_errno(context, targetcli);
3180 * Our list function simply checks to see if a directory is not empty
3183 static int smbc_rmdir_dirempty = True;
3186 rmdir_list_fn(const char *mnt,
3191 if (strncmp(finfo->name, ".", 1) != 0 &&
3192 strncmp(finfo->name, "..", 2) != 0) {
3194 smbc_rmdir_dirempty = False;
3199 * Routine to remove a directory
3203 smbc_rmdir_ctx(SMBCCTX *context,
3214 struct cli_state *targetcli;
3216 if (!context || !context->internal ||
3217 !context->internal->_initialized) {
3231 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3233 if (smbc_parse_path(context, fname,
3234 server, sizeof(server),
3235 share, sizeof(share),
3238 password, sizeof(password),
3245 if (user[0] == (char)0) fstrcpy(user, context->user);
3247 fstrcpy(workgroup, context->workgroup);
3249 srv = smbc_server(context, server, share, workgroup, user, password);
3253 return -1; /* errno set by smbc_server */
3257 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3258 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3260 d_printf("Could not resolve %s\n", path);
3263 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3266 if (!cli_rmdir(targetcli, targetpath)) {
3268 errno = smbc_errno(context, targetcli);
3270 if (errno == EACCES) { /* Check if the dir empty or not */
3272 /* Local storage to avoid buffer overflows */
3275 smbc_rmdir_dirempty = True; /* Make this so ... */
3277 pstrcpy(lpath, targetpath);
3278 pstrcat(lpath, "\\*");
3280 if (cli_list(targetcli, lpath,
3281 aDIR | aSYSTEM | aHIDDEN,
3282 rmdir_list_fn, NULL) < 0) {
3284 /* Fix errno to ignore latest error ... */
3285 DEBUG(5, ("smbc_rmdir: "
3286 "cli_list returned an error: %d\n",
3287 smbc_errno(context, targetcli)));
3292 if (smbc_rmdir_dirempty)
3308 * Routine to return the current directory position
3312 smbc_telldir_ctx(SMBCCTX *context,
3315 off_t ret_val; /* Squash warnings about cast */
3317 if (!context || !context->internal ||
3318 !context->internal->_initialized) {
3325 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3332 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3340 * We return the pointer here as the offset
3342 ret_val = (off_t)(long)dir->dir_next;
3348 * A routine to run down the list and see if the entry is OK
3351 struct smbc_dir_list *
3352 smbc_check_dir_ent(struct smbc_dir_list *list,
3353 struct smbc_dirent *dirent)
3356 /* Run down the list looking for what we want */
3360 struct smbc_dir_list *tmp = list;
3364 if (tmp->dirent == dirent)
3373 return NULL; /* Not found, or an error */
3379 * Routine to seek on a directory
3383 smbc_lseekdir_ctx(SMBCCTX *context,
3387 long int l_offset = offset; /* Handle problems of size */
3388 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3389 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3391 if (!context || !context->internal ||
3392 !context->internal->_initialized) {
3399 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3406 /* Now, check what we were passed and see if it is OK ... */
3408 if (dirent == NULL) { /* Seek to the begining of the list */
3410 dir->dir_next = dir->dir_list;
3415 /* Now, run down the list and make sure that the entry is OK */
3416 /* This may need to be changed if we change the format of the list */
3418 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3420 errno = EINVAL; /* Bad entry */
3425 dir->dir_next = list_ent;
3432 * Routine to fstat a dir
3436 smbc_fstatdir_ctx(SMBCCTX *context,
3441 if (!context || !context->internal ||
3442 !context->internal->_initialized) {
3449 /* No code yet ... */
3456 smbc_chmod_ctx(SMBCCTX *context,
3469 if (!context || !context->internal ||
3470 !context->internal->_initialized) {
3472 errno = EINVAL; /* Best I can think of ... */
3484 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3486 if (smbc_parse_path(context, fname,
3487 server, sizeof(server),
3488 share, sizeof(share),
3491 password, sizeof(password),
3497 if (user[0] == (char)0) fstrcpy(user, context->user);
3499 fstrcpy(workgroup, context->workgroup);
3501 srv = smbc_server(context, server, share, workgroup, user, password);
3504 return -1; /* errno set by smbc_server */
3509 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3510 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3511 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3512 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3514 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3515 errno = smbc_errno(context, &srv->cli);
3523 smbc_utimes_ctx(SMBCCTX *context,
3525 struct timeval *tbuf)
3537 if (!context || !context->internal ||
3538 !context->internal->_initialized) {
3540 errno = EINVAL; /* Best I can think of ... */
3553 a_time = m_time = time(NULL);
3555 a_time = tbuf[0].tv_sec;
3556 m_time = tbuf[1].tv_sec;
3565 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf));
3566 atimebuf[sizeof(atimebuf) - 1] = '\0';
3567 if ((p = strchr(atimebuf, '\n')) != NULL) {
3571 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf));
3572 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3573 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3577 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3578 fname, atimebuf, mtimebuf);
3581 if (smbc_parse_path(context, fname,
3582 server, sizeof(server),
3583 share, sizeof(share),
3586 password, sizeof(password),
3592 if (user[0] == (char)0) fstrcpy(user, context->user);
3594 fstrcpy(workgroup, context->workgroup);
3596 srv = smbc_server(context, server, share, workgroup, user, password);
3599 return -1; /* errno set by smbc_server */
3602 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3603 return -1; /* errno set by smbc_setatr */
3610 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3611 However NT4 gives a "The information may have been modified by a
3612 computer running Windows NT 5.0" if denied ACEs do not appear before
3616 ace_compare(SEC_ACE *ace1,
3619 if (sec_ace_equal(ace1, ace2))
3622 if (ace1->type != ace2->type)
3623 return ace2->type - ace1->type;
3625 if (sid_compare(&ace1->trustee, &ace2->trustee))
3626 return sid_compare(&ace1->trustee, &ace2->trustee);
3628 if (ace1->flags != ace2->flags)
3629 return ace1->flags - ace2->flags;
3631 if (ace1->info.mask != ace2->info.mask)
3632 return ace1->info.mask - ace2->info.mask;
3634 if (ace1->size != ace2->size)
3635 return ace1->size - ace2->size;
3637 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3642 sort_acl(SEC_ACL *the_acl)
3645 if (!the_acl) return;
3647 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]),
3648 QSORT_CAST ace_compare);
3650 for (i=1;i<the_acl->num_aces;) {
3651 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3653 for (j=i; j<the_acl->num_aces-1; j++) {
3654 the_acl->ace[j] = the_acl->ace[j+1];
3656 the_acl->num_aces--;
3663 /* convert a SID to a string, either numeric or username/group */
3665 convert_sid_to_string(struct cli_state *ipc_cli,
3671 char **domains = NULL;
3672 char **names = NULL;
3673 uint32 *types = NULL;
3674 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3675 sid_to_string(str, sid);
3678 return; /* no lookup desired */
3685 /* Ask LSA to convert the sid to a name */
3687 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3688 pol, 1, sid, &domains,
3690 !domains || !domains[0] || !names || !names[0]) {
3696 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3697 domains[0], lp_winbind_separator(),
3701 /* convert a string to a SID, either numeric or username/group */
3703 convert_string_to_sid(struct cli_state *ipc_cli,
3709 uint32 *types = NULL;
3710 DOM_SID *sids = NULL;
3712 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3719 if (strncmp(str, "S-", 2) == 0) {
3720 return string_to_sid(sid, str);
3727 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3728 pol, 1, &str, &sids,
3734 sid_copy(sid, &sids[0]);
3741 /* parse an ACE in the same format as print_ace() */
3743 parse_ace(struct cli_state *ipc_cli,
3753 unsigned int aflags;
3757 const struct perm_value *v;
3763 /* These values discovered by inspection */
3764 static const struct perm_value special_values[] = {
3765 { "R", 0x00120089 },
3766 { "W", 0x00120116 },
3767 { "X", 0x001200a0 },
3768 { "D", 0x00010000 },
3769 { "P", 0x00040000 },
3770 { "O", 0x00080000 },
3774 static const struct perm_value standard_values[] = {
3775 { "READ", 0x001200a9 },
3776 { "CHANGE", 0x001301bf },
3777 { "FULL", 0x001f01ff },
3783 p = strchr_m(str,':');
3784 if (!p) return False;
3787 /* Try to parse numeric form */
3789 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3790 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3794 /* Try to parse text form */
3796 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3801 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3805 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3806 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3807 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3808 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3813 /* Only numeric form accepted for flags at present */
3815 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3816 sscanf(tok, "%i", &aflags))) {
3820 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3824 if (strncmp(tok, "0x", 2) == 0) {
3825 if (sscanf(tok, "%i", &amask) != 1) {
3831 for (v = standard_values; v->perm; v++) {
3832 if (strcmp(tok, v->perm) == 0) {
3843 for (v = special_values; v->perm; v++) {
3844 if (v->perm[0] == *p) {
3850 if (!found) return False;
3860 init_sec_ace(ace, &sid, atype, mask, aflags);
3864 /* add an ACE to a list of ACEs in a SEC_ACL */
3866 add_ace(SEC_ACL **the_acl,
3874 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3878 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3879 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3880 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3881 newacl = make_sec_acl(ctx, (*the_acl)->revision,
3882 1+(*the_acl)->num_aces, aces);
3884 (*the_acl) = newacl;
3889 /* parse a ascii version of a security descriptor */
3891 sec_desc_parse(TALLOC_CTX *ctx,
3892 struct cli_state *ipc_cli,
3897 const char *p = str;
3901 DOM_SID *grp_sid=NULL;
3902 DOM_SID *owner_sid=NULL;
3906 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3908 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3909 revision = strtol(tok+9, NULL, 16);
3913 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3914 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3916 !convert_string_to_sid(ipc_cli, pol,
3918 owner_sid, tok+6)) {
3919 DEBUG(5, ("Failed to parse owner sid\n"));
3925 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3926 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3928 !convert_string_to_sid(ipc_cli, pol,
3930 owner_sid, tok+7)) {
3931 DEBUG(5, ("Failed to parse owner sid\n"));
3937 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3938 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3940 !convert_string_to_sid(ipc_cli, pol,
3943 DEBUG(5, ("Failed to parse group sid\n"));
3949 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3950 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3952 !convert_string_to_sid(ipc_cli, pol,
3955 DEBUG(5, ("Failed to parse group sid\n"));
3961 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3963 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3964 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3967 if(!add_ace(&dacl, &ace, ctx)) {
3968 DEBUG(5, ("Failed to add ACL %s\n", tok));
3974 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3976 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3977 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3980 if(!add_ace(&dacl, &ace, ctx)) {
3981 DEBUG(5, ("Failed to add ACL %s\n", tok));
3987 DEBUG(5, ("Failed to parse security descriptor\n"));
3991 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3992 owner_sid, grp_sid, NULL, dacl, &sd_size);
3995 SAFE_FREE(owner_sid);
4001 /* Obtain the current dos attributes */
4002 static DOS_ATTR_DESC *
4003 dos_attr_query(SMBCCTX *context,
4005 const char *filename,
4008 time_t m_time = 0, a_time = 0, c_time = 0;
4011 SMB_INO_T inode = 0;
4014 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
4020 /* Obtain the DOS attributes */
4021 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
4023 &c_time, &a_time, &m_time, &inode)) {
4025 errno = smbc_errno(context, &srv->cli);
4026 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
4033 ret->a_time = a_time;
4034 ret->c_time = c_time;
4035 ret->m_time = m_time;
4042 /* parse a ascii version of a security descriptor */
4044 dos_attr_parse(SMBCCTX *context,
4049 const char *p = str;
4052 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4054 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
4055 dad->mode = strtol(tok+5, NULL, 16);
4059 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4060 dad->size = (SMB_OFF_T)atof(tok+5);
4064 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
4065 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
4069 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
4070 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
4074 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
4075 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
4079 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4080 dad->inode = (SMB_INO_T)atof(tok+6);
4086 /*****************************************************
4087 Retrieve the acls for a file.
4088 *******************************************************/
4091 cacl_get(SMBCCTX *context,
4094 struct cli_state *ipc_cli,
4110 BOOL exclude_nt_revision = False;
4111 BOOL exclude_nt_owner = False;
4112 BOOL exclude_nt_group = False;
4113 BOOL exclude_nt_acl = False;
4114 BOOL exclude_dos_mode = False;
4115 BOOL exclude_dos_size = False;
4116 BOOL exclude_dos_ctime = False;
4117 BOOL exclude_dos_atime = False;
4118 BOOL exclude_dos_mtime = False;
4119 BOOL exclude_dos_inode = False;
4120 BOOL numeric = True;
4121 BOOL determine_size = (bufsize == 0);
4125 fstring name_sandbox;
4129 time_t m_time = 0, a_time = 0, c_time = 0;
4133 struct cli_state *cli = &srv->cli;
4135 /* Copy name so we can strip off exclusions (if any are specified) */
4136 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4138 /* Ensure name is null terminated */
4139 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4141 /* Play in the sandbox */
4142 name = name_sandbox;
4144 /* If there are any exclusions, point to them and mask them from name */
4145 if ((pExclude = strchr(name, '!')) != NULL)
4150 all = (StrnCaseCmp(name, "system.*", 8) == 0);
4151 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4152 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4153 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4154 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4155 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4156 numeric = (* (name + strlen(name) - 1) != '+');
4158 /* Look for exclusions from "all" requests */
4159 if (all || all_nt || all_dos) {
4161 /* Exclusions are delimited by '!' */
4164 pExclude = (p == NULL ? NULL : p + 1)) {
4166 /* Find end of this exclusion name */
4167 if ((p = strchr(pExclude, '!')) != NULL)
4172 /* Which exclusion name is this? */
4173 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4174 exclude_nt_revision = True;
4176 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4177 exclude_nt_owner = True;
4179 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4180 exclude_nt_group = True;
4182 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4183 exclude_nt_acl = True;
4185 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4186 exclude_dos_mode = True;
4188 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4189 exclude_dos_size = True;
4191 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
4192 exclude_dos_ctime = True;
4194 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
4195 exclude_dos_atime = True;
4197 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
4198 exclude_dos_mtime = True;
4200 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4201 exclude_dos_inode = True;
4204 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4215 * If we are (possibly) talking to an NT or new system and some NT
4216 * attributes have been requested...
4218 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4219 /* Point to the portion after "system.nt_sec_desc." */
4220 name += 19; /* if (all) this will be invalid but unused */
4222 /* ... then obtain any NT attributes which were requested */
4223 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4226 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4227 filename, cli_errstr(cli)));
4232 sd = cli_query_secdesc(cli, fnum, ctx);
4236 ("cacl_get Failed to query old descriptor\n"));
4241 cli_close(cli, fnum);
4243 if (! exclude_nt_revision) {
4244 if (all || all_nt) {
4245 if (determine_size) {
4246 p = talloc_asprintf(ctx,
4255 n = snprintf(buf, bufsize,
4259 } else if (StrCaseCmp(name, "revision") == 0) {
4260 if (determine_size) {
4261 p = talloc_asprintf(ctx, "%d",
4269 n = snprintf(buf, bufsize, "%d",
4274 if (!determine_size && n > bufsize) {
4283 if (! exclude_nt_owner) {
4284 /* Get owner and group sid */
4285 if (sd->owner_sid) {
4286 convert_sid_to_string(ipc_cli, pol,
4291 fstrcpy(sidstr, "");
4294 if (all || all_nt) {
4295 if (determine_size) {
4296 p = talloc_asprintf(ctx, ",OWNER:%s",
4304 n = snprintf(buf, bufsize,
4305 ",OWNER:%s", sidstr);
4307 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4308 if (determine_size) {
4309 p = talloc_asprintf(ctx, "%s", sidstr);
4316 n = snprintf(buf, bufsize, "%s",
4321 if (!determine_size && n > bufsize) {
4330 if (! exclude_nt_group) {
4332 convert_sid_to_string(ipc_cli, pol,
4336 fstrcpy(sidstr, "");
4339 if (all || all_nt) {
4340 if (determine_size) {
4341 p = talloc_asprintf(ctx, ",GROUP:%s",
4349 n = snprintf(buf, bufsize,
4350 ",GROUP:%s", sidstr);
4352 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4353 if (determine_size) {
4354 p = talloc_asprintf(ctx, "%s", sidstr);
4361 n = snprintf(buf, bufsize,
4366 if (!determine_size && n > bufsize) {
4375 if (! exclude_nt_acl) {
4376 /* Add aces to value buffer */
4377 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4379 SEC_ACE *ace = &sd->dacl->ace[i];
4380 convert_sid_to_string(ipc_cli, pol,
4384 if (all || all_nt) {
4385 if (determine_size) {
4386 p = talloc_asprintf(
4402 ",ACL:%s:%d/%d/0x%08x",
4408 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4409 StrCaseCmp(name+3, sidstr) == 0) ||
4410 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4411 StrCaseCmp(name+4, sidstr) == 0)) {
4412 if (determine_size) {
4413 p = talloc_asprintf(
4425 n = snprintf(buf, bufsize,
4431 } else if (all_nt_acls) {
4432 if (determine_size) {
4433 p = talloc_asprintf(
4435 "%s%s:%d/%d/0x%08x",
4447 n = snprintf(buf, bufsize,
4448 "%s%s:%d/%d/0x%08x",
4466 /* Restore name pointer to its original value */
4470 if (all || some_dos) {
4471 /* Point to the portion after "system.dos_attr." */
4472 name += 16; /* if (all) this will be invalid but unused */
4474 /* Obtain the DOS attributes */
4475 if (!smbc_getatr(context, srv, filename, &mode, &size,
4476 &c_time, &a_time, &m_time, &ino)) {
4478 errno = smbc_errno(context, &srv->cli);
4483 if (! exclude_dos_mode) {
4484 if (all || all_dos) {
4485 if (determine_size) {
4486 p = talloc_asprintf(ctx,
4499 n = snprintf(buf, bufsize,
4507 } else if (StrCaseCmp(name, "mode") == 0) {
4508 if (determine_size) {
4509 p = talloc_asprintf(ctx, "0x%x", mode);
4516 n = snprintf(buf, bufsize,
4521 if (!determine_size && n > bufsize) {
4530 if (! exclude_dos_size) {
4531 if (all || all_dos) {
4532 if (determine_size) {
4533 p = talloc_asprintf(
4543 n = snprintf(buf, bufsize,
4547 } else if (StrCaseCmp(name, "size") == 0) {
4548 if (determine_size) {
4549 p = talloc_asprintf(
4559 n = snprintf(buf, bufsize,
4565 if (!determine_size && n > bufsize) {
4574 if (! exclude_dos_ctime) {
4575 if (all || all_dos) {
4576 if (determine_size) {
4577 p = talloc_asprintf(ctx,
4586 n = snprintf(buf, bufsize,
4587 ",C_TIME:%lu", c_time);
4589 } else if (StrCaseCmp(name, "c_time") == 0) {
4590 if (determine_size) {
4591 p = talloc_asprintf(ctx, "%lu", c_time);
4598 n = snprintf(buf, bufsize,
4603 if (!determine_size && n > bufsize) {
4612 if (! exclude_dos_atime) {
4613 if (all || all_dos) {
4614 if (determine_size) {
4615 p = talloc_asprintf(ctx,
4624 n = snprintf(buf, bufsize,
4625 ",A_TIME:%lu", a_time);
4627 } else if (StrCaseCmp(name, "a_time") == 0) {
4628 if (determine_size) {
4629 p = talloc_asprintf(ctx, "%lu", a_time);
4636 n = snprintf(buf, bufsize,
4641 if (!determine_size && n > bufsize) {
4650 if (! exclude_dos_mtime) {
4651 if (all || all_dos) {
4652 if (determine_size) {
4653 p = talloc_asprintf(ctx,
4662 n = snprintf(buf, bufsize,
4663 ",M_TIME:%lu", m_time);
4665 } else if (StrCaseCmp(name, "m_time") == 0) {
4666 if (determine_size) {
4667 p = talloc_asprintf(ctx, "%lu", m_time);
4674 n = snprintf(buf, bufsize,
4679 if (!determine_size && n > bufsize) {
4688 if (! exclude_dos_inode) {
4689 if (all || all_dos) {
4690 if (determine_size) {
4691 p = talloc_asprintf(
4701 n = snprintf(buf, bufsize,
4705 } else if (StrCaseCmp(name, "inode") == 0) {
4706 if (determine_size) {
4707 p = talloc_asprintf(
4717 n = snprintf(buf, bufsize,
4723 if (!determine_size && n > bufsize) {
4732 /* Restore name pointer to its original value */
4745 /*****************************************************
4746 set the ACLs on a file given an ascii description
4747 *******************************************************/
4749 cacl_set(TALLOC_CTX *ctx,
4750 struct cli_state *cli,
4751 struct cli_state *ipc_cli,
4753 const char *filename,
4754 const char *the_acl,
4760 SEC_DESC *sd = NULL, *old;
4761 SEC_ACL *dacl = NULL;
4762 DOM_SID *owner_sid = NULL;
4763 DOM_SID *grp_sid = NULL;
4768 BOOL numeric = True;
4770 /* the_acl will be null for REMOVE_ALL operations */
4772 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4776 /* if this is to set the entire ACL... */
4777 if (*the_acl == '*') {
4778 /* ... then increment past the first colon */
4782 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4783 CONST_DISCARD(char *, the_acl));
4791 /* The desired access below is the only one I could find that works
4792 with NT4, W2KP and Samba */
4794 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4797 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4798 filename, cli_errstr(cli)));
4803 old = cli_query_secdesc(cli, fnum, ctx);
4806 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4811 cli_close(cli, fnum);
4814 case SMBC_XATTR_MODE_REMOVE_ALL:
4815 old->dacl->num_aces = 0;
4816 SAFE_FREE(old->dacl->ace);
4817 SAFE_FREE(old->dacl);
4822 case SMBC_XATTR_MODE_REMOVE:
4823 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4826 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4827 if (sec_ace_equal(&sd->dacl->ace[i],
4828 &old->dacl->ace[j])) {
4830 for (k=j; k<old->dacl->num_aces-1;k++) {
4832 old->dacl->ace[k+1];
4834 old->dacl->num_aces--;
4835 if (old->dacl->num_aces == 0) {
4836 SAFE_FREE(old->dacl->ace);
4837 SAFE_FREE(old->dacl);
4854 case SMBC_XATTR_MODE_ADD:
4855 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4858 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4859 if (sid_equal(&sd->dacl->ace[i].trustee,
4860 &old->dacl->ace[j].trustee)) {
4861 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4866 old->dacl->ace[j] = sd->dacl->ace[i];
4872 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4878 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4879 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4885 case SMBC_XATTR_MODE_SET:
4887 owner_sid = old->owner_sid;
4888 grp_sid = old->grp_sid;
4892 case SMBC_XATTR_MODE_CHOWN:
4893 owner_sid = sd->owner_sid;
4896 case SMBC_XATTR_MODE_CHGRP:
4897 grp_sid = sd->grp_sid;
4901 /* Denied ACE entries must come before allowed ones */
4902 sort_acl(old->dacl);
4904 /* Create new security descriptor and set it */
4905 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4906 owner_sid, grp_sid, NULL, dacl, &sd_size);
4908 fnum = cli_nt_create(cli, filename,
4909 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4912 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4913 filename, cli_errstr(cli)));
4918 if (!cli_set_secdesc(cli, fnum, sd)) {
4919 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4926 cli_close(cli, fnum);
4937 smbc_setxattr_ctx(SMBCCTX *context,
4958 if (!context || !context->internal ||
4959 !context->internal->_initialized) {
4961 errno = EINVAL; /* Best I can think of ... */
4973 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
4974 fname, name, (int) size, (const char*)value));
4976 if (smbc_parse_path(context, fname,
4977 server, sizeof(server),
4978 share, sizeof(share),
4981 password, sizeof(password),
4987 if (user[0] == (char)0) fstrcpy(user, context->user);
4989 fstrcpy(workgroup, context->workgroup);
4991 srv = smbc_server(context, server, share, workgroup, user, password);
4993 return -1; /* errno set by smbc_server */
4996 if (! srv->no_nt_session) {
4997 ipc_srv = smbc_attr_server(context, server, share,
4998 workgroup, user, password,
5000 srv->no_nt_session = True;
5005 ctx = talloc_init("smbc_setxattr");
5012 * Are they asking to set the entire set of known attributes?
5014 if (StrCaseCmp(name, "system.*") == 0 ||
5015 StrCaseCmp(name, "system.*+") == 0) {
5018 talloc_asprintf(ctx, "%s:%s",
5019 name+7, (const char *) value);
5027 ret = cacl_set(ctx, &srv->cli,
5028 &ipc_srv->cli, &pol, path,
5031 ? SMBC_XATTR_MODE_SET
5032 : SMBC_XATTR_MODE_ADD),
5038 /* get a DOS Attribute Descriptor with current attributes */
5039 dad = dos_attr_query(context, ctx, path, srv);
5041 /* Overwrite old with new, using what was provided */
5042 dos_attr_parse(context, dad, srv, namevalue);
5044 /* Set the new DOS attributes */
5045 if (! smbc_setatr(context, srv, path,
5051 /* cause failure if NT failed too */
5056 /* we only fail if both NT and DOS sets failed */
5057 if (ret < 0 && ! dad) {
5058 ret = -1; /* in case dad was null */
5064 talloc_destroy(ctx);
5069 * Are they asking to set an access control element or to set
5070 * the entire access control list?
5072 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5073 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5074 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5075 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5076 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5080 talloc_asprintf(ctx, "%s:%s",
5081 name+19, (const char *) value);
5084 ret = -1; /* errno set by smbc_server() */
5086 else if (! namevalue) {
5090 ret = cacl_set(ctx, &srv->cli,
5091 &ipc_srv->cli, &pol, path,
5094 ? SMBC_XATTR_MODE_SET
5095 : SMBC_XATTR_MODE_ADD),
5098 talloc_destroy(ctx);
5103 * Are they asking to set the owner?
5105 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5106 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5110 talloc_asprintf(ctx, "%s:%s",
5111 name+19, (const char *) value);
5115 ret = -1; /* errno set by smbc_server() */
5117 else if (! namevalue) {
5121 ret = cacl_set(ctx, &srv->cli,
5122 &ipc_srv->cli, &pol, path,
5123 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5125 talloc_destroy(ctx);
5130 * Are they asking to set the group?
5132 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5133 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5137 talloc_asprintf(ctx, "%s:%s",
5138 name+19, (const char *) value);
5141 /* errno set by smbc_server() */
5144 else if (! namevalue) {
5148 ret = cacl_set(ctx, &srv->cli,
5149 &ipc_srv->cli, &pol, path,
5150 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5152 talloc_destroy(ctx);
5157 * Are they asking to set a DOS attribute?
5159 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5160 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5161 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5162 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5163 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
5165 /* get a DOS Attribute Descriptor with current attributes */
5166 dad = dos_attr_query(context, ctx, path, srv);
5169 talloc_asprintf(ctx, "%s:%s",
5170 name+16, (const char *) value);
5175 /* Overwrite old with provided new params */
5176 dos_attr_parse(context, dad, srv, namevalue);
5178 /* Set the new DOS attributes */
5179 ret2 = smbc_setatr(context, srv, path,
5185 /* ret2 has True (success) / False (failure) */
5196 talloc_destroy(ctx);
5200 /* Unsupported attribute name */
5201 talloc_destroy(ctx);
5207 smbc_getxattr_ctx(SMBCCTX *context,
5226 if (!context || !context->internal ||
5227 !context->internal->_initialized) {
5229 errno = EINVAL; /* Best I can think of ... */
5241 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5243 if (smbc_parse_path(context, fname,
5244 server, sizeof(server),
5245 share, sizeof(share),
5248 password, sizeof(password),
5254 if (user[0] == (char)0) fstrcpy(user, context->user);
5256 fstrcpy(workgroup, context->workgroup);
5258 srv = smbc_server(context, server, share, workgroup, user, password);
5260 return -1; /* errno set by smbc_server */
5263 if (! srv->no_nt_session) {
5264 ipc_srv = smbc_attr_server(context, server, share,
5265 workgroup, user, password,
5268 srv->no_nt_session = True;
5274 ctx = talloc_init("smbc:getxattr");
5280 /* Are they requesting a supported attribute? */
5281 if (StrCaseCmp(name, "system.*") == 0 ||
5282 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5283 StrCaseCmp(name, "system.*+") == 0 ||
5284 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5285 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5286 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5287 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5288 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5289 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5290 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5291 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5292 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5293 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5294 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5295 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5296 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5297 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5298 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5299 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5300 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5301 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5302 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
5303 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5306 ret = cacl_get(context, ctx, srv,
5307 ipc_srv == NULL ? NULL : &ipc_srv->cli,
5309 CONST_DISCARD(char *, name),
5310 CONST_DISCARD(char *, value), size);
5311 if (ret < 0 && errno == 0) {
5312 errno = smbc_errno(context, &srv->cli);
5314 talloc_destroy(ctx);
5318 /* Unsupported attribute name */
5319 talloc_destroy(ctx);
5326 smbc_removexattr_ctx(SMBCCTX *context,
5342 if (!context || !context->internal ||
5343 !context->internal->_initialized) {
5345 errno = EINVAL; /* Best I can think of ... */
5357 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5359 if (smbc_parse_path(context, fname,
5360 server, sizeof(server),
5361 share, sizeof(share),
5364 password, sizeof(password),
5370 if (user[0] == (char)0) fstrcpy(user, context->user);
5372 fstrcpy(workgroup, context->workgroup);
5374 srv = smbc_server(context, server, share, workgroup, user, password);
5376 return -1; /* errno set by smbc_server */
5379 if (! srv->no_nt_session) {
5380 ipc_srv = smbc_attr_server(context, server, share,
5381 workgroup, user, password,
5383 srv->no_nt_session = True;
5389 return -1; /* errno set by smbc_attr_server */
5392 ctx = talloc_init("smbc_removexattr");
5398 /* Are they asking to set the entire ACL? */
5399 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5400 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5403 ret = cacl_set(ctx, &srv->cli,
5404 &ipc_srv->cli, &pol, path,
5405 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5406 talloc_destroy(ctx);
5411 * Are they asking to remove one or more spceific security descriptor
5414 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5415 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5416 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5417 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5418 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5419 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5420 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5423 ret = cacl_set(ctx, &srv->cli,
5424 &ipc_srv->cli, &pol, path,
5425 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5426 talloc_destroy(ctx);
5430 /* Unsupported attribute name */
5431 talloc_destroy(ctx);
5437 smbc_listxattr_ctx(SMBCCTX *context,
5443 * This isn't quite what listxattr() is supposed to do. This returns
5444 * the complete set of attribute names, always, rather than only those
5445 * attribute names which actually exist for a file. Hmmm...
5447 const char supported[] =
5450 "system.nt_sec_desc.revision\0"
5451 "system.nt_sec_desc.owner\0"
5452 "system.nt_sec_desc.owner+\0"
5453 "system.nt_sec_desc.group\0"
5454 "system.nt_sec_desc.group+\0"
5455 "system.nt_sec_desc.acl.*\0"
5456 "system.nt_sec_desc.acl\0"
5457 "system.nt_sec_desc.acl+\0"
5458 "system.nt_sec_desc.*\0"
5459 "system.nt_sec_desc.*+\0"
5460 "system.dos_attr.*\0"
5461 "system.dos_attr.mode\0"
5462 "system.dos_attr.c_time\0"
5463 "system.dos_attr.a_time\0"
5464 "system.dos_attr.m_time\0"
5468 return sizeof(supported);
5471 if (sizeof(supported) > size) {
5476 /* this can't be strcpy() because there are embedded null characters */
5477 memcpy(list, supported, sizeof(supported));
5478 return sizeof(supported);
5483 * Open a print file to be written to by other calls
5487 smbc_open_print_job_ctx(SMBCCTX *context,
5496 if (!context || !context->internal ||
5497 !context->internal->_initialized) {
5511 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5513 if (smbc_parse_path(context, fname,
5514 server, sizeof(server),
5515 share, sizeof(share),
5518 password, sizeof(password),
5524 /* What if the path is empty, or the file exists? */
5526 return context->open(context, fname, O_WRONLY, 666);
5531 * Routine to print a file on a remote server ...
5533 * We open the file, which we assume to be on a remote server, and then
5534 * copy it to a print file on the share specified by printq.
5538 smbc_print_file_ctx(SMBCCTX *c_file,
5550 if (!c_file || !c_file->internal->_initialized || !c_print ||
5551 !c_print->internal->_initialized) {
5558 if (!fname && !printq) {
5565 /* Try to open the file for reading ... */
5567 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5569 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5570 return -1; /* smbc_open sets errno */
5574 /* Now, try to open the printer file for writing */
5576 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5578 saverr = errno; /* Save errno */
5579 c_file->close_fn(c_file, fid1);
5585 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5589 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5592 c_file->close_fn(c_file, fid1);
5593 c_print->close_fn(c_print, fid2);
5602 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5603 c_print->close_fn(c_print, fid2);
5617 * Routine to list print jobs on a printer share ...
5621 smbc_list_print_jobs_ctx(SMBCCTX *context,
5623 smbc_list_print_job_fn fn)
5633 if (!context || !context->internal ||
5634 !context->internal->_initialized) {
5648 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5650 if (smbc_parse_path(context, fname,
5651 server, sizeof(server),
5652 share, sizeof(share),
5655 password, sizeof(password),
5661 if (user[0] == (char)0) fstrcpy(user, context->user);
5663 fstrcpy(workgroup, context->workgroup);
5665 srv = smbc_server(context, server, share, workgroup, user, password);
5669 return -1; /* errno set by smbc_server */
5673 if (cli_print_queue(&srv->cli,
5674 (void (*)(struct print_job_info *))fn) < 0) {
5676 errno = smbc_errno(context, &srv->cli);
5686 * Delete a print job from a remote printer share
5690 smbc_unlink_print_job_ctx(SMBCCTX *context,
5703 if (!context || !context->internal ||
5704 !context->internal->_initialized) {
5718 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5720 if (smbc_parse_path(context, fname,
5721 server, sizeof(server),
5722 share, sizeof(share),
5725 password, sizeof(password),
5731 if (user[0] == (char)0) fstrcpy(user, context->user);
5733 fstrcpy(workgroup, context->workgroup);
5735 srv = smbc_server(context, server, share, workgroup, user, password);
5739 return -1; /* errno set by smbc_server */
5743 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5746 errno = smbc_errno(context, &srv->cli);
5747 else if (err == ERRnosuchprintjob)
5758 * Get a new empty handle to fill in with your own info
5761 smbc_new_context(void)
5765 context = SMB_MALLOC_P(SMBCCTX);
5771 ZERO_STRUCTP(context);
5773 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5774 if (!context->internal) {
5779 ZERO_STRUCTP(context->internal);
5782 /* ADD REASONABLE DEFAULTS */
5784 context->timeout = 20000; /* 20 seconds */
5786 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5787 context->options.urlencode_readdir_entries = False;/* backward compat */
5788 context->options.one_share_per_server = False;/* backward compat */
5790 context->open = smbc_open_ctx;
5791 context->creat = smbc_creat_ctx;
5792 context->read = smbc_read_ctx;
5793 context->write = smbc_write_ctx;
5794 context->close_fn = smbc_close_ctx;
5795 context->unlink = smbc_unlink_ctx;
5796 context->rename = smbc_rename_ctx;
5797 context->lseek = smbc_lseek_ctx;
5798 context->stat = smbc_stat_ctx;
5799 context->fstat = smbc_fstat_ctx;
5800 context->opendir = smbc_opendir_ctx;
5801 context->closedir = smbc_closedir_ctx;
5802 context->readdir = smbc_readdir_ctx;
5803 context->getdents = smbc_getdents_ctx;
5804 context->mkdir = smbc_mkdir_ctx;
5805 context->rmdir = smbc_rmdir_ctx;
5806 context->telldir = smbc_telldir_ctx;
5807 context->lseekdir = smbc_lseekdir_ctx;
5808 context->fstatdir = smbc_fstatdir_ctx;
5809 context->chmod = smbc_chmod_ctx;
5810 context->utimes = smbc_utimes_ctx;
5811 context->setxattr = smbc_setxattr_ctx;
5812 context->getxattr = smbc_getxattr_ctx;
5813 context->removexattr = smbc_removexattr_ctx;
5814 context->listxattr = smbc_listxattr_ctx;
5815 context->open_print_job = smbc_open_print_job_ctx;
5816 context->print_file = smbc_print_file_ctx;
5817 context->list_print_jobs = smbc_list_print_jobs_ctx;
5818 context->unlink_print_job = smbc_unlink_print_job_ctx;
5820 context->callbacks.check_server_fn = smbc_check_server;
5821 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5823 smbc_default_cache_functions(context);
5831 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5832 * and thus you'll be leaking memory if not handled properly.
5836 smbc_free_context(SMBCCTX *context,
5846 DEBUG(1,("Performing aggressive shutdown.\n"));
5848 f = context->internal->_files;
5850 context->close_fn(context, f);
5853 context->internal->_files = NULL;
5855 /* First try to remove the servers the nice way. */
5856 if (context->callbacks.purge_cached_fn(context)) {
5859 DEBUG(1, ("Could not purge all servers, "
5860 "Nice way shutdown failed.\n"));
5861 s = context->internal->_servers;
5863 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
5865 cli_shutdown(&s->cli);
5866 context->callbacks.remove_cached_srv_fn(context,
5869 DLIST_REMOVE(context->internal->_servers, s);
5873 context->internal->_servers = NULL;
5877 /* This is the polite way */
5878 if (context->callbacks.purge_cached_fn(context)) {
5879 DEBUG(1, ("Could not purge all servers, "
5880 "free_context failed.\n"));
5884 if (context->internal->_servers) {
5885 DEBUG(1, ("Active servers in context, "
5886 "free_context failed.\n"));
5890 if (context->internal->_files) {
5891 DEBUG(1, ("Active files in context, "
5892 "free_context failed.\n"));
5898 /* Things we have to clean up */
5899 SAFE_FREE(context->workgroup);
5900 SAFE_FREE(context->netbios_name);
5901 SAFE_FREE(context->user);
5903 DEBUG(3, ("Context %p succesfully freed\n", context));
5904 SAFE_FREE(context->internal);
5911 * Initialise the library etc
5913 * We accept a struct containing handle information.
5914 * valid values for info->debug from 0 to 100,
5915 * and insist that info->fn must be non-null.
5918 smbc_init_context(SMBCCTX *context)
5925 if (!context || !context->internal) {
5930 /* Do not initialise the same client twice */
5931 if (context->internal->_initialized) {
5935 if (!context->callbacks.auth_fn ||
5936 context->debug < 0 ||
5937 context->debug > 100) {
5944 if (!smbc_initialized) {
5946 * Do some library-wide intializations the first time we get
5949 BOOL conf_loaded = False;
5951 /* Set this to what the user wants */
5952 DEBUGLEVEL = context->debug;
5954 setup_logging( "libsmbclient", True);
5956 /* Here we would open the smb.conf file if needed ... */
5958 in_client = True; /* FIXME, make a param */
5960 home = getenv("HOME");
5962 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5963 if (lp_load(conf, True, False, False)) {
5966 DEBUG(5, ("Could not load config file: %s\n",
5973 * Well, if that failed, try the dyn_CONFIGFILE
5974 * Which points to the standard locn, and if that
5975 * fails, silently ignore it and use the internal
5979 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
5980 DEBUG(5, ("Could not load config file: %s\n",
5984 * We loaded the global config file. Now lets
5985 * load user-specific modifications to the
5988 slprintf(conf, sizeof(conf),
5989 "%s/.smb/smb.conf.append", home);
5990 if (!lp_load(conf, True, False, False)) {
5992 ("Could not append config file: "
5999 load_interfaces(); /* Load the list of interfaces ... */
6001 reopen_logs(); /* Get logging working ... */
6004 * Block SIGPIPE (from lib/util_sock.c: write())
6005 * It is not needed and should not stop execution
6007 BlockSignals(True, SIGPIPE);
6009 /* Done with one-time initialisation */
6010 smbc_initialized = 1;
6014 if (!context->user) {
6016 * FIXME: Is this the best way to get the user info?
6018 user = getenv("USER");
6019 /* walk around as "guest" if no username can be found */
6020 if (!user) context->user = SMB_STRDUP("guest");
6021 else context->user = SMB_STRDUP(user);
6024 if (!context->netbios_name) {
6026 * We try to get our netbios name from the config. If that
6027 * fails we fall back on constructing our netbios name from
6030 if (global_myname()) {
6031 context->netbios_name = SMB_STRDUP(global_myname());
6035 * Hmmm, I want to get hostname as well, but I am too
6036 * lazy for the moment
6039 context->netbios_name = SMB_MALLOC(17);
6040 if (!context->netbios_name) {
6044 slprintf(context->netbios_name, 16,
6045 "smbc%s%d", context->user, pid);
6049 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
6051 if (!context->workgroup) {
6052 if (lp_workgroup()) {
6053 context->workgroup = SMB_STRDUP(lp_workgroup());
6056 /* TODO: Think about a decent default workgroup */
6057 context->workgroup = SMB_STRDUP("samba");
6061 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
6063 /* shortest timeout is 1 second */
6064 if (context->timeout > 0 && context->timeout < 1000)
6065 context->timeout = 1000;
6068 * FIXME: Should we check the function pointers here?
6071 context->internal->_initialized = 1;
6077 /* Return the verion of samba, and thus libsmbclient */
6081 return samba_version_string();