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
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.
27 #include "include/libsmb_internal.h"
30 * Internal flags for extended attributes
33 /* internal mode values */
34 #define SMBC_XATTR_MODE_ADD 1
35 #define SMBC_XATTR_MODE_REMOVE 2
36 #define SMBC_XATTR_MODE_REMOVE_ALL 3
37 #define SMBC_XATTR_MODE_SET 4
38 #define SMBC_XATTR_MODE_CHOWN 5
39 #define SMBC_XATTR_MODE_CHGRP 6
41 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
43 /*We should test for this in configure ... */
45 #define ENOTSUP EOPNOTSUPP
49 * Functions exported by libsmb_cache.c that we need here
51 int smbc_default_cache_functions(SMBCCTX *context);
54 * check if an element is part of the list.
55 * FIXME: Does not belong here !
56 * Can anyone put this in a macro in dlinklist.h ?
59 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
60 if (!p || !list) return False;
62 if (p == list) return True;
68 extern BOOL in_client;
71 * Is the logging working / configfile read ?
73 static int smbc_initialized = 0;
76 hex2int( unsigned int _char )
78 if ( _char >= 'A' && _char <='F')
79 return _char - 'A' + 10;
80 if ( _char >= 'a' && _char <='f')
81 return _char - 'a' + 10;
82 if ( _char >= '0' && _char <='9')
88 decode_urlpart(char *segment, size_t sizeof_segment)
90 int old_length = strlen(segment);
95 char *new_usegment = 0;
101 /* make a copy of the old one */
102 new_usegment = (char*)SMB_MALLOC( old_length * 3 + 1 );
104 while( i < old_length ) {
105 int bReencode = False;
106 unsigned char character = segment[ i++ ];
107 if ((character <= ' ') || (character > 127))
110 new_usegment [ new_length2++ ] = character;
111 if (character == '%' ) {
112 int a = i+1 < old_length ? hex2int( segment[i] ) : -1;
113 int b = i+1 < old_length ? hex2int( segment[i+1] ) : -1;
114 if ((a == -1) || (b == -1)) { /* Only replace if sequence is valid */
115 /* Contains stray %, make sure to re-encode! */
118 /* Valid %xx sequence */
119 character = a * 16 + b; /* Replace with value of %dd */
121 break; /* Stop at %00 */
123 new_usegment [ new_length2++ ] = (unsigned char) segment[i++];
124 new_usegment [ new_length2++ ] = (unsigned char) segment[i++];
128 unsigned int c = character / 16;
130 new_usegment [ new_length2++ ] = '%';
132 c += (c > 9) ? ('A' - 10) : '0';
133 new_usegment[ new_length2++ ] = c;
136 c += (c > 9) ? ('A' - 10) : '0';
137 new_usegment[ new_length2++ ] = c;
140 new_segment [ new_length++ ] = character;
142 new_segment [ new_length ] = 0;
146 /* realloc it with unix charset */
147 pull_utf8_allocate(&new_usegment, new_segment);
149 /* this assumes (very safely) that removing %aa sequences
150 only shortens the string */
151 strncpy(segment, new_usegment, sizeof_segment);
157 * Function to parse a path and turn it into components
159 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
160 * book, at http://ubiqx.org/cifs/Appendix-D.html. We accept a subset of the
161 * general format ("smb:" only; we do not look for "cifs:"), and expand on
162 * what he calls "context", herein called "options" to avoid conflict with the
163 * SMBCCTX context used throughout this library. We add the "mb" keyword
164 * which applies as follows:
168 * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
172 * smb:// show all workgroups known by the first master browser found
173 * smb://?mb=.any same as smb:// (i.e. without any options)
175 * smb://?mb=.all show all workgroups known by every master browser found.
176 * Why might you want this? In an "appliance" application
177 * where the workgroup/domain being used on the local network
178 * is not known ahead of time, but where one wanted to
179 * provide network services via samba, a unique workgroup
180 * could be used. However, when the appliance is first
181 * started, the local samba instance's master browser has not
182 * synchronized with the other master browser(s) on the
183 * network (and might not synchronize for 12 minutes) and
184 * therefore is not aware of the workgroup/ domain names
185 * available on the network. This option may be used to
186 * overcome the problem of a libsmbclient application
187 * arbitrarily selecting the local (still ignorant) master
188 * browser to obtain its list of workgroups/domains and
189 * getting back a practically emmpty list. By requesting
190 * the list of workgroups/domains from each found master
191 * browser on the local network, a complete list of
192 * workgroups/domains can be built.
194 * smb://?mb=name NOT YET IMPLEMENTED -- show all workgroups known by the
195 * master browser whose name is "name"
197 * smb://name/ if name<1D> or name<1B> exists, list servers in
198 * workgroup, else, if name<20> exists, list all shares
201 * If "options" are provided, this function returns the entire option list as
202 * a string, for later parsing by the caller.
205 static const char *smbc_prefix = "smb:";
208 smbc_parse_path(SMBCCTX *context,
210 char *server, int server_len,
211 char *share, int share_len,
212 char *path, int path_len,
213 char *user, int user_len,
214 char *password, int password_len,
215 char *options, int options_len)
223 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
224 if (options != NULL && options_len > 0) {
225 options[0] = (char)0;
229 /* see if it has the right prefix */
230 len = strlen(smbc_prefix);
231 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
232 return -1; /* What about no smb: ? */
237 /* Watch the test below, we are testing to see if we should exit */
239 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
241 DEBUG(1, ("Invalid path (does not begin with smb://"));
246 p += 2; /* Skip the double slash */
248 /* See if any options were specified */
249 if ( (q = strrchr(p, '?')) != NULL ) {
250 /* There are options. Null terminate here and point to them */
253 DEBUG(4, ("Found options '%s'", q));
255 /* Copy the options */
256 if (options != NULL && options_len > 0) {
257 safe_strcpy(options, q, options_len - 1);
266 strncpy(server, context->workgroup,
267 (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
273 * ok, its for us. Now parse out the server, share etc.
275 * However, we want to parse out [[domain;]user[:password]@] if it
279 /* check that '@' occurs before '/', if '/' exists at all */
280 q = strchr_m(p, '@');
281 r = strchr_m(p, '/');
282 if (q && (!r || q < r)) {
283 pstring username, passwd, domain;
284 const char *u = userinfo;
286 next_token(&p, userinfo, "@", sizeof(fstring));
288 username[0] = passwd[0] = domain[0] = 0;
290 if (strchr_m(u, ';')) {
292 next_token(&u, domain, ";", sizeof(fstring));
296 if (strchr_m(u, ':')) {
298 next_token(&u, username, ":", sizeof(fstring));
305 pstrcpy(username, u);
310 strncpy(user, username, user_len); /* FIXME, domain */
313 strncpy(password, passwd, password_len);
317 if (!next_token(&p, server, "/", sizeof(fstring))) {
323 if (*p == (char)0) goto decoding; /* That's it ... */
325 if (!next_token(&p, share, "/", sizeof(fstring))) {
331 safe_strcpy(path, p, path_len - 1);
333 all_string_sub(path, "/", "\\", 0);
336 decode_urlpart(path, path_len);
337 decode_urlpart(server, server_len);
338 decode_urlpart(share, share_len);
339 decode_urlpart(user, user_len);
340 decode_urlpart(password, password_len);
346 * Verify that the options specified in a URL are valid
348 static int smbc_check_options(char *server, char *share, char *path, char *options)
350 DEBUG(4, ("smbc_check_options(): server='%s' share='%s' path='%s' options='%s'\n", server, share, path, options));
352 /* No options at all is always ok */
353 if (! *options) return 0;
356 * For right now, we only support a very few options possibilities.
357 * No options are supported if server, share, or path are not empty.
358 * If all are empty, then we support the following two choices right
364 if ((*server || *share || *path) && *options) {
365 /* Invalid: options provided with server, share, or path */
366 DEBUG(1, ("Found unsupported options (%s) with non-empty server, share, or path\n", options));
370 if (strcmp(options, "mb=.any") != 0 &&
371 strcmp(options, "mb=.all") != 0) {
372 DEBUG(1, ("Found unsupported options (%s)\n", options));
380 * Convert an SMB error into a UNIX error ...
382 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
384 int ret = cli_errno(c);
386 if (cli_is_dos_error(c)) {
390 cli_dos_error(c, &eclass, &ecode);
392 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
393 (int)eclass, (int)ecode, (int)ecode, ret));
397 status = cli_nt_error(c);
399 DEBUG(3,("smbc errno %s -> %d\n",
400 nt_errstr(status), ret));
408 * returns 0 if the server is in shape. Returns 1 on error
410 * Also useable outside libsmbclient to enable external cache
411 * to do some checks too.
413 int smbc_check_server(SMBCCTX * context, SMBCSRV * server)
415 if ( send_keepalive(server->cli.fd) == False )
418 /* connection is ok */
423 * Remove a server from the cached server list it's unused.
424 * On success, 0 is returned. 1 is returned if the server could not be removed.
426 * Also useable outside libsmbclient
428 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
432 /* are we being fooled ? */
433 if (!context || !context->internal ||
434 !context->internal->_initialized || !srv) return 1;
437 /* Check all open files/directories for a relation with this server */
438 for (file = context->internal->_files; file; file=file->next) {
439 if (file->srv == srv) {
441 DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n",
447 DLIST_REMOVE(context->internal->_servers, srv);
449 cli_shutdown(&srv->cli);
451 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
453 context->callbacks.remove_cached_srv_fn(context, srv);
460 SMBCSRV *find_server(SMBCCTX *context,
472 srv = context->callbacks.get_cached_srv_fn(context, server, share,
473 workgroup, username);
475 if (!auth_called && !srv && (!username[0] || !password[0])) {
476 context->callbacks.auth_fn(server, share,
477 workgroup, sizeof(fstring),
478 username, sizeof(fstring),
479 password, sizeof(fstring));
481 * However, smbc_auth_fn may have picked up info relating to
482 * an existing connection, so try for an existing connection
486 goto check_server_cache;
491 if (context->callbacks.check_server_fn(context, srv)) {
493 * This server is no good anymore
494 * Try to remove it and check for more possible
495 * servers in the cache
497 if (context->callbacks.remove_unused_server_fn(context,
500 * We could not remove the server completely,
501 * remove it from the cache so we will not get
502 * it again. It will be removed when the last
503 * file/dir is closed.
505 context->callbacks.remove_cached_srv_fn(context,
510 * Maybe there are more cached connections to this
513 goto check_server_cache;
522 * Connect to a server, possibly on an existing connection
524 * Here, what we want to do is: If the server and username
525 * match an existing connection, reuse that, otherwise, establish a
528 * If we have to create a new connection, call the auth_fn to get the
529 * info we need, unless the username and password were passed in.
532 SMBCSRV *smbc_server(SMBCCTX *context,
533 const char *server, const char *share,
534 fstring workgroup, fstring username,
539 struct nmb_name called, calling;
540 const char *server_n = server;
543 int tried_reverse = 0;
548 if (server[0] == 0) {
553 srv = find_server(context, server, share,
554 workgroup, username, password);
558 make_nmb_name(&calling, context->netbios_name, 0x0);
559 make_nmb_name(&called , server, 0x20);
561 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
563 #if 0 /* djl: obsolete code? neither group nor p is used beyond here */
564 if ((p=strchr_m(server_n,'#')) &&
565 (strcmp(p+1,"1D")==0 || strcmp(p+1,"01")==0)) {
567 fstrcpy(group, server_n);
568 p = strchr_m(group,'#');
574 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
577 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
581 /* have to open a new connection */
582 if (!cli_initialise(&c)) {
587 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
588 c.use_kerberos = True;
590 if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
591 c.fallback_after_kerberos = True;
594 c.timeout = context->timeout;
596 /* Force use of port 139 for first try, so browse lists can work */
599 if (!cli_connect(&c, server_n, &ip)) {
601 * Port 139 connection failed. Try port 445 to handle
602 * connections to newer (e.g. XP) hosts with NetBIOS disabled.
605 if (!cli_connect(&c, server_n, &ip)) {
612 if (!cli_session_request(&c, &calling, &called)) {
614 if (strcmp(called.name, "*SMBSERVER")) {
615 make_nmb_name(&called , "*SMBSERVER", 0x20);
618 else { /* Try one more time, but ensure we don't loop */
620 /* Only try this if server is an IP address ... */
622 if (is_ipaddress(server) && !tried_reverse) {
624 struct in_addr rem_ip;
626 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
627 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
632 tried_reverse++; /* Yuck */
634 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
635 make_nmb_name(&called, remote_name, 0x20);
646 DEBUG(4,(" session request ok\n"));
648 if (!cli_negprot(&c)) {
654 if (!cli_session_setup(&c, username,
655 password, strlen(password),
656 password, strlen(password),
658 /* Try an anonymous login if it failed and this was allowed by flags. */
659 ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
660 !cli_session_setup(&c, "", "", 1,"", 0, workgroup))) {
666 DEBUG(4,(" session setup ok\n"));
668 if (!cli_send_tconX(&c, share, "?????",
669 password, strlen(password)+1)) {
670 errno = smbc_errno(context, &c);
675 DEBUG(4,(" tconx ok\n"));
678 * Ok, we have got a nice connection
679 * Let's find a free server_fd
682 srv = SMB_MALLOC_P(SMBCSRV);
690 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
692 /* now add it to the cache (internal or external) */
693 /* Let the cache function set errno if it wants to */
695 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
696 int saved_errno = errno;
697 DEBUG(3, (" Failed to add server to cache\n"));
705 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
706 server, share, srv));
708 DLIST_ADD(context->internal->_servers, srv);
713 if (!srv) return NULL;
720 * Connect to a server for getting/setting attributes, possibly on an existing
721 * connection. This works similarly to smbc_server().
723 SMBCSRV *smbc_attr_server(SMBCCTX *context,
724 const char *server, const char *share,
726 fstring username, fstring password,
730 struct cli_state *ipc_cli;
732 SMBCSRV *ipc_srv=NULL;
735 * See if we've already created this special connection. Reference
736 * our "special" share name 'IPC$$'.
738 ipc_srv = find_server(context, server, "IPC$$",
739 workgroup, username, password);
742 /* We didn't find a cached connection. Get the password */
743 if (*password == '\0') {
744 /* ... then retrieve it now. */
745 context->callbacks.auth_fn(server, share,
746 workgroup, sizeof(fstring),
747 username, sizeof(fstring),
748 password, sizeof(fstring));
752 nt_status = cli_full_connection(&ipc_cli,
753 global_myname(), server,
754 &ip, 0, "IPC$", "?????",
758 if (! NT_STATUS_IS_OK(nt_status)) {
759 DEBUG(1,("cli_full_connection failed! (%s)\n",
760 nt_errstr(nt_status)));
765 if (!cli_nt_session_open(ipc_cli, PI_LSARPC)) {
766 DEBUG(1, ("cli_nt_session_open fail!\n"));
768 cli_shutdown(ipc_cli);
772 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
773 but NT sends 0x2000000 so we might as well do it too. */
775 nt_status = cli_lsa_open_policy(ipc_cli,
778 GENERIC_EXECUTE_ACCESS,
781 if (!NT_STATUS_IS_OK(nt_status)) {
782 errno = smbc_errno(context, ipc_cli);
783 cli_shutdown(ipc_cli);
787 ipc_srv = SMB_MALLOC_P(SMBCSRV);
790 cli_shutdown(ipc_cli);
794 ZERO_STRUCTP(ipc_srv);
795 ipc_srv->cli = *ipc_cli;
799 /* now add it to the cache (internal or external) */
801 errno = 0; /* let cache function set errno if it likes */
802 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
807 DEBUG(3, (" Failed to add server to cache\n"));
811 cli_shutdown(&ipc_srv->cli);
816 DLIST_ADD(context->internal->_servers, ipc_srv);
823 * Routine to open() a file ...
826 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
828 fstring server, share, user, password, workgroup;
831 SMBCFILE *file = NULL;
834 if (!context || !context->internal ||
835 !context->internal->_initialized) {
837 errno = EINVAL; /* Best I can think of ... */
849 if (smbc_parse_path(context, fname,
850 server, sizeof(server),
851 share, sizeof(share),
854 password, sizeof(password),
860 if (user[0] == (char)0) fstrcpy(user, context->user);
862 fstrcpy(workgroup, context->workgroup);
864 srv = smbc_server(context, server, share, workgroup, user, password);
868 if (errno == EPERM) errno = EACCES;
869 return NULL; /* smbc_server sets errno */
873 /* Hmmm, the test for a directory is suspect here ... FIXME */
875 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
882 file = SMB_MALLOC_P(SMBCFILE);
893 if ((fd = cli_open(&srv->cli, path, flags, DENY_NONE)) < 0) {
895 /* Handle the error ... */
898 errno = smbc_errno(context, &srv->cli);
903 /* Fill in file struct */
906 file->fname = SMB_STRDUP(fname);
911 DLIST_ADD(context->internal->_files, file);
916 /* Check if opendir needed ... */
921 eno = smbc_errno(context, &srv->cli);
922 file = context->opendir(context, fname);
923 if (!file) errno = eno;
928 errno = EINVAL; /* FIXME, correct errno ? */
934 * Routine to create a file
937 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
939 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
942 if (!context || !context->internal ||
943 !context->internal->_initialized) {
950 return smbc_open_ctx(context, path, creat_bits, mode);
954 * Routine to read() a file ...
957 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
961 if (!context || !context->internal ||
962 !context->internal->_initialized) {
969 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
971 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
978 /* Check that the buffer exists ... */
987 ret = cli_read(&file->srv->cli, file->cli_fd, buf, file->offset, count);
991 errno = smbc_errno(context, &file->srv->cli);
998 DEBUG(4, (" --> %d\n", ret));
1000 return ret; /* Success, ret bytes of data ... */
1005 * Routine to write() a file ...
1008 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1012 if (!context || !context->internal ||
1013 !context->internal->_initialized) {
1020 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1027 /* Check that the buffer exists ... */
1036 ret = cli_write(&file->srv->cli, file->cli_fd, 0, buf, file->offset, count);
1040 errno = smbc_errno(context, &file->srv->cli);
1045 file->offset += ret;
1047 return ret; /* Success, 0 bytes of data ... */
1051 * Routine to close() a file ...
1054 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1058 if (!context || !context->internal ||
1059 !context->internal->_initialized) {
1066 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1076 return context->closedir(context, file);
1080 if (!cli_close(&file->srv->cli, file->cli_fd)) {
1082 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1084 /* Deallocate slot and remove the server
1085 * from the server cache if unused */
1086 errno = smbc_errno(context, &file->srv->cli);
1088 DLIST_REMOVE(context->internal->_files, file);
1089 SAFE_FREE(file->fname);
1091 context->callbacks.remove_unused_server_fn(context, srv);
1097 DLIST_REMOVE(context->internal->_files, file);
1098 SAFE_FREE(file->fname);
1105 * Get info from an SMB server on a file. Use a qpathinfo call first
1106 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1108 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1109 uint16 *mode, size_t *size,
1110 time_t *c_time, time_t *a_time, time_t *m_time,
1114 if (!context || !context->internal ||
1115 !context->internal->_initialized) {
1122 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1124 if (!srv->no_pathinfo2 &&
1125 cli_qpathinfo2(&srv->cli, path, c_time, a_time, m_time, NULL,
1126 size, mode, ino)) return True;
1128 /* if this is NT then don't bother with the getatr */
1129 if (srv->cli.capabilities & CAP_NT_SMBS) {
1134 if (cli_getatr(&srv->cli, path, mode, size, m_time)) {
1135 a_time = c_time = m_time;
1136 srv->no_pathinfo2 = True;
1146 * Routine to unlink() a file
1149 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1151 fstring server, share, user, password, workgroup;
1153 SMBCSRV *srv = NULL;
1155 if (!context || !context->internal ||
1156 !context->internal->_initialized) {
1158 errno = EINVAL; /* Best I can think of ... */
1170 if (smbc_parse_path(context, fname,
1171 server, sizeof(server),
1172 share, sizeof(share),
1175 password, sizeof(password),
1181 if (user[0] == (char)0) fstrcpy(user, context->user);
1183 fstrcpy(workgroup, context->workgroup);
1185 srv = smbc_server(context, server, share, workgroup, user, password);
1189 return -1; /* smbc_server sets errno */
1193 /* if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
1195 int job = smbc_stat_printjob(srv, path, NULL, NULL);
1201 if ((err = cli_printjob_del(&srv->cli, job)) != 0) {
1209 if (!cli_unlink(&srv->cli, path)) {
1211 errno = smbc_errno(context, &srv->cli);
1213 if (errno == EACCES) { /* Check if the file is a directory */
1218 time_t m_time = 0, a_time = 0, c_time = 0;
1221 if (!smbc_getatr(context, srv, path, &mode, &size,
1222 &c_time, &a_time, &m_time, &ino)) {
1224 /* Hmmm, bad error ... What? */
1226 errno = smbc_errno(context, &srv->cli);
1232 if (IS_DOS_DIR(mode))
1235 errno = saverr; /* Restore this */
1244 return 0; /* Success ... */
1249 * Routine to rename() a file
1252 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1253 SMBCCTX *ncontext, const char *nname)
1255 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1256 pstring path1, path2;
1257 SMBCSRV *srv = NULL;
1259 if (!ocontext || !ncontext ||
1260 !ocontext->internal || !ncontext->internal ||
1261 !ocontext->internal->_initialized ||
1262 !ncontext->internal->_initialized) {
1264 errno = EINVAL; /* Best I can think of ... */
1269 if (!oname || !nname) {
1276 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1278 smbc_parse_path(ocontext, oname,
1279 server1, sizeof(server1),
1280 share1, sizeof(share1),
1281 path1, sizeof(path1),
1282 user1, sizeof(user1),
1283 password1, sizeof(password1),
1286 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1288 smbc_parse_path(ncontext, nname,
1289 server2, sizeof(server2),
1290 share2, sizeof(share2),
1291 path2, sizeof(path2),
1292 user2, sizeof(user2),
1293 password2, sizeof(password2),
1296 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1298 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1299 strcmp(user1, user2)) {
1301 /* Can't rename across file systems, or users?? */
1308 fstrcpy(workgroup, ocontext->workgroup);
1309 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1310 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1317 if (!cli_rename(&srv->cli, path1, path2)) {
1318 int eno = smbc_errno(ocontext, &srv->cli);
1320 if (eno != EEXIST ||
1321 !cli_unlink(&srv->cli, path2) ||
1322 !cli_rename(&srv->cli, path1, path2)) {
1330 return 0; /* Success */
1335 * A routine to lseek() a file
1338 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1342 if (!context || !context->internal ||
1343 !context->internal->_initialized) {
1350 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1360 return -1; /* Can't lseek a dir ... */
1366 file->offset = offset;
1370 file->offset += offset;
1374 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
1377 SMB_BIG_UINT b_size = size;
1378 if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
1386 file->offset = size + offset;
1395 return file->offset;
1400 * Generate an inode number from file name for those things that need it
1404 ino_t smbc_inode(SMBCCTX *context, const char *name)
1407 if (!context || !context->internal ||
1408 !context->internal->_initialized) {
1415 if (!*name) return 2; /* FIXME, why 2 ??? */
1416 return (ino_t)str_checksum(name);
1421 * Routine to put basic stat info into a stat structure ... Used by stat and
1426 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname, size_t size, int mode)
1431 if (IS_DOS_DIR(mode)) {
1432 st->st_mode = SMBC_DIR_MODE;
1434 st->st_mode = SMBC_FILE_MODE;
1437 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1438 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1439 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1440 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1443 #ifdef HAVE_STAT_ST_BLKSIZE
1444 st->st_blksize = 512;
1446 #ifdef HAVE_STAT_ST_BLOCKS
1447 st->st_blocks = (size+511)/512;
1449 st->st_uid = getuid();
1450 st->st_gid = getgid();
1452 if (IS_DOS_DIR(mode)) {
1458 if (st->st_ino == 0) {
1459 st->st_ino = smbc_inode(context, fname);
1462 return True; /* FIXME: Is this needed ? */
1467 * Routine to stat a file given a name
1470 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1473 fstring server, share, user, password, workgroup;
1475 time_t m_time = 0, a_time = 0, c_time = 0;
1480 if (!context || !context->internal ||
1481 !context->internal->_initialized) {
1483 errno = EINVAL; /* Best I can think of ... */
1495 DEBUG(4, ("smbc_stat(%s)\n", fname));
1497 if (smbc_parse_path(context, fname,
1498 server, sizeof(server),
1499 share, sizeof(share),
1502 password, sizeof(password),
1508 if (user[0] == (char)0) fstrcpy(user, context->user);
1510 fstrcpy(workgroup, context->workgroup);
1512 srv = smbc_server(context, server, share, workgroup, user, password);
1515 return -1; /* errno set by smbc_server */
1518 if (!smbc_getatr(context, srv, path, &mode, &size,
1519 &c_time, &a_time, &m_time, &ino)) {
1521 errno = smbc_errno(context, &srv->cli);
1528 smbc_setup_stat(context, st, path, size, mode);
1530 st->st_atime = a_time;
1531 st->st_ctime = c_time;
1532 st->st_mtime = m_time;
1533 st->st_dev = srv->dev;
1540 * Routine to stat a file given an fd
1543 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1545 time_t c_time, a_time, m_time;
1550 if (!context || !context->internal ||
1551 !context->internal->_initialized) {
1558 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1567 return context->fstatdir(context, file, st);
1571 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
1572 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
1573 SMB_BIG_UINT b_size = size;
1574 if (!cli_getattrE(&file->srv->cli, file->cli_fd,
1575 &mode, &b_size, &c_time, &a_time, &m_time)) {
1586 smbc_setup_stat(context, st, file->fname, size, mode);
1588 st->st_atime = a_time;
1589 st->st_ctime = c_time;
1590 st->st_mtime = m_time;
1591 st->st_dev = file->srv->dev;
1598 * Routine to open a directory
1599 * We accept the URL syntax explained in smbc_parse_path(), above.
1602 static void smbc_remove_dir(SMBCFILE *dir)
1604 struct smbc_dir_list *d,*f;
1611 SAFE_FREE(f->dirent);
1616 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
1620 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
1622 struct smbc_dirent *dirent;
1624 char *u_name = NULL, *u_comment = NULL;
1625 size_t u_name_len = 0, u_comment_len = 0;
1628 u_name_len = push_utf8_allocate(&u_name, name);
1630 u_comment_len = push_utf8_allocate(&u_comment, comment);
1633 * Allocate space for the dirent, which must be increased by the
1634 * size of the name and the comment and 1 for the null on the comment.
1635 * The null on the name is already accounted for.
1638 size = sizeof(struct smbc_dirent) + u_name_len + u_comment_len + 1;
1640 dirent = SMB_MALLOC(size);
1644 dir->dir_error = ENOMEM;
1649 ZERO_STRUCTP(dirent);
1651 if (dir->dir_list == NULL) {
1653 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
1654 if (!dir->dir_list) {
1657 dir->dir_error = ENOMEM;
1661 ZERO_STRUCTP(dir->dir_list);
1663 dir->dir_end = dir->dir_next = dir->dir_list;
1667 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
1669 if (!dir->dir_end->next) {
1672 dir->dir_error = ENOMEM;
1676 ZERO_STRUCTP(dir->dir_end->next);
1678 dir->dir_end = dir->dir_end->next;
1681 dir->dir_end->next = NULL;
1682 dir->dir_end->dirent = dirent;
1684 dirent->smbc_type = type;
1685 dirent->namelen = u_name_len;
1686 dirent->commentlen = u_comment_len;
1687 dirent->dirlen = size;
1689 strncpy(dirent->name, (u_name?u_name:""), dirent->namelen + 1);
1691 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
1692 strncpy(dirent->comment, (u_comment?u_comment:""), dirent->commentlen + 1);
1694 SAFE_FREE(u_comment);
1702 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
1704 SMBCFILE *dir = (SMBCFILE *)state;
1705 struct smbc_dir_list *dir_list;
1706 struct smbc_dirent *dirent;
1710 dirent_type = dir->dir_type;
1712 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1714 /* An error occurred, what do we do? */
1715 /* FIXME: Add some code here */
1718 /* Point to the one just added */
1719 dirent = dir->dir_end->dirent;
1721 /* See if this was a duplicate */
1722 for (dir_list = dir->dir_list;
1723 dir_list != dir->dir_end;
1724 dir_list = dir_list->next) {
1726 strcmp(dir_list->dirent->name, dirent->name) == 0) {
1727 /* Duplicate. End end of list need to be removed. */
1731 if (do_remove && dir_list->next == dir->dir_end) {
1732 /* Found the end of the list. Remove it. */
1733 dir->dir_end = dir_list;
1734 free(dir_list->next);
1735 dir_list->next = NULL;
1742 list_fn(const char *name, uint32 type, const char *comment, void *state)
1744 SMBCFILE *dir = (SMBCFILE *)state;
1747 /* We need to process the type a little ... */
1749 if (dir->dir_type == SMBC_FILE_SHARE) {
1752 case 0: /* Directory tree */
1753 dirent_type = SMBC_FILE_SHARE;
1757 dirent_type = SMBC_PRINTER_SHARE;
1761 dirent_type = SMBC_COMMS_SHARE;
1765 dirent_type = SMBC_IPC_SHARE;
1769 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
1773 else dirent_type = dir->dir_type;
1775 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1777 /* An error occurred, what do we do? */
1778 /* FIXME: Add some code here */
1784 dir_list_fn(file_info *finfo, const char *mask, void *state)
1787 if (add_dirent((SMBCFILE *)state, finfo->name, "",
1788 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
1790 /* Handle an error ... */
1792 /* FIXME: Add some code ... */
1798 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
1800 fstring server, share, user, password, options;
1803 SMBCSRV *srv = NULL;
1804 SMBCFILE *dir = NULL;
1805 struct in_addr rem_ip;
1807 if (!context || !context->internal ||
1808 !context->internal->_initialized) {
1809 DEBUG(4, ("no valid context\n"));
1816 DEBUG(4, ("no valid fname\n"));
1821 if (smbc_parse_path(context, fname,
1822 server, sizeof(server),
1823 share, sizeof(share),
1826 password, sizeof(password),
1827 options, sizeof(options))) {
1828 DEBUG(4, ("no valid path\n"));
1833 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
1835 /* Ensure the options are valid */
1836 if (smbc_check_options(server, share, path, options)) {
1837 DEBUG(4, ("unacceptable options (%s)\n", options));
1842 if (user[0] == (char)0) fstrcpy(user, context->user);
1844 pstrcpy(workgroup, context->workgroup);
1846 dir = SMB_MALLOC_P(SMBCFILE);
1858 dir->fname = SMB_STRDUP(fname);
1862 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
1864 if (server[0] == (char)0 &&
1865 (! *options || strcmp(options, "mb=.any") == 0)) {
1866 struct in_addr server_ip;
1867 if (share[0] != (char)0 || path[0] != (char)0) {
1871 SAFE_FREE(dir->fname);
1878 * We have server and share and path empty ... so list the
1879 * workgroups first try to get the LMB for our workgroup, and
1880 * if that fails, try the DMB
1883 pstrcpy(workgroup, lp_workgroup());
1885 if (!find_master_ip(workgroup, &server_ip)) {
1886 struct user_auth_info u_info;
1887 struct cli_state *cli;
1889 DEBUG(4, ("Unable to find master browser for workgroup %s\n",
1892 /* find the name of the server ... */
1893 pstrcpy(u_info.username, user);
1894 pstrcpy(u_info.password, password);
1896 if (!(cli = get_ipc_connect_master_ip_bcast(workgroup, &u_info))) {
1897 DEBUG(4, ("Unable to find master browser by "
1903 fstrcpy(server, cli->desthost);
1908 * Do a name status query to find out the name of the
1909 * master browser. We use <01><02>__MSBROWSE__<02>#01 if
1910 * *#00 fails because a domain master browser will not
1911 * respond to a wildcard query (or, at least, an NT4
1912 * server acting as the domain master browser will not).
1914 * We might be able to use ONLY the query on MSBROWSE, but
1915 * that's not yet been tested with all Windows versions,
1916 * so until it is, leave the original wildcard query as
1917 * the first choice and fall back to MSBROWSE if the
1918 * wildcard query fails.
1920 if (!name_status_find("*", 0, 0x20, server_ip, server) &&
1921 !name_status_find(MSBROWSE, 1, 0x1b, server_ip, server)) {
1927 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
1930 * Get a connection to IPC$ on the server if we do not already
1934 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
1938 SAFE_FREE(dir->fname);
1945 dir->dir_type = SMBC_WORKGROUP;
1947 /* Now, list the stuff ... */
1949 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_fn,
1952 DEBUG(1, ("Could not enumerate domains using '%s'\n", workgroup));
1954 SAFE_FREE(dir->fname);
1961 } else if (server[0] == (char)0 &&
1962 (! *options || strcmp(options, "mb=.all") == 0)) {
1966 struct ip_service *ip_list;
1967 struct ip_service server_addr;
1968 struct user_auth_info u_info;
1969 struct cli_state *cli;
1971 if (share[0] != (char)0 || path[0] != (char)0) {
1975 SAFE_FREE(dir->fname);
1981 pstrcpy(u_info.username, user);
1982 pstrcpy(u_info.password, password);
1985 * We have server and share and path empty but options
1986 * requesting that we scan all master browsers for their list
1987 * of workgroups/domains. This implies that we must first try
1988 * broadcast queries to find all master browsers, and if that
1989 * doesn't work, then try our other methods which return only
1990 * a single master browser.
1993 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
1994 if (!find_master_ip(workgroup, &server_addr.ip)) {
2000 ip_list = &server_addr;
2004 for (i = 0; i < count; i++) {
2005 DEBUG(99, ("Found master browser %s\n", inet_ntoa(ip_list[i].ip)));
2007 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
2009 /* cli == NULL is the master browser refused to talk or
2010 could not be found */
2014 fstrcpy(server, cli->desthost);
2017 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2020 * For each returned master browser IP address, get a
2021 * connection to IPC$ on the server if we do not
2022 * already have one, and determine the
2023 * workgroups/domains that it knows about.
2026 srv = smbc_server(context, server,
2027 "IPC$", workgroup, user, password);
2031 SAFE_FREE(dir->fname);
2038 dir->dir_type = SMBC_WORKGROUP;
2040 /* Now, list the stuff ... */
2042 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2046 SAFE_FREE(dir->fname);
2056 * Server not an empty string ... Check the rest and see what
2059 if (share[0] == (char)0) {
2061 if (path[0] != (char)0) { /* Should not have empty share with path */
2065 SAFE_FREE(dir->fname);
2072 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2073 /* However, we check to see if <server> is an IP address first */
2075 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2076 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2077 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2080 dir->dir_type = SMBC_SERVER;
2083 * Get the backup list ...
2087 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2089 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2090 errno = EPERM; /* FIXME, is this correct */
2096 * Get a connection to IPC$ on the server if we do not already have one
2099 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2102 DEBUG(0, ("got no contact to IPC$\n"));
2104 SAFE_FREE(dir->fname);
2113 /* Now, list the servers ... */
2115 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2119 SAFE_FREE(dir->fname);
2128 if (resolve_name(server, &rem_ip, 0x20)) {
2130 /* Now, list the shares ... */
2132 dir->dir_type = SMBC_FILE_SHARE;
2134 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2139 SAFE_FREE(dir->fname);
2148 /* Now, list the servers ... */
2150 if (cli_RNetShareEnum(&srv->cli, list_fn,
2153 errno = cli_errno(&srv->cli);
2155 SAFE_FREE(dir->fname);
2165 errno = ECONNREFUSED; /* Neither the workgroup nor server exists */
2167 SAFE_FREE(dir->fname);
2177 else { /* The server and share are specified ... work from there ... */
2179 /* Well, we connect to the server and list the directory */
2181 dir->dir_type = SMBC_FILE_SHARE;
2183 srv = smbc_server(context, server, share, workgroup, user, password);
2188 SAFE_FREE(dir->fname);
2197 /* Now, list the files ... */
2199 pstrcat(path, "\\*");
2201 if (cli_list(&srv->cli, path, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2205 SAFE_FREE(dir->fname);
2208 errno = smbc_errno(context, &srv->cli);
2216 DLIST_ADD(context->internal->_files, dir);
2222 * Routine to close a directory
2225 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2228 if (!context || !context->internal ||
2229 !context->internal->_initialized) {
2236 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2243 smbc_remove_dir(dir); /* Clean it up */
2245 DLIST_REMOVE(context->internal->_files, dir);
2249 SAFE_FREE(dir->fname);
2250 SAFE_FREE(dir); /* Free the space too */
2258 * Routine to get a directory entry
2261 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2263 struct smbc_dirent *dirp, *dirent;
2265 /* Check that all is ok first ... */
2267 if (!context || !context->internal ||
2268 !context->internal->_initialized) {
2271 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2276 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2279 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2284 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2287 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2292 if (!dir->dir_next) {
2297 dirent = dir->dir_next->dirent;
2305 /* Hmmm, do I even need to copy it? */
2307 memcpy(context->internal->_dirent, dirent, dirent->dirlen); /* Copy the dirent */
2308 dirp = (struct smbc_dirent *)context->internal->_dirent;
2309 dirp->comment = (char *)(&dirp->name + dirent->namelen + 1);
2310 dir->dir_next = dir->dir_next->next;
2312 return (struct smbc_dirent *)context->internal->_dirent;
2318 * Routine to get directory entries
2321 static int smbc_getdents_ctx(SMBCCTX *context, SMBCFILE *dir, struct smbc_dirent *dirp, int count)
2323 struct smbc_dir_list *dirlist;
2324 int rem = count, reqd;
2325 char *ndir = (char *)dirp;
2327 /* Check that all is ok first ... */
2329 if (!context || !context->internal ||
2330 !context->internal->_initialized) {
2337 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2344 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2352 * Now, retrieve the number of entries that will fit in what was passed
2353 * We have to figure out if the info is in the list, or we need to
2354 * send a request to the server to get the info.
2357 while ((dirlist = dir->dir_next)) {
2358 struct smbc_dirent *dirent;
2360 if (!dirlist->dirent) {
2362 errno = ENOENT; /* Bad error */
2367 if (rem < (reqd = (sizeof(struct smbc_dirent) + dirlist->dirent->namelen +
2368 dirlist->dirent->commentlen + 1))) {
2370 if (rem < count) { /* We managed to copy something */
2376 else { /* Nothing copied ... */
2378 errno = EINVAL; /* Not enough space ... */
2385 dirent = dirlist->dirent;
2387 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2389 ((struct smbc_dirent *)ndir)->comment =
2390 (char *)(&((struct smbc_dirent *)ndir)->name + dirent->namelen + 1);
2396 dir->dir_next = dirlist = dirlist -> next;
2407 * Routine to create a directory ...
2410 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2413 fstring server, share, user, password, workgroup;
2416 if (!context || !context->internal ||
2417 !context->internal->_initialized) {
2431 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2433 if (smbc_parse_path(context, fname,
2434 server, sizeof(server),
2435 share, sizeof(share),
2438 password, sizeof(password),
2444 if (user[0] == (char)0) fstrcpy(user, context->user);
2446 fstrcpy(workgroup, context->workgroup);
2448 srv = smbc_server(context, server, share, workgroup, user, password);
2452 return -1; /* errno set by smbc_server */
2456 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2458 mode = aDIR | aRONLY;
2461 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2463 if (strcmp(path, "\\") == 0) {
2465 mode = aDIR | aRONLY;
2471 smbc_stat_printjob(srv, path, &size, &m_time);
2472 c_time = a_time = m_time;
2477 if (!cli_mkdir(&srv->cli, path)) {
2479 errno = smbc_errno(context, &srv->cli);
2489 * Our list function simply checks to see if a directory is not empty
2492 static int smbc_rmdir_dirempty = True;
2494 static void rmdir_list_fn(file_info *finfo, const char *mask, void *state)
2497 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2498 smbc_rmdir_dirempty = False;
2503 * Routine to remove a directory
2506 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2509 fstring server, share, user, password, workgroup;
2512 if (!context || !context->internal ||
2513 !context->internal->_initialized) {
2527 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2529 if (smbc_parse_path(context, fname,
2530 server, sizeof(server),
2531 share, sizeof(share),
2534 password, sizeof(password),
2541 if (user[0] == (char)0) fstrcpy(user, context->user);
2543 fstrcpy(workgroup, context->workgroup);
2545 srv = smbc_server(context, server, share, workgroup, user, password);
2549 return -1; /* errno set by smbc_server */
2553 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2555 mode = aDIR | aRONLY;
2558 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2560 if (strcmp(path, "\\") == 0) {
2562 mode = aDIR | aRONLY;
2568 smbc_stat_printjob(srv, path, &size, &m_time);
2569 c_time = a_time = m_time;
2574 if (!cli_rmdir(&srv->cli, path)) {
2576 errno = smbc_errno(context, &srv->cli);
2578 if (errno == EACCES) { /* Check if the dir empty or not */
2580 pstring lpath; /* Local storage to avoid buffer overflows */
2582 smbc_rmdir_dirempty = True; /* Make this so ... */
2584 pstrcpy(lpath, path);
2585 pstrcat(lpath, "\\*");
2587 if (cli_list(&srv->cli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2590 /* Fix errno to ignore latest error ... */
2592 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
2593 smbc_errno(context, &srv->cli)));
2598 if (smbc_rmdir_dirempty)
2614 * Routine to return the current directory position
2617 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
2619 off_t ret_val; /* Squash warnings about cast */
2621 if (!context || !context->internal ||
2622 !context->internal->_initialized) {
2629 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2636 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2644 * We return the pointer here as the offset
2646 ret_val = (int)dir->dir_next;
2652 * A routine to run down the list and see if the entry is OK
2655 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
2656 struct smbc_dirent *dirent)
2659 /* Run down the list looking for what we want */
2663 struct smbc_dir_list *tmp = list;
2667 if (tmp->dirent == dirent)
2676 return NULL; /* Not found, or an error */
2682 * Routine to seek on a directory
2685 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
2687 long int l_offset = offset; /* Handle problems of size */
2688 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
2689 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
2691 if (!context || !context->internal ||
2692 !context->internal->_initialized) {
2699 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2706 /* Now, check what we were passed and see if it is OK ... */
2708 if (dirent == NULL) { /* Seek to the begining of the list */
2710 dir->dir_next = dir->dir_list;
2715 /* Now, run down the list and make sure that the entry is OK */
2716 /* This may need to be changed if we change the format of the list */
2718 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
2720 errno = EINVAL; /* Bad entry */
2725 dir->dir_next = list_ent;
2732 * Routine to fstat a dir
2735 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
2738 if (!context || !context->internal ||
2739 !context->internal->_initialized) {
2746 /* No code yet ... */
2752 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
2755 fstring server, share, user, password, workgroup;
2759 if (!context || !context->internal ||
2760 !context->internal->_initialized) {
2762 errno = EINVAL; /* Best I can think of ... */
2774 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
2776 if (smbc_parse_path(context, fname,
2777 server, sizeof(server),
2778 share, sizeof(share),
2781 password, sizeof(password),
2787 if (user[0] == (char)0) fstrcpy(user, context->user);
2789 fstrcpy(workgroup, context->workgroup);
2791 srv = smbc_server(context, server, share, workgroup, user, password);
2794 return -1; /* errno set by smbc_server */
2799 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
2800 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
2801 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
2802 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
2804 if (!cli_setatr(&srv->cli, path, mode, 0)) {
2805 errno = smbc_errno(context, &srv->cli);
2812 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
2815 fstring server, share, user, password, workgroup;
2818 time_t t = (tbuf == NULL ? time(NULL) : tbuf->tv_sec);
2820 if (!context || !context->internal ||
2821 !context->internal->_initialized) {
2823 errno = EINVAL; /* Best I can think of ... */
2835 DEBUG(4, ("smbc_utimes(%s, [%s])\n", fname, ctime(&t)));
2837 if (smbc_parse_path(context, fname,
2838 server, sizeof(server),
2839 share, sizeof(share),
2842 password, sizeof(password),
2848 if (user[0] == (char)0) fstrcpy(user, context->user);
2850 fstrcpy(workgroup, context->workgroup);
2852 srv = smbc_server(context, server, share, workgroup, user, password);
2855 return -1; /* errno set by smbc_server */
2858 if (!smbc_getatr(context, srv, path,
2865 if (!cli_setatr(&srv->cli, path, mode, t)) {
2866 /* some servers always refuse directory changes */
2867 if (!(mode & aDIR)) {
2868 errno = smbc_errno(context, &srv->cli);
2877 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
2878 However NT4 gives a "The information may have been modified by a
2879 computer running Windows NT 5.0" if denied ACEs do not appear before
2882 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
2884 if (sec_ace_equal(ace1, ace2))
2887 if (ace1->type != ace2->type)
2888 return ace2->type - ace1->type;
2890 if (sid_compare(&ace1->trustee, &ace2->trustee))
2891 return sid_compare(&ace1->trustee, &ace2->trustee);
2893 if (ace1->flags != ace2->flags)
2894 return ace1->flags - ace2->flags;
2896 if (ace1->info.mask != ace2->info.mask)
2897 return ace1->info.mask - ace2->info.mask;
2899 if (ace1->size != ace2->size)
2900 return ace1->size - ace2->size;
2902 return memcmp(ace1, ace2, sizeof(SEC_ACE));
2906 static void sort_acl(SEC_ACL *the_acl)
2909 if (!the_acl) return;
2911 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
2913 for (i=1;i<the_acl->num_aces;) {
2914 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
2916 for (j=i; j<the_acl->num_aces-1; j++) {
2917 the_acl->ace[j] = the_acl->ace[j+1];
2919 the_acl->num_aces--;
2926 /* convert a SID to a string, either numeric or username/group */
2927 static void convert_sid_to_string(struct cli_state *ipc_cli,
2933 char **domains = NULL;
2934 char **names = NULL;
2935 uint32 *types = NULL;
2937 sid_to_string(str, sid);
2939 if (numeric) return; /* no lookup desired */
2941 /* Ask LSA to convert the sid to a name */
2943 if (!NT_STATUS_IS_OK(cli_lsa_lookup_sids(ipc_cli, ipc_cli->mem_ctx,
2944 pol, 1, sid, &domains,
2946 !domains || !domains[0] || !names || !names[0]) {
2952 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
2953 domains[0], lp_winbind_separator(),
2957 /* convert a string to a SID, either numeric or username/group */
2958 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
2964 uint32 *types = NULL;
2965 DOM_SID *sids = NULL;
2969 if (strncmp(str, "S-", 2) == 0) {
2970 return string_to_sid(sid, str);
2977 if (!NT_STATUS_IS_OK(cli_lsa_lookup_names(ipc_cli, ipc_cli->mem_ctx,
2978 pol, 1, &str, &sids,
2984 sid_copy(sid, &sids[0]);
2991 /* parse an ACE in the same format as print_ace() */
2992 static BOOL parse_ace(struct cli_state *ipc_cli,
3001 unsigned atype, aflags, amask;
3004 const struct perm_value *v;
3010 /* These values discovered by inspection */
3011 static const struct perm_value special_values[] = {
3012 { "R", 0x00120089 },
3013 { "W", 0x00120116 },
3014 { "X", 0x001200a0 },
3015 { "D", 0x00010000 },
3016 { "P", 0x00040000 },
3017 { "O", 0x00080000 },
3021 static const struct perm_value standard_values[] = {
3022 { "READ", 0x001200a9 },
3023 { "CHANGE", 0x001301bf },
3024 { "FULL", 0x001f01ff },
3030 p = strchr_m(str,':');
3031 if (!p) return False;
3034 /* Try to parse numeric form */
3036 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3037 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3041 /* Try to parse text form */
3043 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3048 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3052 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3053 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3054 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3055 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3060 /* Only numeric form accepted for flags at present */
3062 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3063 sscanf(tok, "%i", &aflags))) {
3067 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3071 if (strncmp(tok, "0x", 2) == 0) {
3072 if (sscanf(tok, "%i", &amask) != 1) {
3078 for (v = standard_values; v->perm; v++) {
3079 if (strcmp(tok, v->perm) == 0) {
3090 for (v = special_values; v->perm; v++) {
3091 if (v->perm[0] == *p) {
3097 if (!found) return False;
3107 init_sec_ace(ace, &sid, atype, mask, aflags);
3111 /* add an ACE to a list of ACEs in a SEC_ACL */
3112 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3117 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3121 aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces);
3122 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3123 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3124 new = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3131 /* parse a ascii version of a security descriptor */
3132 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3133 struct cli_state *ipc_cli,
3138 const char *p = str;
3142 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3146 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3148 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3149 revision = strtol(tok+9, NULL, 16);
3153 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3154 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3156 !convert_string_to_sid(ipc_cli, pol,
3158 owner_sid, tok+6)) {
3159 DEBUG(5, ("Failed to parse owner sid\n"));
3165 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3166 owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3168 !convert_string_to_sid(ipc_cli, pol,
3170 owner_sid, tok+7)) {
3171 DEBUG(5, ("Failed to parse owner sid\n"));
3177 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3178 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3180 !convert_string_to_sid(ipc_cli, pol,
3183 DEBUG(5, ("Failed to parse group sid\n"));
3189 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3190 grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
3192 !convert_string_to_sid(ipc_cli, pol,
3195 DEBUG(5, ("Failed to parse group sid\n"));
3201 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3203 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3204 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3207 if(!add_ace(&dacl, &ace, ctx)) {
3208 DEBUG(5, ("Failed to add ACL %s\n", tok));
3214 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3216 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3217 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3220 if(!add_ace(&dacl, &ace, ctx)) {
3221 DEBUG(5, ("Failed to add ACL %s\n", tok));
3227 DEBUG(5, ("Failed to parse security descriptor\n"));
3231 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3232 owner_sid, grp_sid, NULL, dacl, &sd_size);
3235 SAFE_FREE(owner_sid);
3241 /*****************************************************
3242 retrieve the acls for a file
3243 *******************************************************/
3244 static int cacl_get(TALLOC_CTX *ctx, struct cli_state *cli,
3245 struct cli_state *ipc_cli, POLICY_HND *pol,
3246 char *filename, char *name, char *buf, int bufsize)
3252 BOOL numeric = True;
3253 BOOL determine_size = (bufsize == 0);
3259 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3262 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3263 filename, cli_errstr(cli)));
3268 sd = cli_query_secdesc(cli, fnum, ctx);
3271 DEBUG(5, ("cacl_get Failed to query old descriptor\n"));
3276 cli_close(cli, fnum);
3278 all = (*name == '*');
3279 numeric = (* (name + strlen(name) - 1) != '+');
3284 if (determine_size) {
3285 p = talloc_asprintf(ctx,
3286 "REVISION:%d", sd->revision);
3293 n = snprintf(buf, bufsize,
3294 "REVISION:%d", sd->revision);
3296 } else if (StrCaseCmp(name, "revision") == 0) {
3297 if (determine_size) {
3298 p = talloc_asprintf(ctx, "%d", sd->revision);
3305 n = snprintf(buf, bufsize, "%d", sd->revision);
3309 if (!determine_size && n > bufsize) {
3317 /* Get owner and group sid */
3319 if (sd->owner_sid) {
3320 convert_sid_to_string(ipc_cli, pol,
3321 sidstr, numeric, sd->owner_sid);
3323 fstrcpy(sidstr, "");
3327 if (determine_size) {
3328 p = talloc_asprintf(ctx, ",OWNER:%s", sidstr);
3335 n = snprintf(buf, bufsize, ",OWNER:%s", sidstr);
3337 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3338 if (determine_size) {
3339 p = talloc_asprintf(ctx, "%s", sidstr);
3346 n = snprintf(buf, bufsize, "%s", sidstr);
3350 if (!determine_size && n > bufsize) {
3359 convert_sid_to_string(ipc_cli, pol,
3360 sidstr, numeric, sd->grp_sid);
3362 fstrcpy(sidstr, "");
3366 if (determine_size) {
3367 p = talloc_asprintf(ctx, ",GROUP:%s", sidstr);
3374 n = snprintf(buf, bufsize, ",GROUP:%s", sidstr);
3376 } else if (StrnCaseCmp(name, "group", 5) == 0) {
3377 if (determine_size) {
3378 p = talloc_asprintf(ctx, "%s", sidstr);
3385 n = snprintf(buf, bufsize, "%s", sidstr);
3389 if (!determine_size && n > bufsize) {
3397 /* Add aces to value buffer */
3398 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
3400 SEC_ACE *ace = &sd->dacl->ace[i];
3401 convert_sid_to_string(ipc_cli, pol,
3402 sidstr, numeric, &ace->trustee);
3405 if (determine_size) {
3406 p = talloc_asprintf(ctx,
3407 ",ACL:%s:%d/%d/0x%08x",
3418 n = snprintf(buf, bufsize,
3419 ",ACL:%s:%d/%d/0x%08x",
3425 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
3426 StrCaseCmp(name + 3, sidstr) == 0) ||
3427 (StrnCaseCmp(name, "acl+", 4) == 0 &&
3428 StrCaseCmp(name + 4, sidstr) == 0)) {
3429 if (determine_size) {
3430 p = talloc_asprintf(ctx,
3441 n = snprintf(buf, bufsize,
3443 ace->type, ace->flags, ace->info.mask);
3463 /*****************************************************
3464 set the ACLs on a file given an ascii description
3465 *******************************************************/
3466 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
3467 struct cli_state *ipc_cli, POLICY_HND *pol,
3468 const char *filename, const char *the_acl,
3469 int mode, int flags)
3473 SEC_DESC *sd = NULL, *old;
3474 SEC_ACL *dacl = NULL;
3475 DOM_SID *owner_sid = NULL;
3476 DOM_SID *grp_sid = NULL;
3481 BOOL numeric = True;
3483 /* the_acl will be null for REMOVE_ALL operations */
3485 numeric = ((p = strchr(the_acl, ':')) != NULL &&
3489 /* if this is to set the entire ACL... */
3490 if (*the_acl == '*') {
3491 /* ... then increment past the first colon */
3495 sd = sec_desc_parse(ctx, ipc_cli, pol,
3496 numeric, (char *) the_acl);
3504 /* The desired access below is the only one I could find that works
3505 with NT4, W2KP and Samba */
3507 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3510 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3511 filename, cli_errstr(cli)));
3516 old = cli_query_secdesc(cli, fnum, ctx);
3519 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
3524 cli_close(cli, fnum);
3527 case SMBC_XATTR_MODE_REMOVE_ALL:
3528 old->dacl->num_aces = 0;
3529 SAFE_FREE(old->dacl->ace);
3530 SAFE_FREE(old->dacl);
3535 case SMBC_XATTR_MODE_REMOVE:
3536 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3539 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3540 if (sec_ace_equal(&sd->dacl->ace[i],
3541 &old->dacl->ace[j])) {
3543 for (k=j; k<old->dacl->num_aces-1;k++) {
3544 old->dacl->ace[k] = old->dacl->ace[k+1];
3546 old->dacl->num_aces--;
3547 if (old->dacl->num_aces == 0) {
3548 SAFE_FREE(old->dacl->ace);
3549 SAFE_FREE(old->dacl);
3566 case SMBC_XATTR_MODE_ADD:
3567 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3570 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3571 if (sid_equal(&sd->dacl->ace[i].trustee,
3572 &old->dacl->ace[j].trustee)) {
3573 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
3578 old->dacl->ace[j] = sd->dacl->ace[i];
3584 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
3590 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3591 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
3597 case SMBC_XATTR_MODE_SET:
3599 owner_sid = old->owner_sid;
3600 grp_sid = old->grp_sid;
3604 case SMBC_XATTR_MODE_CHOWN:
3605 owner_sid = sd->owner_sid;
3608 case SMBC_XATTR_MODE_CHGRP:
3609 grp_sid = sd->grp_sid;
3613 /* Denied ACE entries must come before allowed ones */
3614 sort_acl(old->dacl);
3616 /* Create new security descriptor and set it */
3617 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
3618 owner_sid, grp_sid, NULL, dacl, &sd_size);
3620 fnum = cli_nt_create(cli, filename,
3621 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
3624 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3625 filename, cli_errstr(cli)));
3630 if (!cli_set_secdesc(cli, fnum, sd)) {
3631 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
3638 cli_close(cli, fnum);
3648 int smbc_setxattr_ctx(SMBCCTX *context,
3658 fstring server, share, user, password, workgroup;
3663 if (!context || !context->internal ||
3664 !context->internal->_initialized) {
3666 errno = EINVAL; /* Best I can think of ... */
3678 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
3679 fname, name, (int) size, (char *) value));
3681 if (smbc_parse_path(context, fname,
3682 server, sizeof(server),
3683 share, sizeof(share),
3686 password, sizeof(password),
3692 if (user[0] == (char)0) fstrcpy(user, context->user);
3694 fstrcpy(workgroup, context->workgroup);
3696 srv = smbc_server(context, server, share, workgroup, user, password);
3698 return -1; /* errno set by smbc_server */
3701 ipc_srv = smbc_attr_server(context, server, share,
3702 workgroup, user, password,
3708 ctx = talloc_init("smbc_setxattr");
3715 * Are they asking to set an access control element or to set
3716 * the entire access control list?
3718 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3719 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3720 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3721 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3722 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3726 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3731 ret = cacl_set(ctx, &srv->cli,
3732 &ipc_srv->cli, &pol, path,
3735 ? SMBC_XATTR_MODE_SET
3736 : SMBC_XATTR_MODE_ADD),
3739 talloc_destroy(ctx);
3744 * Are they asking to set the owner?
3746 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3747 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
3751 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3756 ret = cacl_set(ctx, &srv->cli,
3757 &ipc_srv->cli, &pol, path,
3758 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3760 talloc_destroy(ctx);
3765 * Are they asking to set the group?
3767 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3768 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
3772 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3777 ret = cacl_set(ctx, &srv->cli,
3778 &ipc_srv->cli, &pol, path,
3779 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3781 talloc_destroy(ctx);
3785 /* Unsupported attribute name */
3786 talloc_destroy(ctx);
3791 int smbc_getxattr_ctx(SMBCCTX *context,
3800 fstring server, share, user, password, workgroup;
3805 if (!context || !context->internal ||
3806 !context->internal->_initialized) {
3808 errno = EINVAL; /* Best I can think of ... */
3820 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
3822 if (smbc_parse_path(context, fname,
3823 server, sizeof(server),
3824 share, sizeof(share),
3827 password, sizeof(password),
3833 if (user[0] == (char)0) fstrcpy(user, context->user);
3835 fstrcpy(workgroup, context->workgroup);
3837 srv = smbc_server(context, server, share, workgroup, user, password);
3839 return -1; /* errno set by smbc_server */
3842 ipc_srv = smbc_attr_server(context, server, share,
3843 workgroup, user, password,
3849 ctx = talloc_init("smbc:getxattr");
3855 /* Are they requesting a supported attribute? */
3856 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3857 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3858 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3859 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3860 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3861 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3862 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3863 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3864 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3867 ret = cacl_get(ctx, &srv->cli,
3868 &ipc_srv->cli, &pol,
3869 (char *) path, (char *) name + 19,
3870 (char *) value, size);
3871 if (ret < 0 && errno == 0) {
3872 errno = smbc_errno(context, &srv->cli);
3874 talloc_destroy(ctx);
3878 /* Unsupported attribute name */
3879 talloc_destroy(ctx);
3885 int smbc_removexattr_ctx(SMBCCTX *context,
3892 fstring server, share, user, password, workgroup;
3897 if (!context || !context->internal ||
3898 !context->internal->_initialized) {
3900 errno = EINVAL; /* Best I can think of ... */
3912 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
3914 if (smbc_parse_path(context, fname,
3915 server, sizeof(server),
3916 share, sizeof(share),
3919 password, sizeof(password),
3925 if (user[0] == (char)0) fstrcpy(user, context->user);
3927 fstrcpy(workgroup, context->workgroup);
3929 srv = smbc_server(context, server, share, workgroup, user, password);
3931 return -1; /* errno set by smbc_server */
3934 ipc_srv = smbc_attr_server(context, server, share,
3935 workgroup, user, password,
3941 ipc_srv = smbc_attr_server(context, server, share,
3942 workgroup, user, password,
3948 ctx = talloc_init("smbc_removexattr");
3954 /* Are they asking to set the entire ACL? */
3955 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3956 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
3959 ret = cacl_set(ctx, &srv->cli,
3960 &ipc_srv->cli, &pol, path,
3961 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
3962 talloc_destroy(ctx);
3967 * Are they asking to remove one or more spceific security descriptor
3970 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3971 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3972 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3973 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3974 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3975 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3976 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3979 ret = cacl_set(ctx, &srv->cli,
3980 &ipc_srv->cli, &pol, path,
3981 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
3982 talloc_destroy(ctx);
3986 /* Unsupported attribute name */
3987 talloc_destroy(ctx);
3992 int smbc_listxattr_ctx(SMBCCTX *context,
3998 * This isn't quite what listxattr() is supposed to do. This returns
3999 * the complete set of attributes, always, rather than only those
4000 * attribute names which actually exist for a file. Hmmm...
4002 const char supported[] =
4003 "system.nt_sec_desc.revision\0"
4004 "system.nt_sec_desc.owner\0"
4005 "system.nt_sec_desc.owner+\0"
4006 "system.nt_sec_desc.group\0"
4007 "system.nt_sec_desc.group+\0"
4008 "system.nt_sec_desc.acl\0"
4009 "system.nt_sec_desc.acl+\0"
4010 "system.nt_sec_desc.*\0"
4011 "system.nt_sec_desc.*+\0"
4015 return sizeof(supported);
4018 if (sizeof(supported) > size) {
4023 /* this can't be strcpy() because there are embedded null characters */
4024 memcpy(list, supported, sizeof(supported));
4025 return sizeof(supported);
4030 * Open a print file to be written to by other calls
4033 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
4035 fstring server, share, user, password;
4038 if (!context || !context->internal ||
4039 !context->internal->_initialized) {
4053 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
4055 if (smbc_parse_path(context, fname,
4056 server, sizeof(server),
4057 share, sizeof(share),
4060 password, sizeof(password),
4066 /* What if the path is empty, or the file exists? */
4068 return context->open(context, fname, O_WRONLY, 666);
4073 * Routine to print a file on a remote server ...
4075 * We open the file, which we assume to be on a remote server, and then
4076 * copy it to a print file on the share specified by printq.
4079 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
4081 SMBCFILE *fid1, *fid2;
4082 int bytes, saverr, tot_bytes = 0;
4085 if (!c_file || !c_file->internal->_initialized || !c_print ||
4086 !c_print->internal->_initialized) {
4093 if (!fname && !printq) {
4100 /* Try to open the file for reading ... */
4102 if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
4104 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
4105 return -1; /* smbc_open sets errno */
4109 /* Now, try to open the printer file for writing */
4111 if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
4113 saverr = errno; /* Save errno */
4114 c_file->close(c_file, fid1);
4120 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
4124 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
4127 c_file->close(c_file, fid1);
4128 c_print->close(c_print, fid2);
4137 c_file->close(c_file, fid1); /* We have to close these anyway */
4138 c_print->close(c_print, fid2);
4152 * Routine to list print jobs on a printer share ...
4155 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
4158 fstring server, share, user, password, workgroup;
4161 if (!context || !context->internal ||
4162 !context->internal->_initialized) {
4176 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
4178 if (smbc_parse_path(context, fname,
4179 server, sizeof(server),
4180 share, sizeof(share),
4183 password, sizeof(password),
4189 if (user[0] == (char)0) fstrcpy(user, context->user);
4191 fstrcpy(workgroup, context->workgroup);
4193 srv = smbc_server(context, server, share, workgroup, user, password);
4197 return -1; /* errno set by smbc_server */
4201 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
4203 errno = smbc_errno(context, &srv->cli);
4213 * Delete a print job from a remote printer share
4216 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
4219 fstring server, share, user, password, workgroup;
4223 if (!context || !context->internal ||
4224 !context->internal->_initialized) {
4238 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
4240 if (smbc_parse_path(context, fname,
4241 server, sizeof(server),
4242 share, sizeof(share),
4245 password, sizeof(password),
4251 if (user[0] == (char)0) fstrcpy(user, context->user);
4253 fstrcpy(workgroup, context->workgroup);
4255 srv = smbc_server(context, server, share, workgroup, user, password);
4259 return -1; /* errno set by smbc_server */
4263 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
4266 errno = smbc_errno(context, &srv->cli);
4267 else if (err == ERRnosuchprintjob)
4278 * Get a new empty handle to fill in with your own info
4280 SMBCCTX * smbc_new_context(void)
4284 context = SMB_MALLOC_P(SMBCCTX);
4290 ZERO_STRUCTP(context);
4292 context->internal = SMB_MALLOC_P(struct smbc_internal_data);
4293 if (!context->internal) {
4298 ZERO_STRUCTP(context->internal);
4301 /* ADD REASONABLE DEFAULTS */
4303 context->timeout = 20000; /* 20 seconds */
4305 context->open = smbc_open_ctx;
4306 context->creat = smbc_creat_ctx;
4307 context->read = smbc_read_ctx;
4308 context->write = smbc_write_ctx;
4309 context->close = smbc_close_ctx;
4310 context->unlink = smbc_unlink_ctx;
4311 context->rename = smbc_rename_ctx;
4312 context->lseek = smbc_lseek_ctx;
4313 context->stat = smbc_stat_ctx;
4314 context->fstat = smbc_fstat_ctx;
4315 context->opendir = smbc_opendir_ctx;
4316 context->closedir = smbc_closedir_ctx;
4317 context->readdir = smbc_readdir_ctx;
4318 context->getdents = smbc_getdents_ctx;
4319 context->mkdir = smbc_mkdir_ctx;
4320 context->rmdir = smbc_rmdir_ctx;
4321 context->telldir = smbc_telldir_ctx;
4322 context->lseekdir = smbc_lseekdir_ctx;
4323 context->fstatdir = smbc_fstatdir_ctx;
4324 context->chmod = smbc_chmod_ctx;
4325 context->utimes = smbc_utimes_ctx;
4326 context->setxattr = smbc_setxattr_ctx;
4327 context->getxattr = smbc_getxattr_ctx;
4328 context->removexattr = smbc_removexattr_ctx;
4329 context->listxattr = smbc_listxattr_ctx;
4330 context->open_print_job = smbc_open_print_job_ctx;
4331 context->print_file = smbc_print_file_ctx;
4332 context->list_print_jobs = smbc_list_print_jobs_ctx;
4333 context->unlink_print_job = smbc_unlink_print_job_ctx;
4335 context->callbacks.check_server_fn = smbc_check_server;
4336 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
4338 smbc_default_cache_functions(context);
4346 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
4347 * and thus you'll be leaking memory if not handled properly.
4350 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
4359 DEBUG(1,("Performing aggressive shutdown.\n"));
4361 f = context->internal->_files;
4363 context->close(context, f);
4366 context->internal->_files = NULL;
4368 /* First try to remove the servers the nice way. */
4369 if (context->callbacks.purge_cached_fn(context)) {
4372 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
4373 s = context->internal->_servers;
4375 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
4376 cli_shutdown(&s->cli);
4377 context->callbacks.remove_cached_srv_fn(context, s);
4379 DLIST_REMOVE(context->internal->_servers, s);
4383 context->internal->_servers = NULL;
4387 /* This is the polite way */
4388 if (context->callbacks.purge_cached_fn(context)) {
4389 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
4393 if (context->internal->_servers) {
4394 DEBUG(1, ("Active servers in context, free_context failed.\n"));
4398 if (context->internal->_files) {
4399 DEBUG(1, ("Active files in context, free_context failed.\n"));
4405 /* Things we have to clean up */
4406 SAFE_FREE(context->workgroup);
4407 SAFE_FREE(context->netbios_name);
4408 SAFE_FREE(context->user);
4410 DEBUG(3, ("Context %p succesfully freed\n", context));
4411 SAFE_FREE(context->internal);
4418 * Initialise the library etc
4420 * We accept a struct containing handle information.
4421 * valid values for info->debug from 0 to 100,
4422 * and insist that info->fn must be non-null.
4424 SMBCCTX * smbc_init_context(SMBCCTX * context)
4428 char *user = NULL, *home = NULL;
4430 if (!context || !context->internal) {
4435 /* Do not initialise the same client twice */
4436 if (context->internal->_initialized) {
4440 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
4447 if (!smbc_initialized) {
4448 /* Do some library wide intialisations the first time we get called */
4450 /* Set this to what the user wants */
4451 DEBUGLEVEL = context->debug;
4453 setup_logging( "libsmbclient", True);
4455 /* Here we would open the smb.conf file if needed ... */
4457 home = getenv("HOME");
4459 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
4461 load_interfaces(); /* Load the list of interfaces ... */
4463 in_client = True; /* FIXME, make a param */
4465 if (!lp_load(conf, True, False, False)) {
4468 * Well, if that failed, try the dyn_CONFIGFILE
4469 * Which points to the standard locn, and if that
4470 * fails, silently ignore it and use the internal
4474 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
4475 DEBUG(5, ("Could not load either config file: %s or %s\n",
4476 conf, dyn_CONFIGFILE));
4480 reopen_logs(); /* Get logging working ... */
4483 * Block SIGPIPE (from lib/util_sock.c: write())
4484 * It is not needed and should not stop execution
4486 BlockSignals(True, SIGPIPE);
4488 /* Done with one-time initialisation */
4489 smbc_initialized = 1;
4493 if (!context->user) {
4495 * FIXME: Is this the best way to get the user info?
4497 user = getenv("USER");
4498 /* walk around as "guest" if no username can be found */
4499 if (!user) context->user = SMB_STRDUP("guest");
4500 else context->user = SMB_STRDUP(user);
4503 if (!context->netbios_name) {
4505 * We try to get our netbios name from the config. If that fails we fall
4506 * back on constructing our netbios name from our hostname etc
4508 if (global_myname()) {
4509 context->netbios_name = SMB_STRDUP(global_myname());
4513 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
4516 context->netbios_name = SMB_MALLOC(17);
4517 if (!context->netbios_name) {
4521 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
4525 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
4527 if (!context->workgroup) {
4528 if (lp_workgroup()) {
4529 context->workgroup = SMB_STRDUP(lp_workgroup());
4532 /* TODO: Think about a decent default workgroup */
4533 context->workgroup = SMB_STRDUP("samba");
4537 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
4539 /* shortest timeout is 1 second */
4540 if (context->timeout > 0 && context->timeout < 1000)
4541 context->timeout = 1000;
4544 * FIXME: Should we check the function pointers here?
4547 context->internal->_initialized = 1;