r12263: missed merges for 3.0.21 (patch from brian and derrell's libsmbclient fixes
[Samba.git] / source / libsmb / libsmbclient.c
blob15210664b078d5b2043718ebd2277a3ea301e761
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 *find_lsa_pipe_hnd(struct cli_state *ipc_cli)
87 struct rpc_pipe_client *pipe_hnd;
89 for (pipe_hnd = ipc_cli->pipe_list; pipe_hnd; pipe_hnd = pipe_hnd->next) {
90 if (pipe_hnd->pipe_idx == PI_LSARPC) {
91 return pipe_hnd;
95 return NULL;
98 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file);
99 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence);
101 extern BOOL in_client;
104 * Is the logging working / configfile read ?
106 static int smbc_initialized = 0;
108 static int
109 hex2int( unsigned int _char )
111 if ( _char >= 'A' && _char <='F')
112 return _char - 'A' + 10;
113 if ( _char >= 'a' && _char <='f')
114 return _char - 'a' + 10;
115 if ( _char >= '0' && _char <='9')
116 return _char - '0';
117 return -1;
121 * smbc_urldecode()
123 * Convert strings of %xx to their single character equivalent. Each 'x' must
124 * be a valid hexadecimal digit, or that % sequence is left undecoded.
126 * dest may, but need not be, the same pointer as src.
128 * Returns the number of % sequences which could not be converted due to lack
129 * of two following hexadecimal digits.
132 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
134 int old_length = strlen(src);
135 int i = 0;
136 int err_count = 0;
137 pstring temp;
138 char * p;
140 if ( old_length == 0 ) {
141 return 0;
144 p = temp;
145 while ( i < old_length ) {
146 unsigned char character = src[ i++ ];
148 if (character == '%') {
149 int a = i+1 < old_length ? hex2int( src[i] ) : -1;
150 int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
152 /* Replace valid sequence */
153 if (a != -1 && b != -1) {
155 /* Replace valid %xx sequence with %dd */
156 character = (a * 16) + b;
158 if (character == '\0') {
159 break; /* Stop at %00 */
162 i += 2;
163 } else {
165 err_count++;
169 *p++ = character;
172 *p = '\0';
174 strncpy(dest, temp, max_dest_len);
176 return err_count;
180 * smbc_urlencode()
182 * Convert any characters not specifically allowed in a URL into their %xx
183 * equivalent.
185 * Returns the remaining buffer length.
188 smbc_urlencode(char * dest, char * src, int max_dest_len)
190 char hex[] = "0123456789ABCDEF";
192 for (; *src != '\0' && max_dest_len >= 3; src++) {
194 if ((*src < '0' &&
195 *src != '-' &&
196 *src != '.') ||
197 (*src > '9' &&
198 *src < 'A') ||
199 (*src > 'Z' &&
200 *src < 'a' &&
201 *src != '_') ||
202 (*src > 'z')) {
203 *dest++ = '%';
204 *dest++ = hex[(*src >> 4) & 0x0f];
205 *dest++ = hex[*src & 0x0f];
206 max_dest_len -= 3;
207 } else {
208 *dest++ = *src;
209 max_dest_len--;
213 *dest++ = '\0';
214 max_dest_len--;
216 return max_dest_len;
220 * Function to parse a path and turn it into components
222 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
223 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
224 * general format ("smb:" only; we do not look for "cifs:").
227 * We accept:
228 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
230 * Meaning of URLs:
232 * smb:// Show all workgroups.
234 * The method of locating the list of workgroups varies
235 * depending upon the setting of the context variable
236 * context->options.browse_max_lmb_count. This value
237 * determine the maximum number of local master browsers to
238 * query for the list of workgroups. In order to ensure that
239 * a complete list of workgroups is obtained, all master
240 * browsers must be queried, but if there are many
241 * workgroups, the time spent querying can begin to add up.
242 * For small networks (not many workgroups), it is suggested
243 * that this variable be set to 0, indicating query all local
244 * master browsers. When the network has many workgroups, a
245 * reasonable setting for this variable might be around 3.
247 * smb://name/ if name<1D> or name<1B> exists, list servers in
248 * workgroup, else, if name<20> exists, list all shares
249 * for server ...
251 * If "options" are provided, this function returns the entire option list as a
252 * string, for later parsing by the caller. Note that currently, no options
253 * are supported.
256 static const char *smbc_prefix = "smb:";
258 static int
259 smbc_parse_path(SMBCCTX *context,
260 const char *fname,
261 char *server, int server_len,
262 char *share, int share_len,
263 char *path, int path_len,
264 char *user, int user_len,
265 char *password, int password_len,
266 char *options, int options_len)
268 static pstring s;
269 pstring userinfo;
270 const char *p;
271 char *q, *r;
272 int len;
274 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
275 if (options != NULL && options_len > 0) {
276 options[0] = (char)0;
278 pstrcpy(s, fname);
280 /* see if it has the right prefix */
281 len = strlen(smbc_prefix);
282 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
283 return -1; /* What about no smb: ? */
286 p = s + len;
288 /* Watch the test below, we are testing to see if we should exit */
290 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
292 DEBUG(1, ("Invalid path (does not begin with smb://"));
293 return -1;
297 p += 2; /* Skip the double slash */
299 /* See if any options were specified */
300 if ((q = strrchr(p, '?')) != NULL ) {
301 /* There are options. Null terminate here and point to them */
302 *q++ = '\0';
304 DEBUG(4, ("Found options '%s'", q));
306 /* Copy the options */
307 if (options != NULL && options_len > 0) {
308 safe_strcpy(options, q, options_len - 1);
312 if (*p == (char)0)
313 goto decoding;
315 if (*p == '/') {
317 strncpy(server, context->workgroup,
318 (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
319 return 0;
324 * ok, its for us. Now parse out the server, share etc.
326 * However, we want to parse out [[domain;]user[:password]@] if it
327 * exists ...
330 /* check that '@' occurs before '/', if '/' exists at all */
331 q = strchr_m(p, '@');
332 r = strchr_m(p, '/');
333 if (q && (!r || q < r)) {
334 pstring username, passwd, domain;
335 const char *u = userinfo;
337 next_token(&p, userinfo, "@", sizeof(fstring));
339 username[0] = passwd[0] = domain[0] = 0;
341 if (strchr_m(u, ';')) {
343 next_token(&u, domain, ";", sizeof(fstring));
347 if (strchr_m(u, ':')) {
349 next_token(&u, username, ":", sizeof(fstring));
351 pstrcpy(passwd, u);
354 else {
356 pstrcpy(username, u);
360 if (username[0])
361 strncpy(user, username, user_len); /* FIXME, domain */
363 if (passwd[0])
364 strncpy(password, passwd, password_len);
368 if (!next_token(&p, server, "/", sizeof(fstring))) {
370 return -1;
374 if (*p == (char)0) goto decoding; /* That's it ... */
376 if (!next_token(&p, share, "/", sizeof(fstring))) {
378 return -1;
382 safe_strcpy(path, p, path_len - 1);
384 all_string_sub(path, "/", "\\", 0);
386 decoding:
387 (void) smbc_urldecode(path, path, path_len);
388 (void) smbc_urldecode(server, server, server_len);
389 (void) smbc_urldecode(share, share, share_len);
390 (void) smbc_urldecode(user, user, user_len);
391 (void) smbc_urldecode(password, password, password_len);
393 return 0;
397 * Verify that the options specified in a URL are valid
399 static int smbc_check_options(char *server, char *share, char *path, char *options)
401 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' path='%s' options='%s'\n", server, share, path, options));
403 /* No options at all is always ok */
404 if (! *options) return 0;
406 /* Currently, we don't support any options. */
407 return -1;
411 * Convert an SMB error into a UNIX error ...
413 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
415 int ret = cli_errno(c);
417 if (cli_is_dos_error(c)) {
418 uint8 eclass;
419 uint32 ecode;
421 cli_dos_error(c, &eclass, &ecode);
423 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
424 (int)eclass, (int)ecode, (int)ecode, ret));
425 } else {
426 NTSTATUS status;
428 status = cli_nt_error(c);
430 DEBUG(3,("smbc errno %s -> %d\n",
431 nt_errstr(status), ret));
434 return ret;
438 * Check a server for being alive and well.
439 * returns 0 if the server is in shape. Returns 1 on error
441 * Also useable outside libsmbclient to enable external cache
442 * to do some checks too.
444 int smbc_check_server(SMBCCTX * context, SMBCSRV * server)
446 if ( send_keepalive(server->cli.fd) == False )
447 return 1;
449 /* connection is ok */
450 return 0;
454 * Remove a server from the cached server list it's unused.
455 * On success, 0 is returned. 1 is returned if the server could not be removed.
457 * Also useable outside libsmbclient
459 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
461 SMBCFILE * file;
463 /* are we being fooled ? */
464 if (!context || !context->internal ||
465 !context->internal->_initialized || !srv) return 1;
468 /* Check all open files/directories for a relation with this server */
469 for (file = context->internal->_files; file; file=file->next) {
470 if (file->srv == srv) {
471 /* Still used */
472 DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n",
473 srv, file));
474 return 1;
478 DLIST_REMOVE(context->internal->_servers, srv);
480 cli_shutdown(&srv->cli);
482 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
484 context->callbacks.remove_cached_srv_fn(context, srv);
486 SAFE_FREE(srv);
488 return 0;
491 SMBCSRV *find_server(SMBCCTX *context,
492 const char *server,
493 const char *share,
494 fstring workgroup,
495 fstring username,
496 fstring password)
498 SMBCSRV *srv;
499 int auth_called = 0;
501 check_server_cache:
503 srv = context->callbacks.get_cached_srv_fn(context, server, share,
504 workgroup, username);
506 if (!auth_called && !srv && (!username[0] || !password[0])) {
507 context->callbacks.auth_fn(server, share,
508 workgroup, sizeof(fstring),
509 username, sizeof(fstring),
510 password, sizeof(fstring));
512 * However, smbc_auth_fn may have picked up info relating to
513 * an existing connection, so try for an existing connection
514 * again ...
516 auth_called = 1;
517 goto check_server_cache;
521 if (srv) {
522 if (context->callbacks.check_server_fn(context, srv)) {
524 * This server is no good anymore
525 * Try to remove it and check for more possible
526 * servers in the cache
528 if (context->callbacks.remove_unused_server_fn(context,
529 srv)) {
531 * We could not remove the server completely,
532 * remove it from the cache so we will not get
533 * it again. It will be removed when the last
534 * file/dir is closed.
536 context->callbacks.remove_cached_srv_fn(context,
537 srv);
541 * Maybe there are more cached connections to this
542 * server
544 goto check_server_cache;
547 return srv;
550 return NULL;
554 * Connect to a server, possibly on an existing connection
556 * Here, what we want to do is: If the server and username
557 * match an existing connection, reuse that, otherwise, establish a
558 * new connection.
560 * If we have to create a new connection, call the auth_fn to get the
561 * info we need, unless the username and password were passed in.
564 SMBCSRV *smbc_server(SMBCCTX *context,
565 const char *server, const char *share,
566 fstring workgroup, fstring username,
567 fstring password)
569 SMBCSRV *srv=NULL;
570 struct cli_state c;
571 struct nmb_name called, calling;
572 const char *server_n = server;
573 pstring ipenv;
574 struct in_addr ip;
575 int tried_reverse = 0;
576 int port_try_first;
577 int port_try_next;
578 const char *username_used;
580 zero_ip(&ip);
581 ZERO_STRUCT(c);
583 if (server[0] == 0) {
584 errno = EPERM;
585 return NULL;
588 /* Look for a cached connection */
589 srv = find_server(context, server, share,
590 workgroup, username, password);
593 * If we found a connection and we're only allowed one share per
594 * server...
596 if (srv && *share != '\0' && context->options.one_share_per_server) {
599 * ... then if there's no current connection to the share,
600 * connect to it. find_server(), or rather the function
601 * pointed to by context->callbacks.get_cached_srv_fn which
602 * was called by find_server(), will have issued a tree
603 * disconnect if the requested share is not the same as the
604 * one that was already connected.
606 if (srv->cli.cnum == (uint16) -1) {
607 /* Ensure we have accurate auth info */
608 context->callbacks.auth_fn(server, share,
609 workgroup, sizeof(fstring),
610 username, sizeof(fstring),
611 password, sizeof(fstring));
613 if (! cli_send_tconX(&srv->cli, share, "?????",
614 password, strlen(password)+1)) {
616 errno = smbc_errno(context, &srv->cli);
617 cli_shutdown(&srv->cli);
618 context->callbacks.remove_cached_srv_fn(context, srv);
619 srv = NULL;
622 /* Regenerate the dev value since it's based on both server and share */
623 if (srv) {
624 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
629 /* If we have a connection... */
630 if (srv) {
632 /* ... then we're done here. Give 'em what they came for. */
633 return srv;
636 make_nmb_name(&calling, context->netbios_name, 0x0);
637 make_nmb_name(&called , server, 0x20);
639 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
641 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
643 again:
644 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
646 zero_ip(&ip);
648 /* have to open a new connection */
649 if (!cli_initialise(&c)) {
650 errno = ENOMEM;
651 return NULL;
654 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
655 c.use_kerberos = True;
657 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
658 c.fallback_after_kerberos = True;
661 c.timeout = context->timeout;
664 * Force use of port 139 for first try if share is $IPC, empty, or
665 * null, so browse lists can work
667 if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
668 port_try_first = 139;
669 port_try_next = 445;
670 } else {
671 port_try_first = 445;
672 port_try_next = 139;
675 c.port = port_try_first;
677 if (!cli_connect(&c, server_n, &ip)) {
679 /* First connection attempt failed. Try alternate port. */
680 c.port = port_try_next;
682 if (!cli_connect(&c, server_n, &ip)) {
683 cli_shutdown(&c);
684 errno = ETIMEDOUT;
685 return NULL;
689 if (!cli_session_request(&c, &calling, &called)) {
690 cli_shutdown(&c);
691 if (strcmp(called.name, "*SMBSERVER")) {
692 make_nmb_name(&called , "*SMBSERVER", 0x20);
693 goto again;
695 else { /* Try one more time, but ensure we don't loop */
697 /* Only try this if server is an IP address ... */
699 if (is_ipaddress(server) && !tried_reverse) {
700 fstring remote_name;
701 struct in_addr rem_ip;
703 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
704 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
705 errno = ETIMEDOUT;
706 return NULL;
709 tried_reverse++; /* Yuck */
711 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
712 make_nmb_name(&called, remote_name, 0x20);
713 goto again;
719 errno = ETIMEDOUT;
720 return NULL;
723 DEBUG(4,(" session request ok\n"));
725 if (!cli_negprot(&c)) {
726 cli_shutdown(&c);
727 errno = ETIMEDOUT;
728 return NULL;
731 username_used = username;
733 if (!cli_session_setup(&c, username_used,
734 password, strlen(password),
735 password, strlen(password),
736 workgroup)) {
738 /* Failed. Try an anonymous login, if allowed by flags. */
739 username_used = "";
741 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
742 !cli_session_setup(&c, username_used,
743 password, 1,
744 password, 0,
745 workgroup)) {
747 cli_shutdown(&c);
748 errno = EPERM;
749 return NULL;
753 DEBUG(4,(" session setup ok\n"));
755 if (!cli_send_tconX(&c, share, "?????",
756 password, strlen(password)+1)) {
757 errno = smbc_errno(context, &c);
758 cli_shutdown(&c);
759 return NULL;
762 DEBUG(4,(" tconx ok\n"));
765 * Ok, we have got a nice connection
766 * Let's allocate a server structure.
769 srv = SMB_MALLOC_P(SMBCSRV);
770 if (!srv) {
771 errno = ENOMEM;
772 goto failed;
775 ZERO_STRUCTP(srv);
776 srv->cli = c;
777 srv->cli.allocated = False;
778 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
779 srv->no_pathinfo = False;
780 srv->no_pathinfo2 = False;
781 srv->no_nt_session = False;
783 /* now add it to the cache (internal or external) */
784 /* Let the cache function set errno if it wants to */
785 errno = 0;
786 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
787 int saved_errno = errno;
788 DEBUG(3, (" Failed to add server to cache\n"));
789 errno = saved_errno;
790 if (errno == 0) {
791 errno = ENOMEM;
793 goto failed;
796 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
797 server, share, srv));
799 DLIST_ADD(context->internal->_servers, srv);
800 return srv;
802 failed:
803 cli_shutdown(&c);
804 if (!srv) return NULL;
806 SAFE_FREE(srv);
807 return NULL;
811 * Connect to a server for getting/setting attributes, possibly on an existing
812 * connection. This works similarly to smbc_server().
814 SMBCSRV *smbc_attr_server(SMBCCTX *context,
815 const char *server, const char *share,
816 fstring workgroup,
817 fstring username, fstring password,
818 POLICY_HND *pol)
820 struct in_addr ip;
821 struct cli_state *ipc_cli;
822 struct rpc_pipe_client *pipe_hnd;
823 NTSTATUS nt_status;
824 SMBCSRV *ipc_srv=NULL;
827 * See if we've already created this special connection. Reference
828 * our "special" share name '*IPC$', which is an impossible real share
829 * name due to the leading asterisk.
831 ipc_srv = find_server(context, server, "*IPC$",
832 workgroup, username, password);
833 if (!ipc_srv) {
835 /* We didn't find a cached connection. Get the password */
836 if (*password == '\0') {
837 /* ... then retrieve it now. */
838 context->callbacks.auth_fn(server, share,
839 workgroup, sizeof(fstring),
840 username, sizeof(fstring),
841 password, sizeof(fstring));
844 zero_ip(&ip);
845 nt_status = cli_full_connection(&ipc_cli,
846 global_myname(), server,
847 &ip, 0, "IPC$", "?????",
848 username, workgroup,
849 password, 0,
850 Undefined, NULL);
851 if (! NT_STATUS_IS_OK(nt_status)) {
852 DEBUG(1,("cli_full_connection failed! (%s)\n",
853 nt_errstr(nt_status)));
854 errno = ENOTSUP;
855 return NULL;
858 ipc_srv = SMB_MALLOC_P(SMBCSRV);
859 if (!ipc_srv) {
860 errno = ENOMEM;
861 cli_shutdown(ipc_cli);
862 return NULL;
865 ZERO_STRUCTP(ipc_srv);
866 ipc_srv->cli = *ipc_cli;
867 ipc_srv->cli.allocated = False;
869 free(ipc_cli);
871 if (pol) {
872 pipe_hnd = cli_rpc_pipe_open_noauth(&ipc_srv->cli,
873 PI_LSARPC,
874 &nt_status);
875 if (!pipe_hnd) {
876 DEBUG(1, ("cli_nt_session_open fail!\n"));
877 errno = ENOTSUP;
878 cli_shutdown(&ipc_srv->cli);
879 free(ipc_srv);
880 return NULL;
884 * Some systems don't support
885 * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
886 * so we might as well do it too.
889 nt_status = rpccli_lsa_open_policy(
890 pipe_hnd,
891 ipc_srv->cli.mem_ctx,
892 True,
893 GENERIC_EXECUTE_ACCESS,
894 pol);
896 if (!NT_STATUS_IS_OK(nt_status)) {
897 errno = smbc_errno(context, &ipc_srv->cli);
898 cli_shutdown(&ipc_srv->cli);
899 return NULL;
903 /* now add it to the cache (internal or external) */
905 errno = 0; /* let cache function set errno if it likes */
906 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
907 server,
908 "*IPC$",
909 workgroup,
910 username)) {
911 DEBUG(3, (" Failed to add server to cache\n"));
912 if (errno == 0) {
913 errno = ENOMEM;
915 cli_shutdown(&ipc_srv->cli);
916 free(ipc_srv);
917 return NULL;
920 DLIST_ADD(context->internal->_servers, ipc_srv);
923 return ipc_srv;
927 * Routine to open() a file ...
930 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
932 fstring server, share, user, password, workgroup;
933 pstring path;
934 pstring targetpath;
935 struct cli_state *targetcli;
936 SMBCSRV *srv = NULL;
937 SMBCFILE *file = NULL;
938 int fd;
940 if (!context || !context->internal ||
941 !context->internal->_initialized) {
943 errno = EINVAL; /* Best I can think of ... */
944 return NULL;
948 if (!fname) {
950 errno = EINVAL;
951 return NULL;
955 if (smbc_parse_path(context, fname,
956 server, sizeof(server),
957 share, sizeof(share),
958 path, sizeof(path),
959 user, sizeof(user),
960 password, sizeof(password),
961 NULL, 0)) {
962 errno = EINVAL;
963 return NULL;
966 if (user[0] == (char)0) fstrcpy(user, context->user);
968 fstrcpy(workgroup, context->workgroup);
970 srv = smbc_server(context, server, share, workgroup, user, password);
972 if (!srv) {
974 if (errno == EPERM) errno = EACCES;
975 return NULL; /* smbc_server sets errno */
979 /* Hmmm, the test for a directory is suspect here ... FIXME */
981 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
983 fd = -1;
986 else {
988 file = SMB_MALLOC_P(SMBCFILE);
990 if (!file) {
992 errno = ENOMEM;
993 return NULL;
997 ZERO_STRUCTP(file);
999 /*d_printf(">>>open: resolving %s\n", path);*/
1000 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1002 d_printf("Could not resolve %s\n", path);
1003 return NULL;
1005 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1007 if ( targetcli->dfsroot )
1009 pstring temppath;
1010 pstrcpy(temppath, targetpath);
1011 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1014 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1016 /* Handle the error ... */
1018 SAFE_FREE(file);
1019 errno = smbc_errno(context, targetcli);
1020 return NULL;
1024 /* Fill in file struct */
1026 file->cli_fd = fd;
1027 file->fname = SMB_STRDUP(fname);
1028 file->srv = srv;
1029 file->offset = 0;
1030 file->file = True;
1032 DLIST_ADD(context->internal->_files, file);
1035 * If the file was opened in O_APPEND mode, all write
1036 * operations should be appended to the file. To do that,
1037 * though, using this protocol, would require a getattrE()
1038 * call for each and every write, to determine where the end
1039 * of the file is. (There does not appear to be an append flag
1040 * in the protocol.) Rather than add all of that overhead of
1041 * retrieving the current end-of-file offset prior to each
1042 * write operation, we'll assume that most append operations
1043 * will continuously write, so we'll just set the offset to
1044 * the end of the file now and hope that's adequate.
1046 * Note to self: If this proves inadequate, and O_APPEND
1047 * should, in some cases, be forced for each write, add a
1048 * field in the context options structure, for
1049 * "strict_append_mode" which would select between the current
1050 * behavior (if FALSE) or issuing a getattrE() prior to each
1051 * write and forcing the write to the end of the file (if
1052 * TRUE). Adding that capability will likely require adding
1053 * an "append" flag into the _SMBCFILE structure to track
1054 * whether a file was opened in O_APPEND mode. -- djl
1056 if (flags & O_APPEND) {
1057 if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1058 (void) smbc_close_ctx(context, file);
1059 errno = ENXIO;
1060 return NULL;
1064 return file;
1068 /* Check if opendir needed ... */
1070 if (fd == -1) {
1071 int eno = 0;
1073 eno = smbc_errno(context, &srv->cli);
1074 file = context->opendir(context, fname);
1075 if (!file) errno = eno;
1076 return file;
1080 errno = EINVAL; /* FIXME, correct errno ? */
1081 return NULL;
1086 * Routine to create a file
1089 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1091 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
1094 if (!context || !context->internal ||
1095 !context->internal->_initialized) {
1097 errno = EINVAL;
1098 return NULL;
1102 return smbc_open_ctx(context, path, creat_bits, mode);
1106 * Routine to read() a file ...
1109 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1111 int ret;
1112 fstring server, share, user, password;
1113 pstring path, targetpath;
1114 struct cli_state *targetcli;
1117 * offset:
1119 * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1120 * appears to pass file->offset (which is type off_t) differently than
1121 * a local variable of type off_t. Using local variable "offset" in
1122 * the call to cli_read() instead of file->offset fixes a problem
1123 * retrieving data at an offset greater than 4GB.
1125 off_t offset = file->offset;
1127 if (!context || !context->internal ||
1128 !context->internal->_initialized) {
1130 errno = EINVAL;
1131 return -1;
1135 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1137 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1139 errno = EBADF;
1140 return -1;
1144 /* Check that the buffer exists ... */
1146 if (buf == NULL) {
1148 errno = EINVAL;
1149 return -1;
1153 /*d_printf(">>>read: parsing %s\n", file->fname);*/
1154 if (smbc_parse_path(context, file->fname,
1155 server, sizeof(server),
1156 share, sizeof(share),
1157 path, sizeof(path),
1158 user, sizeof(user),
1159 password, sizeof(password),
1160 NULL, 0)) {
1161 errno = EINVAL;
1162 return -1;
1165 /*d_printf(">>>read: resolving %s\n", path);*/
1166 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1168 d_printf("Could not resolve %s\n", path);
1169 return -1;
1171 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1173 ret = cli_read(targetcli, file->cli_fd, buf, offset, count);
1175 if (ret < 0) {
1177 errno = smbc_errno(context, targetcli);
1178 return -1;
1182 file->offset += ret;
1184 DEBUG(4, (" --> %d\n", ret));
1186 return ret; /* Success, ret bytes of data ... */
1191 * Routine to write() a file ...
1194 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1196 int ret;
1197 off_t offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1198 fstring server, share, user, password;
1199 pstring path, targetpath;
1200 struct cli_state *targetcli;
1202 if (!context || !context->internal ||
1203 !context->internal->_initialized) {
1205 errno = EINVAL;
1206 return -1;
1210 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1212 errno = EBADF;
1213 return -1;
1217 /* Check that the buffer exists ... */
1219 if (buf == NULL) {
1221 errno = EINVAL;
1222 return -1;
1226 /*d_printf(">>>write: parsing %s\n", file->fname);*/
1227 if (smbc_parse_path(context, file->fname,
1228 server, sizeof(server),
1229 share, sizeof(share),
1230 path, sizeof(path),
1231 user, sizeof(user),
1232 password, sizeof(password),
1233 NULL, 0)) {
1234 errno = EINVAL;
1235 return -1;
1238 /*d_printf(">>>write: resolving %s\n", path);*/
1239 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1241 d_printf("Could not resolve %s\n", path);
1242 return -1;
1244 /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1247 ret = cli_write(targetcli, file->cli_fd, 0, buf, offset, count);
1249 if (ret <= 0) {
1251 errno = smbc_errno(context, targetcli);
1252 return -1;
1256 file->offset += ret;
1258 return ret; /* Success, 0 bytes of data ... */
1262 * Routine to close() a file ...
1265 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1267 SMBCSRV *srv;
1268 fstring server, share, user, password;
1269 pstring path, targetpath;
1270 struct cli_state *targetcli;
1272 if (!context || !context->internal ||
1273 !context->internal->_initialized) {
1275 errno = EINVAL;
1276 return -1;
1280 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1282 errno = EBADF;
1283 return -1;
1287 /* IS a dir ... */
1288 if (!file->file) {
1290 return context->closedir(context, file);
1294 /*d_printf(">>>close: parsing %s\n", file->fname);*/
1295 if (smbc_parse_path(context, file->fname,
1296 server, sizeof(server),
1297 share, sizeof(share),
1298 path, sizeof(path),
1299 user, sizeof(user),
1300 password, sizeof(password),
1301 NULL, 0)) {
1302 errno = EINVAL;
1303 return -1;
1306 /*d_printf(">>>close: resolving %s\n", path);*/
1307 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1309 d_printf("Could not resolve %s\n", path);
1310 return -1;
1312 /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1314 if (!cli_close(targetcli, file->cli_fd)) {
1316 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1317 file->fname));
1318 /* Deallocate slot and remove the server
1319 * from the server cache if unused */
1320 errno = smbc_errno(context, targetcli);
1321 srv = file->srv;
1322 DLIST_REMOVE(context->internal->_files, file);
1323 SAFE_FREE(file->fname);
1324 SAFE_FREE(file);
1325 context->callbacks.remove_unused_server_fn(context, srv);
1327 return -1;
1331 DLIST_REMOVE(context->internal->_files, file);
1332 SAFE_FREE(file->fname);
1333 SAFE_FREE(file);
1335 return 0;
1339 * Get info from an SMB server on a file. Use a qpathinfo call first
1340 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1342 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1343 uint16 *mode, SMB_OFF_T *size,
1344 time_t *c_time, time_t *a_time, time_t *m_time,
1345 SMB_INO_T *ino)
1347 pstring fixedpath;
1348 pstring targetpath;
1349 struct cli_state *targetcli;
1350 if (!context || !context->internal ||
1351 !context->internal->_initialized) {
1353 errno = EINVAL;
1354 return -1;
1358 /* path fixup for . and .. */
1359 if (strequal(path, ".") || strequal(path, ".."))
1360 pstrcpy(fixedpath, "\\");
1361 else
1363 pstrcpy(fixedpath, path);
1364 trim_string(fixedpath, NULL, "\\..");
1365 trim_string(fixedpath, NULL, "\\.");
1367 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1369 if (!cli_resolve_path( "", &srv->cli, fixedpath, &targetcli, targetpath))
1371 d_printf("Couldn't resolve %s\n", path);
1372 return False;
1375 if ( targetcli->dfsroot )
1377 pstring temppath;
1378 pstrcpy(temppath, targetpath);
1379 cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1382 if (!srv->no_pathinfo2 &&
1383 cli_qpathinfo2(targetcli, targetpath, c_time, a_time, m_time, NULL,
1384 size, mode, ino)) return True;
1386 /* if this is NT then don't bother with the getatr */
1387 if (targetcli->capabilities & CAP_NT_SMBS) {
1388 errno = EPERM;
1389 return False;
1392 if (cli_getatr(targetcli, targetpath, mode, size, m_time)) {
1393 if (m_time != NULL) {
1394 if (a_time != NULL) *a_time = *m_time;
1395 if (c_time != NULL) *c_time = *m_time;
1397 srv->no_pathinfo2 = True;
1398 return True;
1401 errno = EPERM;
1402 return False;
1407 * Set file info on an SMB server. Use setpathinfo call first. If that
1408 * fails, use setattrE..
1410 * Access and modification time parameters are always used and must be
1411 * provided. Create time, if zero, will be determined from the actual create
1412 * time of the file. If non-zero, the create time will be set as well.
1414 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1416 static BOOL smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1417 time_t c_time, time_t a_time, time_t m_time,
1418 uint16 mode)
1420 int fd;
1421 int ret;
1424 * Get the create time of the file (if not provided); we'll need it in
1425 * the set call.
1427 if (! srv->no_pathinfo && c_time == 0) {
1428 if (! cli_qpathinfo(&srv->cli, path,
1429 &c_time, NULL, NULL, NULL, NULL)) {
1430 /* qpathinfo not available */
1431 srv->no_pathinfo = True;
1432 } else {
1434 * We got a creation time. Some OS versions don't
1435 * return a valid create time, though. If we got an
1436 * invalid time, start with the current time instead.
1438 if (c_time == 0 || c_time == (time_t) -1) {
1439 c_time = time(NULL);
1443 * We got a creation time. For sanity sake, since
1444 * there is no POSIX function to set the create time
1445 * of a file, if the existing create time is greater
1446 * than either of access time or modification time,
1447 * set create time to the smallest of those. This
1448 * ensure that the create time of a file is never
1449 * greater than its last access or modification time.
1451 if (c_time > a_time) c_time = a_time;
1452 if (c_time > m_time) c_time = m_time;
1457 * First, try setpathinfo (if qpathinfo succeeded), for it is the
1458 * modern function for "new code" to be using, and it works given a
1459 * filename rather than requiring that the file be opened to have its
1460 * attributes manipulated.
1462 if (srv->no_pathinfo ||
1463 ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {
1466 * setpathinfo is not supported; go to plan B.
1468 * cli_setatr() does not work on win98, and it also doesn't
1469 * support setting the access time (only the modification
1470 * time), so in all cases, we open the specified file and use
1471 * cli_setattrE() which should work on all OS versions, and
1472 * supports both times.
1475 /* Don't try {q,set}pathinfo() again, with this server */
1476 srv->no_pathinfo = True;
1478 /* Open the file */
1479 if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1481 errno = smbc_errno(context, &srv->cli);
1482 return -1;
1486 * Get the creat time of the file (if it wasn't provided).
1487 * We'll need it in the set call
1489 if (c_time == 0) {
1490 ret = cli_getattrE(&srv->cli, fd,
1491 NULL, NULL,
1492 &c_time, NULL, NULL);
1493 } else {
1494 ret = True;
1497 /* If we got create time, set times */
1498 if (ret) {
1499 /* Some OS versions don't support create time */
1500 if (c_time == 0 || c_time == -1) {
1501 c_time = time(NULL);
1505 * For sanity sake, since there is no POSIX function
1506 * to set the create time of a file, if the existing
1507 * create time is greater than either of access time
1508 * or modification time, set create time to the
1509 * smallest of those. This ensure that the create
1510 * time of a file is never greater than its last
1511 * access or modification time.
1513 if (c_time > a_time) c_time = a_time;
1514 if (c_time > m_time) c_time = m_time;
1516 /* Set the new attributes */
1517 ret = cli_setattrE(&srv->cli, fd,
1518 c_time, a_time, m_time);
1519 cli_close(&srv->cli, fd);
1523 * Unfortunately, setattrE() doesn't have a provision for
1524 * setting the access mode (attributes). We'll have to try
1525 * cli_setatr() for that, and with only this parameter, it
1526 * seems to work on win98.
1528 if (ret && mode != (uint16) -1) {
1529 ret = cli_setatr(&srv->cli, path, mode, 0);
1532 if (! ret) {
1533 errno = smbc_errno(context, &srv->cli);
1534 return False;
1538 return True;
1542 * Routine to unlink() a file
1545 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1547 fstring server, share, user, password, workgroup;
1548 pstring path, targetpath;
1549 struct cli_state *targetcli;
1550 SMBCSRV *srv = NULL;
1552 if (!context || !context->internal ||
1553 !context->internal->_initialized) {
1555 errno = EINVAL; /* Best I can think of ... */
1556 return -1;
1560 if (!fname) {
1562 errno = EINVAL;
1563 return -1;
1567 if (smbc_parse_path(context, fname,
1568 server, sizeof(server),
1569 share, sizeof(share),
1570 path, sizeof(path),
1571 user, sizeof(user),
1572 password, sizeof(password),
1573 NULL, 0)) {
1574 errno = EINVAL;
1575 return -1;
1578 if (user[0] == (char)0) fstrcpy(user, context->user);
1580 fstrcpy(workgroup, context->workgroup);
1582 srv = smbc_server(context, server, share, workgroup, user, password);
1584 if (!srv) {
1586 return -1; /* smbc_server sets errno */
1590 /*d_printf(">>>unlink: resolving %s\n", path);*/
1591 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
1593 d_printf("Could not resolve %s\n", path);
1594 return -1;
1596 /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1598 if (!cli_unlink(targetcli, targetpath)) {
1600 errno = smbc_errno(context, targetcli);
1602 if (errno == EACCES) { /* Check if the file is a directory */
1604 int saverr = errno;
1605 SMB_OFF_T size = 0;
1606 uint16 mode = 0;
1607 time_t m_time = 0, a_time = 0, c_time = 0;
1608 SMB_INO_T ino = 0;
1610 if (!smbc_getatr(context, srv, path, &mode, &size,
1611 &c_time, &a_time, &m_time, &ino)) {
1613 /* Hmmm, bad error ... What? */
1615 errno = smbc_errno(context, targetcli);
1616 return -1;
1619 else {
1621 if (IS_DOS_DIR(mode))
1622 errno = EISDIR;
1623 else
1624 errno = saverr; /* Restore this */
1629 return -1;
1633 return 0; /* Success ... */
1638 * Routine to rename() a file
1641 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1642 SMBCCTX *ncontext, const char *nname)
1644 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1645 pstring path1, path2, targetpath1, targetpath2;
1646 struct cli_state *targetcli1, *targetcli2;
1647 SMBCSRV *srv = NULL;
1649 if (!ocontext || !ncontext ||
1650 !ocontext->internal || !ncontext->internal ||
1651 !ocontext->internal->_initialized ||
1652 !ncontext->internal->_initialized) {
1654 errno = EINVAL; /* Best I can think of ... */
1655 return -1;
1659 if (!oname || !nname) {
1661 errno = EINVAL;
1662 return -1;
1666 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1668 smbc_parse_path(ocontext, oname,
1669 server1, sizeof(server1),
1670 share1, sizeof(share1),
1671 path1, sizeof(path1),
1672 user1, sizeof(user1),
1673 password1, sizeof(password1),
1674 NULL, 0);
1676 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1678 smbc_parse_path(ncontext, nname,
1679 server2, sizeof(server2),
1680 share2, sizeof(share2),
1681 path2, sizeof(path2),
1682 user2, sizeof(user2),
1683 password2, sizeof(password2),
1684 NULL, 0);
1686 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1688 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1689 strcmp(user1, user2)) {
1691 /* Can't rename across file systems, or users?? */
1693 errno = EXDEV;
1694 return -1;
1698 fstrcpy(workgroup, ocontext->workgroup);
1699 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1700 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1701 if (!srv) {
1703 return -1;
1707 /*d_printf(">>>rename: resolving %s\n", path1);*/
1708 if (!cli_resolve_path( "", &srv->cli, path1, &targetcli1, targetpath1))
1710 d_printf("Could not resolve %s\n", path1);
1711 return -1;
1713 /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1714 /*d_printf(">>>rename: resolving %s\n", path2);*/
1715 if (!cli_resolve_path( "", &srv->cli, path2, &targetcli2, targetpath2))
1717 d_printf("Could not resolve %s\n", path2);
1718 return -1;
1720 /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1722 if (strcmp(targetcli1->desthost, targetcli2->desthost) || strcmp(targetcli1->share, targetcli2->share))
1724 /* can't rename across file systems */
1726 errno = EXDEV;
1727 return -1;
1730 if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1731 int eno = smbc_errno(ocontext, targetcli1);
1733 if (eno != EEXIST ||
1734 !cli_unlink(targetcli1, targetpath2) ||
1735 !cli_rename(targetcli1, targetpath1, targetpath2)) {
1737 errno = eno;
1738 return -1;
1743 return 0; /* Success */
1748 * A routine to lseek() a file
1751 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1753 SMB_OFF_T size;
1754 fstring server, share, user, password;
1755 pstring path, targetpath;
1756 struct cli_state *targetcli;
1758 if (!context || !context->internal ||
1759 !context->internal->_initialized) {
1761 errno = EINVAL;
1762 return -1;
1766 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1768 errno = EBADF;
1769 return -1;
1773 if (!file->file) {
1775 errno = EINVAL;
1776 return -1; /* Can't lseek a dir ... */
1780 switch (whence) {
1781 case SEEK_SET:
1782 file->offset = offset;
1783 break;
1785 case SEEK_CUR:
1786 file->offset += offset;
1787 break;
1789 case SEEK_END:
1790 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1791 if (smbc_parse_path(context, file->fname,
1792 server, sizeof(server),
1793 share, sizeof(share),
1794 path, sizeof(path),
1795 user, sizeof(user),
1796 password, sizeof(password),
1797 NULL, 0)) {
1798 errno = EINVAL;
1799 return -1;
1802 /*d_printf(">>>lseek: resolving %s\n", path);*/
1803 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
1805 d_printf("Could not resolve %s\n", path);
1806 return -1;
1808 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1810 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL, &size, NULL, NULL,
1811 NULL, NULL, NULL))
1813 SMB_OFF_T b_size = size;
1814 if (!cli_getattrE(targetcli, file->cli_fd, NULL, &b_size, NULL, NULL,
1815 NULL))
1817 errno = EINVAL;
1818 return -1;
1819 } else
1820 size = b_size;
1822 file->offset = size + offset;
1823 break;
1825 default:
1826 errno = EINVAL;
1827 break;
1831 return file->offset;
1836 * Generate an inode number from file name for those things that need it
1839 static
1840 ino_t smbc_inode(SMBCCTX *context, const char *name)
1843 if (!context || !context->internal ||
1844 !context->internal->_initialized) {
1846 errno = EINVAL;
1847 return -1;
1851 if (!*name) return 2; /* FIXME, why 2 ??? */
1852 return (ino_t)str_checksum(name);
1857 * Routine to put basic stat info into a stat structure ... Used by stat and
1858 * fstat below.
1861 static
1862 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname,
1863 SMB_OFF_T size, int mode)
1866 st->st_mode = 0;
1868 if (IS_DOS_DIR(mode)) {
1869 st->st_mode = SMBC_DIR_MODE;
1870 } else {
1871 st->st_mode = SMBC_FILE_MODE;
1874 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1875 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1876 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1877 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1879 st->st_size = size;
1880 #ifdef HAVE_STAT_ST_BLKSIZE
1881 st->st_blksize = 512;
1882 #endif
1883 #ifdef HAVE_STAT_ST_BLOCKS
1884 st->st_blocks = (size+511)/512;
1885 #endif
1886 st->st_uid = getuid();
1887 st->st_gid = getgid();
1889 if (IS_DOS_DIR(mode)) {
1890 st->st_nlink = 2;
1891 } else {
1892 st->st_nlink = 1;
1895 if (st->st_ino == 0) {
1896 st->st_ino = smbc_inode(context, fname);
1899 return True; /* FIXME: Is this needed ? */
1904 * Routine to stat a file given a name
1907 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1909 SMBCSRV *srv;
1910 fstring server, share, user, password, workgroup;
1911 pstring path;
1912 time_t m_time = 0, a_time = 0, c_time = 0;
1913 SMB_OFF_T size = 0;
1914 uint16 mode = 0;
1915 SMB_INO_T ino = 0;
1917 if (!context || !context->internal ||
1918 !context->internal->_initialized) {
1920 errno = EINVAL; /* Best I can think of ... */
1921 return -1;
1925 if (!fname) {
1927 errno = EINVAL;
1928 return -1;
1932 DEBUG(4, ("smbc_stat(%s)\n", fname));
1934 if (smbc_parse_path(context, fname,
1935 server, sizeof(server),
1936 share, sizeof(share),
1937 path, sizeof(path),
1938 user, sizeof(user),
1939 password, sizeof(password),
1940 NULL, 0)) {
1941 errno = EINVAL;
1942 return -1;
1945 if (user[0] == (char)0) fstrcpy(user, context->user);
1947 fstrcpy(workgroup, context->workgroup);
1949 srv = smbc_server(context, server, share, workgroup, user, password);
1951 if (!srv) {
1952 return -1; /* errno set by smbc_server */
1955 if (!smbc_getatr(context, srv, path, &mode, &size,
1956 &c_time, &a_time, &m_time, &ino)) {
1958 errno = smbc_errno(context, &srv->cli);
1959 return -1;
1963 st->st_ino = ino;
1965 smbc_setup_stat(context, st, path, size, mode);
1967 st->st_atime = a_time;
1968 st->st_ctime = c_time;
1969 st->st_mtime = m_time;
1970 st->st_dev = srv->dev;
1972 return 0;
1977 * Routine to stat a file given an fd
1980 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1982 time_t c_time, a_time, m_time;
1983 SMB_OFF_T size;
1984 uint16 mode;
1985 fstring server, share, user, password;
1986 pstring path, targetpath;
1987 struct cli_state *targetcli;
1988 SMB_INO_T ino = 0;
1990 if (!context || !context->internal ||
1991 !context->internal->_initialized) {
1993 errno = EINVAL;
1994 return -1;
1998 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2000 errno = EBADF;
2001 return -1;
2005 if (!file->file) {
2007 return context->fstatdir(context, file, st);
2011 /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2012 if (smbc_parse_path(context, file->fname,
2013 server, sizeof(server),
2014 share, sizeof(share),
2015 path, sizeof(path),
2016 user, sizeof(user),
2017 password, sizeof(password),
2018 NULL, 0)) {
2019 errno = EINVAL;
2020 return -1;
2023 /*d_printf(">>>fstat: resolving %s\n", path);*/
2024 if (!cli_resolve_path( "", &file->srv->cli, path, &targetcli, targetpath))
2026 d_printf("Could not resolve %s\n", path);
2027 return -1;
2029 /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2031 if (!cli_qfileinfo(targetcli, file->cli_fd,
2032 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
2033 if (!cli_getattrE(targetcli, file->cli_fd,
2034 &mode, &size, &c_time, &a_time, &m_time)) {
2036 errno = EINVAL;
2037 return -1;
2041 st->st_ino = ino;
2043 smbc_setup_stat(context, st, file->fname, size, mode);
2045 st->st_atime = a_time;
2046 st->st_ctime = c_time;
2047 st->st_mtime = m_time;
2048 st->st_dev = file->srv->dev;
2050 return 0;
2055 * Routine to open a directory
2056 * We accept the URL syntax explained in smbc_parse_path(), above.
2059 static void smbc_remove_dir(SMBCFILE *dir)
2061 struct smbc_dir_list *d,*f;
2063 d = dir->dir_list;
2064 while (d) {
2066 f = d; d = d->next;
2068 SAFE_FREE(f->dirent);
2069 SAFE_FREE(f);
2073 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2077 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
2079 struct smbc_dirent *dirent;
2080 int size;
2081 int name_length = (name == NULL ? 0 : strlen(name));
2082 int comment_len = (comment == NULL ? 0 : strlen(comment));
2085 * Allocate space for the dirent, which must be increased by the
2086 * size of the name and the comment and 1 each for the null terminator.
2089 size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2091 dirent = SMB_MALLOC(size);
2093 if (!dirent) {
2095 dir->dir_error = ENOMEM;
2096 return -1;
2100 ZERO_STRUCTP(dirent);
2102 if (dir->dir_list == NULL) {
2104 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2105 if (!dir->dir_list) {
2107 SAFE_FREE(dirent);
2108 dir->dir_error = ENOMEM;
2109 return -1;
2112 ZERO_STRUCTP(dir->dir_list);
2114 dir->dir_end = dir->dir_next = dir->dir_list;
2116 else {
2118 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2120 if (!dir->dir_end->next) {
2122 SAFE_FREE(dirent);
2123 dir->dir_error = ENOMEM;
2124 return -1;
2127 ZERO_STRUCTP(dir->dir_end->next);
2129 dir->dir_end = dir->dir_end->next;
2132 dir->dir_end->next = NULL;
2133 dir->dir_end->dirent = dirent;
2135 dirent->smbc_type = type;
2136 dirent->namelen = name_length;
2137 dirent->commentlen = comment_len;
2138 dirent->dirlen = size;
2140 strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2142 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2143 strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2145 return 0;
2149 static void
2150 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
2152 SMBCFILE *dir = (SMBCFILE *)state;
2153 struct smbc_dir_list *dir_list;
2154 struct smbc_dirent *dirent;
2155 int dirent_type;
2156 int do_remove = 0;
2158 dirent_type = dir->dir_type;
2160 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2162 /* An error occurred, what do we do? */
2163 /* FIXME: Add some code here */
2166 /* Point to the one just added */
2167 dirent = dir->dir_end->dirent;
2169 /* See if this was a duplicate */
2170 for (dir_list = dir->dir_list;
2171 dir_list != dir->dir_end;
2172 dir_list = dir_list->next) {
2173 if (! do_remove &&
2174 strcmp(dir_list->dirent->name, dirent->name) == 0) {
2175 /* Duplicate. End end of list need to be removed. */
2176 do_remove = 1;
2179 if (do_remove && dir_list->next == dir->dir_end) {
2180 /* Found the end of the list. Remove it. */
2181 dir->dir_end = dir_list;
2182 free(dir_list->next);
2183 free(dirent);
2184 dir_list->next = NULL;
2185 break;
2190 static void
2191 list_fn(const char *name, uint32 type, const char *comment, void *state)
2193 SMBCFILE *dir = (SMBCFILE *)state;
2194 int dirent_type;
2197 * We need to process the type a little ...
2199 * Disk share = 0x00000000
2200 * Print share = 0x00000001
2201 * Comms share = 0x00000002 (obsolete?)
2202 * IPC$ share = 0x00000003
2204 * administrative shares:
2205 * ADMIN$, IPC$, C$, D$, E$ ... are type |= 0x80000000
2208 if (dir->dir_type == SMBC_FILE_SHARE) {
2210 switch (type) {
2211 case 0 | 0x80000000:
2212 case 0:
2213 dirent_type = SMBC_FILE_SHARE;
2214 break;
2216 case 1:
2217 dirent_type = SMBC_PRINTER_SHARE;
2218 break;
2220 case 2:
2221 dirent_type = SMBC_COMMS_SHARE;
2222 break;
2224 case 3 | 0x80000000:
2225 case 3:
2226 dirent_type = SMBC_IPC_SHARE;
2227 break;
2229 default:
2230 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2231 break;
2234 else {
2235 dirent_type = dir->dir_type;
2238 if (add_dirent(dir, name, comment, dirent_type) < 0) {
2240 /* An error occurred, what do we do? */
2241 /* FIXME: Add some code here */
2246 static void
2247 dir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
2250 if (add_dirent((SMBCFILE *)state, finfo->name, "",
2251 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2253 /* Handle an error ... */
2255 /* FIXME: Add some code ... */
2261 static int
2262 net_share_enum_rpc(struct cli_state *cli,
2263 void (*fn)(const char *name,
2264 uint32 type,
2265 const char *comment,
2266 void *state),
2267 void *state)
2269 int i;
2270 WERROR result;
2271 ENUM_HND enum_hnd;
2272 uint32 info_level = 1;
2273 uint32 preferred_len = 0xffffffff;
2274 uint32 type;
2275 SRV_SHARE_INFO_CTR ctr;
2276 fstring name = "";
2277 fstring comment = "";
2278 void *mem_ctx;
2279 struct rpc_pipe_client *pipe_hnd;
2280 NTSTATUS nt_status;
2282 /* Open the server service pipe */
2283 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2284 if (!pipe_hnd) {
2285 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2286 return -1;
2289 /* Allocate a context for parsing and for the entries in "ctr" */
2290 mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2291 if (mem_ctx == NULL) {
2292 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2293 cli_rpc_pipe_close(pipe_hnd);
2294 return -1;
2297 /* Issue the NetShareEnum RPC call and retrieve the response */
2298 init_enum_hnd(&enum_hnd, 0);
2299 result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2300 mem_ctx,
2301 info_level,
2302 &ctr,
2303 preferred_len,
2304 &enum_hnd);
2306 /* Was it successful? */
2307 if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2308 /* Nope. Go clean up. */
2309 goto done;
2312 /* For each returned entry... */
2313 for (i = 0; i < ctr.num_entries; i++) {
2315 /* pull out the share name */
2316 rpcstr_pull_unistr2_fstring(
2317 name, &ctr.share.info1[i].info_1_str.uni_netname);
2319 /* pull out the share's comment */
2320 rpcstr_pull_unistr2_fstring(
2321 comment, &ctr.share.info1[i].info_1_str.uni_remark);
2323 /* Get the type value */
2324 type = ctr.share.info1[i].info_1.type;
2326 /* Add this share to the list */
2327 (*fn)(name, type, comment, state);
2330 done:
2331 /* Close the server service pipe */
2332 cli_rpc_pipe_close(pipe_hnd);
2334 /* Free all memory which was allocated for this request */
2335 talloc_free(mem_ctx);
2337 /* Tell 'em if it worked */
2338 return W_ERROR_IS_OK(result) ? 0 : -1;
2343 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
2345 fstring server, share, user, password, options;
2346 pstring workgroup;
2347 pstring path;
2348 uint16 mode;
2349 char *p;
2350 SMBCSRV *srv = NULL;
2351 SMBCFILE *dir = NULL;
2352 struct in_addr rem_ip;
2354 if (!context || !context->internal ||
2355 !context->internal->_initialized) {
2356 DEBUG(4, ("no valid context\n"));
2357 errno = EINVAL + 8192;
2358 return NULL;
2362 if (!fname) {
2363 DEBUG(4, ("no valid fname\n"));
2364 errno = EINVAL + 8193;
2365 return NULL;
2368 if (smbc_parse_path(context, fname,
2369 server, sizeof(server),
2370 share, sizeof(share),
2371 path, sizeof(path),
2372 user, sizeof(user),
2373 password, sizeof(password),
2374 options, sizeof(options))) {
2375 DEBUG(4, ("no valid path\n"));
2376 errno = EINVAL + 8194;
2377 return NULL;
2380 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
2382 /* Ensure the options are valid */
2383 if (smbc_check_options(server, share, path, options)) {
2384 DEBUG(4, ("unacceptable options (%s)\n", options));
2385 errno = EINVAL + 8195;
2386 return NULL;
2389 if (user[0] == (char)0) fstrcpy(user, context->user);
2391 pstrcpy(workgroup, context->workgroup);
2393 dir = SMB_MALLOC_P(SMBCFILE);
2395 if (!dir) {
2397 errno = ENOMEM;
2398 return NULL;
2402 ZERO_STRUCTP(dir);
2404 dir->cli_fd = 0;
2405 dir->fname = SMB_STRDUP(fname);
2406 dir->srv = NULL;
2407 dir->offset = 0;
2408 dir->file = False;
2409 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2411 if (server[0] == (char)0) {
2413 int i;
2414 int count;
2415 int max_lmb_count;
2416 struct ip_service *ip_list;
2417 struct ip_service server_addr;
2418 struct user_auth_info u_info;
2419 struct cli_state *cli;
2421 if (share[0] != (char)0 || path[0] != (char)0) {
2423 errno = EINVAL + 8196;
2424 if (dir) {
2425 SAFE_FREE(dir->fname);
2426 SAFE_FREE(dir);
2428 return NULL;
2431 /* Determine how many local master browsers to query */
2432 max_lmb_count = (context->options.browse_max_lmb_count == 0
2433 ? INT_MAX
2434 : context->options.browse_max_lmb_count);
2436 pstrcpy(u_info.username, user);
2437 pstrcpy(u_info.password, password);
2440 * We have server and share and path empty but options
2441 * requesting that we scan all master browsers for their list
2442 * of workgroups/domains. This implies that we must first try
2443 * broadcast queries to find all master browsers, and if that
2444 * doesn't work, then try our other methods which return only
2445 * a single master browser.
2448 ip_list = NULL;
2449 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2451 SAFE_FREE(ip_list);
2453 if (!find_master_ip(workgroup, &server_addr.ip)) {
2455 errno = ENOENT;
2456 return NULL;
2459 ip_list = &server_addr;
2460 count = 1;
2463 for (i = 0; i < count && i < max_lmb_count; i++) {
2464 DEBUG(99, ("Found master browser %d of %d: %s\n", i+1, MAX(count, max_lmb_count), inet_ntoa(ip_list[i].ip)));
2466 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2467 /* cli == NULL is the master browser refused to talk or
2468 could not be found */
2469 if ( !cli )
2470 continue;
2472 fstrcpy(server, cli->desthost);
2473 cli_shutdown(cli);
2475 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2478 * For each returned master browser IP address, get a
2479 * connection to IPC$ on the server if we do not
2480 * already have one, and determine the
2481 * workgroups/domains that it knows about.
2484 srv = smbc_server(context, server,
2485 "IPC$", workgroup, user, password);
2486 if (!srv) {
2487 continue;
2490 dir->srv = srv;
2491 dir->dir_type = SMBC_WORKGROUP;
2493 /* Now, list the stuff ... */
2495 if (!cli_NetServerEnum(&srv->cli,
2496 workgroup,
2497 SV_TYPE_DOMAIN_ENUM,
2498 list_unique_wg_fn,
2499 (void *)dir)) {
2500 continue;
2504 SAFE_FREE(ip_list);
2505 } else {
2507 * Server not an empty string ... Check the rest and see what
2508 * gives
2510 if (share[0] == (char)0) {
2512 if (path[0] != (char)0) { /* Should not have empty share with path */
2514 errno = EINVAL + 8197;
2515 if (dir) {
2516 SAFE_FREE(dir->fname);
2517 SAFE_FREE(dir);
2519 return NULL;
2523 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2524 /* However, we check to see if <server> is an IP address first */
2526 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2527 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2528 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2529 fstring buserver;
2531 dir->dir_type = SMBC_SERVER;
2534 * Get the backup list ...
2538 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2540 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2541 errno = EPERM; /* FIXME, is this correct */
2542 return NULL;
2547 * Get a connection to IPC$ on the server if we do not already have one
2550 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2552 if (!srv) {
2553 DEBUG(0, ("got no contact to IPC$\n"));
2554 if (dir) {
2555 SAFE_FREE(dir->fname);
2556 SAFE_FREE(dir);
2558 return NULL;
2562 dir->srv = srv;
2564 /* Now, list the servers ... */
2566 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2567 (void *)dir)) {
2569 if (dir) {
2570 SAFE_FREE(dir->fname);
2571 SAFE_FREE(dir);
2573 return NULL;
2577 else {
2579 if (resolve_name(server, &rem_ip, 0x20)) {
2581 /* Now, list the shares ... */
2583 dir->dir_type = SMBC_FILE_SHARE;
2585 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2587 if (!srv) {
2589 if (dir) {
2590 SAFE_FREE(dir->fname);
2591 SAFE_FREE(dir);
2593 return NULL;
2597 dir->srv = srv;
2599 /* Now, list the servers ... */
2601 if (net_share_enum_rpc(
2602 &srv->cli,
2603 list_fn,
2604 (void *) dir) < 0 &&
2605 cli_RNetShareEnum(
2606 &srv->cli,
2607 list_fn,
2608 (void *)dir) < 0) {
2610 errno = cli_errno(&srv->cli);
2611 if (dir) {
2612 SAFE_FREE(dir->fname);
2613 SAFE_FREE(dir);
2615 return NULL;
2620 else {
2622 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2623 if (dir) {
2624 SAFE_FREE(dir->fname);
2625 SAFE_FREE(dir);
2627 return NULL;
2634 else { /* The server and share are specified ... work from there ... */
2635 pstring targetpath;
2636 struct cli_state *targetcli;
2638 /* Well, we connect to the server and list the directory */
2640 dir->dir_type = SMBC_FILE_SHARE;
2642 srv = smbc_server(context, server, share, workgroup, user, password);
2644 if (!srv) {
2646 if (dir) {
2647 SAFE_FREE(dir->fname);
2648 SAFE_FREE(dir);
2650 return NULL;
2654 dir->srv = srv;
2656 /* Now, list the files ... */
2658 p = path + strlen(path);
2659 pstrcat(path, "\\*");
2661 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2663 d_printf("Could not resolve %s\n", path);
2664 return NULL;
2667 if (cli_list(targetcli, targetpath, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2668 (void *)dir) < 0) {
2670 if (dir) {
2671 SAFE_FREE(dir->fname);
2672 SAFE_FREE(dir);
2674 errno = smbc_errno(context, targetcli);
2676 if (errno == EINVAL) {
2678 * See if they asked to opendir something
2679 * other than a directory. If so, the
2680 * converted error value we got would have
2681 * been EINVAL rather than ENOTDIR.
2683 *p = '\0'; /* restore original path */
2685 if (smbc_getatr(context, srv, path,
2686 &mode, NULL,
2687 NULL, NULL, NULL,
2688 NULL) &&
2689 ! IS_DOS_DIR(mode)) {
2691 /* It is. Correct the error value */
2692 errno = ENOTDIR;
2696 return NULL;
2703 DLIST_ADD(context->internal->_files, dir);
2704 return dir;
2709 * Routine to close a directory
2712 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2715 if (!context || !context->internal ||
2716 !context->internal->_initialized) {
2718 errno = EINVAL;
2719 return -1;
2723 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2725 errno = EBADF;
2726 return -1;
2730 smbc_remove_dir(dir); /* Clean it up */
2732 DLIST_REMOVE(context->internal->_files, dir);
2734 if (dir) {
2736 SAFE_FREE(dir->fname);
2737 SAFE_FREE(dir); /* Free the space too */
2740 return 0;
2744 static void smbc_readdir_internal(SMBCCTX * context,
2745 struct smbc_dirent *dest,
2746 struct smbc_dirent *src,
2747 int max_namebuf_len)
2749 if (context->options.urlencode_readdir_entries) {
2751 /* url-encode the name. get back remaining buffer space */
2752 max_namebuf_len =
2753 smbc_urlencode(dest->name, src->name, max_namebuf_len);
2755 /* We now know the name length */
2756 dest->namelen = strlen(dest->name);
2758 /* Save the pointer to the beginning of the comment */
2759 dest->comment = dest->name + dest->namelen + 1;
2761 /* Copy the comment */
2762 strncpy(dest->comment, src->comment, max_namebuf_len);
2764 /* Ensure the comment is null terminated */
2765 if (max_namebuf_len > src->commentlen) {
2766 dest->comment[src->commentlen] = '\0';
2767 } else {
2768 dest->comment[max_namebuf_len - 1] = '\0';
2771 /* Save other fields */
2772 dest->smbc_type = src->smbc_type;
2773 dest->commentlen = strlen(dest->comment);
2774 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
2775 (char *) dest);
2776 } else {
2778 /* No encoding. Just copy the entry as is. */
2779 memcpy(dest, src, src->dirlen);
2780 dest->comment = (char *)(&dest->name + src->namelen + 1);
2786 * Routine to get a directory entry
2789 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2791 int maxlen;
2792 struct smbc_dirent *dirp, *dirent;
2794 /* Check that all is ok first ... */
2796 if (!context || !context->internal ||
2797 !context->internal->_initialized) {
2799 errno = EINVAL;
2800 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2801 return NULL;
2805 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2807 errno = EBADF;
2808 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2809 return NULL;
2813 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2815 errno = ENOTDIR;
2816 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2817 return NULL;
2821 if (!dir->dir_next) {
2822 return NULL;
2825 dirent = dir->dir_next->dirent;
2826 if (!dirent) {
2828 errno = ENOENT;
2829 return NULL;
2833 dirp = (struct smbc_dirent *)context->internal->_dirent;
2834 maxlen = (sizeof(context->internal->_dirent) -
2835 sizeof(struct smbc_dirent));
2837 smbc_readdir_internal(context, dirp, dirent, maxlen);
2839 dir->dir_next = dir->dir_next->next;
2841 return dirp;
2845 * Routine to get directory entries
2848 static int smbc_getdents_ctx(SMBCCTX *context,
2849 SMBCFILE *dir,
2850 struct smbc_dirent *dirp,
2851 int count)
2853 int rem = count;
2854 int reqd;
2855 int maxlen;
2856 char *ndir = (char *)dirp;
2857 struct smbc_dir_list *dirlist;
2859 /* Check that all is ok first ... */
2861 if (!context || !context->internal ||
2862 !context->internal->_initialized) {
2864 errno = EINVAL;
2865 return -1;
2869 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2871 errno = EBADF;
2872 return -1;
2876 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2878 errno = ENOTDIR;
2879 return -1;
2884 * Now, retrieve the number of entries that will fit in what was passed
2885 * We have to figure out if the info is in the list, or we need to
2886 * send a request to the server to get the info.
2889 while ((dirlist = dir->dir_next)) {
2890 struct smbc_dirent *dirent;
2892 if (!dirlist->dirent) {
2894 errno = ENOENT; /* Bad error */
2895 return -1;
2899 /* Do urlencoding of next entry, if so selected */
2900 dirent = (struct smbc_dirent *)context->internal->_dirent;
2901 maxlen = (sizeof(context->internal->_dirent) -
2902 sizeof(struct smbc_dirent));
2903 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
2905 reqd = dirent->dirlen;
2907 if (rem < reqd) {
2909 if (rem < count) { /* We managed to copy something */
2911 errno = 0;
2912 return count - rem;
2915 else { /* Nothing copied ... */
2917 errno = EINVAL; /* Not enough space ... */
2918 return -1;
2924 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2926 ((struct smbc_dirent *)ndir)->comment =
2927 (char *)(&((struct smbc_dirent *)ndir)->name +
2928 dirent->namelen +
2931 ndir += reqd;
2933 rem -= reqd;
2935 dir->dir_next = dirlist = dirlist -> next;
2938 if (rem == count)
2939 return 0;
2940 else
2941 return count - rem;
2946 * Routine to create a directory ...
2949 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2951 SMBCSRV *srv;
2952 fstring server, share, user, password, workgroup;
2953 pstring path, targetpath;
2954 struct cli_state *targetcli;
2956 if (!context || !context->internal ||
2957 !context->internal->_initialized) {
2959 errno = EINVAL;
2960 return -1;
2964 if (!fname) {
2966 errno = EINVAL;
2967 return -1;
2971 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2973 if (smbc_parse_path(context, fname,
2974 server, sizeof(server),
2975 share, sizeof(share),
2976 path, sizeof(path),
2977 user, sizeof(user),
2978 password, sizeof(password),
2979 NULL, 0)) {
2980 errno = EINVAL;
2981 return -1;
2984 if (user[0] == (char)0) fstrcpy(user, context->user);
2986 fstrcpy(workgroup, context->workgroup);
2988 srv = smbc_server(context, server, share, workgroup, user, password);
2990 if (!srv) {
2992 return -1; /* errno set by smbc_server */
2996 /*d_printf(">>>mkdir: resolving %s\n", path);*/
2997 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
2999 d_printf("Could not resolve %s\n", path);
3000 return -1;
3002 /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3004 if (!cli_mkdir(targetcli, targetpath)) {
3006 errno = smbc_errno(context, targetcli);
3007 return -1;
3011 return 0;
3016 * Our list function simply checks to see if a directory is not empty
3019 static int smbc_rmdir_dirempty = True;
3021 static void rmdir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
3024 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
3025 smbc_rmdir_dirempty = False;
3030 * Routine to remove a directory
3033 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
3035 SMBCSRV *srv;
3036 fstring server, share, user, password, workgroup;
3037 pstring path, targetpath;
3038 struct cli_state *targetcli;
3040 if (!context || !context->internal ||
3041 !context->internal->_initialized) {
3043 errno = EINVAL;
3044 return -1;
3048 if (!fname) {
3050 errno = EINVAL;
3051 return -1;
3055 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3057 if (smbc_parse_path(context, fname,
3058 server, sizeof(server),
3059 share, sizeof(share),
3060 path, sizeof(path),
3061 user, sizeof(user),
3062 password, sizeof(password),
3063 NULL, 0))
3065 errno = EINVAL;
3066 return -1;
3069 if (user[0] == (char)0) fstrcpy(user, context->user);
3071 fstrcpy(workgroup, context->workgroup);
3073 srv = smbc_server(context, server, share, workgroup, user, password);
3075 if (!srv) {
3077 return -1; /* errno set by smbc_server */
3081 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
3083 mode = aDIR | aRONLY;
3086 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
3088 if (strcmp(path, "\\") == 0) {
3090 mode = aDIR | aRONLY;
3093 else {
3095 mode = aRONLY;
3096 smbc_stat_printjob(srv, path, &size, &m_time);
3097 c_time = a_time = m_time;
3100 else { */
3102 /*d_printf(">>>rmdir: resolving %s\n", path);*/
3103 if (!cli_resolve_path( "", &srv->cli, path, &targetcli, targetpath))
3105 d_printf("Could not resolve %s\n", path);
3106 return -1;
3108 /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3111 if (!cli_rmdir(targetcli, targetpath)) {
3113 errno = smbc_errno(context, targetcli);
3115 if (errno == EACCES) { /* Check if the dir empty or not */
3117 pstring lpath; /* Local storage to avoid buffer overflows */
3119 smbc_rmdir_dirempty = True; /* Make this so ... */
3121 pstrcpy(lpath, targetpath);
3122 pstrcat(lpath, "\\*");
3124 if (cli_list(targetcli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
3125 NULL) < 0) {
3127 /* Fix errno to ignore latest error ... */
3129 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
3130 smbc_errno(context, targetcli)));
3131 errno = EACCES;
3135 if (smbc_rmdir_dirempty)
3136 errno = EACCES;
3137 else
3138 errno = ENOTEMPTY;
3142 return -1;
3146 return 0;
3151 * Routine to return the current directory position
3154 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
3156 off_t ret_val; /* Squash warnings about cast */
3158 if (!context || !context->internal ||
3159 !context->internal->_initialized) {
3161 errno = EINVAL;
3162 return -1;
3166 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3168 errno = EBADF;
3169 return -1;
3173 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3175 errno = ENOTDIR;
3176 return -1;
3181 * We return the pointer here as the offset
3183 ret_val = (off_t)(long)dir->dir_next;
3184 return ret_val;
3189 * A routine to run down the list and see if the entry is OK
3192 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
3193 struct smbc_dirent *dirent)
3196 /* Run down the list looking for what we want */
3198 if (dirent) {
3200 struct smbc_dir_list *tmp = list;
3202 while (tmp) {
3204 if (tmp->dirent == dirent)
3205 return tmp;
3207 tmp = tmp->next;
3213 return NULL; /* Not found, or an error */
3219 * Routine to seek on a directory
3222 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
3224 long int l_offset = offset; /* Handle problems of size */
3225 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3226 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3228 if (!context || !context->internal ||
3229 !context->internal->_initialized) {
3231 errno = EINVAL;
3232 return -1;
3236 if (dir->file != False) { /* FIXME, should be dir, perhaps */
3238 errno = ENOTDIR;
3239 return -1;
3243 /* Now, check what we were passed and see if it is OK ... */
3245 if (dirent == NULL) { /* Seek to the begining of the list */
3247 dir->dir_next = dir->dir_list;
3248 return 0;
3252 /* Now, run down the list and make sure that the entry is OK */
3253 /* This may need to be changed if we change the format of the list */
3255 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3257 errno = EINVAL; /* Bad entry */
3258 return -1;
3262 dir->dir_next = list_ent;
3264 return 0;
3269 * Routine to fstat a dir
3272 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
3275 if (!context || !context->internal ||
3276 !context->internal->_initialized) {
3278 errno = EINVAL;
3279 return -1;
3283 /* No code yet ... */
3285 return 0;
3289 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
3291 SMBCSRV *srv;
3292 fstring server, share, user, password, workgroup;
3293 pstring path;
3294 uint16 mode;
3296 if (!context || !context->internal ||
3297 !context->internal->_initialized) {
3299 errno = EINVAL; /* Best I can think of ... */
3300 return -1;
3304 if (!fname) {
3306 errno = EINVAL;
3307 return -1;
3311 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3313 if (smbc_parse_path(context, fname,
3314 server, sizeof(server),
3315 share, sizeof(share),
3316 path, sizeof(path),
3317 user, sizeof(user),
3318 password, sizeof(password),
3319 NULL, 0)) {
3320 errno = EINVAL;
3321 return -1;
3324 if (user[0] == (char)0) fstrcpy(user, context->user);
3326 fstrcpy(workgroup, context->workgroup);
3328 srv = smbc_server(context, server, share, workgroup, user, password);
3330 if (!srv) {
3331 return -1; /* errno set by smbc_server */
3334 mode = 0;
3336 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3337 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3338 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3339 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3341 if (!cli_setatr(&srv->cli, path, mode, 0)) {
3342 errno = smbc_errno(context, &srv->cli);
3343 return -1;
3346 return 0;
3349 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
3351 SMBCSRV *srv;
3352 fstring server, share, user, password, workgroup;
3353 pstring path;
3354 time_t a_time;
3355 time_t m_time;
3357 if (!context || !context->internal ||
3358 !context->internal->_initialized) {
3360 errno = EINVAL; /* Best I can think of ... */
3361 return -1;
3365 if (!fname) {
3367 errno = EINVAL;
3368 return -1;
3372 if (tbuf == NULL) {
3373 a_time = m_time = time(NULL);
3374 } else {
3375 a_time = tbuf[0].tv_sec;
3376 m_time = tbuf[1].tv_sec;
3379 if (DEBUGLVL(4))
3381 char *p;
3382 char atimebuf[32];
3383 char mtimebuf[32];
3385 strncpy(atimebuf, ctime(&a_time), sizeof(atimebuf));
3386 atimebuf[sizeof(atimebuf) - 1] = '\0';
3387 if ((p = strchr(atimebuf, '\n')) != NULL) {
3388 *p = '\0';
3391 strncpy(mtimebuf, ctime(&m_time), sizeof(mtimebuf));
3392 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3393 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3394 *p = '\0';
3397 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3398 fname, atimebuf, mtimebuf);
3401 if (smbc_parse_path(context, fname,
3402 server, sizeof(server),
3403 share, sizeof(share),
3404 path, sizeof(path),
3405 user, sizeof(user),
3406 password, sizeof(password),
3407 NULL, 0)) {
3408 errno = EINVAL;
3409 return -1;
3412 if (user[0] == (char)0) fstrcpy(user, context->user);
3414 fstrcpy(workgroup, context->workgroup);
3416 srv = smbc_server(context, server, share, workgroup, user, password);
3418 if (!srv) {
3419 return -1; /* errno set by smbc_server */
3422 if (!smbc_setatr(context, srv, path, 0, a_time, m_time, 0)) {
3423 return -1; /* errno set by smbc_setatr */
3426 return 0;
3430 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3431 However NT4 gives a "The information may have been modified by a
3432 computer running Windows NT 5.0" if denied ACEs do not appear before
3433 allowed ACEs. */
3435 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
3437 if (sec_ace_equal(ace1, ace2))
3438 return 0;
3440 if (ace1->type != ace2->type)
3441 return ace2->type - ace1->type;
3443 if (sid_compare(&ace1->trustee, &ace2->trustee))
3444 return sid_compare(&ace1->trustee, &ace2->trustee);
3446 if (ace1->flags != ace2->flags)
3447 return ace1->flags - ace2->flags;
3449 if (ace1->info.mask != ace2->info.mask)
3450 return ace1->info.mask - ace2->info.mask;
3452 if (ace1->size != ace2->size)
3453 return ace1->size - ace2->size;
3455 return memcmp(ace1, ace2, sizeof(SEC_ACE));
3459 static void sort_acl(SEC_ACL *the_acl)
3461 uint32 i;
3462 if (!the_acl) return;
3464 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
3466 for (i=1;i<the_acl->num_aces;) {
3467 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3468 int j;
3469 for (j=i; j<the_acl->num_aces-1; j++) {
3470 the_acl->ace[j] = the_acl->ace[j+1];
3472 the_acl->num_aces--;
3473 } else {
3474 i++;
3479 /* convert a SID to a string, either numeric or username/group */
3480 static void convert_sid_to_string(struct cli_state *ipc_cli,
3481 POLICY_HND *pol,
3482 fstring str,
3483 BOOL numeric,
3484 DOM_SID *sid)
3486 char **domains = NULL;
3487 char **names = NULL;
3488 uint32 *types = NULL;
3489 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3490 sid_to_string(str, sid);
3492 if (numeric) {
3493 return; /* no lookup desired */
3496 if (!pipe_hnd) {
3497 return;
3500 /* Ask LSA to convert the sid to a name */
3502 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,
3503 pol, 1, sid, &domains,
3504 &names, &types)) ||
3505 !domains || !domains[0] || !names || !names[0]) {
3506 return;
3509 /* Converted OK */
3511 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3512 domains[0], lp_winbind_separator(),
3513 names[0]);
3516 /* convert a string to a SID, either numeric or username/group */
3517 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
3518 POLICY_HND *pol,
3519 BOOL numeric,
3520 DOM_SID *sid,
3521 const char *str)
3523 uint32 *types = NULL;
3524 DOM_SID *sids = NULL;
3525 BOOL result = True;
3526 struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3528 if (!pipe_hnd) {
3529 return False;
3532 if (numeric) {
3533 if (strncmp(str, "S-", 2) == 0) {
3534 return string_to_sid(sid, str);
3537 result = False;
3538 goto done;
3541 if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx,
3542 pol, 1, &str, &sids,
3543 &types))) {
3544 result = False;
3545 goto done;
3548 sid_copy(sid, &sids[0]);
3549 done:
3551 return result;
3555 /* parse an ACE in the same format as print_ace() */
3556 static BOOL parse_ace(struct cli_state *ipc_cli,
3557 POLICY_HND *pol,
3558 SEC_ACE *ace,
3559 BOOL numeric,
3560 char *str)
3562 char *p;
3563 const char *cp;
3564 fstring tok;
3565 unsigned atype, aflags, amask;
3566 DOM_SID sid;
3567 SEC_ACCESS mask;
3568 const struct perm_value *v;
3569 struct perm_value {
3570 const char *perm;
3571 uint32 mask;
3574 /* These values discovered by inspection */
3575 static const struct perm_value special_values[] = {
3576 { "R", 0x00120089 },
3577 { "W", 0x00120116 },
3578 { "X", 0x001200a0 },
3579 { "D", 0x00010000 },
3580 { "P", 0x00040000 },
3581 { "O", 0x00080000 },
3582 { NULL, 0 },
3585 static const struct perm_value standard_values[] = {
3586 { "READ", 0x001200a9 },
3587 { "CHANGE", 0x001301bf },
3588 { "FULL", 0x001f01ff },
3589 { NULL, 0 },
3593 ZERO_STRUCTP(ace);
3594 p = strchr_m(str,':');
3595 if (!p) return False;
3596 *p = '\0';
3597 p++;
3598 /* Try to parse numeric form */
3600 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3601 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3602 goto done;
3605 /* Try to parse text form */
3607 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3608 return False;
3611 cp = p;
3612 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3613 return False;
3616 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3617 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3618 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3619 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3620 } else {
3621 return False;
3624 /* Only numeric form accepted for flags at present */
3626 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3627 sscanf(tok, "%i", &aflags))) {
3628 return False;
3631 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3632 return False;
3635 if (strncmp(tok, "0x", 2) == 0) {
3636 if (sscanf(tok, "%i", &amask) != 1) {
3637 return False;
3639 goto done;
3642 for (v = standard_values; v->perm; v++) {
3643 if (strcmp(tok, v->perm) == 0) {
3644 amask = v->mask;
3645 goto done;
3649 p = tok;
3651 while(*p) {
3652 BOOL found = False;
3654 for (v = special_values; v->perm; v++) {
3655 if (v->perm[0] == *p) {
3656 amask |= v->mask;
3657 found = True;
3661 if (!found) return False;
3662 p++;
3665 if (*p) {
3666 return False;
3669 done:
3670 mask.mask = amask;
3671 init_sec_ace(ace, &sid, atype, mask, aflags);
3672 return True;
3675 /* add an ACE to a list of ACEs in a SEC_ACL */
3676 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3678 SEC_ACL *newacl;
3679 SEC_ACE *aces;
3680 if (! *the_acl) {
3681 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3682 return True;
3685 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3686 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3687 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3688 newacl = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3689 SAFE_FREE(aces);
3690 (*the_acl) = newacl;
3691 return True;
3695 /* parse a ascii version of a security descriptor */
3696 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3697 struct cli_state *ipc_cli,
3698 POLICY_HND *pol,
3699 BOOL numeric,
3700 char *str)
3702 const char *p = str;
3703 fstring tok;
3704 SEC_DESC *ret;
3705 size_t sd_size;
3706 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3707 SEC_ACL *dacl=NULL;
3708 int revision=1;
3710 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3712 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3713 revision = strtol(tok+9, NULL, 16);
3714 continue;
3717 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3718 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3719 if (!owner_sid ||
3720 !convert_string_to_sid(ipc_cli, pol,
3721 numeric,
3722 owner_sid, tok+6)) {
3723 DEBUG(5, ("Failed to parse owner sid\n"));
3724 return NULL;
3726 continue;
3729 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3730 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3731 if (!owner_sid ||
3732 !convert_string_to_sid(ipc_cli, pol,
3733 False,
3734 owner_sid, tok+7)) {
3735 DEBUG(5, ("Failed to parse owner sid\n"));
3736 return NULL;
3738 continue;
3741 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3742 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3743 if (!grp_sid ||
3744 !convert_string_to_sid(ipc_cli, pol,
3745 numeric,
3746 grp_sid, tok+6)) {
3747 DEBUG(5, ("Failed to parse group sid\n"));
3748 return NULL;
3750 continue;
3753 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3754 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3755 if (!grp_sid ||
3756 !convert_string_to_sid(ipc_cli, pol,
3757 False,
3758 grp_sid, tok+6)) {
3759 DEBUG(5, ("Failed to parse group sid\n"));
3760 return NULL;
3762 continue;
3765 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3766 SEC_ACE ace;
3767 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3768 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3769 return NULL;
3771 if(!add_ace(&dacl, &ace, ctx)) {
3772 DEBUG(5, ("Failed to add ACL %s\n", tok));
3773 return NULL;
3775 continue;
3778 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3779 SEC_ACE ace;
3780 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3781 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3782 return NULL;
3784 if(!add_ace(&dacl, &ace, ctx)) {
3785 DEBUG(5, ("Failed to add ACL %s\n", tok));
3786 return NULL;
3788 continue;
3791 DEBUG(5, ("Failed to parse security descriptor\n"));
3792 return NULL;
3795 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3796 owner_sid, grp_sid, NULL, dacl, &sd_size);
3798 SAFE_FREE(grp_sid);
3799 SAFE_FREE(owner_sid);
3801 return ret;
3805 /* Obtain the current dos attributes */
3806 static DOS_ATTR_DESC *dos_attr_query(SMBCCTX *context,
3807 TALLOC_CTX *ctx,
3808 const char *filename,
3809 SMBCSRV *srv)
3811 time_t m_time = 0, a_time = 0, c_time = 0;
3812 SMB_OFF_T size = 0;
3813 uint16 mode = 0;
3814 SMB_INO_T inode = 0;
3815 DOS_ATTR_DESC *ret;
3817 ret = TALLOC_P(ctx, DOS_ATTR_DESC);
3818 if (!ret) {
3819 errno = ENOMEM;
3820 return NULL;
3823 /* Obtain the DOS attributes */
3824 if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
3825 &mode, &size,
3826 &c_time, &a_time, &m_time, &inode)) {
3828 errno = smbc_errno(context, &srv->cli);
3829 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
3830 return NULL;
3834 ret->mode = mode;
3835 ret->size = size;
3836 ret->a_time = a_time;
3837 ret->c_time = c_time;
3838 ret->m_time = m_time;
3839 ret->inode = inode;
3841 return ret;
3845 /* parse a ascii version of a security descriptor */
3846 static void dos_attr_parse(SMBCCTX *context,
3847 DOS_ATTR_DESC *dad,
3848 SMBCSRV *srv,
3849 char *str)
3851 const char *p = str;
3852 fstring tok;
3854 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3856 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
3857 dad->mode = strtol(tok+5, NULL, 16);
3858 continue;
3861 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
3862 dad->size = (SMB_OFF_T)atof(tok+5);
3863 continue;
3866 if (StrnCaseCmp(tok, "A_TIME:", 7) == 0) {
3867 dad->a_time = (time_t)strtol(tok+7, NULL, 10);
3868 continue;
3871 if (StrnCaseCmp(tok, "C_TIME:", 7) == 0) {
3872 dad->c_time = (time_t)strtol(tok+7, NULL, 10);
3873 continue;
3876 if (StrnCaseCmp(tok, "M_TIME:", 7) == 0) {
3877 dad->m_time = (time_t)strtol(tok+7, NULL, 10);
3878 continue;
3881 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
3882 dad->inode = (SMB_INO_T)atof(tok+6);
3883 continue;
3888 /*****************************************************
3889 Retrieve the acls for a file.
3890 *******************************************************/
3892 static int cacl_get(SMBCCTX *context, TALLOC_CTX *ctx, SMBCSRV *srv,
3893 struct cli_state *ipc_cli, POLICY_HND *pol,
3894 char *filename, char *attr_name, char *buf, int bufsize)
3896 uint32 i;
3897 int n = 0;
3898 int n_used;
3899 BOOL all;
3900 BOOL all_nt;
3901 BOOL all_nt_acls;
3902 BOOL all_dos;
3903 BOOL some_nt;
3904 BOOL some_dos;
3905 BOOL exclude_nt_revision = False;
3906 BOOL exclude_nt_owner = False;
3907 BOOL exclude_nt_group = False;
3908 BOOL exclude_nt_acl = False;
3909 BOOL exclude_dos_mode = False;
3910 BOOL exclude_dos_size = False;
3911 BOOL exclude_dos_ctime = False;
3912 BOOL exclude_dos_atime = False;
3913 BOOL exclude_dos_mtime = False;
3914 BOOL exclude_dos_inode = False;
3915 BOOL numeric = True;
3916 BOOL determine_size = (bufsize == 0);
3917 int fnum = -1;
3918 SEC_DESC *sd;
3919 fstring sidstr;
3920 fstring name_sandbox;
3921 char *name;
3922 char *pExclude;
3923 char *p;
3924 time_t m_time = 0, a_time = 0, c_time = 0;
3925 SMB_OFF_T size = 0;
3926 uint16 mode = 0;
3927 SMB_INO_T ino = 0;
3928 struct cli_state *cli = &srv->cli;
3930 /* Copy name so we can strip off exclusions (if any are specified) */
3931 strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
3933 /* Ensure name is null terminated */
3934 name_sandbox[sizeof(name_sandbox) - 1] = '\0';
3936 /* Play in the sandbox */
3937 name = name_sandbox;
3939 /* If there are any exclusions, point to them and mask them from name */
3940 if ((pExclude = strchr(name, '!')) != NULL)
3942 *pExclude++ = '\0';
3945 all = (StrnCaseCmp(name, "system.*", 8) == 0);
3946 all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
3947 all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
3948 all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
3949 some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
3950 some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
3951 numeric = (* (name + strlen(name) - 1) != '+');
3953 /* Look for exclusions from "all" requests */
3954 if (all || all_nt || all_dos) {
3956 /* Exclusions are delimited by '!' */
3957 for (; pExclude != NULL; pExclude = (p == NULL ? NULL : p + 1)) {
3959 /* Find end of this exclusion name */
3960 if ((p = strchr(pExclude, '!')) != NULL)
3962 *p = '\0';
3965 /* Which exclusion name is this? */
3966 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
3967 exclude_nt_revision = True;
3969 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
3970 exclude_nt_owner = True;
3972 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
3973 exclude_nt_group = True;
3975 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
3976 exclude_nt_acl = True;
3978 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
3979 exclude_dos_mode = True;
3981 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
3982 exclude_dos_size = True;
3984 else if (StrCaseCmp(pExclude, "dos_attr.c_time") == 0) {
3985 exclude_dos_ctime = True;
3987 else if (StrCaseCmp(pExclude, "dos_attr.a_time") == 0) {
3988 exclude_dos_atime = True;
3990 else if (StrCaseCmp(pExclude, "dos_attr.m_time") == 0) {
3991 exclude_dos_mtime = True;
3993 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
3994 exclude_dos_inode = True;
3996 else {
3997 DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
3998 pExclude));
3999 errno = ENOATTR;
4000 return -1;
4005 n_used = 0;
4008 * If we are (possibly) talking to an NT or new system and some NT
4009 * attributes have been requested...
4011 if (ipc_cli && (all || some_nt || all_nt_acls)) {
4012 /* Point to the portion after "system.nt_sec_desc." */
4013 name += 19; /* if (all) this will be invalid but unused */
4015 /* ... then obtain any NT attributes which were requested */
4016 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4018 if (fnum == -1) {
4019 DEBUG(5, ("cacl_get failed to open %s: %s\n",
4020 filename, cli_errstr(cli)));
4021 errno = 0;
4022 return -1;
4025 sd = cli_query_secdesc(cli, fnum, ctx);
4027 if (!sd) {
4028 DEBUG(5,
4029 ("cacl_get Failed to query old descriptor\n"));
4030 errno = 0;
4031 return -1;
4034 cli_close(cli, fnum);
4036 if (! exclude_nt_revision) {
4037 if (all || all_nt) {
4038 if (determine_size) {
4039 p = talloc_asprintf(ctx,
4040 "REVISION:%d",
4041 sd->revision);
4042 if (!p) {
4043 errno = ENOMEM;
4044 return -1;
4046 n = strlen(p);
4047 } else {
4048 n = snprintf(buf, bufsize,
4049 "REVISION:%d", sd->revision);
4051 } else if (StrCaseCmp(name, "revision") == 0) {
4052 if (determine_size) {
4053 p = talloc_asprintf(ctx, "%d",
4054 sd->revision);
4055 if (!p) {
4056 errno = ENOMEM;
4057 return -1;
4059 n = strlen(p);
4060 } else {
4061 n = snprintf(buf, bufsize, "%d",
4062 sd->revision);
4066 if (!determine_size && n > bufsize) {
4067 errno = ERANGE;
4068 return -1;
4070 buf += n;
4071 n_used += n;
4072 bufsize -= n;
4075 if (! exclude_nt_owner) {
4076 /* Get owner and group sid */
4077 if (sd->owner_sid) {
4078 convert_sid_to_string(ipc_cli, pol,
4079 sidstr,
4080 numeric,
4081 sd->owner_sid);
4082 } else {
4083 fstrcpy(sidstr, "");
4086 if (all || all_nt) {
4087 if (determine_size) {
4088 p = talloc_asprintf(ctx, ",OWNER:%s",
4089 sidstr);
4090 if (!p) {
4091 errno = ENOMEM;
4092 return -1;
4094 n = strlen(p);
4095 } else {
4096 n = snprintf(buf, bufsize,
4097 ",OWNER:%s", sidstr);
4099 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4100 if (determine_size) {
4101 p = talloc_asprintf(ctx, "%s", sidstr);
4102 if (!p) {
4103 errno = ENOMEM;
4104 return -1;
4106 n = strlen(p);
4107 } else {
4108 n = snprintf(buf, bufsize, "%s",
4109 sidstr);
4113 if (!determine_size && n > bufsize) {
4114 errno = ERANGE;
4115 return -1;
4117 buf += n;
4118 n_used += n;
4119 bufsize -= n;
4122 if (! exclude_nt_group) {
4123 if (sd->grp_sid) {
4124 convert_sid_to_string(ipc_cli, pol,
4125 sidstr, numeric,
4126 sd->grp_sid);
4127 } else {
4128 fstrcpy(sidstr, "");
4131 if (all || all_nt) {
4132 if (determine_size) {
4133 p = talloc_asprintf(ctx, ",GROUP:%s",
4134 sidstr);
4135 if (!p) {
4136 errno = ENOMEM;
4137 return -1;
4139 n = strlen(p);
4140 } else {
4141 n = snprintf(buf, bufsize,
4142 ",GROUP:%s", sidstr);
4144 } else if (StrnCaseCmp(name, "group", 5) == 0) {
4145 if (determine_size) {
4146 p = talloc_asprintf(ctx, "%s", sidstr);
4147 if (!p) {
4148 errno = ENOMEM;
4149 return -1;
4151 n = strlen(p);
4152 } else {
4153 n = snprintf(buf, bufsize, "%s", sidstr);
4157 if (!determine_size && n > bufsize) {
4158 errno = ERANGE;
4159 return -1;
4161 buf += n;
4162 n_used += n;
4163 bufsize -= n;
4166 if (! exclude_nt_acl) {
4167 /* Add aces to value buffer */
4168 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4170 SEC_ACE *ace = &sd->dacl->ace[i];
4171 convert_sid_to_string(ipc_cli, pol,
4172 sidstr, numeric,
4173 &ace->trustee);
4175 if (all || all_nt) {
4176 if (determine_size) {
4177 p = talloc_asprintf(
4178 ctx,
4179 ",ACL:"
4180 "%s:%d/%d/0x%08x",
4181 sidstr,
4182 ace->type,
4183 ace->flags,
4184 ace->info.mask);
4185 if (!p) {
4186 errno = ENOMEM;
4187 return -1;
4189 n = strlen(p);
4190 } else {
4191 n = snprintf(
4192 buf, bufsize,
4193 ",ACL:%s:%d/%d/0x%08x",
4194 sidstr,
4195 ace->type,
4196 ace->flags,
4197 ace->info.mask);
4199 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4200 StrCaseCmp(name + 3, sidstr) == 0) ||
4201 (StrnCaseCmp(name, "acl+", 4) == 0 &&
4202 StrCaseCmp(name + 4, sidstr) == 0)) {
4203 if (determine_size) {
4204 p = talloc_asprintf(
4205 ctx,
4206 "%d/%d/0x%08x",
4207 ace->type,
4208 ace->flags,
4209 ace->info.mask);
4210 if (!p) {
4211 errno = ENOMEM;
4212 return -1;
4214 n = strlen(p);
4215 } else {
4216 n = snprintf(buf, bufsize,
4217 "%d/%d/0x%08x",
4218 ace->type,
4219 ace->flags,
4220 ace->info.mask);
4222 } else if (all_nt_acls) {
4223 if (determine_size) {
4224 p = talloc_asprintf(
4225 ctx,
4226 "%s%s:%d/%d/0x%08x",
4227 i ? "," : "",
4228 sidstr,
4229 ace->type,
4230 ace->flags,
4231 ace->info.mask);
4232 if (!p) {
4233 errno = ENOMEM;
4234 return -1;
4236 n = strlen(p);
4237 } else {
4238 n = snprintf(buf, bufsize,
4239 "%s%s:%d/%d/0x%08x",
4240 i ? "," : "",
4241 sidstr,
4242 ace->type,
4243 ace->flags,
4244 ace->info.mask);
4247 if (n > bufsize) {
4248 errno = ERANGE;
4249 return -1;
4251 buf += n;
4252 n_used += n;
4253 bufsize -= n;
4257 /* Restore name pointer to its original value */
4258 name -= 19;
4261 if (all || some_dos) {
4262 /* Point to the portion after "system.dos_attr." */
4263 name += 16; /* if (all) this will be invalid but unused */
4265 /* Obtain the DOS attributes */
4266 if (!smbc_getatr(context, srv, filename, &mode, &size,
4267 &c_time, &a_time, &m_time, &ino)) {
4269 errno = smbc_errno(context, &srv->cli);
4270 return -1;
4274 if (! exclude_dos_mode) {
4275 if (all || all_dos) {
4276 if (determine_size) {
4277 p = talloc_asprintf(ctx,
4278 "%sMODE:0x%x",
4279 (ipc_cli &&
4280 (all || some_nt)
4281 ? ","
4282 : ""),
4283 mode);
4284 if (!p) {
4285 errno = ENOMEM;
4286 return -1;
4288 n = strlen(p);
4289 } else {
4290 n = snprintf(buf, bufsize,
4291 "%sMODE:0x%x",
4292 (ipc_cli &&
4293 (all || some_nt)
4294 ? ","
4295 : ""),
4296 mode);
4298 } else if (StrCaseCmp(name, "mode") == 0) {
4299 if (determine_size) {
4300 p = talloc_asprintf(ctx, "0x%x", mode);
4301 if (!p) {
4302 errno = ENOMEM;
4303 return -1;
4305 n = strlen(p);
4306 } else {
4307 n = snprintf(buf, bufsize, "0x%x", mode);
4311 if (!determine_size && n > bufsize) {
4312 errno = ERANGE;
4313 return -1;
4315 buf += n;
4316 n_used += n;
4317 bufsize -= n;
4320 if (! exclude_dos_size) {
4321 if (all || all_dos) {
4322 if (determine_size) {
4323 p = talloc_asprintf(
4324 ctx,
4325 ",SIZE:%.0f",
4326 (double)size);
4327 if (!p) {
4328 errno = ENOMEM;
4329 return -1;
4331 n = strlen(p);
4332 } else {
4333 n = snprintf(buf, bufsize,
4334 ",SIZE:%.0f",
4335 (double)size);
4337 } else if (StrCaseCmp(name, "size") == 0) {
4338 if (determine_size) {
4339 p = talloc_asprintf(
4340 ctx,
4341 "%.0f",
4342 (double)size);
4343 if (!p) {
4344 errno = ENOMEM;
4345 return -1;
4347 n = strlen(p);
4348 } else {
4349 n = snprintf(buf, bufsize,
4350 "%.0f",
4351 (double)size);
4355 if (!determine_size && n > bufsize) {
4356 errno = ERANGE;
4357 return -1;
4359 buf += n;
4360 n_used += n;
4361 bufsize -= n;
4364 if (! exclude_dos_ctime) {
4365 if (all || all_dos) {
4366 if (determine_size) {
4367 p = talloc_asprintf(ctx,
4368 ",C_TIME:%lu",
4369 c_time);
4370 if (!p) {
4371 errno = ENOMEM;
4372 return -1;
4374 n = strlen(p);
4375 } else {
4376 n = snprintf(buf, bufsize,
4377 ",C_TIME:%lu", c_time);
4379 } else if (StrCaseCmp(name, "c_time") == 0) {
4380 if (determine_size) {
4381 p = talloc_asprintf(ctx, "%lu", c_time);
4382 if (!p) {
4383 errno = ENOMEM;
4384 return -1;
4386 n = strlen(p);
4387 } else {
4388 n = snprintf(buf, bufsize, "%lu", c_time);
4392 if (!determine_size && n > bufsize) {
4393 errno = ERANGE;
4394 return -1;
4396 buf += n;
4397 n_used += n;
4398 bufsize -= n;
4401 if (! exclude_dos_atime) {
4402 if (all || all_dos) {
4403 if (determine_size) {
4404 p = talloc_asprintf(ctx,
4405 ",A_TIME:%lu",
4406 a_time);
4407 if (!p) {
4408 errno = ENOMEM;
4409 return -1;
4411 n = strlen(p);
4412 } else {
4413 n = snprintf(buf, bufsize,
4414 ",A_TIME:%lu", a_time);
4416 } else if (StrCaseCmp(name, "a_time") == 0) {
4417 if (determine_size) {
4418 p = talloc_asprintf(ctx, "%lu", a_time);
4419 if (!p) {
4420 errno = ENOMEM;
4421 return -1;
4423 n = strlen(p);
4424 } else {
4425 n = snprintf(buf, bufsize, "%lu", a_time);
4429 if (!determine_size && n > bufsize) {
4430 errno = ERANGE;
4431 return -1;
4433 buf += n;
4434 n_used += n;
4435 bufsize -= n;
4438 if (! exclude_dos_mtime) {
4439 if (all || all_dos) {
4440 if (determine_size) {
4441 p = talloc_asprintf(ctx,
4442 ",M_TIME:%lu",
4443 m_time);
4444 if (!p) {
4445 errno = ENOMEM;
4446 return -1;
4448 n = strlen(p);
4449 } else {
4450 n = snprintf(buf, bufsize,
4451 ",M_TIME:%lu", m_time);
4453 } else if (StrCaseCmp(name, "m_time") == 0) {
4454 if (determine_size) {
4455 p = talloc_asprintf(ctx, "%lu", m_time);
4456 if (!p) {
4457 errno = ENOMEM;
4458 return -1;
4460 n = strlen(p);
4461 } else {
4462 n = snprintf(buf, bufsize, "%lu", m_time);
4466 if (!determine_size && n > bufsize) {
4467 errno = ERANGE;
4468 return -1;
4470 buf += n;
4471 n_used += n;
4472 bufsize -= n;
4475 if (! exclude_dos_inode) {
4476 if (all || all_dos) {
4477 if (determine_size) {
4478 p = talloc_asprintf(
4479 ctx,
4480 ",INODE:%.0f",
4481 (double)ino);
4482 if (!p) {
4483 errno = ENOMEM;
4484 return -1;
4486 n = strlen(p);
4487 } else {
4488 n = snprintf(buf, bufsize,
4489 ",INODE:%.0f",
4490 (double) ino);
4492 } else if (StrCaseCmp(name, "inode") == 0) {
4493 if (determine_size) {
4494 p = talloc_asprintf(
4495 ctx,
4496 "%.0f",
4497 (double) ino);
4498 if (!p) {
4499 errno = ENOMEM;
4500 return -1;
4502 n = strlen(p);
4503 } else {
4504 n = snprintf(buf, bufsize,
4505 "%.0f",
4506 (double) ino);
4510 if (!determine_size && n > bufsize) {
4511 errno = ERANGE;
4512 return -1;
4514 buf += n;
4515 n_used += n;
4516 bufsize -= n;
4519 /* Restore name pointer to its original value */
4520 name -= 16;
4523 if (n_used == 0) {
4524 errno = ENOATTR;
4525 return -1;
4528 return n_used;
4532 /*****************************************************
4533 set the ACLs on a file given an ascii description
4534 *******************************************************/
4535 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
4536 struct cli_state *ipc_cli, POLICY_HND *pol,
4537 const char *filename, const char *the_acl,
4538 int mode, int flags)
4540 int fnum;
4541 int err = 0;
4542 SEC_DESC *sd = NULL, *old;
4543 SEC_ACL *dacl = NULL;
4544 DOM_SID *owner_sid = NULL;
4545 DOM_SID *grp_sid = NULL;
4546 uint32 i, j;
4547 size_t sd_size;
4548 int ret = 0;
4549 char *p;
4550 BOOL numeric = True;
4552 /* the_acl will be null for REMOVE_ALL operations */
4553 if (the_acl) {
4554 numeric = ((p = strchr(the_acl, ':')) != NULL &&
4555 p > the_acl &&
4556 p[-1] != '+');
4558 /* if this is to set the entire ACL... */
4559 if (*the_acl == '*') {
4560 /* ... then increment past the first colon */
4561 the_acl = p + 1;
4564 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
4565 CONST_DISCARD(char *, the_acl));
4567 if (!sd) {
4568 errno = EINVAL;
4569 return -1;
4573 /* The desired access below is the only one I could find that works
4574 with NT4, W2KP and Samba */
4576 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4578 if (fnum == -1) {
4579 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4580 filename, cli_errstr(cli)));
4581 errno = 0;
4582 return -1;
4585 old = cli_query_secdesc(cli, fnum, ctx);
4587 if (!old) {
4588 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
4589 errno = 0;
4590 return -1;
4593 cli_close(cli, fnum);
4595 switch (mode) {
4596 case SMBC_XATTR_MODE_REMOVE_ALL:
4597 old->dacl->num_aces = 0;
4598 SAFE_FREE(old->dacl->ace);
4599 SAFE_FREE(old->dacl);
4600 old->off_dacl = 0;
4601 dacl = old->dacl;
4602 break;
4604 case SMBC_XATTR_MODE_REMOVE:
4605 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4606 BOOL found = False;
4608 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4609 if (sec_ace_equal(&sd->dacl->ace[i],
4610 &old->dacl->ace[j])) {
4611 uint32 k;
4612 for (k=j; k<old->dacl->num_aces-1;k++) {
4613 old->dacl->ace[k] = old->dacl->ace[k+1];
4615 old->dacl->num_aces--;
4616 if (old->dacl->num_aces == 0) {
4617 SAFE_FREE(old->dacl->ace);
4618 SAFE_FREE(old->dacl);
4619 old->off_dacl = 0;
4621 found = True;
4622 dacl = old->dacl;
4623 break;
4627 if (!found) {
4628 err = ENOATTR;
4629 ret = -1;
4630 goto failed;
4633 break;
4635 case SMBC_XATTR_MODE_ADD:
4636 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4637 BOOL found = False;
4639 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
4640 if (sid_equal(&sd->dacl->ace[i].trustee,
4641 &old->dacl->ace[j].trustee)) {
4642 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
4643 err = EEXIST;
4644 ret = -1;
4645 goto failed;
4647 old->dacl->ace[j] = sd->dacl->ace[i];
4648 ret = -1;
4649 found = True;
4653 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
4654 err = ENOATTR;
4655 ret = -1;
4656 goto failed;
4659 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
4660 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
4663 dacl = old->dacl;
4664 break;
4666 case SMBC_XATTR_MODE_SET:
4667 old = sd;
4668 owner_sid = old->owner_sid;
4669 grp_sid = old->grp_sid;
4670 dacl = old->dacl;
4671 break;
4673 case SMBC_XATTR_MODE_CHOWN:
4674 owner_sid = sd->owner_sid;
4675 break;
4677 case SMBC_XATTR_MODE_CHGRP:
4678 grp_sid = sd->grp_sid;
4679 break;
4682 /* Denied ACE entries must come before allowed ones */
4683 sort_acl(old->dacl);
4685 /* Create new security descriptor and set it */
4686 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
4687 owner_sid, grp_sid, NULL, dacl, &sd_size);
4689 fnum = cli_nt_create(cli, filename,
4690 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
4692 if (fnum == -1) {
4693 DEBUG(5, ("cacl_set failed to open %s: %s\n",
4694 filename, cli_errstr(cli)));
4695 errno = 0;
4696 return -1;
4699 if (!cli_set_secdesc(cli, fnum, sd)) {
4700 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
4701 ret = -1;
4704 /* Clean up */
4706 failed:
4707 cli_close(cli, fnum);
4709 if (err != 0) {
4710 errno = err;
4713 return ret;
4717 int smbc_setxattr_ctx(SMBCCTX *context,
4718 const char *fname,
4719 const char *name,
4720 const void *value,
4721 size_t size,
4722 int flags)
4724 int ret;
4725 int ret2;
4726 SMBCSRV *srv;
4727 SMBCSRV *ipc_srv;
4728 fstring server, share, user, password, workgroup;
4729 pstring path;
4730 TALLOC_CTX *ctx;
4731 POLICY_HND pol;
4732 DOS_ATTR_DESC *dad;
4734 if (!context || !context->internal ||
4735 !context->internal->_initialized) {
4737 errno = EINVAL; /* Best I can think of ... */
4738 return -1;
4742 if (!fname) {
4744 errno = EINVAL;
4745 return -1;
4749 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n", fname, name, (int) size, (const char*)value));
4751 if (smbc_parse_path(context, fname,
4752 server, sizeof(server),
4753 share, sizeof(share),
4754 path, sizeof(path),
4755 user, sizeof(user),
4756 password, sizeof(password),
4757 NULL, 0)) {
4758 errno = EINVAL;
4759 return -1;
4762 if (user[0] == (char)0) fstrcpy(user, context->user);
4764 fstrcpy(workgroup, context->workgroup);
4766 srv = smbc_server(context, server, share, workgroup, user, password);
4767 if (!srv) {
4768 return -1; /* errno set by smbc_server */
4771 if (! srv->no_nt_session) {
4772 ipc_srv = smbc_attr_server(context, server, share,
4773 workgroup, user, password,
4774 &pol);
4775 srv->no_nt_session = True;
4776 } else {
4777 ipc_srv = NULL;
4780 ctx = talloc_init("smbc_setxattr");
4781 if (!ctx) {
4782 errno = ENOMEM;
4783 return -1;
4787 * Are they asking to set the entire set of known attributes?
4789 if (StrCaseCmp(name, "system.*") == 0 ||
4790 StrCaseCmp(name, "system.*+") == 0) {
4791 /* Yup. */
4792 char *namevalue =
4793 talloc_asprintf(ctx, "%s:%s", name+7, (const char *) value);
4794 if (! namevalue) {
4795 errno = ENOMEM;
4796 ret = -1;
4797 return -1;
4800 if (ipc_srv) {
4801 ret = cacl_set(ctx, &srv->cli,
4802 &ipc_srv->cli, &pol, path,
4803 namevalue,
4804 (*namevalue == '*'
4805 ? SMBC_XATTR_MODE_SET
4806 : SMBC_XATTR_MODE_ADD),
4807 flags);
4808 } else {
4809 ret = 0;
4812 /* get a DOS Attribute Descriptor with current attributes */
4813 dad = dos_attr_query(context, ctx, path, srv);
4814 if (dad) {
4815 /* Overwrite old with new, using what was provided */
4816 dos_attr_parse(context, dad, srv, namevalue);
4818 /* Set the new DOS attributes */
4819 if (! smbc_setatr(context, srv, path,
4820 dad->c_time,
4821 dad->a_time,
4822 dad->m_time,
4823 dad->mode)) {
4825 /* cause failure if NT failed too */
4826 dad = NULL;
4830 /* we only fail if both NT and DOS sets failed */
4831 if (ret < 0 && ! dad) {
4832 ret = -1; /* in case dad was null */
4834 else {
4835 ret = 0;
4838 talloc_destroy(ctx);
4839 return ret;
4843 * Are they asking to set an access control element or to set
4844 * the entire access control list?
4846 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
4847 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
4848 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
4849 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
4850 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
4852 /* Yup. */
4853 char *namevalue =
4854 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4856 if (! ipc_srv) {
4857 ret = -1; /* errno set by smbc_server() */
4859 else if (! namevalue) {
4860 errno = ENOMEM;
4861 ret = -1;
4862 } else {
4863 ret = cacl_set(ctx, &srv->cli,
4864 &ipc_srv->cli, &pol, path,
4865 namevalue,
4866 (*namevalue == '*'
4867 ? SMBC_XATTR_MODE_SET
4868 : SMBC_XATTR_MODE_ADD),
4869 flags);
4871 talloc_destroy(ctx);
4872 return ret;
4876 * Are they asking to set the owner?
4878 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
4879 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
4881 /* Yup. */
4882 char *namevalue =
4883 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4885 if (! ipc_srv) {
4887 ret = -1; /* errno set by smbc_server() */
4889 else if (! namevalue) {
4890 errno = ENOMEM;
4891 ret = -1;
4892 } else {
4893 ret = cacl_set(ctx, &srv->cli,
4894 &ipc_srv->cli, &pol, path,
4895 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4897 talloc_destroy(ctx);
4898 return ret;
4902 * Are they asking to set the group?
4904 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
4905 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
4907 /* Yup. */
4908 char *namevalue =
4909 talloc_asprintf(ctx, "%s:%s", name+19, (const char *) value);
4911 if (! ipc_srv) {
4912 /* errno set by smbc_server() */
4913 ret = -1;
4915 else if (! namevalue) {
4916 errno = ENOMEM;
4917 ret = -1;
4918 } else {
4919 ret = cacl_set(ctx, &srv->cli,
4920 &ipc_srv->cli, &pol, path,
4921 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
4923 talloc_destroy(ctx);
4924 return ret;
4928 * Are they asking to set a DOS attribute?
4930 if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
4931 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
4932 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
4933 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
4934 StrCaseCmp(name, "system.dos_attr.m_time") == 0) {
4936 /* get a DOS Attribute Descriptor with current attributes */
4937 dad = dos_attr_query(context, ctx, path, srv);
4938 if (dad) {
4939 char *namevalue =
4940 talloc_asprintf(ctx, "%s:%s", name+16, (const char *) value);
4941 if (! namevalue) {
4942 errno = ENOMEM;
4943 ret = -1;
4944 } else {
4945 /* Overwrite old with provided new params */
4946 dos_attr_parse(context, dad, srv, namevalue);
4948 /* Set the new DOS attributes */
4949 ret2 = smbc_setatr(context, srv, path,
4950 dad->c_time,
4951 dad->a_time,
4952 dad->m_time,
4953 dad->mode);
4955 /* ret2 has True (success) / False (failure) */
4956 if (ret2) {
4957 ret = 0;
4958 } else {
4959 ret = -1;
4962 } else {
4963 ret = -1;
4966 talloc_destroy(ctx);
4967 return ret;
4970 /* Unsupported attribute name */
4971 talloc_destroy(ctx);
4972 errno = EINVAL;
4973 return -1;
4976 int smbc_getxattr_ctx(SMBCCTX *context,
4977 const char *fname,
4978 const char *name,
4979 const void *value,
4980 size_t size)
4982 int ret;
4983 SMBCSRV *srv;
4984 SMBCSRV *ipc_srv;
4985 fstring server, share, user, password, workgroup;
4986 pstring path;
4987 TALLOC_CTX *ctx;
4988 POLICY_HND pol;
4991 if (!context || !context->internal ||
4992 !context->internal->_initialized) {
4994 errno = EINVAL; /* Best I can think of ... */
4995 return -1;
4999 if (!fname) {
5001 errno = EINVAL;
5002 return -1;
5006 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5008 if (smbc_parse_path(context, fname,
5009 server, sizeof(server),
5010 share, sizeof(share),
5011 path, sizeof(path),
5012 user, sizeof(user),
5013 password, sizeof(password),
5014 NULL, 0)) {
5015 errno = EINVAL;
5016 return -1;
5019 if (user[0] == (char)0) fstrcpy(user, context->user);
5021 fstrcpy(workgroup, context->workgroup);
5023 srv = smbc_server(context, server, share, workgroup, user, password);
5024 if (!srv) {
5025 return -1; /* errno set by smbc_server */
5028 if (! srv->no_nt_session) {
5029 ipc_srv = smbc_attr_server(context, server, share,
5030 workgroup, user, password,
5031 &pol);
5032 if (! ipc_srv) {
5033 srv->no_nt_session = True;
5035 } else {
5036 ipc_srv = NULL;
5039 ctx = talloc_init("smbc:getxattr");
5040 if (!ctx) {
5041 errno = ENOMEM;
5042 return -1;
5045 /* Are they requesting a supported attribute? */
5046 if (StrCaseCmp(name, "system.*") == 0 ||
5047 StrnCaseCmp(name, "system.*!", 9) == 0 ||
5048 StrCaseCmp(name, "system.*+") == 0 ||
5049 StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5050 StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5051 StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5052 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5053 StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5054 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5055 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5056 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5057 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5058 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5059 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5060 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5061 StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5062 StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5063 StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5064 StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5065 StrCaseCmp(name, "system.dos_attr.c_time") == 0 ||
5066 StrCaseCmp(name, "system.dos_attr.a_time") == 0 ||
5067 StrCaseCmp(name, "system.dos_attr.m_time") == 0 ||
5068 StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5070 /* Yup. */
5071 ret = cacl_get(context, ctx, srv,
5072 ipc_srv == NULL ? NULL : &ipc_srv->cli,
5073 &pol, path,
5074 CONST_DISCARD(char *, name),
5075 CONST_DISCARD(char *, value), size);
5076 if (ret < 0 && errno == 0) {
5077 errno = smbc_errno(context, &srv->cli);
5079 talloc_destroy(ctx);
5080 return ret;
5083 /* Unsupported attribute name */
5084 talloc_destroy(ctx);
5085 errno = EINVAL;
5086 return -1;
5090 int smbc_removexattr_ctx(SMBCCTX *context,
5091 const char *fname,
5092 const char *name)
5094 int ret;
5095 SMBCSRV *srv;
5096 SMBCSRV *ipc_srv;
5097 fstring server, share, user, password, workgroup;
5098 pstring path;
5099 TALLOC_CTX *ctx;
5100 POLICY_HND pol;
5102 if (!context || !context->internal ||
5103 !context->internal->_initialized) {
5105 errno = EINVAL; /* Best I can think of ... */
5106 return -1;
5110 if (!fname) {
5112 errno = EINVAL;
5113 return -1;
5117 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5119 if (smbc_parse_path(context, fname,
5120 server, sizeof(server),
5121 share, sizeof(share),
5122 path, sizeof(path),
5123 user, sizeof(user),
5124 password, sizeof(password),
5125 NULL, 0)) {
5126 errno = EINVAL;
5127 return -1;
5130 if (user[0] == (char)0) fstrcpy(user, context->user);
5132 fstrcpy(workgroup, context->workgroup);
5134 srv = smbc_server(context, server, share, workgroup, user, password);
5135 if (!srv) {
5136 return -1; /* errno set by smbc_server */
5139 if (! srv->no_nt_session) {
5140 ipc_srv = smbc_attr_server(context, server, share,
5141 workgroup, user, password,
5142 &pol);
5143 srv->no_nt_session = True;
5144 } else {
5145 ipc_srv = NULL;
5148 if (! ipc_srv) {
5149 return -1; /* errno set by smbc_attr_server */
5152 ctx = talloc_init("smbc_removexattr");
5153 if (!ctx) {
5154 errno = ENOMEM;
5155 return -1;
5158 /* Are they asking to set the entire ACL? */
5159 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5160 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5162 /* Yup. */
5163 ret = cacl_set(ctx, &srv->cli,
5164 &ipc_srv->cli, &pol, path,
5165 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5166 talloc_destroy(ctx);
5167 return ret;
5171 * Are they asking to remove one or more spceific security descriptor
5172 * attributes?
5174 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5175 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5176 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5177 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5178 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5179 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5180 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5182 /* Yup. */
5183 ret = cacl_set(ctx, &srv->cli,
5184 &ipc_srv->cli, &pol, path,
5185 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5186 talloc_destroy(ctx);
5187 return ret;
5190 /* Unsupported attribute name */
5191 talloc_destroy(ctx);
5192 errno = EINVAL;
5193 return -1;
5196 int smbc_listxattr_ctx(SMBCCTX *context,
5197 const char *fname,
5198 char *list,
5199 size_t size)
5202 * This isn't quite what listxattr() is supposed to do. This returns
5203 * the complete set of attribute names, always, rather than only those
5204 * attribute names which actually exist for a file. Hmmm...
5206 const char supported[] =
5207 "system.*\0"
5208 "system.*+\0"
5209 "system.nt_sec_desc.revision\0"
5210 "system.nt_sec_desc.owner\0"
5211 "system.nt_sec_desc.owner+\0"
5212 "system.nt_sec_desc.group\0"
5213 "system.nt_sec_desc.group+\0"
5214 "system.nt_sec_desc.acl.*\0"
5215 "system.nt_sec_desc.acl\0"
5216 "system.nt_sec_desc.acl+\0"
5217 "system.nt_sec_desc.*\0"
5218 "system.nt_sec_desc.*+\0"
5219 "system.dos_attr.*\0"
5220 "system.dos_attr.mode\0"
5221 "system.dos_attr.c_time\0"
5222 "system.dos_attr.a_time\0"
5223 "system.dos_attr.m_time\0"
5226 if (size == 0) {
5227 return sizeof(supported);
5230 if (sizeof(supported) > size) {
5231 errno = ERANGE;
5232 return -1;
5235 /* this can't be strcpy() because there are embedded null characters */
5236 memcpy(list, supported, sizeof(supported));
5237 return sizeof(supported);
5242 * Open a print file to be written to by other calls
5245 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
5247 fstring server, share, user, password;
5248 pstring path;
5250 if (!context || !context->internal ||
5251 !context->internal->_initialized) {
5253 errno = EINVAL;
5254 return NULL;
5258 if (!fname) {
5260 errno = EINVAL;
5261 return NULL;
5265 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5267 if (smbc_parse_path(context, fname,
5268 server, sizeof(server),
5269 share, sizeof(share),
5270 path, sizeof(path),
5271 user, sizeof(user),
5272 password, sizeof(password),
5273 NULL, 0)) {
5274 errno = EINVAL;
5275 return NULL;
5278 /* What if the path is empty, or the file exists? */
5280 return context->open(context, fname, O_WRONLY, 666);
5285 * Routine to print a file on a remote server ...
5287 * We open the file, which we assume to be on a remote server, and then
5288 * copy it to a print file on the share specified by printq.
5291 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
5293 SMBCFILE *fid1, *fid2;
5294 int bytes, saverr, tot_bytes = 0;
5295 char buf[4096];
5297 if (!c_file || !c_file->internal->_initialized || !c_print ||
5298 !c_print->internal->_initialized) {
5300 errno = EINVAL;
5301 return -1;
5305 if (!fname && !printq) {
5307 errno = EINVAL;
5308 return -1;
5312 /* Try to open the file for reading ... */
5314 if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5316 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5317 return -1; /* smbc_open sets errno */
5321 /* Now, try to open the printer file for writing */
5323 if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5325 saverr = errno; /* Save errno */
5326 c_file->close_fn(c_file, fid1);
5327 errno = saverr;
5328 return -1;
5332 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5334 tot_bytes += bytes;
5336 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5338 saverr = errno;
5339 c_file->close_fn(c_file, fid1);
5340 c_print->close_fn(c_print, fid2);
5341 errno = saverr;
5347 saverr = errno;
5349 c_file->close_fn(c_file, fid1); /* We have to close these anyway */
5350 c_print->close_fn(c_print, fid2);
5352 if (bytes < 0) {
5354 errno = saverr;
5355 return -1;
5359 return tot_bytes;
5364 * Routine to list print jobs on a printer share ...
5367 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
5369 SMBCSRV *srv;
5370 fstring server, share, user, password, workgroup;
5371 pstring path;
5373 if (!context || !context->internal ||
5374 !context->internal->_initialized) {
5376 errno = EINVAL;
5377 return -1;
5381 if (!fname) {
5383 errno = EINVAL;
5384 return -1;
5388 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5390 if (smbc_parse_path(context, fname,
5391 server, sizeof(server),
5392 share, sizeof(share),
5393 path, sizeof(path),
5394 user, sizeof(user),
5395 password, sizeof(password),
5396 NULL, 0)) {
5397 errno = EINVAL;
5398 return -1;
5401 if (user[0] == (char)0) fstrcpy(user, context->user);
5403 fstrcpy(workgroup, context->workgroup);
5405 srv = smbc_server(context, server, share, workgroup, user, password);
5407 if (!srv) {
5409 return -1; /* errno set by smbc_server */
5413 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
5415 errno = smbc_errno(context, &srv->cli);
5416 return -1;
5420 return 0;
5425 * Delete a print job from a remote printer share
5428 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
5430 SMBCSRV *srv;
5431 fstring server, share, user, password, workgroup;
5432 pstring path;
5433 int err;
5435 if (!context || !context->internal ||
5436 !context->internal->_initialized) {
5438 errno = EINVAL;
5439 return -1;
5443 if (!fname) {
5445 errno = EINVAL;
5446 return -1;
5450 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
5452 if (smbc_parse_path(context, fname,
5453 server, sizeof(server),
5454 share, sizeof(share),
5455 path, sizeof(path),
5456 user, sizeof(user),
5457 password, sizeof(password),
5458 NULL, 0)) {
5459 errno = EINVAL;
5460 return -1;
5463 if (user[0] == (char)0) fstrcpy(user, context->user);
5465 fstrcpy(workgroup, context->workgroup);
5467 srv = smbc_server(context, server, share, workgroup, user, password);
5469 if (!srv) {
5471 return -1; /* errno set by smbc_server */
5475 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
5477 if (err < 0)
5478 errno = smbc_errno(context, &srv->cli);
5479 else if (err == ERRnosuchprintjob)
5480 errno = EINVAL;
5481 return -1;
5485 return 0;
5490 * Get a new empty handle to fill in with your own info
5492 SMBCCTX * smbc_new_context(void)
5494 SMBCCTX * context;
5496 context = SMB_MALLOC_P(SMBCCTX);
5497 if (!context) {
5498 errno = ENOMEM;
5499 return NULL;
5502 ZERO_STRUCTP(context);
5504 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
5505 if (!context->internal) {
5506 errno = ENOMEM;
5507 return NULL;
5510 ZERO_STRUCTP(context->internal);
5513 /* ADD REASONABLE DEFAULTS */
5514 context->debug = 0;
5515 context->timeout = 20000; /* 20 seconds */
5517 context->options.browse_max_lmb_count = 3; /* # LMBs to query */
5518 context->options.urlencode_readdir_entries = False;/* backward compat */
5519 context->options.one_share_per_server = False;/* backward compat */
5521 context->open = smbc_open_ctx;
5522 context->creat = smbc_creat_ctx;
5523 context->read = smbc_read_ctx;
5524 context->write = smbc_write_ctx;
5525 context->close_fn = smbc_close_ctx;
5526 context->unlink = smbc_unlink_ctx;
5527 context->rename = smbc_rename_ctx;
5528 context->lseek = smbc_lseek_ctx;
5529 context->stat = smbc_stat_ctx;
5530 context->fstat = smbc_fstat_ctx;
5531 context->opendir = smbc_opendir_ctx;
5532 context->closedir = smbc_closedir_ctx;
5533 context->readdir = smbc_readdir_ctx;
5534 context->getdents = smbc_getdents_ctx;
5535 context->mkdir = smbc_mkdir_ctx;
5536 context->rmdir = smbc_rmdir_ctx;
5537 context->telldir = smbc_telldir_ctx;
5538 context->lseekdir = smbc_lseekdir_ctx;
5539 context->fstatdir = smbc_fstatdir_ctx;
5540 context->chmod = smbc_chmod_ctx;
5541 context->utimes = smbc_utimes_ctx;
5542 context->setxattr = smbc_setxattr_ctx;
5543 context->getxattr = smbc_getxattr_ctx;
5544 context->removexattr = smbc_removexattr_ctx;
5545 context->listxattr = smbc_listxattr_ctx;
5546 context->open_print_job = smbc_open_print_job_ctx;
5547 context->print_file = smbc_print_file_ctx;
5548 context->list_print_jobs = smbc_list_print_jobs_ctx;
5549 context->unlink_print_job = smbc_unlink_print_job_ctx;
5551 context->callbacks.check_server_fn = smbc_check_server;
5552 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
5554 smbc_default_cache_functions(context);
5556 return context;
5560 * Free a context
5562 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
5563 * and thus you'll be leaking memory if not handled properly.
5566 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
5568 if (!context) {
5569 errno = EBADF;
5570 return 1;
5573 if (shutdown_ctx) {
5574 SMBCFILE * f;
5575 DEBUG(1,("Performing aggressive shutdown.\n"));
5577 f = context->internal->_files;
5578 while (f) {
5579 context->close_fn(context, f);
5580 f = f->next;
5582 context->internal->_files = NULL;
5584 /* First try to remove the servers the nice way. */
5585 if (context->callbacks.purge_cached_fn(context)) {
5586 SMBCSRV * s;
5587 SMBCSRV * next;
5588 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
5589 s = context->internal->_servers;
5590 while (s) {
5591 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
5592 cli_shutdown(&s->cli);
5593 context->callbacks.remove_cached_srv_fn(context, s);
5594 next = s->next;
5595 DLIST_REMOVE(context->internal->_servers, s);
5596 SAFE_FREE(s);
5597 s = next;
5599 context->internal->_servers = NULL;
5602 else {
5603 /* This is the polite way */
5604 if (context->callbacks.purge_cached_fn(context)) {
5605 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
5606 errno = EBUSY;
5607 return 1;
5609 if (context->internal->_servers) {
5610 DEBUG(1, ("Active servers in context, free_context failed.\n"));
5611 errno = EBUSY;
5612 return 1;
5614 if (context->internal->_files) {
5615 DEBUG(1, ("Active files in context, free_context failed.\n"));
5616 errno = EBUSY;
5617 return 1;
5621 /* Things we have to clean up */
5622 SAFE_FREE(context->workgroup);
5623 SAFE_FREE(context->netbios_name);
5624 SAFE_FREE(context->user);
5626 DEBUG(3, ("Context %p succesfully freed\n", context));
5627 SAFE_FREE(context->internal);
5628 SAFE_FREE(context);
5629 return 0;
5634 * Initialise the library etc
5636 * We accept a struct containing handle information.
5637 * valid values for info->debug from 0 to 100,
5638 * and insist that info->fn must be non-null.
5640 SMBCCTX * smbc_init_context(SMBCCTX * context)
5642 pstring conf;
5643 int pid;
5644 char *user = NULL, *home = NULL;
5646 if (!context || !context->internal) {
5647 errno = EBADF;
5648 return NULL;
5651 /* Do not initialise the same client twice */
5652 if (context->internal->_initialized) {
5653 return 0;
5656 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
5658 errno = EINVAL;
5659 return NULL;
5663 if (!smbc_initialized) {
5664 /* Do some library wide intialisations the first time we get called */
5665 BOOL conf_loaded = False;
5667 /* Set this to what the user wants */
5668 DEBUGLEVEL = context->debug;
5670 setup_logging( "libsmbclient", True);
5672 /* Here we would open the smb.conf file if needed ... */
5674 load_interfaces(); /* Load the list of interfaces ... */
5676 in_client = True; /* FIXME, make a param */
5678 home = getenv("HOME");
5679 if (home) {
5680 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
5681 if (lp_load(conf, True, False, False)) {
5682 conf_loaded = True;
5683 } else {
5684 DEBUG(5, ("Could not load config file: %s\n",
5685 conf));
5689 if (!conf_loaded) {
5691 * Well, if that failed, try the dyn_CONFIGFILE
5692 * Which points to the standard locn, and if that
5693 * fails, silently ignore it and use the internal
5694 * defaults ...
5697 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
5698 DEBUG(5, ("Could not load config file: %s\n",
5699 dyn_CONFIGFILE));
5700 } else if (home) {
5702 * We loaded the global config file. Now lets
5703 * load user-specific modifications to the
5704 * global config.
5706 slprintf(conf, sizeof(conf),
5707 "%s/.smb/smb.conf.append", home);
5708 if (!lp_load(conf, True, False, False)) {
5709 DEBUG(10,
5710 ("Could not append config file: "
5711 "%s\n",
5712 conf));
5717 reopen_logs(); /* Get logging working ... */
5720 * Block SIGPIPE (from lib/util_sock.c: write())
5721 * It is not needed and should not stop execution
5723 BlockSignals(True, SIGPIPE);
5725 /* Done with one-time initialisation */
5726 smbc_initialized = 1;
5730 if (!context->user) {
5732 * FIXME: Is this the best way to get the user info?
5734 user = getenv("USER");
5735 /* walk around as "guest" if no username can be found */
5736 if (!user) context->user = SMB_STRDUP("guest");
5737 else context->user = SMB_STRDUP(user);
5740 if (!context->netbios_name) {
5742 * We try to get our netbios name from the config. If that fails we fall
5743 * back on constructing our netbios name from our hostname etc
5745 if (global_myname()) {
5746 context->netbios_name = SMB_STRDUP(global_myname());
5748 else {
5750 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
5752 pid = sys_getpid();
5753 context->netbios_name = SMB_MALLOC(17);
5754 if (!context->netbios_name) {
5755 errno = ENOMEM;
5756 return NULL;
5758 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
5762 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
5764 if (!context->workgroup) {
5765 if (lp_workgroup()) {
5766 context->workgroup = SMB_STRDUP(lp_workgroup());
5768 else {
5769 /* TODO: Think about a decent default workgroup */
5770 context->workgroup = SMB_STRDUP("samba");
5774 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
5776 /* shortest timeout is 1 second */
5777 if (context->timeout > 0 && context->timeout < 1000)
5778 context->timeout = 1000;
5781 * FIXME: Should we check the function pointers here?
5784 context->internal->_initialized = 1;
5786 return context;
5790 /* Return the verion of samba, and thus libsmbclient */
5791 const char *
5792 smbc_version(void)
5794 return samba_version_string();