r14236: Fix Coverity bug # 90
[Samba/nascimento.git] / source3 / libsmb / libsmbclient.c
blob6b4ae9f4b7002cfa56291a53578dc7fb46cff30d
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 = file->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 /* Check that the buffer exists ... */
1224 if (buf == NULL) {
1226 errno = EINVAL;
1227 return -1;
1231 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1232 if (smbc_parse_path(context, file->fname,
1233 NULL, 0,
1234 server, sizeof(server),
1235 share, sizeof(share),
1236 path, sizeof(path),
1237 user, sizeof(user),
1238 password, sizeof(password),
1239 NULL, 0)) {
1240 errno = EINVAL;
1241 return -1;
1244 /*d_printf(">>>read: resolving %s\n", path);*/
1245 if (!cli_resolve_path("", &file->srv->cli, path,
1246 &targetcli, targetpath))
1248 d_printf("Could not resolve %s\n", path);
1249 return -1;
1251 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1253 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1255 if (ret < 0) {
1257 errno = smbc_errno(context, targetcli);
1258 return -1;
1262 file->offset += ret;
1264 DEBUG(4, (" --> %d\n", ret));
1266 return ret; /* Success, ret bytes of data ... */
1271 * Routine to write() a file ...
1274 static ssize_t
1275 smbc_write_ctx(SMBCCTX *context,
1276 SMBCFILE *file,
1277 void *buf,
1278 size_t count)
1280 int ret;
1281 off_t offset;
1282 fstring server, share, user, password;
1283 pstring path, targetpath;
1284 struct cli_state *targetcli;
1286 /* First check all pointers before dereferencing them */
1288 if (!context || !context->internal ||
1289 !context->internal->_initialized) {
1291 errno = EINVAL;
1292 return -1;
1296 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1298 errno = EBADF;
1299 return -1;
1303 /* Check that the buffer exists ... */
1305 if (buf == NULL) {
1307 errno = EINVAL;
1308 return -1;
1312 offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1314 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1315 if (smbc_parse_path(context, file->fname,
1316 NULL, 0,
1317 server, sizeof(server),
1318 share, sizeof(share),
1319 path, sizeof(path),
1320 user, sizeof(user),
1321 password, sizeof(password),
1322 NULL, 0)) {
1323 errno = EINVAL;
1324 return -1;
1327 /*d_printf(">>>write: resolving %s\n", path);*/
1328 if (!cli_resolve_path("", &file->srv->cli, path,
1329 &targetcli, targetpath))
1331 d_printf("Could not resolve %s\n", path);
1332 return -1;
1334 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1337 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1339 if (ret <= 0) {
1341 errno = smbc_errno(context, targetcli);
1342 return -1;
1346 file->offset += ret;
1348 return ret; /* Success, 0 bytes of data ... */
1352 * Routine to close() a file ...
1355 static int
1356 smbc_close_ctx(SMBCCTX *context,
1357 SMBCFILE *file)
1359 SMBCSRV *srv;
1360 fstring server, share, user, password;
1361 pstring path, targetpath;
1362 struct cli_state *targetcli;
1364 if (!context || !context->internal ||
1365 !context->internal->_initialized) {
1367 errno = EINVAL;
1368 return -1;
1372 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1374 errno = EBADF;
1375 return -1;
1379 /* IS a dir ... */
1380 if (!file->file) {
1382 return context->closedir(context, file);
1386 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1387 if (smbc_parse_path(context, file->fname,
1388 NULL, 0,
1389 server, sizeof(server),
1390 share, sizeof(share),
1391 path, sizeof(path),
1392 user, sizeof(user),
1393 password, sizeof(password),
1394 NULL, 0)) {
1395 errno = EINVAL;
1396 return -1;
1399 /*d_printf(">>>close: resolving %s\n", path);*/
1400 if (!cli_resolve_path("", &file->srv->cli, path,
1401 &targetcli, targetpath))
1403 d_printf("Could not resolve %s\n", path);
1404 return -1;
1406 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1408 if (!cli_close(targetcli, file->cli_fd)) {
1410 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1411 file->fname));
1412 /* Deallocate slot and remove the server
1413 * from the server cache if unused */
1414 errno = smbc_errno(context, targetcli);
1415 srv = file->srv;
1416 DLIST_REMOVE(context->internal->_files, file);
1417 SAFE_FREE(file->fname);
1418 SAFE_FREE(file);
1419 context->callbacks.remove_unused_server_fn(context, srv);
1421 return -1;
1425 DLIST_REMOVE(context->internal->_files, file);
1426 SAFE_FREE(file->fname);
1427 SAFE_FREE(file);
1429 return 0;
1433 * Get info from an SMB server on a file. Use a qpathinfo call first
1434 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1436 static BOOL
1437 smbc_getatr(SMBCCTX * context,
1438 SMBCSRV *srv,
1439 char *path,
1440 uint16 *mode,
1441 SMB_OFF_T *size,
1442 time_t *c_time,
1443 time_t *a_time,
1444 time_t *m_time,
1445 SMB_INO_T *ino)
1447 pstring fixedpath;
1448 pstring targetpath;
1449 struct cli_state *targetcli;
1451 if (!context || !context->internal ||
1452 !context->internal->_initialized) {
1454 errno = EINVAL;
1455 return -1;
1459 /* path fixup for . and .. */
1460 if (strequal(path, ".") || strequal(path, ".."))
1461 pstrcpy(fixedpath, "\\");
1462 else
1464 pstrcpy(fixedpath, path);
1465 trim_string(fixedpath, NULL, "\\..");
1466 trim_string(fixedpath, NULL, "\\.");
1468 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1470 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1472 d_printf("Couldn't resolve %s\n", path);
1473 return False;
1476 if ( targetcli->dfsroot )
1478 pstring temppath;
1479 pstrcpy(temppath, targetpath);
1480 cli_dfs_make_full_path(targetpath, targetcli->desthost,
1481 targetcli->share, temppath);
1484 if (!srv->no_pathinfo2 &&
1485 cli_qpathinfo2(targetcli, targetpath,
1486 c_time, a_time, m_time, NULL, size, mode, ino)) {
1487 return True;
1490 /* if this is NT then don't bother with the getatr */
1491 if (targetcli->capabilities & CAP_NT_SMBS) {
1492 errno = EPERM;
1493 return False;
1496 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1497 if (m_time != NULL) {
1498 if (a_time != NULL) *a_time = *m_time;
1499 if (c_time != NULL) *c_time = *m_time;
1501 srv->no_pathinfo2 = True;
1502 return True;
1505 errno = EPERM;
1506 return False;
1511 * Set file info on an SMB server. Use setpathinfo call first. If that
1512 * fails, use setattrE..
1514 * Access and modification time parameters are always used and must be
1515 * provided. Create time, if zero, will be determined from the actual create
1516 * time of the file. If non-zero, the create time will be set as well.
1518 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1520 static BOOL
1521 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1522 time_t c_time, time_t a_time, time_t m_time,
1523 uint16 mode)
1525 int fd;
1526 int ret;
1529 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1530 * modern function for "new code" to be using, and it works given a
1531 * filename rather than requiring that the file be opened to have its
1532 * attributes manipulated.
1534 if (srv->no_pathinfo ||
1535 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1538 * setpathinfo is not supported; go to plan B.
1540 * cli_setatr() does not work on win98, and it also doesn't
1541 * support setting the access time (only the modification
1542 * time), so in all cases, we open the specified file and use
1543 * cli_setattrE() which should work on all OS versions, and
1544 * supports both times.
1547 /* Don't try {q,set}pathinfo() again, with this server */
1548 srv->no_pathinfo = True;
1550 /* Open the file */
1551 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1553 errno = smbc_errno(context, &srv->cli);
1554 return -1;
1558 * Get the creat time of the file (if it wasn't provided).
1559 * We'll need it in the set call
1561 if (c_time == 0) {
1562 ret = cli_getattrE(&srv->cli, fd,
1563 NULL, NULL,
1564 &c_time, NULL, NULL);
1565 } else {
1566 ret = True;
1569 /* If we got create time, set times */
1570 if (ret) {
1571 /* Some OS versions don't support create time */
1572 if (c_time == 0 || c_time == -1) {
1573 c_time = time(NULL);
1577 * For sanity sake, since there is no POSIX function
1578 * to set the create time of a file, if the existing
1579 * create time is greater than either of access time
1580 * or modification time, set create time to the
1581 * smallest of those. This ensure that the create
1582 * time of a file is never greater than its last
1583 * access or modification time.
1585 if (c_time > a_time) c_time = a_time;
1586 if (c_time > m_time) c_time = m_time;
1588 /* Set the new attributes */
1589 ret = cli_setattrE(&srv->cli, fd,
1590 c_time, a_time, m_time);
1591 cli_close(&srv->cli, fd);
1595 * Unfortunately, setattrE() doesn't have a provision for
1596 * setting the access mode (attributes). We'll have to try
1597 * cli_setatr() for that, and with only this parameter, it
1598 * seems to work on win98.
1600 if (ret && mode != (uint16) -1) {
1601 ret = cli_setatr(&srv->cli, path, mode, 0);
1604 if (! ret) {
1605 errno = smbc_errno(context, &srv->cli);
1606 return False;
1610 return True;
1614 * Routine to unlink() a file
1617 static int
1618 smbc_unlink_ctx(SMBCCTX *context,
1619 const char *fname)
1621 fstring server, share, user, password, workgroup;
1622 pstring path, targetpath;
1623 struct cli_state *targetcli;
1624 SMBCSRV *srv = NULL;
1626 if (!context || !context->internal ||
1627 !context->internal->_initialized) {
1629 errno = EINVAL; /* Best I can think of ... */
1630 return -1;
1634 if (!fname) {
1636 errno = EINVAL;
1637 return -1;
1641 if (smbc_parse_path(context, fname,
1642 workgroup, sizeof(workgroup),
1643 server, sizeof(server),
1644 share, sizeof(share),
1645 path, sizeof(path),
1646 user, sizeof(user),
1647 password, sizeof(password),
1648 NULL, 0)) {
1649 errno = EINVAL;
1650 return -1;
1653 if (user[0] == (char)0) fstrcpy(user, context->user);
1655 srv = smbc_server(context, True,
1656 server, share, workgroup, user, password);
1658 if (!srv) {
1660 return -1; /* smbc_server sets errno */
1664 /*d_printf(">>>unlink: resolving %s\n", path);*/
1665 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1667 d_printf("Could not resolve %s\n", path);
1668 return -1;
1670 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1672 if (!cli_unlink(targetcli, targetpath)) {
1674 errno = smbc_errno(context, targetcli);
1676 if (errno == EACCES) { /* Check if the file is a directory */
1678 int saverr = errno;
1679 SMB_OFF_T size = 0;
1680 uint16 mode = 0;
1681 time_t m_time = 0, a_time = 0, c_time = 0;
1682 SMB_INO_T ino = 0;
1684 if (!smbc_getatr(context, srv, path, &mode, &size,
1685 &c_time, &a_time, &m_time, &ino)) {
1687 /* Hmmm, bad error ... What? */
1689 errno = smbc_errno(context, targetcli);
1690 return -1;
1693 else {
1695 if (IS_DOS_DIR(mode))
1696 errno = EISDIR;
1697 else
1698 errno = saverr; /* Restore this */
1703 return -1;
1707 return 0; /* Success ... */
1712 * Routine to rename() a file
1715 static int
1716 smbc_rename_ctx(SMBCCTX *ocontext,
1717 const char *oname,
1718 SMBCCTX *ncontext,
1719 const char *nname)
1721 fstring server1;
1722 fstring share1;
1723 fstring server2;
1724 fstring share2;
1725 fstring user1;
1726 fstring user2;
1727 fstring password1;
1728 fstring password2;
1729 fstring workgroup;
1730 pstring path1;
1731 pstring path2;
1732 pstring targetpath1;
1733 pstring targetpath2;
1734 struct cli_state *targetcli1;
1735 struct cli_state *targetcli2;
1736 SMBCSRV *srv = NULL;
1738 if (!ocontext || !ncontext ||
1739 !ocontext->internal || !ncontext->internal ||
1740 !ocontext->internal->_initialized ||
1741 !ncontext->internal->_initialized) {
1743 errno = EINVAL; /* Best I can think of ... */
1744 return -1;
1748 if (!oname || !nname) {
1750 errno = EINVAL;
1751 return -1;
1755 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1757 smbc_parse_path(ocontext, oname,
1758 workgroup, sizeof(workgroup),
1759 server1, sizeof(server1),
1760 share1, sizeof(share1),
1761 path1, sizeof(path1),
1762 user1, sizeof(user1),
1763 password1, sizeof(password1),
1764 NULL, 0);
1766 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1768 smbc_parse_path(ncontext, nname,
1769 NULL, 0,
1770 server2, sizeof(server2),
1771 share2, sizeof(share2),
1772 path2, sizeof(path2),
1773 user2, sizeof(user2),
1774 password2, sizeof(password2),
1775 NULL, 0);
1777 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1779 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1780 strcmp(user1, user2)) {
1782 /* Can't rename across file systems, or users?? */
1784 errno = EXDEV;
1785 return -1;
1789 srv = smbc_server(ocontext, True,
1790 server1, share1, workgroup, user1, password1);
1791 if (!srv) {
1793 return -1;
1797 /*d_printf(">>>rename: resolving %s\n", path1);*/
1798 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1800 d_printf("Could not resolve %s\n", path1);
1801 return -1;
1803 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1804 /*d_printf(">>>rename: resolving %s\n", path2);*/
1805 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1807 d_printf("Could not resolve %s\n", path2);
1808 return -1;
1810 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1812 if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1813 strcmp(targetcli1->share, targetcli2->share))
1815 /* can't rename across file systems */
1817 errno = EXDEV;
1818 return -1;
1821 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1822 int eno = smbc_errno(ocontext, targetcli1);
1824 if (eno != EEXIST ||
1825 !cli_unlink(targetcli1, targetpath2) ||
1826 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1828 errno = eno;
1829 return -1;
1834 return 0; /* Success */
1839 * A routine to lseek() a file
1842 static off_t
1843 smbc_lseek_ctx(SMBCCTX *context,
1844 SMBCFILE *file,
1845 off_t offset,
1846 int whence)
1848 SMB_OFF_T size;
1849 fstring server, share, user, password;
1850 pstring path, targetpath;
1851 struct cli_state *targetcli;
1853 if (!context || !context->internal ||
1854 !context->internal->_initialized) {
1856 errno = EINVAL;
1857 return -1;
1861 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1863 errno = EBADF;
1864 return -1;
1868 if (!file->file) {
1870 errno = EINVAL;
1871 return -1; /* Can't lseek a dir ... */
1875 switch (whence) {
1876 case SEEK_SET:
1877 file->offset = offset;
1878 break;
1880 case SEEK_CUR:
1881 file->offset += offset;
1882 break;
1884 case SEEK_END:
1885 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1886 if (smbc_parse_path(context, file->fname,
1887 NULL, 0,
1888 server, sizeof(server),
1889 share, sizeof(share),
1890 path, sizeof(path),
1891 user, sizeof(user),
1892 password, sizeof(password),
1893 NULL, 0)) {
1895 errno = EINVAL;
1896 return -1;
1899 /*d_printf(">>>lseek: resolving %s\n", path);*/
1900 if (!cli_resolve_path("", &file->srv->cli, path,
1901 &targetcli, targetpath))
1903 d_printf("Could not resolve %s\n", path);
1904 return -1;
1906 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1908 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1909 &size, NULL, NULL, NULL, NULL, NULL))
1911 SMB_OFF_T b_size = size;
1912 if (!cli_getattrE(targetcli, file->cli_fd,
1913 NULL, &b_size, NULL, NULL, NULL))
1915 errno = EINVAL;
1916 return -1;
1917 } else
1918 size = b_size;
1920 file->offset = size + offset;
1921 break;
1923 default:
1924 errno = EINVAL;
1925 break;
1929 return file->offset;
1934 * Generate an inode number from file name for those things that need it
1937 static ino_t
1938 smbc_inode(SMBCCTX *context,
1939 const char *name)
1942 if (!context || !context->internal ||
1943 !context->internal->_initialized) {
1945 errno = EINVAL;
1946 return -1;
1950 if (!*name) return 2; /* FIXME, why 2 ??? */
1951 return (ino_t)str_checksum(name);
1956 * Routine to put basic stat info into a stat structure ... Used by stat and
1957 * fstat below.
1960 static int
1961 smbc_setup_stat(SMBCCTX *context,
1962 struct stat *st,
1963 char *fname,
1964 SMB_OFF_T size,
1965 int mode)
1968 st->st_mode = 0;
1970 if (IS_DOS_DIR(mode)) {
1971 st->st_mode = SMBC_DIR_MODE;
1972 } else {
1973 st->st_mode = SMBC_FILE_MODE;
1976 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1977 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1978 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1979 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1981 st->st_size = size;
1982 #ifdef HAVE_STAT_ST_BLKSIZE
1983 st->st_blksize = 512;
1984 #endif
1985 #ifdef HAVE_STAT_ST_BLOCKS
1986 st->st_blocks = (size+511)/512;
1987 #endif
1988 st->st_uid = getuid();
1989 st->st_gid = getgid();
1991 if (IS_DOS_DIR(mode)) {
1992 st->st_nlink = 2;
1993 } else {
1994 st->st_nlink = 1;
1997 if (st->st_ino == 0) {
1998 st->st_ino = smbc_inode(context, fname);
2001 return True; /* FIXME: Is this needed ? */
2006 * Routine to stat a file given a name
2009 static int
2010 smbc_stat_ctx(SMBCCTX *context,
2011 const char *fname,
2012 struct stat *st)
2014 SMBCSRV *srv;
2015 fstring server;
2016 fstring share;
2017 fstring user;
2018 fstring password;
2019 fstring workgroup;
2020 pstring path;
2021 time_t m_time = 0;
2022 time_t a_time = 0;
2023 time_t c_time = 0;
2024 SMB_OFF_T size = 0;
2025 uint16 mode = 0;
2026 SMB_INO_T ino = 0;
2028 if (!context || !context->internal ||
2029 !context->internal->_initialized) {
2031 errno = EINVAL; /* Best I can think of ... */
2032 return -1;
2036 if (!fname) {
2038 errno = EINVAL;
2039 return -1;
2043 DEBUG(4, ("smbc_stat(%s)\n", fname));
2045 if (smbc_parse_path(context, fname,
2046 workgroup, sizeof(workgroup),
2047 server, sizeof(server),
2048 share, sizeof(share),
2049 path, sizeof(path),
2050 user, sizeof(user),
2051 password, sizeof(password),
2052 NULL, 0)) {
2053 errno = EINVAL;
2054 return -1;
2057 if (user[0] == (char)0) fstrcpy(user, context->user);
2059 srv = smbc_server(context, True,
2060 server, share, workgroup, user, password);
2062 if (!srv) {
2063 return -1; /* errno set by smbc_server */
2066 if (!smbc_getatr(context, srv, path, &mode, &size,
2067 &c_time, &a_time, &m_time, &ino)) {
2069 errno = smbc_errno(context, &srv->cli);
2070 return -1;
2074 st->st_ino = ino;
2076 smbc_setup_stat(context, st, path, size, mode);
2078 st->st_atime = a_time;
2079 st->st_ctime = c_time;
2080 st->st_mtime = m_time;
2081 st->st_dev = srv->dev;
2083 return 0;
2088 * Routine to stat a file given an fd
2091 static int
2092 smbc_fstat_ctx(SMBCCTX *context,
2093 SMBCFILE *file,
2094 struct stat *st)
2096 time_t c_time;
2097 time_t a_time;
2098 time_t m_time;
2099 SMB_OFF_T size;
2100 uint16 mode;
2101 fstring server;
2102 fstring share;
2103 fstring user;
2104 fstring password;
2105 pstring path;
2106 pstring targetpath;
2107 struct cli_state *targetcli;
2108 SMB_INO_T ino = 0;
2110 if (!context || !context->internal ||
2111 !context->internal->_initialized) {
2113 errno = EINVAL;
2114 return -1;
2118 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2120 errno = EBADF;
2121 return -1;
2125 if (!file->file) {
2127 return context->fstatdir(context, file, st);
2131 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2132 if (smbc_parse_path(context, file->fname,
2133 NULL, 0,
2134 server, sizeof(server),
2135 share, sizeof(share),
2136 path, sizeof(path),
2137 user, sizeof(user),
2138 password, sizeof(password),
2139 NULL, 0)) {
2140 errno = EINVAL;
2141 return -1;
2144 /*d_printf(">>>fstat: resolving %s\n", path);*/
2145 if (!cli_resolve_path("", &file->srv->cli, path,
2146 &targetcli, targetpath))
2148 d_printf("Could not resolve %s\n", path);
2149 return -1;
2151 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2153 if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2154 &c_time, &a_time, &m_time, NULL, &ino)) {
2155 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2156 &c_time, &a_time, &m_time)) {
2158 errno = EINVAL;
2159 return -1;
2163 st->st_ino = ino;
2165 smbc_setup_stat(context, st, file->fname, size, mode);
2167 st->st_atime = a_time;
2168 st->st_ctime = c_time;
2169 st->st_mtime = m_time;
2170 st->st_dev = file->srv->dev;
2172 return 0;
2177 * Routine to open a directory
2178 * We accept the URL syntax explained in smbc_parse_path(), above.
2181 static void
2182 smbc_remove_dir(SMBCFILE *dir)
2184 struct smbc_dir_list *d,*f;
2186 d = dir->dir_list;
2187 while (d) {
2189 f = d; d = d->next;
2191 SAFE_FREE(f->dirent);
2192 SAFE_FREE(f);
2196 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2200 static int
2201 add_dirent(SMBCFILE *dir,
2202 const char *name,
2203 const char *comment,
2204 uint32 type)
2206 struct smbc_dirent *dirent;
2207 int size;
2208 int name_length = (name == NULL ? 0 : strlen(name));
2209 int comment_len = (comment == NULL ? 0 : strlen(comment));
2212 * Allocate space for the dirent, which must be increased by the
2213 * size of the name and the comment and 1 each for the null terminator.
2216 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2218 dirent = SMB_MALLOC(size);
2220 if (!dirent) {
2222 dir->dir_error = ENOMEM;
2223 return -1;
2227 ZERO_STRUCTP(dirent);
2229 if (dir->dir_list == NULL) {
2231 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2232 if (!dir->dir_list) {
2234 SAFE_FREE(dirent);
2235 dir->dir_error = ENOMEM;
2236 return -1;
2239 ZERO_STRUCTP(dir->dir_list);
2241 dir->dir_end = dir->dir_next = dir->dir_list;
2243 else {
2245 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2247 if (!dir->dir_end->next) {
2249 SAFE_FREE(dirent);
2250 dir->dir_error = ENOMEM;
2251 return -1;
2254 ZERO_STRUCTP(dir->dir_end->next);
2256 dir->dir_end = dir->dir_end->next;
2259 dir->dir_end->next = NULL;
2260 dir->dir_end->dirent = dirent;
2262 dirent->smbc_type = type;
2263 dirent->namelen = name_length;
2264 dirent->commentlen = comment_len;
2265 dirent->dirlen = size;
2268 * dirent->namelen + 1 includes the null (no null termination needed)
2269 * Ditto for dirent->commentlen.
2270 * The space for the two null bytes was allocated.
2272 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2273 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2274 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2276 return 0;
2280 static void
2281 list_unique_wg_fn(const char *name,
2282 uint32 type,
2283 const char *comment,
2284 void *state)
2286 SMBCFILE *dir = (SMBCFILE *)state;
2287 struct smbc_dir_list *dir_list;
2288 struct smbc_dirent *dirent;
2289 int dirent_type;
2290 int do_remove = 0;
2292 dirent_type = dir->dir_type;
2294 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2296 /* An error occurred, what do we do? */
2297 /* FIXME: Add some code here */
2300 /* Point to the one just added */
2301 dirent = dir->dir_end->dirent;
2303 /* See if this was a duplicate */
2304 for (dir_list = dir->dir_list;
2305 dir_list != dir->dir_end;
2306 dir_list = dir_list->next) {
2307 if (! do_remove &&
2308 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2309 /* Duplicate. End end of list need to be removed. */
2310 do_remove = 1;
2313 if (do_remove && dir_list->next == dir->dir_end) {
2314 /* Found the end of the list. Remove it. */
2315 dir->dir_end = dir_list;
2316 free(dir_list->next);
2317 free(dirent);
2318 dir_list->next = NULL;
2319 break;
2324 static void
2325 list_fn(const char *name,
2326 uint32 type,
2327 const char *comment,
2328 void *state)
2330 SMBCFILE *dir = (SMBCFILE *)state;
2331 int dirent_type;
2334 * We need to process the type a little ...
2336 * Disk share = 0x00000000
2337 * Print share = 0x00000001
2338 * Comms share = 0x00000002 (obsolete?)
2339 * IPC$ share = 0x00000003
2341 * administrative shares:
2342 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2345 if (dir->dir_type == SMBC_FILE_SHARE) {
2347 switch (type) {
2348 case 0 | 0x80000000:
2349 case 0:
2350 dirent_type = SMBC_FILE_SHARE;
2351 break;
2353 case 1:
2354 dirent_type = SMBC_PRINTER_SHARE;
2355 break;
2357 case 2:
2358 dirent_type = SMBC_COMMS_SHARE;
2359 break;
2361 case 3 | 0x80000000:
2362 case 3:
2363 dirent_type = SMBC_IPC_SHARE;
2364 break;
2366 default:
2367 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2368 break;
2371 else {
2372 dirent_type = dir->dir_type;
2375 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2377 /* An error occurred, what do we do? */
2378 /* FIXME: Add some code here */
2383 static void
2384 dir_list_fn(const char *mnt,
2385 file_info *finfo,
2386 const char *mask,
2387 void *state)
2390 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2391 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2393 /* Handle an error ... */
2395 /* FIXME: Add some code ... */
2401 static int
2402 net_share_enum_rpc(struct cli_state *cli,
2403 void (*fn)(const char *name,
2404 uint32 type,
2405 const char *comment,
2406 void *state),
2407 void *state)
2409 int i;
2410 WERROR result;
2411 ENUM_HND enum_hnd;
2412 uint32 info_level = 1;
2413 uint32 preferred_len = 0xffffffff;
2414 uint32 type;
2415 SRV_SHARE_INFO_CTR ctr;
2416 fstring name = "";
2417 fstring comment = "";
2418 void *mem_ctx;
2419 struct rpc_pipe_client *pipe_hnd;
2420 NTSTATUS nt_status;
2422 /* Open the server service pipe */
2423 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2424 if (!pipe_hnd) {
2425 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2426 return -1;
2429 /* Allocate a context for parsing and for the entries in "ctr" */
2430 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2431 if (mem_ctx == NULL) {
2432 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2433 cli_rpc_pipe_close(pipe_hnd);
2434 return -1;
2437 /* Issue the NetShareEnum RPC call and retrieve the response */
2438 init_enum_hnd(&enum_hnd, 0);
2439 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2440 mem_ctx,
2441 info_level,
2442 &ctr,
2443 preferred_len,
2444 &enum_hnd);
2446 /* Was it successful? */
2447 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2448 /* Nope. Go clean up. */
2449 goto done;
2452 /* For each returned entry... */
2453 for (i = 0; i < ctr.num_entries; i++) {
2455 /* pull out the share name */
2456 rpcstr_pull_unistr2_fstring(
2457 name, &ctr.share.info1[i].info_1_str.uni_netname);
2459 /* pull out the share's comment */
2460 rpcstr_pull_unistr2_fstring(
2461 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2463 /* Get the type value */
2464 type = ctr.share.info1[i].info_1.type;
2466 /* Add this share to the list */
2467 (*fn)(name, type, comment, state);
2470 done:
2471 /* Close the server service pipe */
2472 cli_rpc_pipe_close(pipe_hnd);
2474 /* Free all memory which was allocated for this request */
2475 TALLOC_FREE(mem_ctx);
2477 /* Tell 'em if it worked */
2478 return W_ERROR_IS_OK(result) ? 0 : -1;
2483 static SMBCFILE *
2484 smbc_opendir_ctx(SMBCCTX *context,
2485 const char *fname)
2487 fstring server, share, user, password, options;
2488 pstring workgroup;
2489 pstring path;
2490 uint16 mode;
2491 char *p;
2492 SMBCSRV *srv = NULL;
2493 SMBCFILE *dir = NULL;
2494 struct in_addr rem_ip;
2496 if (!context || !context->internal ||
2497 !context->internal->_initialized) {
2498 DEBUG(4, ("no valid context\n"));
2499 errno = EINVAL + 8192;
2500 return NULL;
2504 if (!fname) {
2505 DEBUG(4, ("no valid fname\n"));
2506 errno = EINVAL + 8193;
2507 return NULL;
2510 if (smbc_parse_path(context, fname,
2511 workgroup, sizeof(workgroup),
2512 server, sizeof(server),
2513 share, sizeof(share),
2514 path, sizeof(path),
2515 user, sizeof(user),
2516 password, sizeof(password),
2517 options, sizeof(options))) {
2518 DEBUG(4, ("no valid path\n"));
2519 errno = EINVAL + 8194;
2520 return NULL;
2523 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2524 "path='%s' options='%s'\n",
2525 fname, server, share, path, options));
2527 /* Ensure the options are valid */
2528 if (smbc_check_options(server, share, path, options)) {
2529 DEBUG(4, ("unacceptable options (%s)\n", options));
2530 errno = EINVAL + 8195;
2531 return NULL;
2534 if (user[0] == (char)0) fstrcpy(user, context->user);
2536 dir = SMB_MALLOC_P(SMBCFILE);
2538 if (!dir) {
2540 errno = ENOMEM;
2541 return NULL;
2545 ZERO_STRUCTP(dir);
2547 dir->cli_fd = 0;
2548 dir->fname = SMB_STRDUP(fname);
2549 dir->srv = NULL;
2550 dir->offset = 0;
2551 dir->file = False;
2552 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2554 if (server[0] == (char)0) {
2556 int i;
2557 int count;
2558 int max_lmb_count;
2559 struct ip_service *ip_list;
2560 struct ip_service server_addr;
2561 struct user_auth_info u_info;
2562 struct cli_state *cli;
2564 if (share[0] != (char)0 || path[0] != (char)0) {
2566 errno = EINVAL + 8196;
2567 if (dir) {
2568 SAFE_FREE(dir->fname);
2569 SAFE_FREE(dir);
2571 return NULL;
2574 /* Determine how many local master browsers to query */
2575 max_lmb_count = (context->options.browse_max_lmb_count == 0
2576 ? INT_MAX
2577 : context->options.browse_max_lmb_count);
2579 pstrcpy(u_info.username, user);
2580 pstrcpy(u_info.password, password);
2583 * We have server and share and path empty but options
2584 * requesting that we scan all master browsers for their list
2585 * of workgroups/domains. This implies that we must first try
2586 * broadcast queries to find all master browsers, and if that
2587 * doesn't work, then try our other methods which return only
2588 * a single master browser.
2591 ip_list = NULL;
2592 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2594 SAFE_FREE(ip_list);
2596 if (!find_master_ip(workgroup, &server_addr.ip)) {
2598 if (dir) {
2599 SAFE_FREE(dir->fname);
2600 SAFE_FREE(dir);
2602 errno = ENOENT;
2603 return NULL;
2606 ip_list = &server_addr;
2607 count = 1;
2610 for (i = 0; i < count && i < max_lmb_count; i++) {
2611 DEBUG(99, ("Found master browser %d of %d: %s\n",
2612 i+1, MAX(count, max_lmb_count),
2613 inet_ntoa(ip_list[i].ip)));
2615 cli = get_ipc_connect_master_ip(&ip_list[i],
2616 workgroup, &u_info);
2617 /* cli == NULL is the master browser refused to talk or
2618 could not be found */
2619 if ( !cli )
2620 continue;
2622 fstrcpy(server, cli->desthost);
2623 cli_shutdown(cli);
2625 DEBUG(4, ("using workgroup %s %s\n",
2626 workgroup, server));
2629 * For each returned master browser IP address, get a
2630 * connection to IPC$ on the server if we do not
2631 * already have one, and determine the
2632 * workgroups/domains that it knows about.
2635 srv = smbc_server(context, True, server, "IPC$",
2636 workgroup, user, password);
2637 if (!srv) {
2638 continue;
2641 dir->srv = srv;
2642 dir->dir_type = SMBC_WORKGROUP;
2644 /* Now, list the stuff ... */
2646 if (!cli_NetServerEnum(&srv->cli,
2647 workgroup,
2648 SV_TYPE_DOMAIN_ENUM,
2649 list_unique_wg_fn,
2650 (void *)dir)) {
2651 continue;
2655 SAFE_FREE(ip_list);
2656 } else {
2658 * Server not an empty string ... Check the rest and see what
2659 * gives
2661 if (*share == '\0') {
2662 if (*path != '\0') {
2664 /* Should not have empty share with path */
2665 errno = EINVAL + 8197;
2666 if (dir) {
2667 SAFE_FREE(dir->fname);
2668 SAFE_FREE(dir);
2670 return NULL;
2675 * We don't know if <server> is really a server name
2676 * or is a workgroup/domain name. If we already have
2677 * a server structure for it, we'll use it.
2678 * Otherwise, check to see if <server><1D>,
2679 * <server><1B>, or <server><20> translates. We check
2680 * to see if <server> is an IP address first.
2684 * See if we have an existing server. Do not
2685 * establish a connection if one does not already
2686 * exist.
2688 srv = smbc_server(context, False, server, "IPC$",
2689 workgroup, user, password);
2692 * If no existing server and not an IP addr, look for
2693 * LMB or DMB
2695 if (!srv &&
2696 !is_ipaddress(server) &&
2697 (resolve_name(server, &rem_ip, 0x1d) || /* LMB */
2698 resolve_name(server, &rem_ip, 0x1b) )) { /* DMB */
2700 fstring buserver;
2702 dir->dir_type = SMBC_SERVER;
2705 * Get the backup list ...
2707 if (!name_status_find(server, 0, 0,
2708 rem_ip, buserver)) {
2710 DEBUG(0, ("Could not get name of "
2711 "local/domain master browser "
2712 "for server %s\n", server));
2713 if (dir) {
2714 SAFE_FREE(dir->fname);
2715 SAFE_FREE(dir);
2717 errno = EPERM;
2718 return NULL;
2723 * Get a connection to IPC$ on the server if
2724 * we do not already have one
2726 srv = smbc_server(context, True,
2727 buserver, "IPC$",
2728 workgroup, user, password);
2729 if (!srv) {
2730 DEBUG(0, ("got no contact to IPC$\n"));
2731 if (dir) {
2732 SAFE_FREE(dir->fname);
2733 SAFE_FREE(dir);
2735 return NULL;
2739 dir->srv = srv;
2741 /* Now, list the servers ... */
2742 if (!cli_NetServerEnum(&srv->cli, server,
2743 0x0000FFFE, list_fn,
2744 (void *)dir)) {
2746 if (dir) {
2747 SAFE_FREE(dir->fname);
2748 SAFE_FREE(dir);
2750 return NULL;
2752 } else if (srv ||
2753 (resolve_name(server, &rem_ip, 0x20))) {
2755 /* If we hadn't found the server, get one now */
2756 if (!srv) {
2757 srv = smbc_server(context, True,
2758 server, "IPC$",
2759 workgroup,
2760 user, password);
2763 if (!srv) {
2764 if (dir) {
2765 SAFE_FREE(dir->fname);
2766 SAFE_FREE(dir);
2768 return NULL;
2772 dir->dir_type = SMBC_FILE_SHARE;
2773 dir->srv = srv;
2775 /* List the shares ... */
2777 if (net_share_enum_rpc(
2778 &srv->cli,
2779 list_fn,
2780 (void *) dir) < 0 &&
2781 cli_RNetShareEnum(
2782 &srv->cli,
2783 list_fn,
2784 (void *)dir) < 0) {
2786 errno = cli_errno(&srv->cli);
2787 if (dir) {
2788 SAFE_FREE(dir->fname);
2789 SAFE_FREE(dir);
2791 return NULL;
2794 } else {
2795 /* Neither the workgroup nor server exists */
2796 errno = ECONNREFUSED;
2797 if (dir) {
2798 SAFE_FREE(dir->fname);
2799 SAFE_FREE(dir);
2801 return NULL;
2805 else {
2807 * The server and share are specified ... work from
2808 * there ...
2810 pstring targetpath;
2811 struct cli_state *targetcli;
2813 /* We connect to the server and list the directory */
2814 dir->dir_type = SMBC_FILE_SHARE;
2816 srv = smbc_server(context, True, server, share,
2817 workgroup, user, password);
2819 if (!srv) {
2821 if (dir) {
2822 SAFE_FREE(dir->fname);
2823 SAFE_FREE(dir);
2825 return NULL;
2829 dir->srv = srv;
2831 /* Now, list the files ... */
2833 p = path + strlen(path);
2834 pstrcat(path, "\\*");
2836 if (!cli_resolve_path("", &srv->cli, path,
2837 &targetcli, targetpath))
2839 d_printf("Could not resolve %s\n", path);
2840 if (dir) {
2841 SAFE_FREE(dir->fname);
2842 SAFE_FREE(dir);
2844 return NULL;
2847 if (cli_list(targetcli, targetpath,
2848 aDIR | aSYSTEM | aHIDDEN,
2849 dir_list_fn, (void *)dir) < 0) {
2851 if (dir) {
2852 SAFE_FREE(dir->fname);
2853 SAFE_FREE(dir);
2855 errno = smbc_errno(context, targetcli);
2857 if (errno == EINVAL) {
2859 * See if they asked to opendir something
2860 * other than a directory. If so, the
2861 * converted error value we got would have
2862 * been EINVAL rather than ENOTDIR.
2864 *p = '\0'; /* restore original path */
2866 if (smbc_getatr(context, srv, path,
2867 &mode, NULL,
2868 NULL, NULL, NULL,
2869 NULL) &&
2870 ! IS_DOS_DIR(mode)) {
2872 /* It is. Correct the error value */
2873 errno = ENOTDIR;
2877 return NULL;
2884 DLIST_ADD(context->internal->_files, dir);
2885 return dir;
2890 * Routine to close a directory
2893 static int
2894 smbc_closedir_ctx(SMBCCTX *context,
2895 SMBCFILE *dir)
2898 if (!context || !context->internal ||
2899 !context->internal->_initialized) {
2901 errno = EINVAL;
2902 return -1;
2906 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2908 errno = EBADF;
2909 return -1;
2913 smbc_remove_dir(dir); /* Clean it up */
2915 DLIST_REMOVE(context->internal->_files, dir);
2917 if (dir) {
2919 SAFE_FREE(dir->fname);
2920 SAFE_FREE(dir); /* Free the space too */
2923 return 0;
2927 static void
2928 smbc_readdir_internal(SMBCCTX * context,
2929 struct smbc_dirent *dest,
2930 struct smbc_dirent *src,
2931 int max_namebuf_len)
2933 if (context->options.urlencode_readdir_entries) {
2935 /* url-encode the name. get back remaining buffer space */
2936 max_namebuf_len =
2937 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2939 /* We now know the name length */
2940 dest->namelen = strlen(dest->name);
2942 /* Save the pointer to the beginning of the comment */
2943 dest->comment = dest->name + dest->namelen + 1;
2945 /* Copy the comment */
2946 strncpy(dest->comment, src->comment, max_namebuf_len - 1);
2947 dest->comment[max_namebuf_len - 1] = '\0';
2949 /* Save other fields */
2950 dest->smbc_type = src->smbc_type;
2951 dest->commentlen = strlen(dest->comment);
2952 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2953 (char *) dest);
2954 } else {
2956 /* No encoding. Just copy the entry as is. */
2957 memcpy(dest, src, src->dirlen);
2958 dest->comment = (char *)(&dest->name + src->namelen + 1);
2964 * Routine to get a directory entry
2967 struct smbc_dirent *
2968 smbc_readdir_ctx(SMBCCTX *context,
2969 SMBCFILE *dir)
2971 int maxlen;
2972 struct smbc_dirent *dirp, *dirent;
2974 /* Check that all is ok first ... */
2976 if (!context || !context->internal ||
2977 !context->internal->_initialized) {
2979 errno = EINVAL;
2980 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2981 return NULL;
2985 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2987 errno = EBADF;
2988 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2989 return NULL;
2993 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2995 errno = ENOTDIR;
2996 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2997 return NULL;
3001 if (!dir->dir_next) {
3002 return NULL;
3005 dirent = dir->dir_next->dirent;
3006 if (!dirent) {
3008 errno = ENOENT;
3009 return NULL;
3013 dirp = (struct smbc_dirent *)context->internal->_dirent;
3014 maxlen = (sizeof(context->internal->_dirent) -
3015 sizeof(struct smbc_dirent));
3017 smbc_readdir_internal(context, dirp, dirent, maxlen);
3019 dir->dir_next = dir->dir_next->next;
3021 return dirp;
3025 * Routine to get directory entries
3028 static int
3029 smbc_getdents_ctx(SMBCCTX *context,
3030 SMBCFILE *dir,
3031 struct smbc_dirent *dirp,
3032 int count)
3034 int rem = count;
3035 int reqd;
3036 int maxlen;
3037 char *ndir = (char *)dirp;
3038 struct smbc_dir_list *dirlist;
3040 /* Check that all is ok first ... */
3042 if (!context || !context->internal ||
3043 !context->internal->_initialized) {
3045 errno = EINVAL;
3046 return -1;
3050 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3052 errno = EBADF;
3053 return -1;
3057 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3059 errno = ENOTDIR;
3060 return -1;
3065 * Now, retrieve the number of entries that will fit in what was passed
3066 * We have to figure out if the info is in the list, or we need to
3067 * send a request to the server to get the info.
3070 while ((dirlist = dir->dir_next)) {
3071 struct smbc_dirent *dirent;
3073 if (!dirlist->dirent) {
3075 errno = ENOENT; /* Bad error */
3076 return -1;
3080 /* Do urlencoding of next entry, if so selected */
3081 dirent = (struct smbc_dirent *)context->internal->_dirent;
3082 maxlen = (sizeof(context->internal->_dirent) -
3083 sizeof(struct smbc_dirent));
3084 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3086 reqd = dirent->dirlen;
3088 if (rem < reqd) {
3090 if (rem < count) { /* We managed to copy something */
3092 errno = 0;
3093 return count - rem;
3096 else { /* Nothing copied ... */
3098 errno = EINVAL; /* Not enough space ... */
3099 return -1;
3105 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3107 ((struct smbc_dirent *)ndir)->comment =
3108 (char *)(&((struct smbc_dirent *)ndir)->name +
3109 dirent->namelen +
3112 ndir += reqd;
3114 rem -= reqd;
3116 dir->dir_next = dirlist = dirlist -> next;
3119 if (rem == count)
3120 return 0;
3121 else
3122 return count - rem;
3127 * Routine to create a directory ...
3130 static int
3131 smbc_mkdir_ctx(SMBCCTX *context,
3132 const char *fname,
3133 mode_t mode)
3135 SMBCSRV *srv;
3136 fstring server;
3137 fstring share;
3138 fstring user;
3139 fstring password;
3140 fstring workgroup;
3141 pstring path, targetpath;
3142 struct cli_state *targetcli;
3144 if (!context || !context->internal ||
3145 !context->internal->_initialized) {
3147 errno = EINVAL;
3148 return -1;
3152 if (!fname) {
3154 errno = EINVAL;
3155 return -1;
3159 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3161 if (smbc_parse_path(context, fname,
3162 workgroup, sizeof(workgroup),
3163 server, sizeof(server),
3164 share, sizeof(share),
3165 path, sizeof(path),
3166 user, sizeof(user),
3167 password, sizeof(password),
3168 NULL, 0)) {
3169 errno = EINVAL;
3170 return -1;
3173 if (user[0] == (char)0) fstrcpy(user, context->user);
3175 srv = smbc_server(context, True,
3176 server, share, workgroup, user, password);
3178 if (!srv) {
3180 return -1; /* errno set by smbc_server */
3184 /*d_printf(">>>mkdir: resolving %s\n", path);*/
3185 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3187 d_printf("Could not resolve %s\n", path);
3188 return -1;
3190 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3192 if (!cli_mkdir(targetcli, targetpath)) {
3194 errno = smbc_errno(context, targetcli);
3195 return -1;
3199 return 0;
3204 * Our list function simply checks to see if a directory is not empty
3207 static int smbc_rmdir_dirempty = True;
3209 static void
3210 rmdir_list_fn(const char *mnt,
3211 file_info *finfo,
3212 const char *mask,
3213 void *state)
3215 if (strncmp(finfo->name, ".", 1) != 0 &&
3216 strncmp(finfo->name, "..", 2) != 0) {
3218 smbc_rmdir_dirempty = False;
3223 * Routine to remove a directory
3226 static int
3227 smbc_rmdir_ctx(SMBCCTX *context,
3228 const char *fname)
3230 SMBCSRV *srv;
3231 fstring server;
3232 fstring share;
3233 fstring user;
3234 fstring password;
3235 fstring workgroup;
3236 pstring path;
3237 pstring targetpath;
3238 struct cli_state *targetcli;
3240 if (!context || !context->internal ||
3241 !context->internal->_initialized) {
3243 errno = EINVAL;
3244 return -1;
3248 if (!fname) {
3250 errno = EINVAL;
3251 return -1;
3255 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3257 if (smbc_parse_path(context, fname,
3258 workgroup, sizeof(workgroup),
3259 server, sizeof(server),
3260 share, sizeof(share),
3261 path, sizeof(path),
3262 user, sizeof(user),
3263 password, sizeof(password),
3264 NULL, 0))
3266 errno = EINVAL;
3267 return -1;
3270 if (user[0] == (char)0) fstrcpy(user, context->user);
3272 srv = smbc_server(context, True,
3273 server, share, workgroup, user, password);
3275 if (!srv) {
3277 return -1; /* errno set by smbc_server */
3281 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3282 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3284 d_printf("Could not resolve %s\n", path);
3285 return -1;
3287 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3290 if (!cli_rmdir(targetcli, targetpath)) {
3292 errno = smbc_errno(context, targetcli);
3294 if (errno == EACCES) { /* Check if the dir empty or not */
3296 /* Local storage to avoid buffer overflows */
3297 pstring lpath;
3299 smbc_rmdir_dirempty = True; /* Make this so ... */
3301 pstrcpy(lpath, targetpath);
3302 pstrcat(lpath, "\\*");
3304 if (cli_list(targetcli, lpath,
3305 aDIR | aSYSTEM | aHIDDEN,
3306 rmdir_list_fn, NULL) < 0) {
3308 /* Fix errno to ignore latest error ... */
3309 DEBUG(5, ("smbc_rmdir: "
3310 "cli_list returned an error: %d\n",
3311 smbc_errno(context, targetcli)));
3312 errno = EACCES;
3316 if (smbc_rmdir_dirempty)
3317 errno = EACCES;
3318 else
3319 errno = ENOTEMPTY;
3323 return -1;
3327 return 0;
3332 * Routine to return the current directory position
3335 static off_t
3336 smbc_telldir_ctx(SMBCCTX *context,
3337 SMBCFILE *dir)
3339 off_t ret_val; /* Squash warnings about cast */
3341 if (!context || !context->internal ||
3342 !context->internal->_initialized) {
3344 errno = EINVAL;
3345 return -1;
3349 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3351 errno = EBADF;
3352 return -1;
3356 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3358 errno = ENOTDIR;
3359 return -1;
3364 * We return the pointer here as the offset
3366 ret_val = (off_t)(long)dir->dir_next;
3367 return ret_val;
3372 * A routine to run down the list and see if the entry is OK
3375 struct smbc_dir_list *
3376 smbc_check_dir_ent(struct smbc_dir_list *list,
3377 struct smbc_dirent *dirent)
3380 /* Run down the list looking for what we want */
3382 if (dirent) {
3384 struct smbc_dir_list *tmp = list;
3386 while (tmp) {
3388 if (tmp->dirent == dirent)
3389 return tmp;
3391 tmp = tmp->next;
3397 return NULL; /* Not found, or an error */
3403 * Routine to seek on a directory
3406 static int
3407 smbc_lseekdir_ctx(SMBCCTX *context,
3408 SMBCFILE *dir,
3409 off_t offset)
3411 long int l_offset = offset; /* Handle problems of size */
3412 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3413 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3415 if (!context || !context->internal ||
3416 !context->internal->_initialized) {
3418 errno = EINVAL;
3419 return -1;
3423 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3425 errno = ENOTDIR;
3426 return -1;
3430 /* Now, check what we were passed and see if it is OK ... */
3432 if (dirent == NULL) { /* Seek to the begining of the list */
3434 dir->dir_next = dir->dir_list;
3435 return 0;
3439 /* Now, run down the list and make sure that the entry is OK */
3440 /* This may need to be changed if we change the format of the list */
3442 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3444 errno = EINVAL; /* Bad entry */
3445 return -1;
3449 dir->dir_next = list_ent;
3451 return 0;
3456 * Routine to fstat a dir
3459 static int
3460 smbc_fstatdir_ctx(SMBCCTX *context,
3461 SMBCFILE *dir,
3462 struct stat *st)
3465 if (!context || !context->internal ||
3466 !context->internal->_initialized) {
3468 errno = EINVAL;
3469 return -1;
3473 /* No code yet ... */
3475 return 0;
3479 static int
3480 smbc_chmod_ctx(SMBCCTX *context,
3481 const char *fname,
3482 mode_t newmode)
3484 SMBCSRV *srv;
3485 fstring server;
3486 fstring share;
3487 fstring user;
3488 fstring password;
3489 fstring workgroup;
3490 pstring path;
3491 uint16 mode;
3493 if (!context || !context->internal ||
3494 !context->internal->_initialized) {
3496 errno = EINVAL; /* Best I can think of ... */
3497 return -1;
3501 if (!fname) {
3503 errno = EINVAL;
3504 return -1;
3508 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3510 if (smbc_parse_path(context, fname,
3511 workgroup, sizeof(workgroup),
3512 server, sizeof(server),
3513 share, sizeof(share),
3514 path, sizeof(path),
3515 user, sizeof(user),
3516 password, sizeof(password),
3517 NULL, 0)) {
3518 errno = EINVAL;
3519 return -1;
3522 if (user[0] == (char)0) fstrcpy(user, context->user);
3524 srv = smbc_server(context, True,
3525 server, share, workgroup, user, password);
3527 if (!srv) {
3528 return -1; /* errno set by smbc_server */
3531 mode = 0;
3533 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3534 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3535 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3536 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3538 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3539 errno = smbc_errno(context, &srv->cli);
3540 return -1;
3543 return 0;
3546 static int
3547 smbc_utimes_ctx(SMBCCTX *context,
3548 const char *fname,
3549 struct timeval *tbuf)
3551 SMBCSRV *srv;
3552 fstring server;
3553 fstring share;
3554 fstring user;
3555 fstring password;
3556 fstring workgroup;
3557 pstring path;
3558 time_t a_time;
3559 time_t m_time;
3561 if (!context || !context->internal ||
3562 !context->internal->_initialized) {
3564 errno = EINVAL; /* Best I can think of ... */
3565 return -1;
3569 if (!fname) {
3571 errno = EINVAL;
3572 return -1;
3576 if (tbuf == NULL) {
3577 a_time = m_time = time(NULL);
3578 } else {
3579 a_time = tbuf[0].tv_sec;
3580 m_time = tbuf[1].tv_sec;
3583 if (DEBUGLVL(4))
3585 char *p;
3586 char atimebuf[32];
3587 char mtimebuf[32];
3589 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf) - 1);
3590 atimebuf[sizeof(atimebuf) - 1] = '\0';
3591 if ((p = strchr(atimebuf, '\n')) != NULL) {
3592 *p = '\0';
3595 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf) - 1);
3596 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3597 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3598 *p = '\0';
3601 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3602 fname, atimebuf, mtimebuf);
3605 if (smbc_parse_path(context, fname,
3606 workgroup, sizeof(workgroup),
3607 server, sizeof(server),
3608 share, sizeof(share),
3609 path, sizeof(path),
3610 user, sizeof(user),
3611 password, sizeof(password),
3612 NULL, 0)) {
3613 errno = EINVAL;
3614 return -1;
3617 if (user[0] == (char)0) fstrcpy(user, context->user);
3619 srv = smbc_server(context, True,
3620 server, share, workgroup, user, password);
3622 if (!srv) {
3623 return -1; /* errno set by smbc_server */
3626 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3627 return -1; /* errno set by smbc_setatr */
3630 return 0;
3634 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3635 However NT4 gives a "The information may have been modified by a
3636 computer running Windows NT 5.0" if denied ACEs do not appear before
3637 allowed ACEs. */
3639 static int
3640 ace_compare(SEC_ACE *ace1,
3641 SEC_ACE *ace2)
3643 if (sec_ace_equal(ace1, ace2))
3644 return 0;
3646 if (ace1->type != ace2->type)
3647 return ace2->type - ace1->type;
3649 if (sid_compare(&ace1->trustee, &ace2->trustee))
3650 return sid_compare(&ace1->trustee, &ace2->trustee);
3652 if (ace1->flags != ace2->flags)
3653 return ace1->flags - ace2->flags;
3655 if (ace1->info.mask != ace2->info.mask)
3656 return ace1->info.mask - ace2->info.mask;
3658 if (ace1->size != ace2->size)
3659 return ace1->size - ace2->size;
3661 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3665 static void
3666 sort_acl(SEC_ACL *the_acl)
3668 uint32 i;
3669 if (!the_acl) return;
3671 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]),
3672 QSORT_CAST ace_compare);
3674 for (i=1;i<the_acl->num_aces;) {
3675 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3676 int j;
3677 for (j=i; j<the_acl->num_aces-1; j++) {
3678 the_acl->ace[j] = the_acl->ace[j+1];
3680 the_acl->num_aces--;
3681 } else {
3682 i++;
3687 /* convert a SID to a string, either numeric or username/group */
3688 static void
3689 convert_sid_to_string(struct cli_state *ipc_cli,
3690 POLICY_HND *pol,
3691 fstring str,
3692 BOOL numeric,
3693 DOM_SID *sid)
3695 char **domains = NULL;
3696 char **names = NULL;
3697 uint32 *types = NULL;
3698 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3699 sid_to_string(str, sid);
3701 if (numeric) {
3702 return; /* no lookup desired */
3705 if (!pipe_hnd) {
3706 return;
3709 /* Ask LSA to convert the sid to a name */
3711 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3712 pol, 1, sid, &domains,
3713 &names, &types)) ||
3714 !domains || !domains[0] || !names || !names[0]) {
3715 return;
3718 /* Converted OK */
3720 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3721 domains[0], lp_winbind_separator(),
3722 names[0]);
3725 /* convert a string to a SID, either numeric or username/group */
3726 static BOOL
3727 convert_string_to_sid(struct cli_state *ipc_cli,
3728 POLICY_HND *pol,
3729 BOOL numeric,
3730 DOM_SID *sid,
3731 const char *str)
3733 uint32 *types = NULL;
3734 DOM_SID *sids = NULL;
3735 BOOL result = True;
3736 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3738 if (!pipe_hnd) {
3739 return False;
3742 if (numeric) {
3743 if (strncmp(str, "S-", 2) == 0) {
3744 return string_to_sid(sid, str);
3747 result = False;
3748 goto done;
3751 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3752 pol, 1, &str, NULL, &sids,
3753 &types))) {
3754 result = False;
3755 goto done;
3758 sid_copy(sid, &sids[0]);
3759 done:
3761 return result;
3765 /* parse an ACE in the same format as print_ace() */
3766 static BOOL
3767 parse_ace(struct cli_state *ipc_cli,
3768 POLICY_HND *pol,
3769 SEC_ACE *ace,
3770 BOOL numeric,
3771 char *str)
3773 char *p;
3774 const char *cp;
3775 fstring tok;
3776 unsigned int atype;
3777 unsigned int aflags;
3778 unsigned int amask;
3779 DOM_SID sid;
3780 SEC_ACCESS mask;
3781 const struct perm_value *v;
3782 struct perm_value {
3783 const char *perm;
3784 uint32 mask;
3787 /* These values discovered by inspection */
3788 static const struct perm_value special_values[] = {
3789 { "R", 0x00120089 },
3790 { "W", 0x00120116 },
3791 { "X", 0x001200a0 },
3792 { "D", 0x00010000 },
3793 { "P", 0x00040000 },
3794 { "O", 0x00080000 },
3795 { NULL, 0 },
3798 static const struct perm_value standard_values[] = {
3799 { "READ", 0x001200a9 },
3800 { "CHANGE", 0x001301bf },
3801 { "FULL", 0x001f01ff },
3802 { NULL, 0 },
3806 ZERO_STRUCTP(ace);
3807 p = strchr_m(str,':');
3808 if (!p) return False;
3809 *p = '\0';
3810 p++;
3811 /* Try to parse numeric form */
3813 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3814 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3815 goto done;
3818 /* Try to parse text form */
3820 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3821 return False;
3824 cp = p;
3825 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3826 return False;
3829 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3830 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3831 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3832 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3833 } else {
3834 return False;
3837 /* Only numeric form accepted for flags at present */
3839 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3840 sscanf(tok, "%i", &aflags))) {
3841 return False;
3844 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3845 return False;
3848 if (strncmp(tok, "0x", 2) == 0) {
3849 if (sscanf(tok, "%i", &amask) != 1) {
3850 return False;
3852 goto done;
3855 for (v = standard_values; v->perm; v++) {
3856 if (strcmp(tok, v->perm) == 0) {
3857 amask = v->mask;
3858 goto done;
3862 p = tok;
3864 while(*p) {
3865 BOOL found = False;
3867 for (v = special_values; v->perm; v++) {
3868 if (v->perm[0] == *p) {
3869 amask |= v->mask;
3870 found = True;
3874 if (!found) return False;
3875 p++;
3878 if (*p) {
3879 return False;
3882 done:
3883 mask.mask = amask;
3884 init_sec_ace(ace, &sid, atype, mask, aflags);
3885 return True;
3888 /* add an ACE to a list of ACEs in a SEC_ACL */
3889 static BOOL
3890 add_ace(SEC_ACL **the_acl,
3891 SEC_ACE *ace,
3892 TALLOC_CTX *ctx)
3894 SEC_ACL *newacl;
3895 SEC_ACE *aces;
3897 if (! *the_acl) {
3898 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3899 return True;
3902 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3903 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3904 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3905 newacl = make_sec_acl(ctx, (*the_acl)->revision,
3906 1+(*the_acl)->num_aces, aces);
3907 SAFE_FREE(aces);
3908 (*the_acl) = newacl;
3909 return True;
3913 /* parse a ascii version of a security descriptor */
3914 static SEC_DESC *
3915 sec_desc_parse(TALLOC_CTX *ctx,
3916 struct cli_state *ipc_cli,
3917 POLICY_HND *pol,
3918 BOOL numeric,
3919 char *str)
3921 const char *p = str;
3922 fstring tok;
3923 SEC_DESC *ret;
3924 size_t sd_size;
3925 DOM_SID *grp_sid=NULL;
3926 DOM_SID *owner_sid=NULL;
3927 SEC_ACL *dacl=NULL;
3928 int revision=1;
3930 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3932 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3933 revision = strtol(tok+9, NULL, 16);
3934 continue;
3937 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3938 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3939 if (!owner_sid ||
3940 !convert_string_to_sid(ipc_cli, pol,
3941 numeric,
3942 owner_sid, tok+6)) {
3943 DEBUG(5, ("Failed to parse owner sid\n"));
3944 return NULL;
3946 continue;
3949 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3950 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3951 if (!owner_sid ||
3952 !convert_string_to_sid(ipc_cli, pol,
3953 False,
3954 owner_sid, tok+7)) {
3955 DEBUG(5, ("Failed to parse owner sid\n"));
3956 return NULL;
3958 continue;
3961 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3962 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3963 if (!grp_sid ||
3964 !convert_string_to_sid(ipc_cli, pol,
3965 numeric,
3966 grp_sid, tok+6)) {
3967 DEBUG(5, ("Failed to parse group sid\n"));
3968 return NULL;
3970 continue;
3973 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3974 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3975 if (!grp_sid ||
3976 !convert_string_to_sid(ipc_cli, pol,
3977 False,
3978 grp_sid, tok+6)) {
3979 DEBUG(5, ("Failed to parse group sid\n"));
3980 return NULL;
3982 continue;
3985 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3986 SEC_ACE ace;
3987 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3988 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3989 return NULL;
3991 if(!add_ace(&dacl, &ace, ctx)) {
3992 DEBUG(5, ("Failed to add ACL %s\n", tok));
3993 return NULL;
3995 continue;
3998 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3999 SEC_ACE ace;
4000 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
4001 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4002 return NULL;
4004 if(!add_ace(&dacl, &ace, ctx)) {
4005 DEBUG(5, ("Failed to add ACL %s\n", tok));
4006 return NULL;
4008 continue;
4011 DEBUG(5, ("Failed to parse security descriptor\n"));
4012 return NULL;
4015 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
4016 owner_sid, grp_sid, NULL, dacl, &sd_size);
4018 SAFE_FREE(grp_sid);
4019 SAFE_FREE(owner_sid);
4021 return ret;
4025 /* Obtain the current dos attributes */
4026 static DOS_ATTR_DESC *
4027 dos_attr_query(SMBCCTX *context,
4028 TALLOC_CTX *ctx,
4029 const char *filename,
4030 SMBCSRV *srv)
4032 time_t m_time = 0, a_time = 0, c_time = 0;
4033 SMB_OFF_T size = 0;
4034 uint16 mode = 0;
4035 SMB_INO_T inode = 0;
4036 DOS_ATTR_DESC *ret;
4038 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
4039 if (!ret) {
4040 errno = ENOMEM;
4041 return NULL;
4044 /* Obtain the DOS attributes */
4045 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
4046 &mode, &size,
4047 &c_time, &a_time, &m_time, &inode)) {
4049 errno = smbc_errno(context, &srv->cli);
4050 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
4051 return NULL;
4055 ret->mode = mode;
4056 ret->size = size;
4057 ret->a_time = a_time;
4058 ret->c_time = c_time;
4059 ret->m_time = m_time;
4060 ret->inode = inode;
4062 return ret;
4066 /* parse a ascii version of a security descriptor */
4067 static void
4068 dos_attr_parse(SMBCCTX *context,
4069 DOS_ATTR_DESC *dad,
4070 SMBCSRV *srv,
4071 char *str)
4073 const char *p = str;
4074 fstring tok;
4076 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4078 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
4079 dad->mode = strtol(tok+5, NULL, 16);
4080 continue;
4083 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4084 dad->size = (SMB_OFF_T)atof(tok+5);
4085 continue;
4088 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
4089 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
4090 continue;
4093 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
4094 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
4095 continue;
4098 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
4099 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
4100 continue;
4103 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4104 dad->inode = (SMB_INO_T)atof(tok+6);
4105 continue;
4110 /*****************************************************
4111 Retrieve the acls for a file.
4112 *******************************************************/
4114 static int
4115 cacl_get(SMBCCTX *context,
4116 TALLOC_CTX *ctx,
4117 SMBCSRV *srv,
4118 struct cli_state *ipc_cli,
4119 POLICY_HND *pol,
4120 char *filename,
4121 char *attr_name,
4122 char *buf,
4123 int bufsize)
4125 uint32 i;
4126 int n = 0;
4127 int n_used;
4128 BOOL all;
4129 BOOL all_nt;
4130 BOOL all_nt_acls;
4131 BOOL all_dos;
4132 BOOL some_nt;
4133 BOOL some_dos;
4134 BOOL exclude_nt_revision = False;
4135 BOOL exclude_nt_owner = False;
4136 BOOL exclude_nt_group = False;
4137 BOOL exclude_nt_acl = False;
4138 BOOL exclude_dos_mode = False;
4139 BOOL exclude_dos_size = False;
4140 BOOL exclude_dos_ctime = False;
4141 BOOL exclude_dos_atime = False;
4142 BOOL exclude_dos_mtime = False;
4143 BOOL exclude_dos_inode = False;
4144 BOOL numeric = True;
4145 BOOL determine_size = (bufsize == 0);
4146 int fnum = -1;
4147 SEC_DESC *sd;
4148 fstring sidstr;
4149 fstring name_sandbox;
4150 char *name;
4151 char *pExclude;
4152 char *p;
4153 time_t m_time = 0, a_time = 0, c_time = 0;
4154 SMB_OFF_T size = 0;
4155 uint16 mode = 0;
4156 SMB_INO_T ino = 0;
4157 struct cli_state *cli = &srv->cli;
4159 /* Copy name so we can strip off exclusions (if any are specified) */
4160 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4162 /* Ensure name is null terminated */
4163 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4165 /* Play in the sandbox */
4166 name = name_sandbox;
4168 /* If there are any exclusions, point to them and mask them from name */
4169 if ((pExclude = strchr(name, '!')) != NULL)
4171 *pExclude++ = '\0';
4174 all = (StrnCaseCmp(name, "system.*", 8) == 0);
4175 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4176 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4177 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4178 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4179 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4180 numeric = (* (name + strlen(name) - 1) != '+');
4182 /* Look for exclusions from "all" requests */
4183 if (all || all_nt || all_dos) {
4185 /* Exclusions are delimited by '!' */
4186 for (;
4187 pExclude != NULL;
4188 pExclude = (p == NULL ? NULL : p + 1)) {
4190 /* Find end of this exclusion name */
4191 if ((p = strchr(pExclude, '!')) != NULL)
4193 *p = '\0';
4196 /* Which exclusion name is this? */
4197 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4198 exclude_nt_revision = True;
4200 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4201 exclude_nt_owner = True;
4203 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4204 exclude_nt_group = True;
4206 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4207 exclude_nt_acl = True;
4209 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4210 exclude_dos_mode = True;
4212 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4213 exclude_dos_size = True;
4215 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
4216 exclude_dos_ctime = True;
4218 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
4219 exclude_dos_atime = True;
4221 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
4222 exclude_dos_mtime = True;
4224 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4225 exclude_dos_inode = True;
4227 else {
4228 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4229 pExclude));
4230 errno = ENOATTR;
4231 return -1;
4236 n_used = 0;
4239 * If we are (possibly) talking to an NT or new system and some NT
4240 * attributes have been requested...
4242 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4243 /* Point to the portion after "system.nt_sec_desc." */
4244 name += 19; /* if (all) this will be invalid but unused */
4246 /* ... then obtain any NT attributes which were requested */
4247 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4249 if (fnum == -1) {
4250 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4251 filename, cli_errstr(cli)));
4252 errno = 0;
4253 return -1;
4256 sd = cli_query_secdesc(cli, fnum, ctx);
4258 if (!sd) {
4259 DEBUG(5,
4260 ("cacl_get Failed to query old descriptor\n"));
4261 errno = 0;
4262 return -1;
4265 cli_close(cli, fnum);
4267 if (! exclude_nt_revision) {
4268 if (all || all_nt) {
4269 if (determine_size) {
4270 p = talloc_asprintf(ctx,
4271 "REVISION:%d",
4272 sd->revision);
4273 if (!p) {
4274 errno = ENOMEM;
4275 return -1;
4277 n = strlen(p);
4278 } else {
4279 n = snprintf(buf, bufsize,
4280 "REVISION:%d",
4281 sd->revision);
4283 } else if (StrCaseCmp(name, "revision") == 0) {
4284 if (determine_size) {
4285 p = talloc_asprintf(ctx, "%d",
4286 sd->revision);
4287 if (!p) {
4288 errno = ENOMEM;
4289 return -1;
4291 n = strlen(p);
4292 } else {
4293 n = snprintf(buf, bufsize, "%d",
4294 sd->revision);
4298 if (!determine_size && n > bufsize) {
4299 errno = ERANGE;
4300 return -1;
4302 buf += n;
4303 n_used += n;
4304 bufsize -= n;
4307 if (! exclude_nt_owner) {
4308 /* Get owner and group sid */
4309 if (sd->owner_sid) {
4310 convert_sid_to_string(ipc_cli, pol,
4311 sidstr,
4312 numeric,
4313 sd->owner_sid);
4314 } else {
4315 fstrcpy(sidstr, "");
4318 if (all || all_nt) {
4319 if (determine_size) {
4320 p = talloc_asprintf(ctx, ",OWNER:%s",
4321 sidstr);
4322 if (!p) {
4323 errno = ENOMEM;
4324 return -1;
4326 n = strlen(p);
4327 } else {
4328 n = snprintf(buf, bufsize,
4329 ",OWNER:%s", sidstr);
4331 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4332 if (determine_size) {
4333 p = talloc_asprintf(ctx, "%s", sidstr);
4334 if (!p) {
4335 errno = ENOMEM;
4336 return -1;
4338 n = strlen(p);
4339 } else {
4340 n = snprintf(buf, bufsize, "%s",
4341 sidstr);
4345 if (!determine_size && n > bufsize) {
4346 errno = ERANGE;
4347 return -1;
4349 buf += n;
4350 n_used += n;
4351 bufsize -= n;
4354 if (! exclude_nt_group) {
4355 if (sd->grp_sid) {
4356 convert_sid_to_string(ipc_cli, pol,
4357 sidstr, numeric,
4358 sd->grp_sid);
4359 } else {
4360 fstrcpy(sidstr, "");
4363 if (all || all_nt) {
4364 if (determine_size) {
4365 p = talloc_asprintf(ctx, ",GROUP:%s",
4366 sidstr);
4367 if (!p) {
4368 errno = ENOMEM;
4369 return -1;
4371 n = strlen(p);
4372 } else {
4373 n = snprintf(buf, bufsize,
4374 ",GROUP:%s", sidstr);
4376 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4377 if (determine_size) {
4378 p = talloc_asprintf(ctx, "%s", sidstr);
4379 if (!p) {
4380 errno = ENOMEM;
4381 return -1;
4383 n = strlen(p);
4384 } else {
4385 n = snprintf(buf, bufsize,
4386 "%s", sidstr);
4390 if (!determine_size && n > bufsize) {
4391 errno = ERANGE;
4392 return -1;
4394 buf += n;
4395 n_used += n;
4396 bufsize -= n;
4399 if (! exclude_nt_acl) {
4400 /* Add aces to value buffer */
4401 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4403 SEC_ACE *ace = &sd->dacl->ace[i];
4404 convert_sid_to_string(ipc_cli, pol,
4405 sidstr, numeric,
4406 &ace->trustee);
4408 if (all || all_nt) {
4409 if (determine_size) {
4410 p = talloc_asprintf(
4411 ctx,
4412 ",ACL:"
4413 "%s:%d/%d/0x%08x",
4414 sidstr,
4415 ace->type,
4416 ace->flags,
4417 ace->info.mask);
4418 if (!p) {
4419 errno = ENOMEM;
4420 return -1;
4422 n = strlen(p);
4423 } else {
4424 n = snprintf(
4425 buf, bufsize,
4426 ",ACL:%s:%d/%d/0x%08x",
4427 sidstr,
4428 ace->type,
4429 ace->flags,
4430 ace->info.mask);
4432 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4433 StrCaseCmp(name+3, sidstr) == 0) ||
4434 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4435 StrCaseCmp(name+4, sidstr) == 0)) {
4436 if (determine_size) {
4437 p = talloc_asprintf(
4438 ctx,
4439 "%d/%d/0x%08x",
4440 ace->type,
4441 ace->flags,
4442 ace->info.mask);
4443 if (!p) {
4444 errno = ENOMEM;
4445 return -1;
4447 n = strlen(p);
4448 } else {
4449 n = snprintf(buf, bufsize,
4450 "%d/%d/0x%08x",
4451 ace->type,
4452 ace->flags,
4453 ace->info.mask);
4455 } else if (all_nt_acls) {
4456 if (determine_size) {
4457 p = talloc_asprintf(
4458 ctx,
4459 "%s%s:%d/%d/0x%08x",
4460 i ? "," : "",
4461 sidstr,
4462 ace->type,
4463 ace->flags,
4464 ace->info.mask);
4465 if (!p) {
4466 errno = ENOMEM;
4467 return -1;
4469 n = strlen(p);
4470 } else {
4471 n = snprintf(buf, bufsize,
4472 "%s%s:%d/%d/0x%08x",
4473 i ? "," : "",
4474 sidstr,
4475 ace->type,
4476 ace->flags,
4477 ace->info.mask);
4480 if (n > bufsize) {
4481 errno = ERANGE;
4482 return -1;
4484 buf += n;
4485 n_used += n;
4486 bufsize -= n;
4490 /* Restore name pointer to its original value */
4491 name -= 19;
4494 if (all || some_dos) {
4495 /* Point to the portion after "system.dos_attr." */
4496 name += 16; /* if (all) this will be invalid but unused */
4498 /* Obtain the DOS attributes */
4499 if (!smbc_getatr(context, srv, filename, &mode, &size,
4500 &c_time, &a_time, &m_time, &ino)) {
4502 errno = smbc_errno(context, &srv->cli);
4503 return -1;
4507 if (! exclude_dos_mode) {
4508 if (all || all_dos) {
4509 if (determine_size) {
4510 p = talloc_asprintf(ctx,
4511 "%sMODE:0x%x",
4512 (ipc_cli &&
4513 (all || some_nt)
4514 ? ","
4515 : ""),
4516 mode);
4517 if (!p) {
4518 errno = ENOMEM;
4519 return -1;
4521 n = strlen(p);
4522 } else {
4523 n = snprintf(buf, bufsize,
4524 "%sMODE:0x%x",
4525 (ipc_cli &&
4526 (all || some_nt)
4527 ? ","
4528 : ""),
4529 mode);
4531 } else if (StrCaseCmp(name, "mode") == 0) {
4532 if (determine_size) {
4533 p = talloc_asprintf(ctx, "0x%x", mode);
4534 if (!p) {
4535 errno = ENOMEM;
4536 return -1;
4538 n = strlen(p);
4539 } else {
4540 n = snprintf(buf, bufsize,
4541 "0x%x", mode);
4545 if (!determine_size && n > bufsize) {
4546 errno = ERANGE;
4547 return -1;
4549 buf += n;
4550 n_used += n;
4551 bufsize -= n;
4554 if (! exclude_dos_size) {
4555 if (all || all_dos) {
4556 if (determine_size) {
4557 p = talloc_asprintf(
4558 ctx,
4559 ",SIZE:%.0f",
4560 (double)size);
4561 if (!p) {
4562 errno = ENOMEM;
4563 return -1;
4565 n = strlen(p);
4566 } else {
4567 n = snprintf(buf, bufsize,
4568 ",SIZE:%.0f",
4569 (double)size);
4571 } else if (StrCaseCmp(name, "size") == 0) {
4572 if (determine_size) {
4573 p = talloc_asprintf(
4574 ctx,
4575 "%.0f",
4576 (double)size);
4577 if (!p) {
4578 errno = ENOMEM;
4579 return -1;
4581 n = strlen(p);
4582 } else {
4583 n = snprintf(buf, bufsize,
4584 "%.0f",
4585 (double)size);
4589 if (!determine_size && n > bufsize) {
4590 errno = ERANGE;
4591 return -1;
4593 buf += n;
4594 n_used += n;
4595 bufsize -= n;
4598 if (! exclude_dos_ctime) {
4599 if (all || all_dos) {
4600 if (determine_size) {
4601 p = talloc_asprintf(ctx,
4602 ",C_TIME:%lu",
4603 c_time);
4604 if (!p) {
4605 errno = ENOMEM;
4606 return -1;
4608 n = strlen(p);
4609 } else {
4610 n = snprintf(buf, bufsize,
4611 ",C_TIME:%lu", c_time);
4613 } else if (StrCaseCmp(name, "c_time") == 0) {
4614 if (determine_size) {
4615 p = talloc_asprintf(ctx, "%lu", c_time);
4616 if (!p) {
4617 errno = ENOMEM;
4618 return -1;
4620 n = strlen(p);
4621 } else {
4622 n = snprintf(buf, bufsize,
4623 "%lu", c_time);
4627 if (!determine_size && n > bufsize) {
4628 errno = ERANGE;
4629 return -1;
4631 buf += n;
4632 n_used += n;
4633 bufsize -= n;
4636 if (! exclude_dos_atime) {
4637 if (all || all_dos) {
4638 if (determine_size) {
4639 p = talloc_asprintf(ctx,
4640 ",A_TIME:%lu",
4641 a_time);
4642 if (!p) {
4643 errno = ENOMEM;
4644 return -1;
4646 n = strlen(p);
4647 } else {
4648 n = snprintf(buf, bufsize,
4649 ",A_TIME:%lu", a_time);
4651 } else if (StrCaseCmp(name, "a_time") == 0) {
4652 if (determine_size) {
4653 p = talloc_asprintf(ctx, "%lu", a_time);
4654 if (!p) {
4655 errno = ENOMEM;
4656 return -1;
4658 n = strlen(p);
4659 } else {
4660 n = snprintf(buf, bufsize,
4661 "%lu", a_time);
4665 if (!determine_size && n > bufsize) {
4666 errno = ERANGE;
4667 return -1;
4669 buf += n;
4670 n_used += n;
4671 bufsize -= n;
4674 if (! exclude_dos_mtime) {
4675 if (all || all_dos) {
4676 if (determine_size) {
4677 p = talloc_asprintf(ctx,
4678 ",M_TIME:%lu",
4679 m_time);
4680 if (!p) {
4681 errno = ENOMEM;
4682 return -1;
4684 n = strlen(p);
4685 } else {
4686 n = snprintf(buf, bufsize,
4687 ",M_TIME:%lu", m_time);
4689 } else if (StrCaseCmp(name, "m_time") == 0) {
4690 if (determine_size) {
4691 p = talloc_asprintf(ctx, "%lu", m_time);
4692 if (!p) {
4693 errno = ENOMEM;
4694 return -1;
4696 n = strlen(p);
4697 } else {
4698 n = snprintf(buf, bufsize,
4699 "%lu", m_time);
4703 if (!determine_size && n > bufsize) {
4704 errno = ERANGE;
4705 return -1;
4707 buf += n;
4708 n_used += n;
4709 bufsize -= n;
4712 if (! exclude_dos_inode) {
4713 if (all || all_dos) {
4714 if (determine_size) {
4715 p = talloc_asprintf(
4716 ctx,
4717 ",INODE:%.0f",
4718 (double)ino);
4719 if (!p) {
4720 errno = ENOMEM;
4721 return -1;
4723 n = strlen(p);
4724 } else {
4725 n = snprintf(buf, bufsize,
4726 ",INODE:%.0f",
4727 (double) ino);
4729 } else if (StrCaseCmp(name, "inode") == 0) {
4730 if (determine_size) {
4731 p = talloc_asprintf(
4732 ctx,
4733 "%.0f",
4734 (double) ino);
4735 if (!p) {
4736 errno = ENOMEM;
4737 return -1;
4739 n = strlen(p);
4740 } else {
4741 n = snprintf(buf, bufsize,
4742 "%.0f",
4743 (double) ino);
4747 if (!determine_size && n > bufsize) {
4748 errno = ERANGE;
4749 return -1;
4751 buf += n;
4752 n_used += n;
4753 bufsize -= n;
4756 /* Restore name pointer to its original value */
4757 name -= 16;
4760 if (n_used == 0) {
4761 errno = ENOATTR;
4762 return -1;
4765 return n_used;
4769 /*****************************************************
4770 set the ACLs on a file given an ascii description
4771 *******************************************************/
4772 static int
4773 cacl_set(TALLOC_CTX *ctx,
4774 struct cli_state *cli,
4775 struct cli_state *ipc_cli,
4776 POLICY_HND *pol,
4777 const char *filename,
4778 const char *the_acl,
4779 int mode,
4780 int flags)
4782 int fnum;
4783 int err = 0;
4784 SEC_DESC *sd = NULL, *old;
4785 SEC_ACL *dacl = NULL;
4786 DOM_SID *owner_sid = NULL;
4787 DOM_SID *grp_sid = NULL;
4788 uint32 i, j;
4789 size_t sd_size;
4790 int ret = 0;
4791 char *p;
4792 BOOL numeric = True;
4794 /* the_acl will be null for REMOVE_ALL operations */
4795 if (the_acl) {
4796 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4797 p > the_acl &&
4798 p[-1] != '+');
4800 /* if this is to set the entire ACL... */
4801 if (*the_acl == '*') {
4802 /* ... then increment past the first colon */
4803 the_acl = p + 1;
4806 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4807 CONST_DISCARD(char *, the_acl));
4809 if (!sd) {
4810 errno = EINVAL;
4811 return -1;
4815 /* The desired access below is the only one I could find that works
4816 with NT4, W2KP and Samba */
4818 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4820 if (fnum == -1) {
4821 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4822 filename, cli_errstr(cli)));
4823 errno = 0;
4824 return -1;
4827 old = cli_query_secdesc(cli, fnum, ctx);
4829 if (!old) {
4830 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4831 errno = 0;
4832 return -1;
4835 cli_close(cli, fnum);
4837 switch (mode) {
4838 case SMBC_XATTR_MODE_REMOVE_ALL:
4839 old->dacl->num_aces = 0;
4840 SAFE_FREE(old->dacl->ace);
4841 SAFE_FREE(old->dacl);
4842 old->off_dacl = 0;
4843 dacl = old->dacl;
4844 break;
4846 case SMBC_XATTR_MODE_REMOVE:
4847 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4848 BOOL found = False;
4850 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4851 if (sec_ace_equal(&sd->dacl->ace[i],
4852 &old->dacl->ace[j])) {
4853 uint32 k;
4854 for (k=j; k<old->dacl->num_aces-1;k++) {
4855 old->dacl->ace[k] =
4856 old->dacl->ace[k+1];
4858 old->dacl->num_aces--;
4859 if (old->dacl->num_aces == 0) {
4860 SAFE_FREE(old->dacl->ace);
4861 SAFE_FREE(old->dacl);
4862 old->off_dacl = 0;
4864 found = True;
4865 dacl = old->dacl;
4866 break;
4870 if (!found) {
4871 err = ENOATTR;
4872 ret = -1;
4873 goto failed;
4876 break;
4878 case SMBC_XATTR_MODE_ADD:
4879 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4880 BOOL found = False;
4882 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4883 if (sid_equal(&sd->dacl->ace[i].trustee,
4884 &old->dacl->ace[j].trustee)) {
4885 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4886 err = EEXIST;
4887 ret = -1;
4888 goto failed;
4890 old->dacl->ace[j] = sd->dacl->ace[i];
4891 ret = -1;
4892 found = True;
4896 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4897 err = ENOATTR;
4898 ret = -1;
4899 goto failed;
4902 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4903 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4906 dacl = old->dacl;
4907 break;
4909 case SMBC_XATTR_MODE_SET:
4910 old = sd;
4911 owner_sid = old->owner_sid;
4912 grp_sid = old->grp_sid;
4913 dacl = old->dacl;
4914 break;
4916 case SMBC_XATTR_MODE_CHOWN:
4917 owner_sid = sd->owner_sid;
4918 break;
4920 case SMBC_XATTR_MODE_CHGRP:
4921 grp_sid = sd->grp_sid;
4922 break;
4925 /* Denied ACE entries must come before allowed ones */
4926 sort_acl(old->dacl);
4928 /* Create new security descriptor and set it */
4929 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4930 owner_sid, grp_sid, NULL, dacl, &sd_size);
4932 fnum = cli_nt_create(cli, filename,
4933 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4935 if (fnum == -1) {
4936 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4937 filename, cli_errstr(cli)));
4938 errno = 0;
4939 return -1;
4942 if (!cli_set_secdesc(cli, fnum, sd)) {
4943 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4944 ret = -1;
4947 /* Clean up */
4949 failed:
4950 cli_close(cli, fnum);
4952 if (err != 0) {
4953 errno = err;
4956 return ret;
4960 static int
4961 smbc_setxattr_ctx(SMBCCTX *context,
4962 const char *fname,
4963 const char *name,
4964 const void *value,
4965 size_t size,
4966 int flags)
4968 int ret;
4969 int ret2;
4970 SMBCSRV *srv;
4971 SMBCSRV *ipc_srv;
4972 fstring server;
4973 fstring share;
4974 fstring user;
4975 fstring password;
4976 fstring workgroup;
4977 pstring path;
4978 TALLOC_CTX *ctx;
4979 POLICY_HND pol;
4980 DOS_ATTR_DESC *dad;
4982 if (!context || !context->internal ||
4983 !context->internal->_initialized) {
4985 errno = EINVAL; /* Best I can think of ... */
4986 return -1;
4990 if (!fname) {
4992 errno = EINVAL;
4993 return -1;
4997 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
4998 fname, name, (int) size, (const char*)value));
5000 if (smbc_parse_path(context, fname,
5001 workgroup, sizeof(workgroup),
5002 server, sizeof(server),
5003 share, sizeof(share),
5004 path, sizeof(path),
5005 user, sizeof(user),
5006 password, sizeof(password),
5007 NULL, 0)) {
5008 errno = EINVAL;
5009 return -1;
5012 if (user[0] == (char)0) fstrcpy(user, context->user);
5014 srv = smbc_server(context, True,
5015 server, share, workgroup, user, password);
5016 if (!srv) {
5017 return -1; /* errno set by smbc_server */
5020 if (! srv->no_nt_session) {
5021 ipc_srv = smbc_attr_server(context, server, share,
5022 workgroup, user, password,
5023 &pol);
5024 srv->no_nt_session = True;
5025 } else {
5026 ipc_srv = NULL;
5029 ctx = talloc_init("smbc_setxattr");
5030 if (!ctx) {
5031 errno = ENOMEM;
5032 return -1;
5036 * Are they asking to set the entire set of known attributes?
5038 if (StrCaseCmp(name, "system.*") == 0 ||
5039 StrCaseCmp(name, "system.*+") == 0) {
5040 /* Yup. */
5041 char *namevalue =
5042 talloc_asprintf(ctx, "%s:%s",
5043 name+7, (const char *) value);
5044 if (! namevalue) {
5045 errno = ENOMEM;
5046 ret = -1;
5047 return -1;
5050 if (ipc_srv) {
5051 ret = cacl_set(ctx, &srv->cli,
5052 &ipc_srv->cli, &pol, path,
5053 namevalue,
5054 (*namevalue == '*'
5055 ? SMBC_XATTR_MODE_SET
5056 : SMBC_XATTR_MODE_ADD),
5057 flags);
5058 } else {
5059 ret = 0;
5062 /* get a DOS Attribute Descriptor with current attributes */
5063 dad = dos_attr_query(context, ctx, path, srv);
5064 if (dad) {
5065 /* Overwrite old with new, using what was provided */
5066 dos_attr_parse(context, dad, srv, namevalue);
5068 /* Set the new DOS attributes */
5069 if (! smbc_setatr(context, srv, path,
5070 dad->c_time,
5071 dad->a_time,
5072 dad->m_time,
5073 dad->mode)) {
5075 /* cause failure if NT failed too */
5076 dad = NULL;
5080 /* we only fail if both NT and DOS sets failed */
5081 if (ret < 0 && ! dad) {
5082 ret = -1; /* in case dad was null */
5084 else {
5085 ret = 0;
5088 talloc_destroy(ctx);
5089 return ret;
5093 * Are they asking to set an access control element or to set
5094 * the entire access control list?
5096 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5097 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5098 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5099 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5100 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5102 /* Yup. */
5103 char *namevalue =
5104 talloc_asprintf(ctx, "%s:%s",
5105 name+19, (const char *) value);
5107 if (! ipc_srv) {
5108 ret = -1; /* errno set by smbc_server() */
5110 else if (! namevalue) {
5111 errno = ENOMEM;
5112 ret = -1;
5113 } else {
5114 ret = cacl_set(ctx, &srv->cli,
5115 &ipc_srv->cli, &pol, path,
5116 namevalue,
5117 (*namevalue == '*'
5118 ? SMBC_XATTR_MODE_SET
5119 : SMBC_XATTR_MODE_ADD),
5120 flags);
5122 talloc_destroy(ctx);
5123 return ret;
5127 * Are they asking to set the owner?
5129 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5130 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5132 /* Yup. */
5133 char *namevalue =
5134 talloc_asprintf(ctx, "%s:%s",
5135 name+19, (const char *) value);
5137 if (! ipc_srv) {
5139 ret = -1; /* errno set by smbc_server() */
5141 else if (! namevalue) {
5142 errno = ENOMEM;
5143 ret = -1;
5144 } else {
5145 ret = cacl_set(ctx, &srv->cli,
5146 &ipc_srv->cli, &pol, path,
5147 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5149 talloc_destroy(ctx);
5150 return ret;
5154 * Are they asking to set the group?
5156 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5157 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5159 /* Yup. */
5160 char *namevalue =
5161 talloc_asprintf(ctx, "%s:%s",
5162 name+19, (const char *) value);
5164 if (! ipc_srv) {
5165 /* errno set by smbc_server() */
5166 ret = -1;
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 a DOS attribute?
5183 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5184 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5185 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5186 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5187 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
5189 /* get a DOS Attribute Descriptor with current attributes */
5190 dad = dos_attr_query(context, ctx, path, srv);
5191 if (dad) {
5192 char *namevalue =
5193 talloc_asprintf(ctx, "%s:%s",
5194 name+16, (const char *) value);
5195 if (! namevalue) {
5196 errno = ENOMEM;
5197 ret = -1;
5198 } else {
5199 /* Overwrite old with provided new params */
5200 dos_attr_parse(context, dad, srv, namevalue);
5202 /* Set the new DOS attributes */
5203 ret2 = smbc_setatr(context, srv, path,
5204 dad->c_time,
5205 dad->a_time,
5206 dad->m_time,
5207 dad->mode);
5209 /* ret2 has True (success) / False (failure) */
5210 if (ret2) {
5211 ret = 0;
5212 } else {
5213 ret = -1;
5216 } else {
5217 ret = -1;
5220 talloc_destroy(ctx);
5221 return ret;
5224 /* Unsupported attribute name */
5225 talloc_destroy(ctx);
5226 errno = EINVAL;
5227 return -1;
5230 static int
5231 smbc_getxattr_ctx(SMBCCTX *context,
5232 const char *fname,
5233 const char *name,
5234 const void *value,
5235 size_t size)
5237 int ret;
5238 SMBCSRV *srv;
5239 SMBCSRV *ipc_srv;
5240 fstring server;
5241 fstring share;
5242 fstring user;
5243 fstring password;
5244 fstring workgroup;
5245 pstring path;
5246 TALLOC_CTX *ctx;
5247 POLICY_HND pol;
5250 if (!context || !context->internal ||
5251 !context->internal->_initialized) {
5253 errno = EINVAL; /* Best I can think of ... */
5254 return -1;
5258 if (!fname) {
5260 errno = EINVAL;
5261 return -1;
5265 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5267 if (smbc_parse_path(context, fname,
5268 workgroup, sizeof(workgroup),
5269 server, sizeof(server),
5270 share, sizeof(share),
5271 path, sizeof(path),
5272 user, sizeof(user),
5273 password, sizeof(password),
5274 NULL, 0)) {
5275 errno = EINVAL;
5276 return -1;
5279 if (user[0] == (char)0) fstrcpy(user, context->user);
5281 srv = smbc_server(context, True,
5282 server, share, workgroup, user, password);
5283 if (!srv) {
5284 return -1; /* errno set by smbc_server */
5287 if (! srv->no_nt_session) {
5288 ipc_srv = smbc_attr_server(context, server, share,
5289 workgroup, user, password,
5290 &pol);
5291 if (! ipc_srv) {
5292 srv->no_nt_session = True;
5294 } else {
5295 ipc_srv = NULL;
5298 ctx = talloc_init("smbc:getxattr");
5299 if (!ctx) {
5300 errno = ENOMEM;
5301 return -1;
5304 /* Are they requesting a supported attribute? */
5305 if (StrCaseCmp(name, "system.*") == 0 ||
5306 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5307 StrCaseCmp(name, "system.*+") == 0 ||
5308 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5309 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5310 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5311 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5312 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5313 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5314 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5315 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5316 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5317 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5318 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5319 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5320 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5321 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5322 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5323 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5324 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5325 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5326 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
5327 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5329 /* Yup. */
5330 ret = cacl_get(context, ctx, srv,
5331 ipc_srv == NULL ? NULL : &ipc_srv->cli,
5332 &pol, path,
5333 CONST_DISCARD(char *, name),
5334 CONST_DISCARD(char *, value), size);
5335 if (ret < 0 && errno == 0) {
5336 errno = smbc_errno(context, &srv->cli);
5338 talloc_destroy(ctx);
5339 return ret;
5342 /* Unsupported attribute name */
5343 talloc_destroy(ctx);
5344 errno = EINVAL;
5345 return -1;
5349 static int
5350 smbc_removexattr_ctx(SMBCCTX *context,
5351 const char *fname,
5352 const char *name)
5354 int ret;
5355 SMBCSRV *srv;
5356 SMBCSRV *ipc_srv;
5357 fstring server;
5358 fstring share;
5359 fstring user;
5360 fstring password;
5361 fstring workgroup;
5362 pstring path;
5363 TALLOC_CTX *ctx;
5364 POLICY_HND pol;
5366 if (!context || !context->internal ||
5367 !context->internal->_initialized) {
5369 errno = EINVAL; /* Best I can think of ... */
5370 return -1;
5374 if (!fname) {
5376 errno = EINVAL;
5377 return -1;
5381 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5383 if (smbc_parse_path(context, fname,
5384 workgroup, sizeof(workgroup),
5385 server, sizeof(server),
5386 share, sizeof(share),
5387 path, sizeof(path),
5388 user, sizeof(user),
5389 password, sizeof(password),
5390 NULL, 0)) {
5391 errno = EINVAL;
5392 return -1;
5395 if (user[0] == (char)0) fstrcpy(user, context->user);
5397 srv = smbc_server(context, True,
5398 server, share, workgroup, user, password);
5399 if (!srv) {
5400 return -1; /* errno set by smbc_server */
5403 if (! srv->no_nt_session) {
5404 ipc_srv = smbc_attr_server(context, server, share,
5405 workgroup, user, password,
5406 &pol);
5407 srv->no_nt_session = True;
5408 } else {
5409 ipc_srv = NULL;
5412 if (! ipc_srv) {
5413 return -1; /* errno set by smbc_attr_server */
5416 ctx = talloc_init("smbc_removexattr");
5417 if (!ctx) {
5418 errno = ENOMEM;
5419 return -1;
5422 /* Are they asking to set the entire ACL? */
5423 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5424 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5426 /* Yup. */
5427 ret = cacl_set(ctx, &srv->cli,
5428 &ipc_srv->cli, &pol, path,
5429 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5430 talloc_destroy(ctx);
5431 return ret;
5435 * Are they asking to remove one or more spceific security descriptor
5436 * attributes?
5438 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5439 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5440 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5441 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5442 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5443 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5444 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5446 /* Yup. */
5447 ret = cacl_set(ctx, &srv->cli,
5448 &ipc_srv->cli, &pol, path,
5449 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5450 talloc_destroy(ctx);
5451 return ret;
5454 /* Unsupported attribute name */
5455 talloc_destroy(ctx);
5456 errno = EINVAL;
5457 return -1;
5460 static int
5461 smbc_listxattr_ctx(SMBCCTX *context,
5462 const char *fname,
5463 char *list,
5464 size_t size)
5467 * This isn't quite what listxattr() is supposed to do. This returns
5468 * the complete set of attribute names, always, rather than only those
5469 * attribute names which actually exist for a file. Hmmm...
5471 const char supported[] =
5472 "system.*\0"
5473 "system.*+\0"
5474 "system.nt_sec_desc.revision\0"
5475 "system.nt_sec_desc.owner\0"
5476 "system.nt_sec_desc.owner+\0"
5477 "system.nt_sec_desc.group\0"
5478 "system.nt_sec_desc.group+\0"
5479 "system.nt_sec_desc.acl.*\0"
5480 "system.nt_sec_desc.acl\0"
5481 "system.nt_sec_desc.acl+\0"
5482 "system.nt_sec_desc.*\0"
5483 "system.nt_sec_desc.*+\0"
5484 "system.dos_attr.*\0"
5485 "system.dos_attr.mode\0"
5486 "system.dos_attr.c_time\0"
5487 "system.dos_attr.a_time\0"
5488 "system.dos_attr.m_time\0"
5491 if (size == 0) {
5492 return sizeof(supported);
5495 if (sizeof(supported) > size) {
5496 errno = ERANGE;
5497 return -1;
5500 /* this can't be strcpy() because there are embedded null characters */
5501 memcpy(list, supported, sizeof(supported));
5502 return sizeof(supported);
5507 * Open a print file to be written to by other calls
5510 static SMBCFILE *
5511 smbc_open_print_job_ctx(SMBCCTX *context,
5512 const char *fname)
5514 fstring server;
5515 fstring share;
5516 fstring user;
5517 fstring password;
5518 pstring path;
5520 if (!context || !context->internal ||
5521 !context->internal->_initialized) {
5523 errno = EINVAL;
5524 return NULL;
5528 if (!fname) {
5530 errno = EINVAL;
5531 return NULL;
5535 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5537 if (smbc_parse_path(context, fname,
5538 NULL, 0,
5539 server, sizeof(server),
5540 share, sizeof(share),
5541 path, sizeof(path),
5542 user, sizeof(user),
5543 password, sizeof(password),
5544 NULL, 0)) {
5545 errno = EINVAL;
5546 return NULL;
5549 /* What if the path is empty, or the file exists? */
5551 return context->open(context, fname, O_WRONLY, 666);
5556 * Routine to print a file on a remote server ...
5558 * We open the file, which we assume to be on a remote server, and then
5559 * copy it to a print file on the share specified by printq.
5562 static int
5563 smbc_print_file_ctx(SMBCCTX *c_file,
5564 const char *fname,
5565 SMBCCTX *c_print,
5566 const char *printq)
5568 SMBCFILE *fid1;
5569 SMBCFILE *fid2;
5570 int bytes;
5571 int saverr;
5572 int tot_bytes = 0;
5573 char buf[4096];
5575 if (!c_file || !c_file->internal->_initialized || !c_print ||
5576 !c_print->internal->_initialized) {
5578 errno = EINVAL;
5579 return -1;
5583 if (!fname && !printq) {
5585 errno = EINVAL;
5586 return -1;
5590 /* Try to open the file for reading ... */
5592 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5594 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5595 return -1; /* smbc_open sets errno */
5599 /* Now, try to open the printer file for writing */
5601 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5603 saverr = errno; /* Save errno */
5604 c_file->close_fn(c_file, fid1);
5605 errno = saverr;
5606 return -1;
5610 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5612 tot_bytes += bytes;
5614 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5616 saverr = errno;
5617 c_file->close_fn(c_file, fid1);
5618 c_print->close_fn(c_print, fid2);
5619 errno = saverr;
5625 saverr = errno;
5627 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5628 c_print->close_fn(c_print, fid2);
5630 if (bytes < 0) {
5632 errno = saverr;
5633 return -1;
5637 return tot_bytes;
5642 * Routine to list print jobs on a printer share ...
5645 static int
5646 smbc_list_print_jobs_ctx(SMBCCTX *context,
5647 const char *fname,
5648 smbc_list_print_job_fn fn)
5650 SMBCSRV *srv;
5651 fstring server;
5652 fstring share;
5653 fstring user;
5654 fstring password;
5655 fstring workgroup;
5656 pstring path;
5658 if (!context || !context->internal ||
5659 !context->internal->_initialized) {
5661 errno = EINVAL;
5662 return -1;
5666 if (!fname) {
5668 errno = EINVAL;
5669 return -1;
5673 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5675 if (smbc_parse_path(context, fname,
5676 workgroup, sizeof(workgroup),
5677 server, sizeof(server),
5678 share, sizeof(share),
5679 path, sizeof(path),
5680 user, sizeof(user),
5681 password, sizeof(password),
5682 NULL, 0)) {
5683 errno = EINVAL;
5684 return -1;
5687 if (user[0] == (char)0) fstrcpy(user, context->user);
5689 srv = smbc_server(context, True,
5690 server, share, workgroup, user, password);
5692 if (!srv) {
5694 return -1; /* errno set by smbc_server */
5698 if (cli_print_queue(&srv->cli,
5699 (void (*)(struct print_job_info *))fn) < 0) {
5701 errno = smbc_errno(context, &srv->cli);
5702 return -1;
5706 return 0;
5711 * Delete a print job from a remote printer share
5714 static int
5715 smbc_unlink_print_job_ctx(SMBCCTX *context,
5716 const char *fname,
5717 int id)
5719 SMBCSRV *srv;
5720 fstring server;
5721 fstring share;
5722 fstring user;
5723 fstring password;
5724 fstring workgroup;
5725 pstring path;
5726 int err;
5728 if (!context || !context->internal ||
5729 !context->internal->_initialized) {
5731 errno = EINVAL;
5732 return -1;
5736 if (!fname) {
5738 errno = EINVAL;
5739 return -1;
5743 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5745 if (smbc_parse_path(context, fname,
5746 workgroup, sizeof(workgroup),
5747 server, sizeof(server),
5748 share, sizeof(share),
5749 path, sizeof(path),
5750 user, sizeof(user),
5751 password, sizeof(password),
5752 NULL, 0)) {
5753 errno = EINVAL;
5754 return -1;
5757 if (user[0] == (char)0) fstrcpy(user, context->user);
5759 srv = smbc_server(context, True,
5760 server, share, workgroup, user, password);
5762 if (!srv) {
5764 return -1; /* errno set by smbc_server */
5768 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5770 if (err < 0)
5771 errno = smbc_errno(context, &srv->cli);
5772 else if (err == ERRnosuchprintjob)
5773 errno = EINVAL;
5774 return -1;
5778 return 0;
5783 * Get a new empty handle to fill in with your own info
5785 SMBCCTX *
5786 smbc_new_context(void)
5788 SMBCCTX *context;
5790 context = SMB_MALLOC_P(SMBCCTX);
5791 if (!context) {
5792 errno = ENOMEM;
5793 return NULL;
5796 ZERO_STRUCTP(context);
5798 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5799 if (!context->internal) {
5800 SAFE_FREE(context);
5801 errno = ENOMEM;
5802 return NULL;
5805 ZERO_STRUCTP(context->internal);
5808 /* ADD REASONABLE DEFAULTS */
5809 context->debug = 0;
5810 context->timeout = 20000; /* 20 seconds */
5812 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5813 context->options.urlencode_readdir_entries = False;/* backward compat */
5814 context->options.one_share_per_server = False;/* backward compat */
5816 context->open = smbc_open_ctx;
5817 context->creat = smbc_creat_ctx;
5818 context->read = smbc_read_ctx;
5819 context->write = smbc_write_ctx;
5820 context->close_fn = smbc_close_ctx;
5821 context->unlink = smbc_unlink_ctx;
5822 context->rename = smbc_rename_ctx;
5823 context->lseek = smbc_lseek_ctx;
5824 context->stat = smbc_stat_ctx;
5825 context->fstat = smbc_fstat_ctx;
5826 context->opendir = smbc_opendir_ctx;
5827 context->closedir = smbc_closedir_ctx;
5828 context->readdir = smbc_readdir_ctx;
5829 context->getdents = smbc_getdents_ctx;
5830 context->mkdir = smbc_mkdir_ctx;
5831 context->rmdir = smbc_rmdir_ctx;
5832 context->telldir = smbc_telldir_ctx;
5833 context->lseekdir = smbc_lseekdir_ctx;
5834 context->fstatdir = smbc_fstatdir_ctx;
5835 context->chmod = smbc_chmod_ctx;
5836 context->utimes = smbc_utimes_ctx;
5837 context->setxattr = smbc_setxattr_ctx;
5838 context->getxattr = smbc_getxattr_ctx;
5839 context->removexattr = smbc_removexattr_ctx;
5840 context->listxattr = smbc_listxattr_ctx;
5841 context->open_print_job = smbc_open_print_job_ctx;
5842 context->print_file = smbc_print_file_ctx;
5843 context->list_print_jobs = smbc_list_print_jobs_ctx;
5844 context->unlink_print_job = smbc_unlink_print_job_ctx;
5846 context->callbacks.check_server_fn = smbc_check_server;
5847 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5849 smbc_default_cache_functions(context);
5851 return context;
5855 * Free a context
5857 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5858 * and thus you'll be leaking memory if not handled properly.
5862 smbc_free_context(SMBCCTX *context,
5863 int shutdown_ctx)
5865 if (!context) {
5866 errno = EBADF;
5867 return 1;
5870 if (shutdown_ctx) {
5871 SMBCFILE * f;
5872 DEBUG(1,("Performing aggressive shutdown.\n"));
5874 f = context->internal->_files;
5875 while (f) {
5876 context->close_fn(context, f);
5877 f = f->next;
5879 context->internal->_files = NULL;
5881 /* First try to remove the servers the nice way. */
5882 if (context->callbacks.purge_cached_fn(context)) {
5883 SMBCSRV * s;
5884 SMBCSRV * next;
5885 DEBUG(1, ("Could not purge all servers, "
5886 "Nice way shutdown failed.\n"));
5887 s = context->internal->_servers;
5888 while (s) {
5889 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
5890 s, s->cli.fd));
5891 cli_shutdown(&s->cli);
5892 context->callbacks.remove_cached_srv_fn(context,
5894 next = s->next;
5895 DLIST_REMOVE(context->internal->_servers, s);
5896 SAFE_FREE(s);
5897 s = next;
5899 context->internal->_servers = NULL;
5902 else {
5903 /* This is the polite way */
5904 if (context->callbacks.purge_cached_fn(context)) {
5905 DEBUG(1, ("Could not purge all servers, "
5906 "free_context failed.\n"));
5907 errno = EBUSY;
5908 return 1;
5910 if (context->internal->_servers) {
5911 DEBUG(1, ("Active servers in context, "
5912 "free_context failed.\n"));
5913 errno = EBUSY;
5914 return 1;
5916 if (context->internal->_files) {
5917 DEBUG(1, ("Active files in context, "
5918 "free_context failed.\n"));
5919 errno = EBUSY;
5920 return 1;
5924 /* Things we have to clean up */
5925 SAFE_FREE(context->workgroup);
5926 SAFE_FREE(context->netbios_name);
5927 SAFE_FREE(context->user);
5929 DEBUG(3, ("Context %p succesfully freed\n", context));
5930 SAFE_FREE(context->internal);
5931 SAFE_FREE(context);
5932 return 0;
5937 * Each time the context structure is changed, we have binary backward
5938 * compatibility issues. Instead of modifying the public portions of the
5939 * context structure to add new options, instead, we put them in the internal
5940 * portion of the context structure and provide a set function for these new
5941 * options.
5943 void
5944 smbc_option_set(SMBCCTX *context,
5945 char *option_name,
5946 void *option_value)
5948 if (strcmp(option_name, "debug_stderr") == 0) {
5950 * Log to standard error instead of standard output.
5952 context->internal->_debug_stderr = True;
5958 * Initialise the library etc
5960 * We accept a struct containing handle information.
5961 * valid values for info->debug from 0 to 100,
5962 * and insist that info->fn must be non-null.
5964 SMBCCTX *
5965 smbc_init_context(SMBCCTX *context)
5967 pstring conf;
5968 int pid;
5969 char *user = NULL;
5970 char *home = NULL;
5972 if (!context || !context->internal) {
5973 errno = EBADF;
5974 return NULL;
5977 /* Do not initialise the same client twice */
5978 if (context->internal->_initialized) {
5979 return 0;
5982 if (!context->callbacks.auth_fn ||
5983 context->debug < 0 ||
5984 context->debug > 100) {
5986 errno = EINVAL;
5987 return NULL;
5991 if (!smbc_initialized) {
5993 * Do some library-wide intializations the first time we get
5994 * called
5996 BOOL conf_loaded = False;
5998 /* Set this to what the user wants */
5999 DEBUGLEVEL = context->debug;
6001 load_case_tables();
6003 setup_logging("libsmbclient", True);
6004 if (context->internal->_debug_stderr) {
6005 dbf = x_stderr;
6006 x_setbuf(x_stderr, NULL);
6009 /* Here we would open the smb.conf file if needed ... */
6011 in_client = True; /* FIXME, make a param */
6013 home = getenv("HOME");
6014 if (home) {
6015 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
6016 if (lp_load(conf, True, False, False, True)) {
6017 conf_loaded = True;
6018 } else {
6019 DEBUG(5, ("Could not load config file: %s\n",
6020 conf));
6024 if (!conf_loaded) {
6026 * Well, if that failed, try the dyn_CONFIGFILE
6027 * Which points to the standard locn, and if that
6028 * fails, silently ignore it and use the internal
6029 * defaults ...
6032 if (!lp_load(dyn_CONFIGFILE, True, False, False, False)) {
6033 DEBUG(5, ("Could not load config file: %s\n",
6034 dyn_CONFIGFILE));
6035 } else if (home) {
6037 * We loaded the global config file. Now lets
6038 * load user-specific modifications to the
6039 * global config.
6041 slprintf(conf, sizeof(conf),
6042 "%s/.smb/smb.conf.append", home);
6043 if (!lp_load(conf, True, False, False, False)) {
6044 DEBUG(10,
6045 ("Could not append config file: "
6046 "%s\n",
6047 conf));
6052 load_interfaces(); /* Load the list of interfaces ... */
6054 reopen_logs(); /* Get logging working ... */
6057 * Block SIGPIPE (from lib/util_sock.c: write())
6058 * It is not needed and should not stop execution
6060 BlockSignals(True, SIGPIPE);
6062 /* Done with one-time initialisation */
6063 smbc_initialized = 1;
6067 if (!context->user) {
6069 * FIXME: Is this the best way to get the user info?
6071 user = getenv("USER");
6072 /* walk around as "guest" if no username can be found */
6073 if (!user) context->user = SMB_STRDUP("guest");
6074 else context->user = SMB_STRDUP(user);
6077 if (!context->netbios_name) {
6079 * We try to get our netbios name from the config. If that
6080 * fails we fall back on constructing our netbios name from
6081 * our hostname etc
6083 if (global_myname()) {
6084 context->netbios_name = SMB_STRDUP(global_myname());
6086 else {
6088 * Hmmm, I want to get hostname as well, but I am too
6089 * lazy for the moment
6091 pid = sys_getpid();
6092 context->netbios_name = SMB_MALLOC(17);
6093 if (!context->netbios_name) {
6094 errno = ENOMEM;
6095 return NULL;
6097 slprintf(context->netbios_name, 16,
6098 "smbc%s%d", context->user, pid);
6102 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
6104 if (!context->workgroup) {
6105 if (lp_workgroup()) {
6106 context->workgroup = SMB_STRDUP(lp_workgroup());
6108 else {
6109 /* TODO: Think about a decent default workgroup */
6110 context->workgroup = SMB_STRDUP("samba");
6114 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
6116 /* shortest timeout is 1 second */
6117 if (context->timeout > 0 && context->timeout < 1000)
6118 context->timeout = 1000;
6121 * FIXME: Should we check the function pointers here?
6124 context->internal->_initialized = True;
6126 return context;
6130 /* Return the verion of samba, and thus libsmbclient */
6131 const char *
6132 smbc_version(void)
6134 return samba_version_string();