r14418: Try and fix Coverity #39 and #40 by making the
[Samba/nascimento.git] / source3 / libsmb / libsmbclient.c
blobb8070283dac84512a600fa7a65a1ff9035b55d8b
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.
85 static struct rpc_pipe_client *
86 find_lsa_pipe_hnd(struct cli_state *ipc_cli)
88 struct rpc_pipe_client *pipe_hnd;
90 for (pipe_hnd = ipc_cli->pipe_list;
91 pipe_hnd;
92 pipe_hnd = pipe_hnd->next) {
94 if (pipe_hnd->pipe_idx == PI_LSARPC) {
95 return pipe_hnd;
99 return NULL;
102 static int
103 smbc_close_ctx(SMBCCTX *context,
104 SMBCFILE *file);
105 static off_t
106 smbc_lseek_ctx(SMBCCTX *context,
107 SMBCFILE *file,
108 off_t offset,
109 int whence);
111 extern BOOL in_client;
114 * Is the logging working / configfile read ?
116 static int smbc_initialized = 0;
118 static int
119 hex2int( unsigned int _char )
121 if ( _char >= 'A' && _char <='F')
122 return _char - 'A' + 10;
123 if ( _char >= 'a' && _char <='f')
124 return _char - 'a' + 10;
125 if ( _char >= '0' && _char <='9')
126 return _char - '0';
127 return -1;
131 * smbc_urldecode()
133 * Convert strings of %xx to their single character equivalent. Each 'x' must
134 * be a valid hexadecimal digit, or that % sequence is left undecoded.
136 * dest may, but need not be, the same pointer as src.
138 * Returns the number of % sequences which could not be converted due to lack
139 * of two following hexadecimal digits.
142 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
144 int old_length = strlen(src);
145 int i = 0;
146 int err_count = 0;
147 pstring temp;
148 char * p;
150 if ( old_length == 0 ) {
151 return 0;
154 p = temp;
155 while ( i < old_length ) {
156 unsigned char character = src[ i++ ];
158 if (character == '%') {
159 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
160 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
162 /* Replace valid sequence */
163 if (a != -1 && b != -1) {
165 /* Replace valid %xx sequence with %dd */
166 character = (a * 16) + b;
168 if (character == '\0') {
169 break; /* Stop at %00 */
172 i += 2;
173 } else {
175 err_count++;
179 *p++ = character;
182 *p = '\0';
184 strncpy(dest, temp, max_dest_len - 1);
185 dest[max_dest_len - 1] = '\0';
187 return err_count;
191 * smbc_urlencode()
193 * Convert any characters not specifically allowed in a URL into their %xx
194 * equivalent.
196 * Returns the remaining buffer length.
199 smbc_urlencode(char * dest, char * src, int max_dest_len)
201 char hex[] = "0123456789ABCDEF";
203 for (; *src != '\0' && max_dest_len >= 3; src++) {
205 if ((*src < '0' &&
206 *src != '-' &&
207 *src != '.') ||
208 (*src > '9' &&
209 *src < 'A') ||
210 (*src > 'Z' &&
211 *src < 'a' &&
212 *src != '_') ||
213 (*src > 'z')) {
214 *dest++ = '%';
215 *dest++ = hex[(*src >> 4) & 0x0f];
216 *dest++ = hex[*src & 0x0f];
217 max_dest_len -= 3;
218 } else {
219 *dest++ = *src;
220 max_dest_len--;
224 *dest++ = '\0';
225 max_dest_len--;
227 return max_dest_len;
231 * Function to parse a path and turn it into components
233 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
234 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
235 * general format ("smb:" only; we do not look for "cifs:").
238 * We accept:
239 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
241 * Meaning of URLs:
243 * smb:// Show all workgroups.
245 * The method of locating the list of workgroups varies
246 * depending upon the setting of the context variable
247 * context->options.browse_max_lmb_count. This value
248 * determine the maximum number of local master browsers to
249 * query for the list of workgroups. In order to ensure that
250 * a complete list of workgroups is obtained, all master
251 * browsers must be queried, but if there are many
252 * workgroups, the time spent querying can begin to add up.
253 * For small networks (not many workgroups), it is suggested
254 * that this variable be set to 0, indicating query all local
255 * master browsers. When the network has many workgroups, a
256 * reasonable setting for this variable might be around 3.
258 * smb://name/ if name<1D> or name<1B> exists, list servers in
259 * workgroup, else, if name<20> exists, list all shares
260 * for server ...
262 * If "options" are provided, this function returns the entire option list as a
263 * string, for later parsing by the caller. Note that currently, no options
264 * are supported.
267 static const char *smbc_prefix = "smb:";
269 static int
270 smbc_parse_path(SMBCCTX *context,
271 const char *fname,
272 char *workgroup, int workgroup_len,
273 char *server, int server_len,
274 char *share, int share_len,
275 char *path, int path_len,
276 char *user, int user_len,
277 char *password, int password_len,
278 char *options, int options_len)
280 static pstring s;
281 pstring userinfo;
282 const char *p;
283 char *q, *r;
284 int len;
286 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
289 * Assume we wont find an authentication domain to parse, so default
290 * to the workgroup in the provided context.
292 if (workgroup != NULL) {
293 strncpy(workgroup, context->workgroup, workgroup_len - 1);
294 workgroup[workgroup_len - 1] = '\0';
297 if (options != NULL && options_len > 0) {
298 options[0] = (char)0;
300 pstrcpy(s, fname);
302 /* see if it has the right prefix */
303 len = strlen(smbc_prefix);
304 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
305 return -1; /* What about no smb: ? */
308 p = s + len;
310 /* Watch the test below, we are testing to see if we should exit */
312 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
314 DEBUG(1, ("Invalid path (does not begin with smb://"));
315 return -1;
319 p += 2; /* Skip the double slash */
321 /* See if any options were specified */
322 if ((q = strrchr(p, '?')) != NULL ) {
323 /* There are options. Null terminate here and point to them */
324 *q++ = '\0';
326 DEBUG(4, ("Found options '%s'", q));
328 /* Copy the options */
329 if (options != NULL && options_len > 0) {
330 safe_strcpy(options, q, options_len - 1);
334 if (*p == (char)0)
335 goto decoding;
337 if (*p == '/') {
339 strncpy(server, context->workgroup,
340 ((strlen(context->workgroup) < 16)
341 ? strlen(context->workgroup)
342 : 16));
343 server[server_len - 1] = '\0';
344 return 0;
349 * ok, its for us. Now parse out the server, share etc.
351 * However, we want to parse out [[domain;]user[:password]@] if it
352 * exists ...
355 /* check that '@' occurs before '/', if '/' exists at all */
356 q = strchr_m(p, '@');
357 r = strchr_m(p, '/');
358 if (q && (!r || q < r)) {
359 pstring username, passwd, domain;
360 const char *u = userinfo;
362 next_token(&p, userinfo, "@", sizeof(fstring));
364 username[0] = passwd[0] = domain[0] = 0;
366 if (strchr_m(u, ';')) {
368 next_token(&u, domain, ";", sizeof(fstring));
372 if (strchr_m(u, ':')) {
374 next_token(&u, username, ":", sizeof(fstring));
376 pstrcpy(passwd, u);
379 else {
381 pstrcpy(username, u);
385 if (domain[0] && workgroup) {
386 strncpy(workgroup, domain, workgroup_len - 1);
387 workgroup[workgroup_len - 1] = '\0';
390 if (username[0]) {
391 strncpy(user, username, user_len - 1);
392 user[user_len - 1] = '\0';
395 if (passwd[0]) {
396 strncpy(password, passwd, password_len - 1);
397 password[password_len - 1] = '\0';
402 if (!next_token(&p, server, "/", sizeof(fstring))) {
404 return -1;
408 if (*p == (char)0) goto decoding; /* That's it ... */
410 if (!next_token(&p, share, "/", sizeof(fstring))) {
412 return -1;
416 safe_strcpy(path, p, path_len - 1);
418 all_string_sub(path, "/", "\\", 0);
420 decoding:
421 (void) smbc_urldecode(path, path, path_len);
422 (void) smbc_urldecode(server, server, server_len);
423 (void) smbc_urldecode(share, share, share_len);
424 (void) smbc_urldecode(user, user, user_len);
425 (void) smbc_urldecode(password, password, password_len);
427 return 0;
431 * Verify that the options specified in a URL are valid
433 static int
434 smbc_check_options(char *server,
435 char *share,
436 char *path,
437 char *options)
439 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' "
440 "path='%s' options='%s'\n",
441 server, share, path, options));
443 /* No options at all is always ok */
444 if (! *options) return 0;
446 /* Currently, we don't support any options. */
447 return -1;
451 * Convert an SMB error into a UNIX error ...
453 static int
454 smbc_errno(SMBCCTX *context,
455 struct cli_state *c)
457 int ret = cli_errno(c);
459 if (cli_is_dos_error(c)) {
460 uint8 eclass;
461 uint32 ecode;
463 cli_dos_error(c, &eclass, &ecode);
465 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
466 (int)eclass, (int)ecode, (int)ecode, ret));
467 } else {
468 NTSTATUS status;
470 status = cli_nt_error(c);
472 DEBUG(3,("smbc errno %s -> %d\n",
473 nt_errstr(status), ret));
476 return ret;
480 * Check a server for being alive and well.
481 * returns 0 if the server is in shape. Returns 1 on error
483 * Also useable outside libsmbclient to enable external cache
484 * to do some checks too.
486 static int
487 smbc_check_server(SMBCCTX * context,
488 SMBCSRV * server)
490 if ( send_keepalive(server->cli.fd) == False )
491 return 1;
493 /* connection is ok */
494 return 0;
498 * Remove a server from the cached server list it's unused.
499 * On success, 0 is returned. 1 is returned if the server could not be removed.
501 * Also useable outside libsmbclient
504 smbc_remove_unused_server(SMBCCTX * context,
505 SMBCSRV * srv)
507 SMBCFILE * file;
509 /* are we being fooled ? */
510 if (!context || !context->internal ||
511 !context->internal->_initialized || !srv) return 1;
514 /* Check all open files/directories for a relation with this server */
515 for (file = context->internal->_files; file; file=file->next) {
516 if (file->srv == srv) {
517 /* Still used */
518 DEBUG(3, ("smbc_remove_usused_server: "
519 "%p still used by %p.\n",
520 srv, file));
521 return 1;
525 DLIST_REMOVE(context->internal->_servers, srv);
527 cli_shutdown(&srv->cli);
529 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
531 context->callbacks.remove_cached_srv_fn(context, srv);
533 SAFE_FREE(srv);
535 return 0;
538 static SMBCSRV *
539 find_server(SMBCCTX *context,
540 const char *server,
541 const char *share,
542 fstring workgroup,
543 fstring username,
544 fstring password)
546 SMBCSRV *srv;
547 int auth_called = 0;
549 check_server_cache:
551 srv = context->callbacks.get_cached_srv_fn(context, server, share,
552 workgroup, username);
554 if (!auth_called && !srv && (!username[0] || !password[0])) {
555 context->callbacks.auth_fn(server, share,
556 workgroup, sizeof(fstring),
557 username, sizeof(fstring),
558 password, sizeof(fstring));
560 * However, smbc_auth_fn may have picked up info relating to
561 * an existing connection, so try for an existing connection
562 * again ...
564 auth_called = 1;
565 goto check_server_cache;
569 if (srv) {
570 if (context->callbacks.check_server_fn(context, srv)) {
572 * This server is no good anymore
573 * Try to remove it and check for more possible
574 * servers in the cache
576 if (context->callbacks.remove_unused_server_fn(context,
577 srv)) {
579 * We could not remove the server completely,
580 * remove it from the cache so we will not get
581 * it again. It will be removed when the last
582 * file/dir is closed.
584 context->callbacks.remove_cached_srv_fn(context,
585 srv);
589 * Maybe there are more cached connections to this
590 * server
592 goto check_server_cache;
595 return srv;
598 return NULL;
602 * Connect to a server, possibly on an existing connection
604 * Here, what we want to do is: If the server and username
605 * match an existing connection, reuse that, otherwise, establish a
606 * new connection.
608 * If we have to create a new connection, call the auth_fn to get the
609 * info we need, unless the username and password were passed in.
612 static SMBCSRV *
613 smbc_server(SMBCCTX *context,
614 BOOL connect_if_not_found,
615 const char *server,
616 const char *share,
617 fstring workgroup,
618 fstring username,
619 fstring password)
621 SMBCSRV *srv=NULL;
622 struct cli_state c;
623 struct nmb_name called, calling;
624 const char *server_n = server;
625 pstring ipenv;
626 struct in_addr ip;
627 int tried_reverse = 0;
628 int port_try_first;
629 int port_try_next;
630 const char *username_used;
632 zero_ip(&ip);
633 ZERO_STRUCT(c);
635 if (server[0] == 0) {
636 errno = EPERM;
637 return NULL;
640 /* Look for a cached connection */
641 srv = find_server(context, server, share,
642 workgroup, username, password);
645 * If we found a connection and we're only allowed one share per
646 * server...
648 if (srv && *share != '\0' && context->options.one_share_per_server) {
651 * ... then if there's no current connection to the share,
652 * connect to it. find_server(), or rather the function
653 * pointed to by context->callbacks.get_cached_srv_fn which
654 * was called by find_server(), will have issued a tree
655 * disconnect if the requested share is not the same as the
656 * one that was already connected.
658 if (srv->cli.cnum == (uint16) -1) {
659 /* Ensure we have accurate auth info */
660 context->callbacks.auth_fn(server, share,
661 workgroup, sizeof(fstring),
662 username, sizeof(fstring),
663 password, sizeof(fstring));
665 if (! cli_send_tconX(&srv->cli, share, "?????",
666 password, strlen(password)+1)) {
668 errno = smbc_errno(context, &srv->cli);
669 cli_shutdown(&srv->cli);
670 context->callbacks.remove_cached_srv_fn(context,
671 srv);
672 srv = NULL;
676 * Regenerate the dev value since it's based on both
677 * server and share
679 if (srv) {
680 srv->dev = (dev_t)(str_checksum(server) ^
681 str_checksum(share));
686 /* If we have a connection... */
687 if (srv) {
689 /* ... then we're done here. Give 'em what they came for. */
690 return srv;
693 /* If we're not asked to connect when a connection doesn't exist... */
694 if (! connect_if_not_found) {
695 /* ... then we're done here. */
696 return NULL;
699 make_nmb_name(&calling, context->netbios_name, 0x0);
700 make_nmb_name(&called , server, 0x20);
702 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
704 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
706 again:
707 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
709 zero_ip(&ip);
711 /* have to open a new connection */
712 if (!cli_initialise(&c)) {
713 errno = ENOMEM;
714 return NULL;
717 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
718 c.use_kerberos = True;
720 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
721 c.fallback_after_kerberos = True;
724 c.timeout = context->timeout;
727 * Force use of port 139 for first try if share is $IPC, empty, or
728 * null, so browse lists can work
730 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
731 port_try_first = 139;
732 port_try_next = 445;
733 } else {
734 port_try_first = 445;
735 port_try_next = 139;
738 c.port = port_try_first;
740 if (!cli_connect(&c, server_n, &ip)) {
742 /* First connection attempt failed. Try alternate port. */
743 c.port = port_try_next;
745 if (!cli_connect(&c, server_n, &ip)) {
746 cli_shutdown(&c);
747 errno = ETIMEDOUT;
748 return NULL;
752 if (!cli_session_request(&c, &calling, &called)) {
753 cli_shutdown(&c);
754 if (strcmp(called.name, "*SMBSERVER")) {
755 make_nmb_name(&called , "*SMBSERVER", 0x20);
756 goto again;
758 else { /* Try one more time, but ensure we don't loop */
760 /* Only try this if server is an IP address ... */
762 if (is_ipaddress(server) && !tried_reverse) {
763 fstring remote_name;
764 struct in_addr rem_ip;
766 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
767 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
768 errno = ETIMEDOUT;
769 return NULL;
772 tried_reverse++; /* Yuck */
774 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
775 make_nmb_name(&called, remote_name, 0x20);
776 goto again;
782 errno = ETIMEDOUT;
783 return NULL;
786 DEBUG(4,(" session request ok\n"));
788 if (!cli_negprot(&c)) {
789 cli_shutdown(&c);
790 errno = ETIMEDOUT;
791 return NULL;
794 username_used = username;
796 if (!cli_session_setup(&c, username_used,
797 password, strlen(password),
798 password, strlen(password),
799 workgroup)) {
801 /* Failed. Try an anonymous login, if allowed by flags. */
802 username_used = "";
804 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
805 !cli_session_setup(&c, username_used,
806 password, 1,
807 password, 0,
808 workgroup)) {
810 cli_shutdown(&c);
811 errno = EPERM;
812 return NULL;
816 DEBUG(4,(" session setup ok\n"));
818 if (!cli_send_tconX(&c, share, "?????",
819 password, strlen(password)+1)) {
820 errno = smbc_errno(context, &c);
821 cli_shutdown(&c);
822 return NULL;
825 DEBUG(4,(" tconx ok\n"));
828 * Ok, we have got a nice connection
829 * Let's allocate a server structure.
832 srv = SMB_MALLOC_P(SMBCSRV);
833 if (!srv) {
834 errno = ENOMEM;
835 goto failed;
838 ZERO_STRUCTP(srv);
839 srv->cli = c;
840 srv->cli.allocated = False;
841 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
842 srv->no_pathinfo = False;
843 srv->no_pathinfo2 = False;
844 srv->no_nt_session = False;
846 /* now add it to the cache (internal or external) */
847 /* Let the cache function set errno if it wants to */
848 errno = 0;
849 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
850 int saved_errno = errno;
851 DEBUG(3, (" Failed to add server to cache\n"));
852 errno = saved_errno;
853 if (errno == 0) {
854 errno = ENOMEM;
856 goto failed;
859 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
860 server, share, srv));
862 DLIST_ADD(context->internal->_servers, srv);
863 return srv;
865 failed:
866 cli_shutdown(&c);
867 if (!srv) return NULL;
869 SAFE_FREE(srv);
870 return NULL;
874 * Connect to a server for getting/setting attributes, possibly on an existing
875 * connection. This works similarly to smbc_server().
877 static SMBCSRV *
878 smbc_attr_server(SMBCCTX *context,
879 const char *server,
880 const char *share,
881 fstring workgroup,
882 fstring username,
883 fstring password,
884 POLICY_HND *pol)
886 struct in_addr ip;
887 struct cli_state *ipc_cli;
888 struct rpc_pipe_client *pipe_hnd;
889 NTSTATUS nt_status;
890 SMBCSRV *ipc_srv=NULL;
893 * See if we've already created this special connection. Reference
894 * our "special" share name '*IPC$', which is an impossible real share
895 * name due to the leading asterisk.
897 ipc_srv = find_server(context, server, "*IPC$",
898 workgroup, username, password);
899 if (!ipc_srv) {
901 /* We didn't find a cached connection. Get the password */
902 if (*password == '\0') {
903 /* ... then retrieve it now. */
904 context->callbacks.auth_fn(server, share,
905 workgroup, sizeof(fstring),
906 username, sizeof(fstring),
907 password, sizeof(fstring));
910 zero_ip(&ip);
911 nt_status = cli_full_connection(&ipc_cli,
912 global_myname(), server,
913 &ip, 0, "IPC$", "?????",
914 username, workgroup,
915 password, 0,
916 Undefined, NULL);
917 if (! NT_STATUS_IS_OK(nt_status)) {
918 DEBUG(1,("cli_full_connection failed! (%s)\n",
919 nt_errstr(nt_status)));
920 errno = ENOTSUP;
921 return NULL;
924 ipc_srv = SMB_MALLOC_P(SMBCSRV);
925 if (!ipc_srv) {
926 errno = ENOMEM;
927 cli_shutdown(ipc_cli);
928 return NULL;
931 ZERO_STRUCTP(ipc_srv);
932 ipc_srv->cli = *ipc_cli;
933 ipc_srv->cli.allocated = False;
935 free(ipc_cli);
937 if (pol) {
938 pipe_hnd = cli_rpc_pipe_open_noauth(&ipc_srv->cli,
939 PI_LSARPC,
940 &nt_status);
941 if (!pipe_hnd) {
942 DEBUG(1, ("cli_nt_session_open fail!\n"));
943 errno = ENOTSUP;
944 cli_shutdown(&ipc_srv->cli);
945 free(ipc_srv);
946 return NULL;
950 * Some systems don't support
951 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
952 * so we might as well do it too.
955 nt_status = rpccli_lsa_open_policy(
956 pipe_hnd,
957 ipc_srv->cli.mem_ctx,
958 True,
959 GENERIC_EXECUTE_ACCESS,
960 pol);
962 if (!NT_STATUS_IS_OK(nt_status)) {
963 errno = smbc_errno(context, &ipc_srv->cli);
964 cli_shutdown(&ipc_srv->cli);
965 return NULL;
969 /* now add it to the cache (internal or external) */
971 errno = 0; /* let cache function set errno if it likes */
972 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
973 server,
974 "*IPC$",
975 workgroup,
976 username)) {
977 DEBUG(3, (" Failed to add server to cache\n"));
978 if (errno == 0) {
979 errno = ENOMEM;
981 cli_shutdown(&ipc_srv->cli);
982 free(ipc_srv);
983 return NULL;
986 DLIST_ADD(context->internal->_servers, ipc_srv);
989 return ipc_srv;
993 * Routine to open() a file ...
996 static SMBCFILE *
997 smbc_open_ctx(SMBCCTX *context,
998 const char *fname,
999 int flags,
1000 mode_t mode)
1002 fstring server, share, user, password, workgroup;
1003 pstring path;
1004 pstring targetpath;
1005 struct cli_state *targetcli;
1006 SMBCSRV *srv = NULL;
1007 SMBCFILE *file = NULL;
1008 int fd;
1010 if (!context || !context->internal ||
1011 !context->internal->_initialized) {
1013 errno = EINVAL; /* Best I can think of ... */
1014 return NULL;
1018 if (!fname) {
1020 errno = EINVAL;
1021 return NULL;
1025 if (smbc_parse_path(context, fname,
1026 workgroup, sizeof(workgroup),
1027 server, sizeof(server),
1028 share, sizeof(share),
1029 path, sizeof(path),
1030 user, sizeof(user),
1031 password, sizeof(password),
1032 NULL, 0)) {
1033 errno = EINVAL;
1034 return NULL;
1037 if (user[0] == (char)0) fstrcpy(user, context->user);
1039 srv = smbc_server(context, True,
1040 server, share, workgroup, user, password);
1042 if (!srv) {
1044 if (errno == EPERM) errno = EACCES;
1045 return NULL; /* smbc_server sets errno */
1049 /* Hmmm, the test for a directory is suspect here ... FIXME */
1051 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1053 fd = -1;
1056 else {
1058 file = SMB_MALLOC_P(SMBCFILE);
1060 if (!file) {
1062 errno = ENOMEM;
1063 return NULL;
1067 ZERO_STRUCTP(file);
1069 /*d_printf(">>>open: resolving %s\n", path);*/
1070 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1072 d_printf("Could not resolve %s\n", path);
1073 SAFE_FREE(file);
1074 return NULL;
1076 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1078 if ( targetcli->dfsroot )
1080 pstring temppath;
1081 pstrcpy(temppath, targetpath);
1082 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1085 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1087 /* Handle the error ... */
1089 SAFE_FREE(file);
1090 errno = smbc_errno(context, targetcli);
1091 return NULL;
1095 /* Fill in file struct */
1097 file->cli_fd = fd;
1098 file->fname = SMB_STRDUP(fname);
1099 file->srv = srv;
1100 file->offset = 0;
1101 file->file = True;
1103 DLIST_ADD(context->internal->_files, file);
1106 * If the file was opened in O_APPEND mode, all write
1107 * operations should be appended to the file. To do that,
1108 * though, using this protocol, would require a getattrE()
1109 * call for each and every write, to determine where the end
1110 * of the file is. (There does not appear to be an append flag
1111 * in the protocol.) Rather than add all of that overhead of
1112 * retrieving the current end-of-file offset prior to each
1113 * write operation, we'll assume that most append operations
1114 * will continuously write, so we'll just set the offset to
1115 * the end of the file now and hope that's adequate.
1117 * Note to self: If this proves inadequate, and O_APPEND
1118 * should, in some cases, be forced for each write, add a
1119 * field in the context options structure, for
1120 * "strict_append_mode" which would select between the current
1121 * behavior (if FALSE) or issuing a getattrE() prior to each
1122 * write and forcing the write to the end of the file (if
1123 * TRUE). Adding that capability will likely require adding
1124 * an "append" flag into the _SMBCFILE structure to track
1125 * whether a file was opened in O_APPEND mode. -- djl
1127 if (flags & O_APPEND) {
1128 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1129 (void) smbc_close_ctx(context, file);
1130 errno = ENXIO;
1131 return NULL;
1135 return file;
1139 /* Check if opendir needed ... */
1141 if (fd == -1) {
1142 int eno = 0;
1144 eno = smbc_errno(context, &srv->cli);
1145 file = context->opendir(context, fname);
1146 if (!file) errno = eno;
1147 return file;
1151 errno = EINVAL; /* FIXME, correct errno ? */
1152 return NULL;
1157 * Routine to create a file
1160 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1162 static SMBCFILE *
1163 smbc_creat_ctx(SMBCCTX *context,
1164 const char *path,
1165 mode_t mode)
1168 if (!context || !context->internal ||
1169 !context->internal->_initialized) {
1171 errno = EINVAL;
1172 return NULL;
1176 return smbc_open_ctx(context, path, creat_bits, mode);
1180 * Routine to read() a file ...
1183 static ssize_t
1184 smbc_read_ctx(SMBCCTX *context,
1185 SMBCFILE *file,
1186 void *buf,
1187 size_t count)
1189 int ret;
1190 fstring server, share, user, password;
1191 pstring path, targetpath;
1192 struct cli_state *targetcli;
1195 * offset:
1197 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1198 * appears to pass file->offset (which is type off_t) differently than
1199 * a local variable of type off_t. Using local variable "offset" in
1200 * the call to cli_read() instead of file->offset fixes a problem
1201 * retrieving data at an offset greater than 4GB.
1203 off_t offset;
1205 if (!context || !context->internal ||
1206 !context->internal->_initialized) {
1208 errno = EINVAL;
1209 return -1;
1213 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1215 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1217 errno = EBADF;
1218 return -1;
1222 offset = file->offset;
1224 /* Check that the buffer exists ... */
1226 if (buf == NULL) {
1228 errno = EINVAL;
1229 return -1;
1233 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1234 if (smbc_parse_path(context, file->fname,
1235 NULL, 0,
1236 server, sizeof(server),
1237 share, sizeof(share),
1238 path, sizeof(path),
1239 user, sizeof(user),
1240 password, sizeof(password),
1241 NULL, 0)) {
1242 errno = EINVAL;
1243 return -1;
1246 /*d_printf(">>>read: resolving %s\n", path);*/
1247 if (!cli_resolve_path("", &file->srv->cli, path,
1248 &targetcli, targetpath))
1250 d_printf("Could not resolve %s\n", path);
1251 return -1;
1253 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1255 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1257 if (ret < 0) {
1259 errno = smbc_errno(context, targetcli);
1260 return -1;
1264 file->offset += ret;
1266 DEBUG(4, (" --> %d\n", ret));
1268 return ret; /* Success, ret bytes of data ... */
1273 * Routine to write() a file ...
1276 static ssize_t
1277 smbc_write_ctx(SMBCCTX *context,
1278 SMBCFILE *file,
1279 void *buf,
1280 size_t count)
1282 int ret;
1283 off_t offset;
1284 fstring server, share, user, password;
1285 pstring path, targetpath;
1286 struct cli_state *targetcli;
1288 /* First check all pointers before dereferencing them */
1290 if (!context || !context->internal ||
1291 !context->internal->_initialized) {
1293 errno = EINVAL;
1294 return -1;
1298 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1300 errno = EBADF;
1301 return -1;
1305 /* Check that the buffer exists ... */
1307 if (buf == NULL) {
1309 errno = EINVAL;
1310 return -1;
1314 offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1316 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1317 if (smbc_parse_path(context, file->fname,
1318 NULL, 0,
1319 server, sizeof(server),
1320 share, sizeof(share),
1321 path, sizeof(path),
1322 user, sizeof(user),
1323 password, sizeof(password),
1324 NULL, 0)) {
1325 errno = EINVAL;
1326 return -1;
1329 /*d_printf(">>>write: resolving %s\n", path);*/
1330 if (!cli_resolve_path("", &file->srv->cli, path,
1331 &targetcli, targetpath))
1333 d_printf("Could not resolve %s\n", path);
1334 return -1;
1336 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1339 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1341 if (ret <= 0) {
1343 errno = smbc_errno(context, targetcli);
1344 return -1;
1348 file->offset += ret;
1350 return ret; /* Success, 0 bytes of data ... */
1354 * Routine to close() a file ...
1357 static int
1358 smbc_close_ctx(SMBCCTX *context,
1359 SMBCFILE *file)
1361 SMBCSRV *srv;
1362 fstring server, share, user, password;
1363 pstring path, targetpath;
1364 struct cli_state *targetcli;
1366 if (!context || !context->internal ||
1367 !context->internal->_initialized) {
1369 errno = EINVAL;
1370 return -1;
1374 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1376 errno = EBADF;
1377 return -1;
1381 /* IS a dir ... */
1382 if (!file->file) {
1384 return context->closedir(context, file);
1388 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1389 if (smbc_parse_path(context, file->fname,
1390 NULL, 0,
1391 server, sizeof(server),
1392 share, sizeof(share),
1393 path, sizeof(path),
1394 user, sizeof(user),
1395 password, sizeof(password),
1396 NULL, 0)) {
1397 errno = EINVAL;
1398 return -1;
1401 /*d_printf(">>>close: resolving %s\n", path);*/
1402 if (!cli_resolve_path("", &file->srv->cli, path,
1403 &targetcli, targetpath))
1405 d_printf("Could not resolve %s\n", path);
1406 return -1;
1408 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1410 if (!cli_close(targetcli, file->cli_fd)) {
1412 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1413 file->fname));
1414 /* Deallocate slot and remove the server
1415 * from the server cache if unused */
1416 errno = smbc_errno(context, targetcli);
1417 srv = file->srv;
1418 DLIST_REMOVE(context->internal->_files, file);
1419 SAFE_FREE(file->fname);
1420 SAFE_FREE(file);
1421 context->callbacks.remove_unused_server_fn(context, srv);
1423 return -1;
1427 DLIST_REMOVE(context->internal->_files, file);
1428 SAFE_FREE(file->fname);
1429 SAFE_FREE(file);
1431 return 0;
1435 * Get info from an SMB server on a file. Use a qpathinfo call first
1436 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1438 static BOOL
1439 smbc_getatr(SMBCCTX * context,
1440 SMBCSRV *srv,
1441 char *path,
1442 uint16 *mode,
1443 SMB_OFF_T *size,
1444 time_t *c_time,
1445 time_t *a_time,
1446 time_t *m_time,
1447 SMB_INO_T *ino)
1449 pstring fixedpath;
1450 pstring targetpath;
1451 struct cli_state *targetcli;
1453 if (!context || !context->internal ||
1454 !context->internal->_initialized) {
1456 errno = EINVAL;
1457 return -1;
1461 /* path fixup for . and .. */
1462 if (strequal(path, ".") || strequal(path, ".."))
1463 pstrcpy(fixedpath, "\\");
1464 else
1466 pstrcpy(fixedpath, path);
1467 trim_string(fixedpath, NULL, "\\..");
1468 trim_string(fixedpath, NULL, "\\.");
1470 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1472 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1474 d_printf("Couldn't resolve %s\n", path);
1475 return False;
1478 if ( targetcli->dfsroot )
1480 pstring temppath;
1481 pstrcpy(temppath, targetpath);
1482 cli_dfs_make_full_path(targetpath, targetcli->desthost,
1483 targetcli->share, temppath);
1486 if (!srv->no_pathinfo2 &&
1487 cli_qpathinfo2(targetcli, targetpath,
1488 c_time, a_time, m_time, NULL, size, mode, ino)) {
1489 return True;
1492 /* if this is NT then don't bother with the getatr */
1493 if (targetcli->capabilities & CAP_NT_SMBS) {
1494 errno = EPERM;
1495 return False;
1498 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1499 if (m_time != NULL) {
1500 if (a_time != NULL) *a_time = *m_time;
1501 if (c_time != NULL) *c_time = *m_time;
1503 srv->no_pathinfo2 = True;
1504 return True;
1507 errno = EPERM;
1508 return False;
1513 * Set file info on an SMB server. Use setpathinfo call first. If that
1514 * fails, use setattrE..
1516 * Access and modification time parameters are always used and must be
1517 * provided. Create time, if zero, will be determined from the actual create
1518 * time of the file. If non-zero, the create time will be set as well.
1520 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1522 static BOOL
1523 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1524 time_t c_time, time_t a_time, time_t m_time,
1525 uint16 mode)
1527 int fd;
1528 int ret;
1531 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1532 * modern function for "new code" to be using, and it works given a
1533 * filename rather than requiring that the file be opened to have its
1534 * attributes manipulated.
1536 if (srv->no_pathinfo ||
1537 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1540 * setpathinfo is not supported; go to plan B.
1542 * cli_setatr() does not work on win98, and it also doesn't
1543 * support setting the access time (only the modification
1544 * time), so in all cases, we open the specified file and use
1545 * cli_setattrE() which should work on all OS versions, and
1546 * supports both times.
1549 /* Don't try {q,set}pathinfo() again, with this server */
1550 srv->no_pathinfo = True;
1552 /* Open the file */
1553 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1555 errno = smbc_errno(context, &srv->cli);
1556 return -1;
1560 * Get the creat time of the file (if it wasn't provided).
1561 * We'll need it in the set call
1563 if (c_time == 0) {
1564 ret = cli_getattrE(&srv->cli, fd,
1565 NULL, NULL,
1566 &c_time, NULL, NULL);
1567 } else {
1568 ret = True;
1571 /* If we got create time, set times */
1572 if (ret) {
1573 /* Some OS versions don't support create time */
1574 if (c_time == 0 || c_time == -1) {
1575 c_time = time(NULL);
1579 * For sanity sake, since there is no POSIX function
1580 * to set the create time of a file, if the existing
1581 * create time is greater than either of access time
1582 * or modification time, set create time to the
1583 * smallest of those. This ensure that the create
1584 * time of a file is never greater than its last
1585 * access or modification time.
1587 if (c_time > a_time) c_time = a_time;
1588 if (c_time > m_time) c_time = m_time;
1590 /* Set the new attributes */
1591 ret = cli_setattrE(&srv->cli, fd,
1592 c_time, a_time, m_time);
1593 cli_close(&srv->cli, fd);
1597 * Unfortunately, setattrE() doesn't have a provision for
1598 * setting the access mode (attributes). We'll have to try
1599 * cli_setatr() for that, and with only this parameter, it
1600 * seems to work on win98.
1602 if (ret && mode != (uint16) -1) {
1603 ret = cli_setatr(&srv->cli, path, mode, 0);
1606 if (! ret) {
1607 errno = smbc_errno(context, &srv->cli);
1608 return False;
1612 return True;
1616 * Routine to unlink() a file
1619 static int
1620 smbc_unlink_ctx(SMBCCTX *context,
1621 const char *fname)
1623 fstring server, share, user, password, workgroup;
1624 pstring path, targetpath;
1625 struct cli_state *targetcli;
1626 SMBCSRV *srv = NULL;
1628 if (!context || !context->internal ||
1629 !context->internal->_initialized) {
1631 errno = EINVAL; /* Best I can think of ... */
1632 return -1;
1636 if (!fname) {
1638 errno = EINVAL;
1639 return -1;
1643 if (smbc_parse_path(context, fname,
1644 workgroup, sizeof(workgroup),
1645 server, sizeof(server),
1646 share, sizeof(share),
1647 path, sizeof(path),
1648 user, sizeof(user),
1649 password, sizeof(password),
1650 NULL, 0)) {
1651 errno = EINVAL;
1652 return -1;
1655 if (user[0] == (char)0) fstrcpy(user, context->user);
1657 srv = smbc_server(context, True,
1658 server, share, workgroup, user, password);
1660 if (!srv) {
1662 return -1; /* smbc_server sets errno */
1666 /*d_printf(">>>unlink: resolving %s\n", path);*/
1667 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1669 d_printf("Could not resolve %s\n", path);
1670 return -1;
1672 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1674 if (!cli_unlink(targetcli, targetpath)) {
1676 errno = smbc_errno(context, targetcli);
1678 if (errno == EACCES) { /* Check if the file is a directory */
1680 int saverr = errno;
1681 SMB_OFF_T size = 0;
1682 uint16 mode = 0;
1683 time_t m_time = 0, a_time = 0, c_time = 0;
1684 SMB_INO_T ino = 0;
1686 if (!smbc_getatr(context, srv, path, &mode, &size,
1687 &c_time, &a_time, &m_time, &ino)) {
1689 /* Hmmm, bad error ... What? */
1691 errno = smbc_errno(context, targetcli);
1692 return -1;
1695 else {
1697 if (IS_DOS_DIR(mode))
1698 errno = EISDIR;
1699 else
1700 errno = saverr; /* Restore this */
1705 return -1;
1709 return 0; /* Success ... */
1714 * Routine to rename() a file
1717 static int
1718 smbc_rename_ctx(SMBCCTX *ocontext,
1719 const char *oname,
1720 SMBCCTX *ncontext,
1721 const char *nname)
1723 fstring server1;
1724 fstring share1;
1725 fstring server2;
1726 fstring share2;
1727 fstring user1;
1728 fstring user2;
1729 fstring password1;
1730 fstring password2;
1731 fstring workgroup;
1732 pstring path1;
1733 pstring path2;
1734 pstring targetpath1;
1735 pstring targetpath2;
1736 struct cli_state *targetcli1;
1737 struct cli_state *targetcli2;
1738 SMBCSRV *srv = NULL;
1740 if (!ocontext || !ncontext ||
1741 !ocontext->internal || !ncontext->internal ||
1742 !ocontext->internal->_initialized ||
1743 !ncontext->internal->_initialized) {
1745 errno = EINVAL; /* Best I can think of ... */
1746 return -1;
1750 if (!oname || !nname) {
1752 errno = EINVAL;
1753 return -1;
1757 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1759 smbc_parse_path(ocontext, oname,
1760 workgroup, sizeof(workgroup),
1761 server1, sizeof(server1),
1762 share1, sizeof(share1),
1763 path1, sizeof(path1),
1764 user1, sizeof(user1),
1765 password1, sizeof(password1),
1766 NULL, 0);
1768 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1770 smbc_parse_path(ncontext, nname,
1771 NULL, 0,
1772 server2, sizeof(server2),
1773 share2, sizeof(share2),
1774 path2, sizeof(path2),
1775 user2, sizeof(user2),
1776 password2, sizeof(password2),
1777 NULL, 0);
1779 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1781 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1782 strcmp(user1, user2)) {
1784 /* Can't rename across file systems, or users?? */
1786 errno = EXDEV;
1787 return -1;
1791 srv = smbc_server(ocontext, True,
1792 server1, share1, workgroup, user1, password1);
1793 if (!srv) {
1795 return -1;
1799 /*d_printf(">>>rename: resolving %s\n", path1);*/
1800 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1802 d_printf("Could not resolve %s\n", path1);
1803 return -1;
1805 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1806 /*d_printf(">>>rename: resolving %s\n", path2);*/
1807 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1809 d_printf("Could not resolve %s\n", path2);
1810 return -1;
1812 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1814 if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1815 strcmp(targetcli1->share, targetcli2->share))
1817 /* can't rename across file systems */
1819 errno = EXDEV;
1820 return -1;
1823 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1824 int eno = smbc_errno(ocontext, targetcli1);
1826 if (eno != EEXIST ||
1827 !cli_unlink(targetcli1, targetpath2) ||
1828 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1830 errno = eno;
1831 return -1;
1836 return 0; /* Success */
1841 * A routine to lseek() a file
1844 static off_t
1845 smbc_lseek_ctx(SMBCCTX *context,
1846 SMBCFILE *file,
1847 off_t offset,
1848 int whence)
1850 SMB_OFF_T size;
1851 fstring server, share, user, password;
1852 pstring path, targetpath;
1853 struct cli_state *targetcli;
1855 if (!context || !context->internal ||
1856 !context->internal->_initialized) {
1858 errno = EINVAL;
1859 return -1;
1863 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1865 errno = EBADF;
1866 return -1;
1870 if (!file->file) {
1872 errno = EINVAL;
1873 return -1; /* Can't lseek a dir ... */
1877 switch (whence) {
1878 case SEEK_SET:
1879 file->offset = offset;
1880 break;
1882 case SEEK_CUR:
1883 file->offset += offset;
1884 break;
1886 case SEEK_END:
1887 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1888 if (smbc_parse_path(context, file->fname,
1889 NULL, 0,
1890 server, sizeof(server),
1891 share, sizeof(share),
1892 path, sizeof(path),
1893 user, sizeof(user),
1894 password, sizeof(password),
1895 NULL, 0)) {
1897 errno = EINVAL;
1898 return -1;
1901 /*d_printf(">>>lseek: resolving %s\n", path);*/
1902 if (!cli_resolve_path("", &file->srv->cli, path,
1903 &targetcli, targetpath))
1905 d_printf("Could not resolve %s\n", path);
1906 return -1;
1908 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1910 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1911 &size, NULL, NULL, NULL, NULL, NULL))
1913 SMB_OFF_T b_size = size;
1914 if (!cli_getattrE(targetcli, file->cli_fd,
1915 NULL, &b_size, NULL, NULL, NULL))
1917 errno = EINVAL;
1918 return -1;
1919 } else
1920 size = b_size;
1922 file->offset = size + offset;
1923 break;
1925 default:
1926 errno = EINVAL;
1927 break;
1931 return file->offset;
1936 * Generate an inode number from file name for those things that need it
1939 static ino_t
1940 smbc_inode(SMBCCTX *context,
1941 const char *name)
1944 if (!context || !context->internal ||
1945 !context->internal->_initialized) {
1947 errno = EINVAL;
1948 return -1;
1952 if (!*name) return 2; /* FIXME, why 2 ??? */
1953 return (ino_t)str_checksum(name);
1958 * Routine to put basic stat info into a stat structure ... Used by stat and
1959 * fstat below.
1962 static int
1963 smbc_setup_stat(SMBCCTX *context,
1964 struct stat *st,
1965 char *fname,
1966 SMB_OFF_T size,
1967 int mode)
1970 st->st_mode = 0;
1972 if (IS_DOS_DIR(mode)) {
1973 st->st_mode = SMBC_DIR_MODE;
1974 } else {
1975 st->st_mode = SMBC_FILE_MODE;
1978 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1979 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1980 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1981 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1983 st->st_size = size;
1984 #ifdef HAVE_STAT_ST_BLKSIZE
1985 st->st_blksize = 512;
1986 #endif
1987 #ifdef HAVE_STAT_ST_BLOCKS
1988 st->st_blocks = (size+511)/512;
1989 #endif
1990 st->st_uid = getuid();
1991 st->st_gid = getgid();
1993 if (IS_DOS_DIR(mode)) {
1994 st->st_nlink = 2;
1995 } else {
1996 st->st_nlink = 1;
1999 if (st->st_ino == 0) {
2000 st->st_ino = smbc_inode(context, fname);
2003 return True; /* FIXME: Is this needed ? */
2008 * Routine to stat a file given a name
2011 static int
2012 smbc_stat_ctx(SMBCCTX *context,
2013 const char *fname,
2014 struct stat *st)
2016 SMBCSRV *srv;
2017 fstring server;
2018 fstring share;
2019 fstring user;
2020 fstring password;
2021 fstring workgroup;
2022 pstring path;
2023 time_t m_time = 0;
2024 time_t a_time = 0;
2025 time_t c_time = 0;
2026 SMB_OFF_T size = 0;
2027 uint16 mode = 0;
2028 SMB_INO_T ino = 0;
2030 if (!context || !context->internal ||
2031 !context->internal->_initialized) {
2033 errno = EINVAL; /* Best I can think of ... */
2034 return -1;
2038 if (!fname) {
2040 errno = EINVAL;
2041 return -1;
2045 DEBUG(4, ("smbc_stat(%s)\n", fname));
2047 if (smbc_parse_path(context, fname,
2048 workgroup, sizeof(workgroup),
2049 server, sizeof(server),
2050 share, sizeof(share),
2051 path, sizeof(path),
2052 user, sizeof(user),
2053 password, sizeof(password),
2054 NULL, 0)) {
2055 errno = EINVAL;
2056 return -1;
2059 if (user[0] == (char)0) fstrcpy(user, context->user);
2061 srv = smbc_server(context, True,
2062 server, share, workgroup, user, password);
2064 if (!srv) {
2065 return -1; /* errno set by smbc_server */
2068 if (!smbc_getatr(context, srv, path, &mode, &size,
2069 &c_time, &a_time, &m_time, &ino)) {
2071 errno = smbc_errno(context, &srv->cli);
2072 return -1;
2076 st->st_ino = ino;
2078 smbc_setup_stat(context, st, path, size, mode);
2080 st->st_atime = a_time;
2081 st->st_ctime = c_time;
2082 st->st_mtime = m_time;
2083 st->st_dev = srv->dev;
2085 return 0;
2090 * Routine to stat a file given an fd
2093 static int
2094 smbc_fstat_ctx(SMBCCTX *context,
2095 SMBCFILE *file,
2096 struct stat *st)
2098 time_t c_time;
2099 time_t a_time;
2100 time_t m_time;
2101 SMB_OFF_T size;
2102 uint16 mode;
2103 fstring server;
2104 fstring share;
2105 fstring user;
2106 fstring password;
2107 pstring path;
2108 pstring targetpath;
2109 struct cli_state *targetcli;
2110 SMB_INO_T ino = 0;
2112 if (!context || !context->internal ||
2113 !context->internal->_initialized) {
2115 errno = EINVAL;
2116 return -1;
2120 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2122 errno = EBADF;
2123 return -1;
2127 if (!file->file) {
2129 return context->fstatdir(context, file, st);
2133 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2134 if (smbc_parse_path(context, file->fname,
2135 NULL, 0,
2136 server, sizeof(server),
2137 share, sizeof(share),
2138 path, sizeof(path),
2139 user, sizeof(user),
2140 password, sizeof(password),
2141 NULL, 0)) {
2142 errno = EINVAL;
2143 return -1;
2146 /*d_printf(">>>fstat: resolving %s\n", path);*/
2147 if (!cli_resolve_path("", &file->srv->cli, path,
2148 &targetcli, targetpath))
2150 d_printf("Could not resolve %s\n", path);
2151 return -1;
2153 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2155 if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2156 &c_time, &a_time, &m_time, NULL, &ino)) {
2157 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2158 &c_time, &a_time, &m_time)) {
2160 errno = EINVAL;
2161 return -1;
2165 st->st_ino = ino;
2167 smbc_setup_stat(context, st, file->fname, size, mode);
2169 st->st_atime = a_time;
2170 st->st_ctime = c_time;
2171 st->st_mtime = m_time;
2172 st->st_dev = file->srv->dev;
2174 return 0;
2179 * Routine to open a directory
2180 * We accept the URL syntax explained in smbc_parse_path(), above.
2183 static void
2184 smbc_remove_dir(SMBCFILE *dir)
2186 struct smbc_dir_list *d,*f;
2188 d = dir->dir_list;
2189 while (d) {
2191 f = d; d = d->next;
2193 SAFE_FREE(f->dirent);
2194 SAFE_FREE(f);
2198 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2202 static int
2203 add_dirent(SMBCFILE *dir,
2204 const char *name,
2205 const char *comment,
2206 uint32 type)
2208 struct smbc_dirent *dirent;
2209 int size;
2210 int name_length = (name == NULL ? 0 : strlen(name));
2211 int comment_len = (comment == NULL ? 0 : strlen(comment));
2214 * Allocate space for the dirent, which must be increased by the
2215 * size of the name and the comment and 1 each for the null terminator.
2218 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2220 dirent = SMB_MALLOC(size);
2222 if (!dirent) {
2224 dir->dir_error = ENOMEM;
2225 return -1;
2229 ZERO_STRUCTP(dirent);
2231 if (dir->dir_list == NULL) {
2233 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2234 if (!dir->dir_list) {
2236 SAFE_FREE(dirent);
2237 dir->dir_error = ENOMEM;
2238 return -1;
2241 ZERO_STRUCTP(dir->dir_list);
2243 dir->dir_end = dir->dir_next = dir->dir_list;
2245 else {
2247 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2249 if (!dir->dir_end->next) {
2251 SAFE_FREE(dirent);
2252 dir->dir_error = ENOMEM;
2253 return -1;
2256 ZERO_STRUCTP(dir->dir_end->next);
2258 dir->dir_end = dir->dir_end->next;
2261 dir->dir_end->next = NULL;
2262 dir->dir_end->dirent = dirent;
2264 dirent->smbc_type = type;
2265 dirent->namelen = name_length;
2266 dirent->commentlen = comment_len;
2267 dirent->dirlen = size;
2270 * dirent->namelen + 1 includes the null (no null termination needed)
2271 * Ditto for dirent->commentlen.
2272 * The space for the two null bytes was allocated.
2274 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2275 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2276 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2278 return 0;
2282 static void
2283 list_unique_wg_fn(const char *name,
2284 uint32 type,
2285 const char *comment,
2286 void *state)
2288 SMBCFILE *dir = (SMBCFILE *)state;
2289 struct smbc_dir_list *dir_list;
2290 struct smbc_dirent *dirent;
2291 int dirent_type;
2292 int do_remove = 0;
2294 dirent_type = dir->dir_type;
2296 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2298 /* An error occurred, what do we do? */
2299 /* FIXME: Add some code here */
2302 /* Point to the one just added */
2303 dirent = dir->dir_end->dirent;
2305 /* See if this was a duplicate */
2306 for (dir_list = dir->dir_list;
2307 dir_list != dir->dir_end;
2308 dir_list = dir_list->next) {
2309 if (! do_remove &&
2310 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2311 /* Duplicate. End end of list need to be removed. */
2312 do_remove = 1;
2315 if (do_remove && dir_list->next == dir->dir_end) {
2316 /* Found the end of the list. Remove it. */
2317 dir->dir_end = dir_list;
2318 free(dir_list->next);
2319 free(dirent);
2320 dir_list->next = NULL;
2321 break;
2326 static void
2327 list_fn(const char *name,
2328 uint32 type,
2329 const char *comment,
2330 void *state)
2332 SMBCFILE *dir = (SMBCFILE *)state;
2333 int dirent_type;
2336 * We need to process the type a little ...
2338 * Disk share = 0x00000000
2339 * Print share = 0x00000001
2340 * Comms share = 0x00000002 (obsolete?)
2341 * IPC$ share = 0x00000003
2343 * administrative shares:
2344 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2347 if (dir->dir_type == SMBC_FILE_SHARE) {
2349 switch (type) {
2350 case 0 | 0x80000000:
2351 case 0:
2352 dirent_type = SMBC_FILE_SHARE;
2353 break;
2355 case 1:
2356 dirent_type = SMBC_PRINTER_SHARE;
2357 break;
2359 case 2:
2360 dirent_type = SMBC_COMMS_SHARE;
2361 break;
2363 case 3 | 0x80000000:
2364 case 3:
2365 dirent_type = SMBC_IPC_SHARE;
2366 break;
2368 default:
2369 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2370 break;
2373 else {
2374 dirent_type = dir->dir_type;
2377 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2379 /* An error occurred, what do we do? */
2380 /* FIXME: Add some code here */
2385 static void
2386 dir_list_fn(const char *mnt,
2387 file_info *finfo,
2388 const char *mask,
2389 void *state)
2392 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2393 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2395 /* Handle an error ... */
2397 /* FIXME: Add some code ... */
2403 static int
2404 net_share_enum_rpc(struct cli_state *cli,
2405 void (*fn)(const char *name,
2406 uint32 type,
2407 const char *comment,
2408 void *state),
2409 void *state)
2411 int i;
2412 WERROR result;
2413 ENUM_HND enum_hnd;
2414 uint32 info_level = 1;
2415 uint32 preferred_len = 0xffffffff;
2416 uint32 type;
2417 SRV_SHARE_INFO_CTR ctr;
2418 fstring name = "";
2419 fstring comment = "";
2420 void *mem_ctx;
2421 struct rpc_pipe_client *pipe_hnd;
2422 NTSTATUS nt_status;
2424 /* Open the server service pipe */
2425 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2426 if (!pipe_hnd) {
2427 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2428 return -1;
2431 /* Allocate a context for parsing and for the entries in "ctr" */
2432 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2433 if (mem_ctx == NULL) {
2434 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2435 cli_rpc_pipe_close(pipe_hnd);
2436 return -1;
2439 /* Issue the NetShareEnum RPC call and retrieve the response */
2440 init_enum_hnd(&enum_hnd, 0);
2441 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2442 mem_ctx,
2443 info_level,
2444 &ctr,
2445 preferred_len,
2446 &enum_hnd);
2448 /* Was it successful? */
2449 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2450 /* Nope. Go clean up. */
2451 goto done;
2454 /* For each returned entry... */
2455 for (i = 0; i < ctr.num_entries; i++) {
2457 /* pull out the share name */
2458 rpcstr_pull_unistr2_fstring(
2459 name, &ctr.share.info1[i].info_1_str.uni_netname);
2461 /* pull out the share's comment */
2462 rpcstr_pull_unistr2_fstring(
2463 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2465 /* Get the type value */
2466 type = ctr.share.info1[i].info_1.type;
2468 /* Add this share to the list */
2469 (*fn)(name, type, comment, state);
2472 done:
2473 /* Close the server service pipe */
2474 cli_rpc_pipe_close(pipe_hnd);
2476 /* Free all memory which was allocated for this request */
2477 TALLOC_FREE(mem_ctx);
2479 /* Tell 'em if it worked */
2480 return W_ERROR_IS_OK(result) ? 0 : -1;
2485 static SMBCFILE *
2486 smbc_opendir_ctx(SMBCCTX *context,
2487 const char *fname)
2489 fstring server, share, user, password, options;
2490 pstring workgroup;
2491 pstring path;
2492 uint16 mode;
2493 char *p;
2494 SMBCSRV *srv = NULL;
2495 SMBCFILE *dir = NULL;
2496 struct in_addr rem_ip;
2498 if (!context || !context->internal ||
2499 !context->internal->_initialized) {
2500 DEBUG(4, ("no valid context\n"));
2501 errno = EINVAL + 8192;
2502 return NULL;
2506 if (!fname) {
2507 DEBUG(4, ("no valid fname\n"));
2508 errno = EINVAL + 8193;
2509 return NULL;
2512 if (smbc_parse_path(context, fname,
2513 workgroup, sizeof(workgroup),
2514 server, sizeof(server),
2515 share, sizeof(share),
2516 path, sizeof(path),
2517 user, sizeof(user),
2518 password, sizeof(password),
2519 options, sizeof(options))) {
2520 DEBUG(4, ("no valid path\n"));
2521 errno = EINVAL + 8194;
2522 return NULL;
2525 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2526 "path='%s' options='%s'\n",
2527 fname, server, share, path, options));
2529 /* Ensure the options are valid */
2530 if (smbc_check_options(server, share, path, options)) {
2531 DEBUG(4, ("unacceptable options (%s)\n", options));
2532 errno = EINVAL + 8195;
2533 return NULL;
2536 if (user[0] == (char)0) fstrcpy(user, context->user);
2538 dir = SMB_MALLOC_P(SMBCFILE);
2540 if (!dir) {
2542 errno = ENOMEM;
2543 return NULL;
2547 ZERO_STRUCTP(dir);
2549 dir->cli_fd = 0;
2550 dir->fname = SMB_STRDUP(fname);
2551 dir->srv = NULL;
2552 dir->offset = 0;
2553 dir->file = False;
2554 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2556 if (server[0] == (char)0) {
2558 int i;
2559 int count;
2560 int max_lmb_count;
2561 struct ip_service *ip_list;
2562 struct ip_service server_addr;
2563 struct user_auth_info u_info;
2564 struct cli_state *cli;
2566 if (share[0] != (char)0 || path[0] != (char)0) {
2568 errno = EINVAL + 8196;
2569 if (dir) {
2570 SAFE_FREE(dir->fname);
2571 SAFE_FREE(dir);
2573 return NULL;
2576 /* Determine how many local master browsers to query */
2577 max_lmb_count = (context->options.browse_max_lmb_count == 0
2578 ? INT_MAX
2579 : context->options.browse_max_lmb_count);
2581 pstrcpy(u_info.username, user);
2582 pstrcpy(u_info.password, password);
2585 * We have server and share and path empty but options
2586 * requesting that we scan all master browsers for their list
2587 * of workgroups/domains. This implies that we must first try
2588 * broadcast queries to find all master browsers, and if that
2589 * doesn't work, then try our other methods which return only
2590 * a single master browser.
2593 ip_list = NULL;
2594 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2596 SAFE_FREE(ip_list);
2598 if (!find_master_ip(workgroup, &server_addr.ip)) {
2600 if (dir) {
2601 SAFE_FREE(dir->fname);
2602 SAFE_FREE(dir);
2604 errno = ENOENT;
2605 return NULL;
2608 ip_list = &server_addr;
2609 count = 1;
2612 for (i = 0; i < count && i < max_lmb_count; i++) {
2613 DEBUG(99, ("Found master browser %d of %d: %s\n",
2614 i+1, MAX(count, max_lmb_count),
2615 inet_ntoa(ip_list[i].ip)));
2617 cli = get_ipc_connect_master_ip(&ip_list[i],
2618 workgroup, &u_info);
2619 /* cli == NULL is the master browser refused to talk or
2620 could not be found */
2621 if ( !cli )
2622 continue;
2624 fstrcpy(server, cli->desthost);
2625 cli_shutdown(cli);
2627 DEBUG(4, ("using workgroup %s %s\n",
2628 workgroup, server));
2631 * For each returned master browser IP address, get a
2632 * connection to IPC$ on the server if we do not
2633 * already have one, and determine the
2634 * workgroups/domains that it knows about.
2637 srv = smbc_server(context, True, server, "IPC$",
2638 workgroup, user, password);
2639 if (!srv) {
2640 continue;
2643 dir->srv = srv;
2644 dir->dir_type = SMBC_WORKGROUP;
2646 /* Now, list the stuff ... */
2648 if (!cli_NetServerEnum(&srv->cli,
2649 workgroup,
2650 SV_TYPE_DOMAIN_ENUM,
2651 list_unique_wg_fn,
2652 (void *)dir)) {
2653 continue;
2657 SAFE_FREE(ip_list);
2658 } else {
2660 * Server not an empty string ... Check the rest and see what
2661 * gives
2663 if (*share == '\0') {
2664 if (*path != '\0') {
2666 /* Should not have empty share with path */
2667 errno = EINVAL + 8197;
2668 if (dir) {
2669 SAFE_FREE(dir->fname);
2670 SAFE_FREE(dir);
2672 return NULL;
2677 * We don't know if <server> is really a server name
2678 * or is a workgroup/domain name. If we already have
2679 * a server structure for it, we'll use it.
2680 * Otherwise, check to see if <server><1D>,
2681 * <server><1B>, or <server><20> translates. We check
2682 * to see if <server> is an IP address first.
2686 * See if we have an existing server. Do not
2687 * establish a connection if one does not already
2688 * exist.
2690 srv = smbc_server(context, False, server, "IPC$",
2691 workgroup, user, password);
2694 * If no existing server and not an IP addr, look for
2695 * LMB or DMB
2697 if (!srv &&
2698 !is_ipaddress(server) &&
2699 (resolve_name(server, &rem_ip, 0x1d) || /* LMB */
2700 resolve_name(server, &rem_ip, 0x1b) )) { /* DMB */
2702 fstring buserver;
2704 dir->dir_type = SMBC_SERVER;
2707 * Get the backup list ...
2709 if (!name_status_find(server, 0, 0,
2710 rem_ip, buserver)) {
2712 DEBUG(0, ("Could not get name of "
2713 "local/domain master browser "
2714 "for server %s\n", server));
2715 if (dir) {
2716 SAFE_FREE(dir->fname);
2717 SAFE_FREE(dir);
2719 errno = EPERM;
2720 return NULL;
2725 * Get a connection to IPC$ on the server if
2726 * we do not already have one
2728 srv = smbc_server(context, True,
2729 buserver, "IPC$",
2730 workgroup, user, password);
2731 if (!srv) {
2732 DEBUG(0, ("got no contact to IPC$\n"));
2733 if (dir) {
2734 SAFE_FREE(dir->fname);
2735 SAFE_FREE(dir);
2737 return NULL;
2741 dir->srv = srv;
2743 /* Now, list the servers ... */
2744 if (!cli_NetServerEnum(&srv->cli, server,
2745 0x0000FFFE, list_fn,
2746 (void *)dir)) {
2748 if (dir) {
2749 SAFE_FREE(dir->fname);
2750 SAFE_FREE(dir);
2752 return NULL;
2754 } else if (srv ||
2755 (resolve_name(server, &rem_ip, 0x20))) {
2757 /* If we hadn't found the server, get one now */
2758 if (!srv) {
2759 srv = smbc_server(context, True,
2760 server, "IPC$",
2761 workgroup,
2762 user, password);
2765 if (!srv) {
2766 if (dir) {
2767 SAFE_FREE(dir->fname);
2768 SAFE_FREE(dir);
2770 return NULL;
2774 dir->dir_type = SMBC_FILE_SHARE;
2775 dir->srv = srv;
2777 /* List the shares ... */
2779 if (net_share_enum_rpc(
2780 &srv->cli,
2781 list_fn,
2782 (void *) dir) < 0 &&
2783 cli_RNetShareEnum(
2784 &srv->cli,
2785 list_fn,
2786 (void *)dir) < 0) {
2788 errno = cli_errno(&srv->cli);
2789 if (dir) {
2790 SAFE_FREE(dir->fname);
2791 SAFE_FREE(dir);
2793 return NULL;
2796 } else {
2797 /* Neither the workgroup nor server exists */
2798 errno = ECONNREFUSED;
2799 if (dir) {
2800 SAFE_FREE(dir->fname);
2801 SAFE_FREE(dir);
2803 return NULL;
2807 else {
2809 * The server and share are specified ... work from
2810 * there ...
2812 pstring targetpath;
2813 struct cli_state *targetcli;
2815 /* We connect to the server and list the directory */
2816 dir->dir_type = SMBC_FILE_SHARE;
2818 srv = smbc_server(context, True, server, share,
2819 workgroup, user, password);
2821 if (!srv) {
2823 if (dir) {
2824 SAFE_FREE(dir->fname);
2825 SAFE_FREE(dir);
2827 return NULL;
2831 dir->srv = srv;
2833 /* Now, list the files ... */
2835 p = path + strlen(path);
2836 pstrcat(path, "\\*");
2838 if (!cli_resolve_path("", &srv->cli, path,
2839 &targetcli, targetpath))
2841 d_printf("Could not resolve %s\n", path);
2842 if (dir) {
2843 SAFE_FREE(dir->fname);
2844 SAFE_FREE(dir);
2846 return NULL;
2849 if (cli_list(targetcli, targetpath,
2850 aDIR | aSYSTEM | aHIDDEN,
2851 dir_list_fn, (void *)dir) < 0) {
2853 if (dir) {
2854 SAFE_FREE(dir->fname);
2855 SAFE_FREE(dir);
2857 errno = smbc_errno(context, targetcli);
2859 if (errno == EINVAL) {
2861 * See if they asked to opendir something
2862 * other than a directory. If so, the
2863 * converted error value we got would have
2864 * been EINVAL rather than ENOTDIR.
2866 *p = '\0'; /* restore original path */
2868 if (smbc_getatr(context, srv, path,
2869 &mode, NULL,
2870 NULL, NULL, NULL,
2871 NULL) &&
2872 ! IS_DOS_DIR(mode)) {
2874 /* It is. Correct the error value */
2875 errno = ENOTDIR;
2879 return NULL;
2886 DLIST_ADD(context->internal->_files, dir);
2887 return dir;
2892 * Routine to close a directory
2895 static int
2896 smbc_closedir_ctx(SMBCCTX *context,
2897 SMBCFILE *dir)
2900 if (!context || !context->internal ||
2901 !context->internal->_initialized) {
2903 errno = EINVAL;
2904 return -1;
2908 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2910 errno = EBADF;
2911 return -1;
2915 smbc_remove_dir(dir); /* Clean it up */
2917 DLIST_REMOVE(context->internal->_files, dir);
2919 if (dir) {
2921 SAFE_FREE(dir->fname);
2922 SAFE_FREE(dir); /* Free the space too */
2925 return 0;
2929 static void
2930 smbc_readdir_internal(SMBCCTX * context,
2931 struct smbc_dirent *dest,
2932 struct smbc_dirent *src,
2933 int max_namebuf_len)
2935 if (context->options.urlencode_readdir_entries) {
2937 /* url-encode the name. get back remaining buffer space */
2938 max_namebuf_len =
2939 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2941 /* We now know the name length */
2942 dest->namelen = strlen(dest->name);
2944 /* Save the pointer to the beginning of the comment */
2945 dest->comment = dest->name + dest->namelen + 1;
2947 /* Copy the comment */
2948 strncpy(dest->comment, src->comment, max_namebuf_len - 1);
2949 dest->comment[max_namebuf_len - 1] = '\0';
2951 /* Save other fields */
2952 dest->smbc_type = src->smbc_type;
2953 dest->commentlen = strlen(dest->comment);
2954 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2955 (char *) dest);
2956 } else {
2958 /* No encoding. Just copy the entry as is. */
2959 memcpy(dest, src, src->dirlen);
2960 dest->comment = (char *)(&dest->name + src->namelen + 1);
2966 * Routine to get a directory entry
2969 struct smbc_dirent *
2970 smbc_readdir_ctx(SMBCCTX *context,
2971 SMBCFILE *dir)
2973 int maxlen;
2974 struct smbc_dirent *dirp, *dirent;
2976 /* Check that all is ok first ... */
2978 if (!context || !context->internal ||
2979 !context->internal->_initialized) {
2981 errno = EINVAL;
2982 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2983 return NULL;
2987 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2989 errno = EBADF;
2990 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2991 return NULL;
2995 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2997 errno = ENOTDIR;
2998 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2999 return NULL;
3003 if (!dir->dir_next) {
3004 return NULL;
3007 dirent = dir->dir_next->dirent;
3008 if (!dirent) {
3010 errno = ENOENT;
3011 return NULL;
3015 dirp = (struct smbc_dirent *)context->internal->_dirent;
3016 maxlen = (sizeof(context->internal->_dirent) -
3017 sizeof(struct smbc_dirent));
3019 smbc_readdir_internal(context, dirp, dirent, maxlen);
3021 dir->dir_next = dir->dir_next->next;
3023 return dirp;
3027 * Routine to get directory entries
3030 static int
3031 smbc_getdents_ctx(SMBCCTX *context,
3032 SMBCFILE *dir,
3033 struct smbc_dirent *dirp,
3034 int count)
3036 int rem = count;
3037 int reqd;
3038 int maxlen;
3039 char *ndir = (char *)dirp;
3040 struct smbc_dir_list *dirlist;
3042 /* Check that all is ok first ... */
3044 if (!context || !context->internal ||
3045 !context->internal->_initialized) {
3047 errno = EINVAL;
3048 return -1;
3052 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3054 errno = EBADF;
3055 return -1;
3059 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3061 errno = ENOTDIR;
3062 return -1;
3067 * Now, retrieve the number of entries that will fit in what was passed
3068 * We have to figure out if the info is in the list, or we need to
3069 * send a request to the server to get the info.
3072 while ((dirlist = dir->dir_next)) {
3073 struct smbc_dirent *dirent;
3075 if (!dirlist->dirent) {
3077 errno = ENOENT; /* Bad error */
3078 return -1;
3082 /* Do urlencoding of next entry, if so selected */
3083 dirent = (struct smbc_dirent *)context->internal->_dirent;
3084 maxlen = (sizeof(context->internal->_dirent) -
3085 sizeof(struct smbc_dirent));
3086 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3088 reqd = dirent->dirlen;
3090 if (rem < reqd) {
3092 if (rem < count) { /* We managed to copy something */
3094 errno = 0;
3095 return count - rem;
3098 else { /* Nothing copied ... */
3100 errno = EINVAL; /* Not enough space ... */
3101 return -1;
3107 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3109 ((struct smbc_dirent *)ndir)->comment =
3110 (char *)(&((struct smbc_dirent *)ndir)->name +
3111 dirent->namelen +
3114 ndir += reqd;
3116 rem -= reqd;
3118 dir->dir_next = dirlist = dirlist -> next;
3121 if (rem == count)
3122 return 0;
3123 else
3124 return count - rem;
3129 * Routine to create a directory ...
3132 static int
3133 smbc_mkdir_ctx(SMBCCTX *context,
3134 const char *fname,
3135 mode_t mode)
3137 SMBCSRV *srv;
3138 fstring server;
3139 fstring share;
3140 fstring user;
3141 fstring password;
3142 fstring workgroup;
3143 pstring path, targetpath;
3144 struct cli_state *targetcli;
3146 if (!context || !context->internal ||
3147 !context->internal->_initialized) {
3149 errno = EINVAL;
3150 return -1;
3154 if (!fname) {
3156 errno = EINVAL;
3157 return -1;
3161 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3163 if (smbc_parse_path(context, fname,
3164 workgroup, sizeof(workgroup),
3165 server, sizeof(server),
3166 share, sizeof(share),
3167 path, sizeof(path),
3168 user, sizeof(user),
3169 password, sizeof(password),
3170 NULL, 0)) {
3171 errno = EINVAL;
3172 return -1;
3175 if (user[0] == (char)0) fstrcpy(user, context->user);
3177 srv = smbc_server(context, True,
3178 server, share, workgroup, user, password);
3180 if (!srv) {
3182 return -1; /* errno set by smbc_server */
3186 /*d_printf(">>>mkdir: resolving %s\n", path);*/
3187 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3189 d_printf("Could not resolve %s\n", path);
3190 return -1;
3192 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3194 if (!cli_mkdir(targetcli, targetpath)) {
3196 errno = smbc_errno(context, targetcli);
3197 return -1;
3201 return 0;
3206 * Our list function simply checks to see if a directory is not empty
3209 static int smbc_rmdir_dirempty = True;
3211 static void
3212 rmdir_list_fn(const char *mnt,
3213 file_info *finfo,
3214 const char *mask,
3215 void *state)
3217 if (strncmp(finfo->name, ".", 1) != 0 &&
3218 strncmp(finfo->name, "..", 2) != 0) {
3220 smbc_rmdir_dirempty = False;
3225 * Routine to remove a directory
3228 static int
3229 smbc_rmdir_ctx(SMBCCTX *context,
3230 const char *fname)
3232 SMBCSRV *srv;
3233 fstring server;
3234 fstring share;
3235 fstring user;
3236 fstring password;
3237 fstring workgroup;
3238 pstring path;
3239 pstring targetpath;
3240 struct cli_state *targetcli;
3242 if (!context || !context->internal ||
3243 !context->internal->_initialized) {
3245 errno = EINVAL;
3246 return -1;
3250 if (!fname) {
3252 errno = EINVAL;
3253 return -1;
3257 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3259 if (smbc_parse_path(context, fname,
3260 workgroup, sizeof(workgroup),
3261 server, sizeof(server),
3262 share, sizeof(share),
3263 path, sizeof(path),
3264 user, sizeof(user),
3265 password, sizeof(password),
3266 NULL, 0))
3268 errno = EINVAL;
3269 return -1;
3272 if (user[0] == (char)0) fstrcpy(user, context->user);
3274 srv = smbc_server(context, True,
3275 server, share, workgroup, user, password);
3277 if (!srv) {
3279 return -1; /* errno set by smbc_server */
3283 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3284 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3286 d_printf("Could not resolve %s\n", path);
3287 return -1;
3289 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3292 if (!cli_rmdir(targetcli, targetpath)) {
3294 errno = smbc_errno(context, targetcli);
3296 if (errno == EACCES) { /* Check if the dir empty or not */
3298 /* Local storage to avoid buffer overflows */
3299 pstring lpath;
3301 smbc_rmdir_dirempty = True; /* Make this so ... */
3303 pstrcpy(lpath, targetpath);
3304 pstrcat(lpath, "\\*");
3306 if (cli_list(targetcli, lpath,
3307 aDIR | aSYSTEM | aHIDDEN,
3308 rmdir_list_fn, NULL) < 0) {
3310 /* Fix errno to ignore latest error ... */
3311 DEBUG(5, ("smbc_rmdir: "
3312 "cli_list returned an error: %d\n",
3313 smbc_errno(context, targetcli)));
3314 errno = EACCES;
3318 if (smbc_rmdir_dirempty)
3319 errno = EACCES;
3320 else
3321 errno = ENOTEMPTY;
3325 return -1;
3329 return 0;
3334 * Routine to return the current directory position
3337 static off_t
3338 smbc_telldir_ctx(SMBCCTX *context,
3339 SMBCFILE *dir)
3341 off_t ret_val; /* Squash warnings about cast */
3343 if (!context || !context->internal ||
3344 !context->internal->_initialized) {
3346 errno = EINVAL;
3347 return -1;
3351 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3353 errno = EBADF;
3354 return -1;
3358 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3360 errno = ENOTDIR;
3361 return -1;
3366 * We return the pointer here as the offset
3368 ret_val = (off_t)(long)dir->dir_next;
3369 return ret_val;
3374 * A routine to run down the list and see if the entry is OK
3377 struct smbc_dir_list *
3378 smbc_check_dir_ent(struct smbc_dir_list *list,
3379 struct smbc_dirent *dirent)
3382 /* Run down the list looking for what we want */
3384 if (dirent) {
3386 struct smbc_dir_list *tmp = list;
3388 while (tmp) {
3390 if (tmp->dirent == dirent)
3391 return tmp;
3393 tmp = tmp->next;
3399 return NULL; /* Not found, or an error */
3405 * Routine to seek on a directory
3408 static int
3409 smbc_lseekdir_ctx(SMBCCTX *context,
3410 SMBCFILE *dir,
3411 off_t offset)
3413 long int l_offset = offset; /* Handle problems of size */
3414 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3415 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3417 if (!context || !context->internal ||
3418 !context->internal->_initialized) {
3420 errno = EINVAL;
3421 return -1;
3425 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3427 errno = ENOTDIR;
3428 return -1;
3432 /* Now, check what we were passed and see if it is OK ... */
3434 if (dirent == NULL) { /* Seek to the begining of the list */
3436 dir->dir_next = dir->dir_list;
3437 return 0;
3441 /* Now, run down the list and make sure that the entry is OK */
3442 /* This may need to be changed if we change the format of the list */
3444 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3446 errno = EINVAL; /* Bad entry */
3447 return -1;
3451 dir->dir_next = list_ent;
3453 return 0;
3458 * Routine to fstat a dir
3461 static int
3462 smbc_fstatdir_ctx(SMBCCTX *context,
3463 SMBCFILE *dir,
3464 struct stat *st)
3467 if (!context || !context->internal ||
3468 !context->internal->_initialized) {
3470 errno = EINVAL;
3471 return -1;
3475 /* No code yet ... */
3477 return 0;
3481 static int
3482 smbc_chmod_ctx(SMBCCTX *context,
3483 const char *fname,
3484 mode_t newmode)
3486 SMBCSRV *srv;
3487 fstring server;
3488 fstring share;
3489 fstring user;
3490 fstring password;
3491 fstring workgroup;
3492 pstring path;
3493 uint16 mode;
3495 if (!context || !context->internal ||
3496 !context->internal->_initialized) {
3498 errno = EINVAL; /* Best I can think of ... */
3499 return -1;
3503 if (!fname) {
3505 errno = EINVAL;
3506 return -1;
3510 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3512 if (smbc_parse_path(context, fname,
3513 workgroup, sizeof(workgroup),
3514 server, sizeof(server),
3515 share, sizeof(share),
3516 path, sizeof(path),
3517 user, sizeof(user),
3518 password, sizeof(password),
3519 NULL, 0)) {
3520 errno = EINVAL;
3521 return -1;
3524 if (user[0] == (char)0) fstrcpy(user, context->user);
3526 srv = smbc_server(context, True,
3527 server, share, workgroup, user, password);
3529 if (!srv) {
3530 return -1; /* errno set by smbc_server */
3533 mode = 0;
3535 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3536 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3537 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3538 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3540 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3541 errno = smbc_errno(context, &srv->cli);
3542 return -1;
3545 return 0;
3548 static int
3549 smbc_utimes_ctx(SMBCCTX *context,
3550 const char *fname,
3551 struct timeval *tbuf)
3553 SMBCSRV *srv;
3554 fstring server;
3555 fstring share;
3556 fstring user;
3557 fstring password;
3558 fstring workgroup;
3559 pstring path;
3560 time_t a_time;
3561 time_t m_time;
3563 if (!context || !context->internal ||
3564 !context->internal->_initialized) {
3566 errno = EINVAL; /* Best I can think of ... */
3567 return -1;
3571 if (!fname) {
3573 errno = EINVAL;
3574 return -1;
3578 if (tbuf == NULL) {
3579 a_time = m_time = time(NULL);
3580 } else {
3581 a_time = tbuf[0].tv_sec;
3582 m_time = tbuf[1].tv_sec;
3585 if (DEBUGLVL(4))
3587 char *p;
3588 char atimebuf[32];
3589 char mtimebuf[32];
3591 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf) - 1);
3592 atimebuf[sizeof(atimebuf) - 1] = '\0';
3593 if ((p = strchr(atimebuf, '\n')) != NULL) {
3594 *p = '\0';
3597 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf) - 1);
3598 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3599 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3600 *p = '\0';
3603 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3604 fname, atimebuf, mtimebuf);
3607 if (smbc_parse_path(context, fname,
3608 workgroup, sizeof(workgroup),
3609 server, sizeof(server),
3610 share, sizeof(share),
3611 path, sizeof(path),
3612 user, sizeof(user),
3613 password, sizeof(password),
3614 NULL, 0)) {
3615 errno = EINVAL;
3616 return -1;
3619 if (user[0] == (char)0) fstrcpy(user, context->user);
3621 srv = smbc_server(context, True,
3622 server, share, workgroup, user, password);
3624 if (!srv) {
3625 return -1; /* errno set by smbc_server */
3628 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3629 return -1; /* errno set by smbc_setatr */
3632 return 0;
3636 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3637 However NT4 gives a "The information may have been modified by a
3638 computer running Windows NT 5.0" if denied ACEs do not appear before
3639 allowed ACEs. */
3641 static int
3642 ace_compare(SEC_ACE *ace1,
3643 SEC_ACE *ace2)
3645 if (sec_ace_equal(ace1, ace2))
3646 return 0;
3648 if (ace1->type != ace2->type)
3649 return ace2->type - ace1->type;
3651 if (sid_compare(&ace1->trustee, &ace2->trustee))
3652 return sid_compare(&ace1->trustee, &ace2->trustee);
3654 if (ace1->flags != ace2->flags)
3655 return ace1->flags - ace2->flags;
3657 if (ace1->info.mask != ace2->info.mask)
3658 return ace1->info.mask - ace2->info.mask;
3660 if (ace1->size != ace2->size)
3661 return ace1->size - ace2->size;
3663 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3667 static void
3668 sort_acl(SEC_ACL *the_acl)
3670 uint32 i;
3671 if (!the_acl) return;
3673 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]),
3674 QSORT_CAST ace_compare);
3676 for (i=1;i<the_acl->num_aces;) {
3677 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3678 int j;
3679 for (j=i; j<the_acl->num_aces-1; j++) {
3680 the_acl->ace[j] = the_acl->ace[j+1];
3682 the_acl->num_aces--;
3683 } else {
3684 i++;
3689 /* convert a SID to a string, either numeric or username/group */
3690 static void
3691 convert_sid_to_string(struct cli_state *ipc_cli,
3692 POLICY_HND *pol,
3693 fstring str,
3694 BOOL numeric,
3695 DOM_SID *sid)
3697 char **domains = NULL;
3698 char **names = NULL;
3699 uint32 *types = NULL;
3700 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3701 sid_to_string(str, sid);
3703 if (numeric) {
3704 return; /* no lookup desired */
3707 if (!pipe_hnd) {
3708 return;
3711 /* Ask LSA to convert the sid to a name */
3713 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3714 pol, 1, sid, &domains,
3715 &names, &types)) ||
3716 !domains || !domains[0] || !names || !names[0]) {
3717 return;
3720 /* Converted OK */
3722 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3723 domains[0], lp_winbind_separator(),
3724 names[0]);
3727 /* convert a string to a SID, either numeric or username/group */
3728 static BOOL
3729 convert_string_to_sid(struct cli_state *ipc_cli,
3730 POLICY_HND *pol,
3731 BOOL numeric,
3732 DOM_SID *sid,
3733 const char *str)
3735 uint32 *types = NULL;
3736 DOM_SID *sids = NULL;
3737 BOOL result = True;
3738 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3740 if (!pipe_hnd) {
3741 return False;
3744 if (numeric) {
3745 if (strncmp(str, "S-", 2) == 0) {
3746 return string_to_sid(sid, str);
3749 result = False;
3750 goto done;
3753 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3754 pol, 1, &str, NULL, &sids,
3755 &types))) {
3756 result = False;
3757 goto done;
3760 sid_copy(sid, &sids[0]);
3761 done:
3763 return result;
3767 /* parse an ACE in the same format as print_ace() */
3768 static BOOL
3769 parse_ace(struct cli_state *ipc_cli,
3770 POLICY_HND *pol,
3771 SEC_ACE *ace,
3772 BOOL numeric,
3773 char *str)
3775 char *p;
3776 const char *cp;
3777 fstring tok;
3778 unsigned int atype;
3779 unsigned int aflags;
3780 unsigned int amask;
3781 DOM_SID sid;
3782 SEC_ACCESS mask;
3783 const struct perm_value *v;
3784 struct perm_value {
3785 const char *perm;
3786 uint32 mask;
3789 /* These values discovered by inspection */
3790 static const struct perm_value special_values[] = {
3791 { "R", 0x00120089 },
3792 { "W", 0x00120116 },
3793 { "X", 0x001200a0 },
3794 { "D", 0x00010000 },
3795 { "P", 0x00040000 },
3796 { "O", 0x00080000 },
3797 { NULL, 0 },
3800 static const struct perm_value standard_values[] = {
3801 { "READ", 0x001200a9 },
3802 { "CHANGE", 0x001301bf },
3803 { "FULL", 0x001f01ff },
3804 { NULL, 0 },
3808 ZERO_STRUCTP(ace);
3809 p = strchr_m(str,':');
3810 if (!p) return False;
3811 *p = '\0';
3812 p++;
3813 /* Try to parse numeric form */
3815 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3816 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3817 goto done;
3820 /* Try to parse text form */
3822 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3823 return False;
3826 cp = p;
3827 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3828 return False;
3831 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3832 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3833 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3834 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3835 } else {
3836 return False;
3839 /* Only numeric form accepted for flags at present */
3841 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3842 sscanf(tok, "%i", &aflags))) {
3843 return False;
3846 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3847 return False;
3850 if (strncmp(tok, "0x", 2) == 0) {
3851 if (sscanf(tok, "%i", &amask) != 1) {
3852 return False;
3854 goto done;
3857 for (v = standard_values; v->perm; v++) {
3858 if (strcmp(tok, v->perm) == 0) {
3859 amask = v->mask;
3860 goto done;
3864 p = tok;
3866 while(*p) {
3867 BOOL found = False;
3869 for (v = special_values; v->perm; v++) {
3870 if (v->perm[0] == *p) {
3871 amask |= v->mask;
3872 found = True;
3876 if (!found) return False;
3877 p++;
3880 if (*p) {
3881 return False;
3884 done:
3885 mask.mask = amask;
3886 init_sec_ace(ace, &sid, atype, mask, aflags);
3887 return True;
3890 /* add an ACE to a list of ACEs in a SEC_ACL */
3891 static BOOL
3892 add_ace(SEC_ACL **the_acl,
3893 SEC_ACE *ace,
3894 TALLOC_CTX *ctx)
3896 SEC_ACL *newacl;
3897 SEC_ACE *aces;
3899 if (! *the_acl) {
3900 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3901 return True;
3904 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3905 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3906 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3907 newacl = make_sec_acl(ctx, (*the_acl)->revision,
3908 1+(*the_acl)->num_aces, aces);
3909 SAFE_FREE(aces);
3910 (*the_acl) = newacl;
3911 return True;
3915 /* parse a ascii version of a security descriptor */
3916 static SEC_DESC *
3917 sec_desc_parse(TALLOC_CTX *ctx,
3918 struct cli_state *ipc_cli,
3919 POLICY_HND *pol,
3920 BOOL numeric,
3921 char *str)
3923 const char *p = str;
3924 fstring tok;
3925 SEC_DESC *ret = NULL;
3926 size_t sd_size;
3927 DOM_SID *grp_sid=NULL;
3928 DOM_SID *owner_sid=NULL;
3929 SEC_ACL *dacl=NULL;
3930 int revision=1;
3932 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3934 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3935 revision = strtol(tok+9, NULL, 16);
3936 continue;
3939 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3940 if (owner_sid) {
3941 DEBUG(5, ("OWNER specified more than once!\n"));
3942 goto done;
3944 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3945 if (!owner_sid ||
3946 !convert_string_to_sid(ipc_cli, pol,
3947 numeric,
3948 owner_sid, tok+6)) {
3949 DEBUG(5, ("Failed to parse owner sid\n"));
3950 goto done;
3952 continue;
3955 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3956 if (owner_sid) {
3957 DEBUG(5, ("OWNER specified more than once!\n"));
3958 goto done;
3960 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3961 if (!owner_sid ||
3962 !convert_string_to_sid(ipc_cli, pol,
3963 False,
3964 owner_sid, tok+7)) {
3965 DEBUG(5, ("Failed to parse owner sid\n"));
3966 goto done;
3968 continue;
3971 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3972 if (grp_sid) {
3973 DEBUG(5, ("GROUP specified more than once!\n"));
3974 goto done;
3976 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3977 if (!grp_sid ||
3978 !convert_string_to_sid(ipc_cli, pol,
3979 numeric,
3980 grp_sid, tok+6)) {
3981 DEBUG(5, ("Failed to parse group sid\n"));
3982 goto done;
3984 continue;
3987 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3988 if (grp_sid) {
3989 DEBUG(5, ("GROUP specified more than once!\n"));
3990 goto done;
3992 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3993 if (!grp_sid ||
3994 !convert_string_to_sid(ipc_cli, pol,
3995 False,
3996 grp_sid, tok+6)) {
3997 DEBUG(5, ("Failed to parse group sid\n"));
3998 goto done;
4000 continue;
4003 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
4004 SEC_ACE ace;
4005 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
4006 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4007 goto done;
4009 if(!add_ace(&dacl, &ace, ctx)) {
4010 DEBUG(5, ("Failed to add ACL %s\n", tok));
4011 goto done;
4013 continue;
4016 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
4017 SEC_ACE ace;
4018 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
4019 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4020 goto done;
4022 if(!add_ace(&dacl, &ace, ctx)) {
4023 DEBUG(5, ("Failed to add ACL %s\n", tok));
4024 goto done;
4026 continue;
4029 DEBUG(5, ("Failed to parse security descriptor\n"));
4030 goto done;
4033 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
4034 owner_sid, grp_sid, NULL, dacl, &sd_size);
4036 done:
4037 SAFE_FREE(grp_sid);
4038 SAFE_FREE(owner_sid);
4040 return ret;
4044 /* Obtain the current dos attributes */
4045 static DOS_ATTR_DESC *
4046 dos_attr_query(SMBCCTX *context,
4047 TALLOC_CTX *ctx,
4048 const char *filename,
4049 SMBCSRV *srv)
4051 time_t m_time = 0, a_time = 0, c_time = 0;
4052 SMB_OFF_T size = 0;
4053 uint16 mode = 0;
4054 SMB_INO_T inode = 0;
4055 DOS_ATTR_DESC *ret;
4057 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
4058 if (!ret) {
4059 errno = ENOMEM;
4060 return NULL;
4063 /* Obtain the DOS attributes */
4064 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
4065 &mode, &size,
4066 &c_time, &a_time, &m_time, &inode)) {
4068 errno = smbc_errno(context, &srv->cli);
4069 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
4070 return NULL;
4074 ret->mode = mode;
4075 ret->size = size;
4076 ret->a_time = a_time;
4077 ret->c_time = c_time;
4078 ret->m_time = m_time;
4079 ret->inode = inode;
4081 return ret;
4085 /* parse a ascii version of a security descriptor */
4086 static void
4087 dos_attr_parse(SMBCCTX *context,
4088 DOS_ATTR_DESC *dad,
4089 SMBCSRV *srv,
4090 char *str)
4092 const char *p = str;
4093 fstring tok;
4095 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4097 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
4098 dad->mode = strtol(tok+5, NULL, 16);
4099 continue;
4102 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4103 dad->size = (SMB_OFF_T)atof(tok+5);
4104 continue;
4107 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
4108 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
4109 continue;
4112 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
4113 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
4114 continue;
4117 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
4118 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
4119 continue;
4122 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4123 dad->inode = (SMB_INO_T)atof(tok+6);
4124 continue;
4129 /*****************************************************
4130 Retrieve the acls for a file.
4131 *******************************************************/
4133 static int
4134 cacl_get(SMBCCTX *context,
4135 TALLOC_CTX *ctx,
4136 SMBCSRV *srv,
4137 struct cli_state *ipc_cli,
4138 POLICY_HND *pol,
4139 char *filename,
4140 char *attr_name,
4141 char *buf,
4142 int bufsize)
4144 uint32 i;
4145 int n = 0;
4146 int n_used;
4147 BOOL all;
4148 BOOL all_nt;
4149 BOOL all_nt_acls;
4150 BOOL all_dos;
4151 BOOL some_nt;
4152 BOOL some_dos;
4153 BOOL exclude_nt_revision = False;
4154 BOOL exclude_nt_owner = False;
4155 BOOL exclude_nt_group = False;
4156 BOOL exclude_nt_acl = False;
4157 BOOL exclude_dos_mode = False;
4158 BOOL exclude_dos_size = False;
4159 BOOL exclude_dos_ctime = False;
4160 BOOL exclude_dos_atime = False;
4161 BOOL exclude_dos_mtime = False;
4162 BOOL exclude_dos_inode = False;
4163 BOOL numeric = True;
4164 BOOL determine_size = (bufsize == 0);
4165 int fnum = -1;
4166 SEC_DESC *sd;
4167 fstring sidstr;
4168 fstring name_sandbox;
4169 char *name;
4170 char *pExclude;
4171 char *p;
4172 time_t m_time = 0, a_time = 0, c_time = 0;
4173 SMB_OFF_T size = 0;
4174 uint16 mode = 0;
4175 SMB_INO_T ino = 0;
4176 struct cli_state *cli = &srv->cli;
4178 /* Copy name so we can strip off exclusions (if any are specified) */
4179 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4181 /* Ensure name is null terminated */
4182 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4184 /* Play in the sandbox */
4185 name = name_sandbox;
4187 /* If there are any exclusions, point to them and mask them from name */
4188 if ((pExclude = strchr(name, '!')) != NULL)
4190 *pExclude++ = '\0';
4193 all = (StrnCaseCmp(name, "system.*", 8) == 0);
4194 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4195 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4196 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4197 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4198 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4199 numeric = (* (name + strlen(name) - 1) != '+');
4201 /* Look for exclusions from "all" requests */
4202 if (all || all_nt || all_dos) {
4204 /* Exclusions are delimited by '!' */
4205 for (;
4206 pExclude != NULL;
4207 pExclude = (p == NULL ? NULL : p + 1)) {
4209 /* Find end of this exclusion name */
4210 if ((p = strchr(pExclude, '!')) != NULL)
4212 *p = '\0';
4215 /* Which exclusion name is this? */
4216 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4217 exclude_nt_revision = True;
4219 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4220 exclude_nt_owner = True;
4222 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4223 exclude_nt_group = True;
4225 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4226 exclude_nt_acl = True;
4228 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4229 exclude_dos_mode = True;
4231 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4232 exclude_dos_size = True;
4234 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
4235 exclude_dos_ctime = True;
4237 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
4238 exclude_dos_atime = True;
4240 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
4241 exclude_dos_mtime = True;
4243 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4244 exclude_dos_inode = True;
4246 else {
4247 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4248 pExclude));
4249 errno = ENOATTR;
4250 return -1;
4255 n_used = 0;
4258 * If we are (possibly) talking to an NT or new system and some NT
4259 * attributes have been requested...
4261 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4262 /* Point to the portion after "system.nt_sec_desc." */
4263 name += 19; /* if (all) this will be invalid but unused */
4265 /* ... then obtain any NT attributes which were requested */
4266 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4268 if (fnum == -1) {
4269 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4270 filename, cli_errstr(cli)));
4271 errno = 0;
4272 return -1;
4275 sd = cli_query_secdesc(cli, fnum, ctx);
4277 if (!sd) {
4278 DEBUG(5,
4279 ("cacl_get Failed to query old descriptor\n"));
4280 errno = 0;
4281 return -1;
4284 cli_close(cli, fnum);
4286 if (! exclude_nt_revision) {
4287 if (all || all_nt) {
4288 if (determine_size) {
4289 p = talloc_asprintf(ctx,
4290 "REVISION:%d",
4291 sd->revision);
4292 if (!p) {
4293 errno = ENOMEM;
4294 return -1;
4296 n = strlen(p);
4297 } else {
4298 n = snprintf(buf, bufsize,
4299 "REVISION:%d",
4300 sd->revision);
4302 } else if (StrCaseCmp(name, "revision") == 0) {
4303 if (determine_size) {
4304 p = talloc_asprintf(ctx, "%d",
4305 sd->revision);
4306 if (!p) {
4307 errno = ENOMEM;
4308 return -1;
4310 n = strlen(p);
4311 } else {
4312 n = snprintf(buf, bufsize, "%d",
4313 sd->revision);
4317 if (!determine_size && n > bufsize) {
4318 errno = ERANGE;
4319 return -1;
4321 buf += n;
4322 n_used += n;
4323 bufsize -= n;
4326 if (! exclude_nt_owner) {
4327 /* Get owner and group sid */
4328 if (sd->owner_sid) {
4329 convert_sid_to_string(ipc_cli, pol,
4330 sidstr,
4331 numeric,
4332 sd->owner_sid);
4333 } else {
4334 fstrcpy(sidstr, "");
4337 if (all || all_nt) {
4338 if (determine_size) {
4339 p = talloc_asprintf(ctx, ",OWNER:%s",
4340 sidstr);
4341 if (!p) {
4342 errno = ENOMEM;
4343 return -1;
4345 n = strlen(p);
4346 } else {
4347 n = snprintf(buf, bufsize,
4348 ",OWNER:%s", sidstr);
4350 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4351 if (determine_size) {
4352 p = talloc_asprintf(ctx, "%s", sidstr);
4353 if (!p) {
4354 errno = ENOMEM;
4355 return -1;
4357 n = strlen(p);
4358 } else {
4359 n = snprintf(buf, bufsize, "%s",
4360 sidstr);
4364 if (!determine_size && n > bufsize) {
4365 errno = ERANGE;
4366 return -1;
4368 buf += n;
4369 n_used += n;
4370 bufsize -= n;
4373 if (! exclude_nt_group) {
4374 if (sd->grp_sid) {
4375 convert_sid_to_string(ipc_cli, pol,
4376 sidstr, numeric,
4377 sd->grp_sid);
4378 } else {
4379 fstrcpy(sidstr, "");
4382 if (all || all_nt) {
4383 if (determine_size) {
4384 p = talloc_asprintf(ctx, ",GROUP:%s",
4385 sidstr);
4386 if (!p) {
4387 errno = ENOMEM;
4388 return -1;
4390 n = strlen(p);
4391 } else {
4392 n = snprintf(buf, bufsize,
4393 ",GROUP:%s", sidstr);
4395 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4396 if (determine_size) {
4397 p = talloc_asprintf(ctx, "%s", sidstr);
4398 if (!p) {
4399 errno = ENOMEM;
4400 return -1;
4402 n = strlen(p);
4403 } else {
4404 n = snprintf(buf, bufsize,
4405 "%s", sidstr);
4409 if (!determine_size && n > bufsize) {
4410 errno = ERANGE;
4411 return -1;
4413 buf += n;
4414 n_used += n;
4415 bufsize -= n;
4418 if (! exclude_nt_acl) {
4419 /* Add aces to value buffer */
4420 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4422 SEC_ACE *ace = &sd->dacl->ace[i];
4423 convert_sid_to_string(ipc_cli, pol,
4424 sidstr, numeric,
4425 &ace->trustee);
4427 if (all || all_nt) {
4428 if (determine_size) {
4429 p = talloc_asprintf(
4430 ctx,
4431 ",ACL:"
4432 "%s:%d/%d/0x%08x",
4433 sidstr,
4434 ace->type,
4435 ace->flags,
4436 ace->info.mask);
4437 if (!p) {
4438 errno = ENOMEM;
4439 return -1;
4441 n = strlen(p);
4442 } else {
4443 n = snprintf(
4444 buf, bufsize,
4445 ",ACL:%s:%d/%d/0x%08x",
4446 sidstr,
4447 ace->type,
4448 ace->flags,
4449 ace->info.mask);
4451 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4452 StrCaseCmp(name+3, sidstr) == 0) ||
4453 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4454 StrCaseCmp(name+4, sidstr) == 0)) {
4455 if (determine_size) {
4456 p = talloc_asprintf(
4457 ctx,
4458 "%d/%d/0x%08x",
4459 ace->type,
4460 ace->flags,
4461 ace->info.mask);
4462 if (!p) {
4463 errno = ENOMEM;
4464 return -1;
4466 n = strlen(p);
4467 } else {
4468 n = snprintf(buf, bufsize,
4469 "%d/%d/0x%08x",
4470 ace->type,
4471 ace->flags,
4472 ace->info.mask);
4474 } else if (all_nt_acls) {
4475 if (determine_size) {
4476 p = talloc_asprintf(
4477 ctx,
4478 "%s%s:%d/%d/0x%08x",
4479 i ? "," : "",
4480 sidstr,
4481 ace->type,
4482 ace->flags,
4483 ace->info.mask);
4484 if (!p) {
4485 errno = ENOMEM;
4486 return -1;
4488 n = strlen(p);
4489 } else {
4490 n = snprintf(buf, bufsize,
4491 "%s%s:%d/%d/0x%08x",
4492 i ? "," : "",
4493 sidstr,
4494 ace->type,
4495 ace->flags,
4496 ace->info.mask);
4499 if (n > bufsize) {
4500 errno = ERANGE;
4501 return -1;
4503 buf += n;
4504 n_used += n;
4505 bufsize -= n;
4509 /* Restore name pointer to its original value */
4510 name -= 19;
4513 if (all || some_dos) {
4514 /* Point to the portion after "system.dos_attr." */
4515 name += 16; /* if (all) this will be invalid but unused */
4517 /* Obtain the DOS attributes */
4518 if (!smbc_getatr(context, srv, filename, &mode, &size,
4519 &c_time, &a_time, &m_time, &ino)) {
4521 errno = smbc_errno(context, &srv->cli);
4522 return -1;
4526 if (! exclude_dos_mode) {
4527 if (all || all_dos) {
4528 if (determine_size) {
4529 p = talloc_asprintf(ctx,
4530 "%sMODE:0x%x",
4531 (ipc_cli &&
4532 (all || some_nt)
4533 ? ","
4534 : ""),
4535 mode);
4536 if (!p) {
4537 errno = ENOMEM;
4538 return -1;
4540 n = strlen(p);
4541 } else {
4542 n = snprintf(buf, bufsize,
4543 "%sMODE:0x%x",
4544 (ipc_cli &&
4545 (all || some_nt)
4546 ? ","
4547 : ""),
4548 mode);
4550 } else if (StrCaseCmp(name, "mode") == 0) {
4551 if (determine_size) {
4552 p = talloc_asprintf(ctx, "0x%x", mode);
4553 if (!p) {
4554 errno = ENOMEM;
4555 return -1;
4557 n = strlen(p);
4558 } else {
4559 n = snprintf(buf, bufsize,
4560 "0x%x", mode);
4564 if (!determine_size && n > bufsize) {
4565 errno = ERANGE;
4566 return -1;
4568 buf += n;
4569 n_used += n;
4570 bufsize -= n;
4573 if (! exclude_dos_size) {
4574 if (all || all_dos) {
4575 if (determine_size) {
4576 p = talloc_asprintf(
4577 ctx,
4578 ",SIZE:%.0f",
4579 (double)size);
4580 if (!p) {
4581 errno = ENOMEM;
4582 return -1;
4584 n = strlen(p);
4585 } else {
4586 n = snprintf(buf, bufsize,
4587 ",SIZE:%.0f",
4588 (double)size);
4590 } else if (StrCaseCmp(name, "size") == 0) {
4591 if (determine_size) {
4592 p = talloc_asprintf(
4593 ctx,
4594 "%.0f",
4595 (double)size);
4596 if (!p) {
4597 errno = ENOMEM;
4598 return -1;
4600 n = strlen(p);
4601 } else {
4602 n = snprintf(buf, bufsize,
4603 "%.0f",
4604 (double)size);
4608 if (!determine_size && n > bufsize) {
4609 errno = ERANGE;
4610 return -1;
4612 buf += n;
4613 n_used += n;
4614 bufsize -= n;
4617 if (! exclude_dos_ctime) {
4618 if (all || all_dos) {
4619 if (determine_size) {
4620 p = talloc_asprintf(ctx,
4621 ",C_TIME:%lu",
4622 c_time);
4623 if (!p) {
4624 errno = ENOMEM;
4625 return -1;
4627 n = strlen(p);
4628 } else {
4629 n = snprintf(buf, bufsize,
4630 ",C_TIME:%lu", c_time);
4632 } else if (StrCaseCmp(name, "c_time") == 0) {
4633 if (determine_size) {
4634 p = talloc_asprintf(ctx, "%lu", c_time);
4635 if (!p) {
4636 errno = ENOMEM;
4637 return -1;
4639 n = strlen(p);
4640 } else {
4641 n = snprintf(buf, bufsize,
4642 "%lu", c_time);
4646 if (!determine_size && n > bufsize) {
4647 errno = ERANGE;
4648 return -1;
4650 buf += n;
4651 n_used += n;
4652 bufsize -= n;
4655 if (! exclude_dos_atime) {
4656 if (all || all_dos) {
4657 if (determine_size) {
4658 p = talloc_asprintf(ctx,
4659 ",A_TIME:%lu",
4660 a_time);
4661 if (!p) {
4662 errno = ENOMEM;
4663 return -1;
4665 n = strlen(p);
4666 } else {
4667 n = snprintf(buf, bufsize,
4668 ",A_TIME:%lu", a_time);
4670 } else if (StrCaseCmp(name, "a_time") == 0) {
4671 if (determine_size) {
4672 p = talloc_asprintf(ctx, "%lu", a_time);
4673 if (!p) {
4674 errno = ENOMEM;
4675 return -1;
4677 n = strlen(p);
4678 } else {
4679 n = snprintf(buf, bufsize,
4680 "%lu", a_time);
4684 if (!determine_size && n > bufsize) {
4685 errno = ERANGE;
4686 return -1;
4688 buf += n;
4689 n_used += n;
4690 bufsize -= n;
4693 if (! exclude_dos_mtime) {
4694 if (all || all_dos) {
4695 if (determine_size) {
4696 p = talloc_asprintf(ctx,
4697 ",M_TIME:%lu",
4698 m_time);
4699 if (!p) {
4700 errno = ENOMEM;
4701 return -1;
4703 n = strlen(p);
4704 } else {
4705 n = snprintf(buf, bufsize,
4706 ",M_TIME:%lu", m_time);
4708 } else if (StrCaseCmp(name, "m_time") == 0) {
4709 if (determine_size) {
4710 p = talloc_asprintf(ctx, "%lu", m_time);
4711 if (!p) {
4712 errno = ENOMEM;
4713 return -1;
4715 n = strlen(p);
4716 } else {
4717 n = snprintf(buf, bufsize,
4718 "%lu", m_time);
4722 if (!determine_size && n > bufsize) {
4723 errno = ERANGE;
4724 return -1;
4726 buf += n;
4727 n_used += n;
4728 bufsize -= n;
4731 if (! exclude_dos_inode) {
4732 if (all || all_dos) {
4733 if (determine_size) {
4734 p = talloc_asprintf(
4735 ctx,
4736 ",INODE:%.0f",
4737 (double)ino);
4738 if (!p) {
4739 errno = ENOMEM;
4740 return -1;
4742 n = strlen(p);
4743 } else {
4744 n = snprintf(buf, bufsize,
4745 ",INODE:%.0f",
4746 (double) ino);
4748 } else if (StrCaseCmp(name, "inode") == 0) {
4749 if (determine_size) {
4750 p = talloc_asprintf(
4751 ctx,
4752 "%.0f",
4753 (double) ino);
4754 if (!p) {
4755 errno = ENOMEM;
4756 return -1;
4758 n = strlen(p);
4759 } else {
4760 n = snprintf(buf, bufsize,
4761 "%.0f",
4762 (double) ino);
4766 if (!determine_size && n > bufsize) {
4767 errno = ERANGE;
4768 return -1;
4770 buf += n;
4771 n_used += n;
4772 bufsize -= n;
4775 /* Restore name pointer to its original value */
4776 name -= 16;
4779 if (n_used == 0) {
4780 errno = ENOATTR;
4781 return -1;
4784 return n_used;
4788 /*****************************************************
4789 set the ACLs on a file given an ascii description
4790 *******************************************************/
4791 static int
4792 cacl_set(TALLOC_CTX *ctx,
4793 struct cli_state *cli,
4794 struct cli_state *ipc_cli,
4795 POLICY_HND *pol,
4796 const char *filename,
4797 const char *the_acl,
4798 int mode,
4799 int flags)
4801 int fnum;
4802 int err = 0;
4803 SEC_DESC *sd = NULL, *old;
4804 SEC_ACL *dacl = NULL;
4805 DOM_SID *owner_sid = NULL;
4806 DOM_SID *grp_sid = NULL;
4807 uint32 i, j;
4808 size_t sd_size;
4809 int ret = 0;
4810 char *p;
4811 BOOL numeric = True;
4813 /* the_acl will be null for REMOVE_ALL operations */
4814 if (the_acl) {
4815 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4816 p > the_acl &&
4817 p[-1] != '+');
4819 /* if this is to set the entire ACL... */
4820 if (*the_acl == '*') {
4821 /* ... then increment past the first colon */
4822 the_acl = p + 1;
4825 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4826 CONST_DISCARD(char *, the_acl));
4828 if (!sd) {
4829 errno = EINVAL;
4830 return -1;
4834 /* SMBC_XATTR_MODE_REMOVE_ALL is the only caller
4835 that doesn't deref sd */
4837 if (!sd && (mode != SMBC_XATTR_MODE_REMOVE_ALL)) {
4838 errno = EINVAL;
4839 return -1;
4842 /* The desired access below is the only one I could find that works
4843 with NT4, W2KP and Samba */
4845 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4847 if (fnum == -1) {
4848 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4849 filename, cli_errstr(cli)));
4850 errno = 0;
4851 return -1;
4854 old = cli_query_secdesc(cli, fnum, ctx);
4856 if (!old) {
4857 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4858 errno = 0;
4859 return -1;
4862 cli_close(cli, fnum);
4864 switch (mode) {
4865 case SMBC_XATTR_MODE_REMOVE_ALL:
4866 old->dacl->num_aces = 0;
4867 SAFE_FREE(old->dacl->ace);
4868 SAFE_FREE(old->dacl);
4869 old->off_dacl = 0;
4870 dacl = old->dacl;
4871 break;
4873 case SMBC_XATTR_MODE_REMOVE:
4874 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4875 BOOL found = False;
4877 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4878 if (sec_ace_equal(&sd->dacl->ace[i],
4879 &old->dacl->ace[j])) {
4880 uint32 k;
4881 for (k=j; k<old->dacl->num_aces-1;k++) {
4882 old->dacl->ace[k] =
4883 old->dacl->ace[k+1];
4885 old->dacl->num_aces--;
4886 if (old->dacl->num_aces == 0) {
4887 SAFE_FREE(old->dacl->ace);
4888 SAFE_FREE(old->dacl);
4889 old->off_dacl = 0;
4891 found = True;
4892 dacl = old->dacl;
4893 break;
4897 if (!found) {
4898 err = ENOATTR;
4899 ret = -1;
4900 goto failed;
4903 break;
4905 case SMBC_XATTR_MODE_ADD:
4906 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4907 BOOL found = False;
4909 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4910 if (sid_equal(&sd->dacl->ace[i].trustee,
4911 &old->dacl->ace[j].trustee)) {
4912 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4913 err = EEXIST;
4914 ret = -1;
4915 goto failed;
4917 old->dacl->ace[j] = sd->dacl->ace[i];
4918 ret = -1;
4919 found = True;
4923 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4924 err = ENOATTR;
4925 ret = -1;
4926 goto failed;
4929 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4930 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4933 dacl = old->dacl;
4934 break;
4936 case SMBC_XATTR_MODE_SET:
4937 old = sd;
4938 owner_sid = old->owner_sid;
4939 grp_sid = old->grp_sid;
4940 dacl = old->dacl;
4941 break;
4943 case SMBC_XATTR_MODE_CHOWN:
4944 owner_sid = sd->owner_sid;
4945 break;
4947 case SMBC_XATTR_MODE_CHGRP:
4948 grp_sid = sd->grp_sid;
4949 break;
4952 /* Denied ACE entries must come before allowed ones */
4953 sort_acl(old->dacl);
4955 /* Create new security descriptor and set it */
4956 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4957 owner_sid, grp_sid, NULL, dacl, &sd_size);
4959 fnum = cli_nt_create(cli, filename,
4960 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4962 if (fnum == -1) {
4963 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4964 filename, cli_errstr(cli)));
4965 errno = 0;
4966 return -1;
4969 if (!cli_set_secdesc(cli, fnum, sd)) {
4970 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4971 ret = -1;
4974 /* Clean up */
4976 failed:
4977 cli_close(cli, fnum);
4979 if (err != 0) {
4980 errno = err;
4983 return ret;
4987 static int
4988 smbc_setxattr_ctx(SMBCCTX *context,
4989 const char *fname,
4990 const char *name,
4991 const void *value,
4992 size_t size,
4993 int flags)
4995 int ret;
4996 int ret2;
4997 SMBCSRV *srv;
4998 SMBCSRV *ipc_srv;
4999 fstring server;
5000 fstring share;
5001 fstring user;
5002 fstring password;
5003 fstring workgroup;
5004 pstring path;
5005 TALLOC_CTX *ctx;
5006 POLICY_HND pol;
5007 DOS_ATTR_DESC *dad;
5009 if (!context || !context->internal ||
5010 !context->internal->_initialized) {
5012 errno = EINVAL; /* Best I can think of ... */
5013 return -1;
5017 if (!fname) {
5019 errno = EINVAL;
5020 return -1;
5024 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
5025 fname, name, (int) size, (const char*)value));
5027 if (smbc_parse_path(context, fname,
5028 workgroup, sizeof(workgroup),
5029 server, sizeof(server),
5030 share, sizeof(share),
5031 path, sizeof(path),
5032 user, sizeof(user),
5033 password, sizeof(password),
5034 NULL, 0)) {
5035 errno = EINVAL;
5036 return -1;
5039 if (user[0] == (char)0) fstrcpy(user, context->user);
5041 srv = smbc_server(context, True,
5042 server, share, workgroup, user, password);
5043 if (!srv) {
5044 return -1; /* errno set by smbc_server */
5047 if (! srv->no_nt_session) {
5048 ipc_srv = smbc_attr_server(context, server, share,
5049 workgroup, user, password,
5050 &pol);
5051 srv->no_nt_session = True;
5052 } else {
5053 ipc_srv = NULL;
5056 ctx = talloc_init("smbc_setxattr");
5057 if (!ctx) {
5058 errno = ENOMEM;
5059 return -1;
5063 * Are they asking to set the entire set of known attributes?
5065 if (StrCaseCmp(name, "system.*") == 0 ||
5066 StrCaseCmp(name, "system.*+") == 0) {
5067 /* Yup. */
5068 char *namevalue =
5069 talloc_asprintf(ctx, "%s:%s",
5070 name+7, (const char *) value);
5071 if (! namevalue) {
5072 errno = ENOMEM;
5073 ret = -1;
5074 return -1;
5077 if (ipc_srv) {
5078 ret = cacl_set(ctx, &srv->cli,
5079 &ipc_srv->cli, &pol, path,
5080 namevalue,
5081 (*namevalue == '*'
5082 ? SMBC_XATTR_MODE_SET
5083 : SMBC_XATTR_MODE_ADD),
5084 flags);
5085 } else {
5086 ret = 0;
5089 /* get a DOS Attribute Descriptor with current attributes */
5090 dad = dos_attr_query(context, ctx, path, srv);
5091 if (dad) {
5092 /* Overwrite old with new, using what was provided */
5093 dos_attr_parse(context, dad, srv, namevalue);
5095 /* Set the new DOS attributes */
5096 if (! smbc_setatr(context, srv, path,
5097 dad->c_time,
5098 dad->a_time,
5099 dad->m_time,
5100 dad->mode)) {
5102 /* cause failure if NT failed too */
5103 dad = NULL;
5107 /* we only fail if both NT and DOS sets failed */
5108 if (ret < 0 && ! dad) {
5109 ret = -1; /* in case dad was null */
5111 else {
5112 ret = 0;
5115 talloc_destroy(ctx);
5116 return ret;
5120 * Are they asking to set an access control element or to set
5121 * the entire access control list?
5123 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5124 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5125 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5126 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5127 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5129 /* Yup. */
5130 char *namevalue =
5131 talloc_asprintf(ctx, "%s:%s",
5132 name+19, (const char *) value);
5134 if (! ipc_srv) {
5135 ret = -1; /* errno set by smbc_server() */
5137 else if (! namevalue) {
5138 errno = ENOMEM;
5139 ret = -1;
5140 } else {
5141 ret = cacl_set(ctx, &srv->cli,
5142 &ipc_srv->cli, &pol, path,
5143 namevalue,
5144 (*namevalue == '*'
5145 ? SMBC_XATTR_MODE_SET
5146 : SMBC_XATTR_MODE_ADD),
5147 flags);
5149 talloc_destroy(ctx);
5150 return ret;
5154 * Are they asking to set the owner?
5156 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5157 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5159 /* Yup. */
5160 char *namevalue =
5161 talloc_asprintf(ctx, "%s:%s",
5162 name+19, (const char *) value);
5164 if (! ipc_srv) {
5166 ret = -1; /* errno set by smbc_server() */
5168 else if (! namevalue) {
5169 errno = ENOMEM;
5170 ret = -1;
5171 } else {
5172 ret = cacl_set(ctx, &srv->cli,
5173 &ipc_srv->cli, &pol, path,
5174 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5176 talloc_destroy(ctx);
5177 return ret;
5181 * Are they asking to set the group?
5183 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5184 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5186 /* Yup. */
5187 char *namevalue =
5188 talloc_asprintf(ctx, "%s:%s",
5189 name+19, (const char *) value);
5191 if (! ipc_srv) {
5192 /* errno set by smbc_server() */
5193 ret = -1;
5195 else if (! namevalue) {
5196 errno = ENOMEM;
5197 ret = -1;
5198 } else {
5199 ret = cacl_set(ctx, &srv->cli,
5200 &ipc_srv->cli, &pol, path,
5201 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5203 talloc_destroy(ctx);
5204 return ret;
5208 * Are they asking to set a DOS attribute?
5210 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5211 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5212 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5213 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5214 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
5216 /* get a DOS Attribute Descriptor with current attributes */
5217 dad = dos_attr_query(context, ctx, path, srv);
5218 if (dad) {
5219 char *namevalue =
5220 talloc_asprintf(ctx, "%s:%s",
5221 name+16, (const char *) value);
5222 if (! namevalue) {
5223 errno = ENOMEM;
5224 ret = -1;
5225 } else {
5226 /* Overwrite old with provided new params */
5227 dos_attr_parse(context, dad, srv, namevalue);
5229 /* Set the new DOS attributes */
5230 ret2 = smbc_setatr(context, srv, path,
5231 dad->c_time,
5232 dad->a_time,
5233 dad->m_time,
5234 dad->mode);
5236 /* ret2 has True (success) / False (failure) */
5237 if (ret2) {
5238 ret = 0;
5239 } else {
5240 ret = -1;
5243 } else {
5244 ret = -1;
5247 talloc_destroy(ctx);
5248 return ret;
5251 /* Unsupported attribute name */
5252 talloc_destroy(ctx);
5253 errno = EINVAL;
5254 return -1;
5257 static int
5258 smbc_getxattr_ctx(SMBCCTX *context,
5259 const char *fname,
5260 const char *name,
5261 const void *value,
5262 size_t size)
5264 int ret;
5265 SMBCSRV *srv;
5266 SMBCSRV *ipc_srv;
5267 fstring server;
5268 fstring share;
5269 fstring user;
5270 fstring password;
5271 fstring workgroup;
5272 pstring path;
5273 TALLOC_CTX *ctx;
5274 POLICY_HND pol;
5277 if (!context || !context->internal ||
5278 !context->internal->_initialized) {
5280 errno = EINVAL; /* Best I can think of ... */
5281 return -1;
5285 if (!fname) {
5287 errno = EINVAL;
5288 return -1;
5292 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5294 if (smbc_parse_path(context, fname,
5295 workgroup, sizeof(workgroup),
5296 server, sizeof(server),
5297 share, sizeof(share),
5298 path, sizeof(path),
5299 user, sizeof(user),
5300 password, sizeof(password),
5301 NULL, 0)) {
5302 errno = EINVAL;
5303 return -1;
5306 if (user[0] == (char)0) fstrcpy(user, context->user);
5308 srv = smbc_server(context, True,
5309 server, share, workgroup, user, password);
5310 if (!srv) {
5311 return -1; /* errno set by smbc_server */
5314 if (! srv->no_nt_session) {
5315 ipc_srv = smbc_attr_server(context, server, share,
5316 workgroup, user, password,
5317 &pol);
5318 if (! ipc_srv) {
5319 srv->no_nt_session = True;
5321 } else {
5322 ipc_srv = NULL;
5325 ctx = talloc_init("smbc:getxattr");
5326 if (!ctx) {
5327 errno = ENOMEM;
5328 return -1;
5331 /* Are they requesting a supported attribute? */
5332 if (StrCaseCmp(name, "system.*") == 0 ||
5333 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5334 StrCaseCmp(name, "system.*+") == 0 ||
5335 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5336 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5337 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5338 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5339 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5340 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5341 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5342 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5343 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5344 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5345 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5346 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5347 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5348 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5349 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5350 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5351 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5352 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5353 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
5354 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5356 /* Yup. */
5357 ret = cacl_get(context, ctx, srv,
5358 ipc_srv == NULL ? NULL : &ipc_srv->cli,
5359 &pol, path,
5360 CONST_DISCARD(char *, name),
5361 CONST_DISCARD(char *, value), size);
5362 if (ret < 0 && errno == 0) {
5363 errno = smbc_errno(context, &srv->cli);
5365 talloc_destroy(ctx);
5366 return ret;
5369 /* Unsupported attribute name */
5370 talloc_destroy(ctx);
5371 errno = EINVAL;
5372 return -1;
5376 static int
5377 smbc_removexattr_ctx(SMBCCTX *context,
5378 const char *fname,
5379 const char *name)
5381 int ret;
5382 SMBCSRV *srv;
5383 SMBCSRV *ipc_srv;
5384 fstring server;
5385 fstring share;
5386 fstring user;
5387 fstring password;
5388 fstring workgroup;
5389 pstring path;
5390 TALLOC_CTX *ctx;
5391 POLICY_HND pol;
5393 if (!context || !context->internal ||
5394 !context->internal->_initialized) {
5396 errno = EINVAL; /* Best I can think of ... */
5397 return -1;
5401 if (!fname) {
5403 errno = EINVAL;
5404 return -1;
5408 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5410 if (smbc_parse_path(context, fname,
5411 workgroup, sizeof(workgroup),
5412 server, sizeof(server),
5413 share, sizeof(share),
5414 path, sizeof(path),
5415 user, sizeof(user),
5416 password, sizeof(password),
5417 NULL, 0)) {
5418 errno = EINVAL;
5419 return -1;
5422 if (user[0] == (char)0) fstrcpy(user, context->user);
5424 srv = smbc_server(context, True,
5425 server, share, workgroup, user, password);
5426 if (!srv) {
5427 return -1; /* errno set by smbc_server */
5430 if (! srv->no_nt_session) {
5431 ipc_srv = smbc_attr_server(context, server, share,
5432 workgroup, user, password,
5433 &pol);
5434 srv->no_nt_session = True;
5435 } else {
5436 ipc_srv = NULL;
5439 if (! ipc_srv) {
5440 return -1; /* errno set by smbc_attr_server */
5443 ctx = talloc_init("smbc_removexattr");
5444 if (!ctx) {
5445 errno = ENOMEM;
5446 return -1;
5449 /* Are they asking to set the entire ACL? */
5450 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5451 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5453 /* Yup. */
5454 ret = cacl_set(ctx, &srv->cli,
5455 &ipc_srv->cli, &pol, path,
5456 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5457 talloc_destroy(ctx);
5458 return ret;
5462 * Are they asking to remove one or more spceific security descriptor
5463 * attributes?
5465 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5466 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5467 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5468 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5469 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5470 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5471 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5473 /* Yup. */
5474 ret = cacl_set(ctx, &srv->cli,
5475 &ipc_srv->cli, &pol, path,
5476 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5477 talloc_destroy(ctx);
5478 return ret;
5481 /* Unsupported attribute name */
5482 talloc_destroy(ctx);
5483 errno = EINVAL;
5484 return -1;
5487 static int
5488 smbc_listxattr_ctx(SMBCCTX *context,
5489 const char *fname,
5490 char *list,
5491 size_t size)
5494 * This isn't quite what listxattr() is supposed to do. This returns
5495 * the complete set of attribute names, always, rather than only those
5496 * attribute names which actually exist for a file. Hmmm...
5498 const char supported[] =
5499 "system.*\0"
5500 "system.*+\0"
5501 "system.nt_sec_desc.revision\0"
5502 "system.nt_sec_desc.owner\0"
5503 "system.nt_sec_desc.owner+\0"
5504 "system.nt_sec_desc.group\0"
5505 "system.nt_sec_desc.group+\0"
5506 "system.nt_sec_desc.acl.*\0"
5507 "system.nt_sec_desc.acl\0"
5508 "system.nt_sec_desc.acl+\0"
5509 "system.nt_sec_desc.*\0"
5510 "system.nt_sec_desc.*+\0"
5511 "system.dos_attr.*\0"
5512 "system.dos_attr.mode\0"
5513 "system.dos_attr.c_time\0"
5514 "system.dos_attr.a_time\0"
5515 "system.dos_attr.m_time\0"
5518 if (size == 0) {
5519 return sizeof(supported);
5522 if (sizeof(supported) > size) {
5523 errno = ERANGE;
5524 return -1;
5527 /* this can't be strcpy() because there are embedded null characters */
5528 memcpy(list, supported, sizeof(supported));
5529 return sizeof(supported);
5534 * Open a print file to be written to by other calls
5537 static SMBCFILE *
5538 smbc_open_print_job_ctx(SMBCCTX *context,
5539 const char *fname)
5541 fstring server;
5542 fstring share;
5543 fstring user;
5544 fstring password;
5545 pstring path;
5547 if (!context || !context->internal ||
5548 !context->internal->_initialized) {
5550 errno = EINVAL;
5551 return NULL;
5555 if (!fname) {
5557 errno = EINVAL;
5558 return NULL;
5562 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5564 if (smbc_parse_path(context, fname,
5565 NULL, 0,
5566 server, sizeof(server),
5567 share, sizeof(share),
5568 path, sizeof(path),
5569 user, sizeof(user),
5570 password, sizeof(password),
5571 NULL, 0)) {
5572 errno = EINVAL;
5573 return NULL;
5576 /* What if the path is empty, or the file exists? */
5578 return context->open(context, fname, O_WRONLY, 666);
5583 * Routine to print a file on a remote server ...
5585 * We open the file, which we assume to be on a remote server, and then
5586 * copy it to a print file on the share specified by printq.
5589 static int
5590 smbc_print_file_ctx(SMBCCTX *c_file,
5591 const char *fname,
5592 SMBCCTX *c_print,
5593 const char *printq)
5595 SMBCFILE *fid1;
5596 SMBCFILE *fid2;
5597 int bytes;
5598 int saverr;
5599 int tot_bytes = 0;
5600 char buf[4096];
5602 if (!c_file || !c_file->internal->_initialized || !c_print ||
5603 !c_print->internal->_initialized) {
5605 errno = EINVAL;
5606 return -1;
5610 if (!fname && !printq) {
5612 errno = EINVAL;
5613 return -1;
5617 /* Try to open the file for reading ... */
5619 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5621 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5622 return -1; /* smbc_open sets errno */
5626 /* Now, try to open the printer file for writing */
5628 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5630 saverr = errno; /* Save errno */
5631 c_file->close_fn(c_file, fid1);
5632 errno = saverr;
5633 return -1;
5637 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5639 tot_bytes += bytes;
5641 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5643 saverr = errno;
5644 c_file->close_fn(c_file, fid1);
5645 c_print->close_fn(c_print, fid2);
5646 errno = saverr;
5652 saverr = errno;
5654 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5655 c_print->close_fn(c_print, fid2);
5657 if (bytes < 0) {
5659 errno = saverr;
5660 return -1;
5664 return tot_bytes;
5669 * Routine to list print jobs on a printer share ...
5672 static int
5673 smbc_list_print_jobs_ctx(SMBCCTX *context,
5674 const char *fname,
5675 smbc_list_print_job_fn fn)
5677 SMBCSRV *srv;
5678 fstring server;
5679 fstring share;
5680 fstring user;
5681 fstring password;
5682 fstring workgroup;
5683 pstring path;
5685 if (!context || !context->internal ||
5686 !context->internal->_initialized) {
5688 errno = EINVAL;
5689 return -1;
5693 if (!fname) {
5695 errno = EINVAL;
5696 return -1;
5700 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5702 if (smbc_parse_path(context, fname,
5703 workgroup, sizeof(workgroup),
5704 server, sizeof(server),
5705 share, sizeof(share),
5706 path, sizeof(path),
5707 user, sizeof(user),
5708 password, sizeof(password),
5709 NULL, 0)) {
5710 errno = EINVAL;
5711 return -1;
5714 if (user[0] == (char)0) fstrcpy(user, context->user);
5716 srv = smbc_server(context, True,
5717 server, share, workgroup, user, password);
5719 if (!srv) {
5721 return -1; /* errno set by smbc_server */
5725 if (cli_print_queue(&srv->cli,
5726 (void (*)(struct print_job_info *))fn) < 0) {
5728 errno = smbc_errno(context, &srv->cli);
5729 return -1;
5733 return 0;
5738 * Delete a print job from a remote printer share
5741 static int
5742 smbc_unlink_print_job_ctx(SMBCCTX *context,
5743 const char *fname,
5744 int id)
5746 SMBCSRV *srv;
5747 fstring server;
5748 fstring share;
5749 fstring user;
5750 fstring password;
5751 fstring workgroup;
5752 pstring path;
5753 int err;
5755 if (!context || !context->internal ||
5756 !context->internal->_initialized) {
5758 errno = EINVAL;
5759 return -1;
5763 if (!fname) {
5765 errno = EINVAL;
5766 return -1;
5770 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5772 if (smbc_parse_path(context, fname,
5773 workgroup, sizeof(workgroup),
5774 server, sizeof(server),
5775 share, sizeof(share),
5776 path, sizeof(path),
5777 user, sizeof(user),
5778 password, sizeof(password),
5779 NULL, 0)) {
5780 errno = EINVAL;
5781 return -1;
5784 if (user[0] == (char)0) fstrcpy(user, context->user);
5786 srv = smbc_server(context, True,
5787 server, share, workgroup, user, password);
5789 if (!srv) {
5791 return -1; /* errno set by smbc_server */
5795 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5797 if (err < 0)
5798 errno = smbc_errno(context, &srv->cli);
5799 else if (err == ERRnosuchprintjob)
5800 errno = EINVAL;
5801 return -1;
5805 return 0;
5810 * Get a new empty handle to fill in with your own info
5812 SMBCCTX *
5813 smbc_new_context(void)
5815 SMBCCTX *context;
5817 context = SMB_MALLOC_P(SMBCCTX);
5818 if (!context) {
5819 errno = ENOMEM;
5820 return NULL;
5823 ZERO_STRUCTP(context);
5825 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5826 if (!context->internal) {
5827 SAFE_FREE(context);
5828 errno = ENOMEM;
5829 return NULL;
5832 ZERO_STRUCTP(context->internal);
5835 /* ADD REASONABLE DEFAULTS */
5836 context->debug = 0;
5837 context->timeout = 20000; /* 20 seconds */
5839 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5840 context->options.urlencode_readdir_entries = False;/* backward compat */
5841 context->options.one_share_per_server = False;/* backward compat */
5843 context->open = smbc_open_ctx;
5844 context->creat = smbc_creat_ctx;
5845 context->read = smbc_read_ctx;
5846 context->write = smbc_write_ctx;
5847 context->close_fn = smbc_close_ctx;
5848 context->unlink = smbc_unlink_ctx;
5849 context->rename = smbc_rename_ctx;
5850 context->lseek = smbc_lseek_ctx;
5851 context->stat = smbc_stat_ctx;
5852 context->fstat = smbc_fstat_ctx;
5853 context->opendir = smbc_opendir_ctx;
5854 context->closedir = smbc_closedir_ctx;
5855 context->readdir = smbc_readdir_ctx;
5856 context->getdents = smbc_getdents_ctx;
5857 context->mkdir = smbc_mkdir_ctx;
5858 context->rmdir = smbc_rmdir_ctx;
5859 context->telldir = smbc_telldir_ctx;
5860 context->lseekdir = smbc_lseekdir_ctx;
5861 context->fstatdir = smbc_fstatdir_ctx;
5862 context->chmod = smbc_chmod_ctx;
5863 context->utimes = smbc_utimes_ctx;
5864 context->setxattr = smbc_setxattr_ctx;
5865 context->getxattr = smbc_getxattr_ctx;
5866 context->removexattr = smbc_removexattr_ctx;
5867 context->listxattr = smbc_listxattr_ctx;
5868 context->open_print_job = smbc_open_print_job_ctx;
5869 context->print_file = smbc_print_file_ctx;
5870 context->list_print_jobs = smbc_list_print_jobs_ctx;
5871 context->unlink_print_job = smbc_unlink_print_job_ctx;
5873 context->callbacks.check_server_fn = smbc_check_server;
5874 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5876 smbc_default_cache_functions(context);
5878 return context;
5882 * Free a context
5884 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5885 * and thus you'll be leaking memory if not handled properly.
5889 smbc_free_context(SMBCCTX *context,
5890 int shutdown_ctx)
5892 if (!context) {
5893 errno = EBADF;
5894 return 1;
5897 if (shutdown_ctx) {
5898 SMBCFILE * f;
5899 DEBUG(1,("Performing aggressive shutdown.\n"));
5901 f = context->internal->_files;
5902 while (f) {
5903 context->close_fn(context, f);
5904 f = f->next;
5906 context->internal->_files = NULL;
5908 /* First try to remove the servers the nice way. */
5909 if (context->callbacks.purge_cached_fn(context)) {
5910 SMBCSRV * s;
5911 SMBCSRV * next;
5912 DEBUG(1, ("Could not purge all servers, "
5913 "Nice way shutdown failed.\n"));
5914 s = context->internal->_servers;
5915 while (s) {
5916 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
5917 s, s->cli.fd));
5918 cli_shutdown(&s->cli);
5919 context->callbacks.remove_cached_srv_fn(context,
5921 next = s->next;
5922 DLIST_REMOVE(context->internal->_servers, s);
5923 SAFE_FREE(s);
5924 s = next;
5926 context->internal->_servers = NULL;
5929 else {
5930 /* This is the polite way */
5931 if (context->callbacks.purge_cached_fn(context)) {
5932 DEBUG(1, ("Could not purge all servers, "
5933 "free_context failed.\n"));
5934 errno = EBUSY;
5935 return 1;
5937 if (context->internal->_servers) {
5938 DEBUG(1, ("Active servers in context, "
5939 "free_context failed.\n"));
5940 errno = EBUSY;
5941 return 1;
5943 if (context->internal->_files) {
5944 DEBUG(1, ("Active files in context, "
5945 "free_context failed.\n"));
5946 errno = EBUSY;
5947 return 1;
5951 /* Things we have to clean up */
5952 SAFE_FREE(context->workgroup);
5953 SAFE_FREE(context->netbios_name);
5954 SAFE_FREE(context->user);
5956 DEBUG(3, ("Context %p succesfully freed\n", context));
5957 SAFE_FREE(context->internal);
5958 SAFE_FREE(context);
5959 return 0;
5964 * Each time the context structure is changed, we have binary backward
5965 * compatibility issues. Instead of modifying the public portions of the
5966 * context structure to add new options, instead, we put them in the internal
5967 * portion of the context structure and provide a set function for these new
5968 * options.
5970 void
5971 smbc_option_set(SMBCCTX *context,
5972 char *option_name,
5973 void *option_value)
5975 if (strcmp(option_name, "debug_stderr") == 0) {
5977 * Log to standard error instead of standard output.
5979 context->internal->_debug_stderr = True;
5985 * Initialise the library etc
5987 * We accept a struct containing handle information.
5988 * valid values for info->debug from 0 to 100,
5989 * and insist that info->fn must be non-null.
5991 SMBCCTX *
5992 smbc_init_context(SMBCCTX *context)
5994 pstring conf;
5995 int pid;
5996 char *user = NULL;
5997 char *home = NULL;
5999 if (!context || !context->internal) {
6000 errno = EBADF;
6001 return NULL;
6004 /* Do not initialise the same client twice */
6005 if (context->internal->_initialized) {
6006 return 0;
6009 if (!context->callbacks.auth_fn ||
6010 context->debug < 0 ||
6011 context->debug > 100) {
6013 errno = EINVAL;
6014 return NULL;
6018 if (!smbc_initialized) {
6020 * Do some library-wide intializations the first time we get
6021 * called
6023 BOOL conf_loaded = False;
6025 /* Set this to what the user wants */
6026 DEBUGLEVEL = context->debug;
6028 load_case_tables();
6030 setup_logging("libsmbclient", True);
6031 if (context->internal->_debug_stderr) {
6032 dbf = x_stderr;
6033 x_setbuf(x_stderr, NULL);
6036 /* Here we would open the smb.conf file if needed ... */
6038 in_client = True; /* FIXME, make a param */
6040 home = getenv("HOME");
6041 if (home) {
6042 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
6043 if (lp_load(conf, True, False, False, True)) {
6044 conf_loaded = True;
6045 } else {
6046 DEBUG(5, ("Could not load config file: %s\n",
6047 conf));
6051 if (!conf_loaded) {
6053 * Well, if that failed, try the dyn_CONFIGFILE
6054 * Which points to the standard locn, and if that
6055 * fails, silently ignore it and use the internal
6056 * defaults ...
6059 if (!lp_load(dyn_CONFIGFILE, True, False, False, False)) {
6060 DEBUG(5, ("Could not load config file: %s\n",
6061 dyn_CONFIGFILE));
6062 } else if (home) {
6064 * We loaded the global config file. Now lets
6065 * load user-specific modifications to the
6066 * global config.
6068 slprintf(conf, sizeof(conf),
6069 "%s/.smb/smb.conf.append", home);
6070 if (!lp_load(conf, True, False, False, False)) {
6071 DEBUG(10,
6072 ("Could not append config file: "
6073 "%s\n",
6074 conf));
6079 load_interfaces(); /* Load the list of interfaces ... */
6081 reopen_logs(); /* Get logging working ... */
6084 * Block SIGPIPE (from lib/util_sock.c: write())
6085 * It is not needed and should not stop execution
6087 BlockSignals(True, SIGPIPE);
6089 /* Done with one-time initialisation */
6090 smbc_initialized = 1;
6094 if (!context->user) {
6096 * FIXME: Is this the best way to get the user info?
6098 user = getenv("USER");
6099 /* walk around as "guest" if no username can be found */
6100 if (!user) context->user = SMB_STRDUP("guest");
6101 else context->user = SMB_STRDUP(user);
6104 if (!context->netbios_name) {
6106 * We try to get our netbios name from the config. If that
6107 * fails we fall back on constructing our netbios name from
6108 * our hostname etc
6110 if (global_myname()) {
6111 context->netbios_name = SMB_STRDUP(global_myname());
6113 else {
6115 * Hmmm, I want to get hostname as well, but I am too
6116 * lazy for the moment
6118 pid = sys_getpid();
6119 context->netbios_name = SMB_MALLOC(17);
6120 if (!context->netbios_name) {
6121 errno = ENOMEM;
6122 return NULL;
6124 slprintf(context->netbios_name, 16,
6125 "smbc%s%d", context->user, pid);
6129 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
6131 if (!context->workgroup) {
6132 if (lp_workgroup()) {
6133 context->workgroup = SMB_STRDUP(lp_workgroup());
6135 else {
6136 /* TODO: Think about a decent default workgroup */
6137 context->workgroup = SMB_STRDUP("samba");
6141 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
6143 /* shortest timeout is 1 second */
6144 if (context->timeout > 0 && context->timeout < 1000)
6145 context->timeout = 1000;
6148 * FIXME: Should we check the function pointers here?
6151 context->internal->_initialized = True;
6153 return context;
6157 /* Return the verion of samba, and thus libsmbclient */
6158 const char *
6159 smbc_version(void)
6161 return samba_version_string();