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*)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 c.timeout = context->timeout;
589 /* Force use of port 139 for first try, so browse lists can work */
592 if (!cli_connect(&c, server_n, &ip)) {
594 * Port 139 connection failed. Try port 445 to handle
595 * connections to newer (e.g. XP) hosts with NetBIOS disabled.
598 if (!cli_connect(&c, server_n, &ip)) {
604 if (!cli_session_request(&c, &calling, &called)) {
606 if (strcmp(called.name, "*SMBSERVER")) {
607 make_nmb_name(&called , "*SMBSERVER", 0x20);
610 else { /* Try one more time, but ensure we don't loop */
612 /* Only try this if server is an IP address ... */
614 if (is_ipaddress(server) && !tried_reverse) {
616 struct in_addr rem_ip;
618 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
619 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
624 tried_reverse++; /* Yuck */
626 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
627 make_nmb_name(&called, remote_name, 0x20);
638 DEBUG(4,(" session request ok\n"));
640 if (!cli_negprot(&c)) {
646 if (!cli_session_setup(&c, username,
647 password, strlen(password),
648 password, strlen(password),
650 /* try an anonymous login if it failed */
651 !cli_session_setup(&c, "", "", 1,"", 0, workgroup)) {
657 DEBUG(4,(" session setup ok\n"));
659 if (!cli_send_tconX(&c, share, "?????",
660 password, strlen(password)+1)) {
661 errno = smbc_errno(context, &c);
666 DEBUG(4,(" tconx ok\n"));
669 * Ok, we have got a nice connection
670 * Let's find a free server_fd
673 srv = (SMBCSRV *)malloc(sizeof(*srv));
681 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
683 /* now add it to the cache (internal or external) */
684 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
685 DEBUG(3, (" Failed to add server to cache\n"));
690 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
691 server, share, srv));
693 DLIST_ADD(context->internal->_servers, srv);
698 if (!srv) return NULL;
705 * Connect to a server for getting/setting attributes, possibly on an existing
706 * connection. This works similarly to smbc_server().
708 SMBCSRV *smbc_attr_server(SMBCCTX *context,
709 const char *server, const char *share,
711 fstring username, fstring password,
715 struct cli_state *ipc_cli;
717 SMBCSRV *ipc_srv=NULL;
720 * See if we've already created this special connection. Reference
721 * our "special" share name 'IPC$$'.
723 ipc_srv = find_server(context, server, "IPC$$",
724 workgroup, username, password);
727 /* We didn't find a cached connection. Get the password */
728 if (*password == '\0') {
729 /* ... then retrieve it now. */
730 context->callbacks.auth_fn(server, share,
731 workgroup, sizeof(fstring),
732 username, sizeof(fstring),
733 password, sizeof(fstring));
737 nt_status = cli_full_connection(&ipc_cli,
738 global_myname(), server,
739 &ip, 0, "IPC$", "?????",
743 if (! NT_STATUS_IS_OK(nt_status)) {
744 DEBUG(1,("cli_full_connection failed! (%s)\n",
745 nt_errstr(nt_status)));
750 if (!cli_nt_session_open(ipc_cli, PI_LSARPC)) {
751 DEBUG(1, ("cli_nt_session_open fail!\n"));
753 cli_shutdown(ipc_cli);
757 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
758 but NT sends 0x2000000 so we might as well do it too. */
760 nt_status = cli_lsa_open_policy(ipc_cli,
763 GENERIC_EXECUTE_ACCESS,
766 if (!NT_STATUS_IS_OK(nt_status)) {
767 errno = smbc_errno(context, ipc_cli);
768 cli_shutdown(ipc_cli);
772 ipc_srv = (SMBCSRV *)malloc(sizeof(*ipc_srv));
775 cli_shutdown(ipc_cli);
779 ZERO_STRUCTP(ipc_srv);
780 ipc_srv->cli = *ipc_cli;
784 /* now add it to the cache (internal or external) */
786 errno = 0; /* let cache function set errno if it likes */
787 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
792 DEBUG(3, (" Failed to add server to cache\n"));
796 cli_shutdown(&ipc_srv->cli);
801 DLIST_ADD(context->internal->_servers, ipc_srv);
808 * Routine to open() a file ...
811 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
813 fstring server, share, user, password, workgroup;
816 SMBCFILE *file = NULL;
819 if (!context || !context->internal ||
820 !context->internal->_initialized) {
822 errno = EINVAL; /* Best I can think of ... */
834 if (smbc_parse_path(context, fname,
835 server, sizeof(server),
836 share, sizeof(share),
839 password, sizeof(password),
845 if (user[0] == (char)0) fstrcpy(user, context->user);
847 fstrcpy(workgroup, context->workgroup);
849 srv = smbc_server(context, server, share, workgroup, user, password);
853 if (errno == EPERM) errno = EACCES;
854 return NULL; /* smbc_server sets errno */
858 /* Hmmm, the test for a directory is suspect here ... FIXME */
860 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
867 file = malloc(sizeof(SMBCFILE));
878 if ((fd = cli_open(&srv->cli, path, flags, DENY_NONE)) < 0) {
880 /* Handle the error ... */
883 errno = smbc_errno(context, &srv->cli);
888 /* Fill in file struct */
891 file->fname = strdup(fname);
896 DLIST_ADD(context->internal->_files, file);
901 /* Check if opendir needed ... */
906 eno = smbc_errno(context, &srv->cli);
907 file = context->opendir(context, fname);
908 if (!file) errno = eno;
913 errno = EINVAL; /* FIXME, correct errno ? */
919 * Routine to create a file
922 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
924 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
927 if (!context || !context->internal ||
928 !context->internal->_initialized) {
935 return smbc_open_ctx(context, path, creat_bits, mode);
939 * Routine to read() a file ...
942 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
946 if (!context || !context->internal ||
947 !context->internal->_initialized) {
954 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
956 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
963 /* Check that the buffer exists ... */
972 ret = cli_read(&file->srv->cli, file->cli_fd, buf, file->offset, count);
976 errno = smbc_errno(context, &file->srv->cli);
983 DEBUG(4, (" --> %d\n", ret));
985 return ret; /* Success, ret bytes of data ... */
990 * Routine to write() a file ...
993 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
997 if (!context || !context->internal ||
998 !context->internal->_initialized) {
1005 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1012 /* Check that the buffer exists ... */
1021 ret = cli_write(&file->srv->cli, file->cli_fd, 0, buf, file->offset, count);
1025 errno = smbc_errno(context, &file->srv->cli);
1030 file->offset += ret;
1032 return ret; /* Success, 0 bytes of data ... */
1036 * Routine to close() a file ...
1039 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1043 if (!context || !context->internal ||
1044 !context->internal->_initialized) {
1051 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1061 return context->closedir(context, file);
1065 if (!cli_close(&file->srv->cli, file->cli_fd)) {
1067 DEBUG(3, ("cli_close failed on %s. purging server.\n",
1069 /* Deallocate slot and remove the server
1070 * from the server cache if unused */
1071 errno = smbc_errno(context, &file->srv->cli);
1073 DLIST_REMOVE(context->internal->_files, file);
1074 SAFE_FREE(file->fname);
1076 context->callbacks.remove_unused_server_fn(context, srv);
1082 DLIST_REMOVE(context->internal->_files, file);
1083 SAFE_FREE(file->fname);
1090 * Get info from an SMB server on a file. Use a qpathinfo call first
1091 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1093 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
1094 uint16 *mode, size_t *size,
1095 time_t *c_time, time_t *a_time, time_t *m_time,
1099 if (!context || !context->internal ||
1100 !context->internal->_initialized) {
1107 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1109 if (!srv->no_pathinfo2 &&
1110 cli_qpathinfo2(&srv->cli, path, c_time, a_time, m_time, NULL,
1111 size, mode, ino)) return True;
1113 /* if this is NT then don't bother with the getatr */
1114 if (srv->cli.capabilities & CAP_NT_SMBS) {
1119 if (cli_getatr(&srv->cli, path, mode, size, m_time)) {
1120 a_time = c_time = m_time;
1121 srv->no_pathinfo2 = True;
1131 * Routine to unlink() a file
1134 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1136 fstring server, share, user, password, workgroup;
1138 SMBCSRV *srv = NULL;
1140 if (!context || !context->internal ||
1141 !context->internal->_initialized) {
1143 errno = EINVAL; /* Best I can think of ... */
1155 if (smbc_parse_path(context, fname,
1156 server, sizeof(server),
1157 share, sizeof(share),
1160 password, sizeof(password),
1166 if (user[0] == (char)0) fstrcpy(user, context->user);
1168 fstrcpy(workgroup, context->workgroup);
1170 srv = smbc_server(context, server, share, workgroup, user, password);
1174 return -1; /* smbc_server sets errno */
1178 /* if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
1180 int job = smbc_stat_printjob(srv, path, NULL, NULL);
1186 if ((err = cli_printjob_del(&srv->cli, job)) != 0) {
1194 if (!cli_unlink(&srv->cli, path)) {
1196 errno = smbc_errno(context, &srv->cli);
1198 if (errno == EACCES) { /* Check if the file is a directory */
1203 time_t m_time = 0, a_time = 0, c_time = 0;
1206 if (!smbc_getatr(context, srv, path, &mode, &size,
1207 &c_time, &a_time, &m_time, &ino)) {
1209 /* Hmmm, bad error ... What? */
1211 errno = smbc_errno(context, &srv->cli);
1217 if (IS_DOS_DIR(mode))
1220 errno = saverr; /* Restore this */
1229 return 0; /* Success ... */
1234 * Routine to rename() a file
1237 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1238 SMBCCTX *ncontext, const char *nname)
1240 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1241 pstring path1, path2;
1242 SMBCSRV *srv = NULL;
1244 if (!ocontext || !ncontext ||
1245 !ocontext->internal || !ncontext->internal ||
1246 !ocontext->internal->_initialized ||
1247 !ncontext->internal->_initialized) {
1249 errno = EINVAL; /* Best I can think of ... */
1254 if (!oname || !nname) {
1261 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1263 smbc_parse_path(ocontext, oname,
1264 server1, sizeof(server1),
1265 share1, sizeof(share1),
1266 path1, sizeof(path1),
1267 user1, sizeof(user1),
1268 password1, sizeof(password1),
1271 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1273 smbc_parse_path(ncontext, nname,
1274 server2, sizeof(server2),
1275 share2, sizeof(share2),
1276 path2, sizeof(path2),
1277 user2, sizeof(user2),
1278 password2, sizeof(password2),
1281 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1283 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1284 strcmp(user1, user2)) {
1286 /* Can't rename across file systems, or users?? */
1293 fstrcpy(workgroup, ocontext->workgroup);
1294 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1295 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1302 if (!cli_rename(&srv->cli, path1, path2)) {
1303 int eno = smbc_errno(ocontext, &srv->cli);
1305 if (eno != EEXIST ||
1306 !cli_unlink(&srv->cli, path2) ||
1307 !cli_rename(&srv->cli, path1, path2)) {
1315 return 0; /* Success */
1320 * A routine to lseek() a file
1323 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1327 if (!context || !context->internal ||
1328 !context->internal->_initialized) {
1335 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1345 return -1; /* Can't lseek a dir ... */
1351 file->offset = offset;
1355 file->offset += offset;
1359 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
1362 SMB_BIG_UINT b_size = size;
1363 if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
1371 file->offset = size + offset;
1380 return file->offset;
1385 * Generate an inode number from file name for those things that need it
1389 ino_t smbc_inode(SMBCCTX *context, const char *name)
1392 if (!context || !context->internal ||
1393 !context->internal->_initialized) {
1400 if (!*name) return 2; /* FIXME, why 2 ??? */
1401 return (ino_t)str_checksum(name);
1406 * Routine to put basic stat info into a stat structure ... Used by stat and
1411 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname, size_t size, int mode)
1416 if (IS_DOS_DIR(mode)) {
1417 st->st_mode = SMBC_DIR_MODE;
1419 st->st_mode = SMBC_FILE_MODE;
1422 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1423 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1424 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1425 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1428 #ifdef HAVE_STAT_ST_BLKSIZE
1429 st->st_blksize = 512;
1431 #ifdef HAVE_STAT_ST_BLOCKS
1432 st->st_blocks = (size+511)/512;
1434 st->st_uid = getuid();
1435 st->st_gid = getgid();
1437 if (IS_DOS_DIR(mode)) {
1443 if (st->st_ino == 0) {
1444 st->st_ino = smbc_inode(context, fname);
1447 return True; /* FIXME: Is this needed ? */
1452 * Routine to stat a file given a name
1455 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1458 fstring server, share, user, password, workgroup;
1460 time_t m_time = 0, a_time = 0, c_time = 0;
1465 if (!context || !context->internal ||
1466 !context->internal->_initialized) {
1468 errno = EINVAL; /* Best I can think of ... */
1480 DEBUG(4, ("smbc_stat(%s)\n", fname));
1482 if (smbc_parse_path(context, fname,
1483 server, sizeof(server),
1484 share, sizeof(share),
1487 password, sizeof(password),
1493 if (user[0] == (char)0) fstrcpy(user, context->user);
1495 fstrcpy(workgroup, context->workgroup);
1497 srv = smbc_server(context, server, share, workgroup, user, password);
1500 return -1; /* errno set by smbc_server */
1503 if (!smbc_getatr(context, srv, path, &mode, &size,
1504 &c_time, &a_time, &m_time, &ino)) {
1506 errno = smbc_errno(context, &srv->cli);
1513 smbc_setup_stat(context, st, path, size, mode);
1515 st->st_atime = a_time;
1516 st->st_ctime = c_time;
1517 st->st_mtime = m_time;
1518 st->st_dev = srv->dev;
1525 * Routine to stat a file given an fd
1528 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1530 time_t c_time, a_time, m_time;
1535 if (!context || !context->internal ||
1536 !context->internal->_initialized) {
1543 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1552 return context->fstatdir(context, file, st);
1556 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
1557 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
1558 SMB_BIG_UINT b_size = size;
1559 if (!cli_getattrE(&file->srv->cli, file->cli_fd,
1560 &mode, &b_size, &c_time, &a_time, &m_time)) {
1571 smbc_setup_stat(context, st, file->fname, size, mode);
1573 st->st_atime = a_time;
1574 st->st_ctime = c_time;
1575 st->st_mtime = m_time;
1576 st->st_dev = file->srv->dev;
1583 * Routine to open a directory
1584 * We accept the URL syntax explained in smbc_parse_path(), above.
1587 static void smbc_remove_dir(SMBCFILE *dir)
1589 struct smbc_dir_list *d,*f;
1596 SAFE_FREE(f->dirent);
1601 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
1605 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
1607 struct smbc_dirent *dirent;
1609 char *u_name = NULL, *u_comment = NULL;
1610 size_t u_name_len = 0, u_comment_len = 0;
1613 u_name_len = push_utf8_allocate(&u_name, name);
1615 u_comment_len = push_utf8_allocate(&u_comment, comment);
1618 * Allocate space for the dirent, which must be increased by the
1619 * size of the name and the comment and 1 for the null on the comment.
1620 * The null on the name is already accounted for.
1623 size = sizeof(struct smbc_dirent) + u_name_len + u_comment_len + 1;
1625 dirent = malloc(size);
1629 dir->dir_error = ENOMEM;
1634 ZERO_STRUCTP(dirent);
1636 if (dir->dir_list == NULL) {
1638 dir->dir_list = malloc(sizeof(struct smbc_dir_list));
1639 if (!dir->dir_list) {
1642 dir->dir_error = ENOMEM;
1646 ZERO_STRUCTP(dir->dir_list);
1648 dir->dir_end = dir->dir_next = dir->dir_list;
1652 dir->dir_end->next = malloc(sizeof(struct smbc_dir_list));
1654 if (!dir->dir_end->next) {
1657 dir->dir_error = ENOMEM;
1661 ZERO_STRUCTP(dir->dir_end->next);
1663 dir->dir_end = dir->dir_end->next;
1666 dir->dir_end->next = NULL;
1667 dir->dir_end->dirent = dirent;
1669 dirent->smbc_type = type;
1670 dirent->namelen = u_name_len;
1671 dirent->commentlen = u_comment_len;
1672 dirent->dirlen = size;
1674 strncpy(dirent->name, (u_name?u_name:""), dirent->namelen + 1);
1676 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
1677 strncpy(dirent->comment, (u_comment?u_comment:""), dirent->commentlen + 1);
1679 SAFE_FREE(u_comment);
1687 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
1689 SMBCFILE *dir = (SMBCFILE *)state;
1690 struct smbc_dir_list *dir_list;
1691 struct smbc_dirent *dirent;
1695 dirent_type = dir->dir_type;
1697 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1699 /* An error occurred, what do we do? */
1700 /* FIXME: Add some code here */
1703 /* Point to the one just added */
1704 dirent = dir->dir_end->dirent;
1706 /* See if this was a duplicate */
1707 for (dir_list = dir->dir_list;
1708 dir_list != dir->dir_end;
1709 dir_list = dir_list->next) {
1711 strcmp(dir_list->dirent->name, dirent->name) == 0) {
1712 /* Duplicate. End end of list need to be removed. */
1716 if (remove && dir_list->next == dir->dir_end) {
1717 /* Found the end of the list. Remove it. */
1718 dir->dir_end = dir_list;
1719 free(dir_list->next);
1720 dir_list->next = NULL;
1727 list_fn(const char *name, uint32 type, const char *comment, void *state)
1729 SMBCFILE *dir = (SMBCFILE *)state;
1732 /* We need to process the type a little ... */
1734 if (dir->dir_type == SMBC_FILE_SHARE) {
1737 case 0: /* Directory tree */
1738 dirent_type = SMBC_FILE_SHARE;
1742 dirent_type = SMBC_PRINTER_SHARE;
1746 dirent_type = SMBC_COMMS_SHARE;
1750 dirent_type = SMBC_IPC_SHARE;
1754 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
1758 else dirent_type = dir->dir_type;
1760 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1762 /* An error occurred, what do we do? */
1763 /* FIXME: Add some code here */
1769 dir_list_fn(file_info *finfo, const char *mask, void *state)
1772 if (add_dirent((SMBCFILE *)state, finfo->name, "",
1773 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
1775 /* Handle an error ... */
1777 /* FIXME: Add some code ... */
1783 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
1785 fstring server, share, user, password, options;
1788 SMBCSRV *srv = NULL;
1789 SMBCFILE *dir = NULL;
1790 struct in_addr rem_ip;
1792 if (!context || !context->internal ||
1793 !context->internal->_initialized) {
1794 DEBUG(4, ("no valid context\n"));
1801 DEBUG(4, ("no valid fname\n"));
1806 if (smbc_parse_path(context, fname,
1807 server, sizeof(server),
1808 share, sizeof(share),
1811 password, sizeof(password),
1812 options, sizeof(options))) {
1813 DEBUG(4, ("no valid path\n"));
1818 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
1820 /* Ensure the options are valid */
1821 if (smbc_check_options(server, share, path, options)) {
1822 DEBUG(4, ("unacceptable options (%s)\n", options));
1827 if (user[0] == (char)0) fstrcpy(user, context->user);
1829 pstrcpy(workgroup, context->workgroup);
1831 dir = malloc(sizeof(*dir));
1843 dir->fname = strdup(fname);
1847 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
1849 if (server[0] == (char)0 &&
1850 (! *options || strcmp(options, "mb=.any") == 0)) {
1851 struct in_addr server_ip;
1852 if (share[0] != (char)0 || path[0] != (char)0) {
1856 SAFE_FREE(dir->fname);
1863 * We have server and share and path empty ... so list the
1864 * workgroups first try to get the LMB for our workgroup, and
1865 * if that fails, try the DMB
1868 pstrcpy(workgroup, lp_workgroup());
1870 if (!find_master_ip(workgroup, &server_ip)) {
1871 struct user_auth_info u_info;
1872 struct cli_state *cli;
1874 DEBUG(4, ("Unable to find master browser for workgroup %s\n",
1877 /* find the name of the server ... */
1878 pstrcpy(u_info.username, user);
1879 pstrcpy(u_info.password, password);
1881 if (!(cli = get_ipc_connect_master_ip_bcast(workgroup, &u_info))) {
1882 DEBUG(4, ("Unable to find master browser by "
1888 fstrcpy(server, cli->desthost);
1893 * Do a name status query to find out the name of the
1894 * master browser. We use <01><02>__MSBROWSE__<02>#01 if
1895 * *#00 fails because a domain master browser will not
1896 * respond to a wildcard query (or, at least, an NT4
1897 * server acting as the domain master browser will not).
1899 * We might be able to use ONLY the query on MSBROWSE, but
1900 * that's not yet been tested with all Windows versions,
1901 * so until it is, leave the original wildcard query as
1902 * the first choice and fall back to MSBROWSE if the
1903 * wildcard query fails.
1905 if (!name_status_find("*", 0, 0x1d, server_ip, server) &&
1906 !name_status_find(MSBROWSE, 1, 0x1d, server_ip, server)) {
1912 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
1915 * Get a connection to IPC$ on the server if we do not already
1919 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
1923 SAFE_FREE(dir->fname);
1930 dir->dir_type = SMBC_WORKGROUP;
1932 /* Now, list the stuff ... */
1934 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_fn,
1937 DEBUG(1, ("Could not enumerate domains using '%s'\n", workgroup));
1939 SAFE_FREE(dir->fname);
1942 errno = cli_errno(&srv->cli);
1947 } else if (server[0] == (char)0 &&
1948 (! *options || strcmp(options, "mb=.all") == 0)) {
1952 struct ip_service *ip_list;
1953 struct ip_service server_addr;
1954 struct user_auth_info u_info;
1955 struct cli_state *cli;
1957 if (share[0] != (char)0 || path[0] != (char)0) {
1961 SAFE_FREE(dir->fname);
1967 pstrcpy(u_info.username, user);
1968 pstrcpy(u_info.password, password);
1971 * We have server and share and path empty but options
1972 * requesting that we scan all master browsers for their list
1973 * of workgroups/domains. This implies that we must first try
1974 * broadcast queries to find all master browsers, and if that
1975 * doesn't work, then try our other methods which return only
1976 * a single master browser.
1979 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
1980 if (!find_master_ip(workgroup, &server_addr.ip)) {
1986 ip_list = &server_addr;
1990 for (i = 0; i < count; i++) {
1991 DEBUG(99, ("Found master browser %s\n", inet_ntoa(ip_list[i].ip)));
1993 cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
1994 fstrcpy(server, cli->desthost);
1997 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2000 * For each returned master browser IP address, get a
2001 * connection to IPC$ on the server if we do not
2002 * already have one, and determine the
2003 * workgroups/domains that it knows about.
2006 srv = smbc_server(context, server,
2007 "IPC$", workgroup, user, password);
2011 SAFE_FREE(dir->fname);
2018 dir->dir_type = SMBC_WORKGROUP;
2020 /* Now, list the stuff ... */
2022 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2026 SAFE_FREE(dir->fname);
2029 errno = cli_errno(&srv->cli);
2037 * Server not an empty string ... Check the rest and see what
2040 if (share[0] == (char)0) {
2042 if (path[0] != (char)0) { /* Should not have empty share with path */
2046 SAFE_FREE(dir->fname);
2053 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2054 /* However, we check to see if <server> is an IP address first */
2056 if (!is_ipaddress(server) && /* Not an IP addr so check next */
2057 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
2058 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2061 dir->dir_type = SMBC_SERVER;
2064 * Get the backup list ...
2068 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2070 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2071 errno = EPERM; /* FIXME, is this correct */
2077 * Get a connection to IPC$ on the server if we do not already have one
2080 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2083 DEBUG(0, ("got no contact to IPC$\n"));
2085 SAFE_FREE(dir->fname);
2094 /* Now, list the servers ... */
2096 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2100 SAFE_FREE(dir->fname);
2103 errno = cli_errno(&srv->cli);
2110 if (resolve_name(server, &rem_ip, 0x20)) {
2112 /* Now, list the shares ... */
2114 dir->dir_type = SMBC_FILE_SHARE;
2116 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2121 SAFE_FREE(dir->fname);
2130 /* Now, list the servers ... */
2132 if (cli_RNetShareEnum(&srv->cli, list_fn,
2135 errno = cli_errno(&srv->cli);
2137 SAFE_FREE(dir->fname);
2147 errno = ENODEV; /* Neither the workgroup nor server exists */
2149 SAFE_FREE(dir->fname);
2159 else { /* The server and share are specified ... work from there ... */
2161 /* Well, we connect to the server and list the directory */
2163 dir->dir_type = SMBC_FILE_SHARE;
2165 srv = smbc_server(context, server, share, workgroup, user, password);
2170 SAFE_FREE(dir->fname);
2179 /* Now, list the files ... */
2181 pstrcat(path, "\\*");
2183 if (cli_list(&srv->cli, path, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
2187 SAFE_FREE(dir->fname);
2190 errno = smbc_errno(context, &srv->cli);
2198 DLIST_ADD(context->internal->_files, dir);
2204 * Routine to close a directory
2207 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2210 if (!context || !context->internal ||
2211 !context->internal->_initialized) {
2218 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2225 smbc_remove_dir(dir); /* Clean it up */
2227 DLIST_REMOVE(context->internal->_files, dir);
2231 SAFE_FREE(dir->fname);
2232 SAFE_FREE(dir); /* Free the space too */
2240 * Routine to get a directory entry
2243 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2245 struct smbc_dirent *dirp, *dirent;
2247 /* Check that all is ok first ... */
2249 if (!context || !context->internal ||
2250 !context->internal->_initialized) {
2253 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2258 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2261 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2266 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2269 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2274 if (!dir->dir_next) {
2279 dirent = dir->dir_next->dirent;
2287 /* Hmmm, do I even need to copy it? */
2289 memcpy(context->internal->_dirent, dirent, dirent->dirlen); /* Copy the dirent */
2290 dirp = (struct smbc_dirent *)context->internal->_dirent;
2291 dirp->comment = (char *)(&dirp->name + dirent->namelen + 1);
2292 dir->dir_next = dir->dir_next->next;
2294 return (struct smbc_dirent *)context->internal->_dirent;
2300 * Routine to get directory entries
2303 static int smbc_getdents_ctx(SMBCCTX *context, SMBCFILE *dir, struct smbc_dirent *dirp, int count)
2305 struct smbc_dir_list *dirlist;
2306 int rem = count, reqd;
2307 char *ndir = (char *)dirp;
2309 /* Check that all is ok first ... */
2311 if (!context || !context->internal ||
2312 !context->internal->_initialized) {
2319 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2326 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2334 * Now, retrieve the number of entries that will fit in what was passed
2335 * We have to figure out if the info is in the list, or we need to
2336 * send a request to the server to get the info.
2339 while ((dirlist = dir->dir_next)) {
2340 struct smbc_dirent *dirent;
2342 if (!dirlist->dirent) {
2344 errno = ENOENT; /* Bad error */
2349 if (rem < (reqd = (sizeof(struct smbc_dirent) + dirlist->dirent->namelen +
2350 dirlist->dirent->commentlen + 1))) {
2352 if (rem < count) { /* We managed to copy something */
2358 else { /* Nothing copied ... */
2360 errno = EINVAL; /* Not enough space ... */
2367 dirent = dirlist->dirent;
2369 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2371 ((struct smbc_dirent *)ndir)->comment =
2372 (char *)(&((struct smbc_dirent *)ndir)->name + dirent->namelen + 1);
2378 dir->dir_next = dirlist = dirlist -> next;
2389 * Routine to create a directory ...
2392 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2395 fstring server, share, user, password, workgroup;
2398 if (!context || !context->internal ||
2399 !context->internal->_initialized) {
2413 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2415 if (smbc_parse_path(context, fname,
2416 server, sizeof(server),
2417 share, sizeof(share),
2420 password, sizeof(password),
2426 if (user[0] == (char)0) fstrcpy(user, context->user);
2428 fstrcpy(workgroup, context->workgroup);
2430 srv = smbc_server(context, server, share, workgroup, user, password);
2434 return -1; /* errno set by smbc_server */
2438 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2440 mode = aDIR | aRONLY;
2443 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2445 if (strcmp(path, "\\") == 0) {
2447 mode = aDIR | aRONLY;
2453 smbc_stat_printjob(srv, path, &size, &m_time);
2454 c_time = a_time = m_time;
2459 if (!cli_mkdir(&srv->cli, path)) {
2461 errno = smbc_errno(context, &srv->cli);
2471 * Our list function simply checks to see if a directory is not empty
2474 static int smbc_rmdir_dirempty = True;
2476 static void rmdir_list_fn(file_info *finfo, const char *mask, void *state)
2479 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2480 smbc_rmdir_dirempty = False;
2485 * Routine to remove a directory
2488 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2491 fstring server, share, user, password, workgroup;
2494 if (!context || !context->internal ||
2495 !context->internal->_initialized) {
2509 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2511 if (smbc_parse_path(context, fname,
2512 server, sizeof(server),
2513 share, sizeof(share),
2516 password, sizeof(password),
2523 if (user[0] == (char)0) fstrcpy(user, context->user);
2525 fstrcpy(workgroup, context->workgroup);
2527 srv = smbc_server(context, server, share, workgroup, user, password);
2531 return -1; /* errno set by smbc_server */
2535 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2537 mode = aDIR | aRONLY;
2540 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2542 if (strcmp(path, "\\") == 0) {
2544 mode = aDIR | aRONLY;
2550 smbc_stat_printjob(srv, path, &size, &m_time);
2551 c_time = a_time = m_time;
2556 if (!cli_rmdir(&srv->cli, path)) {
2558 errno = smbc_errno(context, &srv->cli);
2560 if (errno == EACCES) { /* Check if the dir empty or not */
2562 pstring lpath; /* Local storage to avoid buffer overflows */
2564 smbc_rmdir_dirempty = True; /* Make this so ... */
2566 pstrcpy(lpath, path);
2567 pstrcat(lpath, "\\*");
2569 if (cli_list(&srv->cli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2572 /* Fix errno to ignore latest error ... */
2574 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
2575 smbc_errno(context, &srv->cli)));
2580 if (smbc_rmdir_dirempty)
2596 * Routine to return the current directory position
2599 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
2601 off_t ret_val; /* Squash warnings about cast */
2603 if (!context || !context->internal ||
2604 !context->internal->_initialized) {
2611 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2618 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2626 * We return the pointer here as the offset
2628 ret_val = (int)dir->dir_next;
2634 * A routine to run down the list and see if the entry is OK
2637 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
2638 struct smbc_dirent *dirent)
2641 /* Run down the list looking for what we want */
2645 struct smbc_dir_list *tmp = list;
2649 if (tmp->dirent == dirent)
2658 return NULL; /* Not found, or an error */
2664 * Routine to seek on a directory
2667 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
2669 long int l_offset = offset; /* Handle problems of size */
2670 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
2671 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
2673 if (!context || !context->internal ||
2674 !context->internal->_initialized) {
2681 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2688 /* Now, check what we were passed and see if it is OK ... */
2690 if (dirent == NULL) { /* Seek to the begining of the list */
2692 dir->dir_next = dir->dir_list;
2697 /* Now, run down the list and make sure that the entry is OK */
2698 /* This may need to be changed if we change the format of the list */
2700 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
2702 errno = EINVAL; /* Bad entry */
2707 dir->dir_next = list_ent;
2714 * Routine to fstat a dir
2717 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
2720 if (!context || !context->internal ||
2721 !context->internal->_initialized) {
2728 /* No code yet ... */
2734 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
2737 fstring server, share, user, password, workgroup;
2741 if (!context || !context->internal ||
2742 !context->internal->_initialized) {
2744 errno = EINVAL; /* Best I can think of ... */
2756 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
2758 if (smbc_parse_path(context, fname,
2759 server, sizeof(server),
2760 share, sizeof(share),
2763 password, sizeof(password),
2769 if (user[0] == (char)0) fstrcpy(user, context->user);
2771 fstrcpy(workgroup, context->workgroup);
2773 srv = smbc_server(context, server, share, workgroup, user, password);
2776 return -1; /* errno set by smbc_server */
2781 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
2782 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
2783 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
2784 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
2786 if (!cli_setatr(&srv->cli, path, mode, 0)) {
2787 errno = smbc_errno(context, &srv->cli);
2794 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
2797 fstring server, share, user, password, workgroup;
2800 time_t t = (tbuf == NULL ? time(NULL) : tbuf->tv_sec);
2802 if (!context || !context->internal ||
2803 !context->internal->_initialized) {
2805 errno = EINVAL; /* Best I can think of ... */
2817 DEBUG(4, ("smbc_utimes(%s, [%s])\n", fname, ctime(&t)));
2819 if (smbc_parse_path(context, fname,
2820 server, sizeof(server),
2821 share, sizeof(share),
2824 password, sizeof(password),
2830 if (user[0] == (char)0) fstrcpy(user, context->user);
2832 fstrcpy(workgroup, context->workgroup);
2834 srv = smbc_server(context, server, share, workgroup, user, password);
2837 return -1; /* errno set by smbc_server */
2840 if (!smbc_getatr(context, srv, path,
2847 if (!cli_setatr(&srv->cli, path, mode, t)) {
2848 /* some servers always refuse directory changes */
2849 if (!(mode & aDIR)) {
2850 errno = smbc_errno(context, &srv->cli);
2859 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
2860 However NT4 gives a "The information may have been modified by a
2861 computer running Windows NT 5.0" if denied ACEs do not appear before
2864 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
2866 if (sec_ace_equal(ace1, ace2))
2869 if (ace1->type != ace2->type)
2870 return ace2->type - ace1->type;
2872 if (sid_compare(&ace1->trustee, &ace2->trustee))
2873 return sid_compare(&ace1->trustee, &ace2->trustee);
2875 if (ace1->flags != ace2->flags)
2876 return ace1->flags - ace2->flags;
2878 if (ace1->info.mask != ace2->info.mask)
2879 return ace1->info.mask - ace2->info.mask;
2881 if (ace1->size != ace2->size)
2882 return ace1->size - ace2->size;
2884 return memcmp(ace1, ace2, sizeof(SEC_ACE));
2888 static void sort_acl(SEC_ACL *the_acl)
2891 if (!the_acl) return;
2893 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
2895 for (i=1;i<the_acl->num_aces;) {
2896 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
2898 for (j=i; j<the_acl->num_aces-1; j++) {
2899 the_acl->ace[j] = the_acl->ace[j+1];
2901 the_acl->num_aces--;
2908 /* convert a SID to a string, either numeric or username/group */
2909 static void convert_sid_to_string(struct cli_state *ipc_cli,
2915 char **domains = NULL;
2916 char **names = NULL;
2917 uint32 *types = NULL;
2919 sid_to_string(str, sid);
2921 if (numeric) return; /* no lookup desired */
2923 /* Ask LSA to convert the sid to a name */
2925 if (!NT_STATUS_IS_OK(cli_lsa_lookup_sids(ipc_cli, ipc_cli->mem_ctx,
2926 pol, 1, sid, &domains,
2928 !domains || !domains[0] || !names || !names[0]) {
2934 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
2935 domains[0], lp_winbind_separator(),
2939 /* convert a string to a SID, either numeric or username/group */
2940 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
2946 uint32 *types = NULL;
2947 DOM_SID *sids = NULL;
2951 if (strncmp(str, "S-", 2) == 0) {
2952 return string_to_sid(sid, str);
2959 if (!NT_STATUS_IS_OK(cli_lsa_lookup_names(ipc_cli, ipc_cli->mem_ctx,
2960 pol, 1, &str, &sids,
2966 sid_copy(sid, &sids[0]);
2973 /* parse an ACE in the same format as print_ace() */
2974 static BOOL parse_ace(struct cli_state *ipc_cli,
2983 unsigned atype, aflags, amask;
2986 const struct perm_value *v;
2992 /* These values discovered by inspection */
2993 static const struct perm_value special_values[] = {
2994 { "R", 0x00120089 },
2995 { "W", 0x00120116 },
2996 { "X", 0x001200a0 },
2997 { "D", 0x00010000 },
2998 { "P", 0x00040000 },
2999 { "O", 0x00080000 },
3003 static const struct perm_value standard_values[] = {
3004 { "READ", 0x001200a9 },
3005 { "CHANGE", 0x001301bf },
3006 { "FULL", 0x001f01ff },
3012 p = strchr_m(str,':');
3013 if (!p) return False;
3016 /* Try to parse numeric form */
3018 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3019 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3023 /* Try to parse text form */
3025 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3030 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3034 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3035 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3036 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3037 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3042 /* Only numeric form accepted for flags at present */
3044 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3045 sscanf(tok, "%i", &aflags))) {
3049 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3053 if (strncmp(tok, "0x", 2) == 0) {
3054 if (sscanf(tok, "%i", &amask) != 1) {
3060 for (v = standard_values; v->perm; v++) {
3061 if (strcmp(tok, v->perm) == 0) {
3072 for (v = special_values; v->perm; v++) {
3073 if (v->perm[0] == *p) {
3079 if (!found) return False;
3089 init_sec_ace(ace, &sid, atype, mask, aflags);
3093 /* add an ACE to a list of ACEs in a SEC_ACL */
3094 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3099 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3103 aces = calloc(1+(*the_acl)->num_aces,sizeof(SEC_ACE));
3104 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3105 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3106 new = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3113 /* parse a ascii version of a security descriptor */
3114 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3115 struct cli_state *ipc_cli,
3120 const char *p = str;
3124 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3128 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3130 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3131 revision = strtol(tok+9, NULL, 16);
3135 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3136 owner_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3138 !convert_string_to_sid(ipc_cli, pol,
3140 owner_sid, tok+6)) {
3141 DEBUG(5, ("Failed to parse owner sid\n"));
3147 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3148 owner_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3150 !convert_string_to_sid(ipc_cli, pol,
3152 owner_sid, tok+7)) {
3153 DEBUG(5, ("Failed to parse owner sid\n"));
3159 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3160 grp_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3162 !convert_string_to_sid(ipc_cli, pol,
3165 DEBUG(5, ("Failed to parse group sid\n"));
3171 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3172 grp_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3174 !convert_string_to_sid(ipc_cli, pol,
3177 DEBUG(5, ("Failed to parse group sid\n"));
3183 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3185 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3186 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3189 if(!add_ace(&dacl, &ace, ctx)) {
3190 DEBUG(5, ("Failed to add ACL %s\n", tok));
3196 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3198 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3199 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3202 if(!add_ace(&dacl, &ace, ctx)) {
3203 DEBUG(5, ("Failed to add ACL %s\n", tok));
3209 DEBUG(5, ("Failed to parse security descriptor\n"));
3213 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
3214 owner_sid, grp_sid, NULL, dacl, &sd_size);
3217 SAFE_FREE(owner_sid);
3223 /*****************************************************
3224 retrieve the acls for a file
3225 *******************************************************/
3226 static int cacl_get(TALLOC_CTX *ctx, struct cli_state *cli,
3227 struct cli_state *ipc_cli, POLICY_HND *pol,
3228 char *filename, char *name, char *buf, int bufsize)
3234 BOOL numeric = True;
3235 BOOL determine_size = (bufsize == 0);
3241 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3244 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3245 filename, cli_errstr(cli)));
3250 sd = cli_query_secdesc(cli, fnum, ctx);
3253 DEBUG(5, ("cacl_get Failed to query old descriptor\n"));
3258 cli_close(cli, fnum);
3260 all = (*name == '*');
3261 numeric = (* (name + strlen(name) - 1) != '+');
3266 if (determine_size) {
3267 p = talloc_asprintf(ctx,
3268 "REVISION:%d", sd->revision);
3275 n = snprintf(buf, bufsize,
3276 "REVISION:%d", sd->revision);
3278 } else if (StrCaseCmp(name, "revision") == 0) {
3279 if (determine_size) {
3280 p = talloc_asprintf(ctx, "%d", sd->revision);
3287 n = snprintf(buf, bufsize, "%d", sd->revision);
3291 if (!determine_size && n > bufsize) {
3299 /* Get owner and group sid */
3301 if (sd->owner_sid) {
3302 convert_sid_to_string(ipc_cli, pol,
3303 sidstr, numeric, sd->owner_sid);
3305 fstrcpy(sidstr, "");
3309 if (determine_size) {
3310 p = talloc_asprintf(ctx, ",OWNER:%s", sidstr);
3317 n = snprintf(buf, bufsize, ",OWNER:%s", sidstr);
3319 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3320 if (determine_size) {
3321 p = talloc_asprintf(ctx, "%s", sidstr);
3328 n = snprintf(buf, bufsize, "%s", sidstr);
3332 if (!determine_size && n > bufsize) {
3341 convert_sid_to_string(ipc_cli, pol,
3342 sidstr, numeric, sd->grp_sid);
3344 fstrcpy(sidstr, "");
3348 if (determine_size) {
3349 p = talloc_asprintf(ctx, ",GROUP:%s", sidstr);
3356 n = snprintf(buf, bufsize, ",GROUP:%s", sidstr);
3358 } else if (StrnCaseCmp(name, "group", 5) == 0) {
3359 if (determine_size) {
3360 p = talloc_asprintf(ctx, "%s", sidstr);
3367 n = snprintf(buf, bufsize, "%s", sidstr);
3371 if (!determine_size && n > bufsize) {
3379 /* Add aces to value buffer */
3380 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
3382 SEC_ACE *ace = &sd->dacl->ace[i];
3383 convert_sid_to_string(ipc_cli, pol,
3384 sidstr, numeric, &ace->trustee);
3387 if (determine_size) {
3388 p = talloc_asprintf(ctx,
3389 ",ACL:%s:%d/%d/0x%08x",
3400 n = snprintf(buf, bufsize,
3401 ",ACL:%s:%d/%d/0x%08x",
3407 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
3408 StrCaseCmp(name + 3, sidstr) == 0) ||
3409 (StrnCaseCmp(name, "acl+", 4) == 0 &&
3410 StrCaseCmp(name + 4, sidstr) == 0)) {
3411 if (determine_size) {
3412 p = talloc_asprintf(ctx,
3423 n = snprintf(buf, bufsize,
3425 ace->type, ace->flags, ace->info.mask);
3445 /*****************************************************
3446 set the ACLs on a file given an ascii description
3447 *******************************************************/
3448 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
3449 struct cli_state *ipc_cli, POLICY_HND *pol,
3450 const char *filename, const char *the_acl,
3451 int mode, int flags)
3455 SEC_DESC *sd = NULL, *old;
3456 SEC_ACL *dacl = NULL;
3457 DOM_SID *owner_sid = NULL;
3458 DOM_SID *grp_sid = NULL;
3463 BOOL numeric = True;
3465 /* the_acl will be null for REMOVE_ALL operations */
3467 numeric = ((p = strchr(the_acl, ':')) != NULL &&
3471 /* if this is to set the entire ACL... */
3472 if (*the_acl == '*') {
3473 /* ... then increment past the first colon */
3477 sd = sec_desc_parse(ctx, ipc_cli, pol,
3478 numeric, (char *) the_acl);
3486 /* The desired access below is the only one I could find that works
3487 with NT4, W2KP and Samba */
3489 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3492 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3493 filename, cli_errstr(cli)));
3498 old = cli_query_secdesc(cli, fnum, ctx);
3501 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
3506 cli_close(cli, fnum);
3509 case SMBC_XATTR_MODE_REMOVE_ALL:
3510 old->dacl->num_aces = 0;
3511 SAFE_FREE(old->dacl->ace);
3512 SAFE_FREE(old->dacl);
3517 case SMBC_XATTR_MODE_REMOVE:
3518 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3521 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3522 if (sec_ace_equal(&sd->dacl->ace[i],
3523 &old->dacl->ace[j])) {
3525 for (k=j; k<old->dacl->num_aces-1;k++) {
3526 old->dacl->ace[k] = old->dacl->ace[k+1];
3528 old->dacl->num_aces--;
3529 if (old->dacl->num_aces == 0) {
3530 SAFE_FREE(old->dacl->ace);
3531 SAFE_FREE(old->dacl);
3548 case SMBC_XATTR_MODE_ADD:
3549 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3552 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3553 if (sid_equal(&sd->dacl->ace[i].trustee,
3554 &old->dacl->ace[j].trustee)) {
3555 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
3560 old->dacl->ace[j] = sd->dacl->ace[i];
3566 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
3572 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3573 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
3579 case SMBC_XATTR_MODE_SET:
3581 owner_sid = old->owner_sid;
3582 grp_sid = old->grp_sid;
3586 case SMBC_XATTR_MODE_CHOWN:
3587 owner_sid = sd->owner_sid;
3590 case SMBC_XATTR_MODE_CHGRP:
3591 grp_sid = sd->grp_sid;
3595 /* Denied ACE entries must come before allowed ones */
3596 sort_acl(old->dacl);
3598 /* Create new security descriptor and set it */
3599 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
3600 owner_sid, grp_sid, NULL, dacl, &sd_size);
3602 fnum = cli_nt_create(cli, filename,
3603 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
3606 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3607 filename, cli_errstr(cli)));
3612 if (!cli_set_secdesc(cli, fnum, sd)) {
3613 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
3620 cli_close(cli, fnum);
3630 int smbc_setxattr_ctx(SMBCCTX *context,
3640 fstring server, share, user, password, workgroup;
3645 if (!context || !context->internal ||
3646 !context->internal->_initialized) {
3648 errno = EINVAL; /* Best I can think of ... */
3660 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
3661 fname, name, (int) size, (char *) value));
3663 if (smbc_parse_path(context, fname,
3664 server, sizeof(server),
3665 share, sizeof(share),
3668 password, sizeof(password),
3674 if (user[0] == (char)0) fstrcpy(user, context->user);
3676 fstrcpy(workgroup, context->workgroup);
3678 srv = smbc_server(context, server, share, workgroup, user, password);
3680 return -1; /* errno set by smbc_server */
3683 ipc_srv = smbc_attr_server(context, server, share,
3684 workgroup, user, password,
3690 ctx = talloc_init("smbc_setxattr");
3697 * Are they asking to set an access control element or to set
3698 * the entire access control list?
3700 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3701 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3702 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3703 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3704 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3708 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3713 ret = cacl_set(ctx, &srv->cli,
3714 &ipc_srv->cli, &pol, path,
3717 ? SMBC_XATTR_MODE_SET
3718 : SMBC_XATTR_MODE_ADD),
3721 talloc_destroy(ctx);
3726 * Are they asking to set the owner?
3728 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3729 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
3733 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3738 ret = cacl_set(ctx, &srv->cli,
3739 &ipc_srv->cli, &pol, path,
3740 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3742 talloc_destroy(ctx);
3747 * Are they asking to set the group?
3749 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3750 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
3754 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3759 ret = cacl_set(ctx, &srv->cli,
3760 &ipc_srv->cli, &pol, path,
3761 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3763 talloc_destroy(ctx);
3767 /* Unsupported attribute name */
3768 talloc_destroy(ctx);
3773 int smbc_getxattr_ctx(SMBCCTX *context,
3782 fstring server, share, user, password, workgroup;
3787 if (!context || !context->internal ||
3788 !context->internal->_initialized) {
3790 errno = EINVAL; /* Best I can think of ... */
3802 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
3804 if (smbc_parse_path(context, fname,
3805 server, sizeof(server),
3806 share, sizeof(share),
3809 password, sizeof(password),
3815 if (user[0] == (char)0) fstrcpy(user, context->user);
3817 fstrcpy(workgroup, context->workgroup);
3819 srv = smbc_server(context, server, share, workgroup, user, password);
3821 return -1; /* errno set by smbc_server */
3824 ipc_srv = smbc_attr_server(context, server, share,
3825 workgroup, user, password,
3831 ctx = talloc_init("smbc:getxattr");
3837 /* Are they requesting a supported attribute? */
3838 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3839 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3840 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3841 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3842 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3843 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3844 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3845 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3846 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3849 ret = cacl_get(ctx, &srv->cli,
3850 &ipc_srv->cli, &pol,
3851 (char *) path, (char *) name + 19,
3852 (char *) value, size);
3853 if (ret < 0 && errno == 0) {
3854 errno = smbc_errno(context, &srv->cli);
3856 talloc_destroy(ctx);
3860 /* Unsupported attribute name */
3861 talloc_destroy(ctx);
3867 int smbc_removexattr_ctx(SMBCCTX *context,
3874 fstring server, share, user, password, workgroup;
3879 if (!context || !context->internal ||
3880 !context->internal->_initialized) {
3882 errno = EINVAL; /* Best I can think of ... */
3894 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
3896 if (smbc_parse_path(context, fname,
3897 server, sizeof(server),
3898 share, sizeof(share),
3901 password, sizeof(password),
3907 if (user[0] == (char)0) fstrcpy(user, context->user);
3909 fstrcpy(workgroup, context->workgroup);
3911 srv = smbc_server(context, server, share, workgroup, user, password);
3913 return -1; /* errno set by smbc_server */
3916 ipc_srv = smbc_attr_server(context, server, share,
3917 workgroup, user, password,
3923 ipc_srv = smbc_attr_server(context, server, share,
3924 workgroup, user, password,
3930 ctx = talloc_init("smbc_removexattr");
3936 /* Are they asking to set the entire ACL? */
3937 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3938 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
3941 ret = cacl_set(ctx, &srv->cli,
3942 &ipc_srv->cli, &pol, path,
3943 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
3944 talloc_destroy(ctx);
3949 * Are they asking to remove one or more spceific security descriptor
3952 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3953 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3954 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3955 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3956 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3957 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3958 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3961 ret = cacl_set(ctx, &srv->cli,
3962 &ipc_srv->cli, &pol, path,
3963 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
3964 talloc_destroy(ctx);
3968 /* Unsupported attribute name */
3969 talloc_destroy(ctx);
3974 int smbc_listxattr_ctx(SMBCCTX *context,
3980 * This isn't quite what listxattr() is supposed to do. This returns
3981 * the complete set of attributes, always, rather than only those
3982 * attribute names which actually exist for a file. Hmmm...
3984 const char supported[] =
3985 "system.nt_sec_desc.revision\0"
3986 "system.nt_sec_desc.owner\0"
3987 "system.nt_sec_desc.owner+\0"
3988 "system.nt_sec_desc.group\0"
3989 "system.nt_sec_desc.group+\0"
3990 "system.nt_sec_desc.acl\0"
3991 "system.nt_sec_desc.acl+\0"
3992 "system.nt_sec_desc.*\0"
3993 "system.nt_sec_desc.*+\0"
3997 return sizeof(supported);
4000 if (sizeof(supported) > size) {
4005 /* this can't be strcpy() because there are embedded null characters */
4006 memcpy(list, supported, sizeof(supported));
4007 return sizeof(supported);
4012 * Open a print file to be written to by other calls
4015 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
4017 fstring server, share, user, password;
4020 if (!context || !context->internal ||
4021 !context->internal->_initialized) {
4035 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
4037 if (smbc_parse_path(context, fname,
4038 server, sizeof(server),
4039 share, sizeof(share),
4042 password, sizeof(password),
4048 /* What if the path is empty, or the file exists? */
4050 return context->open(context, fname, O_WRONLY, 666);
4055 * Routine to print a file on a remote server ...
4057 * We open the file, which we assume to be on a remote server, and then
4058 * copy it to a print file on the share specified by printq.
4061 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
4063 SMBCFILE *fid1, *fid2;
4064 int bytes, saverr, tot_bytes = 0;
4067 if (!c_file || !c_file->internal->_initialized || !c_print ||
4068 !c_print->internal->_initialized) {
4075 if (!fname && !printq) {
4082 /* Try to open the file for reading ... */
4084 if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
4086 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
4087 return -1; /* smbc_open sets errno */
4091 /* Now, try to open the printer file for writing */
4093 if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
4095 saverr = errno; /* Save errno */
4096 c_file->close(c_file, fid1);
4102 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
4106 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
4109 c_file->close(c_file, fid1);
4110 c_print->close(c_print, fid2);
4119 c_file->close(c_file, fid1); /* We have to close these anyway */
4120 c_print->close(c_print, fid2);
4134 * Routine to list print jobs on a printer share ...
4137 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
4140 fstring server, share, user, password, workgroup;
4143 if (!context || !context->internal ||
4144 !context->internal->_initialized) {
4158 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
4160 if (smbc_parse_path(context, fname,
4161 server, sizeof(server),
4162 share, sizeof(share),
4165 password, sizeof(password),
4171 if (user[0] == (char)0) fstrcpy(user, context->user);
4173 fstrcpy(workgroup, context->workgroup);
4175 srv = smbc_server(context, server, share, workgroup, user, password);
4179 return -1; /* errno set by smbc_server */
4183 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
4185 errno = smbc_errno(context, &srv->cli);
4195 * Delete a print job from a remote printer share
4198 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
4201 fstring server, share, user, password, workgroup;
4205 if (!context || !context->internal ||
4206 !context->internal->_initialized) {
4220 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
4222 if (smbc_parse_path(context, fname,
4223 server, sizeof(server),
4224 share, sizeof(share),
4227 password, sizeof(password),
4233 if (user[0] == (char)0) fstrcpy(user, context->user);
4235 fstrcpy(workgroup, context->workgroup);
4237 srv = smbc_server(context, server, share, workgroup, user, password);
4241 return -1; /* errno set by smbc_server */
4245 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
4248 errno = smbc_errno(context, &srv->cli);
4249 else if (err == ERRnosuchprintjob)
4260 * Get a new empty handle to fill in with your own info
4262 SMBCCTX * smbc_new_context(void)
4266 context = malloc(sizeof(SMBCCTX));
4272 ZERO_STRUCTP(context);
4274 context->internal = malloc(sizeof(struct smbc_internal_data));
4275 if (!context->internal) {
4280 ZERO_STRUCTP(context->internal);
4283 /* ADD REASONABLE DEFAULTS */
4285 context->timeout = 20000; /* 20 seconds */
4287 context->open = smbc_open_ctx;
4288 context->creat = smbc_creat_ctx;
4289 context->read = smbc_read_ctx;
4290 context->write = smbc_write_ctx;
4291 context->close = smbc_close_ctx;
4292 context->unlink = smbc_unlink_ctx;
4293 context->rename = smbc_rename_ctx;
4294 context->lseek = smbc_lseek_ctx;
4295 context->stat = smbc_stat_ctx;
4296 context->fstat = smbc_fstat_ctx;
4297 context->opendir = smbc_opendir_ctx;
4298 context->closedir = smbc_closedir_ctx;
4299 context->readdir = smbc_readdir_ctx;
4300 context->getdents = smbc_getdents_ctx;
4301 context->mkdir = smbc_mkdir_ctx;
4302 context->rmdir = smbc_rmdir_ctx;
4303 context->telldir = smbc_telldir_ctx;
4304 context->lseekdir = smbc_lseekdir_ctx;
4305 context->fstatdir = smbc_fstatdir_ctx;
4306 context->chmod = smbc_chmod_ctx;
4307 context->utimes = smbc_utimes_ctx;
4308 context->setxattr = smbc_setxattr_ctx;
4309 context->getxattr = smbc_getxattr_ctx;
4310 context->removexattr = smbc_removexattr_ctx;
4311 context->listxattr = smbc_listxattr_ctx;
4312 context->open_print_job = smbc_open_print_job_ctx;
4313 context->print_file = smbc_print_file_ctx;
4314 context->list_print_jobs = smbc_list_print_jobs_ctx;
4315 context->unlink_print_job = smbc_unlink_print_job_ctx;
4317 context->callbacks.check_server_fn = smbc_check_server;
4318 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
4320 smbc_default_cache_functions(context);
4328 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
4329 * and thus you'll be leaking memory if not handled properly.
4332 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
4341 DEBUG(1,("Performing aggressive shutdown.\n"));
4343 f = context->internal->_files;
4345 context->close(context, f);
4348 context->internal->_files = NULL;
4350 /* First try to remove the servers the nice way. */
4351 if (context->callbacks.purge_cached_fn(context)) {
4354 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
4355 s = context->internal->_servers;
4357 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
4358 cli_shutdown(&s->cli);
4359 context->callbacks.remove_cached_srv_fn(context, s);
4361 DLIST_REMOVE(context->internal->_servers, s);
4365 context->internal->_servers = NULL;
4369 /* This is the polite way */
4370 if (context->callbacks.purge_cached_fn(context)) {
4371 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
4375 if (context->internal->_servers) {
4376 DEBUG(1, ("Active servers in context, free_context failed.\n"));
4380 if (context->internal->_files) {
4381 DEBUG(1, ("Active files in context, free_context failed.\n"));
4387 /* Things we have to clean up */
4388 SAFE_FREE(context->workgroup);
4389 SAFE_FREE(context->netbios_name);
4390 SAFE_FREE(context->user);
4392 DEBUG(3, ("Context %p succesfully freed\n", context));
4393 SAFE_FREE(context->internal);
4400 * Initialise the library etc
4402 * We accept a struct containing handle information.
4403 * valid values for info->debug from 0 to 100,
4404 * and insist that info->fn must be non-null.
4406 SMBCCTX * smbc_init_context(SMBCCTX * context)
4410 char *user = NULL, *home = NULL;
4412 if (!context || !context->internal) {
4417 /* Do not initialise the same client twice */
4418 if (context->internal->_initialized) {
4422 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
4429 if (!smbc_initialized) {
4430 /* Do some library wide intialisations the first time we get called */
4432 /* Set this to what the user wants */
4433 DEBUGLEVEL = context->debug;
4435 setup_logging( "libsmbclient", True);
4437 /* Here we would open the smb.conf file if needed ... */
4439 home = getenv("HOME");
4441 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
4443 load_interfaces(); /* Load the list of interfaces ... */
4445 in_client = True; /* FIXME, make a param */
4447 if (!lp_load(conf, True, False, False)) {
4450 * Well, if that failed, try the dyn_CONFIGFILE
4451 * Which points to the standard locn, and if that
4452 * fails, silently ignore it and use the internal
4456 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
4457 DEBUG(5, ("Could not load either config file: %s or %s\n",
4458 conf, dyn_CONFIGFILE));
4462 reopen_logs(); /* Get logging working ... */
4465 * Block SIGPIPE (from lib/util_sock.c: write())
4466 * It is not needed and should not stop execution
4468 BlockSignals(True, SIGPIPE);
4470 /* Done with one-time initialisation */
4471 smbc_initialized = 1;
4475 if (!context->user) {
4477 * FIXME: Is this the best way to get the user info?
4479 user = getenv("USER");
4480 /* walk around as "guest" if no username can be found */
4481 if (!user) context->user = strdup("guest");
4482 else context->user = strdup(user);
4485 if (!context->netbios_name) {
4487 * We try to get our netbios name from the config. If that fails we fall
4488 * back on constructing our netbios name from our hostname etc
4490 if (global_myname()) {
4491 context->netbios_name = strdup(global_myname());
4495 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
4498 context->netbios_name = malloc(17);
4499 if (!context->netbios_name) {
4503 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
4507 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
4509 if (!context->workgroup) {
4510 if (lp_workgroup()) {
4511 context->workgroup = strdup(lp_workgroup());
4514 /* TODO: Think about a decent default workgroup */
4515 context->workgroup = strdup("samba");
4519 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
4521 /* shortest timeout is 1 second */
4522 if (context->timeout > 0 && context->timeout < 1000)
4523 context->timeout = 1000;
4526 * FIXME: Should we check the function pointers here?
4529 context->internal->_initialized = 1;