r11508: Removed incorrect patch hunk. Thanks to Andrew
[Samba.git] / source / libsmb / libsmbclient.c
blobf180072a70cf42e099aee90041ff47715c39550c
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 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 #include "includes.h"
27 #include "include/libsmb_internal.h"
31 * DOS Attribute values (used internally)
33 typedef struct DOS_ATTR_DESC {
34 int mode;
35 SMB_OFF_T size;
36 time_t a_time;
37 time_t c_time;
38 time_t m_time;
39 SMB_INO_T inode;
40 } DOS_ATTR_DESC;
44 * Internal flags for extended attributes
47 /* internal mode values */
48 #define SMBC_XATTR_MODE_ADD 1
49 #define SMBC_XATTR_MODE_REMOVE 2
50 #define SMBC_XATTR_MODE_REMOVE_ALL 3
51 #define SMBC_XATTR_MODE_SET 4
52 #define SMBC_XATTR_MODE_CHOWN 5
53 #define SMBC_XATTR_MODE_CHGRP 6
55 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
57 /*We should test for this in configure ... */
58 #ifndef ENOTSUP
59 #define ENOTSUP EOPNOTSUPP
60 #endif
63 * Functions exported by libsmb_cache.c that we need here
65 int smbc_default_cache_functions(SMBCCTX *context);
67 /*
68 * check if an element is part of the list.
69 * FIXME: Does not belong here !
70 * Can anyone put this in a macro in dlinklist.h ?
71 * -- Tom
73 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
74 if (!p || !list) return False;
75 do {
76 if (p == list) return True;
77 list = list->next;
78 } while (list);
79 return False;
83 * Find an lsa pipe handle associated with a cli struct.
86 static struct rpc_pipe_client *find_lsa_pipe_hnd(struct cli_state *ipc_cli)
88 struct rpc_pipe_client *pipe_hnd;
90 for (pipe_hnd = ipc_cli->pipe_list; pipe_hnd; pipe_hnd = pipe_hnd->next) {
91 if (pipe_hnd->pipe_idx == PI_LSARPC) {
92 return pipe_hnd;
96 return NULL;
99 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file);
100 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence);
102 extern BOOL in_client;
105 * Is the logging working / configfile read ?
107 static int smbc_initialized = 0;
109 static int
110 hex2int( unsigned int _char )
112 if ( _char >= 'A' && _char <='F')
113 return _char - 'A' + 10;
114 if ( _char >= 'a' && _char <='f')
115 return _char - 'a' + 10;
116 if ( _char >= '0' && _char <='9')
117 return _char - '0';
118 return -1;
122 * smbc_urldecode()
124 * Convert strings of %xx to their single character equivalent. Each 'x' must
125 * be a valid hexadecimal digit, or that % sequence is left undecoded.
127 * dest may, but need not be, the same pointer as src.
129 * Returns the number of % sequences which could not be converted due to lack
130 * of two following hexadecimal digits.
133 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
135 int old_length = strlen(src);
136 int i = 0;
137 int err_count = 0;
138 pstring temp;
139 char * p;
141 if ( old_length == 0 ) {
142 return 0;
145 p = temp;
146 while ( i < old_length ) {
147 unsigned char character = src[ i++ ];
149 if (character == '%') {
150 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
151 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
153 /* Replace valid sequence */
154 if (a != -1 && b != -1) {
156 /* Replace valid %xx sequence with %dd */
157 character = (a * 16) + b;
159 if (character == '\0') {
160 break; /* Stop at %00 */
163 i += 2;
164 } else {
166 err_count++;
170 *p++ = character;
173 *p = '\0';
175 strncpy(dest, temp, max_dest_len);
177 return err_count;
181 * smbc_urlencode()
183 * Convert any characters not specifically allowed in a URL into their %xx
184 * equivalent.
186 * Returns the remaining buffer length.
189 smbc_urlencode(char * dest, char * src, int max_dest_len)
191 char hex[] = "0123456789ABCDEF";
193 for (; *src != '\0' && max_dest_len >= 3; src++) {
195 if ((*src < '0' &&
196 *src != '-' &&
197 *src != '.') ||
198 (*src > '9' &&
199 *src < 'A') ||
200 (*src > 'Z' &&
201 *src < 'a' &&
202 *src != '_') ||
203 (*src > 'z')) {
204 *dest++ = '%';
205 *dest++ = hex[(*src >> 4) & 0x0f];
206 *dest++ = hex[*src & 0x0f];
207 max_dest_len -= 3;
208 } else {
209 *dest++ = *src;
210 max_dest_len--;
214 *dest++ = '\0';
215 max_dest_len--;
217 return max_dest_len;
221 * Function to parse a path and turn it into components
223 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
224 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
225 * general format ("smb:" only; we do not look for "cifs:").
228 * We accept:
229 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
231 * Meaning of URLs:
233 * smb:// Show all workgroups.
235 * The method of locating the list of workgroups varies
236 * depending upon the setting of the context variable
237 * context->options.browse_max_lmb_count. This value
238 * determine the maximum number of local master browsers to
239 * query for the list of workgroups. In order to ensure that
240 * a complete list of workgroups is obtained, all master
241 * browsers must be queried, but if there are many
242 * workgroups, the time spent querying can begin to add up.
243 * For small networks (not many workgroups), it is suggested
244 * that this variable be set to 0, indicating query all local
245 * master browsers. When the network has many workgroups, a
246 * reasonable setting for this variable might be around 3.
248 * smb://name/ if name<1D> or name<1B> exists, list servers in
249 * workgroup, else, if name<20> exists, list all shares
250 * for server ...
252 * If "options" are provided, this function returns the entire option list as a
253 * string, for later parsing by the caller. Note that currently, no options
254 * are supported.
257 static const char *smbc_prefix = "smb:";
259 static int
260 smbc_parse_path(SMBCCTX *context,
261 const char *fname,
262 char *server, int server_len,
263 char *share, int share_len,
264 char *path, int path_len,
265 char *user, int user_len,
266 char *password, int password_len,
267 char *options, int options_len)
269 static pstring s;
270 pstring userinfo;
271 const char *p;
272 char *q, *r;
273 int len;
275 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
276 if (options != NULL && options_len > 0) {
277 options[0] = (char)0;
279 pstrcpy(s, fname);
281 /* see if it has the right prefix */
282 len = strlen(smbc_prefix);
283 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
284 return -1; /* What about no smb: ? */
287 p = s + len;
289 /* Watch the test below, we are testing to see if we should exit */
291 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
293 DEBUG(1, ("Invalid path (does not begin with smb://"));
294 return -1;
298 p += 2; /* Skip the double slash */
300 /* See if any options were specified */
301 if ((q = strrchr(p, '?')) != NULL ) {
302 /* There are options. Null terminate here and point to them */
303 *q++ = '\0';
305 DEBUG(4, ("Found options '%s'", q));
307 /* Copy the options */
308 if (options != NULL && options_len > 0) {
309 safe_strcpy(options, q, options_len - 1);
313 if (*p == (char)0)
314 goto decoding;
316 if (*p == '/') {
318 strncpy(server, context->workgroup,
319 (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
320 return 0;
325 * ok, its for us. Now parse out the server, share etc.
327 * However, we want to parse out [[domain;]user[:password]@] if it
328 * exists ...
331 /* check that '@' occurs before '/', if '/' exists at all */
332 q = strchr_m(p, '@');
333 r = strchr_m(p, '/');
334 if (q && (!r || q < r)) {
335 pstring username, passwd, domain;
336 const char *u = userinfo;
338 next_token(&p, userinfo, "@", sizeof(fstring));
340 username[0] = passwd[0] = domain[0] = 0;
342 if (strchr_m(u, ';')) {
344 next_token(&u, domain, ";", sizeof(fstring));
348 if (strchr_m(u, ':')) {
350 next_token(&u, username, ":", sizeof(fstring));
352 pstrcpy(passwd, u);
355 else {
357 pstrcpy(username, u);
361 if (username[0])
362 strncpy(user, username, user_len); /* FIXME, domain */
364 if (passwd[0])
365 strncpy(password, passwd, password_len);
369 if (!next_token(&p, server, "/", sizeof(fstring))) {
371 return -1;
375 if (*p == (char)0) goto decoding; /* That's it ... */
377 if (!next_token(&p, share, "/", sizeof(fstring))) {
379 return -1;
383 safe_strcpy(path, p, path_len - 1);
385 all_string_sub(path, "/", "\\", 0);
387 decoding:
388 (void) smbc_urldecode(path, path, path_len);
389 (void) smbc_urldecode(server, server, server_len);
390 (void) smbc_urldecode(share, share, share_len);
391 (void) smbc_urldecode(user, user, user_len);
392 (void) smbc_urldecode(password, password, password_len);
394 return 0;
398 * Verify that the options specified in a URL are valid
400 static int smbc_check_options(char *server, char *share, char *path, char *options)
402 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' path='%s' options='%s'\n", server, share, path, options));
404 /* No options at all is always ok */
405 if (! *options) return 0;
407 /* Currently, we don't support any options. */
408 return -1;
412 * Convert an SMB error into a UNIX error ...
414 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
416 int ret = cli_errno(c);
418 if (cli_is_dos_error(c)) {
419 uint8 eclass;
420 uint32 ecode;
422 cli_dos_error(c, &eclass, &ecode);
424 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
425 (int)eclass, (int)ecode, (int)ecode, ret));
426 } else {
427 NTSTATUS status;
429 status = cli_nt_error(c);
431 DEBUG(3,("smbc errno %s -> %d\n",
432 nt_errstr(status), ret));
435 return ret;
439 * Check a server for being alive and well.
440 * returns 0 if the server is in shape. Returns 1 on error
442 * Also useable outside libsmbclient to enable external cache
443 * to do some checks too.
445 int smbc_check_server(SMBCCTX * context, SMBCSRV * server)
447 if ( send_keepalive(server->cli.fd) == False )
448 return 1;
450 /* connection is ok */
451 return 0;
455 * Remove a server from the cached server list it's unused.
456 * On success, 0 is returned. 1 is returned if the server could not be removed.
458 * Also useable outside libsmbclient
460 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
462 SMBCFILE * file;
464 /* are we being fooled ? */
465 if (!context || !context->internal ||
466 !context->internal->_initialized || !srv) return 1;
469 /* Check all open files/directories for a relation with this server */
470 for (file = context->internal->_files; file; file=file->next) {
471 if (file->srv == srv) {
472 /* Still used */
473 DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n",
474 srv, file));
475 return 1;
479 DLIST_REMOVE(context->internal->_servers, srv);
481 cli_shutdown(&srv->cli);
483 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
485 context->callbacks.remove_cached_srv_fn(context, srv);
487 return 0;
490 SMBCSRV *find_server(SMBCCTX *context,
491 const char *server,
492 const char *share,
493 fstring workgroup,
494 fstring username,
495 fstring password)
497 SMBCSRV *srv;
498 int auth_called = 0;
500 check_server_cache:
502 srv = context->callbacks.get_cached_srv_fn(context, server, share,
503 workgroup, username);
505 if (!auth_called && !srv && (!username[0] || !password[0])) {
506 context->callbacks.auth_fn(server, share,
507 workgroup, sizeof(fstring),
508 username, sizeof(fstring),
509 password, sizeof(fstring));
511 * However, smbc_auth_fn may have picked up info relating to
512 * an existing connection, so try for an existing connection
513 * again ...
515 auth_called = 1;
516 goto check_server_cache;
520 if (srv) {
521 if (context->callbacks.check_server_fn(context, srv)) {
523 * This server is no good anymore
524 * Try to remove it and check for more possible
525 * servers in the cache
527 if (context->callbacks.remove_unused_server_fn(context,
528 srv)) {
530 * We could not remove the server completely,
531 * remove it from the cache so we will not get
532 * it again. It will be removed when the last
533 * file/dir is closed.
535 context->callbacks.remove_cached_srv_fn(context,
536 srv);
540 * Maybe there are more cached connections to this
541 * server
543 goto check_server_cache;
546 return srv;
549 return NULL;
553 * Connect to a server, possibly on an existing connection
555 * Here, what we want to do is: If the server and username
556 * match an existing connection, reuse that, otherwise, establish a
557 * new connection.
559 * If we have to create a new connection, call the auth_fn to get the
560 * info we need, unless the username and password were passed in.
563 SMBCSRV *smbc_server(SMBCCTX *context,
564 const char *server, const char *share,
565 fstring workgroup, fstring username,
566 fstring password)
568 SMBCSRV *srv=NULL;
569 struct cli_state c;
570 struct nmb_name called, calling;
571 const char *server_n = server;
572 pstring ipenv;
573 struct in_addr ip;
574 int tried_reverse = 0;
575 int port_try_first;
576 int port_try_next;
577 const char *username_used;
579 zero_ip(&ip);
580 ZERO_STRUCT(c);
582 if (server[0] == 0) {
583 errno = EPERM;
584 return NULL;
587 srv = find_server(context, server, share,
588 workgroup, username, password);
591 * If we found a connection and we're only allowed one share per
592 * server...
594 if (srv && *share != '\0' && context->options.one_share_per_server) {
597 * ... then if there's no current connection to the share,
598 * connect to it. find_server(), or rather the function
599 * pointed to by context->callbacks.get_cached_srv_fn which
600 * was called by find_server(), will have issued a tree
601 * disconnect if the requested share is not the same as the
602 * one that was already connected.
604 if (srv->cli.cnum == (uint16) -1) {
605 /* Ensure we have accurate auth info */
606 context->callbacks.auth_fn(server, share,
607 workgroup, sizeof(fstring),
608 username, sizeof(fstring),
609 password, sizeof(fstring));
611 if (! cli_send_tconX(&srv->cli, share, "?????",
612 password, strlen(password)+1)) {
614 errno = smbc_errno(context, &srv->cli);
615 cli_shutdown(&srv->cli);
616 context->callbacks.remove_cached_srv_fn(context, srv);
617 srv = NULL;
620 /* Regenerate the dev value since it's based on both server and share */
621 if (srv) {
622 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
627 /* If we have a connection... */
628 if (srv) {
630 /* ... then we're done here. Give 'em what they came for. */
631 return srv;
634 make_nmb_name(&calling, context->netbios_name, 0x0);
635 make_nmb_name(&called , server, 0x20);
637 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
639 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
641 again:
642 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
644 zero_ip(&ip);
646 /* have to open a new connection */
647 if (!cli_initialise(&c)) {
648 errno = ENOMEM;
649 return NULL;
652 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
653 c.use_kerberos = True;
655 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
656 c.fallback_after_kerberos = True;
659 c.timeout = context->timeout;
662 * Force use of port 139 for first try if share is $IPC, empty, or
663 * null, so browse lists can work
665 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
666 port_try_first = 139;
667 port_try_next = 445;
668 } else {
669 port_try_first = 445;
670 port_try_next = 139;
673 c.port = port_try_first;
675 if (!cli_connect(&c, server_n, &ip)) {
677 /* First connection attempt failed. Try alternate port. */
678 c.port = port_try_next;
680 if (!cli_connect(&c, server_n, &ip)) {
681 cli_shutdown(&c);
682 errno = ETIMEDOUT;
683 return NULL;
687 if (!cli_session_request(&c, &calling, &called)) {
688 cli_shutdown(&c);
689 if (strcmp(called.name, "*SMBSERVER")) {
690 make_nmb_name(&called , "*SMBSERVER", 0x20);
691 goto again;
693 else { /* Try one more time, but ensure we don't loop */
695 /* Only try this if server is an IP address ... */
697 if (is_ipaddress(server) && !tried_reverse) {
698 fstring remote_name;
699 struct in_addr rem_ip;
701 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
702 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
703 errno = ETIMEDOUT;
704 return NULL;
707 tried_reverse++; /* Yuck */
709 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
710 make_nmb_name(&called, remote_name, 0x20);
711 goto again;
717 errno = ETIMEDOUT;
718 return NULL;
721 DEBUG(4,(" session request ok\n"));
723 if (!cli_negprot(&c)) {
724 cli_shutdown(&c);
725 errno = ETIMEDOUT;
726 return NULL;
729 username_used = username;
731 if (!cli_session_setup(&c, username_used,
732 password, strlen(password),
733 password, strlen(password),
734 workgroup)) {
736 /* Failed. Try an anonymous login, if allowed by flags. */
737 username_used = "";
739 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
740 !cli_session_setup(&c, username_used,
741 password, 1,
742 password, 0,
743 workgroup)) {
745 cli_shutdown(&c);
746 errno = EPERM;
747 return NULL;
751 DEBUG(4,(" session setup ok\n"));
753 if (!cli_send_tconX(&c, share, "?????",
754 password, strlen(password)+1)) {
755 errno = smbc_errno(context, &c);
756 cli_shutdown(&c);
757 return NULL;
760 DEBUG(4,(" tconx ok\n"));
763 * Ok, we have got a nice connection
764 * Let's allocate a server structure.
767 srv = SMB_MALLOC_P(SMBCSRV);
768 if (!srv) {
769 errno = ENOMEM;
770 goto failed;
773 ZERO_STRUCTP(srv);
774 srv->cli = c;
775 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
776 srv->no_pathinfo = False;
777 srv->no_pathinfo2 = False;
778 srv->no_nt_session = False;
780 /* now add it to the cache (internal or external) */
781 /* Let the cache function set errno if it wants to */
782 errno = 0;
783 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username_used)) {
784 int saved_errno = errno;
785 DEBUG(3, (" Failed to add server to cache\n"));
786 errno = saved_errno;
787 if (errno == 0) {
788 errno = ENOMEM;
790 goto failed;
793 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
794 server, share, srv));
796 DLIST_ADD(context->internal->_servers, srv);
797 return srv;
799 failed:
800 cli_shutdown(&c);
801 if (!srv) return NULL;
803 SAFE_FREE(srv);
804 return NULL;
808 * Connect to a server for getting/setting attributes, possibly on an existing
809 * connection. This works similarly to smbc_server().
811 SMBCSRV *smbc_attr_server(SMBCCTX *context,
812 const char *server, const char *share,
813 fstring workgroup,
814 fstring username, fstring password,
815 POLICY_HND *pol)
817 struct in_addr ip;
818 struct cli_state *ipc_cli;
819 struct rpc_pipe_client *pipe_hnd;
820 NTSTATUS nt_status;
821 SMBCSRV *ipc_srv=NULL;
824 * See if we've already created this special connection. Reference our
825 * "special" share name '*IPC$', which is an impossible real share name
826 * due to the leading asterisk.
828 ipc_srv = find_server(context, server, "*IPC$",
829 workgroup, username, password);
830 if (!ipc_srv) {
832 /* We didn't find a cached connection. Get the password */
833 if (*password == '\0') {
834 /* ... then retrieve it now. */
835 context->callbacks.auth_fn(server, share,
836 workgroup, sizeof(fstring),
837 username, sizeof(fstring),
838 password, sizeof(fstring));
841 zero_ip(&ip);
842 nt_status = cli_full_connection(&ipc_cli,
843 global_myname(), server,
844 &ip, 0, "IPC$", "?????",
845 username, workgroup,
846 password, 0,
847 Undefined, NULL);
848 if (! NT_STATUS_IS_OK(nt_status)) {
849 DEBUG(1,("cli_full_connection failed! (%s)\n",
850 nt_errstr(nt_status)));
851 errno = ENOTSUP;
852 return NULL;
855 if(pol) {
856 pipe_hnd = cli_rpc_pipe_open_noauth(ipc_cli, PI_LSARPC, &nt_status);
857 if (!pipe_hnd) {
858 DEBUG(1, ("cli_nt_session_open fail!\n"));
859 errno = ENOTSUP;
860 cli_shutdown(ipc_cli);
861 return NULL;
864 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
865 but NT sends 0x2000000 so we might as well do it too. */
867 nt_status = rpccli_lsa_open_policy(pipe_hnd,
868 ipc_cli->mem_ctx,
869 True,
870 GENERIC_EXECUTE_ACCESS,
871 pol);
873 if (!NT_STATUS_IS_OK(nt_status)) {
874 errno = smbc_errno(context, ipc_cli);
875 cli_shutdown(ipc_cli);
876 return NULL;
880 ipc_srv = SMB_MALLOC_P(SMBCSRV);
881 if (!ipc_srv) {
882 errno = ENOMEM;
883 cli_shutdown(ipc_cli);
884 return NULL;
887 ZERO_STRUCTP(ipc_srv);
888 ipc_srv->cli = *ipc_cli;
890 free(ipc_cli);
892 /* now add it to the cache (internal or external) */
894 errno = 0; /* let cache function set errno if it likes */
895 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
896 server,
897 "*IPC$",
898 workgroup,
899 username)) {
900 DEBUG(3, (" Failed to add server to cache\n"));
901 if (errno == 0) {
902 errno = ENOMEM;
904 cli_shutdown(&ipc_srv->cli);
905 free(ipc_srv);
906 return NULL;
909 DLIST_ADD(context->internal->_servers, ipc_srv);
912 return ipc_srv;
916 * Routine to open() a file ...
919 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
921 fstring server, share, user, password, workgroup;
922 pstring path;
923 pstring targetpath;
924 struct cli_state *targetcli;
925 SMBCSRV *srv = NULL;
926 SMBCFILE *file = NULL;
927 int fd;
929 if (!context || !context->internal ||
930 !context->internal->_initialized) {
932 errno = EINVAL; /* Best I can think of ... */
933 return NULL;
937 if (!fname) {
939 errno = EINVAL;
940 return NULL;
944 if (smbc_parse_path(context, fname,
945 server, sizeof(server),
946 share, sizeof(share),
947 path, sizeof(path),
948 user, sizeof(user),
949 password, sizeof(password),
950 NULL, 0)) {
951 errno = EINVAL;
952 return NULL;
955 if (user[0] == (char)0) fstrcpy(user, context->user);
957 fstrcpy(workgroup, context->workgroup);
959 srv = smbc_server(context, server, share, workgroup, user, password);
961 if (!srv) {
963 if (errno == EPERM) errno = EACCES;
964 return NULL; /* smbc_server sets errno */
968 /* Hmmm, the test for a directory is suspect here ... FIXME */
970 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
972 fd = -1;
975 else {
977 file = SMB_MALLOC_P(SMBCFILE);
979 if (!file) {
981 errno = ENOMEM;
982 return NULL;
986 ZERO_STRUCTP(file);
988 /*d_printf(">>>open: resolving %s\n", path);*/
989 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
991 d_printf("Could not resolve %s\n", path);
992 return NULL;
994 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
996 if ( targetcli->dfsroot )
998 pstring temppath;
999 pstrcpy(temppath, targetpath);
1000 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1003 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1005 /* Handle the error ... */
1007 SAFE_FREE(file);
1008 errno = smbc_errno(context, targetcli);
1009 return NULL;
1013 /* Fill in file struct */
1015 file->cli_fd = fd;
1016 file->fname = SMB_STRDUP(fname);
1017 file->srv = srv;
1018 file->offset = 0;
1019 file->file = True;
1021 DLIST_ADD(context->internal->_files, file);
1024 * If the file was opened in O_APPEND mode, all write
1025 * operations should be appended to the file. To do that,
1026 * though, using this protocol, would require a getattrE()
1027 * call for each and every write, to determine where the end
1028 * of the file is. (There does not appear to be an append flag
1029 * in the protocol.) Rather than add all of that overhead of
1030 * retrieving the current end-of-file offset prior to each
1031 * write operation, we'll assume that most append operations
1032 * will continuously write, so we'll just set the offset to
1033 * the end of the file now and hope that's adequate.
1035 * Note to self: If this proves inadequate, and O_APPEND
1036 * should, in some cases, be forced for each write, add a
1037 * field in the context options structure, for
1038 * "strict_append_mode" which would select between the current
1039 * behavior (if FALSE) or issuing a getattrE() prior to each
1040 * write and forcing the write to the end of the file (if
1041 * TRUE). Adding that capability will likely require adding
1042 * an "append" flag into the _SMBCFILE structure to track
1043 * whether a file was opened in O_APPEND mode. -- djl
1045 if (flags & O_APPEND) {
1046 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1047 (void) smbc_close_ctx(context, file);
1048 errno = ENXIO;
1049 return NULL;
1053 return file;
1057 /* Check if opendir needed ... */
1059 if (fd == -1) {
1060 int eno = 0;
1062 eno = smbc_errno(context, &srv->cli);
1063 file = context->opendir(context, fname);
1064 if (!file) errno = eno;
1065 return file;
1069 errno = EINVAL; /* FIXME, correct errno ? */
1070 return NULL;
1075 * Routine to create a file
1078 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1080 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
1083 if (!context || !context->internal ||
1084 !context->internal->_initialized) {
1086 errno = EINVAL;
1087 return NULL;
1091 return smbc_open_ctx(context, path, creat_bits, mode);
1095 * Routine to read() a file ...
1098 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1100 int ret;
1101 fstring server, share, user, password;
1102 pstring path, targetpath;
1103 struct cli_state *targetcli;
1106 * offset:
1108 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1109 * appears to pass file->offset (which is type off_t) differently than
1110 * a local variable of type off_t. Using local variable "offset" in
1111 * the call to cli_read() instead of file->offset fixes a problem
1112 * retrieving data at an offset greater than 4GB.
1114 off_t offset = file->offset;
1116 if (!context || !context->internal ||
1117 !context->internal->_initialized) {
1119 errno = EINVAL;
1120 return -1;
1124 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1126 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1128 errno = EBADF;
1129 return -1;
1133 /* Check that the buffer exists ... */
1135 if (buf == NULL) {
1137 errno = EINVAL;
1138 return -1;
1142 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1143 if (smbc_parse_path(context, file->fname,
1144 server, sizeof(server),
1145 share, sizeof(share),
1146 path, sizeof(path),
1147 user, sizeof(user),
1148 password, sizeof(password),
1149 NULL, 0)) {
1150 errno = EINVAL;
1151 return -1;
1154 /*d_printf(">>>read: resolving %s\n", path);*/
1155 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1157 d_printf("Could not resolve %s\n", path);
1158 return -1;
1160 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1162 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1164 if (ret < 0) {
1166 errno = smbc_errno(context, targetcli);
1167 return -1;
1171 file->offset += ret;
1173 DEBUG(4, (" --> %d\n", ret));
1175 return ret; /* Success, ret bytes of data ... */
1180 * Routine to write() a file ...
1183 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1185 int ret;
1186 off_t offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1187 fstring server, share, user, password;
1188 pstring path, targetpath;
1189 struct cli_state *targetcli;
1191 if (!context || !context->internal ||
1192 !context->internal->_initialized) {
1194 errno = EINVAL;
1195 return -1;
1199 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1201 errno = EBADF;
1202 return -1;
1206 /* Check that the buffer exists ... */
1208 if (buf == NULL) {
1210 errno = EINVAL;
1211 return -1;
1215 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1216 if (smbc_parse_path(context, file->fname,
1217 server, sizeof(server),
1218 share, sizeof(share),
1219 path, sizeof(path),
1220 user, sizeof(user),
1221 password, sizeof(password),
1222 NULL, 0)) {
1223 errno = EINVAL;
1224 return -1;
1227 /*d_printf(">>>write: resolving %s\n", path);*/
1228 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1230 d_printf("Could not resolve %s\n", path);
1231 return -1;
1233 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1236 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1238 if (ret <= 0) {
1240 errno = smbc_errno(context, targetcli);
1241 return -1;
1245 file->offset += ret;
1247 return ret; /* Success, 0 bytes of data ... */
1251 * Routine to close() a file ...
1254 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1256 SMBCSRV *srv;
1257 fstring server, share, user, password;
1258 pstring path, targetpath;
1259 struct cli_state *targetcli;
1261 if (!context || !context->internal ||
1262 !context->internal->_initialized) {
1264 errno = EINVAL;
1265 return -1;
1269 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1271 errno = EBADF;
1272 return -1;
1276 /* IS a dir ... */
1277 if (!file->file) {
1279 return context->closedir(context, file);
1283 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1284 if (smbc_parse_path(context, file->fname,
1285 server, sizeof(server),
1286 share, sizeof(share),
1287 path, sizeof(path),
1288 user, sizeof(user),
1289 password, sizeof(password),
1290 NULL, 0)) {
1291 errno = EINVAL;
1292 return -1;
1295 /*d_printf(">>>close: resolving %s\n", path);*/
1296 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1298 d_printf("Could not resolve %s\n", path);
1299 return -1;
1301 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1303 if (!cli_close(targetcli, file->cli_fd)) {
1305 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1306 file->fname));
1307 /* Deallocate slot and remove the server
1308 * from the server cache if unused */
1309 errno = smbc_errno(context, targetcli);
1310 srv = file->srv;
1311 DLIST_REMOVE(context->internal->_files, file);
1312 SAFE_FREE(file->fname);
1313 SAFE_FREE(file);
1314 context->callbacks.remove_unused_server_fn(context, srv);
1316 return -1;
1320 DLIST_REMOVE(context->internal->_files, file);
1321 SAFE_FREE(file->fname);
1322 SAFE_FREE(file);
1324 return 0;
1328 * Get info from an SMB server on a file. Use a qpathinfo call first
1329 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1331 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1332 uint16 *mode, SMB_OFF_T *size,
1333 time_t *c_time, time_t *a_time, time_t *m_time,
1334 SMB_INO_T *ino)
1336 pstring fixedpath;
1337 pstring targetpath;
1338 struct cli_state *targetcli;
1339 if (!context || !context->internal ||
1340 !context->internal->_initialized) {
1342 errno = EINVAL;
1343 return -1;
1347 /* path fixup for . and .. */
1348 if (strequal(path, ".") || strequal(path, ".."))
1349 pstrcpy(fixedpath, "\\");
1350 else
1352 pstrcpy(fixedpath, path);
1353 trim_string(fixedpath, NULL, "\\..");
1354 trim_string(fixedpath, NULL, "\\.");
1356 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1358 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1360 d_printf("Couldn't resolve %s\n", path);
1361 return False;
1364 if ( targetcli->dfsroot )
1366 pstring temppath;
1367 pstrcpy(temppath, targetpath);
1368 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1371 if (!srv->no_pathinfo2 &&
1372 cli_qpathinfo2(targetcli, targetpath, c_time, a_time, m_time, NULL,
1373 size, mode, ino)) return True;
1375 /* if this is NT then don't bother with the getatr */
1376 if (targetcli->capabilities & CAP_NT_SMBS) {
1377 errno = EPERM;
1378 return False;
1381 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1382 if (m_time != NULL) {
1383 if (a_time != NULL) *a_time = *m_time;
1384 if (c_time != NULL) *c_time = *m_time;
1386 srv->no_pathinfo2 = True;
1387 return True;
1390 errno = EPERM;
1391 return False;
1396 * Set file info on an SMB server. Use setpathinfo call first. If that
1397 * fails, use setattrE..
1399 * Access and modification time parameters are always used and must be
1400 * provided. Create time, if zero, will be determined from the actual create
1401 * time of the file. If non-zero, the create time will be set as well.
1403 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1405 static BOOL smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1406 time_t c_time, time_t a_time, time_t m_time,
1407 uint16 mode)
1409 int fd;
1410 int ret;
1413 * Get the create time of the file (if not provided); we'll need it in
1414 * the set call.
1416 if (! srv->no_pathinfo && c_time == 0) {
1417 if (! cli_qpathinfo(&srv->cli, path,
1418 &c_time, NULL, NULL, NULL, NULL)) {
1419 /* qpathinfo not available */
1420 srv->no_pathinfo = True;
1421 } else {
1423 * We got a creation time. Some OS versions don't
1424 * return a valid create time, though. If we got an
1425 * invalid time, start with the current time instead.
1427 if (c_time == 0 || c_time == (time_t) -1) {
1428 c_time = time(NULL);
1432 * We got a creation time. For sanity sake, since
1433 * there is no POSIX function to set the create time
1434 * of a file, if the existing create time is greater
1435 * than either of access time or modification time,
1436 * set create time to the smallest of those. This
1437 * ensure that the create time of a file is never
1438 * greater than its last access or modification time.
1440 if (c_time > a_time) c_time = a_time;
1441 if (c_time > m_time) c_time = m_time;
1446 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1447 * modern function for "new code" to be using, and it works given a
1448 * filename rather than requiring that the file be opened to have its
1449 * attributes manipulated.
1451 if (srv->no_pathinfo ||
1452 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1455 * setpathinfo is not supported; go to plan B.
1457 * cli_setatr() does not work on win98, and it also doesn't
1458 * support setting the access time (only the modification
1459 * time), so in all cases, we open the specified file and use
1460 * cli_setattrE() which should work on all OS versions, and
1461 * supports both times.
1464 /* Don't try {q,set}pathinfo() again, with this server */
1465 srv->no_pathinfo = True;
1467 /* Open the file */
1468 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1470 errno = smbc_errno(context, &srv->cli);
1471 return -1;
1475 * Get the creat time of the file (if it wasn't provided).
1476 * We'll need it in the set call
1478 if (c_time == 0) {
1479 ret = cli_getattrE(&srv->cli, fd,
1480 NULL, NULL,
1481 &c_time, NULL, NULL);
1482 } else {
1483 ret = True;
1486 /* If we got create time, set times */
1487 if (ret) {
1488 /* Some OS versions don't support create time */
1489 if (c_time == 0 || c_time == -1) {
1490 c_time = time(NULL);
1494 * For sanity sake, since there is no POSIX function
1495 * to set the create time of a file, if the existing
1496 * create time is greater than either of access time
1497 * or modification time, set create time to the
1498 * smallest of those. This ensure that the create
1499 * time of a file is never greater than its last
1500 * access or modification time.
1502 if (c_time > a_time) c_time = a_time;
1503 if (c_time > m_time) c_time = m_time;
1505 /* Set the new attributes */
1506 ret = cli_setattrE(&srv->cli, fd,
1507 c_time, a_time, m_time);
1508 cli_close(&srv->cli, fd);
1512 * Unfortunately, setattrE() doesn't have a provision for
1513 * setting the access mode (attributes). We'll have to try
1514 * cli_setatr() for that, and with only this parameter, it
1515 * seems to work on win98.
1517 if (ret && mode != (uint16) -1) {
1518 ret = cli_setatr(&srv->cli, path, mode, 0);
1521 if (! ret) {
1522 errno = smbc_errno(context, &srv->cli);
1523 return False;
1527 return True;
1531 * Routine to unlink() a file
1534 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1536 fstring server, share, user, password, workgroup;
1537 pstring path, targetpath;
1538 struct cli_state *targetcli;
1539 SMBCSRV *srv = NULL;
1541 if (!context || !context->internal ||
1542 !context->internal->_initialized) {
1544 errno = EINVAL; /* Best I can think of ... */
1545 return -1;
1549 if (!fname) {
1551 errno = EINVAL;
1552 return -1;
1556 if (smbc_parse_path(context, fname,
1557 server, sizeof(server),
1558 share, sizeof(share),
1559 path, sizeof(path),
1560 user, sizeof(user),
1561 password, sizeof(password),
1562 NULL, 0)) {
1563 errno = EINVAL;
1564 return -1;
1567 if (user[0] == (char)0) fstrcpy(user, context->user);
1569 fstrcpy(workgroup, context->workgroup);
1571 srv = smbc_server(context, server, share, workgroup, user, password);
1573 if (!srv) {
1575 return -1; /* smbc_server sets errno */
1579 /*d_printf(">>>unlink: resolving %s\n", path);*/
1580 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1582 d_printf("Could not resolve %s\n", path);
1583 return -1;
1585 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1587 if (!cli_unlink(targetcli, targetpath)) {
1589 errno = smbc_errno(context, targetcli);
1591 if (errno == EACCES) { /* Check if the file is a directory */
1593 int saverr = errno;
1594 SMB_OFF_T size = 0;
1595 uint16 mode = 0;
1596 time_t m_time = 0, a_time = 0, c_time = 0;
1597 SMB_INO_T ino = 0;
1599 if (!smbc_getatr(context, srv, path, &mode, &size,
1600 &c_time, &a_time, &m_time, &ino)) {
1602 /* Hmmm, bad error ... What? */
1604 errno = smbc_errno(context, targetcli);
1605 return -1;
1608 else {
1610 if (IS_DOS_DIR(mode))
1611 errno = EISDIR;
1612 else
1613 errno = saverr; /* Restore this */
1618 return -1;
1622 return 0; /* Success ... */
1627 * Routine to rename() a file
1630 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1631 SMBCCTX *ncontext, const char *nname)
1633 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1634 pstring path1, path2, targetpath1, targetpath2;
1635 struct cli_state *targetcli1, *targetcli2;
1636 SMBCSRV *srv = NULL;
1638 if (!ocontext || !ncontext ||
1639 !ocontext->internal || !ncontext->internal ||
1640 !ocontext->internal->_initialized ||
1641 !ncontext->internal->_initialized) {
1643 errno = EINVAL; /* Best I can think of ... */
1644 return -1;
1648 if (!oname || !nname) {
1650 errno = EINVAL;
1651 return -1;
1655 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1657 smbc_parse_path(ocontext, oname,
1658 server1, sizeof(server1),
1659 share1, sizeof(share1),
1660 path1, sizeof(path1),
1661 user1, sizeof(user1),
1662 password1, sizeof(password1),
1663 NULL, 0);
1665 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1667 smbc_parse_path(ncontext, nname,
1668 server2, sizeof(server2),
1669 share2, sizeof(share2),
1670 path2, sizeof(path2),
1671 user2, sizeof(user2),
1672 password2, sizeof(password2),
1673 NULL, 0);
1675 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1677 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1678 strcmp(user1, user2)) {
1680 /* Can't rename across file systems, or users?? */
1682 errno = EXDEV;
1683 return -1;
1687 fstrcpy(workgroup, ocontext->workgroup);
1688 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1689 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1690 if (!srv) {
1692 return -1;
1696 /*d_printf(">>>rename: resolving %s\n", path1);*/
1697 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1699 d_printf("Could not resolve %s\n", path1);
1700 return -1;
1702 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1703 /*d_printf(">>>rename: resolving %s\n", path2);*/
1704 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1706 d_printf("Could not resolve %s\n", path2);
1707 return -1;
1709 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1711 if (strcmp(targetcli1->desthost, targetcli2->desthost) || strcmp(targetcli1->share, targetcli2->share))
1713 /* can't rename across file systems */
1715 errno = EXDEV;
1716 return -1;
1719 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1720 int eno = smbc_errno(ocontext, targetcli1);
1722 if (eno != EEXIST ||
1723 !cli_unlink(targetcli1, targetpath2) ||
1724 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1726 errno = eno;
1727 return -1;
1732 return 0; /* Success */
1737 * A routine to lseek() a file
1740 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1742 SMB_OFF_T size;
1743 fstring server, share, user, password;
1744 pstring path, targetpath;
1745 struct cli_state *targetcli;
1747 if (!context || !context->internal ||
1748 !context->internal->_initialized) {
1750 errno = EINVAL;
1751 return -1;
1755 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1757 errno = EBADF;
1758 return -1;
1762 if (!file->file) {
1764 errno = EINVAL;
1765 return -1; /* Can't lseek a dir ... */
1769 switch (whence) {
1770 case SEEK_SET:
1771 file->offset = offset;
1772 break;
1774 case SEEK_CUR:
1775 file->offset += offset;
1776 break;
1778 case SEEK_END:
1779 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1780 if (smbc_parse_path(context, file->fname,
1781 server, sizeof(server),
1782 share, sizeof(share),
1783 path, sizeof(path),
1784 user, sizeof(user),
1785 password, sizeof(password),
1786 NULL, 0)) {
1787 errno = EINVAL;
1788 return -1;
1791 /*d_printf(">>>lseek: resolving %s\n", path);*/
1792 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1794 d_printf("Could not resolve %s\n", path);
1795 return -1;
1797 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1799 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL, &size, NULL, NULL,
1800 NULL, NULL, NULL))
1802 SMB_OFF_T b_size = size;
1803 if (!cli_getattrE(targetcli, file->cli_fd, NULL, &b_size, NULL, NULL,
1804 NULL))
1806 errno = EINVAL;
1807 return -1;
1808 } else
1809 size = b_size;
1811 file->offset = size + offset;
1812 break;
1814 default:
1815 errno = EINVAL;
1816 break;
1820 return file->offset;
1825 * Generate an inode number from file name for those things that need it
1828 static
1829 ino_t smbc_inode(SMBCCTX *context, const char *name)
1832 if (!context || !context->internal ||
1833 !context->internal->_initialized) {
1835 errno = EINVAL;
1836 return -1;
1840 if (!*name) return 2; /* FIXME, why 2 ??? */
1841 return (ino_t)str_checksum(name);
1846 * Routine to put basic stat info into a stat structure ... Used by stat and
1847 * fstat below.
1850 static
1851 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname,
1852 SMB_OFF_T size, int mode)
1855 st->st_mode = 0;
1857 if (IS_DOS_DIR(mode)) {
1858 st->st_mode = SMBC_DIR_MODE;
1859 } else {
1860 st->st_mode = SMBC_FILE_MODE;
1863 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1864 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1865 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1866 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1868 st->st_size = size;
1869 #ifdef HAVE_STAT_ST_BLKSIZE
1870 st->st_blksize = 512;
1871 #endif
1872 #ifdef HAVE_STAT_ST_BLOCKS
1873 st->st_blocks = (size+511)/512;
1874 #endif
1875 st->st_uid = getuid();
1876 st->st_gid = getgid();
1878 if (IS_DOS_DIR(mode)) {
1879 st->st_nlink = 2;
1880 } else {
1881 st->st_nlink = 1;
1884 if (st->st_ino == 0) {
1885 st->st_ino = smbc_inode(context, fname);
1888 return True; /* FIXME: Is this needed ? */
1893 * Routine to stat a file given a name
1896 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1898 SMBCSRV *srv;
1899 fstring server, share, user, password, workgroup;
1900 pstring path;
1901 time_t m_time = 0, a_time = 0, c_time = 0;
1902 SMB_OFF_T size = 0;
1903 uint16 mode = 0;
1904 SMB_INO_T ino = 0;
1906 if (!context || !context->internal ||
1907 !context->internal->_initialized) {
1909 errno = EINVAL; /* Best I can think of ... */
1910 return -1;
1914 if (!fname) {
1916 errno = EINVAL;
1917 return -1;
1921 DEBUG(4, ("smbc_stat(%s)\n", fname));
1923 if (smbc_parse_path(context, fname,
1924 server, sizeof(server),
1925 share, sizeof(share),
1926 path, sizeof(path),
1927 user, sizeof(user),
1928 password, sizeof(password),
1929 NULL, 0)) {
1930 errno = EINVAL;
1931 return -1;
1934 if (user[0] == (char)0) fstrcpy(user, context->user);
1936 fstrcpy(workgroup, context->workgroup);
1938 srv = smbc_server(context, server, share, workgroup, user, password);
1940 if (!srv) {
1941 return -1; /* errno set by smbc_server */
1944 if (!smbc_getatr(context, srv, path, &mode, &size,
1945 &c_time, &a_time, &m_time, &ino)) {
1947 errno = smbc_errno(context, &srv->cli);
1948 return -1;
1952 st->st_ino = ino;
1954 smbc_setup_stat(context, st, path, size, mode);
1956 st->st_atime = a_time;
1957 st->st_ctime = c_time;
1958 st->st_mtime = m_time;
1959 st->st_dev = srv->dev;
1961 return 0;
1966 * Routine to stat a file given an fd
1969 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1971 time_t c_time, a_time, m_time;
1972 SMB_OFF_T size;
1973 uint16 mode;
1974 fstring server, share, user, password;
1975 pstring path, targetpath;
1976 struct cli_state *targetcli;
1977 SMB_INO_T ino = 0;
1979 if (!context || !context->internal ||
1980 !context->internal->_initialized) {
1982 errno = EINVAL;
1983 return -1;
1987 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1989 errno = EBADF;
1990 return -1;
1994 if (!file->file) {
1996 return context->fstatdir(context, file, st);
2000 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2001 if (smbc_parse_path(context, file->fname,
2002 server, sizeof(server),
2003 share, sizeof(share),
2004 path, sizeof(path),
2005 user, sizeof(user),
2006 password, sizeof(password),
2007 NULL, 0)) {
2008 errno = EINVAL;
2009 return -1;
2012 /*d_printf(">>>fstat: resolving %s\n", path);*/
2013 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
2015 d_printf("Could not resolve %s\n", path);
2016 return -1;
2018 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2020 if (!cli_qfileinfo(targetcli, file->cli_fd,
2021 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
2022 if (!cli_getattrE(targetcli, file->cli_fd,
2023 &mode, &size, &c_time, &a_time, &m_time)) {
2025 errno = EINVAL;
2026 return -1;
2030 st->st_ino = ino;
2032 smbc_setup_stat(context, st, file->fname, size, mode);
2034 st->st_atime = a_time;
2035 st->st_ctime = c_time;
2036 st->st_mtime = m_time;
2037 st->st_dev = file->srv->dev;
2039 return 0;
2044 * Routine to open a directory
2045 * We accept the URL syntax explained in smbc_parse_path(), above.
2048 static void smbc_remove_dir(SMBCFILE *dir)
2050 struct smbc_dir_list *d,*f;
2052 d = dir->dir_list;
2053 while (d) {
2055 f = d; d = d->next;
2057 SAFE_FREE(f->dirent);
2058 SAFE_FREE(f);
2062 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2066 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
2068 struct smbc_dirent *dirent;
2069 int size;
2070 int name_length = (name == NULL ? 0 : strlen(name));
2071 int comment_len = (comment == NULL ? 0 : strlen(comment));
2074 * Allocate space for the dirent, which must be increased by the
2075 * size of the name and the comment and 1 each for the null terminator.
2078 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2080 dirent = SMB_MALLOC(size);
2082 if (!dirent) {
2084 dir->dir_error = ENOMEM;
2085 return -1;
2089 ZERO_STRUCTP(dirent);
2091 if (dir->dir_list == NULL) {
2093 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2094 if (!dir->dir_list) {
2096 SAFE_FREE(dirent);
2097 dir->dir_error = ENOMEM;
2098 return -1;
2101 ZERO_STRUCTP(dir->dir_list);
2103 dir->dir_end = dir->dir_next = dir->dir_list;
2105 else {
2107 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2109 if (!dir->dir_end->next) {
2111 SAFE_FREE(dirent);
2112 dir->dir_error = ENOMEM;
2113 return -1;
2116 ZERO_STRUCTP(dir->dir_end->next);
2118 dir->dir_end = dir->dir_end->next;
2121 dir->dir_end->next = NULL;
2122 dir->dir_end->dirent = dirent;
2124 dirent->smbc_type = type;
2125 dirent->namelen = name_length;
2126 dirent->commentlen = comment_len;
2127 dirent->dirlen = size;
2129 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2131 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2132 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2134 return 0;
2138 static void
2139 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
2141 SMBCFILE *dir = (SMBCFILE *)state;
2142 struct smbc_dir_list *dir_list;
2143 struct smbc_dirent *dirent;
2144 int dirent_type;
2145 int do_remove = 0;
2147 dirent_type = dir->dir_type;
2149 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2151 /* An error occurred, what do we do? */
2152 /* FIXME: Add some code here */
2155 /* Point to the one just added */
2156 dirent = dir->dir_end->dirent;
2158 /* See if this was a duplicate */
2159 for (dir_list = dir->dir_list;
2160 dir_list != dir->dir_end;
2161 dir_list = dir_list->next) {
2162 if (! do_remove &&
2163 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2164 /* Duplicate. End end of list need to be removed. */
2165 do_remove = 1;
2168 if (do_remove && dir_list->next == dir->dir_end) {
2169 /* Found the end of the list. Remove it. */
2170 dir->dir_end = dir_list;
2171 free(dir_list->next);
2172 dir_list->next = NULL;
2173 break;
2178 static void
2179 list_fn(const char *name, uint32 type, const char *comment, void *state)
2181 SMBCFILE *dir = (SMBCFILE *)state;
2182 int dirent_type;
2184 /* We need to process the type a little ... */
2186 if (dir->dir_type == SMBC_FILE_SHARE) {
2188 switch (type) {
2189 case 0: /* Directory tree */
2190 dirent_type = SMBC_FILE_SHARE;
2191 break;
2193 case 1:
2194 dirent_type = SMBC_PRINTER_SHARE;
2195 break;
2197 case 2:
2198 dirent_type = SMBC_COMMS_SHARE;
2199 break;
2201 case 3:
2202 dirent_type = SMBC_IPC_SHARE;
2203 break;
2205 default:
2206 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2207 break;
2210 else dirent_type = dir->dir_type;
2212 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2214 /* An error occurred, what do we do? */
2215 /* FIXME: Add some code here */
2220 static void
2221 dir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2224 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2225 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2227 /* Handle an error ... */
2229 /* FIXME: Add some code ... */
2235 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
2237 fstring server, share, user, password, options;
2238 pstring workgroup;
2239 pstring path;
2240 uint16 mode;
2241 char *p;
2242 SMBCSRV *srv = NULL;
2243 SMBCFILE *dir = NULL;
2244 struct in_addr rem_ip;
2246 if (!context || !context->internal ||
2247 !context->internal->_initialized) {
2248 DEBUG(4, ("no valid context\n"));
2249 errno = EINVAL + 8192;
2250 return NULL;
2254 if (!fname) {
2255 DEBUG(4, ("no valid fname\n"));
2256 errno = EINVAL + 8193;
2257 return NULL;
2260 if (smbc_parse_path(context, fname,
2261 server, sizeof(server),
2262 share, sizeof(share),
2263 path, sizeof(path),
2264 user, sizeof(user),
2265 password, sizeof(password),
2266 options, sizeof(options))) {
2267 DEBUG(4, ("no valid path\n"));
2268 errno = EINVAL + 8194;
2269 return NULL;
2272 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
2274 /* Ensure the options are valid */
2275 if (smbc_check_options(server, share, path, options)) {
2276 DEBUG(4, ("unacceptable options (%s)\n", options));
2277 errno = EINVAL + 8195;
2278 return NULL;
2281 if (user[0] == (char)0) fstrcpy(user, context->user);
2283 pstrcpy(workgroup, context->workgroup);
2285 dir = SMB_MALLOC_P(SMBCFILE);
2287 if (!dir) {
2289 errno = ENOMEM;
2290 return NULL;
2294 ZERO_STRUCTP(dir);
2296 dir->cli_fd = 0;
2297 dir->fname = SMB_STRDUP(fname);
2298 dir->srv = NULL;
2299 dir->offset = 0;
2300 dir->file = False;
2301 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2303 if (server[0] == (char)0) {
2305 int i;
2306 int count;
2307 int max_lmb_count;
2308 struct ip_service *ip_list;
2309 struct ip_service server_addr;
2310 struct user_auth_info u_info;
2311 struct cli_state *cli;
2313 if (share[0] != (char)0 || path[0] != (char)0) {
2315 errno = EINVAL + 8196;
2316 if (dir) {
2317 SAFE_FREE(dir->fname);
2318 SAFE_FREE(dir);
2320 return NULL;
2323 /* Determine how many local master browsers to query */
2324 max_lmb_count = (context->options.browse_max_lmb_count == 0
2325 ? INT_MAX
2326 : context->options.browse_max_lmb_count);
2328 pstrcpy(u_info.username, user);
2329 pstrcpy(u_info.password, password);
2332 * We have server and share and path empty but options
2333 * requesting that we scan all master browsers for their list
2334 * of workgroups/domains. This implies that we must first try
2335 * broadcast queries to find all master browsers, and if that
2336 * doesn't work, then try our other methods which return only
2337 * a single master browser.
2340 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2341 if (!find_master_ip(workgroup, &server_addr.ip)) {
2343 errno = ENOENT;
2344 return NULL;
2347 ip_list = &server_addr;
2348 count = 1;
2351 for (i = 0; i < count && i < max_lmb_count; i++) {
2352 DEBUG(99, ("Found master browser %d of %d: %s\n", i+1, MAX(count, max_lmb_count), inet_ntoa(ip_list[i].ip)));
2354 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2355 /* cli == NULL is the master browser refused to talk or
2356 could not be found */
2357 if ( !cli )
2358 continue;
2360 fstrcpy(server, cli->desthost);
2361 cli_shutdown(cli);
2363 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2366 * For each returned master browser IP address, get a
2367 * connection to IPC$ on the server if we do not
2368 * already have one, and determine the
2369 * workgroups/domains that it knows about.
2372 srv = smbc_server(context, server,
2373 "IPC$", workgroup, user, password);
2374 if (!srv) {
2375 continue;
2378 dir->srv = srv;
2379 dir->dir_type = SMBC_WORKGROUP;
2381 /* Now, list the stuff ... */
2383 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2384 (void *)dir)) {
2386 continue;
2389 } else {
2391 * Server not an empty string ... Check the rest and see what
2392 * gives
2394 if (share[0] == (char)0) {
2396 if (path[0] != (char)0) { /* Should not have empty share with path */
2398 errno = EINVAL + 8197;
2399 if (dir) {
2400 SAFE_FREE(dir->fname);
2401 SAFE_FREE(dir);
2403 return NULL;
2407 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2408 /* However, we check to see if <server> is an IP address first */
2410 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2411 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2412 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2413 fstring buserver;
2415 dir->dir_type = SMBC_SERVER;
2418 * Get the backup list ...
2422 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2424 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2425 errno = EPERM; /* FIXME, is this correct */
2426 return NULL;
2431 * Get a connection to IPC$ on the server if we do not already have one
2434 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2436 if (!srv) {
2437 DEBUG(0, ("got no contact to IPC$\n"));
2438 if (dir) {
2439 SAFE_FREE(dir->fname);
2440 SAFE_FREE(dir);
2442 return NULL;
2446 dir->srv = srv;
2448 /* Now, list the servers ... */
2450 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2451 (void *)dir)) {
2453 if (dir) {
2454 SAFE_FREE(dir->fname);
2455 SAFE_FREE(dir);
2457 return NULL;
2461 else {
2463 if (resolve_name(server, &rem_ip, 0x20)) {
2465 /* Now, list the shares ... */
2467 dir->dir_type = SMBC_FILE_SHARE;
2469 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2471 if (!srv) {
2473 if (dir) {
2474 SAFE_FREE(dir->fname);
2475 SAFE_FREE(dir);
2477 return NULL;
2481 dir->srv = srv;
2483 /* Now, list the servers ... */
2485 if (cli_RNetShareEnum(&srv->cli, list_fn,
2486 (void *)dir) < 0) {
2488 errno = cli_errno(&srv->cli);
2489 if (dir) {
2490 SAFE_FREE(dir->fname);
2491 SAFE_FREE(dir);
2493 return NULL;
2498 else {
2500 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2501 if (dir) {
2502 SAFE_FREE(dir->fname);
2503 SAFE_FREE(dir);
2505 return NULL;
2512 else { /* The server and share are specified ... work from there ... */
2513 pstring targetpath;
2514 struct cli_state *targetcli;
2516 /* Well, we connect to the server and list the directory */
2518 dir->dir_type = SMBC_FILE_SHARE;
2520 srv = smbc_server(context, server, share, workgroup, user, password);
2522 if (!srv) {
2524 if (dir) {
2525 SAFE_FREE(dir->fname);
2526 SAFE_FREE(dir);
2528 return NULL;
2532 dir->srv = srv;
2534 /* Now, list the files ... */
2536 p = path + strlen(path);
2537 pstrcat(path, "\\*");
2539 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2541 d_printf("Could not resolve %s\n", path);
2542 return NULL;
2545 if (cli_list(targetcli, targetpath, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2546 (void *)dir) < 0) {
2548 if (dir) {
2549 SAFE_FREE(dir->fname);
2550 SAFE_FREE(dir);
2552 errno = smbc_errno(context, targetcli);
2554 if (errno == EINVAL) {
2556 * See if they asked to opendir something
2557 * other than a directory. If so, the
2558 * converted error value we got would have
2559 * been EINVAL rather than ENOTDIR.
2561 *p = '\0'; /* restore original path */
2563 if (smbc_getatr(context, srv, path,
2564 &mode, NULL,
2565 NULL, NULL, NULL,
2566 NULL) &&
2567 ! IS_DOS_DIR(mode)) {
2569 /* It is. Correct the error value */
2570 errno = ENOTDIR;
2574 return NULL;
2581 DLIST_ADD(context->internal->_files, dir);
2582 return dir;
2587 * Routine to close a directory
2590 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2593 if (!context || !context->internal ||
2594 !context->internal->_initialized) {
2596 errno = EINVAL;
2597 return -1;
2601 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2603 errno = EBADF;
2604 return -1;
2608 smbc_remove_dir(dir); /* Clean it up */
2610 DLIST_REMOVE(context->internal->_files, dir);
2612 if (dir) {
2614 SAFE_FREE(dir->fname);
2615 SAFE_FREE(dir); /* Free the space too */
2618 return 0;
2622 static void smbc_readdir_internal(SMBCCTX * context,
2623 struct smbc_dirent *dest,
2624 struct smbc_dirent *src,
2625 int max_namebuf_len)
2627 if (context->options.urlencode_readdir_entries) {
2629 /* url-encode the name. get back remaining buffer space */
2630 max_namebuf_len =
2631 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2633 /* We now know the name length */
2634 dest->namelen = strlen(dest->name);
2636 /* Save the pointer to the beginning of the comment */
2637 dest->comment = dest->name + dest->namelen + 1;
2639 /* Copy the comment */
2640 strncpy(dest->comment, src->comment, max_namebuf_len);
2642 /* Ensure the comment is null terminated */
2643 if (max_namebuf_len > src->commentlen) {
2644 dest->comment[src->commentlen] = '\0';
2645 } else {
2646 dest->comment[max_namebuf_len - 1] = '\0';
2649 /* Save other fields */
2650 dest->smbc_type = src->smbc_type;
2651 dest->commentlen = strlen(dest->comment);
2652 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2653 (char *) dest);
2654 } else {
2656 /* No encoding. Just copy the entry as is. */
2657 memcpy(dest, src, src->dirlen);
2658 dest->comment = (char *)(&dest->name + src->namelen + 1);
2664 * Routine to get a directory entry
2667 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2669 int maxlen;
2670 struct smbc_dirent *dirp, *dirent;
2672 /* Check that all is ok first ... */
2674 if (!context || !context->internal ||
2675 !context->internal->_initialized) {
2677 errno = EINVAL;
2678 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2679 return NULL;
2683 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2685 errno = EBADF;
2686 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2687 return NULL;
2691 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2693 errno = ENOTDIR;
2694 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2695 return NULL;
2699 if (!dir->dir_next) {
2700 return NULL;
2703 dirent = dir->dir_next->dirent;
2704 if (!dirent) {
2706 errno = ENOENT;
2707 return NULL;
2711 dirp = (struct smbc_dirent *)context->internal->_dirent;
2712 maxlen = (sizeof(context->internal->_dirent) -
2713 sizeof(struct smbc_dirent));
2715 smbc_readdir_internal(context, dirp, dirent, maxlen);
2717 dir->dir_next = dir->dir_next->next;
2719 return dirp;
2723 * Routine to get directory entries
2726 static int smbc_getdents_ctx(SMBCCTX *context,
2727 SMBCFILE *dir,
2728 struct smbc_dirent *dirp,
2729 int count)
2731 int rem = count;
2732 int reqd;
2733 int maxlen;
2734 char *ndir = (char *)dirp;
2735 struct smbc_dir_list *dirlist;
2737 /* Check that all is ok first ... */
2739 if (!context || !context->internal ||
2740 !context->internal->_initialized) {
2742 errno = EINVAL;
2743 return -1;
2747 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2749 errno = EBADF;
2750 return -1;
2754 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2756 errno = ENOTDIR;
2757 return -1;
2762 * Now, retrieve the number of entries that will fit in what was passed
2763 * We have to figure out if the info is in the list, or we need to
2764 * send a request to the server to get the info.
2767 while ((dirlist = dir->dir_next)) {
2768 struct smbc_dirent *dirent;
2770 if (!dirlist->dirent) {
2772 errno = ENOENT; /* Bad error */
2773 return -1;
2777 /* Do urlencoding of next entry, if so selected */
2778 dirent = (struct smbc_dirent *)context->internal->_dirent;
2779 maxlen = (sizeof(context->internal->_dirent) -
2780 sizeof(struct smbc_dirent));
2781 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
2783 reqd = dirent->dirlen;
2785 if (rem < reqd) {
2787 if (rem < count) { /* We managed to copy something */
2789 errno = 0;
2790 return count - rem;
2793 else { /* Nothing copied ... */
2795 errno = EINVAL; /* Not enough space ... */
2796 return -1;
2802 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2804 ((struct smbc_dirent *)ndir)->comment =
2805 (char *)(&((struct smbc_dirent *)ndir)->name +
2806 dirent->namelen +
2809 ndir += reqd;
2811 rem -= reqd;
2813 dir->dir_next = dirlist = dirlist -> next;
2816 if (rem == count)
2817 return 0;
2818 else
2819 return count - rem;
2824 * Routine to create a directory ...
2827 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2829 SMBCSRV *srv;
2830 fstring server, share, user, password, workgroup;
2831 pstring path, targetpath;
2832 struct cli_state *targetcli;
2834 if (!context || !context->internal ||
2835 !context->internal->_initialized) {
2837 errno = EINVAL;
2838 return -1;
2842 if (!fname) {
2844 errno = EINVAL;
2845 return -1;
2849 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2851 if (smbc_parse_path(context, fname,
2852 server, sizeof(server),
2853 share, sizeof(share),
2854 path, sizeof(path),
2855 user, sizeof(user),
2856 password, sizeof(password),
2857 NULL, 0)) {
2858 errno = EINVAL;
2859 return -1;
2862 if (user[0] == (char)0) fstrcpy(user, context->user);
2864 fstrcpy(workgroup, context->workgroup);
2866 srv = smbc_server(context, server, share, workgroup, user, password);
2868 if (!srv) {
2870 return -1; /* errno set by smbc_server */
2874 /*d_printf(">>>mkdir: resolving %s\n", path);*/
2875 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2877 d_printf("Could not resolve %s\n", path);
2878 return -1;
2880 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
2882 if (!cli_mkdir(targetcli, targetpath)) {
2884 errno = smbc_errno(context, targetcli);
2885 return -1;
2889 return 0;
2894 * Our list function simply checks to see if a directory is not empty
2897 static int smbc_rmdir_dirempty = True;
2899 static void rmdir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2902 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2903 smbc_rmdir_dirempty = False;
2908 * Routine to remove a directory
2911 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2913 SMBCSRV *srv;
2914 fstring server, share, user, password, workgroup;
2915 pstring path, targetpath;
2916 struct cli_state *targetcli;
2918 if (!context || !context->internal ||
2919 !context->internal->_initialized) {
2921 errno = EINVAL;
2922 return -1;
2926 if (!fname) {
2928 errno = EINVAL;
2929 return -1;
2933 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2935 if (smbc_parse_path(context, fname,
2936 server, sizeof(server),
2937 share, sizeof(share),
2938 path, sizeof(path),
2939 user, sizeof(user),
2940 password, sizeof(password),
2941 NULL, 0))
2943 errno = EINVAL;
2944 return -1;
2947 if (user[0] == (char)0) fstrcpy(user, context->user);
2949 fstrcpy(workgroup, context->workgroup);
2951 srv = smbc_server(context, server, share, workgroup, user, password);
2953 if (!srv) {
2955 return -1; /* errno set by smbc_server */
2959 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2961 mode = aDIR | aRONLY;
2964 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2966 if (strcmp(path, "\\") == 0) {
2968 mode = aDIR | aRONLY;
2971 else {
2973 mode = aRONLY;
2974 smbc_stat_printjob(srv, path, &size, &m_time);
2975 c_time = a_time = m_time;
2978 else { */
2980 /*d_printf(">>>rmdir: resolving %s\n", path);*/
2981 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2983 d_printf("Could not resolve %s\n", path);
2984 return -1;
2986 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
2989 if (!cli_rmdir(targetcli, targetpath)) {
2991 errno = smbc_errno(context, targetcli);
2993 if (errno == EACCES) { /* Check if the dir empty or not */
2995 pstring lpath; /* Local storage to avoid buffer overflows */
2997 smbc_rmdir_dirempty = True; /* Make this so ... */
2999 pstrcpy(lpath, targetpath);
3000 pstrcat(lpath, "\\*");
3002 if (cli_list(targetcli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
3003 NULL) < 0) {
3005 /* Fix errno to ignore latest error ... */
3007 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
3008 smbc_errno(context, targetcli)));
3009 errno = EACCES;
3013 if (smbc_rmdir_dirempty)
3014 errno = EACCES;
3015 else
3016 errno = ENOTEMPTY;
3020 return -1;
3024 return 0;
3029 * Routine to return the current directory position
3032 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
3034 off_t ret_val; /* Squash warnings about cast */
3036 if (!context || !context->internal ||
3037 !context->internal->_initialized) {
3039 errno = EINVAL;
3040 return -1;
3044 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3046 errno = EBADF;
3047 return -1;
3051 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3053 errno = ENOTDIR;
3054 return -1;
3059 * We return the pointer here as the offset
3061 ret_val = (off_t)(long)dir->dir_next;
3062 return ret_val;
3067 * A routine to run down the list and see if the entry is OK
3070 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
3071 struct smbc_dirent *dirent)
3074 /* Run down the list looking for what we want */
3076 if (dirent) {
3078 struct smbc_dir_list *tmp = list;
3080 while (tmp) {
3082 if (tmp->dirent == dirent)
3083 return tmp;
3085 tmp = tmp->next;
3091 return NULL; /* Not found, or an error */
3097 * Routine to seek on a directory
3100 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
3102 long int l_offset = offset; /* Handle problems of size */
3103 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3104 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3106 if (!context || !context->internal ||
3107 !context->internal->_initialized) {
3109 errno = EINVAL;
3110 return -1;
3114 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3116 errno = ENOTDIR;
3117 return -1;
3121 /* Now, check what we were passed and see if it is OK ... */
3123 if (dirent == NULL) { /* Seek to the begining of the list */
3125 dir->dir_next = dir->dir_list;
3126 return 0;
3130 /* Now, run down the list and make sure that the entry is OK */
3131 /* This may need to be changed if we change the format of the list */
3133 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3135 errno = EINVAL; /* Bad entry */
3136 return -1;
3140 dir->dir_next = list_ent;
3142 return 0;
3147 * Routine to fstat a dir
3150 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
3153 if (!context || !context->internal ||
3154 !context->internal->_initialized) {
3156 errno = EINVAL;
3157 return -1;
3161 /* No code yet ... */
3163 return 0;
3167 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
3169 SMBCSRV *srv;
3170 fstring server, share, user, password, workgroup;
3171 pstring path;
3172 uint16 mode;
3174 if (!context || !context->internal ||
3175 !context->internal->_initialized) {
3177 errno = EINVAL; /* Best I can think of ... */
3178 return -1;
3182 if (!fname) {
3184 errno = EINVAL;
3185 return -1;
3189 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3191 if (smbc_parse_path(context, fname,
3192 server, sizeof(server),
3193 share, sizeof(share),
3194 path, sizeof(path),
3195 user, sizeof(user),
3196 password, sizeof(password),
3197 NULL, 0)) {
3198 errno = EINVAL;
3199 return -1;
3202 if (user[0] == (char)0) fstrcpy(user, context->user);
3204 fstrcpy(workgroup, context->workgroup);
3206 srv = smbc_server(context, server, share, workgroup, user, password);
3208 if (!srv) {
3209 return -1; /* errno set by smbc_server */
3212 mode = 0;
3214 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3215 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3216 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3217 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3219 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3220 errno = smbc_errno(context, &srv->cli);
3221 return -1;
3224 return 0;
3227 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
3229 SMBCSRV *srv;
3230 fstring server, share, user, password, workgroup;
3231 pstring path;
3232 time_t a_time;
3233 time_t m_time;
3235 if (!context || !context->internal ||
3236 !context->internal->_initialized) {
3238 errno = EINVAL; /* Best I can think of ... */
3239 return -1;
3243 if (!fname) {
3245 errno = EINVAL;
3246 return -1;
3250 if (tbuf == NULL) {
3251 a_time = m_time = time(NULL);
3252 } else {
3253 a_time = tbuf[0].tv_sec;
3254 m_time = tbuf[1].tv_sec;
3257 if (DEBUGLVL(4))
3259 char *p;
3260 char atimebuf[32];
3261 char mtimebuf[32];
3263 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf));
3264 atimebuf[sizeof(atimebuf) - 1] = '\0';
3265 if ((p = strchr(atimebuf, '\n')) != NULL) {
3266 *p = '\0';
3269 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf));
3270 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3271 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3272 *p = '\0';
3275 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3276 fname, atimebuf, mtimebuf);
3279 if (smbc_parse_path(context, fname,
3280 server, sizeof(server),
3281 share, sizeof(share),
3282 path, sizeof(path),
3283 user, sizeof(user),
3284 password, sizeof(password),
3285 NULL, 0)) {
3286 errno = EINVAL;
3287 return -1;
3290 if (user[0] == (char)0) fstrcpy(user, context->user);
3292 fstrcpy(workgroup, context->workgroup);
3294 srv = smbc_server(context, server, share, workgroup, user, password);
3296 if (!srv) {
3297 return -1; /* errno set by smbc_server */
3300 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3301 return -1; /* errno set by smbc_setatr */
3304 return 0;
3308 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3309 However NT4 gives a "The information may have been modified by a
3310 computer running Windows NT 5.0" if denied ACEs do not appear before
3311 allowed ACEs. */
3313 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
3315 if (sec_ace_equal(ace1, ace2))
3316 return 0;
3318 if (ace1->type != ace2->type)
3319 return ace2->type - ace1->type;
3321 if (sid_compare(&ace1->trustee, &ace2->trustee))
3322 return sid_compare(&ace1->trustee, &ace2->trustee);
3324 if (ace1->flags != ace2->flags)
3325 return ace1->flags - ace2->flags;
3327 if (ace1->info.mask != ace2->info.mask)
3328 return ace1->info.mask - ace2->info.mask;
3330 if (ace1->size != ace2->size)
3331 return ace1->size - ace2->size;
3333 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3337 static void sort_acl(SEC_ACL *the_acl)
3339 uint32 i;
3340 if (!the_acl) return;
3342 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
3344 for (i=1;i<the_acl->num_aces;) {
3345 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3346 int j;
3347 for (j=i; j<the_acl->num_aces-1; j++) {
3348 the_acl->ace[j] = the_acl->ace[j+1];
3350 the_acl->num_aces--;
3351 } else {
3352 i++;
3357 /* convert a SID to a string, either numeric or username/group */
3358 static void convert_sid_to_string(struct cli_state *ipc_cli,
3359 POLICY_HND *pol,
3360 fstring str,
3361 BOOL numeric,
3362 DOM_SID *sid)
3364 char **domains = NULL;
3365 char **names = NULL;
3366 uint32 *types = NULL;
3367 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3368 sid_to_string(str, sid);
3370 if (numeric) {
3371 return; /* no lookup desired */
3374 if (!pipe_hnd) {
3375 return;
3378 /* Ask LSA to convert the sid to a name */
3380 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3381 pol, 1, sid, &domains,
3382 &names, &types)) ||
3383 !domains || !domains[0] || !names || !names[0]) {
3384 return;
3387 /* Converted OK */
3389 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3390 domains[0], lp_winbind_separator(),
3391 names[0]);
3394 /* convert a string to a SID, either numeric or username/group */
3395 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
3396 POLICY_HND *pol,
3397 BOOL numeric,
3398 DOM_SID *sid,
3399 const char *str)
3401 uint32 *types = NULL;
3402 DOM_SID *sids = NULL;
3403 BOOL result = True;
3404 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3406 if (!pipe_hnd) {
3407 return False;
3410 if (numeric) {
3411 if (strncmp(str, "S-", 2) == 0) {
3412 return string_to_sid(sid, str);
3415 result = False;
3416 goto done;
3419 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3420 pol, 1, &str, &sids,
3421 &types))) {
3422 result = False;
3423 goto done;
3426 sid_copy(sid, &sids[0]);
3427 done:
3429 return result;
3433 /* parse an ACE in the same format as print_ace() */
3434 static BOOL parse_ace(struct cli_state *ipc_cli,
3435 POLICY_HND *pol,
3436 SEC_ACE *ace,
3437 BOOL numeric,
3438 char *str)
3440 char *p;
3441 const char *cp;
3442 fstring tok;
3443 unsigned atype, aflags, amask;
3444 DOM_SID sid;
3445 SEC_ACCESS mask;
3446 const struct perm_value *v;
3447 struct perm_value {
3448 const char *perm;
3449 uint32 mask;
3452 /* These values discovered by inspection */
3453 static const struct perm_value special_values[] = {
3454 { "R", 0x00120089 },
3455 { "W", 0x00120116 },
3456 { "X", 0x001200a0 },
3457 { "D", 0x00010000 },
3458 { "P", 0x00040000 },
3459 { "O", 0x00080000 },
3460 { NULL, 0 },
3463 static const struct perm_value standard_values[] = {
3464 { "READ", 0x001200a9 },
3465 { "CHANGE", 0x001301bf },
3466 { "FULL", 0x001f01ff },
3467 { NULL, 0 },
3471 ZERO_STRUCTP(ace);
3472 p = strchr_m(str,':');
3473 if (!p) return False;
3474 *p = '\0';
3475 p++;
3476 /* Try to parse numeric form */
3478 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3479 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3480 goto done;
3483 /* Try to parse text form */
3485 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3486 return False;
3489 cp = p;
3490 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3491 return False;
3494 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3495 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3496 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3497 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3498 } else {
3499 return False;
3502 /* Only numeric form accepted for flags at present */
3504 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3505 sscanf(tok, "%i", &aflags))) {
3506 return False;
3509 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3510 return False;
3513 if (strncmp(tok, "0x", 2) == 0) {
3514 if (sscanf(tok, "%i", &amask) != 1) {
3515 return False;
3517 goto done;
3520 for (v = standard_values; v->perm; v++) {
3521 if (strcmp(tok, v->perm) == 0) {
3522 amask = v->mask;
3523 goto done;
3527 p = tok;
3529 while(*p) {
3530 BOOL found = False;
3532 for (v = special_values; v->perm; v++) {
3533 if (v->perm[0] == *p) {
3534 amask |= v->mask;
3535 found = True;
3539 if (!found) return False;
3540 p++;
3543 if (*p) {
3544 return False;
3547 done:
3548 mask.mask = amask;
3549 init_sec_ace(ace, &sid, atype, mask, aflags);
3550 return True;
3553 /* add an ACE to a list of ACEs in a SEC_ACL */
3554 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3556 SEC_ACL *newacl;
3557 SEC_ACE *aces;
3558 if (! *the_acl) {
3559 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3560 return True;
3563 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3564 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3565 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3566 newacl = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3567 SAFE_FREE(aces);
3568 (*the_acl) = newacl;
3569 return True;
3573 /* parse a ascii version of a security descriptor */
3574 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3575 struct cli_state *ipc_cli,
3576 POLICY_HND *pol,
3577 BOOL numeric,
3578 char *str)
3580 const char *p = str;
3581 fstring tok;
3582 SEC_DESC *ret;
3583 size_t sd_size;
3584 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3585 SEC_ACL *dacl=NULL;
3586 int revision=1;
3588 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3590 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3591 revision = strtol(tok+9, NULL, 16);
3592 continue;
3595 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3596 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3597 if (!owner_sid ||
3598 !convert_string_to_sid(ipc_cli, pol,
3599 numeric,
3600 owner_sid, tok+6)) {
3601 DEBUG(5, ("Failed to parse owner sid\n"));
3602 return NULL;
3604 continue;
3607 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3608 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3609 if (!owner_sid ||
3610 !convert_string_to_sid(ipc_cli, pol,
3611 False,
3612 owner_sid, tok+7)) {
3613 DEBUG(5, ("Failed to parse owner sid\n"));
3614 return NULL;
3616 continue;
3619 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3620 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3621 if (!grp_sid ||
3622 !convert_string_to_sid(ipc_cli, pol,
3623 numeric,
3624 grp_sid, tok+6)) {
3625 DEBUG(5, ("Failed to parse group sid\n"));
3626 return NULL;
3628 continue;
3631 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3632 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3633 if (!grp_sid ||
3634 !convert_string_to_sid(ipc_cli, pol,
3635 False,
3636 grp_sid, tok+6)) {
3637 DEBUG(5, ("Failed to parse group sid\n"));
3638 return NULL;
3640 continue;
3643 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3644 SEC_ACE ace;
3645 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3646 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3647 return NULL;
3649 if(!add_ace(&dacl, &ace, ctx)) {
3650 DEBUG(5, ("Failed to add ACL %s\n", tok));
3651 return NULL;
3653 continue;
3656 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3657 SEC_ACE ace;
3658 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3659 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3660 return NULL;
3662 if(!add_ace(&dacl, &ace, ctx)) {
3663 DEBUG(5, ("Failed to add ACL %s\n", tok));
3664 return NULL;
3666 continue;
3669 DEBUG(5, ("Failed to parse security descriptor\n"));
3670 return NULL;
3673 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3674 owner_sid, grp_sid, NULL, dacl, &sd_size);
3676 SAFE_FREE(grp_sid);
3677 SAFE_FREE(owner_sid);
3679 return ret;
3683 /* Obtain the current dos attributes */
3684 static DOS_ATTR_DESC *dos_attr_query(SMBCCTX *context,
3685 TALLOC_CTX *ctx,
3686 const char *filename,
3687 SMBCSRV *srv)
3689 time_t m_time = 0, a_time = 0, c_time = 0;
3690 SMB_OFF_T size = 0;
3691 uint16 mode = 0;
3692 SMB_INO_T inode = 0;
3693 DOS_ATTR_DESC *ret;
3695 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
3696 if (!ret) {
3697 errno = ENOMEM;
3698 return NULL;
3701 /* Obtain the DOS attributes */
3702 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
3703 &mode, &size,
3704 &c_time, &a_time, &m_time, &inode)) {
3706 errno = smbc_errno(context, &srv->cli);
3707 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
3708 return NULL;
3712 ret->mode = mode;
3713 ret->size = size;
3714 ret->a_time = a_time;
3715 ret->c_time = c_time;
3716 ret->m_time = m_time;
3717 ret->inode = inode;
3719 return ret;
3723 /* parse a ascii version of a security descriptor */
3724 static void dos_attr_parse(SMBCCTX *context,
3725 DOS_ATTR_DESC *dad,
3726 SMBCSRV *srv,
3727 char *str)
3729 const char *p = str;
3730 fstring tok;
3732 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3734 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
3735 dad->mode = strtol(tok+5, NULL, 16);
3736 continue;
3739 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
3740 dad->size = (SMB_OFF_T)atof(tok+5);
3741 continue;
3744 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
3745 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
3746 continue;
3749 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
3750 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
3751 continue;
3754 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
3755 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
3756 continue;
3759 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
3760 dad->inode = (SMB_INO_T)atof(tok+6);
3761 continue;
3766 /*****************************************************
3767 Retrieve the acls for a file.
3768 *******************************************************/
3770 static int cacl_get(SMBCCTX *context, TALLOC_CTX *ctx, SMBCSRV *srv,
3771 struct cli_state *ipc_cli, POLICY_HND *pol,
3772 char *filename, char *attr_name, char *buf, int bufsize)
3774 uint32 i;
3775 int n = 0;
3776 int n_used;
3777 BOOL all;
3778 BOOL all_nt;
3779 BOOL all_nt_acls;
3780 BOOL all_dos;
3781 BOOL some_nt;
3782 BOOL some_dos;
3783 BOOL exclude_nt_revision = False;
3784 BOOL exclude_nt_owner = False;
3785 BOOL exclude_nt_group = False;
3786 BOOL exclude_nt_acl = False;
3787 BOOL exclude_dos_mode = False;
3788 BOOL exclude_dos_size = False;
3789 BOOL exclude_dos_ctime = False;
3790 BOOL exclude_dos_atime = False;
3791 BOOL exclude_dos_mtime = False;
3792 BOOL exclude_dos_inode = False;
3793 BOOL numeric = True;
3794 BOOL determine_size = (bufsize == 0);
3795 int fnum = -1;
3796 SEC_DESC *sd;
3797 fstring sidstr;
3798 fstring name_sandbox;
3799 char *name;
3800 char *pExclude;
3801 char *p;
3802 time_t m_time = 0, a_time = 0, c_time = 0;
3803 SMB_OFF_T size = 0;
3804 uint16 mode = 0;
3805 SMB_INO_T ino = 0;
3806 struct cli_state *cli = &srv->cli;
3808 /* Copy name so we can strip off exclusions (if any are specified) */
3809 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
3811 /* Ensure name is null terminated */
3812 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
3814 /* Play in the sandbox */
3815 name = name_sandbox;
3817 /* If there are any exclusions, point to them and mask them from name */
3818 if ((pExclude = strchr(name, '!')) != NULL)
3820 *pExclude++ = '\0';
3823 all = (StrnCaseCmp(name, "system.*", 8) == 0);
3824 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
3825 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
3826 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
3827 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
3828 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
3829 numeric = (* (name + strlen(name) - 1) != '+');
3831 /* Look for exclusions from "all" requests */
3832 if (all || all_nt || all_dos) {
3834 /* Exclusions are delimited by '!' */
3835 for (; pExclude != NULL; pExclude = (p == NULL ? NULL : p + 1)) {
3837 /* Find end of this exclusion name */
3838 if ((p = strchr(pExclude, '!')) != NULL)
3840 *p = '\0';
3843 /* Which exclusion name is this? */
3844 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
3845 exclude_nt_revision = True;
3847 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
3848 exclude_nt_owner = True;
3850 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
3851 exclude_nt_group = True;
3853 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
3854 exclude_nt_acl = True;
3856 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
3857 exclude_dos_mode = True;
3859 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
3860 exclude_dos_size = True;
3862 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
3863 exclude_dos_ctime = True;
3865 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
3866 exclude_dos_atime = True;
3868 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
3869 exclude_dos_mtime = True;
3871 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
3872 exclude_dos_inode = True;
3874 else {
3875 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
3876 pExclude));
3877 errno = ENOATTR;
3878 return -1;
3883 n_used = 0;
3886 * If we are (possibly) talking to an NT or new system and some NT
3887 * attributes have been requested...
3889 if (ipc_cli && (all || some_nt || all_nt_acls)) {
3890 /* Point to the portion after "system.nt_sec_desc." */
3891 name += 19; /* if (all) this will be invalid but unused */
3893 /* ... then obtain any NT attributes which were requested */
3894 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3896 if (fnum == -1) {
3897 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3898 filename, cli_errstr(cli)));
3899 errno = 0;
3900 return -1;
3903 sd = cli_query_secdesc(cli, fnum, ctx);
3905 if (!sd) {
3906 DEBUG(5,
3907 ("cacl_get Failed to query old descriptor\n"));
3908 errno = 0;
3909 return -1;
3912 cli_close(cli, fnum);
3914 if (! exclude_nt_revision) {
3915 if (all || all_nt) {
3916 if (determine_size) {
3917 p = talloc_asprintf(ctx,
3918 "REVISION:%d",
3919 sd->revision);
3920 if (!p) {
3921 errno = ENOMEM;
3922 return -1;
3924 n = strlen(p);
3925 } else {
3926 n = snprintf(buf, bufsize,
3927 "REVISION:%d", sd->revision);
3929 } else if (StrCaseCmp(name, "revision") == 0) {
3930 if (determine_size) {
3931 p = talloc_asprintf(ctx, "%d",
3932 sd->revision);
3933 if (!p) {
3934 errno = ENOMEM;
3935 return -1;
3937 n = strlen(p);
3938 } else {
3939 n = snprintf(buf, bufsize, "%d",
3940 sd->revision);
3944 if (!determine_size && n > bufsize) {
3945 errno = ERANGE;
3946 return -1;
3948 buf += n;
3949 n_used += n;
3950 bufsize -= n;
3953 if (! exclude_nt_owner) {
3954 /* Get owner and group sid */
3955 if (sd->owner_sid) {
3956 convert_sid_to_string(ipc_cli, pol,
3957 sidstr,
3958 numeric,
3959 sd->owner_sid);
3960 } else {
3961 fstrcpy(sidstr, "");
3964 if (all || all_nt) {
3965 if (determine_size) {
3966 p = talloc_asprintf(ctx, ",OWNER:%s",
3967 sidstr);
3968 if (!p) {
3969 errno = ENOMEM;
3970 return -1;
3972 n = strlen(p);
3973 } else {
3974 n = snprintf(buf, bufsize,
3975 ",OWNER:%s", sidstr);
3977 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3978 if (determine_size) {
3979 p = talloc_asprintf(ctx, "%s", sidstr);
3980 if (!p) {
3981 errno = ENOMEM;
3982 return -1;
3984 n = strlen(p);
3985 } else {
3986 n = snprintf(buf, bufsize, "%s",
3987 sidstr);
3991 if (!determine_size && n > bufsize) {
3992 errno = ERANGE;
3993 return -1;
3995 buf += n;
3996 n_used += n;
3997 bufsize -= n;
4000 if (! exclude_nt_group) {
4001 if (sd->grp_sid) {
4002 convert_sid_to_string(ipc_cli, pol,
4003 sidstr, numeric,
4004 sd->grp_sid);
4005 } else {
4006 fstrcpy(sidstr, "");
4009 if (all || all_nt) {
4010 if (determine_size) {
4011 p = talloc_asprintf(ctx, ",GROUP:%s",
4012 sidstr);
4013 if (!p) {
4014 errno = ENOMEM;
4015 return -1;
4017 n = strlen(p);
4018 } else {
4019 n = snprintf(buf, bufsize,
4020 ",GROUP:%s", sidstr);
4022 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4023 if (determine_size) {
4024 p = talloc_asprintf(ctx, "%s", sidstr);
4025 if (!p) {
4026 errno = ENOMEM;
4027 return -1;
4029 n = strlen(p);
4030 } else {
4031 n = snprintf(buf, bufsize, "%s", sidstr);
4035 if (!determine_size && n > bufsize) {
4036 errno = ERANGE;
4037 return -1;
4039 buf += n;
4040 n_used += n;
4041 bufsize -= n;
4044 if (! exclude_nt_acl) {
4045 /* Add aces to value buffer */
4046 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4048 SEC_ACE *ace = &sd->dacl->ace[i];
4049 convert_sid_to_string(ipc_cli, pol,
4050 sidstr, numeric,
4051 &ace->trustee);
4053 if (all || all_nt) {
4054 if (determine_size) {
4055 p = talloc_asprintf(
4056 ctx,
4057 ",ACL:"
4058 "%s:%d/%d/0x%08x",
4059 sidstr,
4060 ace->type,
4061 ace->flags,
4062 ace->info.mask);
4063 if (!p) {
4064 errno = ENOMEM;
4065 return -1;
4067 n = strlen(p);
4068 } else {
4069 n = snprintf(
4070 buf, bufsize,
4071 ",ACL:%s:%d/%d/0x%08x",
4072 sidstr,
4073 ace->type,
4074 ace->flags,
4075 ace->info.mask);
4077 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4078 StrCaseCmp(name + 3, sidstr) == 0) ||
4079 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4080 StrCaseCmp(name + 4, sidstr) == 0)) {
4081 if (determine_size) {
4082 p = talloc_asprintf(
4083 ctx,
4084 "%d/%d/0x%08x",
4085 ace->type,
4086 ace->flags,
4087 ace->info.mask);
4088 if (!p) {
4089 errno = ENOMEM;
4090 return -1;
4092 n = strlen(p);
4093 } else {
4094 n = snprintf(buf, bufsize,
4095 "%d/%d/0x%08x",
4096 ace->type,
4097 ace->flags,
4098 ace->info.mask);
4100 } else if (all_nt_acls) {
4101 if (determine_size) {
4102 p = talloc_asprintf(
4103 ctx,
4104 "%s%s:%d/%d/0x%08x",
4105 i ? "," : "",
4106 sidstr,
4107 ace->type,
4108 ace->flags,
4109 ace->info.mask);
4110 if (!p) {
4111 errno = ENOMEM;
4112 return -1;
4114 n = strlen(p);
4115 } else {
4116 n = snprintf(buf, bufsize,
4117 "%s%s:%d/%d/0x%08x",
4118 i ? "," : "",
4119 sidstr,
4120 ace->type,
4121 ace->flags,
4122 ace->info.mask);
4125 if (n > bufsize) {
4126 errno = ERANGE;
4127 return -1;
4129 buf += n;
4130 n_used += n;
4131 bufsize -= n;
4135 /* Restore name pointer to its original value */
4136 name -= 19;
4139 if (all || some_dos) {
4140 /* Point to the portion after "system.dos_attr." */
4141 name += 16; /* if (all) this will be invalid but unused */
4143 /* Obtain the DOS attributes */
4144 if (!smbc_getatr(context, srv, filename, &mode, &size,
4145 &c_time, &a_time, &m_time, &ino)) {
4147 errno = smbc_errno(context, &srv->cli);
4148 return -1;
4152 if (! exclude_dos_mode) {
4153 if (all || all_dos) {
4154 if (determine_size) {
4155 p = talloc_asprintf(ctx,
4156 "%sMODE:0x%x",
4157 (ipc_cli &&
4158 (all || some_nt)
4159 ? ","
4160 : ""),
4161 mode);
4162 if (!p) {
4163 errno = ENOMEM;
4164 return -1;
4166 n = strlen(p);
4167 } else {
4168 n = snprintf(buf, bufsize,
4169 "%sMODE:0x%x",
4170 (ipc_cli &&
4171 (all || some_nt)
4172 ? ","
4173 : ""),
4174 mode);
4176 } else if (StrCaseCmp(name, "mode") == 0) {
4177 if (determine_size) {
4178 p = talloc_asprintf(ctx, "0x%x", mode);
4179 if (!p) {
4180 errno = ENOMEM;
4181 return -1;
4183 n = strlen(p);
4184 } else {
4185 n = snprintf(buf, bufsize, "0x%x", mode);
4189 if (!determine_size && n > bufsize) {
4190 errno = ERANGE;
4191 return -1;
4193 buf += n;
4194 n_used += n;
4195 bufsize -= n;
4198 if (! exclude_dos_size) {
4199 if (all || all_dos) {
4200 if (determine_size) {
4201 p = talloc_asprintf(
4202 ctx,
4203 ",SIZE:%.0f",
4204 (double)size);
4205 if (!p) {
4206 errno = ENOMEM;
4207 return -1;
4209 n = strlen(p);
4210 } else {
4211 n = snprintf(buf, bufsize,
4212 ",SIZE:%.0f",
4213 (double)size);
4215 } else if (StrCaseCmp(name, "size") == 0) {
4216 if (determine_size) {
4217 p = talloc_asprintf(
4218 ctx,
4219 "%.0f",
4220 (double)size);
4221 if (!p) {
4222 errno = ENOMEM;
4223 return -1;
4225 n = strlen(p);
4226 } else {
4227 n = snprintf(buf, bufsize,
4228 "%.0f",
4229 (double)size);
4233 if (!determine_size && n > bufsize) {
4234 errno = ERANGE;
4235 return -1;
4237 buf += n;
4238 n_used += n;
4239 bufsize -= n;
4242 if (! exclude_dos_ctime) {
4243 if (all || all_dos) {
4244 if (determine_size) {
4245 p = talloc_asprintf(ctx,
4246 ",C_TIME:%lu",
4247 c_time);
4248 if (!p) {
4249 errno = ENOMEM;
4250 return -1;
4252 n = strlen(p);
4253 } else {
4254 n = snprintf(buf, bufsize,
4255 ",C_TIME:%lu", c_time);
4257 } else if (StrCaseCmp(name, "c_time") == 0) {
4258 if (determine_size) {
4259 p = talloc_asprintf(ctx, "%lu", c_time);
4260 if (!p) {
4261 errno = ENOMEM;
4262 return -1;
4264 n = strlen(p);
4265 } else {
4266 n = snprintf(buf, bufsize, "%lu", c_time);
4270 if (!determine_size && n > bufsize) {
4271 errno = ERANGE;
4272 return -1;
4274 buf += n;
4275 n_used += n;
4276 bufsize -= n;
4279 if (! exclude_dos_atime) {
4280 if (all || all_dos) {
4281 if (determine_size) {
4282 p = talloc_asprintf(ctx,
4283 ",A_TIME:%lu",
4284 a_time);
4285 if (!p) {
4286 errno = ENOMEM;
4287 return -1;
4289 n = strlen(p);
4290 } else {
4291 n = snprintf(buf, bufsize,
4292 ",A_TIME:%lu", a_time);
4294 } else if (StrCaseCmp(name, "a_time") == 0) {
4295 if (determine_size) {
4296 p = talloc_asprintf(ctx, "%lu", a_time);
4297 if (!p) {
4298 errno = ENOMEM;
4299 return -1;
4301 n = strlen(p);
4302 } else {
4303 n = snprintf(buf, bufsize, "%lu", a_time);
4307 if (!determine_size && n > bufsize) {
4308 errno = ERANGE;
4309 return -1;
4311 buf += n;
4312 n_used += n;
4313 bufsize -= n;
4316 if (! exclude_dos_mtime) {
4317 if (all || all_dos) {
4318 if (determine_size) {
4319 p = talloc_asprintf(ctx,
4320 ",M_TIME:%lu",
4321 m_time);
4322 if (!p) {
4323 errno = ENOMEM;
4324 return -1;
4326 n = strlen(p);
4327 } else {
4328 n = snprintf(buf, bufsize,
4329 ",M_TIME:%lu", m_time);
4331 } else if (StrCaseCmp(name, "m_time") == 0) {
4332 if (determine_size) {
4333 p = talloc_asprintf(ctx, "%lu", m_time);
4334 if (!p) {
4335 errno = ENOMEM;
4336 return -1;
4338 n = strlen(p);
4339 } else {
4340 n = snprintf(buf, bufsize, "%lu", m_time);
4344 if (!determine_size && n > bufsize) {
4345 errno = ERANGE;
4346 return -1;
4348 buf += n;
4349 n_used += n;
4350 bufsize -= n;
4353 if (! exclude_dos_inode) {
4354 if (all || all_dos) {
4355 if (determine_size) {
4356 p = talloc_asprintf(
4357 ctx,
4358 ",INODE:%.0f",
4359 (double)ino);
4360 if (!p) {
4361 errno = ENOMEM;
4362 return -1;
4364 n = strlen(p);
4365 } else {
4366 n = snprintf(buf, bufsize,
4367 ",INODE:%.0f",
4368 (double) ino);
4370 } else if (StrCaseCmp(name, "inode") == 0) {
4371 if (determine_size) {
4372 p = talloc_asprintf(
4373 ctx,
4374 "%.0f",
4375 (double) ino);
4376 if (!p) {
4377 errno = ENOMEM;
4378 return -1;
4380 n = strlen(p);
4381 } else {
4382 n = snprintf(buf, bufsize,
4383 "%.0f",
4384 (double) ino);
4388 if (!determine_size && n > bufsize) {
4389 errno = ERANGE;
4390 return -1;
4392 buf += n;
4393 n_used += n;
4394 bufsize -= n;
4397 /* Restore name pointer to its original value */
4398 name -= 16;
4401 if (n_used == 0) {
4402 errno = ENOATTR;
4403 return -1;
4406 return n_used;
4410 /*****************************************************
4411 set the ACLs on a file given an ascii description
4412 *******************************************************/
4413 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
4414 struct cli_state *ipc_cli, POLICY_HND *pol,
4415 const char *filename, const char *the_acl,
4416 int mode, int flags)
4418 int fnum;
4419 int err = 0;
4420 SEC_DESC *sd = NULL, *old;
4421 SEC_ACL *dacl = NULL;
4422 DOM_SID *owner_sid = NULL;
4423 DOM_SID *grp_sid = NULL;
4424 uint32 i, j;
4425 size_t sd_size;
4426 int ret = 0;
4427 char *p;
4428 BOOL numeric = True;
4430 /* the_acl will be null for REMOVE_ALL operations */
4431 if (the_acl) {
4432 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4433 p > the_acl &&
4434 p[-1] != '+');
4436 /* if this is to set the entire ACL... */
4437 if (*the_acl == '*') {
4438 /* ... then increment past the first colon */
4439 the_acl = p + 1;
4442 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4443 CONST_DISCARD(char *, the_acl));
4445 if (!sd) {
4446 errno = EINVAL;
4447 return -1;
4451 /* The desired access below is the only one I could find that works
4452 with NT4, W2KP and Samba */
4454 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4456 if (fnum == -1) {
4457 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4458 filename, cli_errstr(cli)));
4459 errno = 0;
4460 return -1;
4463 old = cli_query_secdesc(cli, fnum, ctx);
4465 if (!old) {
4466 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4467 errno = 0;
4468 return -1;
4471 cli_close(cli, fnum);
4473 switch (mode) {
4474 case SMBC_XATTR_MODE_REMOVE_ALL:
4475 old->dacl->num_aces = 0;
4476 SAFE_FREE(old->dacl->ace);
4477 SAFE_FREE(old->dacl);
4478 old->off_dacl = 0;
4479 dacl = old->dacl;
4480 break;
4482 case SMBC_XATTR_MODE_REMOVE:
4483 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4484 BOOL found = False;
4486 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4487 if (sec_ace_equal(&sd->dacl->ace[i],
4488 &old->dacl->ace[j])) {
4489 uint32 k;
4490 for (k=j; k<old->dacl->num_aces-1;k++) {
4491 old->dacl->ace[k] = old->dacl->ace[k+1];
4493 old->dacl->num_aces--;
4494 if (old->dacl->num_aces == 0) {
4495 SAFE_FREE(old->dacl->ace);
4496 SAFE_FREE(old->dacl);
4497 old->off_dacl = 0;
4499 found = True;
4500 dacl = old->dacl;
4501 break;
4505 if (!found) {
4506 err = ENOATTR;
4507 ret = -1;
4508 goto failed;
4511 break;
4513 case SMBC_XATTR_MODE_ADD:
4514 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4515 BOOL found = False;
4517 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4518 if (sid_equal(&sd->dacl->ace[i].trustee,
4519 &old->dacl->ace[j].trustee)) {
4520 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4521 err = EEXIST;
4522 ret = -1;
4523 goto failed;
4525 old->dacl->ace[j] = sd->dacl->ace[i];
4526 ret = -1;
4527 found = True;
4531 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4532 err = ENOATTR;
4533 ret = -1;
4534 goto failed;
4537 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4538 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4541 dacl = old->dacl;
4542 break;
4544 case SMBC_XATTR_MODE_SET:
4545 old = sd;
4546 owner_sid = old->owner_sid;
4547 grp_sid = old->grp_sid;
4548 dacl = old->dacl;
4549 break;
4551 case SMBC_XATTR_MODE_CHOWN:
4552 owner_sid = sd->owner_sid;
4553 break;
4555 case SMBC_XATTR_MODE_CHGRP:
4556 grp_sid = sd->grp_sid;
4557 break;
4560 /* Denied ACE entries must come before allowed ones */
4561 sort_acl(old->dacl);
4563 /* Create new security descriptor and set it */
4564 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4565 owner_sid, grp_sid, NULL, dacl, &sd_size);
4567 fnum = cli_nt_create(cli, filename,
4568 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4570 if (fnum == -1) {
4571 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4572 filename, cli_errstr(cli)));
4573 errno = 0;
4574 return -1;
4577 if (!cli_set_secdesc(cli, fnum, sd)) {
4578 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4579 ret = -1;
4582 /* Clean up */
4584 failed:
4585 cli_close(cli, fnum);
4587 if (err != 0) {
4588 errno = err;
4591 return ret;
4595 int smbc_setxattr_ctx(SMBCCTX *context,
4596 const char *fname,
4597 const char *name,
4598 const void *value,
4599 size_t size,
4600 int flags)
4602 int ret;
4603 int ret2;
4604 SMBCSRV *srv;
4605 SMBCSRV *ipc_srv;
4606 fstring server, share, user, password, workgroup;
4607 pstring path;
4608 TALLOC_CTX *ctx;
4609 POLICY_HND pol;
4610 DOS_ATTR_DESC *dad;
4612 if (!context || !context->internal ||
4613 !context->internal->_initialized) {
4615 errno = EINVAL; /* Best I can think of ... */
4616 return -1;
4620 if (!fname) {
4622 errno = EINVAL;
4623 return -1;
4627 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n", fname, name, (int) size, (const char*)value));
4629 if (smbc_parse_path(context, fname,
4630 server, sizeof(server),
4631 share, sizeof(share),
4632 path, sizeof(path),
4633 user, sizeof(user),
4634 password, sizeof(password),
4635 NULL, 0)) {
4636 errno = EINVAL;
4637 return -1;
4640 if (user[0] == (char)0) fstrcpy(user, context->user);
4642 fstrcpy(workgroup, context->workgroup);
4644 srv = smbc_server(context, server, share, workgroup, user, password);
4645 if (!srv) {
4646 return -1; /* errno set by smbc_server */
4649 if (! srv->no_nt_session) {
4650 ipc_srv = smbc_attr_server(context, server, share,
4651 workgroup, user, password,
4652 &pol);
4653 srv->no_nt_session = True;
4654 } else {
4655 ipc_srv = NULL;
4658 ctx = talloc_init("smbc_setxattr");
4659 if (!ctx) {
4660 errno = ENOMEM;
4661 return -1;
4665 * Are they asking to set the entire set of known attributes?
4667 if (StrCaseCmp(name, "system.*") == 0 ||
4668 StrCaseCmp(name, "system.*+") == 0) {
4669 /* Yup. */
4670 char *namevalue =
4671 talloc_asprintf(ctx, "%s:%s", name+7, (const char *) value);
4672 if (! namevalue) {
4673 errno = ENOMEM;
4674 ret = -1;
4675 return -1;
4678 if (ipc_srv) {
4679 ret = cacl_set(ctx, &srv->cli,
4680 &ipc_srv->cli, &pol, path,
4681 namevalue,
4682 (*namevalue == '*'
4683 ? SMBC_XATTR_MODE_SET
4684 : SMBC_XATTR_MODE_ADD),
4685 flags);
4686 } else {
4687 ret = 0;
4690 /* get a DOS Attribute Descriptor with current attributes */
4691 dad = dos_attr_query(context, ctx, path, srv);
4692 if (dad) {
4693 /* Overwrite old with new, using what was provided */
4694 dos_attr_parse(context, dad, srv, namevalue);
4696 /* Set the new DOS attributes */
4697 if (! smbc_setatr(context, srv, path,
4698 dad->c_time,
4699 dad->a_time,
4700 dad->m_time,
4701 dad->mode)) {
4703 /* cause failure if NT failed too */
4704 dad = NULL;
4708 /* we only fail if both NT and DOS sets failed */
4709 if (ret < 0 && ! dad) {
4710 ret = -1; /* in case dad was null */
4712 else {
4713 ret = 0;
4716 talloc_destroy(ctx);
4717 return ret;
4721 * Are they asking to set an access control element or to set
4722 * the entire access control list?
4724 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4725 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4726 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4727 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4728 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4730 /* Yup. */
4731 char *namevalue =
4732 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4734 if (! ipc_srv) {
4735 ret = -1; /* errno set by smbc_server() */
4737 else if (! namevalue) {
4738 errno = ENOMEM;
4739 ret = -1;
4740 } else {
4741 ret = cacl_set(ctx, &srv->cli,
4742 &ipc_srv->cli, &pol, path,
4743 namevalue,
4744 (*namevalue == '*'
4745 ? SMBC_XATTR_MODE_SET
4746 : SMBC_XATTR_MODE_ADD),
4747 flags);
4749 talloc_destroy(ctx);
4750 return ret;
4754 * Are they asking to set the owner?
4756 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4757 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
4759 /* Yup. */
4760 char *namevalue =
4761 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4763 if (! ipc_srv) {
4765 ret = -1; /* errno set by smbc_server() */
4767 else if (! namevalue) {
4768 errno = ENOMEM;
4769 ret = -1;
4770 } else {
4771 ret = cacl_set(ctx, &srv->cli,
4772 &ipc_srv->cli, &pol, path,
4773 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4775 talloc_destroy(ctx);
4776 return ret;
4780 * Are they asking to set the group?
4782 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4783 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
4785 /* Yup. */
4786 char *namevalue =
4787 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4789 if (! ipc_srv) {
4790 /* errno set by smbc_server() */
4791 ret = -1;
4793 else if (! namevalue) {
4794 errno = ENOMEM;
4795 ret = -1;
4796 } else {
4797 ret = cacl_set(ctx, &srv->cli,
4798 &ipc_srv->cli, &pol, path,
4799 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4801 talloc_destroy(ctx);
4802 return ret;
4806 * Are they asking to set a DOS attribute?
4808 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4809 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4810 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4811 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4812 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
4814 /* get a DOS Attribute Descriptor with current attributes */
4815 dad = dos_attr_query(context, ctx, path, srv);
4816 if (dad) {
4817 char *namevalue =
4818 talloc_asprintf(ctx, "%s:%s", name+16, (const char *) value);
4819 if (! namevalue) {
4820 errno = ENOMEM;
4821 ret = -1;
4822 } else {
4823 /* Overwrite old with provided new params */
4824 dos_attr_parse(context, dad, srv, namevalue);
4826 /* Set the new DOS attributes */
4827 ret2 = smbc_setatr(context, srv, path,
4828 dad->c_time,
4829 dad->a_time,
4830 dad->m_time,
4831 dad->mode);
4833 /* ret2 has True (success) / False (failure) */
4834 if (ret2) {
4835 ret = 0;
4836 } else {
4837 ret = -1;
4840 } else {
4841 ret = -1;
4844 talloc_destroy(ctx);
4845 return ret;
4848 /* Unsupported attribute name */
4849 talloc_destroy(ctx);
4850 errno = EINVAL;
4851 return -1;
4854 int smbc_getxattr_ctx(SMBCCTX *context,
4855 const char *fname,
4856 const char *name,
4857 const void *value,
4858 size_t size)
4860 int ret;
4861 SMBCSRV *srv;
4862 SMBCSRV *ipc_srv;
4863 fstring server, share, user, password, workgroup;
4864 pstring path;
4865 TALLOC_CTX *ctx;
4866 POLICY_HND pol;
4869 if (!context || !context->internal ||
4870 !context->internal->_initialized) {
4872 errno = EINVAL; /* Best I can think of ... */
4873 return -1;
4877 if (!fname) {
4879 errno = EINVAL;
4880 return -1;
4884 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
4886 if (smbc_parse_path(context, fname,
4887 server, sizeof(server),
4888 share, sizeof(share),
4889 path, sizeof(path),
4890 user, sizeof(user),
4891 password, sizeof(password),
4892 NULL, 0)) {
4893 errno = EINVAL;
4894 return -1;
4897 if (user[0] == (char)0) fstrcpy(user, context->user);
4899 fstrcpy(workgroup, context->workgroup);
4901 srv = smbc_server(context, server, share, workgroup, user, password);
4902 if (!srv) {
4903 return -1; /* errno set by smbc_server */
4906 if (! srv->no_nt_session) {
4907 ipc_srv = smbc_attr_server(context, server, share,
4908 workgroup, user, password,
4909 &pol);
4910 if (! ipc_srv) {
4911 srv->no_nt_session = True;
4913 } else {
4914 ipc_srv = NULL;
4917 ctx = talloc_init("smbc:getxattr");
4918 if (!ctx) {
4919 errno = ENOMEM;
4920 return -1;
4923 /* Are they requesting a supported attribute? */
4924 if (StrCaseCmp(name, "system.*") == 0 ||
4925 StrnCaseCmp(name, "system.*!", 9) == 0 ||
4926 StrCaseCmp(name, "system.*+") == 0 ||
4927 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
4928 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4929 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
4930 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4931 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
4932 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4933 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4934 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
4935 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4936 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
4937 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4938 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
4939 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4940 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
4941 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4942 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
4943 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4944 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4945 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
4946 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
4948 /* Yup. */
4949 ret = cacl_get(context, ctx, srv,
4950 ipc_srv == NULL ? NULL : &ipc_srv->cli,
4951 &pol, path,
4952 CONST_DISCARD(char *, name),
4953 CONST_DISCARD(char *, value), size);
4954 if (ret < 0 && errno == 0) {
4955 errno = smbc_errno(context, &srv->cli);
4957 talloc_destroy(ctx);
4958 return ret;
4961 /* Unsupported attribute name */
4962 talloc_destroy(ctx);
4963 errno = EINVAL;
4964 return -1;
4968 int smbc_removexattr_ctx(SMBCCTX *context,
4969 const char *fname,
4970 const char *name)
4972 int ret;
4973 SMBCSRV *srv;
4974 SMBCSRV *ipc_srv;
4975 fstring server, share, user, password, workgroup;
4976 pstring path;
4977 TALLOC_CTX *ctx;
4978 POLICY_HND pol;
4980 if (!context || !context->internal ||
4981 !context->internal->_initialized) {
4983 errno = EINVAL; /* Best I can think of ... */
4984 return -1;
4988 if (!fname) {
4990 errno = EINVAL;
4991 return -1;
4995 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
4997 if (smbc_parse_path(context, fname,
4998 server, sizeof(server),
4999 share, sizeof(share),
5000 path, sizeof(path),
5001 user, sizeof(user),
5002 password, sizeof(password),
5003 NULL, 0)) {
5004 errno = EINVAL;
5005 return -1;
5008 if (user[0] == (char)0) fstrcpy(user, context->user);
5010 fstrcpy(workgroup, context->workgroup);
5012 srv = smbc_server(context, server, share, workgroup, user, password);
5013 if (!srv) {
5014 return -1; /* errno set by smbc_server */
5017 if (! srv->no_nt_session) {
5018 ipc_srv = smbc_attr_server(context, server, share,
5019 workgroup, user, password,
5020 &pol);
5021 srv->no_nt_session = True;
5022 } else {
5023 ipc_srv = NULL;
5026 if (! ipc_srv) {
5027 return -1; /* errno set by smbc_attr_server */
5030 ctx = talloc_init("smbc_removexattr");
5031 if (!ctx) {
5032 errno = ENOMEM;
5033 return -1;
5036 /* Are they asking to set the entire ACL? */
5037 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5038 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5040 /* Yup. */
5041 ret = cacl_set(ctx, &srv->cli,
5042 &ipc_srv->cli, &pol, path,
5043 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5044 talloc_destroy(ctx);
5045 return ret;
5049 * Are they asking to remove one or more spceific security descriptor
5050 * attributes?
5052 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5053 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5054 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5055 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5056 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5057 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5058 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5060 /* Yup. */
5061 ret = cacl_set(ctx, &srv->cli,
5062 &ipc_srv->cli, &pol, path,
5063 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5064 talloc_destroy(ctx);
5065 return ret;
5068 /* Unsupported attribute name */
5069 talloc_destroy(ctx);
5070 errno = EINVAL;
5071 return -1;
5074 int smbc_listxattr_ctx(SMBCCTX *context,
5075 const char *fname,
5076 char *list,
5077 size_t size)
5080 * This isn't quite what listxattr() is supposed to do. This returns
5081 * the complete set of attribute names, always, rather than only those
5082 * attribute names which actually exist for a file. Hmmm...
5084 const char supported[] =
5085 "system.*\0"
5086 "system.*+\0"
5087 "system.nt_sec_desc.revision\0"
5088 "system.nt_sec_desc.owner\0"
5089 "system.nt_sec_desc.owner+\0"
5090 "system.nt_sec_desc.group\0"
5091 "system.nt_sec_desc.group+\0"
5092 "system.nt_sec_desc.acl.*\0"
5093 "system.nt_sec_desc.acl\0"
5094 "system.nt_sec_desc.acl+\0"
5095 "system.nt_sec_desc.*\0"
5096 "system.nt_sec_desc.*+\0"
5097 "system.dos_attr.*\0"
5098 "system.dos_attr.mode\0"
5099 "system.dos_attr.c_time\0"
5100 "system.dos_attr.a_time\0"
5101 "system.dos_attr.m_time\0"
5104 if (size == 0) {
5105 return sizeof(supported);
5108 if (sizeof(supported) > size) {
5109 errno = ERANGE;
5110 return -1;
5113 /* this can't be strcpy() because there are embedded null characters */
5114 memcpy(list, supported, sizeof(supported));
5115 return sizeof(supported);
5120 * Open a print file to be written to by other calls
5123 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
5125 fstring server, share, user, password;
5126 pstring path;
5128 if (!context || !context->internal ||
5129 !context->internal->_initialized) {
5131 errno = EINVAL;
5132 return NULL;
5136 if (!fname) {
5138 errno = EINVAL;
5139 return NULL;
5143 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5145 if (smbc_parse_path(context, fname,
5146 server, sizeof(server),
5147 share, sizeof(share),
5148 path, sizeof(path),
5149 user, sizeof(user),
5150 password, sizeof(password),
5151 NULL, 0)) {
5152 errno = EINVAL;
5153 return NULL;
5156 /* What if the path is empty, or the file exists? */
5158 return context->open(context, fname, O_WRONLY, 666);
5163 * Routine to print a file on a remote server ...
5165 * We open the file, which we assume to be on a remote server, and then
5166 * copy it to a print file on the share specified by printq.
5169 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
5171 SMBCFILE *fid1, *fid2;
5172 int bytes, saverr, tot_bytes = 0;
5173 char buf[4096];
5175 if (!c_file || !c_file->internal->_initialized || !c_print ||
5176 !c_print->internal->_initialized) {
5178 errno = EINVAL;
5179 return -1;
5183 if (!fname && !printq) {
5185 errno = EINVAL;
5186 return -1;
5190 /* Try to open the file for reading ... */
5192 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5194 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5195 return -1; /* smbc_open sets errno */
5199 /* Now, try to open the printer file for writing */
5201 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5203 saverr = errno; /* Save errno */
5204 c_file->close_fn(c_file, fid1);
5205 errno = saverr;
5206 return -1;
5210 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5212 tot_bytes += bytes;
5214 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5216 saverr = errno;
5217 c_file->close_fn(c_file, fid1);
5218 c_print->close_fn(c_print, fid2);
5219 errno = saverr;
5225 saverr = errno;
5227 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5228 c_print->close_fn(c_print, fid2);
5230 if (bytes < 0) {
5232 errno = saverr;
5233 return -1;
5237 return tot_bytes;
5242 * Routine to list print jobs on a printer share ...
5245 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
5247 SMBCSRV *srv;
5248 fstring server, share, user, password, workgroup;
5249 pstring path;
5251 if (!context || !context->internal ||
5252 !context->internal->_initialized) {
5254 errno = EINVAL;
5255 return -1;
5259 if (!fname) {
5261 errno = EINVAL;
5262 return -1;
5266 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5268 if (smbc_parse_path(context, fname,
5269 server, sizeof(server),
5270 share, sizeof(share),
5271 path, sizeof(path),
5272 user, sizeof(user),
5273 password, sizeof(password),
5274 NULL, 0)) {
5275 errno = EINVAL;
5276 return -1;
5279 if (user[0] == (char)0) fstrcpy(user, context->user);
5281 fstrcpy(workgroup, context->workgroup);
5283 srv = smbc_server(context, server, share, workgroup, user, password);
5285 if (!srv) {
5287 return -1; /* errno set by smbc_server */
5291 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
5293 errno = smbc_errno(context, &srv->cli);
5294 return -1;
5298 return 0;
5303 * Delete a print job from a remote printer share
5306 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
5308 SMBCSRV *srv;
5309 fstring server, share, user, password, workgroup;
5310 pstring path;
5311 int err;
5313 if (!context || !context->internal ||
5314 !context->internal->_initialized) {
5316 errno = EINVAL;
5317 return -1;
5321 if (!fname) {
5323 errno = EINVAL;
5324 return -1;
5328 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5330 if (smbc_parse_path(context, fname,
5331 server, sizeof(server),
5332 share, sizeof(share),
5333 path, sizeof(path),
5334 user, sizeof(user),
5335 password, sizeof(password),
5336 NULL, 0)) {
5337 errno = EINVAL;
5338 return -1;
5341 if (user[0] == (char)0) fstrcpy(user, context->user);
5343 fstrcpy(workgroup, context->workgroup);
5345 srv = smbc_server(context, server, share, workgroup, user, password);
5347 if (!srv) {
5349 return -1; /* errno set by smbc_server */
5353 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5355 if (err < 0)
5356 errno = smbc_errno(context, &srv->cli);
5357 else if (err == ERRnosuchprintjob)
5358 errno = EINVAL;
5359 return -1;
5363 return 0;
5368 * Get a new empty handle to fill in with your own info
5370 SMBCCTX * smbc_new_context(void)
5372 SMBCCTX * context;
5374 context = SMB_MALLOC_P(SMBCCTX);
5375 if (!context) {
5376 errno = ENOMEM;
5377 return NULL;
5380 ZERO_STRUCTP(context);
5382 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5383 if (!context->internal) {
5384 errno = ENOMEM;
5385 return NULL;
5388 ZERO_STRUCTP(context->internal);
5391 /* ADD REASONABLE DEFAULTS */
5392 context->debug = 0;
5393 context->timeout = 20000; /* 20 seconds */
5395 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5396 context->options.urlencode_readdir_entries = False;/* backward compat */
5397 context->options.one_share_per_server = False;/* backward compat */
5399 context->open = smbc_open_ctx;
5400 context->creat = smbc_creat_ctx;
5401 context->read = smbc_read_ctx;
5402 context->write = smbc_write_ctx;
5403 context->close_fn = smbc_close_ctx;
5404 context->unlink = smbc_unlink_ctx;
5405 context->rename = smbc_rename_ctx;
5406 context->lseek = smbc_lseek_ctx;
5407 context->stat = smbc_stat_ctx;
5408 context->fstat = smbc_fstat_ctx;
5409 context->opendir = smbc_opendir_ctx;
5410 context->closedir = smbc_closedir_ctx;
5411 context->readdir = smbc_readdir_ctx;
5412 context->getdents = smbc_getdents_ctx;
5413 context->mkdir = smbc_mkdir_ctx;
5414 context->rmdir = smbc_rmdir_ctx;
5415 context->telldir = smbc_telldir_ctx;
5416 context->lseekdir = smbc_lseekdir_ctx;
5417 context->fstatdir = smbc_fstatdir_ctx;
5418 context->chmod = smbc_chmod_ctx;
5419 context->utimes = smbc_utimes_ctx;
5420 context->setxattr = smbc_setxattr_ctx;
5421 context->getxattr = smbc_getxattr_ctx;
5422 context->removexattr = smbc_removexattr_ctx;
5423 context->listxattr = smbc_listxattr_ctx;
5424 context->open_print_job = smbc_open_print_job_ctx;
5425 context->print_file = smbc_print_file_ctx;
5426 context->list_print_jobs = smbc_list_print_jobs_ctx;
5427 context->unlink_print_job = smbc_unlink_print_job_ctx;
5429 context->callbacks.check_server_fn = smbc_check_server;
5430 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5432 smbc_default_cache_functions(context);
5434 return context;
5438 * Free a context
5440 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5441 * and thus you'll be leaking memory if not handled properly.
5444 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
5446 if (!context) {
5447 errno = EBADF;
5448 return 1;
5451 if (shutdown_ctx) {
5452 SMBCFILE * f;
5453 DEBUG(1,("Performing aggressive shutdown.\n"));
5455 f = context->internal->_files;
5456 while (f) {
5457 context->close_fn(context, f);
5458 f = f->next;
5460 context->internal->_files = NULL;
5462 /* First try to remove the servers the nice way. */
5463 if (context->callbacks.purge_cached_fn(context)) {
5464 SMBCSRV * s;
5465 SMBCSRV * next;
5466 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
5467 s = context->internal->_servers;
5468 while (s) {
5469 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
5470 cli_shutdown(&s->cli);
5471 context->callbacks.remove_cached_srv_fn(context, s);
5472 next = s->next;
5473 DLIST_REMOVE(context->internal->_servers, s);
5474 SAFE_FREE(s);
5475 s = next;
5477 context->internal->_servers = NULL;
5480 else {
5481 /* This is the polite way */
5482 if (context->callbacks.purge_cached_fn(context)) {
5483 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
5484 errno = EBUSY;
5485 return 1;
5487 if (context->internal->_servers) {
5488 DEBUG(1, ("Active servers in context, free_context failed.\n"));
5489 errno = EBUSY;
5490 return 1;
5492 if (context->internal->_files) {
5493 DEBUG(1, ("Active files in context, free_context failed.\n"));
5494 errno = EBUSY;
5495 return 1;
5499 /* Things we have to clean up */
5500 SAFE_FREE(context->workgroup);
5501 SAFE_FREE(context->netbios_name);
5502 SAFE_FREE(context->user);
5504 DEBUG(3, ("Context %p succesfully freed\n", context));
5505 SAFE_FREE(context->internal);
5506 SAFE_FREE(context);
5507 return 0;
5512 * Initialise the library etc
5514 * We accept a struct containing handle information.
5515 * valid values for info->debug from 0 to 100,
5516 * and insist that info->fn must be non-null.
5518 SMBCCTX * smbc_init_context(SMBCCTX * context)
5520 pstring conf;
5521 int pid;
5522 char *user = NULL, *home = NULL;
5524 if (!context || !context->internal) {
5525 errno = EBADF;
5526 return NULL;
5529 /* Do not initialise the same client twice */
5530 if (context->internal->_initialized) {
5531 return 0;
5534 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
5536 errno = EINVAL;
5537 return NULL;
5541 if (!smbc_initialized) {
5542 /* Do some library wide intialisations the first time we get called */
5543 BOOL conf_loaded = False;
5545 /* Set this to what the user wants */
5546 DEBUGLEVEL = context->debug;
5548 setup_logging( "libsmbclient", True);
5550 /* Here we would open the smb.conf file if needed ... */
5552 load_interfaces(); /* Load the list of interfaces ... */
5554 in_client = True; /* FIXME, make a param */
5556 home = getenv("HOME");
5557 if (home) {
5558 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5559 if (lp_load(conf, True, False, False)) {
5560 conf_loaded = True;
5561 } else {
5562 DEBUG(5, ("Could not load config file: %s\n",
5563 conf));
5567 if (!conf_loaded) {
5569 * Well, if that failed, try the dyn_CONFIGFILE
5570 * Which points to the standard locn, and if that
5571 * fails, silently ignore it and use the internal
5572 * defaults ...
5575 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
5576 DEBUG(5, ("Could not load config file: %s\n",
5577 dyn_CONFIGFILE));
5578 } else if (home) {
5580 * We loaded the global config file. Now lets
5581 * load user-specific modifications to the
5582 * global config.
5584 slprintf(conf, sizeof(conf),
5585 "%s/.smb/smb.conf.append", home);
5586 if (!lp_load(conf, True, False, False)) {
5587 DEBUG(10,
5588 ("Could not append config file: "
5589 "%s\n",
5590 conf));
5595 reopen_logs(); /* Get logging working ... */
5598 * Block SIGPIPE (from lib/util_sock.c: write())
5599 * It is not needed and should not stop execution
5601 BlockSignals(True, SIGPIPE);
5603 /* Done with one-time initialisation */
5604 smbc_initialized = 1;
5608 if (!context->user) {
5610 * FIXME: Is this the best way to get the user info?
5612 user = getenv("USER");
5613 /* walk around as "guest" if no username can be found */
5614 if (!user) context->user = SMB_STRDUP("guest");
5615 else context->user = SMB_STRDUP(user);
5618 if (!context->netbios_name) {
5620 * We try to get our netbios name from the config. If that fails we fall
5621 * back on constructing our netbios name from our hostname etc
5623 if (global_myname()) {
5624 context->netbios_name = SMB_STRDUP(global_myname());
5626 else {
5628 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
5630 pid = sys_getpid();
5631 context->netbios_name = SMB_MALLOC(17);
5632 if (!context->netbios_name) {
5633 errno = ENOMEM;
5634 return NULL;
5636 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
5640 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
5642 if (!context->workgroup) {
5643 if (lp_workgroup()) {
5644 context->workgroup = SMB_STRDUP(lp_workgroup());
5646 else {
5647 /* TODO: Think about a decent default workgroup */
5648 context->workgroup = SMB_STRDUP("samba");
5652 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
5654 /* shortest timeout is 1 second */
5655 if (context->timeout > 0 && context->timeout < 1000)
5656 context->timeout = 1000;
5659 * FIXME: Should we check the function pointers here?
5662 context->internal->_initialized = 1;
5664 return context;
5668 /* Return the verion of samba, and thus libsmbclient */
5669 const char *
5670 smbc_version(void)
5672 return samba_version_string();