r24981: - Use the formal syntax for calling functions through pointers. I've wanted
[Samba.git] / source / libsmb / libsmbclient.c
blob73940087865e1ce83f551e6de98f24e2aac6d554
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 in_addr ip;
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_ip(&ip);
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_ip(&ip);
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, &ip);
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, &ip);
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 in_addr rem_ip;
803 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
804 DEBUG(4, ("Could not convert IP address "
805 "%s to struct in_addr\n", server));
806 errno = ETIMEDOUT;
807 return NULL;
810 tried_reverse++; /* Yuck */
812 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
813 make_nmb_name(&called, remote_name, 0x20);
814 goto again;
818 errno = ETIMEDOUT;
819 return NULL;
822 DEBUG(4,(" session request ok\n"));
824 if (!cli_negprot(c)) {
825 cli_shutdown(c);
826 errno = ETIMEDOUT;
827 return NULL;
830 username_used = username;
832 if (!NT_STATUS_IS_OK(cli_session_setup(c, username_used,
833 password, strlen(password),
834 password, strlen(password),
835 workgroup))) {
837 /* Failed. Try an anonymous login, if allowed by flags. */
838 username_used = "";
840 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
841 !NT_STATUS_IS_OK(cli_session_setup(c, username_used,
842 password, 1,
843 password, 0,
844 workgroup))) {
846 cli_shutdown(c);
847 errno = EPERM;
848 return NULL;
852 DEBUG(4,(" session setup ok\n"));
854 if (!cli_send_tconX(c, share, "?????",
855 password, strlen(password)+1)) {
856 errno = smbc_errno(context, c);
857 cli_shutdown(c);
858 return NULL;
861 DEBUG(4,(" tconx ok\n"));
864 * Ok, we have got a nice connection
865 * Let's allocate a server structure.
868 srv = SMB_MALLOC_P(SMBCSRV);
869 if (!srv) {
870 errno = ENOMEM;
871 goto failed;
874 ZERO_STRUCTP(srv);
875 srv->cli = c;
876 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
877 srv->no_pathinfo = False;
878 srv->no_pathinfo2 = False;
879 srv->no_nt_session = False;
881 /* now add it to the cache (internal or external) */
882 /* Let the cache function set errno if it wants to */
883 errno = 0;
884 if ((context->callbacks.add_cached_srv_fn)(context, srv,
885 server, share,
886 workgroup, username)) {
887 int saved_errno = errno;
888 DEBUG(3, (" Failed to add server to cache\n"));
889 errno = saved_errno;
890 if (errno == 0) {
891 errno = ENOMEM;
893 goto failed;
896 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
897 server, share, srv));
899 DLIST_ADD(context->internal->_servers, srv);
900 return srv;
902 failed:
903 cli_shutdown(c);
904 if (!srv) {
905 return NULL;
908 SAFE_FREE(srv);
909 return NULL;
913 * Connect to a server for getting/setting attributes, possibly on an existing
914 * connection. This works similarly to smbc_server().
916 static SMBCSRV *
917 smbc_attr_server(SMBCCTX *context,
918 const char *server,
919 const char *share,
920 fstring workgroup,
921 fstring username,
922 fstring password,
923 POLICY_HND *pol)
925 int flags;
926 struct in_addr ip;
927 struct cli_state *ipc_cli;
928 struct rpc_pipe_client *pipe_hnd;
929 NTSTATUS nt_status;
930 SMBCSRV *ipc_srv=NULL;
933 * See if we've already created this special connection. Reference
934 * our "special" share name '*IPC$', which is an impossible real share
935 * name due to the leading asterisk.
937 ipc_srv = find_server(context, server, "*IPC$",
938 workgroup, username, password);
939 if (!ipc_srv) {
941 /* We didn't find a cached connection. Get the password */
942 if (*password == '\0') {
943 /* ... then retrieve it now. */
944 if (context->internal->_auth_fn_with_context != NULL) {
945 (context->internal->_auth_fn_with_context)(
946 context,
947 server, share,
948 workgroup, sizeof(fstring),
949 username, sizeof(fstring),
950 password, sizeof(fstring));
951 } else {
952 (context->callbacks.auth_fn)(
953 server, share,
954 workgroup, sizeof(fstring),
955 username, sizeof(fstring),
956 password, sizeof(fstring));
960 flags = 0;
961 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
962 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
965 zero_ip(&ip);
966 nt_status = cli_full_connection(&ipc_cli,
967 global_myname(), server,
968 &ip, 0, "IPC$", "?????",
969 username, workgroup,
970 password, flags,
971 Undefined, NULL);
972 if (! NT_STATUS_IS_OK(nt_status)) {
973 DEBUG(1,("cli_full_connection failed! (%s)\n",
974 nt_errstr(nt_status)));
975 errno = ENOTSUP;
976 return NULL;
979 ipc_srv = SMB_MALLOC_P(SMBCSRV);
980 if (!ipc_srv) {
981 errno = ENOMEM;
982 cli_shutdown(ipc_cli);
983 return NULL;
986 ZERO_STRUCTP(ipc_srv);
987 ipc_srv->cli = ipc_cli;
989 if (pol) {
990 pipe_hnd = cli_rpc_pipe_open_noauth(ipc_srv->cli,
991 PI_LSARPC,
992 &nt_status);
993 if (!pipe_hnd) {
994 DEBUG(1, ("cli_nt_session_open fail!\n"));
995 errno = ENOTSUP;
996 cli_shutdown(ipc_srv->cli);
997 free(ipc_srv);
998 return NULL;
1002 * Some systems don't support
1003 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
1004 * so we might as well do it too.
1007 nt_status = rpccli_lsa_open_policy(
1008 pipe_hnd,
1009 ipc_srv->cli->mem_ctx,
1010 True,
1011 GENERIC_EXECUTE_ACCESS,
1012 pol);
1014 if (!NT_STATUS_IS_OK(nt_status)) {
1015 errno = smbc_errno(context, ipc_srv->cli);
1016 cli_shutdown(ipc_srv->cli);
1017 return NULL;
1021 /* now add it to the cache (internal or external) */
1023 errno = 0; /* let cache function set errno if it likes */
1024 if ((context->callbacks.add_cached_srv_fn)(context, ipc_srv,
1025 server,
1026 "*IPC$",
1027 workgroup,
1028 username)) {
1029 DEBUG(3, (" Failed to add server to cache\n"));
1030 if (errno == 0) {
1031 errno = ENOMEM;
1033 cli_shutdown(ipc_srv->cli);
1034 free(ipc_srv);
1035 return NULL;
1038 DLIST_ADD(context->internal->_servers, ipc_srv);
1041 return ipc_srv;
1045 * Routine to open() a file ...
1048 static SMBCFILE *
1049 smbc_open_ctx(SMBCCTX *context,
1050 const char *fname,
1051 int flags,
1052 mode_t mode)
1054 fstring server, share, user, password, workgroup;
1055 pstring path;
1056 pstring targetpath;
1057 struct cli_state *targetcli;
1058 SMBCSRV *srv = NULL;
1059 SMBCFILE *file = NULL;
1060 int fd;
1062 if (!context || !context->internal ||
1063 !context->internal->_initialized) {
1065 errno = EINVAL; /* Best I can think of ... */
1066 return NULL;
1070 if (!fname) {
1072 errno = EINVAL;
1073 return NULL;
1077 if (smbc_parse_path(context, fname,
1078 workgroup, sizeof(workgroup),
1079 server, sizeof(server),
1080 share, sizeof(share),
1081 path, sizeof(path),
1082 user, sizeof(user),
1083 password, sizeof(password),
1084 NULL, 0)) {
1085 errno = EINVAL;
1086 return NULL;
1089 if (user[0] == (char)0) fstrcpy(user, context->user);
1091 srv = smbc_server(context, True,
1092 server, share, workgroup, user, password);
1094 if (!srv) {
1096 if (errno == EPERM) errno = EACCES;
1097 return NULL; /* smbc_server sets errno */
1101 /* Hmmm, the test for a directory is suspect here ... FIXME */
1103 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1105 fd = -1;
1108 else {
1110 file = SMB_MALLOC_P(SMBCFILE);
1112 if (!file) {
1114 errno = ENOMEM;
1115 return NULL;
1119 ZERO_STRUCTP(file);
1121 /*d_printf(">>>open: resolving %s\n", path);*/
1122 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1124 d_printf("Could not resolve %s\n", path);
1125 SAFE_FREE(file);
1126 return NULL;
1128 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1130 if ((fd = cli_open(targetcli, targetpath, flags,
1131 context->internal->_share_mode)) < 0) {
1133 /* Handle the error ... */
1135 SAFE_FREE(file);
1136 errno = smbc_errno(context, targetcli);
1137 return NULL;
1141 /* Fill in file struct */
1143 file->cli_fd = fd;
1144 file->fname = SMB_STRDUP(fname);
1145 file->srv = srv;
1146 file->offset = 0;
1147 file->file = True;
1149 DLIST_ADD(context->internal->_files, file);
1152 * If the file was opened in O_APPEND mode, all write
1153 * operations should be appended to the file. To do that,
1154 * though, using this protocol, would require a getattrE()
1155 * call for each and every write, to determine where the end
1156 * of the file is. (There does not appear to be an append flag
1157 * in the protocol.) Rather than add all of that overhead of
1158 * retrieving the current end-of-file offset prior to each
1159 * write operation, we'll assume that most append operations
1160 * will continuously write, so we'll just set the offset to
1161 * the end of the file now and hope that's adequate.
1163 * Note to self: If this proves inadequate, and O_APPEND
1164 * should, in some cases, be forced for each write, add a
1165 * field in the context options structure, for
1166 * "strict_append_mode" which would select between the current
1167 * behavior (if FALSE) or issuing a getattrE() prior to each
1168 * write and forcing the write to the end of the file (if
1169 * TRUE). Adding that capability will likely require adding
1170 * an "append" flag into the _SMBCFILE structure to track
1171 * whether a file was opened in O_APPEND mode. -- djl
1173 if (flags & O_APPEND) {
1174 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1175 (void) smbc_close_ctx(context, file);
1176 errno = ENXIO;
1177 return NULL;
1181 return file;
1185 /* Check if opendir needed ... */
1187 if (fd == -1) {
1188 int eno = 0;
1190 eno = smbc_errno(context, srv->cli);
1191 file = (context->opendir)(context, fname);
1192 if (!file) errno = eno;
1193 return file;
1197 errno = EINVAL; /* FIXME, correct errno ? */
1198 return NULL;
1203 * Routine to create a file
1206 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1208 static SMBCFILE *
1209 smbc_creat_ctx(SMBCCTX *context,
1210 const char *path,
1211 mode_t mode)
1214 if (!context || !context->internal ||
1215 !context->internal->_initialized) {
1217 errno = EINVAL;
1218 return NULL;
1222 return smbc_open_ctx(context, path, creat_bits, mode);
1226 * Routine to read() a file ...
1229 static ssize_t
1230 smbc_read_ctx(SMBCCTX *context,
1231 SMBCFILE *file,
1232 void *buf,
1233 size_t count)
1235 int ret;
1236 fstring server, share, user, password;
1237 pstring path, targetpath;
1238 struct cli_state *targetcli;
1241 * offset:
1243 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1244 * appears to pass file->offset (which is type off_t) differently than
1245 * a local variable of type off_t. Using local variable "offset" in
1246 * the call to cli_read() instead of file->offset fixes a problem
1247 * retrieving data at an offset greater than 4GB.
1249 off_t offset;
1251 if (!context || !context->internal ||
1252 !context->internal->_initialized) {
1254 errno = EINVAL;
1255 return -1;
1259 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1261 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1263 errno = EBADF;
1264 return -1;
1268 offset = file->offset;
1270 /* Check that the buffer exists ... */
1272 if (buf == NULL) {
1274 errno = EINVAL;
1275 return -1;
1279 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1280 if (smbc_parse_path(context, file->fname,
1281 NULL, 0,
1282 server, sizeof(server),
1283 share, sizeof(share),
1284 path, sizeof(path),
1285 user, sizeof(user),
1286 password, sizeof(password),
1287 NULL, 0)) {
1288 errno = EINVAL;
1289 return -1;
1292 /*d_printf(">>>read: resolving %s\n", path);*/
1293 if (!cli_resolve_path("", file->srv->cli, path,
1294 &targetcli, targetpath))
1296 d_printf("Could not resolve %s\n", path);
1297 return -1;
1299 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1301 ret = cli_read(targetcli, file->cli_fd, (char *)buf, offset, count);
1303 if (ret < 0) {
1305 errno = smbc_errno(context, targetcli);
1306 return -1;
1310 file->offset += ret;
1312 DEBUG(4, (" --> %d\n", ret));
1314 return ret; /* Success, ret bytes of data ... */
1319 * Routine to write() a file ...
1322 static ssize_t
1323 smbc_write_ctx(SMBCCTX *context,
1324 SMBCFILE *file,
1325 void *buf,
1326 size_t count)
1328 int ret;
1329 off_t offset;
1330 fstring server, share, user, password;
1331 pstring path, targetpath;
1332 struct cli_state *targetcli;
1334 /* First check all pointers before dereferencing them */
1336 if (!context || !context->internal ||
1337 !context->internal->_initialized) {
1339 errno = EINVAL;
1340 return -1;
1344 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1346 errno = EBADF;
1347 return -1;
1351 /* Check that the buffer exists ... */
1353 if (buf == NULL) {
1355 errno = EINVAL;
1356 return -1;
1360 offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1362 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1363 if (smbc_parse_path(context, file->fname,
1364 NULL, 0,
1365 server, sizeof(server),
1366 share, sizeof(share),
1367 path, sizeof(path),
1368 user, sizeof(user),
1369 password, sizeof(password),
1370 NULL, 0)) {
1371 errno = EINVAL;
1372 return -1;
1375 /*d_printf(">>>write: resolving %s\n", path);*/
1376 if (!cli_resolve_path("", file->srv->cli, path,
1377 &targetcli, targetpath))
1379 d_printf("Could not resolve %s\n", path);
1380 return -1;
1382 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1385 ret = cli_write(targetcli, file->cli_fd, 0, (char *)buf, offset, count);
1387 if (ret <= 0) {
1389 errno = smbc_errno(context, targetcli);
1390 return -1;
1394 file->offset += ret;
1396 return ret; /* Success, 0 bytes of data ... */
1400 * Routine to close() a file ...
1403 static int
1404 smbc_close_ctx(SMBCCTX *context,
1405 SMBCFILE *file)
1407 SMBCSRV *srv;
1408 fstring server, share, user, password;
1409 pstring path, targetpath;
1410 struct cli_state *targetcli;
1412 if (!context || !context->internal ||
1413 !context->internal->_initialized) {
1415 errno = EINVAL;
1416 return -1;
1420 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1422 errno = EBADF;
1423 return -1;
1427 /* IS a dir ... */
1428 if (!file->file) {
1430 return (context->closedir)(context, file);
1434 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1435 if (smbc_parse_path(context, file->fname,
1436 NULL, 0,
1437 server, sizeof(server),
1438 share, sizeof(share),
1439 path, sizeof(path),
1440 user, sizeof(user),
1441 password, sizeof(password),
1442 NULL, 0)) {
1443 errno = EINVAL;
1444 return -1;
1447 /*d_printf(">>>close: resolving %s\n", path);*/
1448 if (!cli_resolve_path("", file->srv->cli, path,
1449 &targetcli, targetpath))
1451 d_printf("Could not resolve %s\n", path);
1452 return -1;
1454 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1456 if (!cli_close(targetcli, file->cli_fd)) {
1458 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1459 file->fname));
1460 /* Deallocate slot and remove the server
1461 * from the server cache if unused */
1462 errno = smbc_errno(context, targetcli);
1463 srv = file->srv;
1464 DLIST_REMOVE(context->internal->_files, file);
1465 SAFE_FREE(file->fname);
1466 SAFE_FREE(file);
1467 (context->callbacks.remove_unused_server_fn)(context, srv);
1469 return -1;
1473 DLIST_REMOVE(context->internal->_files, file);
1474 SAFE_FREE(file->fname);
1475 SAFE_FREE(file);
1477 return 0;
1481 * Get info from an SMB server on a file. Use a qpathinfo call first
1482 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1484 static BOOL
1485 smbc_getatr(SMBCCTX * context,
1486 SMBCSRV *srv,
1487 char *path,
1488 uint16 *mode,
1489 SMB_OFF_T *size,
1490 struct timespec *create_time_ts,
1491 struct timespec *access_time_ts,
1492 struct timespec *write_time_ts,
1493 struct timespec *change_time_ts,
1494 SMB_INO_T *ino)
1496 pstring fixedpath;
1497 pstring targetpath;
1498 struct cli_state *targetcli;
1499 time_t write_time;
1501 if (!context || !context->internal ||
1502 !context->internal->_initialized) {
1504 errno = EINVAL;
1505 return -1;
1509 /* path fixup for . and .. */
1510 if (strequal(path, ".") || strequal(path, ".."))
1511 pstrcpy(fixedpath, "\\");
1512 else
1514 pstrcpy(fixedpath, path);
1515 trim_string(fixedpath, NULL, "\\..");
1516 trim_string(fixedpath, NULL, "\\.");
1518 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1520 if (!cli_resolve_path( "", srv->cli, fixedpath, &targetcli, targetpath))
1522 d_printf("Couldn't resolve %s\n", path);
1523 return False;
1526 if (!srv->no_pathinfo2 &&
1527 cli_qpathinfo2(targetcli, targetpath,
1528 create_time_ts,
1529 access_time_ts,
1530 write_time_ts,
1531 change_time_ts,
1532 size, mode, ino)) {
1533 return True;
1536 /* if this is NT then don't bother with the getatr */
1537 if (targetcli->capabilities & CAP_NT_SMBS) {
1538 errno = EPERM;
1539 return False;
1542 if (cli_getatr(targetcli, targetpath, mode, size, &write_time)) {
1544 struct timespec w_time_ts;
1546 w_time_ts = convert_time_t_to_timespec(write_time);
1548 if (write_time_ts != NULL) {
1549 *write_time_ts = w_time_ts;
1552 if (create_time_ts != NULL) {
1553 *create_time_ts = w_time_ts;
1556 if (access_time_ts != NULL) {
1557 *access_time_ts = w_time_ts;
1560 if (change_time_ts != NULL) {
1561 *change_time_ts = w_time_ts;
1564 srv->no_pathinfo2 = True;
1565 return True;
1568 errno = EPERM;
1569 return False;
1574 * Set file info on an SMB server. Use setpathinfo call first. If that
1575 * fails, use setattrE..
1577 * Access and modification time parameters are always used and must be
1578 * provided. Create time, if zero, will be determined from the actual create
1579 * time of the file. If non-zero, the create time will be set as well.
1581 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1583 static BOOL
1584 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1585 time_t create_time,
1586 time_t access_time,
1587 time_t write_time,
1588 time_t change_time,
1589 uint16 mode)
1591 int fd;
1592 int ret;
1595 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1596 * modern function for "new code" to be using, and it works given a
1597 * filename rather than requiring that the file be opened to have its
1598 * attributes manipulated.
1600 if (srv->no_pathinfo ||
1601 ! cli_setpathinfo(srv->cli, path,
1602 create_time,
1603 access_time,
1604 write_time,
1605 change_time,
1606 mode)) {
1609 * setpathinfo is not supported; go to plan B.
1611 * cli_setatr() does not work on win98, and it also doesn't
1612 * support setting the access time (only the modification
1613 * time), so in all cases, we open the specified file and use
1614 * cli_setattrE() which should work on all OS versions, and
1615 * supports both times.
1618 /* Don't try {q,set}pathinfo() again, with this server */
1619 srv->no_pathinfo = True;
1621 /* Open the file */
1622 if ((fd = cli_open(srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1624 errno = smbc_errno(context, srv->cli);
1625 return -1;
1628 /* Set the new attributes */
1629 ret = cli_setattrE(srv->cli, fd,
1630 change_time,
1631 access_time,
1632 write_time);
1634 /* Close the file */
1635 cli_close(srv->cli, fd);
1638 * Unfortunately, setattrE() doesn't have a provision for
1639 * setting the access mode (attributes). We'll have to try
1640 * cli_setatr() for that, and with only this parameter, it
1641 * seems to work on win98.
1643 if (ret && mode != (uint16) -1) {
1644 ret = cli_setatr(srv->cli, path, mode, 0);
1647 if (! ret) {
1648 errno = smbc_errno(context, srv->cli);
1649 return False;
1653 return True;
1657 * Routine to unlink() a file
1660 static int
1661 smbc_unlink_ctx(SMBCCTX *context,
1662 const char *fname)
1664 fstring server, share, user, password, workgroup;
1665 pstring path, targetpath;
1666 struct cli_state *targetcli;
1667 SMBCSRV *srv = NULL;
1669 if (!context || !context->internal ||
1670 !context->internal->_initialized) {
1672 errno = EINVAL; /* Best I can think of ... */
1673 return -1;
1677 if (!fname) {
1679 errno = EINVAL;
1680 return -1;
1684 if (smbc_parse_path(context, fname,
1685 workgroup, sizeof(workgroup),
1686 server, sizeof(server),
1687 share, sizeof(share),
1688 path, sizeof(path),
1689 user, sizeof(user),
1690 password, sizeof(password),
1691 NULL, 0)) {
1692 errno = EINVAL;
1693 return -1;
1696 if (user[0] == (char)0) fstrcpy(user, context->user);
1698 srv = smbc_server(context, True,
1699 server, share, workgroup, user, password);
1701 if (!srv) {
1703 return -1; /* smbc_server sets errno */
1707 /*d_printf(">>>unlink: resolving %s\n", path);*/
1708 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1710 d_printf("Could not resolve %s\n", path);
1711 return -1;
1713 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1715 if (!cli_unlink(targetcli, targetpath)) {
1717 errno = smbc_errno(context, targetcli);
1719 if (errno == EACCES) { /* Check if the file is a directory */
1721 int saverr = errno;
1722 SMB_OFF_T size = 0;
1723 uint16 mode = 0;
1724 struct timespec write_time_ts;
1725 struct timespec access_time_ts;
1726 struct timespec change_time_ts;
1727 SMB_INO_T ino = 0;
1729 if (!smbc_getatr(context, srv, path, &mode, &size,
1730 NULL,
1731 &access_time_ts,
1732 &write_time_ts,
1733 &change_time_ts,
1734 &ino)) {
1736 /* Hmmm, bad error ... What? */
1738 errno = smbc_errno(context, targetcli);
1739 return -1;
1742 else {
1744 if (IS_DOS_DIR(mode))
1745 errno = EISDIR;
1746 else
1747 errno = saverr; /* Restore this */
1752 return -1;
1756 return 0; /* Success ... */
1761 * Routine to rename() a file
1764 static int
1765 smbc_rename_ctx(SMBCCTX *ocontext,
1766 const char *oname,
1767 SMBCCTX *ncontext,
1768 const char *nname)
1770 fstring server1;
1771 fstring share1;
1772 fstring server2;
1773 fstring share2;
1774 fstring user1;
1775 fstring user2;
1776 fstring password1;
1777 fstring password2;
1778 fstring workgroup;
1779 pstring path1;
1780 pstring path2;
1781 pstring targetpath1;
1782 pstring targetpath2;
1783 struct cli_state *targetcli1;
1784 struct cli_state *targetcli2;
1785 SMBCSRV *srv = NULL;
1787 if (!ocontext || !ncontext ||
1788 !ocontext->internal || !ncontext->internal ||
1789 !ocontext->internal->_initialized ||
1790 !ncontext->internal->_initialized) {
1792 errno = EINVAL; /* Best I can think of ... */
1793 return -1;
1797 if (!oname || !nname) {
1799 errno = EINVAL;
1800 return -1;
1804 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1806 smbc_parse_path(ocontext, oname,
1807 workgroup, sizeof(workgroup),
1808 server1, sizeof(server1),
1809 share1, sizeof(share1),
1810 path1, sizeof(path1),
1811 user1, sizeof(user1),
1812 password1, sizeof(password1),
1813 NULL, 0);
1815 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1817 smbc_parse_path(ncontext, nname,
1818 NULL, 0,
1819 server2, sizeof(server2),
1820 share2, sizeof(share2),
1821 path2, sizeof(path2),
1822 user2, sizeof(user2),
1823 password2, sizeof(password2),
1824 NULL, 0);
1826 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1828 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1829 strcmp(user1, user2)) {
1831 /* Can't rename across file systems, or users?? */
1833 errno = EXDEV;
1834 return -1;
1838 srv = smbc_server(ocontext, True,
1839 server1, share1, workgroup, user1, password1);
1840 if (!srv) {
1842 return -1;
1846 /*d_printf(">>>rename: resolving %s\n", path1);*/
1847 if (!cli_resolve_path( "", srv->cli, path1, &targetcli1, targetpath1))
1849 d_printf("Could not resolve %s\n", path1);
1850 return -1;
1852 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1853 /*d_printf(">>>rename: resolving %s\n", path2);*/
1854 if (!cli_resolve_path( "", srv->cli, path2, &targetcli2, targetpath2))
1856 d_printf("Could not resolve %s\n", path2);
1857 return -1;
1859 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1861 if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1862 strcmp(targetcli1->share, targetcli2->share))
1864 /* can't rename across file systems */
1866 errno = EXDEV;
1867 return -1;
1870 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1871 int eno = smbc_errno(ocontext, targetcli1);
1873 if (eno != EEXIST ||
1874 !cli_unlink(targetcli1, targetpath2) ||
1875 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1877 errno = eno;
1878 return -1;
1883 return 0; /* Success */
1888 * A routine to lseek() a file
1891 static off_t
1892 smbc_lseek_ctx(SMBCCTX *context,
1893 SMBCFILE *file,
1894 off_t offset,
1895 int whence)
1897 SMB_OFF_T size;
1898 fstring server, share, user, password;
1899 pstring path, targetpath;
1900 struct cli_state *targetcli;
1902 if (!context || !context->internal ||
1903 !context->internal->_initialized) {
1905 errno = EINVAL;
1906 return -1;
1910 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1912 errno = EBADF;
1913 return -1;
1917 if (!file->file) {
1919 errno = EINVAL;
1920 return -1; /* Can't lseek a dir ... */
1924 switch (whence) {
1925 case SEEK_SET:
1926 file->offset = offset;
1927 break;
1929 case SEEK_CUR:
1930 file->offset += offset;
1931 break;
1933 case SEEK_END:
1934 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1935 if (smbc_parse_path(context, file->fname,
1936 NULL, 0,
1937 server, sizeof(server),
1938 share, sizeof(share),
1939 path, sizeof(path),
1940 user, sizeof(user),
1941 password, sizeof(password),
1942 NULL, 0)) {
1944 errno = EINVAL;
1945 return -1;
1948 /*d_printf(">>>lseek: resolving %s\n", path);*/
1949 if (!cli_resolve_path("", file->srv->cli, path,
1950 &targetcli, targetpath))
1952 d_printf("Could not resolve %s\n", path);
1953 return -1;
1955 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1957 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1958 &size, NULL, NULL, NULL, NULL, NULL))
1960 SMB_OFF_T b_size = size;
1961 if (!cli_getattrE(targetcli, file->cli_fd,
1962 NULL, &b_size, NULL, NULL, NULL))
1964 errno = EINVAL;
1965 return -1;
1966 } else
1967 size = b_size;
1969 file->offset = size + offset;
1970 break;
1972 default:
1973 errno = EINVAL;
1974 break;
1978 return file->offset;
1983 * Generate an inode number from file name for those things that need it
1986 static ino_t
1987 smbc_inode(SMBCCTX *context,
1988 const char *name)
1991 if (!context || !context->internal ||
1992 !context->internal->_initialized) {
1994 errno = EINVAL;
1995 return -1;
1999 if (!*name) return 2; /* FIXME, why 2 ??? */
2000 return (ino_t)str_checksum(name);
2005 * Routine to put basic stat info into a stat structure ... Used by stat and
2006 * fstat below.
2009 static int
2010 smbc_setup_stat(SMBCCTX *context,
2011 struct stat *st,
2012 char *fname,
2013 SMB_OFF_T size,
2014 int mode)
2017 st->st_mode = 0;
2019 if (IS_DOS_DIR(mode)) {
2020 st->st_mode = SMBC_DIR_MODE;
2021 } else {
2022 st->st_mode = SMBC_FILE_MODE;
2025 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
2026 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
2027 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
2028 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
2030 st->st_size = size;
2031 #ifdef HAVE_STAT_ST_BLKSIZE
2032 st->st_blksize = 512;
2033 #endif
2034 #ifdef HAVE_STAT_ST_BLOCKS
2035 st->st_blocks = (size+511)/512;
2036 #endif
2037 st->st_uid = getuid();
2038 st->st_gid = getgid();
2040 if (IS_DOS_DIR(mode)) {
2041 st->st_nlink = 2;
2042 } else {
2043 st->st_nlink = 1;
2046 if (st->st_ino == 0) {
2047 st->st_ino = smbc_inode(context, fname);
2050 return True; /* FIXME: Is this needed ? */
2055 * Routine to stat a file given a name
2058 static int
2059 smbc_stat_ctx(SMBCCTX *context,
2060 const char *fname,
2061 struct stat *st)
2063 SMBCSRV *srv;
2064 fstring server;
2065 fstring share;
2066 fstring user;
2067 fstring password;
2068 fstring workgroup;
2069 pstring path;
2070 struct timespec write_time_ts;
2071 struct timespec access_time_ts;
2072 struct timespec change_time_ts;
2073 SMB_OFF_T size = 0;
2074 uint16 mode = 0;
2075 SMB_INO_T ino = 0;
2077 if (!context || !context->internal ||
2078 !context->internal->_initialized) {
2080 errno = EINVAL; /* Best I can think of ... */
2081 return -1;
2085 if (!fname) {
2087 errno = EINVAL;
2088 return -1;
2092 DEBUG(4, ("smbc_stat(%s)\n", fname));
2094 if (smbc_parse_path(context, fname,
2095 workgroup, sizeof(workgroup),
2096 server, sizeof(server),
2097 share, sizeof(share),
2098 path, sizeof(path),
2099 user, sizeof(user),
2100 password, sizeof(password),
2101 NULL, 0)) {
2102 errno = EINVAL;
2103 return -1;
2106 if (user[0] == (char)0) fstrcpy(user, context->user);
2108 srv = smbc_server(context, True,
2109 server, share, workgroup, user, password);
2111 if (!srv) {
2112 return -1; /* errno set by smbc_server */
2115 if (!smbc_getatr(context, srv, path, &mode, &size,
2116 NULL,
2117 &access_time_ts,
2118 &write_time_ts,
2119 &change_time_ts,
2120 &ino)) {
2122 errno = smbc_errno(context, srv->cli);
2123 return -1;
2127 st->st_ino = ino;
2129 smbc_setup_stat(context, st, path, size, mode);
2131 set_atimespec(st, access_time_ts);
2132 set_ctimespec(st, change_time_ts);
2133 set_mtimespec(st, write_time_ts);
2134 st->st_dev = srv->dev;
2136 return 0;
2141 * Routine to stat a file given an fd
2144 static int
2145 smbc_fstat_ctx(SMBCCTX *context,
2146 SMBCFILE *file,
2147 struct stat *st)
2149 struct timespec change_time_ts;
2150 struct timespec access_time_ts;
2151 struct timespec write_time_ts;
2152 SMB_OFF_T size;
2153 uint16 mode;
2154 fstring server;
2155 fstring share;
2156 fstring user;
2157 fstring password;
2158 pstring path;
2159 pstring targetpath;
2160 struct cli_state *targetcli;
2161 SMB_INO_T ino = 0;
2163 if (!context || !context->internal ||
2164 !context->internal->_initialized) {
2166 errno = EINVAL;
2167 return -1;
2171 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2173 errno = EBADF;
2174 return -1;
2178 if (!file->file) {
2180 return (context->fstatdir)(context, file, st);
2184 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2185 if (smbc_parse_path(context, file->fname,
2186 NULL, 0,
2187 server, sizeof(server),
2188 share, sizeof(share),
2189 path, sizeof(path),
2190 user, sizeof(user),
2191 password, sizeof(password),
2192 NULL, 0)) {
2193 errno = EINVAL;
2194 return -1;
2197 /*d_printf(">>>fstat: resolving %s\n", path);*/
2198 if (!cli_resolve_path("", file->srv->cli, path,
2199 &targetcli, targetpath))
2201 d_printf("Could not resolve %s\n", path);
2202 return -1;
2204 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2206 if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2207 NULL,
2208 &access_time_ts,
2209 &write_time_ts,
2210 &change_time_ts,
2211 &ino)) {
2213 time_t change_time, access_time, write_time;
2215 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2216 &change_time, &access_time, &write_time)) {
2218 errno = EINVAL;
2219 return -1;
2222 change_time_ts = convert_time_t_to_timespec(change_time);
2223 access_time_ts = convert_time_t_to_timespec(access_time);
2224 write_time_ts = convert_time_t_to_timespec(write_time);
2227 st->st_ino = ino;
2229 smbc_setup_stat(context, st, file->fname, size, mode);
2231 set_atimespec(st, access_time_ts);
2232 set_ctimespec(st, change_time_ts);
2233 set_mtimespec(st, write_time_ts);
2234 st->st_dev = file->srv->dev;
2236 return 0;
2241 * Routine to open a directory
2242 * We accept the URL syntax explained in smbc_parse_path(), above.
2245 static void
2246 smbc_remove_dir(SMBCFILE *dir)
2248 struct smbc_dir_list *d,*f;
2250 d = dir->dir_list;
2251 while (d) {
2253 f = d; d = d->next;
2255 SAFE_FREE(f->dirent);
2256 SAFE_FREE(f);
2260 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2264 static int
2265 add_dirent(SMBCFILE *dir,
2266 const char *name,
2267 const char *comment,
2268 uint32 type)
2270 struct smbc_dirent *dirent;
2271 int size;
2272 int name_length = (name == NULL ? 0 : strlen(name));
2273 int comment_len = (comment == NULL ? 0 : strlen(comment));
2276 * Allocate space for the dirent, which must be increased by the
2277 * size of the name and the comment and 1 each for the null terminator.
2280 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2282 dirent = (struct smbc_dirent *)SMB_MALLOC(size);
2284 if (!dirent) {
2286 dir->dir_error = ENOMEM;
2287 return -1;
2291 ZERO_STRUCTP(dirent);
2293 if (dir->dir_list == NULL) {
2295 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2296 if (!dir->dir_list) {
2298 SAFE_FREE(dirent);
2299 dir->dir_error = ENOMEM;
2300 return -1;
2303 ZERO_STRUCTP(dir->dir_list);
2305 dir->dir_end = dir->dir_next = dir->dir_list;
2307 else {
2309 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2311 if (!dir->dir_end->next) {
2313 SAFE_FREE(dirent);
2314 dir->dir_error = ENOMEM;
2315 return -1;
2318 ZERO_STRUCTP(dir->dir_end->next);
2320 dir->dir_end = dir->dir_end->next;
2323 dir->dir_end->next = NULL;
2324 dir->dir_end->dirent = dirent;
2326 dirent->smbc_type = type;
2327 dirent->namelen = name_length;
2328 dirent->commentlen = comment_len;
2329 dirent->dirlen = size;
2332 * dirent->namelen + 1 includes the null (no null termination needed)
2333 * Ditto for dirent->commentlen.
2334 * The space for the two null bytes was allocated.
2336 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2337 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2338 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2340 return 0;
2344 static void
2345 list_unique_wg_fn(const char *name,
2346 uint32 type,
2347 const char *comment,
2348 void *state)
2350 SMBCFILE *dir = (SMBCFILE *)state;
2351 struct smbc_dir_list *dir_list;
2352 struct smbc_dirent *dirent;
2353 int dirent_type;
2354 int do_remove = 0;
2356 dirent_type = dir->dir_type;
2358 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2360 /* An error occurred, what do we do? */
2361 /* FIXME: Add some code here */
2364 /* Point to the one just added */
2365 dirent = dir->dir_end->dirent;
2367 /* See if this was a duplicate */
2368 for (dir_list = dir->dir_list;
2369 dir_list != dir->dir_end;
2370 dir_list = dir_list->next) {
2371 if (! do_remove &&
2372 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2373 /* Duplicate. End end of list need to be removed. */
2374 do_remove = 1;
2377 if (do_remove && dir_list->next == dir->dir_end) {
2378 /* Found the end of the list. Remove it. */
2379 dir->dir_end = dir_list;
2380 free(dir_list->next);
2381 free(dirent);
2382 dir_list->next = NULL;
2383 break;
2388 static void
2389 list_fn(const char *name,
2390 uint32 type,
2391 const char *comment,
2392 void *state)
2394 SMBCFILE *dir = (SMBCFILE *)state;
2395 int dirent_type;
2398 * We need to process the type a little ...
2400 * Disk share = 0x00000000
2401 * Print share = 0x00000001
2402 * Comms share = 0x00000002 (obsolete?)
2403 * IPC$ share = 0x00000003
2405 * administrative shares:
2406 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2409 if (dir->dir_type == SMBC_FILE_SHARE) {
2411 switch (type) {
2412 case 0 | 0x80000000:
2413 case 0:
2414 dirent_type = SMBC_FILE_SHARE;
2415 break;
2417 case 1:
2418 dirent_type = SMBC_PRINTER_SHARE;
2419 break;
2421 case 2:
2422 dirent_type = SMBC_COMMS_SHARE;
2423 break;
2425 case 3 | 0x80000000:
2426 case 3:
2427 dirent_type = SMBC_IPC_SHARE;
2428 break;
2430 default:
2431 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2432 break;
2435 else {
2436 dirent_type = dir->dir_type;
2439 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2441 /* An error occurred, what do we do? */
2442 /* FIXME: Add some code here */
2447 static void
2448 dir_list_fn(const char *mnt,
2449 file_info *finfo,
2450 const char *mask,
2451 void *state)
2454 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2455 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2457 /* Handle an error ... */
2459 /* FIXME: Add some code ... */
2465 static int
2466 net_share_enum_rpc(struct cli_state *cli,
2467 void (*fn)(const char *name,
2468 uint32 type,
2469 const char *comment,
2470 void *state),
2471 void *state)
2473 int i;
2474 NTSTATUS result;
2475 uint32 enum_hnd;
2476 uint32 info_level = 1;
2477 uint32 preferred_len = 0xffffffff;
2478 struct srvsvc_NetShareCtr1 ctr1;
2479 union srvsvc_NetShareCtr ctr;
2480 void *mem_ctx;
2481 struct rpc_pipe_client *pipe_hnd;
2482 uint32 numentries;
2483 NTSTATUS nt_status;
2485 /* Open the server service pipe */
2486 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2487 if (!pipe_hnd) {
2488 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2489 return -1;
2492 /* Allocate a context for parsing and for the entries in "ctr" */
2493 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2494 if (mem_ctx == NULL) {
2495 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2496 cli_rpc_pipe_close(pipe_hnd);
2497 return -1;
2500 ZERO_STRUCT(ctr1);
2501 ctr.ctr1 = &ctr1;
2503 /* Issue the NetShareEnum RPC call and retrieve the response */
2504 enum_hnd = 0;
2505 result = rpccli_srvsvc_NetShareEnum(pipe_hnd, mem_ctx, NULL,
2506 &info_level, &ctr, preferred_len,
2507 &numentries, &enum_hnd);
2509 /* Was it successful? */
2510 if (!NT_STATUS_IS_OK(result) || numentries == 0) {
2511 /* Nope. Go clean up. */
2512 goto done;
2515 /* For each returned entry... */
2516 for (i = 0; i < numentries; i++) {
2518 /* Add this share to the list */
2519 (*fn)(ctr.ctr1->array[i].name,
2520 ctr.ctr1->array[i].type,
2521 ctr.ctr1->array[i].comment, state);
2524 done:
2525 /* Close the server service pipe */
2526 cli_rpc_pipe_close(pipe_hnd);
2528 /* Free all memory which was allocated for this request */
2529 TALLOC_FREE(mem_ctx);
2531 /* Tell 'em if it worked */
2532 return NT_STATUS_IS_OK(result) ? 0 : -1;
2537 static SMBCFILE *
2538 smbc_opendir_ctx(SMBCCTX *context,
2539 const char *fname)
2541 int saved_errno;
2542 fstring server, share, user, password, options;
2543 pstring workgroup;
2544 pstring path;
2545 uint16 mode;
2546 char *p;
2547 SMBCSRV *srv = NULL;
2548 SMBCFILE *dir = NULL;
2549 struct _smbc_callbacks *cb;
2550 struct in_addr rem_ip;
2552 if (!context || !context->internal ||
2553 !context->internal->_initialized) {
2554 DEBUG(4, ("no valid context\n"));
2555 errno = EINVAL + 8192;
2556 return NULL;
2560 if (!fname) {
2561 DEBUG(4, ("no valid fname\n"));
2562 errno = EINVAL + 8193;
2563 return NULL;
2566 if (smbc_parse_path(context, fname,
2567 workgroup, sizeof(workgroup),
2568 server, sizeof(server),
2569 share, sizeof(share),
2570 path, sizeof(path),
2571 user, sizeof(user),
2572 password, sizeof(password),
2573 options, sizeof(options))) {
2574 DEBUG(4, ("no valid path\n"));
2575 errno = EINVAL + 8194;
2576 return NULL;
2579 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2580 "path='%s' options='%s'\n",
2581 fname, server, share, path, options));
2583 /* Ensure the options are valid */
2584 if (smbc_check_options(server, share, path, options)) {
2585 DEBUG(4, ("unacceptable options (%s)\n", options));
2586 errno = EINVAL + 8195;
2587 return NULL;
2590 if (user[0] == (char)0) fstrcpy(user, context->user);
2592 dir = SMB_MALLOC_P(SMBCFILE);
2594 if (!dir) {
2596 errno = ENOMEM;
2597 return NULL;
2601 ZERO_STRUCTP(dir);
2603 dir->cli_fd = 0;
2604 dir->fname = SMB_STRDUP(fname);
2605 dir->srv = NULL;
2606 dir->offset = 0;
2607 dir->file = False;
2608 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2610 if (server[0] == (char)0) {
2612 int i;
2613 int count;
2614 int max_lmb_count;
2615 struct ip_service *ip_list;
2616 struct ip_service server_addr;
2617 struct user_auth_info u_info;
2618 struct cli_state *cli;
2620 if (share[0] != (char)0 || path[0] != (char)0) {
2622 errno = EINVAL + 8196;
2623 if (dir) {
2624 SAFE_FREE(dir->fname);
2625 SAFE_FREE(dir);
2627 return NULL;
2630 /* Determine how many local master browsers to query */
2631 max_lmb_count = (context->options.browse_max_lmb_count == 0
2632 ? INT_MAX
2633 : context->options.browse_max_lmb_count);
2635 pstrcpy(u_info.username, user);
2636 pstrcpy(u_info.password, password);
2639 * We have server and share and path empty but options
2640 * requesting that we scan all master browsers for their list
2641 * of workgroups/domains. This implies that we must first try
2642 * broadcast queries to find all master browsers, and if that
2643 * doesn't work, then try our other methods which return only
2644 * a single master browser.
2647 ip_list = NULL;
2648 if (!NT_STATUS_IS_OK(name_resolve_bcast(MSBROWSE, 1, &ip_list,
2649 &count)))
2652 SAFE_FREE(ip_list);
2654 if (!find_master_ip(workgroup, &server_addr.ip)) {
2656 if (dir) {
2657 SAFE_FREE(dir->fname);
2658 SAFE_FREE(dir);
2660 errno = ENOENT;
2661 return NULL;
2664 ip_list = &server_addr;
2665 count = 1;
2668 for (i = 0; i < count && i < max_lmb_count; i++) {
2669 DEBUG(99, ("Found master browser %d of %d: %s\n",
2670 i+1, MAX(count, max_lmb_count),
2671 inet_ntoa(ip_list[i].ip)));
2673 cli = get_ipc_connect_master_ip(&ip_list[i],
2674 workgroup, &u_info);
2675 /* cli == NULL is the master browser refused to talk or
2676 could not be found */
2677 if ( !cli )
2678 continue;
2680 fstrcpy(server, cli->desthost);
2681 cli_shutdown(cli);
2683 DEBUG(4, ("using workgroup %s %s\n",
2684 workgroup, server));
2687 * For each returned master browser IP address, get a
2688 * connection to IPC$ on the server if we do not
2689 * already have one, and determine the
2690 * workgroups/domains that it knows about.
2693 srv = smbc_server(context, True, server, "IPC$",
2694 workgroup, user, password);
2695 if (!srv) {
2696 continue;
2699 dir->srv = srv;
2700 dir->dir_type = SMBC_WORKGROUP;
2702 /* Now, list the stuff ... */
2704 if (!cli_NetServerEnum(srv->cli,
2705 workgroup,
2706 SV_TYPE_DOMAIN_ENUM,
2707 list_unique_wg_fn,
2708 (void *)dir)) {
2709 continue;
2713 SAFE_FREE(ip_list);
2714 } else {
2716 * Server not an empty string ... Check the rest and see what
2717 * gives
2719 if (*share == '\0') {
2720 if (*path != '\0') {
2722 /* Should not have empty share with path */
2723 errno = EINVAL + 8197;
2724 if (dir) {
2725 SAFE_FREE(dir->fname);
2726 SAFE_FREE(dir);
2728 return NULL;
2733 * We don't know if <server> is really a server name
2734 * or is a workgroup/domain name. If we already have
2735 * a server structure for it, we'll use it.
2736 * Otherwise, check to see if <server><1D>,
2737 * <server><1B>, or <server><20> translates. We check
2738 * to see if <server> is an IP address first.
2742 * See if we have an existing server. Do not
2743 * establish a connection if one does not already
2744 * exist.
2746 srv = smbc_server(context, False, server, "IPC$",
2747 workgroup, user, password);
2750 * If no existing server and not an IP addr, look for
2751 * LMB or DMB
2753 if (!srv &&
2754 !is_ipaddress(server) &&
2755 (resolve_name(server, &rem_ip, 0x1d) || /* LMB */
2756 resolve_name(server, &rem_ip, 0x1b) )) { /* DMB */
2758 fstring buserver;
2760 dir->dir_type = SMBC_SERVER;
2763 * Get the backup list ...
2765 if (!name_status_find(server, 0, 0,
2766 rem_ip, buserver)) {
2768 DEBUG(0, ("Could not get name of "
2769 "local/domain master browser "
2770 "for server %s\n", server));
2771 if (dir) {
2772 SAFE_FREE(dir->fname);
2773 SAFE_FREE(dir);
2775 errno = EPERM;
2776 return NULL;
2781 * Get a connection to IPC$ on the server if
2782 * we do not already have one
2784 srv = smbc_server(context, True,
2785 buserver, "IPC$",
2786 workgroup, user, password);
2787 if (!srv) {
2788 DEBUG(0, ("got no contact to IPC$\n"));
2789 if (dir) {
2790 SAFE_FREE(dir->fname);
2791 SAFE_FREE(dir);
2793 return NULL;
2797 dir->srv = srv;
2799 /* Now, list the servers ... */
2800 if (!cli_NetServerEnum(srv->cli, server,
2801 0x0000FFFE, list_fn,
2802 (void *)dir)) {
2804 if (dir) {
2805 SAFE_FREE(dir->fname);
2806 SAFE_FREE(dir);
2808 return NULL;
2810 } else if (srv ||
2811 (resolve_name(server, &rem_ip, 0x20))) {
2813 /* If we hadn't found the server, get one now */
2814 if (!srv) {
2815 srv = smbc_server(context, True,
2816 server, "IPC$",
2817 workgroup,
2818 user, password);
2821 if (!srv) {
2822 if (dir) {
2823 SAFE_FREE(dir->fname);
2824 SAFE_FREE(dir);
2826 return NULL;
2830 dir->dir_type = SMBC_FILE_SHARE;
2831 dir->srv = srv;
2833 /* List the shares ... */
2835 if (net_share_enum_rpc(
2836 srv->cli,
2837 list_fn,
2838 (void *) dir) < 0 &&
2839 cli_RNetShareEnum(
2840 srv->cli,
2841 list_fn,
2842 (void *)dir) < 0) {
2844 errno = cli_errno(srv->cli);
2845 if (dir) {
2846 SAFE_FREE(dir->fname);
2847 SAFE_FREE(dir);
2849 return NULL;
2852 } else {
2853 /* Neither the workgroup nor server exists */
2854 errno = ECONNREFUSED;
2855 if (dir) {
2856 SAFE_FREE(dir->fname);
2857 SAFE_FREE(dir);
2859 return NULL;
2863 else {
2865 * The server and share are specified ... work from
2866 * there ...
2868 pstring targetpath;
2869 struct cli_state *targetcli;
2871 /* We connect to the server and list the directory */
2872 dir->dir_type = SMBC_FILE_SHARE;
2874 srv = smbc_server(context, True, server, share,
2875 workgroup, user, password);
2877 if (!srv) {
2879 if (dir) {
2880 SAFE_FREE(dir->fname);
2881 SAFE_FREE(dir);
2883 return NULL;
2887 dir->srv = srv;
2889 /* Now, list the files ... */
2891 p = path + strlen(path);
2892 pstrcat(path, "\\*");
2894 if (!cli_resolve_path("", srv->cli, path,
2895 &targetcli, targetpath))
2897 d_printf("Could not resolve %s\n", path);
2898 if (dir) {
2899 SAFE_FREE(dir->fname);
2900 SAFE_FREE(dir);
2902 return NULL;
2905 if (cli_list(targetcli, targetpath,
2906 aDIR | aSYSTEM | aHIDDEN,
2907 dir_list_fn, (void *)dir) < 0) {
2909 if (dir) {
2910 SAFE_FREE(dir->fname);
2911 SAFE_FREE(dir);
2913 saved_errno = smbc_errno(context, targetcli);
2915 if (saved_errno == EINVAL) {
2917 * See if they asked to opendir something
2918 * other than a directory. If so, the
2919 * converted error value we got would have
2920 * been EINVAL rather than ENOTDIR.
2922 *p = '\0'; /* restore original path */
2924 if (smbc_getatr(context, srv, path,
2925 &mode, NULL,
2926 NULL, NULL, NULL, NULL,
2927 NULL) &&
2928 ! IS_DOS_DIR(mode)) {
2930 /* It is. Correct the error value */
2931 saved_errno = ENOTDIR;
2936 * If there was an error and the server is no
2937 * good any more...
2939 cb = &context->callbacks;
2940 if (cli_is_error(targetcli) &&
2941 (cb->check_server_fn)(context, srv)) {
2943 /* ... then remove it. */
2944 if ((cb->remove_unused_server_fn)(context,
2945 srv)) {
2947 * We could not remove the
2948 * server completely, remove
2949 * it from the cache so we
2950 * will not get it again. It
2951 * will be removed when the
2952 * last file/dir is closed.
2954 (cb->remove_cached_srv_fn)(context,
2955 srv);
2959 errno = saved_errno;
2960 return NULL;
2966 DLIST_ADD(context->internal->_files, dir);
2967 return dir;
2972 * Routine to close a directory
2975 static int
2976 smbc_closedir_ctx(SMBCCTX *context,
2977 SMBCFILE *dir)
2980 if (!context || !context->internal ||
2981 !context->internal->_initialized) {
2983 errno = EINVAL;
2984 return -1;
2988 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2990 errno = EBADF;
2991 return -1;
2995 smbc_remove_dir(dir); /* Clean it up */
2997 DLIST_REMOVE(context->internal->_files, dir);
2999 if (dir) {
3001 SAFE_FREE(dir->fname);
3002 SAFE_FREE(dir); /* Free the space too */
3005 return 0;
3009 static void
3010 smbc_readdir_internal(SMBCCTX * context,
3011 struct smbc_dirent *dest,
3012 struct smbc_dirent *src,
3013 int max_namebuf_len)
3015 if (context->options.urlencode_readdir_entries) {
3017 /* url-encode the name. get back remaining buffer space */
3018 max_namebuf_len =
3019 smbc_urlencode(dest->name, src->name, max_namebuf_len);
3021 /* We now know the name length */
3022 dest->namelen = strlen(dest->name);
3024 /* Save the pointer to the beginning of the comment */
3025 dest->comment = dest->name + dest->namelen + 1;
3027 /* Copy the comment */
3028 strncpy(dest->comment, src->comment, max_namebuf_len - 1);
3029 dest->comment[max_namebuf_len - 1] = '\0';
3031 /* Save other fields */
3032 dest->smbc_type = src->smbc_type;
3033 dest->commentlen = strlen(dest->comment);
3034 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
3035 (char *) dest);
3036 } else {
3038 /* No encoding. Just copy the entry as is. */
3039 memcpy(dest, src, src->dirlen);
3040 dest->comment = (char *)(&dest->name + src->namelen + 1);
3046 * Routine to get a directory entry
3049 struct smbc_dirent *
3050 smbc_readdir_ctx(SMBCCTX *context,
3051 SMBCFILE *dir)
3053 int maxlen;
3054 struct smbc_dirent *dirp, *dirent;
3056 /* Check that all is ok first ... */
3058 if (!context || !context->internal ||
3059 !context->internal->_initialized) {
3061 errno = EINVAL;
3062 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
3063 return NULL;
3067 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3069 errno = EBADF;
3070 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
3071 return NULL;
3075 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3077 errno = ENOTDIR;
3078 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
3079 return NULL;
3083 if (!dir->dir_next) {
3084 return NULL;
3087 dirent = dir->dir_next->dirent;
3088 if (!dirent) {
3090 errno = ENOENT;
3091 return NULL;
3095 dirp = (struct smbc_dirent *)context->internal->_dirent;
3096 maxlen = (sizeof(context->internal->_dirent) -
3097 sizeof(struct smbc_dirent));
3099 smbc_readdir_internal(context, dirp, dirent, maxlen);
3101 dir->dir_next = dir->dir_next->next;
3103 return dirp;
3107 * Routine to get directory entries
3110 static int
3111 smbc_getdents_ctx(SMBCCTX *context,
3112 SMBCFILE *dir,
3113 struct smbc_dirent *dirp,
3114 int count)
3116 int rem = count;
3117 int reqd;
3118 int maxlen;
3119 char *ndir = (char *)dirp;
3120 struct smbc_dir_list *dirlist;
3122 /* Check that all is ok first ... */
3124 if (!context || !context->internal ||
3125 !context->internal->_initialized) {
3127 errno = EINVAL;
3128 return -1;
3132 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3134 errno = EBADF;
3135 return -1;
3139 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3141 errno = ENOTDIR;
3142 return -1;
3147 * Now, retrieve the number of entries that will fit in what was passed
3148 * We have to figure out if the info is in the list, or we need to
3149 * send a request to the server to get the info.
3152 while ((dirlist = dir->dir_next)) {
3153 struct smbc_dirent *dirent;
3155 if (!dirlist->dirent) {
3157 errno = ENOENT; /* Bad error */
3158 return -1;
3162 /* Do urlencoding of next entry, if so selected */
3163 dirent = (struct smbc_dirent *)context->internal->_dirent;
3164 maxlen = (sizeof(context->internal->_dirent) -
3165 sizeof(struct smbc_dirent));
3166 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3168 reqd = dirent->dirlen;
3170 if (rem < reqd) {
3172 if (rem < count) { /* We managed to copy something */
3174 errno = 0;
3175 return count - rem;
3178 else { /* Nothing copied ... */
3180 errno = EINVAL; /* Not enough space ... */
3181 return -1;
3187 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3189 ((struct smbc_dirent *)ndir)->comment =
3190 (char *)(&((struct smbc_dirent *)ndir)->name +
3191 dirent->namelen +
3194 ndir += reqd;
3196 rem -= reqd;
3198 dir->dir_next = dirlist = dirlist -> next;
3201 if (rem == count)
3202 return 0;
3203 else
3204 return count - rem;
3209 * Routine to create a directory ...
3212 static int
3213 smbc_mkdir_ctx(SMBCCTX *context,
3214 const char *fname,
3215 mode_t mode)
3217 SMBCSRV *srv;
3218 fstring server;
3219 fstring share;
3220 fstring user;
3221 fstring password;
3222 fstring workgroup;
3223 pstring path, targetpath;
3224 struct cli_state *targetcli;
3226 if (!context || !context->internal ||
3227 !context->internal->_initialized) {
3229 errno = EINVAL;
3230 return -1;
3234 if (!fname) {
3236 errno = EINVAL;
3237 return -1;
3241 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3243 if (smbc_parse_path(context, fname,
3244 workgroup, sizeof(workgroup),
3245 server, sizeof(server),
3246 share, sizeof(share),
3247 path, sizeof(path),
3248 user, sizeof(user),
3249 password, sizeof(password),
3250 NULL, 0)) {
3251 errno = EINVAL;
3252 return -1;
3255 if (user[0] == (char)0) fstrcpy(user, context->user);
3257 srv = smbc_server(context, True,
3258 server, share, workgroup, user, password);
3260 if (!srv) {
3262 return -1; /* errno set by smbc_server */
3266 /*d_printf(">>>mkdir: resolving %s\n", path);*/
3267 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
3269 d_printf("Could not resolve %s\n", path);
3270 return -1;
3272 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3274 if (!cli_mkdir(targetcli, targetpath)) {
3276 errno = smbc_errno(context, targetcli);
3277 return -1;
3281 return 0;
3286 * Our list function simply checks to see if a directory is not empty
3289 static int smbc_rmdir_dirempty = True;
3291 static void
3292 rmdir_list_fn(const char *mnt,
3293 file_info *finfo,
3294 const char *mask,
3295 void *state)
3297 if (strncmp(finfo->name, ".", 1) != 0 &&
3298 strncmp(finfo->name, "..", 2) != 0) {
3300 smbc_rmdir_dirempty = False;
3305 * Routine to remove a directory
3308 static int
3309 smbc_rmdir_ctx(SMBCCTX *context,
3310 const char *fname)
3312 SMBCSRV *srv;
3313 fstring server;
3314 fstring share;
3315 fstring user;
3316 fstring password;
3317 fstring workgroup;
3318 pstring path;
3319 pstring targetpath;
3320 struct cli_state *targetcli;
3322 if (!context || !context->internal ||
3323 !context->internal->_initialized) {
3325 errno = EINVAL;
3326 return -1;
3330 if (!fname) {
3332 errno = EINVAL;
3333 return -1;
3337 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3339 if (smbc_parse_path(context, fname,
3340 workgroup, sizeof(workgroup),
3341 server, sizeof(server),
3342 share, sizeof(share),
3343 path, sizeof(path),
3344 user, sizeof(user),
3345 password, sizeof(password),
3346 NULL, 0))
3348 errno = EINVAL;
3349 return -1;
3352 if (user[0] == (char)0) fstrcpy(user, context->user);
3354 srv = smbc_server(context, True,
3355 server, share, workgroup, user, password);
3357 if (!srv) {
3359 return -1; /* errno set by smbc_server */
3363 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3364 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
3366 d_printf("Could not resolve %s\n", path);
3367 return -1;
3369 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3372 if (!cli_rmdir(targetcli, targetpath)) {
3374 errno = smbc_errno(context, targetcli);
3376 if (errno == EACCES) { /* Check if the dir empty or not */
3378 /* Local storage to avoid buffer overflows */
3379 pstring lpath;
3381 smbc_rmdir_dirempty = True; /* Make this so ... */
3383 pstrcpy(lpath, targetpath);
3384 pstrcat(lpath, "\\*");
3386 if (cli_list(targetcli, lpath,
3387 aDIR | aSYSTEM | aHIDDEN,
3388 rmdir_list_fn, NULL) < 0) {
3390 /* Fix errno to ignore latest error ... */
3391 DEBUG(5, ("smbc_rmdir: "
3392 "cli_list returned an error: %d\n",
3393 smbc_errno(context, targetcli)));
3394 errno = EACCES;
3398 if (smbc_rmdir_dirempty)
3399 errno = EACCES;
3400 else
3401 errno = ENOTEMPTY;
3405 return -1;
3409 return 0;
3414 * Routine to return the current directory position
3417 static off_t
3418 smbc_telldir_ctx(SMBCCTX *context,
3419 SMBCFILE *dir)
3421 if (!context || !context->internal ||
3422 !context->internal->_initialized) {
3424 errno = EINVAL;
3425 return -1;
3429 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3431 errno = EBADF;
3432 return -1;
3436 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3438 errno = ENOTDIR;
3439 return -1;
3443 /* See if we're already at the end. */
3444 if (dir->dir_next == NULL) {
3445 /* We are. */
3446 return -1;
3450 * We return the pointer here as the offset
3452 return (off_t)(long)dir->dir_next->dirent;
3456 * A routine to run down the list and see if the entry is OK
3459 struct smbc_dir_list *
3460 smbc_check_dir_ent(struct smbc_dir_list *list,
3461 struct smbc_dirent *dirent)
3464 /* Run down the list looking for what we want */
3466 if (dirent) {
3468 struct smbc_dir_list *tmp = list;
3470 while (tmp) {
3472 if (tmp->dirent == dirent)
3473 return tmp;
3475 tmp = tmp->next;
3481 return NULL; /* Not found, or an error */
3487 * Routine to seek on a directory
3490 static int
3491 smbc_lseekdir_ctx(SMBCCTX *context,
3492 SMBCFILE *dir,
3493 off_t offset)
3495 long int l_offset = offset; /* Handle problems of size */
3496 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3497 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3499 if (!context || !context->internal ||
3500 !context->internal->_initialized) {
3502 errno = EINVAL;
3503 return -1;
3507 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3509 errno = ENOTDIR;
3510 return -1;
3514 /* Now, check what we were passed and see if it is OK ... */
3516 if (dirent == NULL) { /* Seek to the begining of the list */
3518 dir->dir_next = dir->dir_list;
3519 return 0;
3523 if (offset == -1) { /* Seek to the end of the list */
3524 dir->dir_next = NULL;
3525 return 0;
3528 /* Now, run down the list and make sure that the entry is OK */
3529 /* This may need to be changed if we change the format of the list */
3531 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3533 errno = EINVAL; /* Bad entry */
3534 return -1;
3538 dir->dir_next = list_ent;
3540 return 0;
3545 * Routine to fstat a dir
3548 static int
3549 smbc_fstatdir_ctx(SMBCCTX *context,
3550 SMBCFILE *dir,
3551 struct stat *st)
3554 if (!context || !context->internal ||
3555 !context->internal->_initialized) {
3557 errno = EINVAL;
3558 return -1;
3562 /* No code yet ... */
3564 return 0;
3568 static int
3569 smbc_chmod_ctx(SMBCCTX *context,
3570 const char *fname,
3571 mode_t newmode)
3573 SMBCSRV *srv;
3574 fstring server;
3575 fstring share;
3576 fstring user;
3577 fstring password;
3578 fstring workgroup;
3579 pstring path;
3580 uint16 mode;
3582 if (!context || !context->internal ||
3583 !context->internal->_initialized) {
3585 errno = EINVAL; /* Best I can think of ... */
3586 return -1;
3590 if (!fname) {
3592 errno = EINVAL;
3593 return -1;
3597 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3599 if (smbc_parse_path(context, fname,
3600 workgroup, sizeof(workgroup),
3601 server, sizeof(server),
3602 share, sizeof(share),
3603 path, sizeof(path),
3604 user, sizeof(user),
3605 password, sizeof(password),
3606 NULL, 0)) {
3607 errno = EINVAL;
3608 return -1;
3611 if (user[0] == (char)0) fstrcpy(user, context->user);
3613 srv = smbc_server(context, True,
3614 server, share, workgroup, user, password);
3616 if (!srv) {
3617 return -1; /* errno set by smbc_server */
3620 mode = 0;
3622 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3623 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3624 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3625 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3627 if (!cli_setatr(srv->cli, path, mode, 0)) {
3628 errno = smbc_errno(context, srv->cli);
3629 return -1;
3632 return 0;
3635 static int
3636 smbc_utimes_ctx(SMBCCTX *context,
3637 const char *fname,
3638 struct timeval *tbuf)
3640 SMBCSRV *srv;
3641 fstring server;
3642 fstring share;
3643 fstring user;
3644 fstring password;
3645 fstring workgroup;
3646 pstring path;
3647 time_t access_time;
3648 time_t write_time;
3650 if (!context || !context->internal ||
3651 !context->internal->_initialized) {
3653 errno = EINVAL; /* Best I can think of ... */
3654 return -1;
3658 if (!fname) {
3660 errno = EINVAL;
3661 return -1;
3665 if (tbuf == NULL) {
3666 access_time = write_time = time(NULL);
3667 } else {
3668 access_time = tbuf[0].tv_sec;
3669 write_time = tbuf[1].tv_sec;
3672 if (DEBUGLVL(4))
3674 char *p;
3675 char atimebuf[32];
3676 char mtimebuf[32];
3678 strncpy(atimebuf, ctime(&access_time), sizeof(atimebuf) - 1);
3679 atimebuf[sizeof(atimebuf) - 1] = '\0';
3680 if ((p = strchr(atimebuf, '\n')) != NULL) {
3681 *p = '\0';
3684 strncpy(mtimebuf, ctime(&write_time), sizeof(mtimebuf) - 1);
3685 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3686 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3687 *p = '\0';
3690 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3691 fname, atimebuf, mtimebuf);
3694 if (smbc_parse_path(context, fname,
3695 workgroup, sizeof(workgroup),
3696 server, sizeof(server),
3697 share, sizeof(share),
3698 path, sizeof(path),
3699 user, sizeof(user),
3700 password, sizeof(password),
3701 NULL, 0)) {
3702 errno = EINVAL;
3703 return -1;
3706 if (user[0] == (char)0) fstrcpy(user, context->user);
3708 srv = smbc_server(context, True,
3709 server, share, workgroup, user, password);
3711 if (!srv) {
3712 return -1; /* errno set by smbc_server */
3715 if (!smbc_setatr(context, srv, path,
3716 0, access_time, write_time, 0, 0)) {
3717 return -1; /* errno set by smbc_setatr */
3720 return 0;
3725 * Sort ACEs according to the documentation at
3726 * http://support.microsoft.com/kb/269175, at least as far as it defines the
3727 * order.
3730 static int
3731 ace_compare(SEC_ACE *ace1,
3732 SEC_ACE *ace2)
3734 BOOL b1;
3735 BOOL b2;
3737 /* If the ACEs are equal, we have nothing more to do. */
3738 if (sec_ace_equal(ace1, ace2)) {
3739 return 0;
3742 /* Inherited follow non-inherited */
3743 b1 = ((ace1->flags & SEC_ACE_FLAG_INHERITED_ACE) != 0);
3744 b2 = ((ace2->flags & SEC_ACE_FLAG_INHERITED_ACE) != 0);
3745 if (b1 != b2) {
3746 return (b1 ? 1 : -1);
3750 * What shall we do with AUDITs and ALARMs? It's undefined. We'll
3751 * sort them after DENY and ALLOW.
3753 b1 = (ace1->type != SEC_ACE_TYPE_ACCESS_ALLOWED &&
3754 ace1->type != SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT &&
3755 ace1->type != SEC_ACE_TYPE_ACCESS_DENIED &&
3756 ace1->type != SEC_ACE_TYPE_ACCESS_DENIED_OBJECT);
3757 b2 = (ace2->type != SEC_ACE_TYPE_ACCESS_ALLOWED &&
3758 ace2->type != SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT &&
3759 ace2->type != SEC_ACE_TYPE_ACCESS_DENIED &&
3760 ace2->type != SEC_ACE_TYPE_ACCESS_DENIED_OBJECT);
3761 if (b1 != b2) {
3762 return (b1 ? 1 : -1);
3765 /* Allowed ACEs follow denied ACEs */
3766 b1 = (ace1->type == SEC_ACE_TYPE_ACCESS_ALLOWED ||
3767 ace1->type == SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT);
3768 b2 = (ace2->type == SEC_ACE_TYPE_ACCESS_ALLOWED ||
3769 ace2->type == SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT);
3770 if (b1 != b2) {
3771 return (b1 ? 1 : -1);
3775 * ACEs applying to an entity's object follow those applying to the
3776 * entity itself
3778 b1 = (ace1->type == SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT ||
3779 ace1->type == SEC_ACE_TYPE_ACCESS_DENIED_OBJECT);
3780 b2 = (ace2->type == SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT ||
3781 ace2->type == SEC_ACE_TYPE_ACCESS_DENIED_OBJECT);
3782 if (b1 != b2) {
3783 return (b1 ? 1 : -1);
3787 * If we get this far, the ACEs are similar as far as the
3788 * characteristics we typically care about (those defined by the
3789 * referenced MS document). We'll now sort by characteristics that
3790 * just seems reasonable.
3793 if (ace1->type != ace2->type) {
3794 return ace2->type - ace1->type;
3797 if (sid_compare(&ace1->trustee, &ace2->trustee)) {
3798 return sid_compare(&ace1->trustee, &ace2->trustee);
3801 if (ace1->flags != ace2->flags) {
3802 return ace1->flags - ace2->flags;
3805 if (ace1->access_mask != ace2->access_mask) {
3806 return ace1->access_mask - ace2->access_mask;
3809 if (ace1->size != ace2->size) {
3810 return ace1->size - ace2->size;
3813 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3817 static void
3818 sort_acl(SEC_ACL *the_acl)
3820 uint32 i;
3821 if (!the_acl) return;
3823 qsort(the_acl->aces, the_acl->num_aces, sizeof(the_acl->aces[0]),
3824 QSORT_CAST ace_compare);
3826 for (i=1;i<the_acl->num_aces;) {
3827 if (sec_ace_equal(&the_acl->aces[i-1], &the_acl->aces[i])) {
3828 int j;
3829 for (j=i; j<the_acl->num_aces-1; j++) {
3830 the_acl->aces[j] = the_acl->aces[j+1];
3832 the_acl->num_aces--;
3833 } else {
3834 i++;
3839 /* convert a SID to a string, either numeric or username/group */
3840 static void
3841 convert_sid_to_string(struct cli_state *ipc_cli,
3842 POLICY_HND *pol,
3843 fstring str,
3844 BOOL numeric,
3845 DOM_SID *sid)
3847 char **domains = NULL;
3848 char **names = NULL;
3849 enum lsa_SidType *types = NULL;
3850 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3851 sid_to_string(str, sid);
3853 if (numeric) {
3854 return; /* no lookup desired */
3857 if (!pipe_hnd) {
3858 return;
3861 /* Ask LSA to convert the sid to a name */
3863 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3864 pol, 1, sid, &domains,
3865 &names, &types)) ||
3866 !domains || !domains[0] || !names || !names[0]) {
3867 return;
3870 /* Converted OK */
3872 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3873 domains[0], lp_winbind_separator(),
3874 names[0]);
3877 /* convert a string to a SID, either numeric or username/group */
3878 static BOOL
3879 convert_string_to_sid(struct cli_state *ipc_cli,
3880 POLICY_HND *pol,
3881 BOOL numeric,
3882 DOM_SID *sid,
3883 const char *str)
3885 enum lsa_SidType *types = NULL;
3886 DOM_SID *sids = NULL;
3887 BOOL result = True;
3888 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3890 if (!pipe_hnd) {
3891 return False;
3894 if (numeric) {
3895 if (strncmp(str, "S-", 2) == 0) {
3896 return string_to_sid(sid, str);
3899 result = False;
3900 goto done;
3903 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3904 pol, 1, &str, NULL, 1, &sids,
3905 &types))) {
3906 result = False;
3907 goto done;
3910 sid_copy(sid, &sids[0]);
3911 done:
3913 return result;
3917 /* parse an ACE in the same format as print_ace() */
3918 static BOOL
3919 parse_ace(struct cli_state *ipc_cli,
3920 POLICY_HND *pol,
3921 SEC_ACE *ace,
3922 BOOL numeric,
3923 char *str)
3925 char *p;
3926 const char *cp;
3927 fstring tok;
3928 unsigned int atype;
3929 unsigned int aflags;
3930 unsigned int amask;
3931 DOM_SID sid;
3932 SEC_ACCESS mask;
3933 const struct perm_value *v;
3934 struct perm_value {
3935 const char *perm;
3936 uint32 mask;
3939 /* These values discovered by inspection */
3940 static const struct perm_value special_values[] = {
3941 { "R", 0x00120089 },
3942 { "W", 0x00120116 },
3943 { "X", 0x001200a0 },
3944 { "D", 0x00010000 },
3945 { "P", 0x00040000 },
3946 { "O", 0x00080000 },
3947 { NULL, 0 },
3950 static const struct perm_value standard_values[] = {
3951 { "READ", 0x001200a9 },
3952 { "CHANGE", 0x001301bf },
3953 { "FULL", 0x001f01ff },
3954 { NULL, 0 },
3958 ZERO_STRUCTP(ace);
3959 p = strchr_m(str,':');
3960 if (!p) return False;
3961 *p = '\0';
3962 p++;
3963 /* Try to parse numeric form */
3965 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3966 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3967 goto done;
3970 /* Try to parse text form */
3972 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3973 return False;
3976 cp = p;
3977 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3978 return False;
3981 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3982 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3983 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3984 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3985 } else {
3986 return False;
3989 /* Only numeric form accepted for flags at present */
3991 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3992 sscanf(tok, "%i", &aflags))) {
3993 return False;
3996 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3997 return False;
4000 if (strncmp(tok, "0x", 2) == 0) {
4001 if (sscanf(tok, "%i", &amask) != 1) {
4002 return False;
4004 goto done;
4007 for (v = standard_values; v->perm; v++) {
4008 if (strcmp(tok, v->perm) == 0) {
4009 amask = v->mask;
4010 goto done;
4014 p = tok;
4016 while(*p) {
4017 BOOL found = False;
4019 for (v = special_values; v->perm; v++) {
4020 if (v->perm[0] == *p) {
4021 amask |= v->mask;
4022 found = True;
4026 if (!found) return False;
4027 p++;
4030 if (*p) {
4031 return False;
4034 done:
4035 mask = amask;
4036 init_sec_ace(ace, &sid, atype, mask, aflags);
4037 return True;
4040 /* add an ACE to a list of ACEs in a SEC_ACL */
4041 static BOOL
4042 add_ace(SEC_ACL **the_acl,
4043 SEC_ACE *ace,
4044 TALLOC_CTX *ctx)
4046 SEC_ACL *newacl;
4047 SEC_ACE *aces;
4049 if (! *the_acl) {
4050 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
4051 return True;
4054 if ((aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces)) == NULL) {
4055 return False;
4057 memcpy(aces, (*the_acl)->aces, (*the_acl)->num_aces * sizeof(SEC_ACE));
4058 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
4059 newacl = make_sec_acl(ctx, (*the_acl)->revision,
4060 1+(*the_acl)->num_aces, aces);
4061 SAFE_FREE(aces);
4062 (*the_acl) = newacl;
4063 return True;
4067 /* parse a ascii version of a security descriptor */
4068 static SEC_DESC *
4069 sec_desc_parse(TALLOC_CTX *ctx,
4070 struct cli_state *ipc_cli,
4071 POLICY_HND *pol,
4072 BOOL numeric,
4073 char *str)
4075 const char *p = str;
4076 fstring tok;
4077 SEC_DESC *ret = NULL;
4078 size_t sd_size;
4079 DOM_SID *grp_sid=NULL;
4080 DOM_SID *owner_sid=NULL;
4081 SEC_ACL *dacl=NULL;
4082 int revision=1;
4084 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4086 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
4087 revision = strtol(tok+9, NULL, 16);
4088 continue;
4091 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
4092 if (owner_sid) {
4093 DEBUG(5, ("OWNER specified more than once!\n"));
4094 goto done;
4096 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4097 if (!owner_sid ||
4098 !convert_string_to_sid(ipc_cli, pol,
4099 numeric,
4100 owner_sid, tok+6)) {
4101 DEBUG(5, ("Failed to parse owner sid\n"));
4102 goto done;
4104 continue;
4107 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
4108 if (owner_sid) {
4109 DEBUG(5, ("OWNER specified more than once!\n"));
4110 goto done;
4112 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4113 if (!owner_sid ||
4114 !convert_string_to_sid(ipc_cli, pol,
4115 False,
4116 owner_sid, tok+7)) {
4117 DEBUG(5, ("Failed to parse owner sid\n"));
4118 goto done;
4120 continue;
4123 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
4124 if (grp_sid) {
4125 DEBUG(5, ("GROUP specified more than once!\n"));
4126 goto done;
4128 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4129 if (!grp_sid ||
4130 !convert_string_to_sid(ipc_cli, pol,
4131 numeric,
4132 grp_sid, tok+6)) {
4133 DEBUG(5, ("Failed to parse group sid\n"));
4134 goto done;
4136 continue;
4139 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
4140 if (grp_sid) {
4141 DEBUG(5, ("GROUP specified more than once!\n"));
4142 goto done;
4144 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4145 if (!grp_sid ||
4146 !convert_string_to_sid(ipc_cli, pol,
4147 False,
4148 grp_sid, tok+6)) {
4149 DEBUG(5, ("Failed to parse group sid\n"));
4150 goto done;
4152 continue;
4155 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
4156 SEC_ACE ace;
4157 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
4158 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4159 goto done;
4161 if(!add_ace(&dacl, &ace, ctx)) {
4162 DEBUG(5, ("Failed to add ACL %s\n", tok));
4163 goto done;
4165 continue;
4168 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
4169 SEC_ACE ace;
4170 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
4171 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4172 goto done;
4174 if(!add_ace(&dacl, &ace, ctx)) {
4175 DEBUG(5, ("Failed to add ACL %s\n", tok));
4176 goto done;
4178 continue;
4181 DEBUG(5, ("Failed to parse security descriptor\n"));
4182 goto done;
4185 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
4186 owner_sid, grp_sid, NULL, dacl, &sd_size);
4188 done:
4189 SAFE_FREE(grp_sid);
4190 SAFE_FREE(owner_sid);
4192 return ret;
4196 /* Obtain the current dos attributes */
4197 static DOS_ATTR_DESC *
4198 dos_attr_query(SMBCCTX *context,
4199 TALLOC_CTX *ctx,
4200 const char *filename,
4201 SMBCSRV *srv)
4203 struct timespec create_time_ts;
4204 struct timespec write_time_ts;
4205 struct timespec access_time_ts;
4206 struct timespec change_time_ts;
4207 SMB_OFF_T size = 0;
4208 uint16 mode = 0;
4209 SMB_INO_T inode = 0;
4210 DOS_ATTR_DESC *ret;
4212 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
4213 if (!ret) {
4214 errno = ENOMEM;
4215 return NULL;
4218 /* Obtain the DOS attributes */
4219 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
4220 &mode, &size,
4221 &create_time_ts,
4222 &access_time_ts,
4223 &write_time_ts,
4224 &change_time_ts,
4225 &inode)) {
4227 errno = smbc_errno(context, srv->cli);
4228 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
4229 return NULL;
4233 ret->mode = mode;
4234 ret->size = size;
4235 ret->create_time = convert_timespec_to_time_t(create_time_ts);
4236 ret->access_time = convert_timespec_to_time_t(access_time_ts);
4237 ret->write_time = convert_timespec_to_time_t(write_time_ts);
4238 ret->change_time = convert_timespec_to_time_t(change_time_ts);
4239 ret->inode = inode;
4241 return ret;
4245 /* parse a ascii version of a security descriptor */
4246 static void
4247 dos_attr_parse(SMBCCTX *context,
4248 DOS_ATTR_DESC *dad,
4249 SMBCSRV *srv,
4250 char *str)
4252 int n;
4253 const char *p = str;
4254 fstring tok;
4255 struct {
4256 const char * create_time_attr;
4257 const char * access_time_attr;
4258 const char * write_time_attr;
4259 const char * change_time_attr;
4260 } attr_strings;
4262 /* Determine whether to use old-style or new-style attribute names */
4263 if (context->internal->_full_time_names) {
4264 /* new-style names */
4265 attr_strings.create_time_attr = "CREATE_TIME";
4266 attr_strings.access_time_attr = "ACCESS_TIME";
4267 attr_strings.write_time_attr = "WRITE_TIME";
4268 attr_strings.change_time_attr = "CHANGE_TIME";
4269 } else {
4270 /* old-style names */
4271 attr_strings.create_time_attr = NULL;
4272 attr_strings.access_time_attr = "A_TIME";
4273 attr_strings.write_time_attr = "M_TIME";
4274 attr_strings.change_time_attr = "C_TIME";
4277 /* if this is to set the entire ACL... */
4278 if (*str == '*') {
4279 /* ... then increment past the first colon if there is one */
4280 if ((p = strchr(str, ':')) != NULL) {
4281 ++p;
4282 } else {
4283 p = str;
4287 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4289 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
4290 dad->mode = strtol(tok+5, NULL, 16);
4291 continue;
4294 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4295 dad->size = (SMB_OFF_T)atof(tok+5);
4296 continue;
4299 n = strlen(attr_strings.access_time_attr);
4300 if (StrnCaseCmp(tok, attr_strings.access_time_attr, n) == 0) {
4301 dad->access_time = (time_t)strtol(tok+n+1, NULL, 10);
4302 continue;
4305 n = strlen(attr_strings.change_time_attr);
4306 if (StrnCaseCmp(tok, attr_strings.change_time_attr, n) == 0) {
4307 dad->change_time = (time_t)strtol(tok+n+1, NULL, 10);
4308 continue;
4311 n = strlen(attr_strings.write_time_attr);
4312 if (StrnCaseCmp(tok, attr_strings.write_time_attr, n) == 0) {
4313 dad->write_time = (time_t)strtol(tok+n+1, NULL, 10);
4314 continue;
4317 if (attr_strings.create_time_attr != NULL) {
4318 n = strlen(attr_strings.create_time_attr);
4319 if (StrnCaseCmp(tok, attr_strings.create_time_attr,
4320 n) == 0) {
4321 dad->create_time = (time_t)strtol(tok+n+1,
4322 NULL, 10);
4323 continue;
4327 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4328 dad->inode = (SMB_INO_T)atof(tok+6);
4329 continue;
4334 /*****************************************************
4335 Retrieve the acls for a file.
4336 *******************************************************/
4338 static int
4339 cacl_get(SMBCCTX *context,
4340 TALLOC_CTX *ctx,
4341 SMBCSRV *srv,
4342 struct cli_state *ipc_cli,
4343 POLICY_HND *pol,
4344 char *filename,
4345 char *attr_name,
4346 char *buf,
4347 int bufsize)
4349 uint32 i;
4350 int n = 0;
4351 int n_used;
4352 BOOL all;
4353 BOOL all_nt;
4354 BOOL all_nt_acls;
4355 BOOL all_dos;
4356 BOOL some_nt;
4357 BOOL some_dos;
4358 BOOL exclude_nt_revision = False;
4359 BOOL exclude_nt_owner = False;
4360 BOOL exclude_nt_group = False;
4361 BOOL exclude_nt_acl = False;
4362 BOOL exclude_dos_mode = False;
4363 BOOL exclude_dos_size = False;
4364 BOOL exclude_dos_create_time = False;
4365 BOOL exclude_dos_access_time = False;
4366 BOOL exclude_dos_write_time = False;
4367 BOOL exclude_dos_change_time = False;
4368 BOOL exclude_dos_inode = False;
4369 BOOL numeric = True;
4370 BOOL determine_size = (bufsize == 0);
4371 int fnum = -1;
4372 SEC_DESC *sd;
4373 fstring sidstr;
4374 fstring name_sandbox;
4375 char *name;
4376 char *pExclude;
4377 char *p;
4378 struct timespec create_time_ts;
4379 struct timespec write_time_ts;
4380 struct timespec access_time_ts;
4381 struct timespec change_time_ts;
4382 time_t create_time = (time_t)0;
4383 time_t write_time = (time_t)0;
4384 time_t access_time = (time_t)0;
4385 time_t change_time = (time_t)0;
4386 SMB_OFF_T size = 0;
4387 uint16 mode = 0;
4388 SMB_INO_T ino = 0;
4389 struct cli_state *cli = srv->cli;
4390 struct {
4391 const char * create_time_attr;
4392 const char * access_time_attr;
4393 const char * write_time_attr;
4394 const char * change_time_attr;
4395 } attr_strings;
4396 struct {
4397 const char * create_time_attr;
4398 const char * access_time_attr;
4399 const char * write_time_attr;
4400 const char * change_time_attr;
4401 } excl_attr_strings;
4403 /* Determine whether to use old-style or new-style attribute names */
4404 if (context->internal->_full_time_names) {
4405 /* new-style names */
4406 attr_strings.create_time_attr = "CREATE_TIME";
4407 attr_strings.access_time_attr = "ACCESS_TIME";
4408 attr_strings.write_time_attr = "WRITE_TIME";
4409 attr_strings.change_time_attr = "CHANGE_TIME";
4411 excl_attr_strings.create_time_attr = "CREATE_TIME";
4412 excl_attr_strings.access_time_attr = "ACCESS_TIME";
4413 excl_attr_strings.write_time_attr = "WRITE_TIME";
4414 excl_attr_strings.change_time_attr = "CHANGE_TIME";
4415 } else {
4416 /* old-style names */
4417 attr_strings.create_time_attr = NULL;
4418 attr_strings.access_time_attr = "A_TIME";
4419 attr_strings.write_time_attr = "M_TIME";
4420 attr_strings.change_time_attr = "C_TIME";
4422 excl_attr_strings.create_time_attr = NULL;
4423 excl_attr_strings.access_time_attr = "dos_attr.A_TIME";
4424 excl_attr_strings.write_time_attr = "dos_attr.M_TIME";
4425 excl_attr_strings.change_time_attr = "dos_attr.C_TIME";
4428 /* Copy name so we can strip off exclusions (if any are specified) */
4429 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4431 /* Ensure name is null terminated */
4432 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4434 /* Play in the sandbox */
4435 name = name_sandbox;
4437 /* If there are any exclusions, point to them and mask them from name */
4438 if ((pExclude = strchr(name, '!')) != NULL)
4440 *pExclude++ = '\0';
4443 all = (StrnCaseCmp(name, "system.*", 8) == 0);
4444 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4445 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4446 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4447 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4448 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4449 numeric = (* (name + strlen(name) - 1) != '+');
4451 /* Look for exclusions from "all" requests */
4452 if (all || all_nt || all_dos) {
4454 /* Exclusions are delimited by '!' */
4455 for (;
4456 pExclude != NULL;
4457 pExclude = (p == NULL ? NULL : p + 1)) {
4459 /* Find end of this exclusion name */
4460 if ((p = strchr(pExclude, '!')) != NULL)
4462 *p = '\0';
4465 /* Which exclusion name is this? */
4466 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4467 exclude_nt_revision = True;
4469 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4470 exclude_nt_owner = True;
4472 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4473 exclude_nt_group = True;
4475 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4476 exclude_nt_acl = True;
4478 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4479 exclude_dos_mode = True;
4481 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4482 exclude_dos_size = True;
4484 else if (excl_attr_strings.create_time_attr != NULL &&
4485 StrCaseCmp(pExclude,
4486 excl_attr_strings.change_time_attr) == 0) {
4487 exclude_dos_create_time = True;
4489 else if (StrCaseCmp(pExclude,
4490 excl_attr_strings.access_time_attr) == 0) {
4491 exclude_dos_access_time = True;
4493 else if (StrCaseCmp(pExclude,
4494 excl_attr_strings.write_time_attr) == 0) {
4495 exclude_dos_write_time = True;
4497 else if (StrCaseCmp(pExclude,
4498 excl_attr_strings.change_time_attr) == 0) {
4499 exclude_dos_change_time = True;
4501 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4502 exclude_dos_inode = True;
4504 else {
4505 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4506 pExclude));
4507 errno = ENOATTR;
4508 return -1;
4513 n_used = 0;
4516 * If we are (possibly) talking to an NT or new system and some NT
4517 * attributes have been requested...
4519 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4520 /* Point to the portion after "system.nt_sec_desc." */
4521 name += 19; /* if (all) this will be invalid but unused */
4523 /* ... then obtain any NT attributes which were requested */
4524 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4526 if (fnum == -1) {
4527 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4528 filename, cli_errstr(cli)));
4529 errno = 0;
4530 return -1;
4533 sd = cli_query_secdesc(cli, fnum, ctx);
4535 if (!sd) {
4536 DEBUG(5,
4537 ("cacl_get Failed to query old descriptor\n"));
4538 errno = 0;
4539 return -1;
4542 cli_close(cli, fnum);
4544 if (! exclude_nt_revision) {
4545 if (all || all_nt) {
4546 if (determine_size) {
4547 p = talloc_asprintf(ctx,
4548 "REVISION:%d",
4549 sd->revision);
4550 if (!p) {
4551 errno = ENOMEM;
4552 return -1;
4554 n = strlen(p);
4555 } else {
4556 n = snprintf(buf, bufsize,
4557 "REVISION:%d",
4558 sd->revision);
4560 } else if (StrCaseCmp(name, "revision") == 0) {
4561 if (determine_size) {
4562 p = talloc_asprintf(ctx, "%d",
4563 sd->revision);
4564 if (!p) {
4565 errno = ENOMEM;
4566 return -1;
4568 n = strlen(p);
4569 } else {
4570 n = snprintf(buf, bufsize, "%d",
4571 sd->revision);
4575 if (!determine_size && n > bufsize) {
4576 errno = ERANGE;
4577 return -1;
4579 buf += n;
4580 n_used += n;
4581 bufsize -= n;
4582 n = 0;
4585 if (! exclude_nt_owner) {
4586 /* Get owner and group sid */
4587 if (sd->owner_sid) {
4588 convert_sid_to_string(ipc_cli, pol,
4589 sidstr,
4590 numeric,
4591 sd->owner_sid);
4592 } else {
4593 fstrcpy(sidstr, "");
4596 if (all || all_nt) {
4597 if (determine_size) {
4598 p = talloc_asprintf(ctx, ",OWNER:%s",
4599 sidstr);
4600 if (!p) {
4601 errno = ENOMEM;
4602 return -1;
4604 n = strlen(p);
4605 } else if (sidstr[0] != '\0') {
4606 n = snprintf(buf, bufsize,
4607 ",OWNER:%s", sidstr);
4609 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4610 if (determine_size) {
4611 p = talloc_asprintf(ctx, "%s", sidstr);
4612 if (!p) {
4613 errno = ENOMEM;
4614 return -1;
4616 n = strlen(p);
4617 } else {
4618 n = snprintf(buf, bufsize, "%s",
4619 sidstr);
4623 if (!determine_size && n > bufsize) {
4624 errno = ERANGE;
4625 return -1;
4627 buf += n;
4628 n_used += n;
4629 bufsize -= n;
4630 n = 0;
4633 if (! exclude_nt_group) {
4634 if (sd->group_sid) {
4635 convert_sid_to_string(ipc_cli, pol,
4636 sidstr, numeric,
4637 sd->group_sid);
4638 } else {
4639 fstrcpy(sidstr, "");
4642 if (all || all_nt) {
4643 if (determine_size) {
4644 p = talloc_asprintf(ctx, ",GROUP:%s",
4645 sidstr);
4646 if (!p) {
4647 errno = ENOMEM;
4648 return -1;
4650 n = strlen(p);
4651 } else if (sidstr[0] != '\0') {
4652 n = snprintf(buf, bufsize,
4653 ",GROUP:%s", sidstr);
4655 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4656 if (determine_size) {
4657 p = talloc_asprintf(ctx, "%s", sidstr);
4658 if (!p) {
4659 errno = ENOMEM;
4660 return -1;
4662 n = strlen(p);
4663 } else {
4664 n = snprintf(buf, bufsize,
4665 "%s", sidstr);
4669 if (!determine_size && n > bufsize) {
4670 errno = ERANGE;
4671 return -1;
4673 buf += n;
4674 n_used += n;
4675 bufsize -= n;
4676 n = 0;
4679 if (! exclude_nt_acl) {
4680 /* Add aces to value buffer */
4681 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4683 SEC_ACE *ace = &sd->dacl->aces[i];
4684 convert_sid_to_string(ipc_cli, pol,
4685 sidstr, numeric,
4686 &ace->trustee);
4688 if (all || all_nt) {
4689 if (determine_size) {
4690 p = talloc_asprintf(
4691 ctx,
4692 ",ACL:"
4693 "%s:%d/%d/0x%08x",
4694 sidstr,
4695 ace->type,
4696 ace->flags,
4697 ace->access_mask);
4698 if (!p) {
4699 errno = ENOMEM;
4700 return -1;
4702 n = strlen(p);
4703 } else {
4704 n = snprintf(
4705 buf, bufsize,
4706 ",ACL:%s:%d/%d/0x%08x",
4707 sidstr,
4708 ace->type,
4709 ace->flags,
4710 ace->access_mask);
4712 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4713 StrCaseCmp(name+3, sidstr) == 0) ||
4714 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4715 StrCaseCmp(name+4, sidstr) == 0)) {
4716 if (determine_size) {
4717 p = talloc_asprintf(
4718 ctx,
4719 "%d/%d/0x%08x",
4720 ace->type,
4721 ace->flags,
4722 ace->access_mask);
4723 if (!p) {
4724 errno = ENOMEM;
4725 return -1;
4727 n = strlen(p);
4728 } else {
4729 n = snprintf(buf, bufsize,
4730 "%d/%d/0x%08x",
4731 ace->type,
4732 ace->flags,
4733 ace->access_mask);
4735 } else if (all_nt_acls) {
4736 if (determine_size) {
4737 p = talloc_asprintf(
4738 ctx,
4739 "%s%s:%d/%d/0x%08x",
4740 i ? "," : "",
4741 sidstr,
4742 ace->type,
4743 ace->flags,
4744 ace->access_mask);
4745 if (!p) {
4746 errno = ENOMEM;
4747 return -1;
4749 n = strlen(p);
4750 } else {
4751 n = snprintf(buf, bufsize,
4752 "%s%s:%d/%d/0x%08x",
4753 i ? "," : "",
4754 sidstr,
4755 ace->type,
4756 ace->flags,
4757 ace->access_mask);
4760 if (!determine_size && n > bufsize) {
4761 errno = ERANGE;
4762 return -1;
4764 buf += n;
4765 n_used += n;
4766 bufsize -= n;
4767 n = 0;
4771 /* Restore name pointer to its original value */
4772 name -= 19;
4775 if (all || some_dos) {
4776 /* Point to the portion after "system.dos_attr." */
4777 name += 16; /* if (all) this will be invalid but unused */
4779 /* Obtain the DOS attributes */
4780 if (!smbc_getatr(context, srv, filename, &mode, &size,
4781 &create_time_ts,
4782 &access_time_ts,
4783 &write_time_ts,
4784 &change_time_ts,
4785 &ino)) {
4787 errno = smbc_errno(context, srv->cli);
4788 return -1;
4792 create_time = convert_timespec_to_time_t(create_time_ts);
4793 access_time = convert_timespec_to_time_t(access_time_ts);
4794 write_time = convert_timespec_to_time_t(write_time_ts);
4795 change_time = convert_timespec_to_time_t(change_time_ts);
4797 if (! exclude_dos_mode) {
4798 if (all || all_dos) {
4799 if (determine_size) {
4800 p = talloc_asprintf(ctx,
4801 "%sMODE:0x%x",
4802 (ipc_cli &&
4803 (all || some_nt)
4804 ? ","
4805 : ""),
4806 mode);
4807 if (!p) {
4808 errno = ENOMEM;
4809 return -1;
4811 n = strlen(p);
4812 } else {
4813 n = snprintf(buf, bufsize,
4814 "%sMODE:0x%x",
4815 (ipc_cli &&
4816 (all || some_nt)
4817 ? ","
4818 : ""),
4819 mode);
4821 } else if (StrCaseCmp(name, "mode") == 0) {
4822 if (determine_size) {
4823 p = talloc_asprintf(ctx, "0x%x", mode);
4824 if (!p) {
4825 errno = ENOMEM;
4826 return -1;
4828 n = strlen(p);
4829 } else {
4830 n = snprintf(buf, bufsize,
4831 "0x%x", mode);
4835 if (!determine_size && n > bufsize) {
4836 errno = ERANGE;
4837 return -1;
4839 buf += n;
4840 n_used += n;
4841 bufsize -= n;
4842 n = 0;
4845 if (! exclude_dos_size) {
4846 if (all || all_dos) {
4847 if (determine_size) {
4848 p = talloc_asprintf(
4849 ctx,
4850 ",SIZE:%.0f",
4851 (double)size);
4852 if (!p) {
4853 errno = ENOMEM;
4854 return -1;
4856 n = strlen(p);
4857 } else {
4858 n = snprintf(buf, bufsize,
4859 ",SIZE:%.0f",
4860 (double)size);
4862 } else if (StrCaseCmp(name, "size") == 0) {
4863 if (determine_size) {
4864 p = talloc_asprintf(
4865 ctx,
4866 "%.0f",
4867 (double)size);
4868 if (!p) {
4869 errno = ENOMEM;
4870 return -1;
4872 n = strlen(p);
4873 } else {
4874 n = snprintf(buf, bufsize,
4875 "%.0f",
4876 (double)size);
4880 if (!determine_size && n > bufsize) {
4881 errno = ERANGE;
4882 return -1;
4884 buf += n;
4885 n_used += n;
4886 bufsize -= n;
4887 n = 0;
4890 if (! exclude_dos_create_time &&
4891 attr_strings.create_time_attr != NULL) {
4892 if (all || all_dos) {
4893 if (determine_size) {
4894 p = talloc_asprintf(ctx,
4895 ",%s:%lu",
4896 attr_strings.create_time_attr,
4897 create_time);
4898 if (!p) {
4899 errno = ENOMEM;
4900 return -1;
4902 n = strlen(p);
4903 } else {
4904 n = snprintf(buf, bufsize,
4905 ",%s:%lu",
4906 attr_strings.create_time_attr,
4907 create_time);
4909 } else if (StrCaseCmp(name, attr_strings.create_time_attr) == 0) {
4910 if (determine_size) {
4911 p = talloc_asprintf(ctx, "%lu", create_time);
4912 if (!p) {
4913 errno = ENOMEM;
4914 return -1;
4916 n = strlen(p);
4917 } else {
4918 n = snprintf(buf, bufsize,
4919 "%lu", create_time);
4923 if (!determine_size && n > bufsize) {
4924 errno = ERANGE;
4925 return -1;
4927 buf += n;
4928 n_used += n;
4929 bufsize -= n;
4930 n = 0;
4933 if (! exclude_dos_access_time) {
4934 if (all || all_dos) {
4935 if (determine_size) {
4936 p = talloc_asprintf(ctx,
4937 ",%s:%lu",
4938 attr_strings.access_time_attr,
4939 access_time);
4940 if (!p) {
4941 errno = ENOMEM;
4942 return -1;
4944 n = strlen(p);
4945 } else {
4946 n = snprintf(buf, bufsize,
4947 ",%s:%lu",
4948 attr_strings.access_time_attr,
4949 access_time);
4951 } else if (StrCaseCmp(name, attr_strings.access_time_attr) == 0) {
4952 if (determine_size) {
4953 p = talloc_asprintf(ctx, "%lu", access_time);
4954 if (!p) {
4955 errno = ENOMEM;
4956 return -1;
4958 n = strlen(p);
4959 } else {
4960 n = snprintf(buf, bufsize,
4961 "%lu", access_time);
4965 if (!determine_size && n > bufsize) {
4966 errno = ERANGE;
4967 return -1;
4969 buf += n;
4970 n_used += n;
4971 bufsize -= n;
4972 n = 0;
4975 if (! exclude_dos_write_time) {
4976 if (all || all_dos) {
4977 if (determine_size) {
4978 p = talloc_asprintf(ctx,
4979 ",%s:%lu",
4980 attr_strings.write_time_attr,
4981 write_time);
4982 if (!p) {
4983 errno = ENOMEM;
4984 return -1;
4986 n = strlen(p);
4987 } else {
4988 n = snprintf(buf, bufsize,
4989 ",%s:%lu",
4990 attr_strings.write_time_attr,
4991 write_time);
4993 } else if (StrCaseCmp(name, attr_strings.write_time_attr) == 0) {
4994 if (determine_size) {
4995 p = talloc_asprintf(ctx, "%lu", write_time);
4996 if (!p) {
4997 errno = ENOMEM;
4998 return -1;
5000 n = strlen(p);
5001 } else {
5002 n = snprintf(buf, bufsize,
5003 "%lu", write_time);
5007 if (!determine_size && n > bufsize) {
5008 errno = ERANGE;
5009 return -1;
5011 buf += n;
5012 n_used += n;
5013 bufsize -= n;
5014 n = 0;
5017 if (! exclude_dos_change_time) {
5018 if (all || all_dos) {
5019 if (determine_size) {
5020 p = talloc_asprintf(ctx,
5021 ",%s:%lu",
5022 attr_strings.change_time_attr,
5023 change_time);
5024 if (!p) {
5025 errno = ENOMEM;
5026 return -1;
5028 n = strlen(p);
5029 } else {
5030 n = snprintf(buf, bufsize,
5031 ",%s:%lu",
5032 attr_strings.change_time_attr,
5033 change_time);
5035 } else if (StrCaseCmp(name, attr_strings.change_time_attr) == 0) {
5036 if (determine_size) {
5037 p = talloc_asprintf(ctx, "%lu", change_time);
5038 if (!p) {
5039 errno = ENOMEM;
5040 return -1;
5042 n = strlen(p);
5043 } else {
5044 n = snprintf(buf, bufsize,
5045 "%lu", change_time);
5049 if (!determine_size && n > bufsize) {
5050 errno = ERANGE;
5051 return -1;
5053 buf += n;
5054 n_used += n;
5055 bufsize -= n;
5056 n = 0;
5059 if (! exclude_dos_inode) {
5060 if (all || all_dos) {
5061 if (determine_size) {
5062 p = talloc_asprintf(
5063 ctx,
5064 ",INODE:%.0f",
5065 (double)ino);
5066 if (!p) {
5067 errno = ENOMEM;
5068 return -1;
5070 n = strlen(p);
5071 } else {
5072 n = snprintf(buf, bufsize,
5073 ",INODE:%.0f",
5074 (double) ino);
5076 } else if (StrCaseCmp(name, "inode") == 0) {
5077 if (determine_size) {
5078 p = talloc_asprintf(
5079 ctx,
5080 "%.0f",
5081 (double) ino);
5082 if (!p) {
5083 errno = ENOMEM;
5084 return -1;
5086 n = strlen(p);
5087 } else {
5088 n = snprintf(buf, bufsize,
5089 "%.0f",
5090 (double) ino);
5094 if (!determine_size && n > bufsize) {
5095 errno = ERANGE;
5096 return -1;
5098 buf += n;
5099 n_used += n;
5100 bufsize -= n;
5101 n = 0;
5104 /* Restore name pointer to its original value */
5105 name -= 16;
5108 if (n_used == 0) {
5109 errno = ENOATTR;
5110 return -1;
5113 return n_used;
5117 /*****************************************************
5118 set the ACLs on a file given an ascii description
5119 *******************************************************/
5120 static int
5121 cacl_set(TALLOC_CTX *ctx,
5122 struct cli_state *cli,
5123 struct cli_state *ipc_cli,
5124 POLICY_HND *pol,
5125 const char *filename,
5126 const char *the_acl,
5127 int mode,
5128 int flags)
5130 int fnum;
5131 int err = 0;
5132 SEC_DESC *sd = NULL, *old;
5133 SEC_ACL *dacl = NULL;
5134 DOM_SID *owner_sid = NULL;
5135 DOM_SID *grp_sid = NULL;
5136 uint32 i, j;
5137 size_t sd_size;
5138 int ret = 0;
5139 char *p;
5140 BOOL numeric = True;
5142 /* the_acl will be null for REMOVE_ALL operations */
5143 if (the_acl) {
5144 numeric = ((p = strchr(the_acl, ':')) != NULL &&
5145 p > the_acl &&
5146 p[-1] != '+');
5148 /* if this is to set the entire ACL... */
5149 if (*the_acl == '*') {
5150 /* ... then increment past the first colon */
5151 the_acl = p + 1;
5154 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
5155 CONST_DISCARD(char *, the_acl));
5157 if (!sd) {
5158 errno = EINVAL;
5159 return -1;
5163 /* SMBC_XATTR_MODE_REMOVE_ALL is the only caller
5164 that doesn't deref sd */
5166 if (!sd && (mode != SMBC_XATTR_MODE_REMOVE_ALL)) {
5167 errno = EINVAL;
5168 return -1;
5171 /* The desired access below is the only one I could find that works
5172 with NT4, W2KP and Samba */
5174 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
5176 if (fnum == -1) {
5177 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5178 filename, cli_errstr(cli)));
5179 errno = 0;
5180 return -1;
5183 old = cli_query_secdesc(cli, fnum, ctx);
5185 if (!old) {
5186 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
5187 errno = 0;
5188 return -1;
5191 cli_close(cli, fnum);
5193 switch (mode) {
5194 case SMBC_XATTR_MODE_REMOVE_ALL:
5195 old->dacl->num_aces = 0;
5196 dacl = old->dacl;
5197 break;
5199 case SMBC_XATTR_MODE_REMOVE:
5200 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5201 BOOL found = False;
5203 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
5204 if (sec_ace_equal(&sd->dacl->aces[i],
5205 &old->dacl->aces[j])) {
5206 uint32 k;
5207 for (k=j; k<old->dacl->num_aces-1;k++) {
5208 old->dacl->aces[k] =
5209 old->dacl->aces[k+1];
5211 old->dacl->num_aces--;
5212 found = True;
5213 dacl = old->dacl;
5214 break;
5218 if (!found) {
5219 err = ENOATTR;
5220 ret = -1;
5221 goto failed;
5224 break;
5226 case SMBC_XATTR_MODE_ADD:
5227 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5228 BOOL found = False;
5230 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
5231 if (sid_equal(&sd->dacl->aces[i].trustee,
5232 &old->dacl->aces[j].trustee)) {
5233 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
5234 err = EEXIST;
5235 ret = -1;
5236 goto failed;
5238 old->dacl->aces[j] = sd->dacl->aces[i];
5239 ret = -1;
5240 found = True;
5244 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
5245 err = ENOATTR;
5246 ret = -1;
5247 goto failed;
5250 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5251 add_ace(&old->dacl, &sd->dacl->aces[i], ctx);
5254 dacl = old->dacl;
5255 break;
5257 case SMBC_XATTR_MODE_SET:
5258 old = sd;
5259 owner_sid = old->owner_sid;
5260 grp_sid = old->group_sid;
5261 dacl = old->dacl;
5262 break;
5264 case SMBC_XATTR_MODE_CHOWN:
5265 owner_sid = sd->owner_sid;
5266 break;
5268 case SMBC_XATTR_MODE_CHGRP:
5269 grp_sid = sd->group_sid;
5270 break;
5273 /* Denied ACE entries must come before allowed ones */
5274 sort_acl(old->dacl);
5276 /* Create new security descriptor and set it */
5277 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
5278 owner_sid, grp_sid, NULL, dacl, &sd_size);
5280 fnum = cli_nt_create(cli, filename,
5281 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
5283 if (fnum == -1) {
5284 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5285 filename, cli_errstr(cli)));
5286 errno = 0;
5287 return -1;
5290 if (!cli_set_secdesc(cli, fnum, sd)) {
5291 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
5292 ret = -1;
5295 /* Clean up */
5297 failed:
5298 cli_close(cli, fnum);
5300 if (err != 0) {
5301 errno = err;
5304 return ret;
5308 static int
5309 smbc_setxattr_ctx(SMBCCTX *context,
5310 const char *fname,
5311 const char *name,
5312 const void *value,
5313 size_t size,
5314 int flags)
5316 int ret;
5317 int ret2;
5318 SMBCSRV *srv;
5319 SMBCSRV *ipc_srv;
5320 fstring server;
5321 fstring share;
5322 fstring user;
5323 fstring password;
5324 fstring workgroup;
5325 pstring path;
5326 TALLOC_CTX *ctx;
5327 POLICY_HND pol;
5328 DOS_ATTR_DESC *dad;
5329 struct {
5330 const char * create_time_attr;
5331 const char * access_time_attr;
5332 const char * write_time_attr;
5333 const char * change_time_attr;
5334 } attr_strings;
5336 if (!context || !context->internal ||
5337 !context->internal->_initialized) {
5339 errno = EINVAL; /* Best I can think of ... */
5340 return -1;
5344 if (!fname) {
5346 errno = EINVAL;
5347 return -1;
5351 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
5352 fname, name, (int) size, (const char*)value));
5354 if (smbc_parse_path(context, fname,
5355 workgroup, sizeof(workgroup),
5356 server, sizeof(server),
5357 share, sizeof(share),
5358 path, sizeof(path),
5359 user, sizeof(user),
5360 password, sizeof(password),
5361 NULL, 0)) {
5362 errno = EINVAL;
5363 return -1;
5366 if (user[0] == (char)0) fstrcpy(user, context->user);
5368 srv = smbc_server(context, True,
5369 server, share, workgroup, user, password);
5370 if (!srv) {
5371 return -1; /* errno set by smbc_server */
5374 if (! srv->no_nt_session) {
5375 ipc_srv = smbc_attr_server(context, server, share,
5376 workgroup, user, password,
5377 &pol);
5378 if (! ipc_srv) {
5379 srv->no_nt_session = True;
5381 } else {
5382 ipc_srv = NULL;
5385 ctx = talloc_init("smbc_setxattr");
5386 if (!ctx) {
5387 errno = ENOMEM;
5388 return -1;
5392 * Are they asking to set the entire set of known attributes?
5394 if (StrCaseCmp(name, "system.*") == 0 ||
5395 StrCaseCmp(name, "system.*+") == 0) {
5396 /* Yup. */
5397 char *namevalue =
5398 talloc_asprintf(ctx, "%s:%s",
5399 name+7, (const char *) value);
5400 if (! namevalue) {
5401 errno = ENOMEM;
5402 ret = -1;
5403 return -1;
5406 if (ipc_srv) {
5407 ret = cacl_set(ctx, srv->cli,
5408 ipc_srv->cli, &pol, path,
5409 namevalue,
5410 (*namevalue == '*'
5411 ? SMBC_XATTR_MODE_SET
5412 : SMBC_XATTR_MODE_ADD),
5413 flags);
5414 } else {
5415 ret = 0;
5418 /* get a DOS Attribute Descriptor with current attributes */
5419 dad = dos_attr_query(context, ctx, path, srv);
5420 if (dad) {
5421 /* Overwrite old with new, using what was provided */
5422 dos_attr_parse(context, dad, srv, namevalue);
5424 /* Set the new DOS attributes */
5425 if (! smbc_setatr(context, srv, path,
5426 dad->create_time,
5427 dad->access_time,
5428 dad->write_time,
5429 dad->change_time,
5430 dad->mode)) {
5432 /* cause failure if NT failed too */
5433 dad = NULL;
5437 /* we only fail if both NT and DOS sets failed */
5438 if (ret < 0 && ! dad) {
5439 ret = -1; /* in case dad was null */
5441 else {
5442 ret = 0;
5445 talloc_destroy(ctx);
5446 return ret;
5450 * Are they asking to set an access control element or to set
5451 * the entire access control list?
5453 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5454 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5455 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5456 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5457 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5459 /* Yup. */
5460 char *namevalue =
5461 talloc_asprintf(ctx, "%s:%s",
5462 name+19, (const char *) value);
5464 if (! ipc_srv) {
5465 ret = -1; /* errno set by smbc_server() */
5467 else if (! namevalue) {
5468 errno = ENOMEM;
5469 ret = -1;
5470 } else {
5471 ret = cacl_set(ctx, srv->cli,
5472 ipc_srv->cli, &pol, path,
5473 namevalue,
5474 (*namevalue == '*'
5475 ? SMBC_XATTR_MODE_SET
5476 : SMBC_XATTR_MODE_ADD),
5477 flags);
5479 talloc_destroy(ctx);
5480 return ret;
5484 * Are they asking to set the owner?
5486 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5487 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5489 /* Yup. */
5490 char *namevalue =
5491 talloc_asprintf(ctx, "%s:%s",
5492 name+19, (const char *) value);
5494 if (! ipc_srv) {
5496 ret = -1; /* errno set by smbc_server() */
5498 else if (! namevalue) {
5499 errno = ENOMEM;
5500 ret = -1;
5501 } else {
5502 ret = cacl_set(ctx, srv->cli,
5503 ipc_srv->cli, &pol, path,
5504 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5506 talloc_destroy(ctx);
5507 return ret;
5511 * Are they asking to set the group?
5513 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5514 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5516 /* Yup. */
5517 char *namevalue =
5518 talloc_asprintf(ctx, "%s:%s",
5519 name+19, (const char *) value);
5521 if (! ipc_srv) {
5522 /* errno set by smbc_server() */
5523 ret = -1;
5525 else if (! namevalue) {
5526 errno = ENOMEM;
5527 ret = -1;
5528 } else {
5529 ret = cacl_set(ctx, srv->cli,
5530 ipc_srv->cli, &pol, path,
5531 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5533 talloc_destroy(ctx);
5534 return ret;
5537 /* Determine whether to use old-style or new-style attribute names */
5538 if (context->internal->_full_time_names) {
5539 /* new-style names */
5540 attr_strings.create_time_attr = "system.dos_attr.CREATE_TIME";
5541 attr_strings.access_time_attr = "system.dos_attr.ACCESS_TIME";
5542 attr_strings.write_time_attr = "system.dos_attr.WRITE_TIME";
5543 attr_strings.change_time_attr = "system.dos_attr.CHANGE_TIME";
5544 } else {
5545 /* old-style names */
5546 attr_strings.create_time_attr = NULL;
5547 attr_strings.access_time_attr = "system.dos_attr.A_TIME";
5548 attr_strings.write_time_attr = "system.dos_attr.M_TIME";
5549 attr_strings.change_time_attr = "system.dos_attr.C_TIME";
5553 * Are they asking to set a DOS attribute?
5555 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5556 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5557 (attr_strings.create_time_attr != NULL &&
5558 StrCaseCmp(name, attr_strings.create_time_attr) == 0) ||
5559 StrCaseCmp(name, attr_strings.access_time_attr) == 0 ||
5560 StrCaseCmp(name, attr_strings.write_time_attr) == 0 ||
5561 StrCaseCmp(name, attr_strings.change_time_attr) == 0) {
5563 /* get a DOS Attribute Descriptor with current attributes */
5564 dad = dos_attr_query(context, ctx, path, srv);
5565 if (dad) {
5566 char *namevalue =
5567 talloc_asprintf(ctx, "%s:%s",
5568 name+16, (const char *) value);
5569 if (! namevalue) {
5570 errno = ENOMEM;
5571 ret = -1;
5572 } else {
5573 /* Overwrite old with provided new params */
5574 dos_attr_parse(context, dad, srv, namevalue);
5576 /* Set the new DOS attributes */
5577 ret2 = smbc_setatr(context, srv, path,
5578 dad->create_time,
5579 dad->access_time,
5580 dad->write_time,
5581 dad->change_time,
5582 dad->mode);
5584 /* ret2 has True (success) / False (failure) */
5585 if (ret2) {
5586 ret = 0;
5587 } else {
5588 ret = -1;
5591 } else {
5592 ret = -1;
5595 talloc_destroy(ctx);
5596 return ret;
5599 /* Unsupported attribute name */
5600 talloc_destroy(ctx);
5601 errno = EINVAL;
5602 return -1;
5605 static int
5606 smbc_getxattr_ctx(SMBCCTX *context,
5607 const char *fname,
5608 const char *name,
5609 const void *value,
5610 size_t size)
5612 int ret;
5613 SMBCSRV *srv;
5614 SMBCSRV *ipc_srv;
5615 fstring server;
5616 fstring share;
5617 fstring user;
5618 fstring password;
5619 fstring workgroup;
5620 pstring path;
5621 TALLOC_CTX *ctx;
5622 POLICY_HND pol;
5623 struct {
5624 const char * create_time_attr;
5625 const char * access_time_attr;
5626 const char * write_time_attr;
5627 const char * change_time_attr;
5628 } attr_strings;
5631 if (!context || !context->internal ||
5632 !context->internal->_initialized) {
5634 errno = EINVAL; /* Best I can think of ... */
5635 return -1;
5639 if (!fname) {
5641 errno = EINVAL;
5642 return -1;
5646 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5648 if (smbc_parse_path(context, fname,
5649 workgroup, sizeof(workgroup),
5650 server, sizeof(server),
5651 share, sizeof(share),
5652 path, sizeof(path),
5653 user, sizeof(user),
5654 password, sizeof(password),
5655 NULL, 0)) {
5656 errno = EINVAL;
5657 return -1;
5660 if (user[0] == (char)0) fstrcpy(user, context->user);
5662 srv = smbc_server(context, True,
5663 server, share, workgroup, user, password);
5664 if (!srv) {
5665 return -1; /* errno set by smbc_server */
5668 if (! srv->no_nt_session) {
5669 ipc_srv = smbc_attr_server(context, server, share,
5670 workgroup, user, password,
5671 &pol);
5672 if (! ipc_srv) {
5673 srv->no_nt_session = True;
5675 } else {
5676 ipc_srv = NULL;
5679 ctx = talloc_init("smbc:getxattr");
5680 if (!ctx) {
5681 errno = ENOMEM;
5682 return -1;
5685 /* Determine whether to use old-style or new-style attribute names */
5686 if (context->internal->_full_time_names) {
5687 /* new-style names */
5688 attr_strings.create_time_attr = "system.dos_attr.CREATE_TIME";
5689 attr_strings.access_time_attr = "system.dos_attr.ACCESS_TIME";
5690 attr_strings.write_time_attr = "system.dos_attr.WRITE_TIME";
5691 attr_strings.change_time_attr = "system.dos_attr.CHANGE_TIME";
5692 } else {
5693 /* old-style names */
5694 attr_strings.create_time_attr = NULL;
5695 attr_strings.access_time_attr = "system.dos_attr.A_TIME";
5696 attr_strings.write_time_attr = "system.dos_attr.M_TIME";
5697 attr_strings.change_time_attr = "system.dos_attr.C_TIME";
5700 /* Are they requesting a supported attribute? */
5701 if (StrCaseCmp(name, "system.*") == 0 ||
5702 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5703 StrCaseCmp(name, "system.*+") == 0 ||
5704 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5705 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5706 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5707 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5708 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5709 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5710 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5711 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5712 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5713 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5714 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5715 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5716 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5717 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5718 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5719 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5720 (attr_strings.create_time_attr != NULL &&
5721 StrCaseCmp(name, attr_strings.create_time_attr) == 0) ||
5722 StrCaseCmp(name, attr_strings.access_time_attr) == 0 ||
5723 StrCaseCmp(name, attr_strings.write_time_attr) == 0 ||
5724 StrCaseCmp(name, attr_strings.change_time_attr) == 0 ||
5725 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5727 /* Yup. */
5728 ret = cacl_get(context, ctx, srv,
5729 ipc_srv == NULL ? NULL : ipc_srv->cli,
5730 &pol, path,
5731 CONST_DISCARD(char *, name),
5732 CONST_DISCARD(char *, value), size);
5733 if (ret < 0 && errno == 0) {
5734 errno = smbc_errno(context, srv->cli);
5736 talloc_destroy(ctx);
5737 return ret;
5740 /* Unsupported attribute name */
5741 talloc_destroy(ctx);
5742 errno = EINVAL;
5743 return -1;
5747 static int
5748 smbc_removexattr_ctx(SMBCCTX *context,
5749 const char *fname,
5750 const char *name)
5752 int ret;
5753 SMBCSRV *srv;
5754 SMBCSRV *ipc_srv;
5755 fstring server;
5756 fstring share;
5757 fstring user;
5758 fstring password;
5759 fstring workgroup;
5760 pstring path;
5761 TALLOC_CTX *ctx;
5762 POLICY_HND pol;
5764 if (!context || !context->internal ||
5765 !context->internal->_initialized) {
5767 errno = EINVAL; /* Best I can think of ... */
5768 return -1;
5772 if (!fname) {
5774 errno = EINVAL;
5775 return -1;
5779 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5781 if (smbc_parse_path(context, fname,
5782 workgroup, sizeof(workgroup),
5783 server, sizeof(server),
5784 share, sizeof(share),
5785 path, sizeof(path),
5786 user, sizeof(user),
5787 password, sizeof(password),
5788 NULL, 0)) {
5789 errno = EINVAL;
5790 return -1;
5793 if (user[0] == (char)0) fstrcpy(user, context->user);
5795 srv = smbc_server(context, True,
5796 server, share, workgroup, user, password);
5797 if (!srv) {
5798 return -1; /* errno set by smbc_server */
5801 if (! srv->no_nt_session) {
5802 ipc_srv = smbc_attr_server(context, server, share,
5803 workgroup, user, password,
5804 &pol);
5805 if (! ipc_srv) {
5806 srv->no_nt_session = True;
5808 } else {
5809 ipc_srv = NULL;
5812 if (! ipc_srv) {
5813 return -1; /* errno set by smbc_attr_server */
5816 ctx = talloc_init("smbc_removexattr");
5817 if (!ctx) {
5818 errno = ENOMEM;
5819 return -1;
5822 /* Are they asking to set the entire ACL? */
5823 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5824 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5826 /* Yup. */
5827 ret = cacl_set(ctx, srv->cli,
5828 ipc_srv->cli, &pol, path,
5829 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5830 talloc_destroy(ctx);
5831 return ret;
5835 * Are they asking to remove one or more spceific security descriptor
5836 * attributes?
5838 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5839 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5840 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5841 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5842 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5843 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5844 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5846 /* Yup. */
5847 ret = cacl_set(ctx, srv->cli,
5848 ipc_srv->cli, &pol, path,
5849 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5850 talloc_destroy(ctx);
5851 return ret;
5854 /* Unsupported attribute name */
5855 talloc_destroy(ctx);
5856 errno = EINVAL;
5857 return -1;
5860 static int
5861 smbc_listxattr_ctx(SMBCCTX *context,
5862 const char *fname,
5863 char *list,
5864 size_t size)
5867 * This isn't quite what listxattr() is supposed to do. This returns
5868 * the complete set of attribute names, always, rather than only those
5869 * attribute names which actually exist for a file. Hmmm...
5871 const char supported_old[] =
5872 "system.*\0"
5873 "system.*+\0"
5874 "system.nt_sec_desc.revision\0"
5875 "system.nt_sec_desc.owner\0"
5876 "system.nt_sec_desc.owner+\0"
5877 "system.nt_sec_desc.group\0"
5878 "system.nt_sec_desc.group+\0"
5879 "system.nt_sec_desc.acl.*\0"
5880 "system.nt_sec_desc.acl\0"
5881 "system.nt_sec_desc.acl+\0"
5882 "system.nt_sec_desc.*\0"
5883 "system.nt_sec_desc.*+\0"
5884 "system.dos_attr.*\0"
5885 "system.dos_attr.mode\0"
5886 "system.dos_attr.c_time\0"
5887 "system.dos_attr.a_time\0"
5888 "system.dos_attr.m_time\0"
5890 const char supported_new[] =
5891 "system.*\0"
5892 "system.*+\0"
5893 "system.nt_sec_desc.revision\0"
5894 "system.nt_sec_desc.owner\0"
5895 "system.nt_sec_desc.owner+\0"
5896 "system.nt_sec_desc.group\0"
5897 "system.nt_sec_desc.group+\0"
5898 "system.nt_sec_desc.acl.*\0"
5899 "system.nt_sec_desc.acl\0"
5900 "system.nt_sec_desc.acl+\0"
5901 "system.nt_sec_desc.*\0"
5902 "system.nt_sec_desc.*+\0"
5903 "system.dos_attr.*\0"
5904 "system.dos_attr.mode\0"
5905 "system.dos_attr.create_time\0"
5906 "system.dos_attr.access_time\0"
5907 "system.dos_attr.write_time\0"
5908 "system.dos_attr.change_time\0"
5910 const char * supported;
5912 if (context->internal->_full_time_names) {
5913 supported = supported_new;
5914 } else {
5915 supported = supported_old;
5918 if (size == 0) {
5919 return sizeof(supported);
5922 if (sizeof(supported) > size) {
5923 errno = ERANGE;
5924 return -1;
5927 /* this can't be strcpy() because there are embedded null characters */
5928 memcpy(list, supported, sizeof(supported));
5929 return sizeof(supported);
5934 * Open a print file to be written to by other calls
5937 static SMBCFILE *
5938 smbc_open_print_job_ctx(SMBCCTX *context,
5939 const char *fname)
5941 fstring server;
5942 fstring share;
5943 fstring user;
5944 fstring password;
5945 pstring path;
5947 if (!context || !context->internal ||
5948 !context->internal->_initialized) {
5950 errno = EINVAL;
5951 return NULL;
5955 if (!fname) {
5957 errno = EINVAL;
5958 return NULL;
5962 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5964 if (smbc_parse_path(context, fname,
5965 NULL, 0,
5966 server, sizeof(server),
5967 share, sizeof(share),
5968 path, sizeof(path),
5969 user, sizeof(user),
5970 password, sizeof(password),
5971 NULL, 0)) {
5972 errno = EINVAL;
5973 return NULL;
5976 /* What if the path is empty, or the file exists? */
5978 return (context->open)(context, fname, O_WRONLY, 666);
5983 * Routine to print a file on a remote server ...
5985 * We open the file, which we assume to be on a remote server, and then
5986 * copy it to a print file on the share specified by printq.
5989 static int
5990 smbc_print_file_ctx(SMBCCTX *c_file,
5991 const char *fname,
5992 SMBCCTX *c_print,
5993 const char *printq)
5995 SMBCFILE *fid1;
5996 SMBCFILE *fid2;
5997 int bytes;
5998 int saverr;
5999 int tot_bytes = 0;
6000 char buf[4096];
6002 if (!c_file || !c_file->internal->_initialized || !c_print ||
6003 !c_print->internal->_initialized) {
6005 errno = EINVAL;
6006 return -1;
6010 if (!fname && !printq) {
6012 errno = EINVAL;
6013 return -1;
6017 /* Try to open the file for reading ... */
6019 if ((long)(fid1 = (c_file->open)(c_file, fname, O_RDONLY, 0666)) < 0) {
6021 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
6022 return -1; /* smbc_open sets errno */
6026 /* Now, try to open the printer file for writing */
6028 if ((long)(fid2 = (c_print->open_print_job)(c_print, printq)) < 0) {
6030 saverr = errno; /* Save errno */
6031 (c_file->close_fn)(c_file, fid1);
6032 errno = saverr;
6033 return -1;
6037 while ((bytes = (c_file->read)(c_file, fid1, buf, sizeof(buf))) > 0) {
6039 tot_bytes += bytes;
6041 if (((c_print->write)(c_print, fid2, buf, bytes)) < 0) {
6043 saverr = errno;
6044 (c_file->close_fn)(c_file, fid1);
6045 (c_print->close_fn)(c_print, fid2);
6046 errno = saverr;
6052 saverr = errno;
6054 (c_file->close_fn)(c_file, fid1); /* We have to close these anyway */
6055 (c_print->close_fn)(c_print, fid2);
6057 if (bytes < 0) {
6059 errno = saverr;
6060 return -1;
6064 return tot_bytes;
6069 * Routine to list print jobs on a printer share ...
6072 static int
6073 smbc_list_print_jobs_ctx(SMBCCTX *context,
6074 const char *fname,
6075 smbc_list_print_job_fn fn)
6077 SMBCSRV *srv;
6078 fstring server;
6079 fstring share;
6080 fstring user;
6081 fstring password;
6082 fstring workgroup;
6083 pstring path;
6085 if (!context || !context->internal ||
6086 !context->internal->_initialized) {
6088 errno = EINVAL;
6089 return -1;
6093 if (!fname) {
6095 errno = EINVAL;
6096 return -1;
6100 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
6102 if (smbc_parse_path(context, fname,
6103 workgroup, sizeof(workgroup),
6104 server, sizeof(server),
6105 share, sizeof(share),
6106 path, sizeof(path),
6107 user, sizeof(user),
6108 password, sizeof(password),
6109 NULL, 0)) {
6110 errno = EINVAL;
6111 return -1;
6114 if (user[0] == (char)0) fstrcpy(user, context->user);
6116 srv = smbc_server(context, True,
6117 server, share, workgroup, user, password);
6119 if (!srv) {
6121 return -1; /* errno set by smbc_server */
6125 if (cli_print_queue(srv->cli,
6126 (void (*)(struct print_job_info *))fn) < 0) {
6128 errno = smbc_errno(context, srv->cli);
6129 return -1;
6133 return 0;
6138 * Delete a print job from a remote printer share
6141 static int
6142 smbc_unlink_print_job_ctx(SMBCCTX *context,
6143 const char *fname,
6144 int id)
6146 SMBCSRV *srv;
6147 fstring server;
6148 fstring share;
6149 fstring user;
6150 fstring password;
6151 fstring workgroup;
6152 pstring path;
6153 int err;
6155 if (!context || !context->internal ||
6156 !context->internal->_initialized) {
6158 errno = EINVAL;
6159 return -1;
6163 if (!fname) {
6165 errno = EINVAL;
6166 return -1;
6170 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
6172 if (smbc_parse_path(context, fname,
6173 workgroup, sizeof(workgroup),
6174 server, sizeof(server),
6175 share, sizeof(share),
6176 path, sizeof(path),
6177 user, sizeof(user),
6178 password, sizeof(password),
6179 NULL, 0)) {
6180 errno = EINVAL;
6181 return -1;
6184 if (user[0] == (char)0) fstrcpy(user, context->user);
6186 srv = smbc_server(context, True,
6187 server, share, workgroup, user, password);
6189 if (!srv) {
6191 return -1; /* errno set by smbc_server */
6195 if ((err = cli_printjob_del(srv->cli, id)) != 0) {
6197 if (err < 0)
6198 errno = smbc_errno(context, srv->cli);
6199 else if (err == ERRnosuchprintjob)
6200 errno = EINVAL;
6201 return -1;
6205 return 0;
6210 * Get a new empty handle to fill in with your own info
6212 SMBCCTX *
6213 smbc_new_context(void)
6215 SMBCCTX *context;
6217 context = SMB_MALLOC_P(SMBCCTX);
6218 if (!context) {
6219 errno = ENOMEM;
6220 return NULL;
6223 ZERO_STRUCTP(context);
6225 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
6226 if (!context->internal) {
6227 SAFE_FREE(context);
6228 errno = ENOMEM;
6229 return NULL;
6232 ZERO_STRUCTP(context->internal);
6235 /* ADD REASONABLE DEFAULTS */
6236 context->debug = 0;
6237 context->timeout = 20000; /* 20 seconds */
6239 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
6240 context->options.urlencode_readdir_entries = False;/* backward compat */
6241 context->options.one_share_per_server = False;/* backward compat */
6242 context->internal->_share_mode = SMBC_SHAREMODE_DENY_NONE;
6243 /* backward compat */
6245 context->open = smbc_open_ctx;
6246 context->creat = smbc_creat_ctx;
6247 context->read = smbc_read_ctx;
6248 context->write = smbc_write_ctx;
6249 context->close_fn = smbc_close_ctx;
6250 context->unlink = smbc_unlink_ctx;
6251 context->rename = smbc_rename_ctx;
6252 context->lseek = smbc_lseek_ctx;
6253 context->stat = smbc_stat_ctx;
6254 context->fstat = smbc_fstat_ctx;
6255 context->opendir = smbc_opendir_ctx;
6256 context->closedir = smbc_closedir_ctx;
6257 context->readdir = smbc_readdir_ctx;
6258 context->getdents = smbc_getdents_ctx;
6259 context->mkdir = smbc_mkdir_ctx;
6260 context->rmdir = smbc_rmdir_ctx;
6261 context->telldir = smbc_telldir_ctx;
6262 context->lseekdir = smbc_lseekdir_ctx;
6263 context->fstatdir = smbc_fstatdir_ctx;
6264 context->chmod = smbc_chmod_ctx;
6265 context->utimes = smbc_utimes_ctx;
6266 context->setxattr = smbc_setxattr_ctx;
6267 context->getxattr = smbc_getxattr_ctx;
6268 context->removexattr = smbc_removexattr_ctx;
6269 context->listxattr = smbc_listxattr_ctx;
6270 context->open_print_job = smbc_open_print_job_ctx;
6271 context->print_file = smbc_print_file_ctx;
6272 context->list_print_jobs = smbc_list_print_jobs_ctx;
6273 context->unlink_print_job = smbc_unlink_print_job_ctx;
6275 context->callbacks.check_server_fn = smbc_check_server;
6276 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
6278 smbc_default_cache_functions(context);
6280 return context;
6284 * Free a context
6286 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
6287 * and thus you'll be leaking memory if not handled properly.
6291 smbc_free_context(SMBCCTX *context,
6292 int shutdown_ctx)
6294 if (!context) {
6295 errno = EBADF;
6296 return 1;
6299 if (shutdown_ctx) {
6300 SMBCFILE * f;
6301 DEBUG(1,("Performing aggressive shutdown.\n"));
6303 f = context->internal->_files;
6304 while (f) {
6305 (context->close_fn)(context, f);
6306 f = f->next;
6308 context->internal->_files = NULL;
6310 /* First try to remove the servers the nice way. */
6311 if (context->callbacks.purge_cached_fn(context)) {
6312 SMBCSRV * s;
6313 SMBCSRV * next;
6314 DEBUG(1, ("Could not purge all servers, "
6315 "Nice way shutdown failed.\n"));
6316 s = context->internal->_servers;
6317 while (s) {
6318 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
6319 s, s->cli->fd));
6320 cli_shutdown(s->cli);
6321 (context->callbacks.remove_cached_srv_fn)(context,
6323 next = s->next;
6324 DLIST_REMOVE(context->internal->_servers, s);
6325 SAFE_FREE(s);
6326 s = next;
6328 context->internal->_servers = NULL;
6331 else {
6332 /* This is the polite way */
6333 if ((context->callbacks.purge_cached_fn)(context)) {
6334 DEBUG(1, ("Could not purge all servers, "
6335 "free_context failed.\n"));
6336 errno = EBUSY;
6337 return 1;
6339 if (context->internal->_servers) {
6340 DEBUG(1, ("Active servers in context, "
6341 "free_context failed.\n"));
6342 errno = EBUSY;
6343 return 1;
6345 if (context->internal->_files) {
6346 DEBUG(1, ("Active files in context, "
6347 "free_context failed.\n"));
6348 errno = EBUSY;
6349 return 1;
6353 /* Things we have to clean up */
6354 SAFE_FREE(context->workgroup);
6355 SAFE_FREE(context->netbios_name);
6356 SAFE_FREE(context->user);
6358 DEBUG(3, ("Context %p succesfully freed\n", context));
6359 SAFE_FREE(context->internal);
6360 SAFE_FREE(context);
6361 return 0;
6366 * Each time the context structure is changed, we have binary backward
6367 * compatibility issues. Instead of modifying the public portions of the
6368 * context structure to add new options, instead, we put them in the internal
6369 * portion of the context structure and provide a set function for these new
6370 * options.
6372 void
6373 smbc_option_set(SMBCCTX *context,
6374 char *option_name,
6375 ... /* option_value */)
6377 va_list ap;
6378 union {
6379 int i;
6380 BOOL b;
6381 smbc_get_auth_data_with_context_fn auth_fn;
6382 void *v;
6383 } option_value;
6385 va_start(ap, option_name);
6387 if (strcmp(option_name, "debug_to_stderr") == 0) {
6389 * Log to standard error instead of standard output.
6391 option_value.b = (BOOL) va_arg(ap, int);
6392 context->internal->_debug_stderr = option_value.b;
6394 } else if (strcmp(option_name, "full_time_names") == 0) {
6396 * Use new-style time attribute names, e.g. WRITE_TIME rather
6397 * than the old-style names such as M_TIME. This allows also
6398 * setting/getting CREATE_TIME which was previously
6399 * unimplemented. (Note that the old C_TIME was supposed to
6400 * be CHANGE_TIME but was confused and sometimes referred to
6401 * CREATE_TIME.)
6403 option_value.b = (BOOL) va_arg(ap, int);
6404 context->internal->_full_time_names = option_value.b;
6406 } else if (strcmp(option_name, "open_share_mode") == 0) {
6408 * The share mode to use for files opened with
6409 * smbc_open_ctx(). The default is SMBC_SHAREMODE_DENY_NONE.
6411 option_value.i = va_arg(ap, int);
6412 context->internal->_share_mode =
6413 (smbc_share_mode) option_value.i;
6415 } else if (strcmp(option_name, "auth_function") == 0) {
6417 * Use the new-style authentication function which includes
6418 * the context.
6420 option_value.auth_fn =
6421 va_arg(ap, smbc_get_auth_data_with_context_fn);
6422 context->internal->_auth_fn_with_context =
6423 option_value.auth_fn;
6424 } else if (strcmp(option_name, "user_data") == 0) {
6426 * Save a user data handle which may be retrieved by the user
6427 * with smbc_option_get()
6429 option_value.v = va_arg(ap, void *);
6430 context->internal->_user_data = option_value.v;
6433 va_end(ap);
6438 * Retrieve the current value of an option
6440 void *
6441 smbc_option_get(SMBCCTX *context,
6442 char *option_name)
6444 if (strcmp(option_name, "debug_stderr") == 0) {
6446 * Log to standard error instead of standard output.
6448 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6449 return (void *) (intptr_t) context->internal->_debug_stderr;
6450 #else
6451 return (void *) context->internal->_debug_stderr;
6452 #endif
6453 } else if (strcmp(option_name, "full_time_names") == 0) {
6455 * Use new-style time attribute names, e.g. WRITE_TIME rather
6456 * than the old-style names such as M_TIME. This allows also
6457 * setting/getting CREATE_TIME which was previously
6458 * unimplemented. (Note that the old C_TIME was supposed to
6459 * be CHANGE_TIME but was confused and sometimes referred to
6460 * CREATE_TIME.)
6462 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6463 return (void *) (intptr_t) context->internal->_full_time_names;
6464 #else
6465 return (void *) context->internal->_full_time_names;
6466 #endif
6468 } else if (strcmp(option_name, "auth_function") == 0) {
6470 * Use the new-style authentication function which includes
6471 * the context.
6473 return (void *) context->internal->_auth_fn_with_context;
6474 } else if (strcmp(option_name, "user_data") == 0) {
6476 * Save a user data handle which may be retrieved by the user
6477 * with smbc_option_get()
6479 return context->internal->_user_data;
6482 return NULL;
6487 * Initialise the library etc
6489 * We accept a struct containing handle information.
6490 * valid values for info->debug from 0 to 100,
6491 * and insist that info->fn must be non-null.
6493 SMBCCTX *
6494 smbc_init_context(SMBCCTX *context)
6496 pstring conf;
6497 int pid;
6498 char *user = NULL;
6499 char *home = NULL;
6501 if (!context || !context->internal) {
6502 errno = EBADF;
6503 return NULL;
6506 /* Do not initialise the same client twice */
6507 if (context->internal->_initialized) {
6508 return 0;
6511 if ((!context->callbacks.auth_fn &&
6512 !context->internal->_auth_fn_with_context) ||
6513 context->debug < 0 ||
6514 context->debug > 100) {
6516 errno = EINVAL;
6517 return NULL;
6521 if (!smbc_initialized) {
6523 * Do some library-wide intializations the first time we get
6524 * called
6526 BOOL conf_loaded = False;
6528 /* Set this to what the user wants */
6529 DEBUGLEVEL = context->debug;
6531 load_case_tables();
6533 setup_logging("libsmbclient", True);
6534 if (context->internal->_debug_stderr) {
6535 dbf = x_stderr;
6536 x_setbuf(x_stderr, NULL);
6539 /* Here we would open the smb.conf file if needed ... */
6541 in_client = True; /* FIXME, make a param */
6543 home = getenv("HOME");
6544 if (home) {
6545 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
6546 if (lp_load(conf, True, False, False, True)) {
6547 conf_loaded = True;
6548 } else {
6549 DEBUG(5, ("Could not load config file: %s\n",
6550 conf));
6554 if (!conf_loaded) {
6556 * Well, if that failed, try the dyn_CONFIGFILE
6557 * Which points to the standard locn, and if that
6558 * fails, silently ignore it and use the internal
6559 * defaults ...
6562 if (!lp_load(dyn_CONFIGFILE, True, False, False, False)) {
6563 DEBUG(5, ("Could not load config file: %s\n",
6564 dyn_CONFIGFILE));
6565 } else if (home) {
6567 * We loaded the global config file. Now lets
6568 * load user-specific modifications to the
6569 * global config.
6571 slprintf(conf, sizeof(conf),
6572 "%s/.smb/smb.conf.append", home);
6573 if (!lp_load(conf, True, False, False, False)) {
6574 DEBUG(10,
6575 ("Could not append config file: "
6576 "%s\n",
6577 conf));
6582 load_interfaces(); /* Load the list of interfaces ... */
6584 reopen_logs(); /* Get logging working ... */
6587 * Block SIGPIPE (from lib/util_sock.c: write())
6588 * It is not needed and should not stop execution
6590 BlockSignals(True, SIGPIPE);
6592 /* Done with one-time initialisation */
6593 smbc_initialized = 1;
6597 if (!context->user) {
6599 * FIXME: Is this the best way to get the user info?
6601 user = getenv("USER");
6602 /* walk around as "guest" if no username can be found */
6603 if (!user) context->user = SMB_STRDUP("guest");
6604 else context->user = SMB_STRDUP(user);
6607 if (!context->netbios_name) {
6609 * We try to get our netbios name from the config. If that
6610 * fails we fall back on constructing our netbios name from
6611 * our hostname etc
6613 if (global_myname()) {
6614 context->netbios_name = SMB_STRDUP(global_myname());
6616 else {
6618 * Hmmm, I want to get hostname as well, but I am too
6619 * lazy for the moment
6621 pid = sys_getpid();
6622 context->netbios_name = (char *)SMB_MALLOC(17);
6623 if (!context->netbios_name) {
6624 errno = ENOMEM;
6625 return NULL;
6627 slprintf(context->netbios_name, 16,
6628 "smbc%s%d", context->user, pid);
6632 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
6634 if (!context->workgroup) {
6635 if (lp_workgroup()) {
6636 context->workgroup = SMB_STRDUP(lp_workgroup());
6638 else {
6639 /* TODO: Think about a decent default workgroup */
6640 context->workgroup = SMB_STRDUP("samba");
6644 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
6646 /* shortest timeout is 1 second */
6647 if (context->timeout > 0 && context->timeout < 1000)
6648 context->timeout = 1000;
6651 * FIXME: Should we check the function pointers here?
6654 context->internal->_initialized = True;
6656 return context;
6660 /* Return the verion of samba, and thus libsmbclient */
6661 const char *
6662 smbc_version(void)
6664 return samba_version_string();