Fix some warnings
[Samba.git] / source3 / libsmb / libsmbclient.c
blobdbc51d168eb50441c9300ad5e8604225b911c191
1 /*
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 3 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, see <http://www.gnu.org/licenses/>.
24 #include "includes.h"
26 #include "include/libsmb_internal.h"
28 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir);
29 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
30 struct smbc_dirent *dirent);
33 * DOS Attribute values (used internally)
35 typedef struct DOS_ATTR_DESC {
36 int mode;
37 SMB_OFF_T size;
38 time_t create_time;
39 time_t access_time;
40 time_t write_time;
41 time_t change_time;
42 SMB_INO_T inode;
43 } DOS_ATTR_DESC;
47 * Internal flags for extended attributes
50 /* internal mode values */
51 #define SMBC_XATTR_MODE_ADD 1
52 #define SMBC_XATTR_MODE_REMOVE 2
53 #define SMBC_XATTR_MODE_REMOVE_ALL 3
54 #define SMBC_XATTR_MODE_SET 4
55 #define SMBC_XATTR_MODE_CHOWN 5
56 #define SMBC_XATTR_MODE_CHGRP 6
58 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
60 /*We should test for this in configure ... */
61 #ifndef ENOTSUP
62 #define ENOTSUP EOPNOTSUPP
63 #endif
66 * Functions exported by libsmb_cache.c that we need here
68 int smbc_default_cache_functions(SMBCCTX *context);
70 /*
71 * check if an element is part of the list.
72 * FIXME: Does not belong here !
73 * Can anyone put this in a macro in dlinklist.h ?
74 * -- Tom
76 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
77 if (!p || !list) return False;
78 do {
79 if (p == list) return True;
80 list = list->next;
81 } while (list);
82 return False;
86 * Find an lsa pipe handle associated with a cli struct.
88 static struct rpc_pipe_client *
89 find_lsa_pipe_hnd(struct cli_state *ipc_cli)
91 struct rpc_pipe_client *pipe_hnd;
93 for (pipe_hnd = ipc_cli->pipe_list;
94 pipe_hnd;
95 pipe_hnd = pipe_hnd->next) {
97 if (pipe_hnd->pipe_idx == PI_LSARPC) {
98 return pipe_hnd;
102 return NULL;
105 static int
106 smbc_close_ctx(SMBCCTX *context,
107 SMBCFILE *file);
108 static off_t
109 smbc_lseek_ctx(SMBCCTX *context,
110 SMBCFILE *file,
111 off_t offset,
112 int whence);
114 extern bool in_client;
117 * Is the logging working / configfile read ?
119 static int smbc_initialized = 0;
121 static int
122 hex2int( unsigned int _char )
124 if ( _char >= 'A' && _char <='F')
125 return _char - 'A' + 10;
126 if ( _char >= 'a' && _char <='f')
127 return _char - 'a' + 10;
128 if ( _char >= '0' && _char <='9')
129 return _char - '0';
130 return -1;
134 * smbc_urldecode()
136 * Convert strings of %xx to their single character equivalent. Each 'x' must
137 * be a valid hexadecimal digit, or that % sequence is left undecoded.
139 * dest may, but need not be, the same pointer as src.
141 * Returns the number of % sequences which could not be converted due to lack
142 * of two following hexadecimal digits.
145 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
147 int old_length = strlen(src);
148 int i = 0;
149 int err_count = 0;
150 pstring temp;
151 char * p;
153 if ( old_length == 0 ) {
154 return 0;
157 p = temp;
158 while ( i < old_length ) {
159 unsigned char character = src[ i++ ];
161 if (character == '%') {
162 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
163 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
165 /* Replace valid sequence */
166 if (a != -1 && b != -1) {
168 /* Replace valid %xx sequence with %dd */
169 character = (a * 16) + b;
171 if (character == '\0') {
172 break; /* Stop at %00 */
175 i += 2;
176 } else {
178 err_count++;
182 *p++ = character;
185 *p = '\0';
187 strncpy(dest, temp, max_dest_len - 1);
188 dest[max_dest_len - 1] = '\0';
190 return err_count;
194 * smbc_urlencode()
196 * Convert any characters not specifically allowed in a URL into their %xx
197 * equivalent.
199 * Returns the remaining buffer length.
202 smbc_urlencode(char * dest, char * src, int max_dest_len)
204 char hex[] = "0123456789ABCDEF";
206 for (; *src != '\0' && max_dest_len >= 3; src++) {
208 if ((*src < '0' &&
209 *src != '-' &&
210 *src != '.') ||
211 (*src > '9' &&
212 *src < 'A') ||
213 (*src > 'Z' &&
214 *src < 'a' &&
215 *src != '_') ||
216 (*src > 'z')) {
217 *dest++ = '%';
218 *dest++ = hex[(*src >> 4) & 0x0f];
219 *dest++ = hex[*src & 0x0f];
220 max_dest_len -= 3;
221 } else {
222 *dest++ = *src;
223 max_dest_len--;
227 *dest++ = '\0';
228 max_dest_len--;
230 return max_dest_len;
234 * Function to parse a path and turn it into components
236 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
237 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
238 * general format ("smb:" only; we do not look for "cifs:").
241 * We accept:
242 * smb://[[[domain;]user[:password]@]server[/share[/path[/file]]]][?options]
244 * Meaning of URLs:
246 * smb:// Show all workgroups.
248 * The method of locating the list of workgroups varies
249 * depending upon the setting of the context variable
250 * context->options.browse_max_lmb_count. This value
251 * determine the maximum number of local master browsers to
252 * query for the list of workgroups. In order to ensure that
253 * a complete list of workgroups is obtained, all master
254 * browsers must be queried, but if there are many
255 * workgroups, the time spent querying can begin to add up.
256 * For small networks (not many workgroups), it is suggested
257 * that this variable be set to 0, indicating query all local
258 * master browsers. When the network has many workgroups, a
259 * reasonable setting for this variable might be around 3.
261 * smb://name/ if name<1D> or name<1B> exists, list servers in
262 * workgroup, else, if name<20> exists, list all shares
263 * for server ...
265 * If "options" are provided, this function returns the entire option list as a
266 * string, for later parsing by the caller. Note that currently, no options
267 * are supported.
270 static const char *smbc_prefix = "smb:";
272 static int
273 smbc_parse_path(SMBCCTX *context,
274 const char *fname,
275 char *workgroup, int workgroup_len,
276 char *server, int server_len,
277 char *share, int share_len,
278 char *path, int path_len,
279 char *user, int user_len,
280 char *password, int password_len,
281 char *options, int options_len)
283 static pstring s;
284 pstring userinfo;
285 const char *p;
286 char *q, *r;
287 int len;
289 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
292 * Assume we wont find an authentication domain to parse, so default
293 * to the workgroup in the provided context.
295 if (workgroup != NULL) {
296 strncpy(workgroup, context->workgroup, workgroup_len - 1);
297 workgroup[workgroup_len - 1] = '\0';
300 if (options != NULL && options_len > 0) {
301 options[0] = (char)0;
303 pstrcpy(s, fname);
305 /* see if it has the right prefix */
306 len = strlen(smbc_prefix);
307 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
308 return -1; /* What about no smb: ? */
311 p = s + len;
313 /* Watch the test below, we are testing to see if we should exit */
315 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
317 DEBUG(1, ("Invalid path (does not begin with smb://"));
318 return -1;
322 p += 2; /* Skip the double slash */
324 /* See if any options were specified */
325 if ((q = strrchr(p, '?')) != NULL ) {
326 /* There are options. Null terminate here and point to them */
327 *q++ = '\0';
329 DEBUG(4, ("Found options '%s'", q));
331 /* Copy the options */
332 if (options != NULL && options_len > 0) {
333 safe_strcpy(options, q, options_len - 1);
337 if (*p == (char)0)
338 goto decoding;
340 if (*p == '/') {
341 int wl = strlen(context->workgroup);
343 if (wl > 16) {
344 wl = 16;
347 strncpy(server, context->workgroup, wl);
348 server[wl] = '\0';
349 return 0;
353 * ok, its for us. Now parse out the server, share etc.
355 * However, we want to parse out [[domain;]user[:password]@] if it
356 * exists ...
359 /* check that '@' occurs before '/', if '/' exists at all */
360 q = strchr_m(p, '@');
361 r = strchr_m(p, '/');
362 if (q && (!r || q < r)) {
363 pstring username, passwd, domain;
364 const char *u = userinfo;
366 next_token_no_ltrim(&p, userinfo, "@", sizeof(fstring));
368 username[0] = passwd[0] = domain[0] = 0;
370 if (strchr_m(u, ';')) {
372 next_token_no_ltrim(&u, domain, ";", sizeof(fstring));
376 if (strchr_m(u, ':')) {
378 next_token_no_ltrim(&u, username, ":", sizeof(fstring));
380 pstrcpy(passwd, u);
383 else {
385 pstrcpy(username, u);
389 if (domain[0] && workgroup) {
390 strncpy(workgroup, domain, workgroup_len - 1);
391 workgroup[workgroup_len - 1] = '\0';
394 if (username[0]) {
395 strncpy(user, username, user_len - 1);
396 user[user_len - 1] = '\0';
399 if (passwd[0]) {
400 strncpy(password, passwd, password_len - 1);
401 password[password_len - 1] = '\0';
406 if (!next_token(&p, server, "/", sizeof(fstring))) {
408 return -1;
412 if (*p == (char)0) goto decoding; /* That's it ... */
414 if (!next_token(&p, share, "/", sizeof(fstring))) {
416 return -1;
421 * Prepend a leading slash if there's a file path, as required by
422 * NetApp filers.
424 *path = '\0';
425 if (*p != '\0') {
426 *path = '/';
427 safe_strcpy(path + 1, p, path_len - 2);
430 all_string_sub(path, "/", "\\", 0);
432 decoding:
433 (void) smbc_urldecode(path, path, path_len);
434 (void) smbc_urldecode(server, server, server_len);
435 (void) smbc_urldecode(share, share, share_len);
436 (void) smbc_urldecode(user, user, user_len);
437 (void) smbc_urldecode(password, password, password_len);
439 return 0;
443 * Verify that the options specified in a URL are valid
445 static int
446 smbc_check_options(char *server,
447 char *share,
448 char *path,
449 char *options)
451 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' "
452 "path='%s' options='%s'\n",
453 server, share, path, options));
455 /* No options at all is always ok */
456 if (! *options) return 0;
458 /* Currently, we don't support any options. */
459 return -1;
463 * Convert an SMB error into a UNIX error ...
465 static int
466 smbc_errno(SMBCCTX *context,
467 struct cli_state *c)
469 int ret = cli_errno(c);
471 if (cli_is_dos_error(c)) {
472 uint8 eclass;
473 uint32 ecode;
475 cli_dos_error(c, &eclass, &ecode);
477 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
478 (int)eclass, (int)ecode, (int)ecode, ret));
479 } else {
480 NTSTATUS status;
482 status = cli_nt_error(c);
484 DEBUG(3,("smbc errno %s -> %d\n",
485 nt_errstr(status), ret));
488 return ret;
492 * Check a server for being alive and well.
493 * returns 0 if the server is in shape. Returns 1 on error
495 * Also useable outside libsmbclient to enable external cache
496 * to do some checks too.
498 static int
499 smbc_check_server(SMBCCTX * context,
500 SMBCSRV * server)
502 socklen_t size;
503 struct sockaddr addr;
505 size = sizeof(addr);
506 return (getpeername(server->cli->fd, &addr, &size) == -1);
510 * Remove a server from the cached server list it's unused.
511 * On success, 0 is returned. 1 is returned if the server could not be removed.
513 * Also useable outside libsmbclient
516 smbc_remove_unused_server(SMBCCTX * context,
517 SMBCSRV * srv)
519 SMBCFILE * file;
521 /* are we being fooled ? */
522 if (!context || !context->internal ||
523 !context->internal->_initialized || !srv) return 1;
526 /* Check all open files/directories for a relation with this server */
527 for (file = context->internal->_files; file; file=file->next) {
528 if (file->srv == srv) {
529 /* Still used */
530 DEBUG(3, ("smbc_remove_usused_server: "
531 "%p still used by %p.\n",
532 srv, file));
533 return 1;
537 DLIST_REMOVE(context->internal->_servers, srv);
539 cli_shutdown(srv->cli);
540 srv->cli = NULL;
542 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
544 (context->callbacks.remove_cached_srv_fn)(context, srv);
546 SAFE_FREE(srv);
548 return 0;
551 static SMBCSRV *
552 find_server(SMBCCTX *context,
553 const char *server,
554 const char *share,
555 fstring workgroup,
556 fstring username,
557 fstring password)
559 SMBCSRV *srv;
560 int auth_called = 0;
562 check_server_cache:
564 srv = (context->callbacks.get_cached_srv_fn)(context, server, share,
565 workgroup, username);
567 if (!auth_called && !srv && (!username[0] || !password[0])) {
568 if (context->internal->_auth_fn_with_context != NULL) {
569 (context->internal->_auth_fn_with_context)(
570 context,
571 server, share,
572 workgroup, sizeof(fstring),
573 username, sizeof(fstring),
574 password, sizeof(fstring));
575 } else {
576 (context->callbacks.auth_fn)(
577 server, share,
578 workgroup, sizeof(fstring),
579 username, sizeof(fstring),
580 password, sizeof(fstring));
584 * However, smbc_auth_fn may have picked up info relating to
585 * an existing connection, so try for an existing connection
586 * again ...
588 auth_called = 1;
589 goto check_server_cache;
593 if (srv) {
594 if ((context->callbacks.check_server_fn)(context, srv)) {
596 * This server is no good anymore
597 * Try to remove it and check for more possible
598 * servers in the cache
600 if ((context->callbacks.remove_unused_server_fn)(context,
601 srv)) {
603 * We could not remove the server completely,
604 * remove it from the cache so we will not get
605 * it again. It will be removed when the last
606 * file/dir is closed.
608 (context->callbacks.remove_cached_srv_fn)(context,
609 srv);
613 * Maybe there are more cached connections to this
614 * server
616 goto check_server_cache;
619 return srv;
622 return NULL;
626 * Connect to a server, possibly on an existing connection
628 * Here, what we want to do is: If the server and username
629 * match an existing connection, reuse that, otherwise, establish a
630 * new connection.
632 * If we have to create a new connection, call the auth_fn to get the
633 * info we need, unless the username and password were passed in.
636 static SMBCSRV *
637 smbc_server(SMBCCTX *context,
638 bool connect_if_not_found,
639 const char *server,
640 const char *share,
641 fstring workgroup,
642 fstring username,
643 fstring password)
645 SMBCSRV *srv=NULL;
646 struct cli_state *c;
647 struct nmb_name called, calling;
648 const char *server_n = server;
649 pstring ipenv;
650 struct sockaddr_storage ss;
651 int tried_reverse = 0;
652 int port_try_first;
653 int port_try_next;
654 const char *username_used;
655 NTSTATUS status;
657 zero_addr(&ss);
658 ZERO_STRUCT(c);
660 if (server[0] == 0) {
661 errno = EPERM;
662 return NULL;
665 /* Look for a cached connection */
666 srv = find_server(context, server, share,
667 workgroup, username, password);
670 * If we found a connection and we're only allowed one share per
671 * server...
673 if (srv && *share != '\0' && context->options.one_share_per_server) {
676 * ... then if there's no current connection to the share,
677 * connect to it. find_server(), or rather the function
678 * pointed to by context->callbacks.get_cached_srv_fn which
679 * was called by find_server(), will have issued a tree
680 * disconnect if the requested share is not the same as the
681 * one that was already connected.
683 if (srv->cli->cnum == (uint16) -1) {
684 /* Ensure we have accurate auth info */
685 if (context->internal->_auth_fn_with_context != NULL) {
686 (context->internal->_auth_fn_with_context)(
687 context,
688 server, share,
689 workgroup, sizeof(fstring),
690 username, sizeof(fstring),
691 password, sizeof(fstring));
692 } else {
693 (context->callbacks.auth_fn)(
694 server, share,
695 workgroup, sizeof(fstring),
696 username, sizeof(fstring),
697 password, sizeof(fstring));
700 if (! cli_send_tconX(srv->cli, share, "?????",
701 password, strlen(password)+1)) {
703 errno = smbc_errno(context, srv->cli);
704 cli_shutdown(srv->cli);
705 srv->cli = NULL;
706 (context->callbacks.remove_cached_srv_fn)(context,
707 srv);
708 srv = NULL;
712 * Regenerate the dev value since it's based on both
713 * server and share
715 if (srv) {
716 srv->dev = (dev_t)(str_checksum(server) ^
717 str_checksum(share));
722 /* If we have a connection... */
723 if (srv) {
725 /* ... then we're done here. Give 'em what they came for. */
726 return srv;
729 /* If we're not asked to connect when a connection doesn't exist... */
730 if (! connect_if_not_found) {
731 /* ... then we're done here. */
732 return NULL;
735 make_nmb_name(&calling, context->netbios_name, 0x0);
736 make_nmb_name(&called , server, 0x20);
738 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
740 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
742 again:
743 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
745 zero_addr(&ss);
747 /* have to open a new connection */
748 if ((c = cli_initialise()) == NULL) {
749 errno = ENOMEM;
750 return NULL;
753 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
754 c->use_kerberos = True;
756 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
757 c->fallback_after_kerberos = True;
760 c->timeout = context->timeout;
763 * Force use of port 139 for first try if share is $IPC, empty, or
764 * null, so browse lists can work
766 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
767 port_try_first = 139;
768 port_try_next = 445;
769 } else {
770 port_try_first = 445;
771 port_try_next = 139;
774 c->port = port_try_first;
776 status = cli_connect(c, server_n, &ss);
777 if (!NT_STATUS_IS_OK(status)) {
779 /* First connection attempt failed. Try alternate port. */
780 c->port = port_try_next;
782 status = cli_connect(c, server_n, &ss);
783 if (!NT_STATUS_IS_OK(status)) {
784 cli_shutdown(c);
785 errno = ETIMEDOUT;
786 return NULL;
790 if (!cli_session_request(c, &calling, &called)) {
791 cli_shutdown(c);
792 if (strcmp(called.name, "*SMBSERVER")) {
793 make_nmb_name(&called , "*SMBSERVER", 0x20);
794 goto again;
795 } else { /* Try one more time, but ensure we don't loop */
797 /* Only try this if server is an IP address ... */
799 if (is_ipaddress(server) && !tried_reverse) {
800 fstring remote_name;
801 struct sockaddr_storage rem_ss;
803 if (!interpret_string_addr(&rem_ss, server,
804 NI_NUMERICHOST)) {
805 DEBUG(4, ("Could not convert IP address "
806 "%s to struct sockaddr_storage\n",
807 server));
808 errno = ETIMEDOUT;
809 return NULL;
812 tried_reverse++; /* Yuck */
814 if (name_status_find("*", 0, 0, &rem_ss, remote_name)) {
815 make_nmb_name(&called, remote_name, 0x20);
816 goto again;
820 errno = ETIMEDOUT;
821 return NULL;
824 DEBUG(4,(" session request ok\n"));
826 if (!cli_negprot(c)) {
827 cli_shutdown(c);
828 errno = ETIMEDOUT;
829 return NULL;
832 username_used = username;
834 if (!NT_STATUS_IS_OK(cli_session_setup(c, username_used,
835 password, strlen(password),
836 password, strlen(password),
837 workgroup))) {
839 /* Failed. Try an anonymous login, if allowed by flags. */
840 username_used = "";
842 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
843 !NT_STATUS_IS_OK(cli_session_setup(c, username_used,
844 password, 1,
845 password, 0,
846 workgroup))) {
848 cli_shutdown(c);
849 errno = EPERM;
850 return NULL;
854 DEBUG(4,(" session setup ok\n"));
856 if (!cli_send_tconX(c, share, "?????",
857 password, strlen(password)+1)) {
858 errno = smbc_errno(context, c);
859 cli_shutdown(c);
860 return NULL;
863 DEBUG(4,(" tconx ok\n"));
866 * Ok, we have got a nice connection
867 * Let's allocate a server structure.
870 srv = SMB_MALLOC_P(SMBCSRV);
871 if (!srv) {
872 errno = ENOMEM;
873 goto failed;
876 ZERO_STRUCTP(srv);
877 srv->cli = c;
878 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
879 srv->no_pathinfo = False;
880 srv->no_pathinfo2 = False;
881 srv->no_nt_session = False;
883 /* now add it to the cache (internal or external) */
884 /* Let the cache function set errno if it wants to */
885 errno = 0;
886 if ((context->callbacks.add_cached_srv_fn)(context, srv,
887 server, share,
888 workgroup, username)) {
889 int saved_errno = errno;
890 DEBUG(3, (" Failed to add server to cache\n"));
891 errno = saved_errno;
892 if (errno == 0) {
893 errno = ENOMEM;
895 goto failed;
898 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
899 server, share, srv));
901 DLIST_ADD(context->internal->_servers, srv);
902 return srv;
904 failed:
905 cli_shutdown(c);
906 if (!srv) {
907 return NULL;
910 SAFE_FREE(srv);
911 return NULL;
915 * Connect to a server for getting/setting attributes, possibly on an existing
916 * connection. This works similarly to smbc_server().
918 static SMBCSRV *
919 smbc_attr_server(SMBCCTX *context,
920 const char *server,
921 const char *share,
922 fstring workgroup,
923 fstring username,
924 fstring password,
925 POLICY_HND *pol)
927 int flags;
928 struct sockaddr_storage ss;
929 struct cli_state *ipc_cli;
930 struct rpc_pipe_client *pipe_hnd;
931 NTSTATUS nt_status;
932 SMBCSRV *ipc_srv=NULL;
935 * See if we've already created this special connection. Reference
936 * our "special" share name '*IPC$', which is an impossible real share
937 * name due to the leading asterisk.
939 ipc_srv = find_server(context, server, "*IPC$",
940 workgroup, username, password);
941 if (!ipc_srv) {
943 /* We didn't find a cached connection. Get the password */
944 if (*password == '\0') {
945 /* ... then retrieve it now. */
946 if (context->internal->_auth_fn_with_context != NULL) {
947 (context->internal->_auth_fn_with_context)(
948 context,
949 server, share,
950 workgroup, sizeof(fstring),
951 username, sizeof(fstring),
952 password, sizeof(fstring));
953 } else {
954 (context->callbacks.auth_fn)(
955 server, share,
956 workgroup, sizeof(fstring),
957 username, sizeof(fstring),
958 password, sizeof(fstring));
962 flags = 0;
963 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
964 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
967 zero_addr(&ss);
968 nt_status = cli_full_connection(&ipc_cli,
969 global_myname(), server,
970 &ss, 0, "IPC$", "?????",
971 username, workgroup,
972 password, flags,
973 Undefined, NULL);
974 if (! NT_STATUS_IS_OK(nt_status)) {
975 DEBUG(1,("cli_full_connection failed! (%s)\n",
976 nt_errstr(nt_status)));
977 errno = ENOTSUP;
978 return NULL;
981 ipc_srv = SMB_MALLOC_P(SMBCSRV);
982 if (!ipc_srv) {
983 errno = ENOMEM;
984 cli_shutdown(ipc_cli);
985 return NULL;
988 ZERO_STRUCTP(ipc_srv);
989 ipc_srv->cli = ipc_cli;
991 if (pol) {
992 pipe_hnd = cli_rpc_pipe_open_noauth(ipc_srv->cli,
993 PI_LSARPC,
994 &nt_status);
995 if (!pipe_hnd) {
996 DEBUG(1, ("cli_nt_session_open fail!\n"));
997 errno = ENOTSUP;
998 cli_shutdown(ipc_srv->cli);
999 free(ipc_srv);
1000 return NULL;
1004 * Some systems don't support
1005 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
1006 * so we might as well do it too.
1009 nt_status = rpccli_lsa_open_policy(
1010 pipe_hnd,
1011 ipc_srv->cli->mem_ctx,
1012 True,
1013 GENERIC_EXECUTE_ACCESS,
1014 pol);
1016 if (!NT_STATUS_IS_OK(nt_status)) {
1017 errno = smbc_errno(context, ipc_srv->cli);
1018 cli_shutdown(ipc_srv->cli);
1019 return NULL;
1023 /* now add it to the cache (internal or external) */
1025 errno = 0; /* let cache function set errno if it likes */
1026 if ((context->callbacks.add_cached_srv_fn)(context, ipc_srv,
1027 server,
1028 "*IPC$",
1029 workgroup,
1030 username)) {
1031 DEBUG(3, (" Failed to add server to cache\n"));
1032 if (errno == 0) {
1033 errno = ENOMEM;
1035 cli_shutdown(ipc_srv->cli);
1036 free(ipc_srv);
1037 return NULL;
1040 DLIST_ADD(context->internal->_servers, ipc_srv);
1043 return ipc_srv;
1047 * Routine to open() a file ...
1050 static SMBCFILE *
1051 smbc_open_ctx(SMBCCTX *context,
1052 const char *fname,
1053 int flags,
1054 mode_t mode)
1056 fstring server, share, user, password, workgroup;
1057 pstring path;
1058 pstring targetpath;
1059 struct cli_state *targetcli;
1060 SMBCSRV *srv = NULL;
1061 SMBCFILE *file = NULL;
1062 int fd;
1064 if (!context || !context->internal ||
1065 !context->internal->_initialized) {
1067 errno = EINVAL; /* Best I can think of ... */
1068 return NULL;
1072 if (!fname) {
1074 errno = EINVAL;
1075 return NULL;
1079 if (smbc_parse_path(context, fname,
1080 workgroup, sizeof(workgroup),
1081 server, sizeof(server),
1082 share, sizeof(share),
1083 path, sizeof(path),
1084 user, sizeof(user),
1085 password, sizeof(password),
1086 NULL, 0)) {
1087 errno = EINVAL;
1088 return NULL;
1091 if (user[0] == (char)0) fstrcpy(user, context->user);
1093 srv = smbc_server(context, True,
1094 server, share, workgroup, user, password);
1096 if (!srv) {
1098 if (errno == EPERM) errno = EACCES;
1099 return NULL; /* smbc_server sets errno */
1103 /* Hmmm, the test for a directory is suspect here ... FIXME */
1105 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1107 fd = -1;
1110 else {
1112 file = SMB_MALLOC_P(SMBCFILE);
1114 if (!file) {
1116 errno = ENOMEM;
1117 return NULL;
1121 ZERO_STRUCTP(file);
1123 /*d_printf(">>>open: resolving %s\n", path);*/
1124 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1126 d_printf("Could not resolve %s\n", path);
1127 SAFE_FREE(file);
1128 return NULL;
1130 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1132 if ((fd = cli_open(targetcli, targetpath, flags,
1133 context->internal->_share_mode)) < 0) {
1135 /* Handle the error ... */
1137 SAFE_FREE(file);
1138 errno = smbc_errno(context, targetcli);
1139 return NULL;
1143 /* Fill in file struct */
1145 file->cli_fd = fd;
1146 file->fname = SMB_STRDUP(fname);
1147 file->srv = srv;
1148 file->offset = 0;
1149 file->file = True;
1151 DLIST_ADD(context->internal->_files, file);
1154 * If the file was opened in O_APPEND mode, all write
1155 * operations should be appended to the file. To do that,
1156 * though, using this protocol, would require a getattrE()
1157 * call for each and every write, to determine where the end
1158 * of the file is. (There does not appear to be an append flag
1159 * in the protocol.) Rather than add all of that overhead of
1160 * retrieving the current end-of-file offset prior to each
1161 * write operation, we'll assume that most append operations
1162 * will continuously write, so we'll just set the offset to
1163 * the end of the file now and hope that's adequate.
1165 * Note to self: If this proves inadequate, and O_APPEND
1166 * should, in some cases, be forced for each write, add a
1167 * field in the context options structure, for
1168 * "strict_append_mode" which would select between the current
1169 * behavior (if FALSE) or issuing a getattrE() prior to each
1170 * write and forcing the write to the end of the file (if
1171 * TRUE). Adding that capability will likely require adding
1172 * an "append" flag into the _SMBCFILE structure to track
1173 * whether a file was opened in O_APPEND mode. -- djl
1175 if (flags & O_APPEND) {
1176 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1177 (void) smbc_close_ctx(context, file);
1178 errno = ENXIO;
1179 return NULL;
1183 return file;
1187 /* Check if opendir needed ... */
1189 if (fd == -1) {
1190 int eno = 0;
1192 eno = smbc_errno(context, srv->cli);
1193 file = (context->opendir)(context, fname);
1194 if (!file) errno = eno;
1195 return file;
1199 errno = EINVAL; /* FIXME, correct errno ? */
1200 return NULL;
1205 * Routine to create a file
1208 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1210 static SMBCFILE *
1211 smbc_creat_ctx(SMBCCTX *context,
1212 const char *path,
1213 mode_t mode)
1216 if (!context || !context->internal ||
1217 !context->internal->_initialized) {
1219 errno = EINVAL;
1220 return NULL;
1224 return smbc_open_ctx(context, path, creat_bits, mode);
1228 * Routine to read() a file ...
1231 static ssize_t
1232 smbc_read_ctx(SMBCCTX *context,
1233 SMBCFILE *file,
1234 void *buf,
1235 size_t count)
1237 int ret;
1238 fstring server, share, user, password;
1239 pstring path, targetpath;
1240 struct cli_state *targetcli;
1243 * offset:
1245 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1246 * appears to pass file->offset (which is type off_t) differently than
1247 * a local variable of type off_t. Using local variable "offset" in
1248 * the call to cli_read() instead of file->offset fixes a problem
1249 * retrieving data at an offset greater than 4GB.
1251 off_t offset;
1253 if (!context || !context->internal ||
1254 !context->internal->_initialized) {
1256 errno = EINVAL;
1257 return -1;
1261 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1263 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1265 errno = EBADF;
1266 return -1;
1270 offset = file->offset;
1272 /* Check that the buffer exists ... */
1274 if (buf == NULL) {
1276 errno = EINVAL;
1277 return -1;
1281 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1282 if (smbc_parse_path(context, file->fname,
1283 NULL, 0,
1284 server, sizeof(server),
1285 share, sizeof(share),
1286 path, sizeof(path),
1287 user, sizeof(user),
1288 password, sizeof(password),
1289 NULL, 0)) {
1290 errno = EINVAL;
1291 return -1;
1294 /*d_printf(">>>read: resolving %s\n", path);*/
1295 if (!cli_resolve_path("", file->srv->cli, path,
1296 &targetcli, targetpath))
1298 d_printf("Could not resolve %s\n", path);
1299 return -1;
1301 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1303 ret = cli_read(targetcli, file->cli_fd, (char *)buf, offset, count);
1305 if (ret < 0) {
1307 errno = smbc_errno(context, targetcli);
1308 return -1;
1312 file->offset += ret;
1314 DEBUG(4, (" --> %d\n", ret));
1316 return ret; /* Success, ret bytes of data ... */
1321 * Routine to write() a file ...
1324 static ssize_t
1325 smbc_write_ctx(SMBCCTX *context,
1326 SMBCFILE *file,
1327 void *buf,
1328 size_t count)
1330 int ret;
1331 off_t offset;
1332 fstring server, share, user, password;
1333 pstring path, targetpath;
1334 struct cli_state *targetcli;
1336 /* First check all pointers before dereferencing them */
1338 if (!context || !context->internal ||
1339 !context->internal->_initialized) {
1341 errno = EINVAL;
1342 return -1;
1346 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1348 errno = EBADF;
1349 return -1;
1353 /* Check that the buffer exists ... */
1355 if (buf == NULL) {
1357 errno = EINVAL;
1358 return -1;
1362 offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1364 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1365 if (smbc_parse_path(context, file->fname,
1366 NULL, 0,
1367 server, sizeof(server),
1368 share, sizeof(share),
1369 path, sizeof(path),
1370 user, sizeof(user),
1371 password, sizeof(password),
1372 NULL, 0)) {
1373 errno = EINVAL;
1374 return -1;
1377 /*d_printf(">>>write: resolving %s\n", path);*/
1378 if (!cli_resolve_path("", file->srv->cli, path,
1379 &targetcli, targetpath))
1381 d_printf("Could not resolve %s\n", path);
1382 return -1;
1384 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1387 ret = cli_write(targetcli, file->cli_fd, 0, (char *)buf, offset, count);
1389 if (ret <= 0) {
1391 errno = smbc_errno(context, targetcli);
1392 return -1;
1396 file->offset += ret;
1398 return ret; /* Success, 0 bytes of data ... */
1402 * Routine to close() a file ...
1405 static int
1406 smbc_close_ctx(SMBCCTX *context,
1407 SMBCFILE *file)
1409 SMBCSRV *srv;
1410 fstring server, share, user, password;
1411 pstring path, targetpath;
1412 struct cli_state *targetcli;
1414 if (!context || !context->internal ||
1415 !context->internal->_initialized) {
1417 errno = EINVAL;
1418 return -1;
1422 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1424 errno = EBADF;
1425 return -1;
1429 /* IS a dir ... */
1430 if (!file->file) {
1432 return (context->closedir)(context, file);
1436 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1437 if (smbc_parse_path(context, file->fname,
1438 NULL, 0,
1439 server, sizeof(server),
1440 share, sizeof(share),
1441 path, sizeof(path),
1442 user, sizeof(user),
1443 password, sizeof(password),
1444 NULL, 0)) {
1445 errno = EINVAL;
1446 return -1;
1449 /*d_printf(">>>close: resolving %s\n", path);*/
1450 if (!cli_resolve_path("", file->srv->cli, path,
1451 &targetcli, targetpath))
1453 d_printf("Could not resolve %s\n", path);
1454 return -1;
1456 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1458 if (!cli_close(targetcli, file->cli_fd)) {
1460 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1461 file->fname));
1462 /* Deallocate slot and remove the server
1463 * from the server cache if unused */
1464 errno = smbc_errno(context, targetcli);
1465 srv = file->srv;
1466 DLIST_REMOVE(context->internal->_files, file);
1467 SAFE_FREE(file->fname);
1468 SAFE_FREE(file);
1469 (context->callbacks.remove_unused_server_fn)(context, srv);
1471 return -1;
1475 DLIST_REMOVE(context->internal->_files, file);
1476 SAFE_FREE(file->fname);
1477 SAFE_FREE(file);
1479 return 0;
1483 * Get info from an SMB server on a file. Use a qpathinfo call first
1484 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1486 static bool
1487 smbc_getatr(SMBCCTX * context,
1488 SMBCSRV *srv,
1489 char *path,
1490 uint16 *mode,
1491 SMB_OFF_T *size,
1492 struct timespec *create_time_ts,
1493 struct timespec *access_time_ts,
1494 struct timespec *write_time_ts,
1495 struct timespec *change_time_ts,
1496 SMB_INO_T *ino)
1498 pstring fixedpath;
1499 pstring targetpath;
1500 struct cli_state *targetcli;
1501 time_t write_time;
1503 if (!context || !context->internal ||
1504 !context->internal->_initialized) {
1506 errno = EINVAL;
1507 return -1;
1511 /* path fixup for . and .. */
1512 if (strequal(path, ".") || strequal(path, ".."))
1513 pstrcpy(fixedpath, "\\");
1514 else
1516 pstrcpy(fixedpath, path);
1517 trim_string(fixedpath, NULL, "\\..");
1518 trim_string(fixedpath, NULL, "\\.");
1520 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1522 if (!cli_resolve_path( "", srv->cli, fixedpath, &targetcli, targetpath))
1524 d_printf("Couldn't resolve %s\n", path);
1525 return False;
1528 if (!srv->no_pathinfo2 &&
1529 cli_qpathinfo2(targetcli, targetpath,
1530 create_time_ts,
1531 access_time_ts,
1532 write_time_ts,
1533 change_time_ts,
1534 size, mode, ino)) {
1535 return True;
1538 /* if this is NT then don't bother with the getatr */
1539 if (targetcli->capabilities & CAP_NT_SMBS) {
1540 errno = EPERM;
1541 return False;
1544 if (cli_getatr(targetcli, targetpath, mode, size, &write_time)) {
1546 struct timespec w_time_ts;
1548 w_time_ts = convert_time_t_to_timespec(write_time);
1550 if (write_time_ts != NULL) {
1551 *write_time_ts = w_time_ts;
1554 if (create_time_ts != NULL) {
1555 *create_time_ts = w_time_ts;
1558 if (access_time_ts != NULL) {
1559 *access_time_ts = w_time_ts;
1562 if (change_time_ts != NULL) {
1563 *change_time_ts = w_time_ts;
1566 srv->no_pathinfo2 = True;
1567 return True;
1570 errno = EPERM;
1571 return False;
1576 * Set file info on an SMB server. Use setpathinfo call first. If that
1577 * fails, use setattrE..
1579 * Access and modification time parameters are always used and must be
1580 * provided. Create time, if zero, will be determined from the actual create
1581 * time of the file. If non-zero, the create time will be set as well.
1583 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1585 static bool
1586 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1587 time_t create_time,
1588 time_t access_time,
1589 time_t write_time,
1590 time_t change_time,
1591 uint16 mode)
1593 int fd;
1594 int ret;
1597 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1598 * modern function for "new code" to be using, and it works given a
1599 * filename rather than requiring that the file be opened to have its
1600 * attributes manipulated.
1602 if (srv->no_pathinfo ||
1603 ! cli_setpathinfo(srv->cli, path,
1604 create_time,
1605 access_time,
1606 write_time,
1607 change_time,
1608 mode)) {
1611 * setpathinfo is not supported; go to plan B.
1613 * cli_setatr() does not work on win98, and it also doesn't
1614 * support setting the access time (only the modification
1615 * time), so in all cases, we open the specified file and use
1616 * cli_setattrE() which should work on all OS versions, and
1617 * supports both times.
1620 /* Don't try {q,set}pathinfo() again, with this server */
1621 srv->no_pathinfo = True;
1623 /* Open the file */
1624 if ((fd = cli_open(srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1626 errno = smbc_errno(context, srv->cli);
1627 return -1;
1630 /* Set the new attributes */
1631 ret = cli_setattrE(srv->cli, fd,
1632 change_time,
1633 access_time,
1634 write_time);
1636 /* Close the file */
1637 cli_close(srv->cli, fd);
1640 * Unfortunately, setattrE() doesn't have a provision for
1641 * setting the access mode (attributes). We'll have to try
1642 * cli_setatr() for that, and with only this parameter, it
1643 * seems to work on win98.
1645 if (ret && mode != (uint16) -1) {
1646 ret = cli_setatr(srv->cli, path, mode, 0);
1649 if (! ret) {
1650 errno = smbc_errno(context, srv->cli);
1651 return False;
1655 return True;
1659 * Routine to unlink() a file
1662 static int
1663 smbc_unlink_ctx(SMBCCTX *context,
1664 const char *fname)
1666 fstring server, share, user, password, workgroup;
1667 pstring path, targetpath;
1668 struct cli_state *targetcli;
1669 SMBCSRV *srv = NULL;
1671 if (!context || !context->internal ||
1672 !context->internal->_initialized) {
1674 errno = EINVAL; /* Best I can think of ... */
1675 return -1;
1679 if (!fname) {
1681 errno = EINVAL;
1682 return -1;
1686 if (smbc_parse_path(context, fname,
1687 workgroup, sizeof(workgroup),
1688 server, sizeof(server),
1689 share, sizeof(share),
1690 path, sizeof(path),
1691 user, sizeof(user),
1692 password, sizeof(password),
1693 NULL, 0)) {
1694 errno = EINVAL;
1695 return -1;
1698 if (user[0] == (char)0) fstrcpy(user, context->user);
1700 srv = smbc_server(context, True,
1701 server, share, workgroup, user, password);
1703 if (!srv) {
1705 return -1; /* smbc_server sets errno */
1709 /*d_printf(">>>unlink: resolving %s\n", path);*/
1710 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1712 d_printf("Could not resolve %s\n", path);
1713 return -1;
1715 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1717 if (!cli_unlink(targetcli, targetpath)) {
1719 errno = smbc_errno(context, targetcli);
1721 if (errno == EACCES) { /* Check if the file is a directory */
1723 int saverr = errno;
1724 SMB_OFF_T size = 0;
1725 uint16 mode = 0;
1726 struct timespec write_time_ts;
1727 struct timespec access_time_ts;
1728 struct timespec change_time_ts;
1729 SMB_INO_T ino = 0;
1731 if (!smbc_getatr(context, srv, path, &mode, &size,
1732 NULL,
1733 &access_time_ts,
1734 &write_time_ts,
1735 &change_time_ts,
1736 &ino)) {
1738 /* Hmmm, bad error ... What? */
1740 errno = smbc_errno(context, targetcli);
1741 return -1;
1744 else {
1746 if (IS_DOS_DIR(mode))
1747 errno = EISDIR;
1748 else
1749 errno = saverr; /* Restore this */
1754 return -1;
1758 return 0; /* Success ... */
1763 * Routine to rename() a file
1766 static int
1767 smbc_rename_ctx(SMBCCTX *ocontext,
1768 const char *oname,
1769 SMBCCTX *ncontext,
1770 const char *nname)
1772 fstring server1;
1773 fstring share1;
1774 fstring server2;
1775 fstring share2;
1776 fstring user1;
1777 fstring user2;
1778 fstring password1;
1779 fstring password2;
1780 fstring workgroup;
1781 pstring path1;
1782 pstring path2;
1783 pstring targetpath1;
1784 pstring targetpath2;
1785 struct cli_state *targetcli1;
1786 struct cli_state *targetcli2;
1787 SMBCSRV *srv = NULL;
1789 if (!ocontext || !ncontext ||
1790 !ocontext->internal || !ncontext->internal ||
1791 !ocontext->internal->_initialized ||
1792 !ncontext->internal->_initialized) {
1794 errno = EINVAL; /* Best I can think of ... */
1795 return -1;
1799 if (!oname || !nname) {
1801 errno = EINVAL;
1802 return -1;
1806 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1808 smbc_parse_path(ocontext, oname,
1809 workgroup, sizeof(workgroup),
1810 server1, sizeof(server1),
1811 share1, sizeof(share1),
1812 path1, sizeof(path1),
1813 user1, sizeof(user1),
1814 password1, sizeof(password1),
1815 NULL, 0);
1817 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1819 smbc_parse_path(ncontext, nname,
1820 NULL, 0,
1821 server2, sizeof(server2),
1822 share2, sizeof(share2),
1823 path2, sizeof(path2),
1824 user2, sizeof(user2),
1825 password2, sizeof(password2),
1826 NULL, 0);
1828 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1830 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1831 strcmp(user1, user2)) {
1833 /* Can't rename across file systems, or users?? */
1835 errno = EXDEV;
1836 return -1;
1840 srv = smbc_server(ocontext, True,
1841 server1, share1, workgroup, user1, password1);
1842 if (!srv) {
1844 return -1;
1848 /*d_printf(">>>rename: resolving %s\n", path1);*/
1849 if (!cli_resolve_path( "", srv->cli, path1, &targetcli1, targetpath1))
1851 d_printf("Could not resolve %s\n", path1);
1852 return -1;
1854 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1855 /*d_printf(">>>rename: resolving %s\n", path2);*/
1856 if (!cli_resolve_path( "", srv->cli, path2, &targetcli2, targetpath2))
1858 d_printf("Could not resolve %s\n", path2);
1859 return -1;
1861 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1863 if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1864 strcmp(targetcli1->share, targetcli2->share))
1866 /* can't rename across file systems */
1868 errno = EXDEV;
1869 return -1;
1872 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1873 int eno = smbc_errno(ocontext, targetcli1);
1875 if (eno != EEXIST ||
1876 !cli_unlink(targetcli1, targetpath2) ||
1877 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1879 errno = eno;
1880 return -1;
1885 return 0; /* Success */
1890 * A routine to lseek() a file
1893 static off_t
1894 smbc_lseek_ctx(SMBCCTX *context,
1895 SMBCFILE *file,
1896 off_t offset,
1897 int whence)
1899 SMB_OFF_T size;
1900 fstring server, share, user, password;
1901 pstring path, targetpath;
1902 struct cli_state *targetcli;
1904 if (!context || !context->internal ||
1905 !context->internal->_initialized) {
1907 errno = EINVAL;
1908 return -1;
1912 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1914 errno = EBADF;
1915 return -1;
1919 if (!file->file) {
1921 errno = EINVAL;
1922 return -1; /* Can't lseek a dir ... */
1926 switch (whence) {
1927 case SEEK_SET:
1928 file->offset = offset;
1929 break;
1931 case SEEK_CUR:
1932 file->offset += offset;
1933 break;
1935 case SEEK_END:
1936 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1937 if (smbc_parse_path(context, file->fname,
1938 NULL, 0,
1939 server, sizeof(server),
1940 share, sizeof(share),
1941 path, sizeof(path),
1942 user, sizeof(user),
1943 password, sizeof(password),
1944 NULL, 0)) {
1946 errno = EINVAL;
1947 return -1;
1950 /*d_printf(">>>lseek: resolving %s\n", path);*/
1951 if (!cli_resolve_path("", file->srv->cli, path,
1952 &targetcli, targetpath))
1954 d_printf("Could not resolve %s\n", path);
1955 return -1;
1957 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1959 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1960 &size, NULL, NULL, NULL, NULL, NULL))
1962 SMB_OFF_T b_size = size;
1963 if (!cli_getattrE(targetcli, file->cli_fd,
1964 NULL, &b_size, NULL, NULL, NULL))
1966 errno = EINVAL;
1967 return -1;
1968 } else
1969 size = b_size;
1971 file->offset = size + offset;
1972 break;
1974 default:
1975 errno = EINVAL;
1976 break;
1980 return file->offset;
1985 * Generate an inode number from file name for those things that need it
1988 static ino_t
1989 smbc_inode(SMBCCTX *context,
1990 const char *name)
1993 if (!context || !context->internal ||
1994 !context->internal->_initialized) {
1996 errno = EINVAL;
1997 return -1;
2001 if (!*name) return 2; /* FIXME, why 2 ??? */
2002 return (ino_t)str_checksum(name);
2007 * Routine to put basic stat info into a stat structure ... Used by stat and
2008 * fstat below.
2011 static int
2012 smbc_setup_stat(SMBCCTX *context,
2013 struct stat *st,
2014 char *fname,
2015 SMB_OFF_T size,
2016 int mode)
2019 st->st_mode = 0;
2021 if (IS_DOS_DIR(mode)) {
2022 st->st_mode = SMBC_DIR_MODE;
2023 } else {
2024 st->st_mode = SMBC_FILE_MODE;
2027 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
2028 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
2029 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
2030 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
2032 st->st_size = size;
2033 #ifdef HAVE_STAT_ST_BLKSIZE
2034 st->st_blksize = 512;
2035 #endif
2036 #ifdef HAVE_STAT_ST_BLOCKS
2037 st->st_blocks = (size+511)/512;
2038 #endif
2039 st->st_uid = getuid();
2040 st->st_gid = getgid();
2042 if (IS_DOS_DIR(mode)) {
2043 st->st_nlink = 2;
2044 } else {
2045 st->st_nlink = 1;
2048 if (st->st_ino == 0) {
2049 st->st_ino = smbc_inode(context, fname);
2052 return True; /* FIXME: Is this needed ? */
2057 * Routine to stat a file given a name
2060 static int
2061 smbc_stat_ctx(SMBCCTX *context,
2062 const char *fname,
2063 struct stat *st)
2065 SMBCSRV *srv;
2066 fstring server;
2067 fstring share;
2068 fstring user;
2069 fstring password;
2070 fstring workgroup;
2071 pstring path;
2072 struct timespec write_time_ts;
2073 struct timespec access_time_ts;
2074 struct timespec change_time_ts;
2075 SMB_OFF_T size = 0;
2076 uint16 mode = 0;
2077 SMB_INO_T ino = 0;
2079 if (!context || !context->internal ||
2080 !context->internal->_initialized) {
2082 errno = EINVAL; /* Best I can think of ... */
2083 return -1;
2087 if (!fname) {
2089 errno = EINVAL;
2090 return -1;
2094 DEBUG(4, ("smbc_stat(%s)\n", fname));
2096 if (smbc_parse_path(context, fname,
2097 workgroup, sizeof(workgroup),
2098 server, sizeof(server),
2099 share, sizeof(share),
2100 path, sizeof(path),
2101 user, sizeof(user),
2102 password, sizeof(password),
2103 NULL, 0)) {
2104 errno = EINVAL;
2105 return -1;
2108 if (user[0] == (char)0) fstrcpy(user, context->user);
2110 srv = smbc_server(context, True,
2111 server, share, workgroup, user, password);
2113 if (!srv) {
2114 return -1; /* errno set by smbc_server */
2117 if (!smbc_getatr(context, srv, path, &mode, &size,
2118 NULL,
2119 &access_time_ts,
2120 &write_time_ts,
2121 &change_time_ts,
2122 &ino)) {
2124 errno = smbc_errno(context, srv->cli);
2125 return -1;
2129 st->st_ino = ino;
2131 smbc_setup_stat(context, st, path, size, mode);
2133 set_atimespec(st, access_time_ts);
2134 set_ctimespec(st, change_time_ts);
2135 set_mtimespec(st, write_time_ts);
2136 st->st_dev = srv->dev;
2138 return 0;
2143 * Routine to stat a file given an fd
2146 static int
2147 smbc_fstat_ctx(SMBCCTX *context,
2148 SMBCFILE *file,
2149 struct stat *st)
2151 struct timespec change_time_ts;
2152 struct timespec access_time_ts;
2153 struct timespec write_time_ts;
2154 SMB_OFF_T size;
2155 uint16 mode;
2156 fstring server;
2157 fstring share;
2158 fstring user;
2159 fstring password;
2160 pstring path;
2161 pstring targetpath;
2162 struct cli_state *targetcli;
2163 SMB_INO_T ino = 0;
2165 if (!context || !context->internal ||
2166 !context->internal->_initialized) {
2168 errno = EINVAL;
2169 return -1;
2173 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2175 errno = EBADF;
2176 return -1;
2180 if (!file->file) {
2182 return (context->fstatdir)(context, file, st);
2186 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2187 if (smbc_parse_path(context, file->fname,
2188 NULL, 0,
2189 server, sizeof(server),
2190 share, sizeof(share),
2191 path, sizeof(path),
2192 user, sizeof(user),
2193 password, sizeof(password),
2194 NULL, 0)) {
2195 errno = EINVAL;
2196 return -1;
2199 /*d_printf(">>>fstat: resolving %s\n", path);*/
2200 if (!cli_resolve_path("", file->srv->cli, path,
2201 &targetcli, targetpath))
2203 d_printf("Could not resolve %s\n", path);
2204 return -1;
2206 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2208 if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2209 NULL,
2210 &access_time_ts,
2211 &write_time_ts,
2212 &change_time_ts,
2213 &ino)) {
2215 time_t change_time, access_time, write_time;
2217 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2218 &change_time, &access_time, &write_time)) {
2220 errno = EINVAL;
2221 return -1;
2224 change_time_ts = convert_time_t_to_timespec(change_time);
2225 access_time_ts = convert_time_t_to_timespec(access_time);
2226 write_time_ts = convert_time_t_to_timespec(write_time);
2229 st->st_ino = ino;
2231 smbc_setup_stat(context, st, file->fname, size, mode);
2233 set_atimespec(st, access_time_ts);
2234 set_ctimespec(st, change_time_ts);
2235 set_mtimespec(st, write_time_ts);
2236 st->st_dev = file->srv->dev;
2238 return 0;
2243 * Routine to open a directory
2244 * We accept the URL syntax explained in smbc_parse_path(), above.
2247 static void
2248 smbc_remove_dir(SMBCFILE *dir)
2250 struct smbc_dir_list *d,*f;
2252 d = dir->dir_list;
2253 while (d) {
2255 f = d; d = d->next;
2257 SAFE_FREE(f->dirent);
2258 SAFE_FREE(f);
2262 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2266 static int
2267 add_dirent(SMBCFILE *dir,
2268 const char *name,
2269 const char *comment,
2270 uint32 type)
2272 struct smbc_dirent *dirent;
2273 int size;
2274 int name_length = (name == NULL ? 0 : strlen(name));
2275 int comment_len = (comment == NULL ? 0 : strlen(comment));
2278 * Allocate space for the dirent, which must be increased by the
2279 * size of the name and the comment and 1 each for the null terminator.
2282 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2284 dirent = (struct smbc_dirent *)SMB_MALLOC(size);
2286 if (!dirent) {
2288 dir->dir_error = ENOMEM;
2289 return -1;
2293 ZERO_STRUCTP(dirent);
2295 if (dir->dir_list == NULL) {
2297 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2298 if (!dir->dir_list) {
2300 SAFE_FREE(dirent);
2301 dir->dir_error = ENOMEM;
2302 return -1;
2305 ZERO_STRUCTP(dir->dir_list);
2307 dir->dir_end = dir->dir_next = dir->dir_list;
2309 else {
2311 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2313 if (!dir->dir_end->next) {
2315 SAFE_FREE(dirent);
2316 dir->dir_error = ENOMEM;
2317 return -1;
2320 ZERO_STRUCTP(dir->dir_end->next);
2322 dir->dir_end = dir->dir_end->next;
2325 dir->dir_end->next = NULL;
2326 dir->dir_end->dirent = dirent;
2328 dirent->smbc_type = type;
2329 dirent->namelen = name_length;
2330 dirent->commentlen = comment_len;
2331 dirent->dirlen = size;
2334 * dirent->namelen + 1 includes the null (no null termination needed)
2335 * Ditto for dirent->commentlen.
2336 * The space for the two null bytes was allocated.
2338 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2339 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2340 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2342 return 0;
2346 static void
2347 list_unique_wg_fn(const char *name,
2348 uint32 type,
2349 const char *comment,
2350 void *state)
2352 SMBCFILE *dir = (SMBCFILE *)state;
2353 struct smbc_dir_list *dir_list;
2354 struct smbc_dirent *dirent;
2355 int dirent_type;
2356 int do_remove = 0;
2358 dirent_type = dir->dir_type;
2360 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2362 /* An error occurred, what do we do? */
2363 /* FIXME: Add some code here */
2366 /* Point to the one just added */
2367 dirent = dir->dir_end->dirent;
2369 /* See if this was a duplicate */
2370 for (dir_list = dir->dir_list;
2371 dir_list != dir->dir_end;
2372 dir_list = dir_list->next) {
2373 if (! do_remove &&
2374 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2375 /* Duplicate. End end of list need to be removed. */
2376 do_remove = 1;
2379 if (do_remove && dir_list->next == dir->dir_end) {
2380 /* Found the end of the list. Remove it. */
2381 dir->dir_end = dir_list;
2382 free(dir_list->next);
2383 free(dirent);
2384 dir_list->next = NULL;
2385 break;
2390 static void
2391 list_fn(const char *name,
2392 uint32 type,
2393 const char *comment,
2394 void *state)
2396 SMBCFILE *dir = (SMBCFILE *)state;
2397 int dirent_type;
2400 * We need to process the type a little ...
2402 * Disk share = 0x00000000
2403 * Print share = 0x00000001
2404 * Comms share = 0x00000002 (obsolete?)
2405 * IPC$ share = 0x00000003
2407 * administrative shares:
2408 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2411 if (dir->dir_type == SMBC_FILE_SHARE) {
2413 switch (type) {
2414 case 0 | 0x80000000:
2415 case 0:
2416 dirent_type = SMBC_FILE_SHARE;
2417 break;
2419 case 1:
2420 dirent_type = SMBC_PRINTER_SHARE;
2421 break;
2423 case 2:
2424 dirent_type = SMBC_COMMS_SHARE;
2425 break;
2427 case 3 | 0x80000000:
2428 case 3:
2429 dirent_type = SMBC_IPC_SHARE;
2430 break;
2432 default:
2433 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2434 break;
2437 else {
2438 dirent_type = dir->dir_type;
2441 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2443 /* An error occurred, what do we do? */
2444 /* FIXME: Add some code here */
2449 static void
2450 dir_list_fn(const char *mnt,
2451 file_info *finfo,
2452 const char *mask,
2453 void *state)
2456 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2457 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2459 /* Handle an error ... */
2461 /* FIXME: Add some code ... */
2467 static int
2468 net_share_enum_rpc(struct cli_state *cli,
2469 void (*fn)(const char *name,
2470 uint32 type,
2471 const char *comment,
2472 void *state),
2473 void *state)
2475 int i;
2476 WERROR result;
2477 ENUM_HND enum_hnd;
2478 uint32 info_level = 1;
2479 uint32 preferred_len = 0xffffffff;
2480 uint32 type;
2481 SRV_SHARE_INFO_CTR ctr;
2482 fstring name = "";
2483 fstring comment = "";
2484 void *mem_ctx;
2485 struct rpc_pipe_client *pipe_hnd;
2486 NTSTATUS nt_status;
2488 /* Open the server service pipe */
2489 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2490 if (!pipe_hnd) {
2491 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2492 return -1;
2495 /* Allocate a context for parsing and for the entries in "ctr" */
2496 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2497 if (mem_ctx == NULL) {
2498 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2499 cli_rpc_pipe_close(pipe_hnd);
2500 return -1;
2503 /* Issue the NetShareEnum RPC call and retrieve the response */
2504 init_enum_hnd(&enum_hnd, 0);
2505 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2506 mem_ctx,
2507 info_level,
2508 &ctr,
2509 preferred_len,
2510 &enum_hnd);
2512 /* Was it successful? */
2513 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2514 /* Nope. Go clean up. */
2515 goto done;
2518 /* For each returned entry... */
2519 for (i = 0; i < ctr.num_entries; i++) {
2521 /* pull out the share name */
2522 rpcstr_pull_unistr2_fstring(
2523 name, &ctr.share.info1[i].info_1_str.uni_netname);
2525 /* pull out the share's comment */
2526 rpcstr_pull_unistr2_fstring(
2527 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2529 /* Get the type value */
2530 type = ctr.share.info1[i].info_1.type;
2532 /* Add this share to the list */
2533 (*fn)(name, type, comment, state);
2536 done:
2537 /* Close the server service pipe */
2538 cli_rpc_pipe_close(pipe_hnd);
2540 /* Free all memory which was allocated for this request */
2541 TALLOC_FREE(mem_ctx);
2543 /* Tell 'em if it worked */
2544 return W_ERROR_IS_OK(result) ? 0 : -1;
2549 static SMBCFILE *
2550 smbc_opendir_ctx(SMBCCTX *context,
2551 const char *fname)
2553 int saved_errno;
2554 fstring server, share, user, password, options;
2555 pstring workgroup;
2556 pstring path;
2557 uint16 mode;
2558 char *p;
2559 SMBCSRV *srv = NULL;
2560 SMBCFILE *dir = NULL;
2561 struct _smbc_callbacks *cb;
2562 struct sockaddr_storage rem_ss;
2564 if (!context || !context->internal ||
2565 !context->internal->_initialized) {
2566 DEBUG(4, ("no valid context\n"));
2567 errno = EINVAL + 8192;
2568 return NULL;
2572 if (!fname) {
2573 DEBUG(4, ("no valid fname\n"));
2574 errno = EINVAL + 8193;
2575 return NULL;
2578 if (smbc_parse_path(context, fname,
2579 workgroup, sizeof(workgroup),
2580 server, sizeof(server),
2581 share, sizeof(share),
2582 path, sizeof(path),
2583 user, sizeof(user),
2584 password, sizeof(password),
2585 options, sizeof(options))) {
2586 DEBUG(4, ("no valid path\n"));
2587 errno = EINVAL + 8194;
2588 return NULL;
2591 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2592 "path='%s' options='%s'\n",
2593 fname, server, share, path, options));
2595 /* Ensure the options are valid */
2596 if (smbc_check_options(server, share, path, options)) {
2597 DEBUG(4, ("unacceptable options (%s)\n", options));
2598 errno = EINVAL + 8195;
2599 return NULL;
2602 if (user[0] == (char)0) fstrcpy(user, context->user);
2604 dir = SMB_MALLOC_P(SMBCFILE);
2606 if (!dir) {
2607 errno = ENOMEM;
2608 return NULL;
2611 ZERO_STRUCTP(dir);
2613 dir->cli_fd = 0;
2614 dir->fname = SMB_STRDUP(fname);
2615 dir->srv = NULL;
2616 dir->offset = 0;
2617 dir->file = False;
2618 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2620 if (server[0] == (char)0) {
2622 int i;
2623 int count;
2624 int max_lmb_count;
2625 struct ip_service *ip_list;
2626 struct ip_service server_addr;
2627 struct user_auth_info u_info;
2628 struct cli_state *cli;
2630 if (share[0] != (char)0 || path[0] != (char)0) {
2632 errno = EINVAL + 8196;
2633 if (dir) {
2634 SAFE_FREE(dir->fname);
2635 SAFE_FREE(dir);
2637 return NULL;
2640 /* Determine how many local master browsers to query */
2641 max_lmb_count = (context->options.browse_max_lmb_count == 0
2642 ? INT_MAX
2643 : context->options.browse_max_lmb_count);
2645 pstrcpy(u_info.username, user);
2646 pstrcpy(u_info.password, password);
2649 * We have server and share and path empty but options
2650 * requesting that we scan all master browsers for their list
2651 * of workgroups/domains. This implies that we must first try
2652 * broadcast queries to find all master browsers, and if that
2653 * doesn't work, then try our other methods which return only
2654 * a single master browser.
2657 ip_list = NULL;
2658 if (!NT_STATUS_IS_OK(name_resolve_bcast(MSBROWSE, 1, &ip_list,
2659 &count)))
2662 SAFE_FREE(ip_list);
2664 if (!find_master_ip(workgroup, &server_addr.ss)) {
2666 if (dir) {
2667 SAFE_FREE(dir->fname);
2668 SAFE_FREE(dir);
2670 errno = ENOENT;
2671 return NULL;
2674 ip_list = (struct ip_service *)memdup(
2675 &server_addr, sizeof(server_addr));
2676 if (ip_list == NULL) {
2677 errno = ENOMEM;
2678 return NULL;
2680 count = 1;
2683 for (i = 0; i < count && i < max_lmb_count; i++) {
2684 char addr[INET6_ADDRSTRLEN];
2685 print_sockaddr(addr, sizeof(addr), &ip_list[i].ss);
2686 DEBUG(99, ("Found master browser %d of %d: %s\n",
2687 i+1, MAX(count, max_lmb_count),
2688 addr));
2690 cli = get_ipc_connect_master_ip(&ip_list[i],
2691 workgroup, &u_info);
2692 /* cli == NULL is the master browser refused to talk or
2693 could not be found */
2694 if ( !cli )
2695 continue;
2697 fstrcpy(server, cli->desthost);
2698 cli_shutdown(cli);
2700 DEBUG(4, ("using workgroup %s %s\n",
2701 workgroup, server));
2704 * For each returned master browser IP address, get a
2705 * connection to IPC$ on the server if we do not
2706 * already have one, and determine the
2707 * workgroups/domains that it knows about.
2710 srv = smbc_server(context, True, server, "IPC$",
2711 workgroup, user, password);
2712 if (!srv) {
2713 continue;
2716 dir->srv = srv;
2717 dir->dir_type = SMBC_WORKGROUP;
2719 /* Now, list the stuff ... */
2721 if (!cli_NetServerEnum(srv->cli,
2722 workgroup,
2723 SV_TYPE_DOMAIN_ENUM,
2724 list_unique_wg_fn,
2725 (void *)dir)) {
2726 continue;
2730 SAFE_FREE(ip_list);
2731 } else {
2733 * Server not an empty string ... Check the rest and see what
2734 * gives
2736 if (*share == '\0') {
2737 if (*path != '\0') {
2739 /* Should not have empty share with path */
2740 errno = EINVAL + 8197;
2741 if (dir) {
2742 SAFE_FREE(dir->fname);
2743 SAFE_FREE(dir);
2745 return NULL;
2750 * We don't know if <server> is really a server name
2751 * or is a workgroup/domain name. If we already have
2752 * a server structure for it, we'll use it.
2753 * Otherwise, check to see if <server><1D>,
2754 * <server><1B>, or <server><20> translates. We check
2755 * to see if <server> is an IP address first.
2759 * See if we have an existing server. Do not
2760 * establish a connection if one does not already
2761 * exist.
2763 srv = smbc_server(context, False, server, "IPC$",
2764 workgroup, user, password);
2767 * If no existing server and not an IP addr, look for
2768 * LMB or DMB
2770 if (!srv &&
2771 !is_ipaddress(server) &&
2772 (resolve_name(server, &rem_ss, 0x1d) || /* LMB */
2773 resolve_name(server, &rem_ss, 0x1b) )) { /* DMB */
2775 fstring buserver;
2777 dir->dir_type = SMBC_SERVER;
2780 * Get the backup list ...
2782 if (!name_status_find(server, 0, 0,
2783 &rem_ss, buserver)) {
2785 DEBUG(0, ("Could not get name of "
2786 "local/domain master browser "
2787 "for server %s\n", server));
2788 if (dir) {
2789 SAFE_FREE(dir->fname);
2790 SAFE_FREE(dir);
2792 errno = EPERM;
2793 return NULL;
2798 * Get a connection to IPC$ on the server if
2799 * we do not already have one
2801 srv = smbc_server(context, True,
2802 buserver, "IPC$",
2803 workgroup, user, password);
2804 if (!srv) {
2805 DEBUG(0, ("got no contact to IPC$\n"));
2806 if (dir) {
2807 SAFE_FREE(dir->fname);
2808 SAFE_FREE(dir);
2810 return NULL;
2814 dir->srv = srv;
2816 /* Now, list the servers ... */
2817 if (!cli_NetServerEnum(srv->cli, server,
2818 0x0000FFFE, list_fn,
2819 (void *)dir)) {
2821 if (dir) {
2822 SAFE_FREE(dir->fname);
2823 SAFE_FREE(dir);
2825 return NULL;
2827 } else if (srv ||
2828 (resolve_name(server, &rem_ss, 0x20))) {
2830 /* If we hadn't found the server, get one now */
2831 if (!srv) {
2832 srv = smbc_server(context, True,
2833 server, "IPC$",
2834 workgroup,
2835 user, password);
2838 if (!srv) {
2839 if (dir) {
2840 SAFE_FREE(dir->fname);
2841 SAFE_FREE(dir);
2843 return NULL;
2847 dir->dir_type = SMBC_FILE_SHARE;
2848 dir->srv = srv;
2850 /* List the shares ... */
2852 if (net_share_enum_rpc(
2853 srv->cli,
2854 list_fn,
2855 (void *) dir) < 0 &&
2856 cli_RNetShareEnum(
2857 srv->cli,
2858 list_fn,
2859 (void *)dir) < 0) {
2861 errno = cli_errno(srv->cli);
2862 if (dir) {
2863 SAFE_FREE(dir->fname);
2864 SAFE_FREE(dir);
2866 return NULL;
2869 } else {
2870 /* Neither the workgroup nor server exists */
2871 errno = ECONNREFUSED;
2872 if (dir) {
2873 SAFE_FREE(dir->fname);
2874 SAFE_FREE(dir);
2876 return NULL;
2880 else {
2882 * The server and share are specified ... work from
2883 * there ...
2885 pstring targetpath;
2886 struct cli_state *targetcli;
2888 /* We connect to the server and list the directory */
2889 dir->dir_type = SMBC_FILE_SHARE;
2891 srv = smbc_server(context, True, server, share,
2892 workgroup, user, password);
2894 if (!srv) {
2896 if (dir) {
2897 SAFE_FREE(dir->fname);
2898 SAFE_FREE(dir);
2900 return NULL;
2904 dir->srv = srv;
2906 /* Now, list the files ... */
2908 p = path + strlen(path);
2909 pstrcat(path, "\\*");
2911 if (!cli_resolve_path("", srv->cli, path,
2912 &targetcli, targetpath))
2914 d_printf("Could not resolve %s\n", path);
2915 if (dir) {
2916 SAFE_FREE(dir->fname);
2917 SAFE_FREE(dir);
2919 return NULL;
2922 if (cli_list(targetcli, targetpath,
2923 aDIR | aSYSTEM | aHIDDEN,
2924 dir_list_fn, (void *)dir) < 0) {
2926 if (dir) {
2927 SAFE_FREE(dir->fname);
2928 SAFE_FREE(dir);
2930 saved_errno = smbc_errno(context, targetcli);
2932 if (saved_errno == EINVAL) {
2934 * See if they asked to opendir something
2935 * other than a directory. If so, the
2936 * converted error value we got would have
2937 * been EINVAL rather than ENOTDIR.
2939 *p = '\0'; /* restore original path */
2941 if (smbc_getatr(context, srv, path,
2942 &mode, NULL,
2943 NULL, NULL, NULL, NULL,
2944 NULL) &&
2945 ! IS_DOS_DIR(mode)) {
2947 /* It is. Correct the error value */
2948 saved_errno = ENOTDIR;
2953 * If there was an error and the server is no
2954 * good any more...
2956 cb = &context->callbacks;
2957 if (cli_is_error(targetcli) &&
2958 (cb->check_server_fn)(context, srv)) {
2960 /* ... then remove it. */
2961 if ((cb->remove_unused_server_fn)(context,
2962 srv)) {
2964 * We could not remove the
2965 * server completely, remove
2966 * it from the cache so we
2967 * will not get it again. It
2968 * will be removed when the
2969 * last file/dir is closed.
2971 (cb->remove_cached_srv_fn)(context,
2972 srv);
2976 errno = saved_errno;
2977 return NULL;
2983 DLIST_ADD(context->internal->_files, dir);
2984 return dir;
2989 * Routine to close a directory
2992 static int
2993 smbc_closedir_ctx(SMBCCTX *context,
2994 SMBCFILE *dir)
2997 if (!context || !context->internal ||
2998 !context->internal->_initialized) {
3000 errno = EINVAL;
3001 return -1;
3005 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3007 errno = EBADF;
3008 return -1;
3012 smbc_remove_dir(dir); /* Clean it up */
3014 DLIST_REMOVE(context->internal->_files, dir);
3016 if (dir) {
3018 SAFE_FREE(dir->fname);
3019 SAFE_FREE(dir); /* Free the space too */
3022 return 0;
3026 static void
3027 smbc_readdir_internal(SMBCCTX * context,
3028 struct smbc_dirent *dest,
3029 struct smbc_dirent *src,
3030 int max_namebuf_len)
3032 if (context->options.urlencode_readdir_entries) {
3034 /* url-encode the name. get back remaining buffer space */
3035 max_namebuf_len =
3036 smbc_urlencode(dest->name, src->name, max_namebuf_len);
3038 /* We now know the name length */
3039 dest->namelen = strlen(dest->name);
3041 /* Save the pointer to the beginning of the comment */
3042 dest->comment = dest->name + dest->namelen + 1;
3044 /* Copy the comment */
3045 strncpy(dest->comment, src->comment, max_namebuf_len - 1);
3046 dest->comment[max_namebuf_len - 1] = '\0';
3048 /* Save other fields */
3049 dest->smbc_type = src->smbc_type;
3050 dest->commentlen = strlen(dest->comment);
3051 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
3052 (char *) dest);
3053 } else {
3055 /* No encoding. Just copy the entry as is. */
3056 memcpy(dest, src, src->dirlen);
3057 dest->comment = (char *)(&dest->name + src->namelen + 1);
3063 * Routine to get a directory entry
3066 struct smbc_dirent *
3067 smbc_readdir_ctx(SMBCCTX *context,
3068 SMBCFILE *dir)
3070 int maxlen;
3071 struct smbc_dirent *dirp, *dirent;
3073 /* Check that all is ok first ... */
3075 if (!context || !context->internal ||
3076 !context->internal->_initialized) {
3078 errno = EINVAL;
3079 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
3080 return NULL;
3084 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3086 errno = EBADF;
3087 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
3088 return NULL;
3092 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3094 errno = ENOTDIR;
3095 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
3096 return NULL;
3100 if (!dir->dir_next) {
3101 return NULL;
3104 dirent = dir->dir_next->dirent;
3105 if (!dirent) {
3107 errno = ENOENT;
3108 return NULL;
3112 dirp = (struct smbc_dirent *)context->internal->_dirent;
3113 maxlen = (sizeof(context->internal->_dirent) -
3114 sizeof(struct smbc_dirent));
3116 smbc_readdir_internal(context, dirp, dirent, maxlen);
3118 dir->dir_next = dir->dir_next->next;
3120 return dirp;
3124 * Routine to get directory entries
3127 static int
3128 smbc_getdents_ctx(SMBCCTX *context,
3129 SMBCFILE *dir,
3130 struct smbc_dirent *dirp,
3131 int count)
3133 int rem = count;
3134 int reqd;
3135 int maxlen;
3136 char *ndir = (char *)dirp;
3137 struct smbc_dir_list *dirlist;
3139 /* Check that all is ok first ... */
3141 if (!context || !context->internal ||
3142 !context->internal->_initialized) {
3144 errno = EINVAL;
3145 return -1;
3149 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3151 errno = EBADF;
3152 return -1;
3156 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3158 errno = ENOTDIR;
3159 return -1;
3164 * Now, retrieve the number of entries that will fit in what was passed
3165 * We have to figure out if the info is in the list, or we need to
3166 * send a request to the server to get the info.
3169 while ((dirlist = dir->dir_next)) {
3170 struct smbc_dirent *dirent;
3172 if (!dirlist->dirent) {
3174 errno = ENOENT; /* Bad error */
3175 return -1;
3179 /* Do urlencoding of next entry, if so selected */
3180 dirent = (struct smbc_dirent *)context->internal->_dirent;
3181 maxlen = (sizeof(context->internal->_dirent) -
3182 sizeof(struct smbc_dirent));
3183 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3185 reqd = dirent->dirlen;
3187 if (rem < reqd) {
3189 if (rem < count) { /* We managed to copy something */
3191 errno = 0;
3192 return count - rem;
3195 else { /* Nothing copied ... */
3197 errno = EINVAL; /* Not enough space ... */
3198 return -1;
3204 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3206 ((struct smbc_dirent *)ndir)->comment =
3207 (char *)(&((struct smbc_dirent *)ndir)->name +
3208 dirent->namelen +
3211 ndir += reqd;
3213 rem -= reqd;
3215 dir->dir_next = dirlist = dirlist -> next;
3218 if (rem == count)
3219 return 0;
3220 else
3221 return count - rem;
3226 * Routine to create a directory ...
3229 static int
3230 smbc_mkdir_ctx(SMBCCTX *context,
3231 const char *fname,
3232 mode_t mode)
3234 SMBCSRV *srv;
3235 fstring server;
3236 fstring share;
3237 fstring user;
3238 fstring password;
3239 fstring workgroup;
3240 pstring path, targetpath;
3241 struct cli_state *targetcli;
3243 if (!context || !context->internal ||
3244 !context->internal->_initialized) {
3246 errno = EINVAL;
3247 return -1;
3251 if (!fname) {
3253 errno = EINVAL;
3254 return -1;
3258 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3260 if (smbc_parse_path(context, fname,
3261 workgroup, sizeof(workgroup),
3262 server, sizeof(server),
3263 share, sizeof(share),
3264 path, sizeof(path),
3265 user, sizeof(user),
3266 password, sizeof(password),
3267 NULL, 0)) {
3268 errno = EINVAL;
3269 return -1;
3272 if (user[0] == (char)0) fstrcpy(user, context->user);
3274 srv = smbc_server(context, True,
3275 server, share, workgroup, user, password);
3277 if (!srv) {
3279 return -1; /* errno set by smbc_server */
3283 /*d_printf(">>>mkdir: resolving %s\n", path);*/
3284 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
3286 d_printf("Could not resolve %s\n", path);
3287 return -1;
3289 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3291 if (!cli_mkdir(targetcli, targetpath)) {
3293 errno = smbc_errno(context, targetcli);
3294 return -1;
3298 return 0;
3303 * Our list function simply checks to see if a directory is not empty
3306 static int smbc_rmdir_dirempty = True;
3308 static void
3309 rmdir_list_fn(const char *mnt,
3310 file_info *finfo,
3311 const char *mask,
3312 void *state)
3314 if (strncmp(finfo->name, ".", 1) != 0 &&
3315 strncmp(finfo->name, "..", 2) != 0) {
3317 smbc_rmdir_dirempty = False;
3322 * Routine to remove a directory
3325 static int
3326 smbc_rmdir_ctx(SMBCCTX *context,
3327 const char *fname)
3329 SMBCSRV *srv;
3330 fstring server;
3331 fstring share;
3332 fstring user;
3333 fstring password;
3334 fstring workgroup;
3335 pstring path;
3336 pstring targetpath;
3337 struct cli_state *targetcli;
3339 if (!context || !context->internal ||
3340 !context->internal->_initialized) {
3342 errno = EINVAL;
3343 return -1;
3347 if (!fname) {
3349 errno = EINVAL;
3350 return -1;
3354 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3356 if (smbc_parse_path(context, fname,
3357 workgroup, sizeof(workgroup),
3358 server, sizeof(server),
3359 share, sizeof(share),
3360 path, sizeof(path),
3361 user, sizeof(user),
3362 password, sizeof(password),
3363 NULL, 0))
3365 errno = EINVAL;
3366 return -1;
3369 if (user[0] == (char)0) fstrcpy(user, context->user);
3371 srv = smbc_server(context, True,
3372 server, share, workgroup, user, password);
3374 if (!srv) {
3376 return -1; /* errno set by smbc_server */
3380 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3381 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
3383 d_printf("Could not resolve %s\n", path);
3384 return -1;
3386 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3389 if (!cli_rmdir(targetcli, targetpath)) {
3391 errno = smbc_errno(context, targetcli);
3393 if (errno == EACCES) { /* Check if the dir empty or not */
3395 /* Local storage to avoid buffer overflows */
3396 pstring lpath;
3398 smbc_rmdir_dirempty = True; /* Make this so ... */
3400 pstrcpy(lpath, targetpath);
3401 pstrcat(lpath, "\\*");
3403 if (cli_list(targetcli, lpath,
3404 aDIR | aSYSTEM | aHIDDEN,
3405 rmdir_list_fn, NULL) < 0) {
3407 /* Fix errno to ignore latest error ... */
3408 DEBUG(5, ("smbc_rmdir: "
3409 "cli_list returned an error: %d\n",
3410 smbc_errno(context, targetcli)));
3411 errno = EACCES;
3415 if (smbc_rmdir_dirempty)
3416 errno = EACCES;
3417 else
3418 errno = ENOTEMPTY;
3422 return -1;
3426 return 0;
3431 * Routine to return the current directory position
3434 static off_t
3435 smbc_telldir_ctx(SMBCCTX *context,
3436 SMBCFILE *dir)
3438 if (!context || !context->internal ||
3439 !context->internal->_initialized) {
3441 errno = EINVAL;
3442 return -1;
3446 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3448 errno = EBADF;
3449 return -1;
3453 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3455 errno = ENOTDIR;
3456 return -1;
3460 /* See if we're already at the end. */
3461 if (dir->dir_next == NULL) {
3462 /* We are. */
3463 return -1;
3467 * We return the pointer here as the offset
3469 return (off_t)(long)dir->dir_next->dirent;
3473 * A routine to run down the list and see if the entry is OK
3476 struct smbc_dir_list *
3477 smbc_check_dir_ent(struct smbc_dir_list *list,
3478 struct smbc_dirent *dirent)
3481 /* Run down the list looking for what we want */
3483 if (dirent) {
3485 struct smbc_dir_list *tmp = list;
3487 while (tmp) {
3489 if (tmp->dirent == dirent)
3490 return tmp;
3492 tmp = tmp->next;
3498 return NULL; /* Not found, or an error */
3504 * Routine to seek on a directory
3507 static int
3508 smbc_lseekdir_ctx(SMBCCTX *context,
3509 SMBCFILE *dir,
3510 off_t offset)
3512 long int l_offset = offset; /* Handle problems of size */
3513 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3514 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3516 if (!context || !context->internal ||
3517 !context->internal->_initialized) {
3519 errno = EINVAL;
3520 return -1;
3524 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3526 errno = ENOTDIR;
3527 return -1;
3531 /* Now, check what we were passed and see if it is OK ... */
3533 if (dirent == NULL) { /* Seek to the begining of the list */
3535 dir->dir_next = dir->dir_list;
3536 return 0;
3540 if (offset == -1) { /* Seek to the end of the list */
3541 dir->dir_next = NULL;
3542 return 0;
3545 /* Now, run down the list and make sure that the entry is OK */
3546 /* This may need to be changed if we change the format of the list */
3548 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3550 errno = EINVAL; /* Bad entry */
3551 return -1;
3555 dir->dir_next = list_ent;
3557 return 0;
3562 * Routine to fstat a dir
3565 static int
3566 smbc_fstatdir_ctx(SMBCCTX *context,
3567 SMBCFILE *dir,
3568 struct stat *st)
3571 if (!context || !context->internal ||
3572 !context->internal->_initialized) {
3574 errno = EINVAL;
3575 return -1;
3579 /* No code yet ... */
3581 return 0;
3585 static int
3586 smbc_chmod_ctx(SMBCCTX *context,
3587 const char *fname,
3588 mode_t newmode)
3590 SMBCSRV *srv;
3591 fstring server;
3592 fstring share;
3593 fstring user;
3594 fstring password;
3595 fstring workgroup;
3596 pstring path;
3597 uint16 mode;
3599 if (!context || !context->internal ||
3600 !context->internal->_initialized) {
3602 errno = EINVAL; /* Best I can think of ... */
3603 return -1;
3607 if (!fname) {
3609 errno = EINVAL;
3610 return -1;
3614 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3616 if (smbc_parse_path(context, fname,
3617 workgroup, sizeof(workgroup),
3618 server, sizeof(server),
3619 share, sizeof(share),
3620 path, sizeof(path),
3621 user, sizeof(user),
3622 password, sizeof(password),
3623 NULL, 0)) {
3624 errno = EINVAL;
3625 return -1;
3628 if (user[0] == (char)0) fstrcpy(user, context->user);
3630 srv = smbc_server(context, True,
3631 server, share, workgroup, user, password);
3633 if (!srv) {
3634 return -1; /* errno set by smbc_server */
3637 mode = 0;
3639 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3640 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3641 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3642 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3644 if (!cli_setatr(srv->cli, path, mode, 0)) {
3645 errno = smbc_errno(context, srv->cli);
3646 return -1;
3649 return 0;
3652 static int
3653 smbc_utimes_ctx(SMBCCTX *context,
3654 const char *fname,
3655 struct timeval *tbuf)
3657 SMBCSRV *srv;
3658 fstring server;
3659 fstring share;
3660 fstring user;
3661 fstring password;
3662 fstring workgroup;
3663 pstring path;
3664 time_t access_time;
3665 time_t write_time;
3667 if (!context || !context->internal ||
3668 !context->internal->_initialized) {
3670 errno = EINVAL; /* Best I can think of ... */
3671 return -1;
3675 if (!fname) {
3677 errno = EINVAL;
3678 return -1;
3682 if (tbuf == NULL) {
3683 access_time = write_time = time(NULL);
3684 } else {
3685 access_time = tbuf[0].tv_sec;
3686 write_time = tbuf[1].tv_sec;
3689 if (DEBUGLVL(4))
3691 char *p;
3692 char atimebuf[32];
3693 char mtimebuf[32];
3695 strncpy(atimebuf, ctime(&access_time), sizeof(atimebuf) - 1);
3696 atimebuf[sizeof(atimebuf) - 1] = '\0';
3697 if ((p = strchr(atimebuf, '\n')) != NULL) {
3698 *p = '\0';
3701 strncpy(mtimebuf, ctime(&write_time), sizeof(mtimebuf) - 1);
3702 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3703 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3704 *p = '\0';
3707 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3708 fname, atimebuf, mtimebuf);
3711 if (smbc_parse_path(context, fname,
3712 workgroup, sizeof(workgroup),
3713 server, sizeof(server),
3714 share, sizeof(share),
3715 path, sizeof(path),
3716 user, sizeof(user),
3717 password, sizeof(password),
3718 NULL, 0)) {
3719 errno = EINVAL;
3720 return -1;
3723 if (user[0] == (char)0) fstrcpy(user, context->user);
3725 srv = smbc_server(context, True,
3726 server, share, workgroup, user, password);
3728 if (!srv) {
3729 return -1; /* errno set by smbc_server */
3732 if (!smbc_setatr(context, srv, path,
3733 0, access_time, write_time, 0, 0)) {
3734 return -1; /* errno set by smbc_setatr */
3737 return 0;
3742 * Sort ACEs according to the documentation at
3743 * http://support.microsoft.com/kb/269175, at least as far as it defines the
3744 * order.
3747 static int
3748 ace_compare(SEC_ACE *ace1,
3749 SEC_ACE *ace2)
3751 bool b1;
3752 bool b2;
3754 /* If the ACEs are equal, we have nothing more to do. */
3755 if (sec_ace_equal(ace1, ace2)) {
3756 return 0;
3759 /* Inherited follow non-inherited */
3760 b1 = ((ace1->flags & SEC_ACE_FLAG_INHERITED_ACE) != 0);
3761 b2 = ((ace2->flags & SEC_ACE_FLAG_INHERITED_ACE) != 0);
3762 if (b1 != b2) {
3763 return (b1 ? 1 : -1);
3767 * What shall we do with AUDITs and ALARMs? It's undefined. We'll
3768 * sort them after DENY and ALLOW.
3770 b1 = (ace1->type != SEC_ACE_TYPE_ACCESS_ALLOWED &&
3771 ace1->type != SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT &&
3772 ace1->type != SEC_ACE_TYPE_ACCESS_DENIED &&
3773 ace1->type != SEC_ACE_TYPE_ACCESS_DENIED_OBJECT);
3774 b2 = (ace2->type != SEC_ACE_TYPE_ACCESS_ALLOWED &&
3775 ace2->type != SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT &&
3776 ace2->type != SEC_ACE_TYPE_ACCESS_DENIED &&
3777 ace2->type != SEC_ACE_TYPE_ACCESS_DENIED_OBJECT);
3778 if (b1 != b2) {
3779 return (b1 ? 1 : -1);
3782 /* Allowed ACEs follow denied ACEs */
3783 b1 = (ace1->type == SEC_ACE_TYPE_ACCESS_ALLOWED ||
3784 ace1->type == SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT);
3785 b2 = (ace2->type == SEC_ACE_TYPE_ACCESS_ALLOWED ||
3786 ace2->type == SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT);
3787 if (b1 != b2) {
3788 return (b1 ? 1 : -1);
3792 * ACEs applying to an entity's object follow those applying to the
3793 * entity itself
3795 b1 = (ace1->type == SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT ||
3796 ace1->type == SEC_ACE_TYPE_ACCESS_DENIED_OBJECT);
3797 b2 = (ace2->type == SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT ||
3798 ace2->type == SEC_ACE_TYPE_ACCESS_DENIED_OBJECT);
3799 if (b1 != b2) {
3800 return (b1 ? 1 : -1);
3804 * If we get this far, the ACEs are similar as far as the
3805 * characteristics we typically care about (those defined by the
3806 * referenced MS document). We'll now sort by characteristics that
3807 * just seems reasonable.
3810 if (ace1->type != ace2->type) {
3811 return ace2->type - ace1->type;
3814 if (sid_compare(&ace1->trustee, &ace2->trustee)) {
3815 return sid_compare(&ace1->trustee, &ace2->trustee);
3818 if (ace1->flags != ace2->flags) {
3819 return ace1->flags - ace2->flags;
3822 if (ace1->access_mask != ace2->access_mask) {
3823 return ace1->access_mask - ace2->access_mask;
3826 if (ace1->size != ace2->size) {
3827 return ace1->size - ace2->size;
3830 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3834 static void
3835 sort_acl(SEC_ACL *the_acl)
3837 uint32 i;
3838 if (!the_acl) return;
3840 qsort(the_acl->aces, the_acl->num_aces, sizeof(the_acl->aces[0]),
3841 QSORT_CAST ace_compare);
3843 for (i=1;i<the_acl->num_aces;) {
3844 if (sec_ace_equal(&the_acl->aces[i-1], &the_acl->aces[i])) {
3845 int j;
3846 for (j=i; j<the_acl->num_aces-1; j++) {
3847 the_acl->aces[j] = the_acl->aces[j+1];
3849 the_acl->num_aces--;
3850 } else {
3851 i++;
3856 /* convert a SID to a string, either numeric or username/group */
3857 static void
3858 convert_sid_to_string(struct cli_state *ipc_cli,
3859 POLICY_HND *pol,
3860 fstring str,
3861 bool numeric,
3862 DOM_SID *sid)
3864 char **domains = NULL;
3865 char **names = NULL;
3866 enum lsa_SidType *types = NULL;
3867 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3868 sid_to_string(str, sid);
3870 if (numeric) {
3871 return; /* no lookup desired */
3874 if (!pipe_hnd) {
3875 return;
3878 /* Ask LSA to convert the sid to a name */
3880 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3881 pol, 1, sid, &domains,
3882 &names, &types)) ||
3883 !domains || !domains[0] || !names || !names[0]) {
3884 return;
3887 /* Converted OK */
3889 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3890 domains[0], lp_winbind_separator(),
3891 names[0]);
3894 /* convert a string to a SID, either numeric or username/group */
3895 static bool
3896 convert_string_to_sid(struct cli_state *ipc_cli,
3897 POLICY_HND *pol,
3898 bool numeric,
3899 DOM_SID *sid,
3900 const char *str)
3902 enum lsa_SidType *types = NULL;
3903 DOM_SID *sids = NULL;
3904 bool result = True;
3905 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3907 if (!pipe_hnd) {
3908 return False;
3911 if (numeric) {
3912 if (strncmp(str, "S-", 2) == 0) {
3913 return string_to_sid(sid, str);
3916 result = False;
3917 goto done;
3920 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3921 pol, 1, &str, NULL, 1, &sids,
3922 &types))) {
3923 result = False;
3924 goto done;
3927 sid_copy(sid, &sids[0]);
3928 done:
3930 return result;
3934 /* parse an ACE in the same format as print_ace() */
3935 static bool
3936 parse_ace(struct cli_state *ipc_cli,
3937 POLICY_HND *pol,
3938 SEC_ACE *ace,
3939 bool numeric,
3940 char *str)
3942 char *p;
3943 const char *cp;
3944 fstring tok;
3945 unsigned int atype;
3946 unsigned int aflags;
3947 unsigned int amask;
3948 DOM_SID sid;
3949 SEC_ACCESS mask;
3950 const struct perm_value *v;
3951 struct perm_value {
3952 const char *perm;
3953 uint32 mask;
3956 /* These values discovered by inspection */
3957 static const struct perm_value special_values[] = {
3958 { "R", 0x00120089 },
3959 { "W", 0x00120116 },
3960 { "X", 0x001200a0 },
3961 { "D", 0x00010000 },
3962 { "P", 0x00040000 },
3963 { "O", 0x00080000 },
3964 { NULL, 0 },
3967 static const struct perm_value standard_values[] = {
3968 { "READ", 0x001200a9 },
3969 { "CHANGE", 0x001301bf },
3970 { "FULL", 0x001f01ff },
3971 { NULL, 0 },
3975 ZERO_STRUCTP(ace);
3976 p = strchr_m(str,':');
3977 if (!p) return False;
3978 *p = '\0';
3979 p++;
3980 /* Try to parse numeric form */
3982 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3983 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3984 goto done;
3987 /* Try to parse text form */
3989 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3990 return False;
3993 cp = p;
3994 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3995 return False;
3998 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3999 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
4000 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
4001 atype = SEC_ACE_TYPE_ACCESS_DENIED;
4002 } else {
4003 return False;
4006 /* Only numeric form accepted for flags at present */
4008 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
4009 sscanf(tok, "%i", &aflags))) {
4010 return False;
4013 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
4014 return False;
4017 if (strncmp(tok, "0x", 2) == 0) {
4018 if (sscanf(tok, "%i", &amask) != 1) {
4019 return False;
4021 goto done;
4024 for (v = standard_values; v->perm; v++) {
4025 if (strcmp(tok, v->perm) == 0) {
4026 amask = v->mask;
4027 goto done;
4031 p = tok;
4033 while(*p) {
4034 bool found = False;
4036 for (v = special_values; v->perm; v++) {
4037 if (v->perm[0] == *p) {
4038 amask |= v->mask;
4039 found = True;
4043 if (!found) return False;
4044 p++;
4047 if (*p) {
4048 return False;
4051 done:
4052 mask = amask;
4053 init_sec_ace(ace, &sid, atype, mask, aflags);
4054 return True;
4057 /* add an ACE to a list of ACEs in a SEC_ACL */
4058 static bool
4059 add_ace(SEC_ACL **the_acl,
4060 SEC_ACE *ace,
4061 TALLOC_CTX *ctx)
4063 SEC_ACL *newacl;
4064 SEC_ACE *aces;
4066 if (! *the_acl) {
4067 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
4068 return True;
4071 if ((aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces)) == NULL) {
4072 return False;
4074 memcpy(aces, (*the_acl)->aces, (*the_acl)->num_aces * sizeof(SEC_ACE));
4075 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
4076 newacl = make_sec_acl(ctx, (*the_acl)->revision,
4077 1+(*the_acl)->num_aces, aces);
4078 SAFE_FREE(aces);
4079 (*the_acl) = newacl;
4080 return True;
4084 /* parse a ascii version of a security descriptor */
4085 static SEC_DESC *
4086 sec_desc_parse(TALLOC_CTX *ctx,
4087 struct cli_state *ipc_cli,
4088 POLICY_HND *pol,
4089 bool numeric,
4090 char *str)
4092 const char *p = str;
4093 fstring tok;
4094 SEC_DESC *ret = NULL;
4095 size_t sd_size;
4096 DOM_SID *group_sid=NULL;
4097 DOM_SID *owner_sid=NULL;
4098 SEC_ACL *dacl=NULL;
4099 int revision=1;
4101 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4103 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
4104 revision = strtol(tok+9, NULL, 16);
4105 continue;
4108 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
4109 if (owner_sid) {
4110 DEBUG(5, ("OWNER specified more than once!\n"));
4111 goto done;
4113 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4114 if (!owner_sid ||
4115 !convert_string_to_sid(ipc_cli, pol,
4116 numeric,
4117 owner_sid, tok+6)) {
4118 DEBUG(5, ("Failed to parse owner sid\n"));
4119 goto done;
4121 continue;
4124 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
4125 if (owner_sid) {
4126 DEBUG(5, ("OWNER specified more than once!\n"));
4127 goto done;
4129 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4130 if (!owner_sid ||
4131 !convert_string_to_sid(ipc_cli, pol,
4132 False,
4133 owner_sid, tok+7)) {
4134 DEBUG(5, ("Failed to parse owner sid\n"));
4135 goto done;
4137 continue;
4140 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
4141 if (group_sid) {
4142 DEBUG(5, ("GROUP specified more than once!\n"));
4143 goto done;
4145 group_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4146 if (!group_sid ||
4147 !convert_string_to_sid(ipc_cli, pol,
4148 numeric,
4149 group_sid, tok+6)) {
4150 DEBUG(5, ("Failed to parse group sid\n"));
4151 goto done;
4153 continue;
4156 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
4157 if (group_sid) {
4158 DEBUG(5, ("GROUP specified more than once!\n"));
4159 goto done;
4161 group_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4162 if (!group_sid ||
4163 !convert_string_to_sid(ipc_cli, pol,
4164 False,
4165 group_sid, tok+6)) {
4166 DEBUG(5, ("Failed to parse group sid\n"));
4167 goto done;
4169 continue;
4172 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
4173 SEC_ACE ace;
4174 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
4175 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4176 goto done;
4178 if(!add_ace(&dacl, &ace, ctx)) {
4179 DEBUG(5, ("Failed to add ACL %s\n", tok));
4180 goto done;
4182 continue;
4185 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
4186 SEC_ACE ace;
4187 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
4188 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4189 goto done;
4191 if(!add_ace(&dacl, &ace, ctx)) {
4192 DEBUG(5, ("Failed to add ACL %s\n", tok));
4193 goto done;
4195 continue;
4198 DEBUG(5, ("Failed to parse security descriptor\n"));
4199 goto done;
4202 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
4203 owner_sid, group_sid, NULL, dacl, &sd_size);
4205 done:
4206 SAFE_FREE(group_sid);
4207 SAFE_FREE(owner_sid);
4209 return ret;
4213 /* Obtain the current dos attributes */
4214 static DOS_ATTR_DESC *
4215 dos_attr_query(SMBCCTX *context,
4216 TALLOC_CTX *ctx,
4217 const char *filename,
4218 SMBCSRV *srv)
4220 struct timespec create_time_ts;
4221 struct timespec write_time_ts;
4222 struct timespec access_time_ts;
4223 struct timespec change_time_ts;
4224 SMB_OFF_T size = 0;
4225 uint16 mode = 0;
4226 SMB_INO_T inode = 0;
4227 DOS_ATTR_DESC *ret;
4229 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
4230 if (!ret) {
4231 errno = ENOMEM;
4232 return NULL;
4235 /* Obtain the DOS attributes */
4236 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
4237 &mode, &size,
4238 &create_time_ts,
4239 &access_time_ts,
4240 &write_time_ts,
4241 &change_time_ts,
4242 &inode)) {
4244 errno = smbc_errno(context, srv->cli);
4245 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
4246 return NULL;
4250 ret->mode = mode;
4251 ret->size = size;
4252 ret->create_time = convert_timespec_to_time_t(create_time_ts);
4253 ret->access_time = convert_timespec_to_time_t(access_time_ts);
4254 ret->write_time = convert_timespec_to_time_t(write_time_ts);
4255 ret->change_time = convert_timespec_to_time_t(change_time_ts);
4256 ret->inode = inode;
4258 return ret;
4262 /* parse a ascii version of a security descriptor */
4263 static void
4264 dos_attr_parse(SMBCCTX *context,
4265 DOS_ATTR_DESC *dad,
4266 SMBCSRV *srv,
4267 char *str)
4269 int n;
4270 const char *p = str;
4271 fstring tok;
4272 struct {
4273 const char * create_time_attr;
4274 const char * access_time_attr;
4275 const char * write_time_attr;
4276 const char * change_time_attr;
4277 } attr_strings;
4279 /* Determine whether to use old-style or new-style attribute names */
4280 if (context->internal->_full_time_names) {
4281 /* new-style names */
4282 attr_strings.create_time_attr = "CREATE_TIME";
4283 attr_strings.access_time_attr = "ACCESS_TIME";
4284 attr_strings.write_time_attr = "WRITE_TIME";
4285 attr_strings.change_time_attr = "CHANGE_TIME";
4286 } else {
4287 /* old-style names */
4288 attr_strings.create_time_attr = NULL;
4289 attr_strings.access_time_attr = "A_TIME";
4290 attr_strings.write_time_attr = "M_TIME";
4291 attr_strings.change_time_attr = "C_TIME";
4294 /* if this is to set the entire ACL... */
4295 if (*str == '*') {
4296 /* ... then increment past the first colon if there is one */
4297 if ((p = strchr(str, ':')) != NULL) {
4298 ++p;
4299 } else {
4300 p = str;
4304 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4306 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
4307 dad->mode = strtol(tok+5, NULL, 16);
4308 continue;
4311 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4312 dad->size = (SMB_OFF_T)atof(tok+5);
4313 continue;
4316 n = strlen(attr_strings.access_time_attr);
4317 if (StrnCaseCmp(tok, attr_strings.access_time_attr, n) == 0) {
4318 dad->access_time = (time_t)strtol(tok+n+1, NULL, 10);
4319 continue;
4322 n = strlen(attr_strings.change_time_attr);
4323 if (StrnCaseCmp(tok, attr_strings.change_time_attr, n) == 0) {
4324 dad->change_time = (time_t)strtol(tok+n+1, NULL, 10);
4325 continue;
4328 n = strlen(attr_strings.write_time_attr);
4329 if (StrnCaseCmp(tok, attr_strings.write_time_attr, n) == 0) {
4330 dad->write_time = (time_t)strtol(tok+n+1, NULL, 10);
4331 continue;
4334 if (attr_strings.create_time_attr != NULL) {
4335 n = strlen(attr_strings.create_time_attr);
4336 if (StrnCaseCmp(tok, attr_strings.create_time_attr,
4337 n) == 0) {
4338 dad->create_time = (time_t)strtol(tok+n+1,
4339 NULL, 10);
4340 continue;
4344 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4345 dad->inode = (SMB_INO_T)atof(tok+6);
4346 continue;
4351 /*****************************************************
4352 Retrieve the acls for a file.
4353 *******************************************************/
4355 static int
4356 cacl_get(SMBCCTX *context,
4357 TALLOC_CTX *ctx,
4358 SMBCSRV *srv,
4359 struct cli_state *ipc_cli,
4360 POLICY_HND *pol,
4361 char *filename,
4362 char *attr_name,
4363 char *buf,
4364 int bufsize)
4366 uint32 i;
4367 int n = 0;
4368 int n_used;
4369 bool all;
4370 bool all_nt;
4371 bool all_nt_acls;
4372 bool all_dos;
4373 bool some_nt;
4374 bool some_dos;
4375 bool exclude_nt_revision = False;
4376 bool exclude_nt_owner = False;
4377 bool exclude_nt_group = False;
4378 bool exclude_nt_acl = False;
4379 bool exclude_dos_mode = False;
4380 bool exclude_dos_size = False;
4381 bool exclude_dos_create_time = False;
4382 bool exclude_dos_access_time = False;
4383 bool exclude_dos_write_time = False;
4384 bool exclude_dos_change_time = False;
4385 bool exclude_dos_inode = False;
4386 bool numeric = True;
4387 bool determine_size = (bufsize == 0);
4388 int fnum = -1;
4389 SEC_DESC *sd;
4390 fstring sidstr;
4391 fstring name_sandbox;
4392 char *name;
4393 char *pExclude;
4394 char *p;
4395 struct timespec create_time_ts;
4396 struct timespec write_time_ts;
4397 struct timespec access_time_ts;
4398 struct timespec change_time_ts;
4399 time_t create_time = (time_t)0;
4400 time_t write_time = (time_t)0;
4401 time_t access_time = (time_t)0;
4402 time_t change_time = (time_t)0;
4403 SMB_OFF_T size = 0;
4404 uint16 mode = 0;
4405 SMB_INO_T ino = 0;
4406 struct cli_state *cli = srv->cli;
4407 struct {
4408 const char * create_time_attr;
4409 const char * access_time_attr;
4410 const char * write_time_attr;
4411 const char * change_time_attr;
4412 } attr_strings;
4413 struct {
4414 const char * create_time_attr;
4415 const char * access_time_attr;
4416 const char * write_time_attr;
4417 const char * change_time_attr;
4418 } excl_attr_strings;
4420 /* Determine whether to use old-style or new-style attribute names */
4421 if (context->internal->_full_time_names) {
4422 /* new-style names */
4423 attr_strings.create_time_attr = "CREATE_TIME";
4424 attr_strings.access_time_attr = "ACCESS_TIME";
4425 attr_strings.write_time_attr = "WRITE_TIME";
4426 attr_strings.change_time_attr = "CHANGE_TIME";
4428 excl_attr_strings.create_time_attr = "CREATE_TIME";
4429 excl_attr_strings.access_time_attr = "ACCESS_TIME";
4430 excl_attr_strings.write_time_attr = "WRITE_TIME";
4431 excl_attr_strings.change_time_attr = "CHANGE_TIME";
4432 } else {
4433 /* old-style names */
4434 attr_strings.create_time_attr = NULL;
4435 attr_strings.access_time_attr = "A_TIME";
4436 attr_strings.write_time_attr = "M_TIME";
4437 attr_strings.change_time_attr = "C_TIME";
4439 excl_attr_strings.create_time_attr = NULL;
4440 excl_attr_strings.access_time_attr = "dos_attr.A_TIME";
4441 excl_attr_strings.write_time_attr = "dos_attr.M_TIME";
4442 excl_attr_strings.change_time_attr = "dos_attr.C_TIME";
4445 /* Copy name so we can strip off exclusions (if any are specified) */
4446 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4448 /* Ensure name is null terminated */
4449 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4451 /* Play in the sandbox */
4452 name = name_sandbox;
4454 /* If there are any exclusions, point to them and mask them from name */
4455 if ((pExclude = strchr(name, '!')) != NULL)
4457 *pExclude++ = '\0';
4460 all = (StrnCaseCmp(name, "system.*", 8) == 0);
4461 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4462 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4463 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4464 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4465 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4466 numeric = (* (name + strlen(name) - 1) != '+');
4468 /* Look for exclusions from "all" requests */
4469 if (all || all_nt || all_dos) {
4471 /* Exclusions are delimited by '!' */
4472 for (;
4473 pExclude != NULL;
4474 pExclude = (p == NULL ? NULL : p + 1)) {
4476 /* Find end of this exclusion name */
4477 if ((p = strchr(pExclude, '!')) != NULL)
4479 *p = '\0';
4482 /* Which exclusion name is this? */
4483 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4484 exclude_nt_revision = True;
4486 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4487 exclude_nt_owner = True;
4489 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4490 exclude_nt_group = True;
4492 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4493 exclude_nt_acl = True;
4495 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4496 exclude_dos_mode = True;
4498 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4499 exclude_dos_size = True;
4501 else if (excl_attr_strings.create_time_attr != NULL &&
4502 StrCaseCmp(pExclude,
4503 excl_attr_strings.change_time_attr) == 0) {
4504 exclude_dos_create_time = True;
4506 else if (StrCaseCmp(pExclude,
4507 excl_attr_strings.access_time_attr) == 0) {
4508 exclude_dos_access_time = True;
4510 else if (StrCaseCmp(pExclude,
4511 excl_attr_strings.write_time_attr) == 0) {
4512 exclude_dos_write_time = True;
4514 else if (StrCaseCmp(pExclude,
4515 excl_attr_strings.change_time_attr) == 0) {
4516 exclude_dos_change_time = True;
4518 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4519 exclude_dos_inode = True;
4521 else {
4522 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4523 pExclude));
4524 errno = ENOATTR;
4525 return -1;
4530 n_used = 0;
4533 * If we are (possibly) talking to an NT or new system and some NT
4534 * attributes have been requested...
4536 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4537 /* Point to the portion after "system.nt_sec_desc." */
4538 name += 19; /* if (all) this will be invalid but unused */
4540 /* ... then obtain any NT attributes which were requested */
4541 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4543 if (fnum == -1) {
4544 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4545 filename, cli_errstr(cli)));
4546 errno = 0;
4547 return -1;
4550 sd = cli_query_secdesc(cli, fnum, ctx);
4552 if (!sd) {
4553 DEBUG(5,
4554 ("cacl_get Failed to query old descriptor\n"));
4555 errno = 0;
4556 return -1;
4559 cli_close(cli, fnum);
4561 if (! exclude_nt_revision) {
4562 if (all || all_nt) {
4563 if (determine_size) {
4564 p = talloc_asprintf(ctx,
4565 "REVISION:%d",
4566 sd->revision);
4567 if (!p) {
4568 errno = ENOMEM;
4569 return -1;
4571 n = strlen(p);
4572 } else {
4573 n = snprintf(buf, bufsize,
4574 "REVISION:%d",
4575 sd->revision);
4577 } else if (StrCaseCmp(name, "revision") == 0) {
4578 if (determine_size) {
4579 p = talloc_asprintf(ctx, "%d",
4580 sd->revision);
4581 if (!p) {
4582 errno = ENOMEM;
4583 return -1;
4585 n = strlen(p);
4586 } else {
4587 n = snprintf(buf, bufsize, "%d",
4588 sd->revision);
4592 if (!determine_size && n > bufsize) {
4593 errno = ERANGE;
4594 return -1;
4596 buf += n;
4597 n_used += n;
4598 bufsize -= n;
4599 n = 0;
4602 if (! exclude_nt_owner) {
4603 /* Get owner and group sid */
4604 if (sd->owner_sid) {
4605 convert_sid_to_string(ipc_cli, pol,
4606 sidstr,
4607 numeric,
4608 sd->owner_sid);
4609 } else {
4610 fstrcpy(sidstr, "");
4613 if (all || all_nt) {
4614 if (determine_size) {
4615 p = talloc_asprintf(ctx, ",OWNER:%s",
4616 sidstr);
4617 if (!p) {
4618 errno = ENOMEM;
4619 return -1;
4621 n = strlen(p);
4622 } else if (sidstr[0] != '\0') {
4623 n = snprintf(buf, bufsize,
4624 ",OWNER:%s", sidstr);
4626 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4627 if (determine_size) {
4628 p = talloc_asprintf(ctx, "%s", sidstr);
4629 if (!p) {
4630 errno = ENOMEM;
4631 return -1;
4633 n = strlen(p);
4634 } else {
4635 n = snprintf(buf, bufsize, "%s",
4636 sidstr);
4640 if (!determine_size && n > bufsize) {
4641 errno = ERANGE;
4642 return -1;
4644 buf += n;
4645 n_used += n;
4646 bufsize -= n;
4647 n = 0;
4650 if (! exclude_nt_group) {
4651 if (sd->group_sid) {
4652 convert_sid_to_string(ipc_cli, pol,
4653 sidstr, numeric,
4654 sd->group_sid);
4655 } else {
4656 fstrcpy(sidstr, "");
4659 if (all || all_nt) {
4660 if (determine_size) {
4661 p = talloc_asprintf(ctx, ",GROUP:%s",
4662 sidstr);
4663 if (!p) {
4664 errno = ENOMEM;
4665 return -1;
4667 n = strlen(p);
4668 } else if (sidstr[0] != '\0') {
4669 n = snprintf(buf, bufsize,
4670 ",GROUP:%s", sidstr);
4672 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4673 if (determine_size) {
4674 p = talloc_asprintf(ctx, "%s", sidstr);
4675 if (!p) {
4676 errno = ENOMEM;
4677 return -1;
4679 n = strlen(p);
4680 } else {
4681 n = snprintf(buf, bufsize,
4682 "%s", sidstr);
4686 if (!determine_size && n > bufsize) {
4687 errno = ERANGE;
4688 return -1;
4690 buf += n;
4691 n_used += n;
4692 bufsize -= n;
4693 n = 0;
4696 if (! exclude_nt_acl) {
4697 /* Add aces to value buffer */
4698 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4700 SEC_ACE *ace = &sd->dacl->aces[i];
4701 convert_sid_to_string(ipc_cli, pol,
4702 sidstr, numeric,
4703 &ace->trustee);
4705 if (all || all_nt) {
4706 if (determine_size) {
4707 p = talloc_asprintf(
4708 ctx,
4709 ",ACL:"
4710 "%s:%d/%d/0x%08x",
4711 sidstr,
4712 ace->type,
4713 ace->flags,
4714 ace->access_mask);
4715 if (!p) {
4716 errno = ENOMEM;
4717 return -1;
4719 n = strlen(p);
4720 } else {
4721 n = snprintf(
4722 buf, bufsize,
4723 ",ACL:%s:%d/%d/0x%08x",
4724 sidstr,
4725 ace->type,
4726 ace->flags,
4727 ace->access_mask);
4729 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4730 StrCaseCmp(name+3, sidstr) == 0) ||
4731 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4732 StrCaseCmp(name+4, sidstr) == 0)) {
4733 if (determine_size) {
4734 p = talloc_asprintf(
4735 ctx,
4736 "%d/%d/0x%08x",
4737 ace->type,
4738 ace->flags,
4739 ace->access_mask);
4740 if (!p) {
4741 errno = ENOMEM;
4742 return -1;
4744 n = strlen(p);
4745 } else {
4746 n = snprintf(buf, bufsize,
4747 "%d/%d/0x%08x",
4748 ace->type,
4749 ace->flags,
4750 ace->access_mask);
4752 } else if (all_nt_acls) {
4753 if (determine_size) {
4754 p = talloc_asprintf(
4755 ctx,
4756 "%s%s:%d/%d/0x%08x",
4757 i ? "," : "",
4758 sidstr,
4759 ace->type,
4760 ace->flags,
4761 ace->access_mask);
4762 if (!p) {
4763 errno = ENOMEM;
4764 return -1;
4766 n = strlen(p);
4767 } else {
4768 n = snprintf(buf, bufsize,
4769 "%s%s:%d/%d/0x%08x",
4770 i ? "," : "",
4771 sidstr,
4772 ace->type,
4773 ace->flags,
4774 ace->access_mask);
4777 if (!determine_size && n > bufsize) {
4778 errno = ERANGE;
4779 return -1;
4781 buf += n;
4782 n_used += n;
4783 bufsize -= n;
4784 n = 0;
4788 /* Restore name pointer to its original value */
4789 name -= 19;
4792 if (all || some_dos) {
4793 /* Point to the portion after "system.dos_attr." */
4794 name += 16; /* if (all) this will be invalid but unused */
4796 /* Obtain the DOS attributes */
4797 if (!smbc_getatr(context, srv, filename, &mode, &size,
4798 &create_time_ts,
4799 &access_time_ts,
4800 &write_time_ts,
4801 &change_time_ts,
4802 &ino)) {
4804 errno = smbc_errno(context, srv->cli);
4805 return -1;
4809 create_time = convert_timespec_to_time_t(create_time_ts);
4810 access_time = convert_timespec_to_time_t(access_time_ts);
4811 write_time = convert_timespec_to_time_t(write_time_ts);
4812 change_time = convert_timespec_to_time_t(change_time_ts);
4814 if (! exclude_dos_mode) {
4815 if (all || all_dos) {
4816 if (determine_size) {
4817 p = talloc_asprintf(ctx,
4818 "%sMODE:0x%x",
4819 (ipc_cli &&
4820 (all || some_nt)
4821 ? ","
4822 : ""),
4823 mode);
4824 if (!p) {
4825 errno = ENOMEM;
4826 return -1;
4828 n = strlen(p);
4829 } else {
4830 n = snprintf(buf, bufsize,
4831 "%sMODE:0x%x",
4832 (ipc_cli &&
4833 (all || some_nt)
4834 ? ","
4835 : ""),
4836 mode);
4838 } else if (StrCaseCmp(name, "mode") == 0) {
4839 if (determine_size) {
4840 p = talloc_asprintf(ctx, "0x%x", mode);
4841 if (!p) {
4842 errno = ENOMEM;
4843 return -1;
4845 n = strlen(p);
4846 } else {
4847 n = snprintf(buf, bufsize,
4848 "0x%x", mode);
4852 if (!determine_size && n > bufsize) {
4853 errno = ERANGE;
4854 return -1;
4856 buf += n;
4857 n_used += n;
4858 bufsize -= n;
4859 n = 0;
4862 if (! exclude_dos_size) {
4863 if (all || all_dos) {
4864 if (determine_size) {
4865 p = talloc_asprintf(
4866 ctx,
4867 ",SIZE:%.0f",
4868 (double)size);
4869 if (!p) {
4870 errno = ENOMEM;
4871 return -1;
4873 n = strlen(p);
4874 } else {
4875 n = snprintf(buf, bufsize,
4876 ",SIZE:%.0f",
4877 (double)size);
4879 } else if (StrCaseCmp(name, "size") == 0) {
4880 if (determine_size) {
4881 p = talloc_asprintf(
4882 ctx,
4883 "%.0f",
4884 (double)size);
4885 if (!p) {
4886 errno = ENOMEM;
4887 return -1;
4889 n = strlen(p);
4890 } else {
4891 n = snprintf(buf, bufsize,
4892 "%.0f",
4893 (double)size);
4897 if (!determine_size && n > bufsize) {
4898 errno = ERANGE;
4899 return -1;
4901 buf += n;
4902 n_used += n;
4903 bufsize -= n;
4904 n = 0;
4907 if (! exclude_dos_create_time &&
4908 attr_strings.create_time_attr != NULL) {
4909 if (all || all_dos) {
4910 if (determine_size) {
4911 p = talloc_asprintf(ctx,
4912 ",%s:%lu",
4913 attr_strings.create_time_attr,
4914 create_time);
4915 if (!p) {
4916 errno = ENOMEM;
4917 return -1;
4919 n = strlen(p);
4920 } else {
4921 n = snprintf(buf, bufsize,
4922 ",%s:%lu",
4923 attr_strings.create_time_attr,
4924 create_time);
4926 } else if (StrCaseCmp(name, attr_strings.create_time_attr) == 0) {
4927 if (determine_size) {
4928 p = talloc_asprintf(ctx, "%lu", create_time);
4929 if (!p) {
4930 errno = ENOMEM;
4931 return -1;
4933 n = strlen(p);
4934 } else {
4935 n = snprintf(buf, bufsize,
4936 "%lu", create_time);
4940 if (!determine_size && n > bufsize) {
4941 errno = ERANGE;
4942 return -1;
4944 buf += n;
4945 n_used += n;
4946 bufsize -= n;
4947 n = 0;
4950 if (! exclude_dos_access_time) {
4951 if (all || all_dos) {
4952 if (determine_size) {
4953 p = talloc_asprintf(ctx,
4954 ",%s:%lu",
4955 attr_strings.access_time_attr,
4956 access_time);
4957 if (!p) {
4958 errno = ENOMEM;
4959 return -1;
4961 n = strlen(p);
4962 } else {
4963 n = snprintf(buf, bufsize,
4964 ",%s:%lu",
4965 attr_strings.access_time_attr,
4966 access_time);
4968 } else if (StrCaseCmp(name, attr_strings.access_time_attr) == 0) {
4969 if (determine_size) {
4970 p = talloc_asprintf(ctx, "%lu", access_time);
4971 if (!p) {
4972 errno = ENOMEM;
4973 return -1;
4975 n = strlen(p);
4976 } else {
4977 n = snprintf(buf, bufsize,
4978 "%lu", access_time);
4982 if (!determine_size && n > bufsize) {
4983 errno = ERANGE;
4984 return -1;
4986 buf += n;
4987 n_used += n;
4988 bufsize -= n;
4989 n = 0;
4992 if (! exclude_dos_write_time) {
4993 if (all || all_dos) {
4994 if (determine_size) {
4995 p = talloc_asprintf(ctx,
4996 ",%s:%lu",
4997 attr_strings.write_time_attr,
4998 write_time);
4999 if (!p) {
5000 errno = ENOMEM;
5001 return -1;
5003 n = strlen(p);
5004 } else {
5005 n = snprintf(buf, bufsize,
5006 ",%s:%lu",
5007 attr_strings.write_time_attr,
5008 write_time);
5010 } else if (StrCaseCmp(name, attr_strings.write_time_attr) == 0) {
5011 if (determine_size) {
5012 p = talloc_asprintf(ctx, "%lu", write_time);
5013 if (!p) {
5014 errno = ENOMEM;
5015 return -1;
5017 n = strlen(p);
5018 } else {
5019 n = snprintf(buf, bufsize,
5020 "%lu", write_time);
5024 if (!determine_size && n > bufsize) {
5025 errno = ERANGE;
5026 return -1;
5028 buf += n;
5029 n_used += n;
5030 bufsize -= n;
5031 n = 0;
5034 if (! exclude_dos_change_time) {
5035 if (all || all_dos) {
5036 if (determine_size) {
5037 p = talloc_asprintf(ctx,
5038 ",%s:%lu",
5039 attr_strings.change_time_attr,
5040 change_time);
5041 if (!p) {
5042 errno = ENOMEM;
5043 return -1;
5045 n = strlen(p);
5046 } else {
5047 n = snprintf(buf, bufsize,
5048 ",%s:%lu",
5049 attr_strings.change_time_attr,
5050 change_time);
5052 } else if (StrCaseCmp(name, attr_strings.change_time_attr) == 0) {
5053 if (determine_size) {
5054 p = talloc_asprintf(ctx, "%lu", change_time);
5055 if (!p) {
5056 errno = ENOMEM;
5057 return -1;
5059 n = strlen(p);
5060 } else {
5061 n = snprintf(buf, bufsize,
5062 "%lu", change_time);
5066 if (!determine_size && n > bufsize) {
5067 errno = ERANGE;
5068 return -1;
5070 buf += n;
5071 n_used += n;
5072 bufsize -= n;
5073 n = 0;
5076 if (! exclude_dos_inode) {
5077 if (all || all_dos) {
5078 if (determine_size) {
5079 p = talloc_asprintf(
5080 ctx,
5081 ",INODE:%.0f",
5082 (double)ino);
5083 if (!p) {
5084 errno = ENOMEM;
5085 return -1;
5087 n = strlen(p);
5088 } else {
5089 n = snprintf(buf, bufsize,
5090 ",INODE:%.0f",
5091 (double) ino);
5093 } else if (StrCaseCmp(name, "inode") == 0) {
5094 if (determine_size) {
5095 p = talloc_asprintf(
5096 ctx,
5097 "%.0f",
5098 (double) ino);
5099 if (!p) {
5100 errno = ENOMEM;
5101 return -1;
5103 n = strlen(p);
5104 } else {
5105 n = snprintf(buf, bufsize,
5106 "%.0f",
5107 (double) ino);
5111 if (!determine_size && n > bufsize) {
5112 errno = ERANGE;
5113 return -1;
5115 buf += n;
5116 n_used += n;
5117 bufsize -= n;
5118 n = 0;
5121 /* Restore name pointer to its original value */
5122 name -= 16;
5125 if (n_used == 0) {
5126 errno = ENOATTR;
5127 return -1;
5130 return n_used;
5134 /*****************************************************
5135 set the ACLs on a file given an ascii description
5136 *******************************************************/
5137 static int
5138 cacl_set(TALLOC_CTX *ctx,
5139 struct cli_state *cli,
5140 struct cli_state *ipc_cli,
5141 POLICY_HND *pol,
5142 const char *filename,
5143 const char *the_acl,
5144 int mode,
5145 int flags)
5147 int fnum;
5148 int err = 0;
5149 SEC_DESC *sd = NULL, *old;
5150 SEC_ACL *dacl = NULL;
5151 DOM_SID *owner_sid = NULL;
5152 DOM_SID *group_sid = NULL;
5153 uint32 i, j;
5154 size_t sd_size;
5155 int ret = 0;
5156 char *p;
5157 bool numeric = True;
5159 /* the_acl will be null for REMOVE_ALL operations */
5160 if (the_acl) {
5161 numeric = ((p = strchr(the_acl, ':')) != NULL &&
5162 p > the_acl &&
5163 p[-1] != '+');
5165 /* if this is to set the entire ACL... */
5166 if (*the_acl == '*') {
5167 /* ... then increment past the first colon */
5168 the_acl = p + 1;
5171 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
5172 CONST_DISCARD(char *, the_acl));
5174 if (!sd) {
5175 errno = EINVAL;
5176 return -1;
5180 /* SMBC_XATTR_MODE_REMOVE_ALL is the only caller
5181 that doesn't deref sd */
5183 if (!sd && (mode != SMBC_XATTR_MODE_REMOVE_ALL)) {
5184 errno = EINVAL;
5185 return -1;
5188 /* The desired access below is the only one I could find that works
5189 with NT4, W2KP and Samba */
5191 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
5193 if (fnum == -1) {
5194 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5195 filename, cli_errstr(cli)));
5196 errno = 0;
5197 return -1;
5200 old = cli_query_secdesc(cli, fnum, ctx);
5202 if (!old) {
5203 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
5204 errno = 0;
5205 return -1;
5208 cli_close(cli, fnum);
5210 switch (mode) {
5211 case SMBC_XATTR_MODE_REMOVE_ALL:
5212 old->dacl->num_aces = 0;
5213 dacl = old->dacl;
5214 break;
5216 case SMBC_XATTR_MODE_REMOVE:
5217 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5218 bool found = False;
5220 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
5221 if (sec_ace_equal(&sd->dacl->aces[i],
5222 &old->dacl->aces[j])) {
5223 uint32 k;
5224 for (k=j; k<old->dacl->num_aces-1;k++) {
5225 old->dacl->aces[k] =
5226 old->dacl->aces[k+1];
5228 old->dacl->num_aces--;
5229 found = True;
5230 dacl = old->dacl;
5231 break;
5235 if (!found) {
5236 err = ENOATTR;
5237 ret = -1;
5238 goto failed;
5241 break;
5243 case SMBC_XATTR_MODE_ADD:
5244 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5245 bool found = False;
5247 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
5248 if (sid_equal(&sd->dacl->aces[i].trustee,
5249 &old->dacl->aces[j].trustee)) {
5250 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
5251 err = EEXIST;
5252 ret = -1;
5253 goto failed;
5255 old->dacl->aces[j] = sd->dacl->aces[i];
5256 ret = -1;
5257 found = True;
5261 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
5262 err = ENOATTR;
5263 ret = -1;
5264 goto failed;
5267 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5268 add_ace(&old->dacl, &sd->dacl->aces[i], ctx);
5271 dacl = old->dacl;
5272 break;
5274 case SMBC_XATTR_MODE_SET:
5275 old = sd;
5276 owner_sid = old->owner_sid;
5277 group_sid = old->group_sid;
5278 dacl = old->dacl;
5279 break;
5281 case SMBC_XATTR_MODE_CHOWN:
5282 owner_sid = sd->owner_sid;
5283 break;
5285 case SMBC_XATTR_MODE_CHGRP:
5286 group_sid = sd->group_sid;
5287 break;
5290 /* Denied ACE entries must come before allowed ones */
5291 sort_acl(old->dacl);
5293 /* Create new security descriptor and set it */
5294 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
5295 owner_sid, group_sid, NULL, dacl, &sd_size);
5297 fnum = cli_nt_create(cli, filename,
5298 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
5300 if (fnum == -1) {
5301 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5302 filename, cli_errstr(cli)));
5303 errno = 0;
5304 return -1;
5307 if (!cli_set_secdesc(cli, fnum, sd)) {
5308 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
5309 ret = -1;
5312 /* Clean up */
5314 failed:
5315 cli_close(cli, fnum);
5317 if (err != 0) {
5318 errno = err;
5321 return ret;
5325 static int
5326 smbc_setxattr_ctx(SMBCCTX *context,
5327 const char *fname,
5328 const char *name,
5329 const void *value,
5330 size_t size,
5331 int flags)
5333 int ret;
5334 int ret2;
5335 SMBCSRV *srv;
5336 SMBCSRV *ipc_srv;
5337 fstring server;
5338 fstring share;
5339 fstring user;
5340 fstring password;
5341 fstring workgroup;
5342 pstring path;
5343 TALLOC_CTX *ctx;
5344 POLICY_HND pol;
5345 DOS_ATTR_DESC *dad;
5346 struct {
5347 const char * create_time_attr;
5348 const char * access_time_attr;
5349 const char * write_time_attr;
5350 const char * change_time_attr;
5351 } attr_strings;
5353 if (!context || !context->internal ||
5354 !context->internal->_initialized) {
5356 errno = EINVAL; /* Best I can think of ... */
5357 return -1;
5361 if (!fname) {
5363 errno = EINVAL;
5364 return -1;
5368 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
5369 fname, name, (int) size, (const char*)value));
5371 if (smbc_parse_path(context, fname,
5372 workgroup, sizeof(workgroup),
5373 server, sizeof(server),
5374 share, sizeof(share),
5375 path, sizeof(path),
5376 user, sizeof(user),
5377 password, sizeof(password),
5378 NULL, 0)) {
5379 errno = EINVAL;
5380 return -1;
5383 if (user[0] == (char)0) fstrcpy(user, context->user);
5385 srv = smbc_server(context, True,
5386 server, share, workgroup, user, password);
5387 if (!srv) {
5388 return -1; /* errno set by smbc_server */
5391 if (! srv->no_nt_session) {
5392 ipc_srv = smbc_attr_server(context, server, share,
5393 workgroup, user, password,
5394 &pol);
5395 if (! ipc_srv) {
5396 srv->no_nt_session = True;
5398 } else {
5399 ipc_srv = NULL;
5402 ctx = talloc_init("smbc_setxattr");
5403 if (!ctx) {
5404 errno = ENOMEM;
5405 return -1;
5409 * Are they asking to set the entire set of known attributes?
5411 if (StrCaseCmp(name, "system.*") == 0 ||
5412 StrCaseCmp(name, "system.*+") == 0) {
5413 /* Yup. */
5414 char *namevalue =
5415 talloc_asprintf(ctx, "%s:%s",
5416 name+7, (const char *) value);
5417 if (! namevalue) {
5418 errno = ENOMEM;
5419 ret = -1;
5420 return -1;
5423 if (ipc_srv) {
5424 ret = cacl_set(ctx, srv->cli,
5425 ipc_srv->cli, &pol, path,
5426 namevalue,
5427 (*namevalue == '*'
5428 ? SMBC_XATTR_MODE_SET
5429 : SMBC_XATTR_MODE_ADD),
5430 flags);
5431 } else {
5432 ret = 0;
5435 /* get a DOS Attribute Descriptor with current attributes */
5436 dad = dos_attr_query(context, ctx, path, srv);
5437 if (dad) {
5438 /* Overwrite old with new, using what was provided */
5439 dos_attr_parse(context, dad, srv, namevalue);
5441 /* Set the new DOS attributes */
5442 if (! smbc_setatr(context, srv, path,
5443 dad->create_time,
5444 dad->access_time,
5445 dad->write_time,
5446 dad->change_time,
5447 dad->mode)) {
5449 /* cause failure if NT failed too */
5450 dad = NULL;
5454 /* we only fail if both NT and DOS sets failed */
5455 if (ret < 0 && ! dad) {
5456 ret = -1; /* in case dad was null */
5458 else {
5459 ret = 0;
5462 talloc_destroy(ctx);
5463 return ret;
5467 * Are they asking to set an access control element or to set
5468 * the entire access control list?
5470 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5471 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5472 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5473 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5474 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5476 /* Yup. */
5477 char *namevalue =
5478 talloc_asprintf(ctx, "%s:%s",
5479 name+19, (const char *) value);
5481 if (! ipc_srv) {
5482 ret = -1; /* errno set by smbc_server() */
5484 else if (! namevalue) {
5485 errno = ENOMEM;
5486 ret = -1;
5487 } else {
5488 ret = cacl_set(ctx, srv->cli,
5489 ipc_srv->cli, &pol, path,
5490 namevalue,
5491 (*namevalue == '*'
5492 ? SMBC_XATTR_MODE_SET
5493 : SMBC_XATTR_MODE_ADD),
5494 flags);
5496 talloc_destroy(ctx);
5497 return ret;
5501 * Are they asking to set the owner?
5503 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5504 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5506 /* Yup. */
5507 char *namevalue =
5508 talloc_asprintf(ctx, "%s:%s",
5509 name+19, (const char *) value);
5511 if (! ipc_srv) {
5513 ret = -1; /* errno set by smbc_server() */
5515 else if (! namevalue) {
5516 errno = ENOMEM;
5517 ret = -1;
5518 } else {
5519 ret = cacl_set(ctx, srv->cli,
5520 ipc_srv->cli, &pol, path,
5521 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5523 talloc_destroy(ctx);
5524 return ret;
5528 * Are they asking to set the group?
5530 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5531 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5533 /* Yup. */
5534 char *namevalue =
5535 talloc_asprintf(ctx, "%s:%s",
5536 name+19, (const char *) value);
5538 if (! ipc_srv) {
5539 /* errno set by smbc_server() */
5540 ret = -1;
5542 else if (! namevalue) {
5543 errno = ENOMEM;
5544 ret = -1;
5545 } else {
5546 ret = cacl_set(ctx, srv->cli,
5547 ipc_srv->cli, &pol, path,
5548 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5550 talloc_destroy(ctx);
5551 return ret;
5554 /* Determine whether to use old-style or new-style attribute names */
5555 if (context->internal->_full_time_names) {
5556 /* new-style names */
5557 attr_strings.create_time_attr = "system.dos_attr.CREATE_TIME";
5558 attr_strings.access_time_attr = "system.dos_attr.ACCESS_TIME";
5559 attr_strings.write_time_attr = "system.dos_attr.WRITE_TIME";
5560 attr_strings.change_time_attr = "system.dos_attr.CHANGE_TIME";
5561 } else {
5562 /* old-style names */
5563 attr_strings.create_time_attr = NULL;
5564 attr_strings.access_time_attr = "system.dos_attr.A_TIME";
5565 attr_strings.write_time_attr = "system.dos_attr.M_TIME";
5566 attr_strings.change_time_attr = "system.dos_attr.C_TIME";
5570 * Are they asking to set a DOS attribute?
5572 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5573 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5574 (attr_strings.create_time_attr != NULL &&
5575 StrCaseCmp(name, attr_strings.create_time_attr) == 0) ||
5576 StrCaseCmp(name, attr_strings.access_time_attr) == 0 ||
5577 StrCaseCmp(name, attr_strings.write_time_attr) == 0 ||
5578 StrCaseCmp(name, attr_strings.change_time_attr) == 0) {
5580 /* get a DOS Attribute Descriptor with current attributes */
5581 dad = dos_attr_query(context, ctx, path, srv);
5582 if (dad) {
5583 char *namevalue =
5584 talloc_asprintf(ctx, "%s:%s",
5585 name+16, (const char *) value);
5586 if (! namevalue) {
5587 errno = ENOMEM;
5588 ret = -1;
5589 } else {
5590 /* Overwrite old with provided new params */
5591 dos_attr_parse(context, dad, srv, namevalue);
5593 /* Set the new DOS attributes */
5594 ret2 = smbc_setatr(context, srv, path,
5595 dad->create_time,
5596 dad->access_time,
5597 dad->write_time,
5598 dad->change_time,
5599 dad->mode);
5601 /* ret2 has True (success) / False (failure) */
5602 if (ret2) {
5603 ret = 0;
5604 } else {
5605 ret = -1;
5608 } else {
5609 ret = -1;
5612 talloc_destroy(ctx);
5613 return ret;
5616 /* Unsupported attribute name */
5617 talloc_destroy(ctx);
5618 errno = EINVAL;
5619 return -1;
5622 static int
5623 smbc_getxattr_ctx(SMBCCTX *context,
5624 const char *fname,
5625 const char *name,
5626 const void *value,
5627 size_t size)
5629 int ret;
5630 SMBCSRV *srv;
5631 SMBCSRV *ipc_srv;
5632 fstring server;
5633 fstring share;
5634 fstring user;
5635 fstring password;
5636 fstring workgroup;
5637 pstring path;
5638 TALLOC_CTX *ctx;
5639 POLICY_HND pol;
5640 struct {
5641 const char * create_time_attr;
5642 const char * access_time_attr;
5643 const char * write_time_attr;
5644 const char * change_time_attr;
5645 } attr_strings;
5648 if (!context || !context->internal ||
5649 !context->internal->_initialized) {
5651 errno = EINVAL; /* Best I can think of ... */
5652 return -1;
5656 if (!fname) {
5658 errno = EINVAL;
5659 return -1;
5663 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5665 if (smbc_parse_path(context, fname,
5666 workgroup, sizeof(workgroup),
5667 server, sizeof(server),
5668 share, sizeof(share),
5669 path, sizeof(path),
5670 user, sizeof(user),
5671 password, sizeof(password),
5672 NULL, 0)) {
5673 errno = EINVAL;
5674 return -1;
5677 if (user[0] == (char)0) fstrcpy(user, context->user);
5679 srv = smbc_server(context, True,
5680 server, share, workgroup, user, password);
5681 if (!srv) {
5682 return -1; /* errno set by smbc_server */
5685 if (! srv->no_nt_session) {
5686 ipc_srv = smbc_attr_server(context, server, share,
5687 workgroup, user, password,
5688 &pol);
5689 if (! ipc_srv) {
5690 srv->no_nt_session = True;
5692 } else {
5693 ipc_srv = NULL;
5696 ctx = talloc_init("smbc:getxattr");
5697 if (!ctx) {
5698 errno = ENOMEM;
5699 return -1;
5702 /* Determine whether to use old-style or new-style attribute names */
5703 if (context->internal->_full_time_names) {
5704 /* new-style names */
5705 attr_strings.create_time_attr = "system.dos_attr.CREATE_TIME";
5706 attr_strings.access_time_attr = "system.dos_attr.ACCESS_TIME";
5707 attr_strings.write_time_attr = "system.dos_attr.WRITE_TIME";
5708 attr_strings.change_time_attr = "system.dos_attr.CHANGE_TIME";
5709 } else {
5710 /* old-style names */
5711 attr_strings.create_time_attr = NULL;
5712 attr_strings.access_time_attr = "system.dos_attr.A_TIME";
5713 attr_strings.write_time_attr = "system.dos_attr.M_TIME";
5714 attr_strings.change_time_attr = "system.dos_attr.C_TIME";
5717 /* Are they requesting a supported attribute? */
5718 if (StrCaseCmp(name, "system.*") == 0 ||
5719 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5720 StrCaseCmp(name, "system.*+") == 0 ||
5721 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5722 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5723 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5724 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5725 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5726 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5727 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5728 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5729 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5730 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5731 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5732 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5733 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5734 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5735 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5736 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5737 (attr_strings.create_time_attr != NULL &&
5738 StrCaseCmp(name, attr_strings.create_time_attr) == 0) ||
5739 StrCaseCmp(name, attr_strings.access_time_attr) == 0 ||
5740 StrCaseCmp(name, attr_strings.write_time_attr) == 0 ||
5741 StrCaseCmp(name, attr_strings.change_time_attr) == 0 ||
5742 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5744 /* Yup. */
5745 ret = cacl_get(context, ctx, srv,
5746 ipc_srv == NULL ? NULL : ipc_srv->cli,
5747 &pol, path,
5748 CONST_DISCARD(char *, name),
5749 CONST_DISCARD(char *, value), size);
5750 if (ret < 0 && errno == 0) {
5751 errno = smbc_errno(context, srv->cli);
5753 talloc_destroy(ctx);
5754 return ret;
5757 /* Unsupported attribute name */
5758 talloc_destroy(ctx);
5759 errno = EINVAL;
5760 return -1;
5764 static int
5765 smbc_removexattr_ctx(SMBCCTX *context,
5766 const char *fname,
5767 const char *name)
5769 int ret;
5770 SMBCSRV *srv;
5771 SMBCSRV *ipc_srv;
5772 fstring server;
5773 fstring share;
5774 fstring user;
5775 fstring password;
5776 fstring workgroup;
5777 pstring path;
5778 TALLOC_CTX *ctx;
5779 POLICY_HND pol;
5781 if (!context || !context->internal ||
5782 !context->internal->_initialized) {
5784 errno = EINVAL; /* Best I can think of ... */
5785 return -1;
5789 if (!fname) {
5791 errno = EINVAL;
5792 return -1;
5796 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5798 if (smbc_parse_path(context, fname,
5799 workgroup, sizeof(workgroup),
5800 server, sizeof(server),
5801 share, sizeof(share),
5802 path, sizeof(path),
5803 user, sizeof(user),
5804 password, sizeof(password),
5805 NULL, 0)) {
5806 errno = EINVAL;
5807 return -1;
5810 if (user[0] == (char)0) fstrcpy(user, context->user);
5812 srv = smbc_server(context, True,
5813 server, share, workgroup, user, password);
5814 if (!srv) {
5815 return -1; /* errno set by smbc_server */
5818 if (! srv->no_nt_session) {
5819 ipc_srv = smbc_attr_server(context, server, share,
5820 workgroup, user, password,
5821 &pol);
5822 if (! ipc_srv) {
5823 srv->no_nt_session = True;
5825 } else {
5826 ipc_srv = NULL;
5829 if (! ipc_srv) {
5830 return -1; /* errno set by smbc_attr_server */
5833 ctx = talloc_init("smbc_removexattr");
5834 if (!ctx) {
5835 errno = ENOMEM;
5836 return -1;
5839 /* Are they asking to set the entire ACL? */
5840 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5841 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5843 /* Yup. */
5844 ret = cacl_set(ctx, srv->cli,
5845 ipc_srv->cli, &pol, path,
5846 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5847 talloc_destroy(ctx);
5848 return ret;
5852 * Are they asking to remove one or more spceific security descriptor
5853 * attributes?
5855 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5856 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5857 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5858 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5859 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5860 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5861 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5863 /* Yup. */
5864 ret = cacl_set(ctx, srv->cli,
5865 ipc_srv->cli, &pol, path,
5866 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5867 talloc_destroy(ctx);
5868 return ret;
5871 /* Unsupported attribute name */
5872 talloc_destroy(ctx);
5873 errno = EINVAL;
5874 return -1;
5877 static int
5878 smbc_listxattr_ctx(SMBCCTX *context,
5879 const char *fname,
5880 char *list,
5881 size_t size)
5884 * This isn't quite what listxattr() is supposed to do. This returns
5885 * the complete set of attribute names, always, rather than only those
5886 * attribute names which actually exist for a file. Hmmm...
5888 const char supported_old[] =
5889 "system.*\0"
5890 "system.*+\0"
5891 "system.nt_sec_desc.revision\0"
5892 "system.nt_sec_desc.owner\0"
5893 "system.nt_sec_desc.owner+\0"
5894 "system.nt_sec_desc.group\0"
5895 "system.nt_sec_desc.group+\0"
5896 "system.nt_sec_desc.acl.*\0"
5897 "system.nt_sec_desc.acl\0"
5898 "system.nt_sec_desc.acl+\0"
5899 "system.nt_sec_desc.*\0"
5900 "system.nt_sec_desc.*+\0"
5901 "system.dos_attr.*\0"
5902 "system.dos_attr.mode\0"
5903 "system.dos_attr.c_time\0"
5904 "system.dos_attr.a_time\0"
5905 "system.dos_attr.m_time\0"
5907 const char supported_new[] =
5908 "system.*\0"
5909 "system.*+\0"
5910 "system.nt_sec_desc.revision\0"
5911 "system.nt_sec_desc.owner\0"
5912 "system.nt_sec_desc.owner+\0"
5913 "system.nt_sec_desc.group\0"
5914 "system.nt_sec_desc.group+\0"
5915 "system.nt_sec_desc.acl.*\0"
5916 "system.nt_sec_desc.acl\0"
5917 "system.nt_sec_desc.acl+\0"
5918 "system.nt_sec_desc.*\0"
5919 "system.nt_sec_desc.*+\0"
5920 "system.dos_attr.*\0"
5921 "system.dos_attr.mode\0"
5922 "system.dos_attr.create_time\0"
5923 "system.dos_attr.access_time\0"
5924 "system.dos_attr.write_time\0"
5925 "system.dos_attr.change_time\0"
5927 const char * supported;
5929 if (context->internal->_full_time_names) {
5930 supported = supported_new;
5931 } else {
5932 supported = supported_old;
5935 if (size == 0) {
5936 return sizeof(supported);
5939 if (sizeof(supported) > size) {
5940 errno = ERANGE;
5941 return -1;
5944 /* this can't be strcpy() because there are embedded null characters */
5945 memcpy(list, supported, sizeof(supported));
5946 return sizeof(supported);
5951 * Open a print file to be written to by other calls
5954 static SMBCFILE *
5955 smbc_open_print_job_ctx(SMBCCTX *context,
5956 const char *fname)
5958 fstring server;
5959 fstring share;
5960 fstring user;
5961 fstring password;
5962 pstring path;
5964 if (!context || !context->internal ||
5965 !context->internal->_initialized) {
5967 errno = EINVAL;
5968 return NULL;
5972 if (!fname) {
5974 errno = EINVAL;
5975 return NULL;
5979 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5981 if (smbc_parse_path(context, fname,
5982 NULL, 0,
5983 server, sizeof(server),
5984 share, sizeof(share),
5985 path, sizeof(path),
5986 user, sizeof(user),
5987 password, sizeof(password),
5988 NULL, 0)) {
5989 errno = EINVAL;
5990 return NULL;
5993 /* What if the path is empty, or the file exists? */
5995 return (context->open)(context, fname, O_WRONLY, 666);
6000 * Routine to print a file on a remote server ...
6002 * We open the file, which we assume to be on a remote server, and then
6003 * copy it to a print file on the share specified by printq.
6006 static int
6007 smbc_print_file_ctx(SMBCCTX *c_file,
6008 const char *fname,
6009 SMBCCTX *c_print,
6010 const char *printq)
6012 SMBCFILE *fid1;
6013 SMBCFILE *fid2;
6014 int bytes;
6015 int saverr;
6016 int tot_bytes = 0;
6017 char buf[4096];
6019 if (!c_file || !c_file->internal->_initialized || !c_print ||
6020 !c_print->internal->_initialized) {
6022 errno = EINVAL;
6023 return -1;
6027 if (!fname && !printq) {
6029 errno = EINVAL;
6030 return -1;
6034 /* Try to open the file for reading ... */
6036 if ((long)(fid1 = (c_file->open)(c_file, fname, O_RDONLY, 0666)) < 0) {
6038 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
6039 return -1; /* smbc_open sets errno */
6043 /* Now, try to open the printer file for writing */
6045 if ((long)(fid2 = (c_print->open_print_job)(c_print, printq)) < 0) {
6047 saverr = errno; /* Save errno */
6048 (c_file->close_fn)(c_file, fid1);
6049 errno = saverr;
6050 return -1;
6054 while ((bytes = (c_file->read)(c_file, fid1, buf, sizeof(buf))) > 0) {
6056 tot_bytes += bytes;
6058 if (((c_print->write)(c_print, fid2, buf, bytes)) < 0) {
6060 saverr = errno;
6061 (c_file->close_fn)(c_file, fid1);
6062 (c_print->close_fn)(c_print, fid2);
6063 errno = saverr;
6069 saverr = errno;
6071 (c_file->close_fn)(c_file, fid1); /* We have to close these anyway */
6072 (c_print->close_fn)(c_print, fid2);
6074 if (bytes < 0) {
6076 errno = saverr;
6077 return -1;
6081 return tot_bytes;
6086 * Routine to list print jobs on a printer share ...
6089 static int
6090 smbc_list_print_jobs_ctx(SMBCCTX *context,
6091 const char *fname,
6092 smbc_list_print_job_fn fn)
6094 SMBCSRV *srv;
6095 fstring server;
6096 fstring share;
6097 fstring user;
6098 fstring password;
6099 fstring workgroup;
6100 pstring path;
6102 if (!context || !context->internal ||
6103 !context->internal->_initialized) {
6105 errno = EINVAL;
6106 return -1;
6110 if (!fname) {
6112 errno = EINVAL;
6113 return -1;
6117 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
6119 if (smbc_parse_path(context, fname,
6120 workgroup, sizeof(workgroup),
6121 server, sizeof(server),
6122 share, sizeof(share),
6123 path, sizeof(path),
6124 user, sizeof(user),
6125 password, sizeof(password),
6126 NULL, 0)) {
6127 errno = EINVAL;
6128 return -1;
6131 if (user[0] == (char)0) fstrcpy(user, context->user);
6133 srv = smbc_server(context, True,
6134 server, share, workgroup, user, password);
6136 if (!srv) {
6138 return -1; /* errno set by smbc_server */
6142 if (cli_print_queue(srv->cli,
6143 (void (*)(struct print_job_info *))fn) < 0) {
6145 errno = smbc_errno(context, srv->cli);
6146 return -1;
6150 return 0;
6155 * Delete a print job from a remote printer share
6158 static int
6159 smbc_unlink_print_job_ctx(SMBCCTX *context,
6160 const char *fname,
6161 int id)
6163 SMBCSRV *srv;
6164 fstring server;
6165 fstring share;
6166 fstring user;
6167 fstring password;
6168 fstring workgroup;
6169 pstring path;
6170 int err;
6172 if (!context || !context->internal ||
6173 !context->internal->_initialized) {
6175 errno = EINVAL;
6176 return -1;
6180 if (!fname) {
6182 errno = EINVAL;
6183 return -1;
6187 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
6189 if (smbc_parse_path(context, fname,
6190 workgroup, sizeof(workgroup),
6191 server, sizeof(server),
6192 share, sizeof(share),
6193 path, sizeof(path),
6194 user, sizeof(user),
6195 password, sizeof(password),
6196 NULL, 0)) {
6197 errno = EINVAL;
6198 return -1;
6201 if (user[0] == (char)0) fstrcpy(user, context->user);
6203 srv = smbc_server(context, True,
6204 server, share, workgroup, user, password);
6206 if (!srv) {
6208 return -1; /* errno set by smbc_server */
6212 if ((err = cli_printjob_del(srv->cli, id)) != 0) {
6214 if (err < 0)
6215 errno = smbc_errno(context, srv->cli);
6216 else if (err == ERRnosuchprintjob)
6217 errno = EINVAL;
6218 return -1;
6222 return 0;
6227 * Get a new empty handle to fill in with your own info
6229 SMBCCTX *
6230 smbc_new_context(void)
6232 SMBCCTX *context;
6234 context = SMB_MALLOC_P(SMBCCTX);
6235 if (!context) {
6236 errno = ENOMEM;
6237 return NULL;
6240 ZERO_STRUCTP(context);
6242 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
6243 if (!context->internal) {
6244 SAFE_FREE(context);
6245 errno = ENOMEM;
6246 return NULL;
6249 ZERO_STRUCTP(context->internal);
6252 /* ADD REASONABLE DEFAULTS */
6253 context->debug = 0;
6254 context->timeout = 20000; /* 20 seconds */
6256 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
6257 context->options.urlencode_readdir_entries = False;/* backward compat */
6258 context->options.one_share_per_server = False;/* backward compat */
6259 context->internal->_share_mode = SMBC_SHAREMODE_DENY_NONE;
6260 /* backward compat */
6262 context->open = smbc_open_ctx;
6263 context->creat = smbc_creat_ctx;
6264 context->read = smbc_read_ctx;
6265 context->write = smbc_write_ctx;
6266 context->close_fn = smbc_close_ctx;
6267 context->unlink = smbc_unlink_ctx;
6268 context->rename = smbc_rename_ctx;
6269 context->lseek = smbc_lseek_ctx;
6270 context->stat = smbc_stat_ctx;
6271 context->fstat = smbc_fstat_ctx;
6272 context->opendir = smbc_opendir_ctx;
6273 context->closedir = smbc_closedir_ctx;
6274 context->readdir = smbc_readdir_ctx;
6275 context->getdents = smbc_getdents_ctx;
6276 context->mkdir = smbc_mkdir_ctx;
6277 context->rmdir = smbc_rmdir_ctx;
6278 context->telldir = smbc_telldir_ctx;
6279 context->lseekdir = smbc_lseekdir_ctx;
6280 context->fstatdir = smbc_fstatdir_ctx;
6281 context->chmod = smbc_chmod_ctx;
6282 context->utimes = smbc_utimes_ctx;
6283 context->setxattr = smbc_setxattr_ctx;
6284 context->getxattr = smbc_getxattr_ctx;
6285 context->removexattr = smbc_removexattr_ctx;
6286 context->listxattr = smbc_listxattr_ctx;
6287 context->open_print_job = smbc_open_print_job_ctx;
6288 context->print_file = smbc_print_file_ctx;
6289 context->list_print_jobs = smbc_list_print_jobs_ctx;
6290 context->unlink_print_job = smbc_unlink_print_job_ctx;
6292 context->callbacks.check_server_fn = smbc_check_server;
6293 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
6295 smbc_default_cache_functions(context);
6297 return context;
6301 * Free a context
6303 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
6304 * and thus you'll be leaking memory if not handled properly.
6308 smbc_free_context(SMBCCTX *context,
6309 int shutdown_ctx)
6311 if (!context) {
6312 errno = EBADF;
6313 return 1;
6316 if (shutdown_ctx) {
6317 SMBCFILE * f;
6318 DEBUG(1,("Performing aggressive shutdown.\n"));
6320 f = context->internal->_files;
6321 while (f) {
6322 (context->close_fn)(context, f);
6323 f = f->next;
6325 context->internal->_files = NULL;
6327 /* First try to remove the servers the nice way. */
6328 if (context->callbacks.purge_cached_fn(context)) {
6329 SMBCSRV * s;
6330 SMBCSRV * next;
6331 DEBUG(1, ("Could not purge all servers, "
6332 "Nice way shutdown failed.\n"));
6333 s = context->internal->_servers;
6334 while (s) {
6335 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
6336 s, s->cli->fd));
6337 cli_shutdown(s->cli);
6338 (context->callbacks.remove_cached_srv_fn)(context,
6340 next = s->next;
6341 DLIST_REMOVE(context->internal->_servers, s);
6342 SAFE_FREE(s);
6343 s = next;
6345 context->internal->_servers = NULL;
6348 else {
6349 /* This is the polite way */
6350 if ((context->callbacks.purge_cached_fn)(context)) {
6351 DEBUG(1, ("Could not purge all servers, "
6352 "free_context failed.\n"));
6353 errno = EBUSY;
6354 return 1;
6356 if (context->internal->_servers) {
6357 DEBUG(1, ("Active servers in context, "
6358 "free_context failed.\n"));
6359 errno = EBUSY;
6360 return 1;
6362 if (context->internal->_files) {
6363 DEBUG(1, ("Active files in context, "
6364 "free_context failed.\n"));
6365 errno = EBUSY;
6366 return 1;
6370 /* Things we have to clean up */
6371 SAFE_FREE(context->workgroup);
6372 SAFE_FREE(context->netbios_name);
6373 SAFE_FREE(context->user);
6375 DEBUG(3, ("Context %p succesfully freed\n", context));
6376 SAFE_FREE(context->internal);
6377 SAFE_FREE(context);
6378 return 0;
6383 * Each time the context structure is changed, we have binary backward
6384 * compatibility issues. Instead of modifying the public portions of the
6385 * context structure to add new options, instead, we put them in the internal
6386 * portion of the context structure and provide a set function for these new
6387 * options.
6389 void
6390 smbc_option_set(SMBCCTX *context,
6391 char *option_name,
6392 ... /* option_value */)
6394 va_list ap;
6395 union {
6396 int i;
6397 bool b;
6398 smbc_get_auth_data_with_context_fn auth_fn;
6399 void *v;
6400 } option_value;
6402 va_start(ap, option_name);
6404 if (strcmp(option_name, "debug_to_stderr") == 0) {
6406 * Log to standard error instead of standard output.
6408 option_value.b = (bool) va_arg(ap, int);
6409 context->internal->_debug_stderr = option_value.b;
6411 } else if (strcmp(option_name, "full_time_names") == 0) {
6413 * Use new-style time attribute names, e.g. WRITE_TIME rather
6414 * than the old-style names such as M_TIME. This allows also
6415 * setting/getting CREATE_TIME which was previously
6416 * unimplemented. (Note that the old C_TIME was supposed to
6417 * be CHANGE_TIME but was confused and sometimes referred to
6418 * CREATE_TIME.)
6420 option_value.b = (bool) va_arg(ap, int);
6421 context->internal->_full_time_names = option_value.b;
6423 } else if (strcmp(option_name, "open_share_mode") == 0) {
6425 * The share mode to use for files opened with
6426 * smbc_open_ctx(). The default is SMBC_SHAREMODE_DENY_NONE.
6428 option_value.i = va_arg(ap, int);
6429 context->internal->_share_mode =
6430 (smbc_share_mode) option_value.i;
6432 } else if (strcmp(option_name, "auth_function") == 0) {
6434 * Use the new-style authentication function which includes
6435 * the context.
6437 option_value.auth_fn =
6438 va_arg(ap, smbc_get_auth_data_with_context_fn);
6439 context->internal->_auth_fn_with_context =
6440 option_value.auth_fn;
6441 } else if (strcmp(option_name, "user_data") == 0) {
6443 * Save a user data handle which may be retrieved by the user
6444 * with smbc_option_get()
6446 option_value.v = va_arg(ap, void *);
6447 context->internal->_user_data = option_value.v;
6450 va_end(ap);
6455 * Retrieve the current value of an option
6457 void *
6458 smbc_option_get(SMBCCTX *context,
6459 char *option_name)
6461 if (strcmp(option_name, "debug_stderr") == 0) {
6463 * Log to standard error instead of standard output.
6465 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6466 return (void *) (intptr_t) context->internal->_debug_stderr;
6467 #else
6468 return (void *) context->internal->_debug_stderr;
6469 #endif
6470 } else if (strcmp(option_name, "full_time_names") == 0) {
6472 * Use new-style time attribute names, e.g. WRITE_TIME rather
6473 * than the old-style names such as M_TIME. This allows also
6474 * setting/getting CREATE_TIME which was previously
6475 * unimplemented. (Note that the old C_TIME was supposed to
6476 * be CHANGE_TIME but was confused and sometimes referred to
6477 * CREATE_TIME.)
6479 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6480 return (void *) (intptr_t) context->internal->_full_time_names;
6481 #else
6482 return (void *) context->internal->_full_time_names;
6483 #endif
6485 } else if (strcmp(option_name, "auth_function") == 0) {
6487 * Use the new-style authentication function which includes
6488 * the context.
6490 return (void *) context->internal->_auth_fn_with_context;
6491 } else if (strcmp(option_name, "user_data") == 0) {
6493 * Save a user data handle which may be retrieved by the user
6494 * with smbc_option_get()
6496 return context->internal->_user_data;
6499 return NULL;
6504 * Initialise the library etc
6506 * We accept a struct containing handle information.
6507 * valid values for info->debug from 0 to 100,
6508 * and insist that info->fn must be non-null.
6510 SMBCCTX *
6511 smbc_init_context(SMBCCTX *context)
6513 pstring conf;
6514 int pid;
6515 char *user = NULL;
6516 char *home = NULL;
6518 if (!context || !context->internal) {
6519 errno = EBADF;
6520 return NULL;
6523 /* Do not initialise the same client twice */
6524 if (context->internal->_initialized) {
6525 return 0;
6528 if ((!context->callbacks.auth_fn &&
6529 !context->internal->_auth_fn_with_context) ||
6530 context->debug < 0 ||
6531 context->debug > 100) {
6533 errno = EINVAL;
6534 return NULL;
6538 if (!smbc_initialized) {
6540 * Do some library-wide intializations the first time we get
6541 * called
6543 bool conf_loaded = False;
6545 /* Set this to what the user wants */
6546 DEBUGLEVEL = context->debug;
6548 load_case_tables();
6550 setup_logging("libsmbclient", True);
6551 if (context->internal->_debug_stderr) {
6552 dbf = x_stderr;
6553 x_setbuf(x_stderr, NULL);
6556 /* Here we would open the smb.conf file if needed ... */
6558 in_client = True; /* FIXME, make a param */
6560 home = getenv("HOME");
6561 if (home) {
6562 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
6563 if (lp_load(conf, True, False, False, True)) {
6564 conf_loaded = True;
6565 } else {
6566 DEBUG(5, ("Could not load config file: %s\n",
6567 conf));
6571 if (!conf_loaded) {
6573 * Well, if that failed, try the dyn_CONFIGFILE
6574 * Which points to the standard locn, and if that
6575 * fails, silently ignore it and use the internal
6576 * defaults ...
6579 if (!lp_load(dyn_CONFIGFILE, True, False, False, False)) {
6580 DEBUG(5, ("Could not load config file: %s\n",
6581 dyn_CONFIGFILE));
6582 } else if (home) {
6584 * We loaded the global config file. Now lets
6585 * load user-specific modifications to the
6586 * global config.
6588 slprintf(conf, sizeof(conf),
6589 "%s/.smb/smb.conf.append", home);
6590 if (!lp_load(conf, True, False, False, False)) {
6591 DEBUG(10,
6592 ("Could not append config file: "
6593 "%s\n",
6594 conf));
6599 load_interfaces(); /* Load the list of interfaces ... */
6601 reopen_logs(); /* Get logging working ... */
6604 * Block SIGPIPE (from lib/util_sock.c: write())
6605 * It is not needed and should not stop execution
6607 BlockSignals(True, SIGPIPE);
6609 /* Done with one-time initialisation */
6610 smbc_initialized = 1;
6614 if (!context->user) {
6616 * FIXME: Is this the best way to get the user info?
6618 user = getenv("USER");
6619 /* walk around as "guest" if no username can be found */
6620 if (!user) context->user = SMB_STRDUP("guest");
6621 else context->user = SMB_STRDUP(user);
6624 if (!context->netbios_name) {
6626 * We try to get our netbios name from the config. If that
6627 * fails we fall back on constructing our netbios name from
6628 * our hostname etc
6630 if (global_myname()) {
6631 context->netbios_name = SMB_STRDUP(global_myname());
6633 else {
6635 * Hmmm, I want to get hostname as well, but I am too
6636 * lazy for the moment
6638 pid = sys_getpid();
6639 context->netbios_name = (char *)SMB_MALLOC(17);
6640 if (!context->netbios_name) {
6641 errno = ENOMEM;
6642 return NULL;
6644 slprintf(context->netbios_name, 16,
6645 "smbc%s%d", context->user, pid);
6649 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
6651 if (!context->workgroup) {
6652 if (lp_workgroup()) {
6653 context->workgroup = SMB_STRDUP(lp_workgroup());
6655 else {
6656 /* TODO: Think about a decent default workgroup */
6657 context->workgroup = SMB_STRDUP("samba");
6661 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
6663 /* shortest timeout is 1 second */
6664 if (context->timeout > 0 && context->timeout < 1000)
6665 context->timeout = 1000;
6668 * FIXME: Should we check the function pointers here?
6671 context->internal->_initialized = True;
6673 return context;
6677 /* Return the verion of samba, and thus libsmbclient */
6678 const char *
6679 smbc_version(void)
6681 return samba_version_string();