Apply the changes to libsmbclient that derrell has contributed. Fix some
[Samba/gebeck_regimport.git] / source3 / libsmb / libsmbclient.c
bloba11a965fdeca3c77d87fd39f9da03097b6b39eaa
1 /*
2 Unix SMB/Netbios implementation.
3 SMB client library implementation
4 Copyright (C) Andrew Tridgell 1998
5 Copyright (C) Richard Sharpe 2000, 2002
6 Copyright (C) John Terpstra 2000
7 Copyright (C) Tom Jansen (Ninja ISD) 2002
8 Copyright (C) Derrell Lipman 2003
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 #include "includes.h"
27 #include "../include/libsmb_internal.h"
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
46 * Functions exported by libsmb_cache.c that we need here
48 int smbc_default_cache_functions(SMBCCTX *context);
50 /*
51 * check if an element is part of the list.
52 * FIXME: Does not belong here !
53 * Can anyone put this in a macro in dlinklist.h ?
54 * -- Tom
56 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
57 if (!p || !list) return False;
58 do {
59 if (p == list) return True;
60 list = list->next;
61 } while (list);
62 return False;
65 extern BOOL in_client;
68 * Is the logging working / configfile read ?
70 static int smbc_initialized = 0;
72 static int
73 hex2int( unsigned int _char )
75 if ( _char >= 'A' && _char <='F')
76 return _char - 'A' + 10;
77 if ( _char >= 'a' && _char <='f')
78 return _char - 'a' + 10;
79 if ( _char >= '0' && _char <='9')
80 return _char - '0';
81 return -1;
84 static void
85 decode_urlpart(char *segment, size_t sizeof_segment)
87 int old_length = strlen(segment);
88 int new_length = 0;
89 int new_length2 = 0;
90 int i = 0;
91 pstring new_segment;
92 char *new_usegment = 0;
94 if ( !old_length ) {
95 return;
98 /* make a copy of the old one */
99 new_usegment = (char*)malloc( old_length * 3 + 1 );
101 while( i < old_length ) {
102 int bReencode = False;
103 unsigned char character = segment[ i++ ];
104 if ((character <= ' ') || (character > 127))
105 bReencode = True;
107 new_usegment [ new_length2++ ] = character;
108 if (character == '%' ) {
109 int a = i+1 < old_length ? hex2int( segment[i] ) : -1;
110 int b = i+1 < old_length ? hex2int( segment[i+1] ) : -1;
111 if ((a == -1) || (b == -1)) { /* Only replace if sequence is valid */
112 /* Contains stray %, make sure to re-encode! */
113 bReencode = True;
114 } else {
115 /* Valid %xx sequence */
116 character = a * 16 + b; /* Replace with value of %dd */
117 if (!character)
118 break; /* Stop at %00 */
120 new_usegment [ new_length2++ ] = (unsigned char) segment[i++];
121 new_usegment [ new_length2++ ] = (unsigned char) segment[i++];
124 if (bReencode) {
125 unsigned int c = character / 16;
126 new_length2--;
127 new_usegment [ new_length2++ ] = '%';
129 c += (c > 9) ? ('A' - 10) : '0';
130 new_usegment[ new_length2++ ] = c;
132 c = character % 16;
133 c += (c > 9) ? ('A' - 10) : '0';
134 new_usegment[ new_length2++ ] = c;
137 new_segment [ new_length++ ] = character;
139 new_segment [ new_length ] = 0;
141 free(new_usegment);
143 /* realloc it with unix charset */
144 pull_utf8_allocate((void**)&new_usegment, new_segment);
146 /* this assumes (very safely) that removing %aa sequences
147 only shortens the string */
148 strncpy(segment, new_usegment, sizeof_segment);
150 free(new_usegment);
154 * Function to parse a path and turn it into components
156 * We accept smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]]
158 * smb:// means show all the workgroups
159 * smb://name/ means, if name<1D> or name<1B> exists, list servers in workgroup,
160 * else, if name<20> exists, list all shares for server ...
163 static const char *smbc_prefix = "smb:";
165 static int
166 smbc_parse_path(SMBCCTX *context, const char *fname, char *server, char *share, char *path,
167 char *user, char *password) /* FIXME, lengths of strings */
169 static pstring s;
170 pstring userinfo;
171 const char *p;
172 char *q, *r;
173 int len;
175 server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
176 pstrcpy(s, fname);
178 /* clean_fname(s); causing problems ... */
180 /* see if it has the right prefix */
181 len = strlen(smbc_prefix);
182 if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
183 return -1; /* What about no smb: ? */
186 p = s + len;
188 /* Watch the test below, we are testing to see if we should exit */
190 if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
192 return -1;
196 p += 2; /* Skip the // or \\ */
198 if (*p == (char)0)
199 goto decoding;
201 if (*p == '/') {
203 strncpy(server, context->workgroup,
204 (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
205 return 0;
210 * ok, its for us. Now parse out the server, share etc.
212 * However, we want to parse out [[domain;]user[:password]@] if it
213 * exists ...
216 /* check that '@' occurs before '/', if '/' exists at all */
217 q = strchr_m(p, '@');
218 r = strchr_m(p, '/');
219 if (q && (!r || q < r)) {
220 pstring username, passwd, domain;
221 const char *u = userinfo;
223 next_token(&p, userinfo, "@", sizeof(fstring));
225 username[0] = passwd[0] = domain[0] = 0;
227 if (strchr_m(u, ';')) {
229 next_token(&u, domain, ";", sizeof(fstring));
233 if (strchr_m(u, ':')) {
235 next_token(&u, username, ":", sizeof(fstring));
237 pstrcpy(passwd, u);
240 else {
242 pstrcpy(username, u);
246 if (username[0])
247 strncpy(user, username, sizeof(fstring)); /* FIXME, size and domain */
249 if (passwd[0])
250 strncpy(password, passwd, sizeof(fstring)); /* FIXME, size */
254 if (!next_token(&p, server, "/", sizeof(fstring))) {
256 return -1;
260 if (*p == (char)0) goto decoding; /* That's it ... */
262 if (!next_token(&p, share, "/", sizeof(fstring))) {
264 return -1;
268 pstrcpy(path, p);
270 all_string_sub(path, "/", "\\", 0);
272 decoding:
273 decode_urlpart(path, sizeof(pstring));
274 decode_urlpart(server, sizeof(fstring));
275 decode_urlpart(share, sizeof(fstring));
276 decode_urlpart(user, sizeof(fstring));
277 decode_urlpart(password, sizeof(fstring));
279 return 0;
283 * Convert an SMB error into a UNIX error ...
286 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
288 int ret = cli_errno(c);
290 if (cli_is_dos_error(c)) {
291 uint8 eclass;
292 uint32 ecode;
294 cli_dos_error(c, &eclass, &ecode);
296 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n",
297 (int)eclass, (int)ecode, (int)ecode, ret));
298 } else {
299 NTSTATUS status;
301 status = cli_nt_error(c);
303 DEBUG(3,("smbc errno %s -> %d\n",
304 nt_errstr(status), ret));
307 return ret;
311 * Check a server_fd.
312 * returns 0 if the server is in shape. Returns 1 on error
314 * Also useable outside libsmbclient to enable external cache
315 * to do some checks too.
317 int smbc_check_server(SMBCCTX * context, SMBCSRV * server)
319 if ( send_keepalive(server->cli.fd) == False )
320 return 1;
322 /* connection is ok */
323 return 0;
327 * Remove a server from the cached server list it's unused.
328 * On success, 0 is returned. 1 is returned if the server could not be removed.
330 * Also useable outside libsmbclient
332 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
334 SMBCFILE * file;
336 /* are we being fooled ? */
337 if (!context || !context->internal ||
338 !context->internal->_initialized || !srv) return 1;
341 /* Check all open files/directories for a relation with this server */
342 for (file = context->internal->_files; file; file=file->next) {
343 if (file->srv == srv) {
344 /* Still used */
345 DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n",
346 srv, file));
347 return 1;
351 DLIST_REMOVE(context->internal->_servers, srv);
353 cli_shutdown(&srv->cli);
355 DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
357 context->callbacks.remove_cached_srv_fn(context, srv);
359 SAFE_FREE(srv);
361 return 0;
364 SMBCSRV *find_server(SMBCCTX *context,
365 const char *server,
366 const char *share,
367 fstring workgroup,
368 fstring username,
369 fstring password)
371 SMBCSRV *srv;
372 int auth_called = 0;
374 check_server_cache:
376 srv = context->callbacks.get_cached_srv_fn(context, server, share,
377 workgroup, username);
379 if (!auth_called && !srv && (!username[0] || !password[0])) {
380 context->callbacks.auth_fn(server, share,
381 workgroup, sizeof(fstring),
382 username, sizeof(fstring),
383 password, sizeof(fstring));
385 * However, smbc_auth_fn may have picked up info relating to
386 * an existing connection, so try for an existing connection
387 * again ...
389 auth_called = 1;
390 goto check_server_cache;
394 if (srv) {
395 if (context->callbacks.check_server_fn(context, srv)) {
397 * This server is no good anymore
398 * Try to remove it and check for more possible
399 * servers in the cache
401 if (context->callbacks.remove_unused_server_fn(context,
402 srv)) {
404 * We could not remove the server completely,
405 * remove it from the cache so we will not get
406 * it again. It will be removed when the last
407 * file/dir is closed.
409 context->callbacks.remove_cached_srv_fn(context,
410 srv);
414 * Maybe there are more cached connections to this
415 * server
417 goto check_server_cache;
419 return srv;
422 return NULL;
426 * Connect to a server, possibly on an existing connection
428 * Here, what we want to do is: If the server and username
429 * match an existing connection, reuse that, otherwise, establish a
430 * new connection.
432 * If we have to create a new connection, call the auth_fn to get the
433 * info we need, unless the username and password were passed in.
436 SMBCSRV *smbc_server(SMBCCTX *context,
437 const char *server, const char *share,
438 fstring workgroup, fstring username,
439 fstring password)
441 SMBCSRV *srv=NULL;
442 struct cli_state c;
443 struct nmb_name called, calling;
444 char *p;
445 const char *server_n = server;
446 fstring group;
447 pstring ipenv;
448 struct in_addr ip;
449 int tried_reverse = 0;
451 zero_ip(&ip);
452 ZERO_STRUCT(c);
454 if (server[0] == 0) {
455 errno = EPERM;
456 return NULL;
459 srv = find_server(context, server, share,
460 workgroup, username, password);
461 if (srv)
462 return srv;
464 make_nmb_name(&calling, context->netbios_name, 0x0);
465 make_nmb_name(&called , server, 0x20);
467 DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
469 if ((p=strchr_m(server_n,'#')) &&
470 (strcmp(p+1,"1D")==0 || strcmp(p+1,"01")==0)) {
472 fstrcpy(group, server_n);
473 p = strchr_m(group,'#');
474 *p = 0;
478 DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
480 again:
481 slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
483 zero_ip(&ip);
485 /* have to open a new connection */
486 if (!cli_initialise(&c)) {
487 errno = ENOMEM;
488 return NULL;
491 c.timeout = context->timeout;
493 /* Force use of port 139 for first try, so browse lists can work */
494 c.port = 139;
496 if (!cli_connect(&c, server_n, &ip)) {
498 * Port 139 connection failed. Try port 445 to handle
499 * connections to newer (e.g. XP) hosts with NetBIOS disabled.
501 c.port = 445;
502 if (!cli_connect(&c, server_n, &ip)) {
503 cli_shutdown(&c);
504 errno = ENETUNREACH;
505 return NULL;
509 if (!cli_session_request(&c, &calling, &called)) {
510 cli_shutdown(&c);
511 if (strcmp(called.name, "*SMBSERVER")) {
512 make_nmb_name(&called , "*SMBSERVER", 0x20);
513 goto again;
515 else { /* Try one more time, but ensure we don't loop */
517 /* Only try this if server is an IP address ... */
519 if (is_ipaddress(server) && !tried_reverse) {
520 fstring remote_name;
521 struct in_addr rem_ip;
523 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
524 DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
525 errno = ENOENT;
526 return NULL;
529 tried_reverse++; /* Yuck */
531 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
532 make_nmb_name(&called, remote_name, 0x20);
533 goto again;
539 errno = ENOENT;
540 return NULL;
543 DEBUG(4,(" session request ok\n"));
545 if (!cli_negprot(&c)) {
546 cli_shutdown(&c);
547 errno = ENOENT;
548 return NULL;
551 if (!cli_session_setup(&c, username,
552 password, strlen(password),
553 password, strlen(password),
554 workgroup) &&
555 /* try an anonymous login if it failed */
556 !cli_session_setup(&c, "", "", 1,"", 0, workgroup)) {
557 cli_shutdown(&c);
558 errno = EPERM;
559 return NULL;
562 DEBUG(4,(" session setup ok\n"));
564 if (!cli_send_tconX(&c, share, "?????",
565 password, strlen(password)+1)) {
566 errno = smbc_errno(context, &c);
567 cli_shutdown(&c);
568 return NULL;
571 DEBUG(4,(" tconx ok\n"));
574 * Ok, we have got a nice connection
575 * Let's find a free server_fd
578 srv = (SMBCSRV *)malloc(sizeof(*srv));
579 if (!srv) {
580 errno = ENOMEM;
581 goto failed;
584 ZERO_STRUCTP(srv);
585 srv->cli = c;
586 srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
588 /* now add it to the cache (internal or external) */
589 if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
590 DEBUG(3, (" Failed to add server to cache\n"));
591 goto failed;
595 DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
596 server, share, srv));
598 return srv;
600 failed:
601 cli_shutdown(&c);
602 if (!srv) return NULL;
604 SAFE_FREE(srv);
605 return NULL;
609 * Connect to a server for getting/setting attributes, possibly on an existing
610 * connection. This works similarly to smbc_server().
612 SMBCSRV *smbc_attr_server(SMBCCTX *context,
613 const char *server, const char *share,
614 fstring workgroup,
615 fstring username, fstring password)
617 struct in_addr ip;
618 struct cli_state *ipc_cli;
619 NTSTATUS nt_status;
620 SMBCSRV *ipc_srv=NULL;
621 POLICY_HND pol;
624 * See if we've already created this special connection. Reference
625 * our "special" share name 'IPC$$'.
627 ipc_srv = find_server(context, server, "IPC$$",
628 workgroup, username, password);
629 if (!ipc_srv) {
631 /* We didn't find a cached connection. Get the password */
632 if (*password == '\0') {
633 /* ... then retrieve it now. */
634 context->callbacks.auth_fn(server, share,
635 workgroup, sizeof(fstring),
636 username, sizeof(fstring),
637 password, sizeof(fstring));
640 zero_ip(&ip);
641 nt_status = cli_full_connection(&ipc_cli,
642 global_myname(), server,
643 &ip, 0, "IPC$", "?????",
644 username, workgroup,
645 password, 0,
646 Undefined, NULL);
647 if (! NT_STATUS_IS_OK(nt_status)) {
648 DEBUG(0,("cli_full_connection failed! (%s)\n",
649 nt_errstr(nt_status)));
650 errno = ENOTSUP;
651 return NULL;
654 if (!cli_nt_session_open(ipc_cli, PI_LSARPC)) {
655 DEBUG(0, ("cli_nt_session_open fail! (%s)\n",
656 nt_errstr(nt_status)));
657 errno = ENOTSUP;
658 free(ipc_cli);
659 return NULL;
662 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
663 but NT sends 0x2000000 so we might as well do it too. */
665 nt_status = cli_lsa_open_policy(ipc_cli,
666 ipc_cli->mem_ctx,
667 True,
668 GENERIC_EXECUTE_ACCESS,
669 &pol);
671 if (!NT_STATUS_IS_OK(nt_status)) {
672 errno = smbc_errno(context, ipc_cli);
673 free(ipc_cli);
674 return NULL;
677 ipc_srv = (SMBCSRV *)malloc(sizeof(*ipc_srv));
678 if (!ipc_srv) {
679 errno = ENOMEM;
680 free(ipc_cli);
681 return NULL;
684 ZERO_STRUCTP(ipc_srv);
685 ipc_srv->cli = *ipc_cli;
687 free(ipc_cli);
689 /* now add it to the cache (internal or external) */
690 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
691 server,
692 "IPC$$",
693 workgroup,
694 username)) {
695 DEBUG(3, (" Failed to add server to cache\n"));
696 return NULL;
700 return ipc_srv;
704 * Routine to open() a file ...
707 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
709 fstring server, share, user, password, workgroup;
710 pstring path;
711 SMBCSRV *srv = NULL;
712 SMBCFILE *file = NULL;
713 int fd;
715 if (!context || !context->internal ||
716 !context->internal->_initialized) {
718 errno = EINVAL; /* Best I can think of ... */
719 return NULL;
723 if (!fname) {
725 errno = EINVAL;
726 return NULL;
730 smbc_parse_path(context, fname, server, share, path, user, password); /* FIXME, check errors */
732 if (user[0] == (char)0) fstrcpy(user, context->user);
734 fstrcpy(workgroup, context->workgroup);
736 srv = smbc_server(context, server, share, workgroup, user, password);
738 if (!srv) {
740 if (errno == EPERM) errno = EACCES;
741 return NULL; /* smbc_server sets errno */
745 /* Hmmm, the test for a directory is suspect here ... FIXME */
747 if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
749 fd = -1;
752 else {
754 file = malloc(sizeof(SMBCFILE));
756 if (!file) {
758 errno = ENOMEM;
759 return NULL;
763 ZERO_STRUCTP(file);
765 if ((fd = cli_open(&srv->cli, path, flags, DENY_NONE)) < 0) {
767 /* Handle the error ... */
769 SAFE_FREE(file);
770 errno = smbc_errno(context, &srv->cli);
771 return NULL;
775 /* Fill in file struct */
777 file->cli_fd = fd;
778 file->fname = strdup(fname);
779 file->srv = srv;
780 file->offset = 0;
781 file->file = True;
783 DLIST_ADD(context->internal->_files, file);
784 return file;
788 /* Check if opendir needed ... */
790 if (fd == -1) {
791 int eno = 0;
793 eno = smbc_errno(context, &srv->cli);
794 file = context->opendir(context, fname);
795 if (!file) errno = eno;
796 return file;
800 errno = EINVAL; /* FIXME, correct errno ? */
801 return NULL;
806 * Routine to create a file
809 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
811 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
814 if (!context || !context->internal ||
815 !context->internal->_initialized) {
817 errno = EINVAL;
818 return NULL;
822 return smbc_open_ctx(context, path, creat_bits, mode);
826 * Routine to read() a file ...
829 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
831 int ret;
833 if (!context || !context->internal ||
834 !context->internal->_initialized) {
836 errno = EINVAL;
837 return -1;
841 DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
843 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
845 errno = EBADF;
846 return -1;
850 /* Check that the buffer exists ... */
852 if (buf == NULL) {
854 errno = EINVAL;
855 return -1;
859 ret = cli_read(&file->srv->cli, file->cli_fd, buf, file->offset, count);
861 if (ret < 0) {
863 errno = smbc_errno(context, &file->srv->cli);
864 return -1;
868 file->offset += ret;
870 DEBUG(4, (" --> %d\n", ret));
872 return ret; /* Success, ret bytes of data ... */
877 * Routine to write() a file ...
880 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
882 int ret;
884 if (!context || !context->internal ||
885 !context->internal->_initialized) {
887 errno = EINVAL;
888 return -1;
892 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
894 errno = EBADF;
895 return -1;
899 /* Check that the buffer exists ... */
901 if (buf == NULL) {
903 errno = EINVAL;
904 return -1;
908 ret = cli_write(&file->srv->cli, file->cli_fd, 0, buf, file->offset, count);
910 if (ret <= 0) {
912 errno = smbc_errno(context, &file->srv->cli);
913 return -1;
917 file->offset += ret;
919 return ret; /* Success, 0 bytes of data ... */
923 * Routine to close() a file ...
926 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
928 SMBCSRV *srv;
930 if (!context || !context->internal ||
931 !context->internal->_initialized) {
933 errno = EINVAL;
934 return -1;
938 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
940 errno = EBADF;
941 return -1;
945 /* IS a dir ... */
946 if (!file->file) {
948 return context->closedir(context, file);
952 if (!cli_close(&file->srv->cli, file->cli_fd)) {
954 DEBUG(3, ("cli_close failed on %s. purging server.\n",
955 file->fname));
956 /* Deallocate slot and remove the server
957 * from the server cache if unused */
958 errno = smbc_errno(context, &file->srv->cli);
959 srv = file->srv;
960 DLIST_REMOVE(context->internal->_files, file);
961 SAFE_FREE(file->fname);
962 SAFE_FREE(file);
963 context->callbacks.remove_unused_server_fn(context, srv);
965 return -1;
969 DLIST_REMOVE(context->internal->_files, file);
970 SAFE_FREE(file->fname);
971 SAFE_FREE(file);
973 return 0;
977 * Get info from an SMB server on a file. Use a qpathinfo call first
978 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
980 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path,
981 uint16 *mode, size_t *size,
982 time_t *c_time, time_t *a_time, time_t *m_time,
983 SMB_INO_T *ino)
986 if (!context || !context->internal ||
987 !context->internal->_initialized) {
989 errno = EINVAL;
990 return -1;
994 DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
996 if (!srv->no_pathinfo2 &&
997 cli_qpathinfo2(&srv->cli, path, c_time, a_time, m_time, NULL,
998 size, mode, ino)) return True;
1000 /* if this is NT then don't bother with the getatr */
1001 if (srv->cli.capabilities & CAP_NT_SMBS) {
1002 errno = EPERM;
1003 return False;
1006 if (cli_getatr(&srv->cli, path, mode, size, m_time)) {
1007 a_time = c_time = m_time;
1008 srv->no_pathinfo2 = True;
1009 return True;
1012 errno = EPERM;
1013 return False;
1018 * Routine to unlink() a file
1021 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1023 fstring server, share, user, password, workgroup;
1024 pstring path;
1025 SMBCSRV *srv = NULL;
1027 if (!context || !context->internal ||
1028 !context->internal->_initialized) {
1030 errno = EINVAL; /* Best I can think of ... */
1031 return -1;
1035 if (!fname) {
1037 errno = EINVAL;
1038 return -1;
1042 smbc_parse_path(context, fname, server, share, path, user, password); /* FIXME, check errors */
1044 if (user[0] == (char)0) fstrcpy(user, context->user);
1046 fstrcpy(workgroup, context->workgroup);
1048 srv = smbc_server(context, server, share, workgroup, user, password);
1050 if (!srv) {
1052 return -1; /* smbc_server sets errno */
1056 /* if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
1058 int job = smbc_stat_printjob(srv, path, NULL, NULL);
1059 if (job == -1) {
1061 return -1;
1064 if ((err = cli_printjob_del(&srv->cli, job)) != 0) {
1067 return -1;
1070 } else */
1072 if (!cli_unlink(&srv->cli, path)) {
1074 errno = smbc_errno(context, &srv->cli);
1076 if (errno == EACCES) { /* Check if the file is a directory */
1078 int saverr = errno;
1079 size_t size = 0;
1080 uint16 mode = 0;
1081 time_t m_time = 0, a_time = 0, c_time = 0;
1082 SMB_INO_T ino = 0;
1084 if (!smbc_getatr(context, srv, path, &mode, &size,
1085 &c_time, &a_time, &m_time, &ino)) {
1087 /* Hmmm, bad error ... What? */
1089 errno = smbc_errno(context, &srv->cli);
1090 return -1;
1093 else {
1095 if (IS_DOS_DIR(mode))
1096 errno = EISDIR;
1097 else
1098 errno = saverr; /* Restore this */
1103 return -1;
1107 return 0; /* Success ... */
1112 * Routine to rename() a file
1115 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname,
1116 SMBCCTX *ncontext, const char *nname)
1118 fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1119 pstring path1, path2;
1120 SMBCSRV *srv = NULL;
1122 if (!ocontext || !ncontext ||
1123 !ocontext->internal || !ncontext->internal ||
1124 !ocontext->internal->_initialized ||
1125 !ncontext->internal->_initialized) {
1127 errno = EINVAL; /* Best I can think of ... */
1128 return -1;
1132 if (!oname || !nname) {
1134 errno = EINVAL;
1135 return -1;
1139 DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1141 smbc_parse_path(ocontext, oname, server1, share1, path1, user1, password1);
1143 if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1145 smbc_parse_path(ncontext, nname, server2, share2, path2, user2, password2);
1147 if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1149 if (strcmp(server1, server2) || strcmp(share1, share2) ||
1150 strcmp(user1, user2)) {
1152 /* Can't rename across file systems, or users?? */
1154 errno = EXDEV;
1155 return -1;
1159 fstrcpy(workgroup, ocontext->workgroup);
1160 /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */
1161 srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1162 if (!srv) {
1164 return -1;
1168 if (!cli_rename(&srv->cli, path1, path2)) {
1169 int eno = smbc_errno(ocontext, &srv->cli);
1171 if (eno != EEXIST ||
1172 !cli_unlink(&srv->cli, path2) ||
1173 !cli_rename(&srv->cli, path1, path2)) {
1175 errno = eno;
1176 return -1;
1181 return 0; /* Success */
1186 * A routine to lseek() a file
1189 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1191 size_t size;
1193 if (!context || !context->internal ||
1194 !context->internal->_initialized) {
1196 errno = EINVAL;
1197 return -1;
1201 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1203 errno = EBADF;
1204 return -1;
1208 if (!file->file) {
1210 errno = EINVAL;
1211 return -1; /* Can't lseek a dir ... */
1215 switch (whence) {
1216 case SEEK_SET:
1217 file->offset = offset;
1218 break;
1220 case SEEK_CUR:
1221 file->offset += offset;
1222 break;
1224 case SEEK_END:
1225 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
1226 NULL, NULL, NULL))
1228 SMB_BIG_UINT b_size = size;
1229 if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
1230 NULL))
1232 errno = EINVAL;
1233 return -1;
1234 } else
1235 size = b_size;
1237 file->offset = size + offset;
1238 break;
1240 default:
1241 errno = EINVAL;
1242 break;
1246 return file->offset;
1251 * Generate an inode number from file name for those things that need it
1254 static
1255 ino_t smbc_inode(SMBCCTX *context, const char *name)
1258 if (!context || !context->internal ||
1259 !context->internal->_initialized) {
1261 errno = EINVAL;
1262 return -1;
1266 if (!*name) return 2; /* FIXME, why 2 ??? */
1267 return (ino_t)str_checksum(name);
1272 * Routine to put basic stat info into a stat structure ... Used by stat and
1273 * fstat below.
1276 static
1277 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname, size_t size, int mode)
1280 st->st_mode = 0;
1282 if (IS_DOS_DIR(mode)) {
1283 st->st_mode = SMBC_DIR_MODE;
1284 } else {
1285 st->st_mode = SMBC_FILE_MODE;
1288 if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1289 if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1290 if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1291 if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1293 st->st_size = size;
1294 #ifdef HAVE_STAT_ST_BLKSIZE
1295 st->st_blksize = 512;
1296 #endif
1297 #ifdef HAVE_STAT_ST_BLOCKS
1298 st->st_blocks = (size+511)/512;
1299 #endif
1300 st->st_uid = getuid();
1301 st->st_gid = getgid();
1303 if (IS_DOS_DIR(mode)) {
1304 st->st_nlink = 2;
1305 } else {
1306 st->st_nlink = 1;
1309 if (st->st_ino == 0) {
1310 st->st_ino = smbc_inode(context, fname);
1313 return True; /* FIXME: Is this needed ? */
1318 * Routine to stat a file given a name
1321 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1323 SMBCSRV *srv;
1324 fstring server, share, user, password, workgroup;
1325 pstring path;
1326 time_t m_time = 0, a_time = 0, c_time = 0;
1327 size_t size = 0;
1328 uint16 mode = 0;
1329 SMB_INO_T ino = 0;
1331 if (!context || !context->internal ||
1332 !context->internal->_initialized) {
1334 errno = EINVAL; /* Best I can think of ... */
1335 return -1;
1339 if (!fname) {
1341 errno = EINVAL;
1342 return -1;
1346 DEBUG(4, ("smbc_stat(%s)\n", fname));
1348 smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
1350 if (user[0] == (char)0) fstrcpy(user, context->user);
1352 fstrcpy(workgroup, context->workgroup);
1354 srv = smbc_server(context, server, share, workgroup, user, password);
1356 if (!srv) {
1357 return -1; /* errno set by smbc_server */
1360 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
1362 mode = aDIR | aRONLY;
1365 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
1367 if (strcmp(path, "\\") == 0) {
1369 mode = aDIR | aRONLY;
1372 else {
1374 mode = aRONLY;
1375 smbc_stat_printjob(srv, path, &size, &m_time);
1376 c_time = a_time = m_time;
1379 else { */
1381 if (!smbc_getatr(context, srv, path, &mode, &size,
1382 &c_time, &a_time, &m_time, &ino)) {
1384 errno = smbc_errno(context, &srv->cli);
1385 return -1;
1389 st->st_ino = ino;
1391 smbc_setup_stat(context, st, path, size, mode);
1393 st->st_atime = a_time;
1394 st->st_ctime = c_time;
1395 st->st_mtime = m_time;
1396 st->st_dev = srv->dev;
1398 return 0;
1403 * Routine to stat a file given an fd
1406 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1408 time_t c_time, a_time, m_time;
1409 size_t size;
1410 uint16 mode;
1411 SMB_INO_T ino = 0;
1413 if (!context || !context->internal ||
1414 !context->internal->_initialized) {
1416 errno = EINVAL;
1417 return -1;
1421 if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1423 errno = EBADF;
1424 return -1;
1428 if (!file->file) {
1430 return context->fstatdir(context, file, st);
1434 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
1435 &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
1436 SMB_BIG_UINT b_size = size;
1437 if (!cli_getattrE(&file->srv->cli, file->cli_fd,
1438 &mode, &b_size, &c_time, &a_time, &m_time)) {
1440 errno = EINVAL;
1441 return -1;
1442 } else
1443 size = b_size;
1447 st->st_ino = ino;
1449 smbc_setup_stat(context, st, file->fname, size, mode);
1451 st->st_atime = a_time;
1452 st->st_ctime = c_time;
1453 st->st_mtime = m_time;
1454 st->st_dev = file->srv->dev;
1456 return 0;
1461 * Routine to open a directory
1463 * We want to allow:
1465 * smb: which should list all the workgroups available
1466 * smb:workgroup
1467 * smb:workgroup//server
1468 * smb://server
1469 * smb://server/share
1470 * smb://<IP-addr> which should list shares on server
1471 * smb://<IP-addr>/share which should list files on share
1474 static void smbc_remove_dir(SMBCFILE *dir)
1476 struct smbc_dir_list *d,*f;
1478 d = dir->dir_list;
1479 while (d) {
1481 f = d; d = d->next;
1483 SAFE_FREE(f->dirent);
1484 SAFE_FREE(f);
1488 dir->dir_list = dir->dir_end = dir->dir_next = NULL;
1492 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
1494 struct smbc_dirent *dirent;
1495 int size;
1496 char *u_name = NULL, *u_comment = NULL;
1497 size_t u_name_len = 0, u_comment_len = 0;
1499 if (name)
1500 u_name_len = push_utf8_allocate(&u_name, name);
1501 if (comment)
1502 u_comment_len = push_utf8_allocate(&u_comment, comment);
1505 * Allocate space for the dirent, which must be increased by the
1506 * size of the name and the comment and 1 for the null on the comment.
1507 * The null on the name is already accounted for.
1510 size = sizeof(struct smbc_dirent) + u_name_len + u_comment_len + 1;
1512 dirent = malloc(size);
1514 if (!dirent) {
1516 dir->dir_error = ENOMEM;
1517 return -1;
1521 ZERO_STRUCTP(dirent);
1523 if (dir->dir_list == NULL) {
1525 dir->dir_list = malloc(sizeof(struct smbc_dir_list));
1526 if (!dir->dir_list) {
1528 SAFE_FREE(dirent);
1529 dir->dir_error = ENOMEM;
1530 return -1;
1533 ZERO_STRUCTP(dir->dir_list);
1535 dir->dir_end = dir->dir_next = dir->dir_list;
1538 else {
1540 dir->dir_end->next = malloc(sizeof(struct smbc_dir_list));
1542 if (!dir->dir_end->next) {
1544 SAFE_FREE(dirent);
1545 dir->dir_error = ENOMEM;
1546 return -1;
1549 ZERO_STRUCTP(dir->dir_end->next);
1551 dir->dir_end = dir->dir_end->next;
1555 dir->dir_end->next = NULL;
1556 dir->dir_end->dirent = dirent;
1558 dirent->smbc_type = type;
1559 dirent->namelen = u_name_len;
1560 dirent->commentlen = u_comment_len;
1561 dirent->dirlen = size;
1563 strncpy(dirent->name, (u_name?u_name:""), dirent->namelen + 1);
1565 dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
1566 strncpy(dirent->comment, (u_comment?u_comment:""), dirent->commentlen + 1);
1568 SAFE_FREE(u_comment);
1569 SAFE_FREE(u_name);
1571 return 0;
1575 static void
1576 list_fn(const char *name, uint32 type, const char *comment, void *state)
1578 SMBCFILE *dir = (SMBCFILE *)state;
1579 int dirent_type;
1581 /* We need to process the type a little ... */
1583 if (dir->dir_type == SMBC_FILE_SHARE) {
1585 switch (type) {
1586 case 0: /* Directory tree */
1587 dirent_type = SMBC_FILE_SHARE;
1588 break;
1590 case 1:
1591 dirent_type = SMBC_PRINTER_SHARE;
1592 break;
1594 case 2:
1595 dirent_type = SMBC_COMMS_SHARE;
1596 break;
1598 case 3:
1599 dirent_type = SMBC_IPC_SHARE;
1600 break;
1602 default:
1603 dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
1604 break;
1607 else dirent_type = dir->dir_type;
1609 if (add_dirent(dir, name, comment, dirent_type) < 0) {
1611 /* An error occurred, what do we do? */
1612 /* FIXME: Add some code here */
1618 static void
1619 dir_list_fn(file_info *finfo, const char *mask, void *state)
1622 if (add_dirent((SMBCFILE *)state, finfo->name, "",
1623 (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
1625 /* Handle an error ... */
1627 /* FIXME: Add some code ... */
1633 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
1635 fstring server, share, user, password;
1636 pstring workgroup;
1637 pstring path;
1638 SMBCSRV *srv = NULL;
1639 SMBCFILE *dir = NULL;
1640 struct in_addr rem_ip;
1642 if (!context || !context->internal ||
1643 !context->internal->_initialized) {
1644 DEBUG(4, ("no valid context\n"));
1645 errno = EINVAL;
1646 return NULL;
1650 if (!fname) {
1651 DEBUG(4, ("no valid fname\n"));
1652 errno = EINVAL;
1653 return NULL;
1656 if (smbc_parse_path(context, fname, server, share, path, user, password)) {
1657 DEBUG(4, ("no valid path\n"));
1658 errno = EINVAL;
1659 return NULL;
1662 DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s'\n", fname, server, share, path));
1664 if (user[0] == (char)0) fstrcpy(user, context->user);
1666 pstrcpy(workgroup, context->workgroup);
1668 dir = malloc(sizeof(*dir));
1670 if (!dir) {
1672 errno = ENOMEM;
1673 return NULL;
1677 ZERO_STRUCTP(dir);
1679 dir->cli_fd = 0;
1680 dir->fname = strdup(fname);
1681 dir->srv = NULL;
1682 dir->offset = 0;
1683 dir->file = False;
1684 dir->dir_list = dir->dir_next = dir->dir_end = NULL;
1686 if (server[0] == (char)0) {
1687 struct in_addr server_ip;
1688 if (share[0] != (char)0 || path[0] != (char)0) {
1690 errno = EINVAL;
1691 if (dir) {
1692 SAFE_FREE(dir->fname);
1693 SAFE_FREE(dir);
1695 return NULL;
1698 /* We have server and share and path empty ... so list the workgroups */
1699 /* first try to get the LMB for our workgroup, and if that fails, */
1700 /* try the DMB */
1702 pstrcpy(workgroup, lp_workgroup());
1704 if (!find_master_ip(workgroup, &server_ip)) {
1705 struct user_auth_info u_info;
1706 struct cli_state *cli;
1708 DEBUG(4, ("Unable to find master browser for workgroup %s\n",
1709 workgroup));
1711 /* find the name of the server ... */
1712 pstrcpy(u_info.username, user);
1713 pstrcpy(u_info.password, password);
1715 if (!(cli = get_ipc_connect_master_ip_bcast(workgroup, &u_info))) {
1716 DEBUG(4, ("Unable to find master browser by "
1717 "broadcast\n"));
1718 errno = ENOENT;
1719 return NULL;
1722 fstrcpy(server, cli->desthost);
1724 cli_shutdown(cli);
1725 } else {
1726 if (!name_status_find("*", 0, 0, server_ip, server)) {
1727 errno = ENOENT;
1728 return NULL;
1732 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
1735 * Get a connection to IPC$ on the server if we do not already have one
1738 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
1739 if (!srv) {
1741 if (dir) {
1742 SAFE_FREE(dir->fname);
1743 SAFE_FREE(dir);
1745 return NULL;
1748 dir->srv = srv;
1749 dir->dir_type = SMBC_WORKGROUP;
1751 /* Now, list the stuff ... */
1753 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_fn,
1754 (void *)dir)) {
1756 if (dir) {
1757 SAFE_FREE(dir->fname);
1758 SAFE_FREE(dir);
1760 errno = cli_errno(&srv->cli);
1762 return NULL;
1766 else { /* Server not an empty string ... Check the rest and see what gives */
1768 if (share[0] == (char)0) {
1770 if (path[0] != (char)0) { /* Should not have empty share with path */
1772 errno = EINVAL;
1773 if (dir) {
1774 SAFE_FREE(dir->fname);
1775 SAFE_FREE(dir);
1777 return NULL;
1781 /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
1782 /* However, we check to see if <server> is an IP address first */
1784 if (!is_ipaddress(server) && /* Not an IP addr so check next */
1785 (resolve_name(server, &rem_ip, 0x1d) || /* Found LMB */
1786 resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
1787 pstring buserver;
1789 dir->dir_type = SMBC_SERVER;
1792 * Get the backup list ...
1796 if (!name_status_find("*", 0, 0, rem_ip, buserver)) {
1798 DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
1799 errno = EPERM; /* FIXME, is this correct */
1800 return NULL;
1805 * Get a connection to IPC$ on the server if we do not already have one
1808 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
1810 if (!srv) {
1811 DEBUG(0, ("got no contact to IPC$\n"));
1812 if (dir) {
1813 SAFE_FREE(dir->fname);
1814 SAFE_FREE(dir);
1816 return NULL;
1820 dir->srv = srv;
1822 /* Now, list the servers ... */
1824 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
1825 (void *)dir)) {
1827 if (dir) {
1828 SAFE_FREE(dir->fname);
1829 SAFE_FREE(dir);
1831 errno = cli_errno(&srv->cli);
1832 return NULL;
1837 else {
1839 if (resolve_name(server, &rem_ip, 0x20)) {
1841 /* Now, list the shares ... */
1843 dir->dir_type = SMBC_FILE_SHARE;
1845 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
1847 if (!srv) {
1849 if (dir) {
1850 SAFE_FREE(dir->fname);
1851 SAFE_FREE(dir);
1853 return NULL;
1857 dir->srv = srv;
1859 /* Now, list the servers ... */
1861 if (cli_RNetShareEnum(&srv->cli, list_fn,
1862 (void *)dir) < 0) {
1864 errno = cli_errno(&srv->cli);
1865 if (dir) {
1866 SAFE_FREE(dir->fname);
1867 SAFE_FREE(dir);
1869 return NULL;
1874 else {
1876 errno = ENODEV; /* Neither the workgroup nor server exists */
1877 if (dir) {
1878 SAFE_FREE(dir->fname);
1879 SAFE_FREE(dir);
1881 return NULL;
1888 else { /* The server and share are specified ... work from there ... */
1890 /* Well, we connect to the server and list the directory */
1892 dir->dir_type = SMBC_FILE_SHARE;
1894 srv = smbc_server(context, server, share, workgroup, user, password);
1896 if (!srv) {
1898 if (dir) {
1899 SAFE_FREE(dir->fname);
1900 SAFE_FREE(dir);
1902 return NULL;
1906 dir->srv = srv;
1908 /* Now, list the files ... */
1910 pstrcat(path, "\\*");
1912 if (cli_list(&srv->cli, path, aDIR | aSYSTEM | aHIDDEN, dir_list_fn,
1913 (void *)dir) < 0) {
1915 if (dir) {
1916 SAFE_FREE(dir->fname);
1917 SAFE_FREE(dir);
1919 errno = smbc_errno(context, &srv->cli);
1920 return NULL;
1927 DLIST_ADD(context->internal->_files, dir);
1928 return dir;
1933 * Routine to close a directory
1936 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
1939 if (!context || !context->internal ||
1940 !context->internal->_initialized) {
1942 errno = EINVAL;
1943 return -1;
1947 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
1949 errno = EBADF;
1950 return -1;
1954 smbc_remove_dir(dir); /* Clean it up */
1956 DLIST_REMOVE(context->internal->_files, dir);
1958 if (dir) {
1960 SAFE_FREE(dir->fname);
1961 SAFE_FREE(dir); /* Free the space too */
1965 return 0;
1970 * Routine to get a directory entry
1973 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
1975 struct smbc_dirent *dirp, *dirent;
1977 /* Check that all is ok first ... */
1979 if (!context || !context->internal ||
1980 !context->internal->_initialized) {
1982 errno = EINVAL;
1983 return NULL;
1987 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
1989 errno = EBADF;
1990 return NULL;
1994 if (dir->file != False) { /* FIXME, should be dir, perhaps */
1996 errno = ENOTDIR;
1997 return NULL;
2001 if (!dir->dir_next)
2002 return NULL;
2003 else {
2005 dirent = dir->dir_next->dirent;
2007 if (!dirent) {
2009 errno = ENOENT;
2010 return NULL;
2014 /* Hmmm, do I even need to copy it? */
2016 memcpy(context->internal->_dirent, dirent, dirent->dirlen); /* Copy the dirent */
2017 dirp = (struct smbc_dirent *)context->internal->_dirent;
2018 dirp->comment = (char *)(&dirp->name + dirent->namelen + 1);
2019 dir->dir_next = dir->dir_next->next;
2021 return (struct smbc_dirent *)context->internal->_dirent;
2027 * Routine to get directory entries
2030 static int smbc_getdents_ctx(SMBCCTX *context, SMBCFILE *dir, struct smbc_dirent *dirp, int count)
2032 struct smbc_dir_list *dirlist;
2033 int rem = count, reqd;
2034 char *ndir = (char *)dirp;
2036 /* Check that all is ok first ... */
2038 if (!context || !context->internal ||
2039 !context->internal->_initialized) {
2041 errno = EINVAL;
2042 return -1;
2046 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2048 errno = EBADF;
2049 return -1;
2053 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2055 errno = ENOTDIR;
2056 return -1;
2061 * Now, retrieve the number of entries that will fit in what was passed
2062 * We have to figure out if the info is in the list, or we need to
2063 * send a request to the server to get the info.
2066 while ((dirlist = dir->dir_next)) {
2067 struct smbc_dirent *dirent;
2069 if (!dirlist->dirent) {
2071 errno = ENOENT; /* Bad error */
2072 return -1;
2076 if (rem < (reqd = (sizeof(struct smbc_dirent) + dirlist->dirent->namelen +
2077 dirlist->dirent->commentlen + 1))) {
2079 if (rem < count) { /* We managed to copy something */
2081 errno = 0;
2082 return count - rem;
2085 else { /* Nothing copied ... */
2087 errno = EINVAL; /* Not enough space ... */
2088 return -1;
2094 dirent = dirlist->dirent;
2096 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2098 ((struct smbc_dirent *)ndir)->comment =
2099 (char *)(&((struct smbc_dirent *)ndir)->name + dirent->namelen + 1);
2101 ndir += reqd;
2103 rem -= reqd;
2105 dir->dir_next = dirlist = dirlist -> next;
2108 if (rem == count)
2109 return 0;
2110 else
2111 return count - rem;
2116 * Routine to create a directory ...
2119 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2121 SMBCSRV *srv;
2122 fstring server, share, user, password, workgroup;
2123 pstring path;
2125 if (!context || !context->internal ||
2126 !context->internal->_initialized) {
2128 errno = EINVAL;
2129 return -1;
2133 if (!fname) {
2135 errno = EINVAL;
2136 return -1;
2140 DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2142 smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
2144 if (user[0] == (char)0) fstrcpy(user, context->user);
2146 fstrcpy(workgroup, context->workgroup);
2148 srv = smbc_server(context, server, share, workgroup, user, password);
2150 if (!srv) {
2152 return -1; /* errno set by smbc_server */
2156 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2158 mode = aDIR | aRONLY;
2161 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2163 if (strcmp(path, "\\") == 0) {
2165 mode = aDIR | aRONLY;
2168 else {
2170 mode = aRONLY;
2171 smbc_stat_printjob(srv, path, &size, &m_time);
2172 c_time = a_time = m_time;
2175 else { */
2177 if (!cli_mkdir(&srv->cli, path)) {
2179 errno = smbc_errno(context, &srv->cli);
2180 return -1;
2184 return 0;
2189 * Our list function simply checks to see if a directory is not empty
2192 static int smbc_rmdir_dirempty = True;
2194 static void rmdir_list_fn(file_info *finfo, const char *mask, void *state)
2197 if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2198 smbc_rmdir_dirempty = False;
2203 * Routine to remove a directory
2206 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2208 SMBCSRV *srv;
2209 fstring server, share, user, password, workgroup;
2210 pstring path;
2212 if (!context || !context->internal ||
2213 !context->internal->_initialized) {
2215 errno = EINVAL;
2216 return -1;
2220 if (!fname) {
2222 errno = EINVAL;
2223 return -1;
2227 DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2229 smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
2231 if (user[0] == (char)0) fstrcpy(user, context->user);
2233 fstrcpy(workgroup, context->workgroup);
2235 srv = smbc_server(context, server, share, workgroup, user, password);
2237 if (!srv) {
2239 return -1; /* errno set by smbc_server */
2243 /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2245 mode = aDIR | aRONLY;
2248 else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2250 if (strcmp(path, "\\") == 0) {
2252 mode = aDIR | aRONLY;
2255 else {
2257 mode = aRONLY;
2258 smbc_stat_printjob(srv, path, &size, &m_time);
2259 c_time = a_time = m_time;
2262 else { */
2264 if (!cli_rmdir(&srv->cli, path)) {
2266 errno = smbc_errno(context, &srv->cli);
2268 if (errno == EACCES) { /* Check if the dir empty or not */
2270 pstring lpath; /* Local storage to avoid buffer overflows */
2272 smbc_rmdir_dirempty = True; /* Make this so ... */
2274 pstrcpy(lpath, path);
2275 pstrcat(lpath, "\\*");
2277 if (cli_list(&srv->cli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2278 NULL) < 0) {
2280 /* Fix errno to ignore latest error ... */
2282 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n",
2283 smbc_errno(context, &srv->cli)));
2284 errno = EACCES;
2288 if (smbc_rmdir_dirempty)
2289 errno = EACCES;
2290 else
2291 errno = ENOTEMPTY;
2295 return -1;
2299 return 0;
2304 * Routine to return the current directory position
2307 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
2309 off_t ret_val; /* Squash warnings about cast */
2311 if (!context || !context->internal ||
2312 !context->internal->_initialized) {
2314 errno = EINVAL;
2315 return -1;
2319 if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2321 errno = EBADF;
2322 return -1;
2326 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2328 errno = ENOTDIR;
2329 return -1;
2334 * We return the pointer here as the offset
2336 ret_val = (int)dir->dir_next;
2337 return ret_val;
2342 * A routine to run down the list and see if the entry is OK
2345 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list,
2346 struct smbc_dirent *dirent)
2349 /* Run down the list looking for what we want */
2351 if (dirent) {
2353 struct smbc_dir_list *tmp = list;
2355 while (tmp) {
2357 if (tmp->dirent == dirent)
2358 return tmp;
2360 tmp = tmp->next;
2366 return NULL; /* Not found, or an error */
2372 * Routine to seek on a directory
2375 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
2377 long int l_offset = offset; /* Handle problems of size */
2378 struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
2379 struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
2381 if (!context || !context->internal ||
2382 !context->internal->_initialized) {
2384 errno = EINVAL;
2385 return -1;
2389 if (dir->file != False) { /* FIXME, should be dir, perhaps */
2391 errno = ENOTDIR;
2392 return -1;
2396 /* Now, check what we were passed and see if it is OK ... */
2398 if (dirent == NULL) { /* Seek to the begining of the list */
2400 dir->dir_next = dir->dir_list;
2401 return 0;
2405 /* Now, run down the list and make sure that the entry is OK */
2406 /* This may need to be changed if we change the format of the list */
2408 if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
2410 errno = EINVAL; /* Bad entry */
2411 return -1;
2415 dir->dir_next = list_ent;
2417 return 0;
2422 * Routine to fstat a dir
2425 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
2428 if (!context || !context->internal ||
2429 !context->internal->_initialized) {
2431 errno = EINVAL;
2432 return -1;
2436 /* No code yet ... */
2438 return 0;
2442 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
2444 SMBCSRV *srv;
2445 fstring server, share, user, password, workgroup;
2446 pstring path;
2447 uint16 mode;
2449 if (!context || !context->internal ||
2450 !context->internal->_initialized) {
2452 errno = EINVAL; /* Best I can think of ... */
2453 return -1;
2457 if (!fname) {
2459 errno = EINVAL;
2460 return -1;
2464 DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
2466 smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
2468 if (user[0] == (char)0) fstrcpy(user, context->user);
2470 fstrcpy(workgroup, context->workgroup);
2472 srv = smbc_server(context, server, share, workgroup, user, password);
2474 if (!srv) {
2475 return -1; /* errno set by smbc_server */
2478 mode = 0;
2480 if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
2481 if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
2482 if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
2483 if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
2485 if (!cli_setatr(&srv->cli, path, mode, 0)) {
2486 errno = smbc_errno(context, &srv->cli);
2487 return -1;
2490 return 0;
2493 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
2495 SMBCSRV *srv;
2496 fstring server, share, user, password, workgroup;
2497 pstring path;
2498 uint16 mode;
2499 time_t t = (tbuf == NULL ? time(NULL) : tbuf->tv_sec);
2501 if (!context || !context->internal ||
2502 !context->internal->_initialized) {
2504 errno = EINVAL; /* Best I can think of ... */
2505 return -1;
2509 if (!fname) {
2511 errno = EINVAL;
2512 return -1;
2516 DEBUG(4, ("smbc_utimes(%s, [%s])\n", fname, ctime(&t)));
2518 smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
2520 if (user[0] == (char)0) fstrcpy(user, context->user);
2522 fstrcpy(workgroup, context->workgroup);
2524 srv = smbc_server(context, server, share, workgroup, user, password);
2526 if (!srv) {
2527 return -1; /* errno set by smbc_server */
2530 if (!smbc_getatr(context, srv, path,
2531 &mode, NULL,
2532 NULL, NULL, NULL,
2533 NULL)) {
2534 return -1;
2537 if (!cli_setatr(&srv->cli, path, mode, t)) {
2538 /* some servers always refuse directory changes */
2539 if (!(mode & aDIR)) {
2540 errno = smbc_errno(context, &srv->cli);
2541 return -1;
2545 return 0;
2549 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
2550 However NT4 gives a "The information may have been modified by a
2551 computer running Windows NT 5.0" if denied ACEs do not appear before
2552 allowed ACEs. */
2554 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
2556 if (sec_ace_equal(ace1, ace2))
2557 return 0;
2559 if (ace1->type != ace2->type)
2560 return ace2->type - ace1->type;
2562 if (sid_compare(&ace1->trustee, &ace2->trustee))
2563 return sid_compare(&ace1->trustee, &ace2->trustee);
2565 if (ace1->flags != ace2->flags)
2566 return ace1->flags - ace2->flags;
2568 if (ace1->info.mask != ace2->info.mask)
2569 return ace1->info.mask - ace2->info.mask;
2571 if (ace1->size != ace2->size)
2572 return ace1->size - ace2->size;
2574 return memcmp(ace1, ace2, sizeof(SEC_ACE));
2578 static void sort_acl(SEC_ACL *the_acl)
2580 uint32 i;
2581 if (!the_acl) return;
2583 qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
2585 for (i=1;i<the_acl->num_aces;) {
2586 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
2587 int j;
2588 for (j=i; j<the_acl->num_aces-1; j++) {
2589 the_acl->ace[j] = the_acl->ace[j+1];
2591 the_acl->num_aces--;
2592 } else {
2593 i++;
2598 /* convert a SID to a string, either numeric or username/group */
2599 static void convert_sid_to_string(struct cli_state *ipc_cli,
2600 POLICY_HND *pol,
2601 fstring str,
2602 BOOL numeric,
2603 DOM_SID *sid)
2605 char **domains = NULL;
2606 char **names = NULL;
2607 uint32 *types = NULL;
2609 sid_to_string(str, sid);
2611 if (numeric) return; /* no lookup desired */
2613 /* Ask LSA to convert the sid to a name */
2615 if (!NT_STATUS_IS_OK(cli_lsa_lookup_sids(ipc_cli, ipc_cli->mem_ctx,
2616 pol, 1, sid, &domains,
2617 &names, &types)) ||
2618 !domains || !domains[0] || !names || !names[0]) {
2619 return;
2622 /* Converted OK */
2624 slprintf(str, sizeof(fstring) - 1, "%s%s%s",
2625 domains[0], lp_winbind_separator(),
2626 names[0]);
2629 /* convert a string to a SID, either numeric or username/group */
2630 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
2631 POLICY_HND *pol,
2632 BOOL numeric,
2633 DOM_SID *sid,
2634 const char *str)
2636 uint32 *types = NULL;
2637 DOM_SID *sids = NULL;
2638 BOOL result = True;
2640 if (numeric) {
2641 if (strncmp(str, "S-", 2) == 0) {
2642 return string_to_sid(sid, str);
2645 result = False;
2646 goto done;
2649 if (!NT_STATUS_IS_OK(cli_lsa_lookup_names(ipc_cli, ipc_cli->mem_ctx,
2650 pol, 1, &str, &sids,
2651 &types))) {
2652 result = False;
2653 goto done;
2656 sid_copy(sid, &sids[0]);
2657 done:
2659 return result;
2663 /* parse an ACE in the same format as print_ace() */
2664 static BOOL parse_ace(struct cli_state *ipc_cli,
2665 POLICY_HND *pol,
2666 SEC_ACE *ace,
2667 BOOL numeric,
2668 char *str)
2670 char *p;
2671 const char *cp;
2672 fstring tok;
2673 unsigned atype, aflags, amask;
2674 DOM_SID sid;
2675 SEC_ACCESS mask;
2676 const struct perm_value *v;
2677 struct perm_value {
2678 const char *perm;
2679 uint32 mask;
2682 /* These values discovered by inspection */
2683 static const struct perm_value special_values[] = {
2684 { "R", 0x00120089 },
2685 { "W", 0x00120116 },
2686 { "X", 0x001200a0 },
2687 { "D", 0x00010000 },
2688 { "P", 0x00040000 },
2689 { "O", 0x00080000 },
2690 { NULL, 0 },
2693 static const struct perm_value standard_values[] = {
2694 { "READ", 0x001200a9 },
2695 { "CHANGE", 0x001301bf },
2696 { "FULL", 0x001f01ff },
2697 { NULL, 0 },
2701 ZERO_STRUCTP(ace);
2702 p = strchr_m(str,':');
2703 if (!p) return False;
2704 *p = '\0';
2705 p++;
2706 /* Try to parse numeric form */
2708 if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
2709 convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
2710 goto done;
2713 /* Try to parse text form */
2715 if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
2716 return False;
2719 cp = p;
2720 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
2721 return False;
2724 if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
2725 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
2726 } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
2727 atype = SEC_ACE_TYPE_ACCESS_DENIED;
2728 } else {
2729 return False;
2732 /* Only numeric form accepted for flags at present */
2734 if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
2735 sscanf(tok, "%i", &aflags))) {
2736 return False;
2739 if (!next_token(&cp, tok, "/", sizeof(fstring))) {
2740 return False;
2743 if (strncmp(tok, "0x", 2) == 0) {
2744 if (sscanf(tok, "%i", &amask) != 1) {
2745 return False;
2747 goto done;
2750 for (v = standard_values; v->perm; v++) {
2751 if (strcmp(tok, v->perm) == 0) {
2752 amask = v->mask;
2753 goto done;
2757 p = tok;
2759 while(*p) {
2760 BOOL found = False;
2762 for (v = special_values; v->perm; v++) {
2763 if (v->perm[0] == *p) {
2764 amask |= v->mask;
2765 found = True;
2769 if (!found) return False;
2770 p++;
2773 if (*p) {
2774 return False;
2777 done:
2778 mask.mask = amask;
2779 init_sec_ace(ace, &sid, atype, mask, aflags);
2780 return True;
2783 /* add an ACE to a list of ACEs in a SEC_ACL */
2784 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
2786 SEC_ACL *new;
2787 SEC_ACE *aces;
2788 if (! *the_acl) {
2789 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
2790 return True;
2793 aces = calloc(1+(*the_acl)->num_aces,sizeof(SEC_ACE));
2794 memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
2795 memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
2796 new = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
2797 SAFE_FREE(aces);
2798 (*the_acl) = new;
2799 return True;
2803 /* parse a ascii version of a security descriptor */
2804 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
2805 struct cli_state *ipc_cli,
2806 POLICY_HND *pol,
2807 BOOL numeric,
2808 char *str)
2810 const char *p = str;
2811 fstring tok;
2812 SEC_DESC *ret;
2813 size_t sd_size;
2814 DOM_SID *grp_sid=NULL, *owner_sid=NULL;
2815 SEC_ACL *dacl=NULL;
2816 int revision=1;
2818 while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
2820 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
2821 revision = strtol(tok+9, NULL, 16);
2822 continue;
2825 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
2826 owner_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
2827 if (!owner_sid ||
2828 !convert_string_to_sid(ipc_cli, pol,
2829 numeric,
2830 owner_sid, tok+6)) {
2831 DEBUG(5, ("Failed to parse owner sid\n"));
2832 return NULL;
2834 continue;
2837 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
2838 owner_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
2839 if (!owner_sid ||
2840 !convert_string_to_sid(ipc_cli, pol,
2841 False,
2842 owner_sid, tok+7)) {
2843 DEBUG(5, ("Failed to parse owner sid\n"));
2844 return NULL;
2846 continue;
2849 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
2850 grp_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
2851 if (!grp_sid ||
2852 !convert_string_to_sid(ipc_cli, pol,
2853 numeric,
2854 grp_sid, tok+6)) {
2855 DEBUG(5, ("Failed to parse group sid\n"));
2856 return NULL;
2858 continue;
2861 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
2862 grp_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
2863 if (!grp_sid ||
2864 !convert_string_to_sid(ipc_cli, pol,
2865 False,
2866 grp_sid, tok+6)) {
2867 DEBUG(5, ("Failed to parse group sid\n"));
2868 return NULL;
2870 continue;
2873 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
2874 SEC_ACE ace;
2875 if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
2876 DEBUG(5, ("Failed to parse ACL %s\n", tok));
2877 return NULL;
2879 if(!add_ace(&dacl, &ace, ctx)) {
2880 DEBUG(5, ("Failed to add ACL %s\n", tok));
2881 return NULL;
2883 continue;
2886 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
2887 SEC_ACE ace;
2888 if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
2889 DEBUG(5, ("Failed to parse ACL %s\n", tok));
2890 return NULL;
2892 if(!add_ace(&dacl, &ace, ctx)) {
2893 DEBUG(5, ("Failed to add ACL %s\n", tok));
2894 return NULL;
2896 continue;
2899 DEBUG(5, ("Failed to parse security descriptor\n"));
2900 return NULL;
2903 ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE,
2904 owner_sid, grp_sid, NULL, dacl, &sd_size);
2906 SAFE_FREE(grp_sid);
2907 SAFE_FREE(owner_sid);
2909 return ret;
2913 /*****************************************************
2914 retrieve the acls for a file
2915 *******************************************************/
2916 static int cacl_get(TALLOC_CTX *ctx, struct cli_state *cli,
2917 struct cli_state *ipc_cli, POLICY_HND *pol,
2918 char *filename, char *name, char *buf, int bufsize)
2920 uint32 i;
2921 int n = 0;
2922 int n_used;
2923 BOOL all;
2924 BOOL numeric = True;
2925 BOOL determine_size = (bufsize == 0);
2926 int fnum = -1;
2927 SEC_DESC *sd;
2928 fstring sidstr;
2929 char *p;
2931 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
2933 if (fnum == -1) {
2934 DEBUG(5, ("cacl_get failed to open %s: %s\n",
2935 filename, cli_errstr(cli)));
2936 errno = 0;
2937 return -1;
2940 sd = cli_query_secdesc(cli, fnum, ctx);
2942 if (!sd) {
2943 DEBUG(5, ("cacl_get Failed to query old descriptor\n"));
2944 errno = 0;
2945 return -1;
2948 cli_close(cli, fnum);
2950 all = (*name == '*');
2951 numeric = (* (name + strlen(name) - 1) != '+');
2953 n_used = 0;
2955 if (all) {
2956 if (determine_size) {
2957 p = talloc_asprintf(ctx,
2958 "REVISION:%d", sd->revision);
2959 if (!p) {
2960 errno = ENOMEM;
2961 return -1;
2963 n = strlen(p);
2964 } else {
2965 n = snprintf(buf, bufsize,
2966 "REVISION:%d", sd->revision);
2968 } else if (StrCaseCmp(name, "revision") == 0) {
2969 if (determine_size) {
2970 p = talloc_asprintf(ctx, "%d", sd->revision);
2971 if (!p) {
2972 errno = ENOMEM;
2973 return -1;
2975 n = strlen(p);
2976 } else {
2977 n = snprintf(buf, bufsize, "%d", sd->revision);
2981 if (!determine_size && n > bufsize) {
2982 errno = ERANGE;
2983 return -1;
2985 buf += n;
2986 n_used += n;
2987 bufsize -= n;
2989 /* Get owner and group sid */
2991 if (sd->owner_sid) {
2992 convert_sid_to_string(ipc_cli, pol,
2993 sidstr, numeric, sd->owner_sid);
2994 } else {
2995 fstrcpy(sidstr, "");
2998 if (all) {
2999 if (determine_size) {
3000 p = talloc_asprintf(ctx, ",OWNER:%s", sidstr);
3001 if (!p) {
3002 errno = ENOMEM;
3003 return -1;
3005 n = strlen(p);
3006 } else {
3007 n = snprintf(buf, bufsize, ",OWNER:%s", sidstr);
3009 } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3010 if (determine_size) {
3011 p = talloc_asprintf(ctx, "%s", sidstr);
3012 if (!p) {
3013 errno = ENOMEM;
3014 return -1;
3016 n = strlen(p);
3017 } else {
3018 n = snprintf(buf, bufsize, "%s", sidstr);
3022 if (!determine_size && n > bufsize) {
3023 errno = ERANGE;
3024 return -1;
3026 buf += n;
3027 n_used += n;
3028 bufsize -= n;
3030 if (sd->grp_sid) {
3031 convert_sid_to_string(ipc_cli, pol,
3032 sidstr, numeric, sd->grp_sid);
3033 } else {
3034 fstrcpy(sidstr, "");
3037 if (all) {
3038 if (determine_size) {
3039 p = talloc_asprintf(ctx, ",GROUP:%s", sidstr);
3040 if (!p) {
3041 errno = ENOMEM;
3042 return -1;
3044 n = strlen(p);
3045 } else {
3046 n = snprintf(buf, bufsize, ",GROUP:%s", sidstr);
3048 } else if (StrnCaseCmp(name, "group", 5) == 0) {
3049 if (determine_size) {
3050 p = talloc_asprintf(ctx, "%s", sidstr);
3051 if (!p) {
3052 errno = ENOMEM;
3053 return -1;
3055 n = strlen(p);
3056 } else {
3057 n = snprintf(buf, bufsize, "%s", sidstr);
3061 if (!determine_size && n > bufsize) {
3062 errno = ERANGE;
3063 return -1;
3065 buf += n;
3066 n_used += n;
3067 bufsize -= n;
3069 /* Add aces to value buffer */
3070 for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
3072 SEC_ACE *ace = &sd->dacl->ace[i];
3073 convert_sid_to_string(ipc_cli, pol,
3074 sidstr, numeric, &ace->trustee);
3076 if (all) {
3077 if (determine_size) {
3078 p = talloc_asprintf(ctx,
3079 ",ACL:%s:%d/%d/0x%08x",
3080 sidstr,
3081 ace->type,
3082 ace->flags,
3083 ace->info.mask);
3084 if (!p) {
3085 errno = ENOMEM;
3086 return -1;
3088 n = strlen(p);
3089 } else {
3090 n = snprintf(buf, bufsize,
3091 ",ACL:%s:%d/%d/0x%08x",
3092 sidstr,
3093 ace->type,
3094 ace->flags,
3095 ace->info.mask);
3097 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
3098 StrCaseCmp(name + 3, sidstr) == 0) ||
3099 (StrnCaseCmp(name, "acl+", 4) == 0 &&
3100 StrCaseCmp(name + 4, sidstr) == 0)) {
3101 if (determine_size) {
3102 p = talloc_asprintf(ctx,
3103 "%d/%d/0x%08x",
3104 ace->type,
3105 ace->flags,
3106 ace->info.mask);
3107 if (!p) {
3108 errno = ENOMEM;
3109 return -1;
3111 n = strlen(p);
3112 } else {
3113 n = snprintf(buf, bufsize,
3114 "%d/%d/0x%08x",
3115 ace->type, ace->flags, ace->info.mask);
3118 if (n > bufsize) {
3119 errno = ERANGE;
3120 return -1;
3122 buf += n;
3123 n_used += n;
3124 bufsize -= n;
3127 if (n_used == 0) {
3128 errno = ENOATTR;
3129 return -1;
3131 return n_used;
3135 /*****************************************************
3136 set the ACLs on a file given an ascii description
3137 *******************************************************/
3138 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
3139 struct cli_state *ipc_cli, POLICY_HND *pol,
3140 const char *filename, const char *the_acl,
3141 int mode, int flags)
3143 int fnum;
3144 int err = 0;
3145 SEC_DESC *sd = NULL, *old;
3146 SEC_ACL *dacl = NULL;
3147 DOM_SID *owner_sid = NULL;
3148 DOM_SID *grp_sid = NULL;
3149 uint32 i, j;
3150 size_t sd_size;
3151 int ret = 0;
3152 char *p;
3153 BOOL numeric = True;
3155 /* the_acl will be null for REMOVE_ALL operations */
3156 if (the_acl) {
3157 numeric = ((p = strchr(the_acl, ':')) != NULL &&
3158 p > the_acl &&
3159 p[-1] != '+');
3161 /* if this is to set the entire ACL... */
3162 if (*the_acl == '*') {
3163 /* ... then increment past the first colon */
3164 the_acl = p + 1;
3167 sd = sec_desc_parse(ctx, ipc_cli, pol,
3168 numeric, (char *) the_acl);
3170 if (!sd) {
3171 errno = EINVAL;
3172 return -1;
3176 /* The desired access below is the only one I could find that works
3177 with NT4, W2KP and Samba */
3179 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3181 if (fnum == -1) {
3182 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3183 filename, cli_errstr(cli)));
3184 errno = 0;
3185 return -1;
3188 old = cli_query_secdesc(cli, fnum, ctx);
3190 if (!old) {
3191 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
3192 errno = 0;
3193 return -1;
3196 cli_close(cli, fnum);
3198 switch (mode) {
3199 case SMBC_XATTR_MODE_REMOVE_ALL:
3200 old->dacl->num_aces = 0;
3201 SAFE_FREE(old->dacl->ace);
3202 SAFE_FREE(old->dacl);
3203 old->off_dacl = 0;
3204 dacl = old->dacl;
3205 break;
3207 case SMBC_XATTR_MODE_REMOVE:
3208 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3209 BOOL found = False;
3211 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3212 if (sec_ace_equal(&sd->dacl->ace[i],
3213 &old->dacl->ace[j])) {
3214 uint32 k;
3215 for (k=j; k<old->dacl->num_aces-1;k++) {
3216 old->dacl->ace[k] = old->dacl->ace[k+1];
3218 old->dacl->num_aces--;
3219 if (old->dacl->num_aces == 0) {
3220 SAFE_FREE(old->dacl->ace);
3221 SAFE_FREE(old->dacl);
3222 old->off_dacl = 0;
3224 found = True;
3225 dacl = old->dacl;
3226 break;
3230 if (!found) {
3231 err = ENOATTR;
3232 ret = -1;
3233 goto failed;
3236 break;
3238 case SMBC_XATTR_MODE_ADD:
3239 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3240 BOOL found = False;
3242 for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3243 if (sid_equal(&sd->dacl->ace[i].trustee,
3244 &old->dacl->ace[j].trustee)) {
3245 if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
3246 err = EEXIST;
3247 ret = -1;
3248 goto failed;
3250 old->dacl->ace[j] = sd->dacl->ace[i];
3251 ret = -1;
3252 found = True;
3256 if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
3257 err = ENOATTR;
3258 ret = -1;
3259 goto failed;
3262 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3263 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
3266 dacl = old->dacl;
3267 break;
3269 case SMBC_XATTR_MODE_SET:
3270 old = sd;
3271 owner_sid = old->owner_sid;
3272 grp_sid = old->grp_sid;
3273 dacl = old->dacl;
3274 break;
3276 case SMBC_XATTR_MODE_CHOWN:
3277 owner_sid = sd->owner_sid;
3278 break;
3280 case SMBC_XATTR_MODE_CHGRP:
3281 grp_sid = sd->grp_sid;
3282 break;
3285 /* Denied ACE entries must come before allowed ones */
3286 sort_acl(old->dacl);
3288 /* Create new security descriptor and set it */
3289 sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
3290 owner_sid, grp_sid, NULL, dacl, &sd_size);
3292 fnum = cli_nt_create(cli, filename,
3293 WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
3295 if (fnum == -1) {
3296 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3297 filename, cli_errstr(cli)));
3298 errno = 0;
3299 return -1;
3302 if (!cli_set_secdesc(cli, fnum, sd)) {
3303 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
3304 ret = -1;
3307 /* Clean up */
3309 failed:
3310 cli_close(cli, fnum);
3312 if (err != 0) {
3313 errno = err;
3316 return ret;
3320 int smbc_setxattr_ctx(SMBCCTX *context,
3321 const char *fname,
3322 const char *name,
3323 const void *value,
3324 size_t size,
3325 int flags)
3327 int ret;
3328 SMBCSRV *srv;
3329 SMBCSRV *ipc_srv;
3330 fstring server, share, user, password, workgroup;
3331 pstring path;
3332 TALLOC_CTX *ctx;
3333 POLICY_HND pol;
3335 if (!context || !context->internal ||
3336 !context->internal->_initialized) {
3338 errno = EINVAL; /* Best I can think of ... */
3339 return -1;
3343 if (!fname) {
3345 errno = EINVAL;
3346 return -1;
3350 DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
3351 fname, name, (int) size, (char *) value));
3353 smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
3355 if (user[0] == (char)0) fstrcpy(user, context->user);
3357 fstrcpy(workgroup, context->workgroup);
3359 srv = smbc_server(context, server, share, workgroup, user, password);
3360 if (!srv) {
3361 return -1; /* errno set by smbc_server */
3364 ipc_srv = smbc_attr_server(context, server, share,
3365 workgroup, user, password);
3366 if (!ipc_srv) {
3367 return -1;
3370 ctx = talloc_init("smbc_setxattr");
3371 if (!ctx) {
3372 errno = ENOMEM;
3373 return -1;
3377 * Are they asking to set an access control element or to set
3378 * the entire access control list?
3380 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3381 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3382 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3383 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3384 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3386 /* Yup. */
3387 char *namevalue =
3388 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3389 if (! namevalue) {
3390 errno = ENOMEM;
3391 ret = -1;
3392 } else {
3393 ret = cacl_set(ctx, &srv->cli,
3394 &ipc_srv->cli, &pol, path,
3395 namevalue,
3396 (*namevalue == '*'
3397 ? SMBC_XATTR_MODE_SET
3398 : SMBC_XATTR_MODE_ADD),
3399 flags);
3401 talloc_destroy(ctx);
3402 return ret;
3406 * Are they asking to set the owner?
3408 if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3409 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
3411 /* Yup. */
3412 char *namevalue =
3413 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3414 if (! namevalue) {
3415 errno = ENOMEM;
3416 ret = -1;
3417 } else {
3418 ret = cacl_set(ctx, &srv->cli,
3419 &ipc_srv->cli, &pol, path,
3420 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3422 talloc_destroy(ctx);
3423 return ret;
3427 * Are they asking to set the group?
3429 if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3430 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
3432 /* Yup. */
3433 char *namevalue =
3434 talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3435 if (! namevalue) {
3436 errno = ENOMEM;
3437 ret = -1;
3438 } else {
3439 ret = cacl_set(ctx, &srv->cli,
3440 &ipc_srv->cli, &pol, path,
3441 namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3443 talloc_destroy(ctx);
3444 return ret;
3447 /* Unsupported attribute name */
3448 talloc_destroy(ctx);
3449 errno = EINVAL;
3450 return -1;
3453 int smbc_getxattr_ctx(SMBCCTX *context,
3454 const char *fname,
3455 const char *name,
3456 const void *value,
3457 size_t size)
3459 int ret;
3460 SMBCSRV *srv;
3461 SMBCSRV *ipc_srv;
3462 fstring server, share, user, password, workgroup;
3463 pstring path;
3464 TALLOC_CTX *ctx;
3465 POLICY_HND pol;
3467 if (!context || !context->internal ||
3468 !context->internal->_initialized) {
3470 errno = EINVAL; /* Best I can think of ... */
3471 return -1;
3475 if (!fname) {
3477 errno = EINVAL;
3478 return -1;
3482 DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
3484 smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
3486 if (user[0] == (char)0) fstrcpy(user, context->user);
3488 fstrcpy(workgroup, context->workgroup);
3490 srv = smbc_server(context, server, share, workgroup, user, password);
3491 if (!srv) {
3492 return -1; /* errno set by smbc_server */
3495 ipc_srv = smbc_attr_server(context, server, share,
3496 workgroup, user, password);
3497 if (!ipc_srv) {
3498 return -1;
3501 ctx = talloc_init("smbc:getxattr");
3502 if (!ctx) {
3503 errno = ENOMEM;
3504 return -1;
3507 /* Are they requesting a supported attribute? */
3508 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3509 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3510 StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3511 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3512 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3513 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3514 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3515 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3516 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3518 /* Yup. */
3519 ret = cacl_get(ctx, &srv->cli,
3520 &ipc_srv->cli, &pol,
3521 (char *) path, (char *) name + 19,
3522 (char *) value, size);
3523 if (ret < 0 && errno == 0) {
3524 errno = smbc_errno(context, &srv->cli);
3526 talloc_destroy(ctx);
3527 return ret;
3530 /* Unsupported attribute name */
3531 talloc_destroy(ctx);
3532 errno = EINVAL;
3533 return -1;
3537 int smbc_removexattr_ctx(SMBCCTX *context,
3538 const char *fname,
3539 const char *name)
3541 int ret;
3542 SMBCSRV *srv;
3543 SMBCSRV *ipc_srv;
3544 fstring server, share, user, password, workgroup;
3545 pstring path;
3546 TALLOC_CTX *ctx;
3547 POLICY_HND pol;
3549 if (!context || !context->internal ||
3550 !context->internal->_initialized) {
3552 errno = EINVAL; /* Best I can think of ... */
3553 return -1;
3557 if (!fname) {
3559 errno = EINVAL;
3560 return -1;
3564 DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
3566 smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
3568 if (user[0] == (char)0) fstrcpy(user, context->user);
3570 fstrcpy(workgroup, context->workgroup);
3572 srv = smbc_server(context, server, share, workgroup, user, password);
3573 if (!srv) {
3574 return -1; /* errno set by smbc_server */
3577 ipc_srv = smbc_attr_server(context, server, share,
3578 workgroup, user, password);
3579 if (!ipc_srv) {
3580 return -1;
3583 ipc_srv = smbc_attr_server(context, server, share,
3584 workgroup, user, password);
3585 if (!ipc_srv) {
3586 return -1;
3589 ctx = talloc_init("smbc_removexattr");
3590 if (!ctx) {
3591 errno = ENOMEM;
3592 return -1;
3595 /* Are they asking to set the entire ACL? */
3596 if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3597 StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
3599 /* Yup. */
3600 ret = cacl_set(ctx, &srv->cli,
3601 &ipc_srv->cli, &pol, path,
3602 NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
3603 talloc_destroy(ctx);
3604 return ret;
3608 * Are they asking to remove one or more spceific security descriptor
3609 * attributes?
3611 if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3612 StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3613 StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3614 StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3615 StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3616 StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3617 StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3619 /* Yup. */
3620 ret = cacl_set(ctx, &srv->cli,
3621 &ipc_srv->cli, &pol, path,
3622 name + 19, SMBC_XATTR_MODE_REMOVE, 0);
3623 talloc_destroy(ctx);
3624 return ret;
3627 /* Unsupported attribute name */
3628 talloc_destroy(ctx);
3629 errno = EINVAL;
3630 return -1;
3633 int smbc_listxattr_ctx(SMBCCTX *context,
3634 const char *fname,
3635 char *list,
3636 size_t size)
3639 * This isn't quite what listxattr() is supposed to do. This returns
3640 * the complete set of attributes, always, rather than only those
3641 * attribute names which actually exist for a file. Hmmm...
3643 const char supported[] =
3644 "system.nt_sec_desc.revision\0"
3645 "system.nt_sec_desc.owner\0"
3646 "system.nt_sec_desc.owner+\0"
3647 "system.nt_sec_desc.group\0"
3648 "system.nt_sec_desc.group+\0"
3649 "system.nt_sec_desc.acl\0"
3650 "system.nt_sec_desc.acl+\0"
3651 "system.nt_sec_desc.*\0"
3652 "system.nt_sec_desc.*+\0"
3655 if (size == 0) {
3656 return sizeof(supported);
3659 if (sizeof(supported) > size) {
3660 errno = ERANGE;
3661 return -1;
3664 /* this can't be strcpy() because there are embedded null characters */
3665 memcpy(list, supported, sizeof(supported));
3666 return sizeof(supported);
3671 * Open a print file to be written to by other calls
3674 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
3676 fstring server, share, user, password;
3677 pstring path;
3679 if (!context || !context->internal ||
3680 !context->internal->_initialized) {
3682 errno = EINVAL;
3683 return NULL;
3687 if (!fname) {
3689 errno = EINVAL;
3690 return NULL;
3694 DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
3696 smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
3698 /* What if the path is empty, or the file exists? */
3700 return context->open(context, fname, O_WRONLY, 666);
3705 * Routine to print a file on a remote server ...
3707 * We open the file, which we assume to be on a remote server, and then
3708 * copy it to a print file on the share specified by printq.
3711 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
3713 SMBCFILE *fid1, *fid2;
3714 int bytes, saverr, tot_bytes = 0;
3715 char buf[4096];
3717 if (!c_file || !c_file->internal->_initialized || !c_print ||
3718 !c_print->internal->_initialized) {
3720 errno = EINVAL;
3721 return -1;
3725 if (!fname && !printq) {
3727 errno = EINVAL;
3728 return -1;
3732 /* Try to open the file for reading ... */
3734 if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
3736 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
3737 return -1; /* smbc_open sets errno */
3741 /* Now, try to open the printer file for writing */
3743 if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
3745 saverr = errno; /* Save errno */
3746 c_file->close(c_file, fid1);
3747 errno = saverr;
3748 return -1;
3752 while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
3754 tot_bytes += bytes;
3756 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
3758 saverr = errno;
3759 c_file->close(c_file, fid1);
3760 c_print->close(c_print, fid2);
3761 errno = saverr;
3767 saverr = errno;
3769 c_file->close(c_file, fid1); /* We have to close these anyway */
3770 c_print->close(c_print, fid2);
3772 if (bytes < 0) {
3774 errno = saverr;
3775 return -1;
3779 return tot_bytes;
3784 * Routine to list print jobs on a printer share ...
3787 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
3789 SMBCSRV *srv;
3790 fstring server, share, user, password, workgroup;
3791 pstring path;
3793 if (!context || !context->internal ||
3794 !context->internal->_initialized) {
3796 errno = EINVAL;
3797 return -1;
3801 if (!fname) {
3803 errno = EINVAL;
3804 return -1;
3808 DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
3810 smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
3812 if (user[0] == (char)0) fstrcpy(user, context->user);
3814 fstrcpy(workgroup, context->workgroup);
3816 srv = smbc_server(context, server, share, workgroup, user, password);
3818 if (!srv) {
3820 return -1; /* errno set by smbc_server */
3824 if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
3826 errno = smbc_errno(context, &srv->cli);
3827 return -1;
3831 return 0;
3836 * Delete a print job from a remote printer share
3839 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
3841 SMBCSRV *srv;
3842 fstring server, share, user, password, workgroup;
3843 pstring path;
3844 int err;
3846 if (!context || !context->internal ||
3847 !context->internal->_initialized) {
3849 errno = EINVAL;
3850 return -1;
3854 if (!fname) {
3856 errno = EINVAL;
3857 return -1;
3861 DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
3863 smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
3865 if (user[0] == (char)0) fstrcpy(user, context->user);
3867 fstrcpy(workgroup, context->workgroup);
3869 srv = smbc_server(context, server, share, workgroup, user, password);
3871 if (!srv) {
3873 return -1; /* errno set by smbc_server */
3877 if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
3879 if (err < 0)
3880 errno = smbc_errno(context, &srv->cli);
3881 else if (err == ERRnosuchprintjob)
3882 errno = EINVAL;
3883 return -1;
3887 return 0;
3892 * Get a new empty handle to fill in with your own info
3894 SMBCCTX * smbc_new_context(void)
3896 SMBCCTX * context;
3898 context = malloc(sizeof(SMBCCTX));
3899 if (!context) {
3900 errno = ENOMEM;
3901 return NULL;
3904 ZERO_STRUCTP(context);
3906 context->internal = malloc(sizeof(struct smbc_internal_data));
3907 if (!context->internal) {
3908 errno = ENOMEM;
3909 return NULL;
3912 ZERO_STRUCTP(context->internal);
3915 /* ADD REASONABLE DEFAULTS */
3916 context->debug = 0;
3917 context->timeout = 20000; /* 20 seconds */
3919 context->open = smbc_open_ctx;
3920 context->creat = smbc_creat_ctx;
3921 context->read = smbc_read_ctx;
3922 context->write = smbc_write_ctx;
3923 context->close = smbc_close_ctx;
3924 context->unlink = smbc_unlink_ctx;
3925 context->rename = smbc_rename_ctx;
3926 context->lseek = smbc_lseek_ctx;
3927 context->stat = smbc_stat_ctx;
3928 context->fstat = smbc_fstat_ctx;
3929 context->opendir = smbc_opendir_ctx;
3930 context->closedir = smbc_closedir_ctx;
3931 context->readdir = smbc_readdir_ctx;
3932 context->getdents = smbc_getdents_ctx;
3933 context->mkdir = smbc_mkdir_ctx;
3934 context->rmdir = smbc_rmdir_ctx;
3935 context->telldir = smbc_telldir_ctx;
3936 context->lseekdir = smbc_lseekdir_ctx;
3937 context->fstatdir = smbc_fstatdir_ctx;
3938 context->chmod = smbc_chmod_ctx;
3939 context->utimes = smbc_utimes_ctx;
3940 context->setxattr = smbc_setxattr_ctx;
3941 context->getxattr = smbc_getxattr_ctx;
3942 context->removexattr = smbc_removexattr_ctx;
3943 context->listxattr = smbc_listxattr_ctx;
3944 context->open_print_job = smbc_open_print_job_ctx;
3945 context->print_file = smbc_print_file_ctx;
3946 context->list_print_jobs = smbc_list_print_jobs_ctx;
3947 context->unlink_print_job = smbc_unlink_print_job_ctx;
3949 context->callbacks.check_server_fn = smbc_check_server;
3950 context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
3952 smbc_default_cache_functions(context);
3954 return context;
3958 * Free a context
3960 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
3961 * and thus you'll be leaking memory if not handled properly.
3964 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
3966 if (!context) {
3967 errno = EBADF;
3968 return 1;
3971 if (shutdown_ctx) {
3972 SMBCFILE * f;
3973 DEBUG(1,("Performing aggressive shutdown.\n"));
3975 f = context->internal->_files;
3976 while (f) {
3977 context->close(context, f);
3978 f = f->next;
3980 context->internal->_files = NULL;
3982 /* First try to remove the servers the nice way. */
3983 if (context->callbacks.purge_cached_fn(context)) {
3984 SMBCSRV * s;
3985 DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
3986 s = context->internal->_servers;
3987 while (s) {
3988 cli_shutdown(&s->cli);
3989 context->callbacks.remove_cached_srv_fn(context, s);
3990 SAFE_FREE(s);
3991 s = s->next;
3993 context->internal->_servers = NULL;
3996 else {
3997 /* This is the polite way */
3998 if (context->callbacks.purge_cached_fn(context)) {
3999 DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
4000 errno = EBUSY;
4001 return 1;
4003 if (context->internal->_servers) {
4004 DEBUG(1, ("Active servers in context, free_context failed.\n"));
4005 errno = EBUSY;
4006 return 1;
4008 if (context->internal->_files) {
4009 DEBUG(1, ("Active files in context, free_context failed.\n"));
4010 errno = EBUSY;
4011 return 1;
4015 /* Things we have to clean up */
4016 SAFE_FREE(context->workgroup);
4017 SAFE_FREE(context->netbios_name);
4018 SAFE_FREE(context->user);
4020 DEBUG(3, ("Context %p succesfully freed\n", context));
4021 SAFE_FREE(context->internal);
4022 SAFE_FREE(context);
4023 return 0;
4028 * Initialise the library etc
4030 * We accept a struct containing handle information.
4031 * valid values for info->debug from 0 to 100,
4032 * and insist that info->fn must be non-null.
4034 SMBCCTX * smbc_init_context(SMBCCTX * context)
4036 pstring conf;
4037 int pid;
4038 char *user = NULL, *home = NULL;
4040 if (!context || !context->internal) {
4041 errno = EBADF;
4042 return NULL;
4045 /* Do not initialise the same client twice */
4046 if (context->internal->_initialized) {
4047 return 0;
4050 if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
4052 errno = EINVAL;
4053 return NULL;
4057 if (!smbc_initialized) {
4058 /* Do some library wide intialisations the first time we get called */
4060 /* Set this to what the user wants */
4061 DEBUGLEVEL = context->debug;
4063 setup_logging( "libsmbclient", True);
4065 /* Here we would open the smb.conf file if needed ... */
4067 home = getenv("HOME");
4069 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
4071 load_interfaces(); /* Load the list of interfaces ... */
4073 in_client = True; /* FIXME, make a param */
4075 if (!lp_load(conf, True, False, False)) {
4078 * Well, if that failed, try the dyn_CONFIGFILE
4079 * Which points to the standard locn, and if that
4080 * fails, silently ignore it and use the internal
4081 * defaults ...
4084 if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
4085 DEBUG(5, ("Could not load either config file: %s or %s\n",
4086 conf, dyn_CONFIGFILE));
4090 reopen_logs(); /* Get logging working ... */
4093 * Block SIGPIPE (from lib/util_sock.c: write())
4094 * It is not needed and should not stop execution
4096 BlockSignals(True, SIGPIPE);
4098 /* Done with one-time initialisation */
4099 smbc_initialized = 1;
4103 if (!context->user) {
4105 * FIXME: Is this the best way to get the user info?
4107 user = getenv("USER");
4108 /* walk around as "guest" if no username can be found */
4109 if (!user) context->user = strdup("guest");
4110 else context->user = strdup(user);
4113 if (!context->netbios_name) {
4115 * We try to get our netbios name from the config. If that fails we fall
4116 * back on constructing our netbios name from our hostname etc
4118 if (global_myname()) {
4119 context->netbios_name = strdup(global_myname());
4121 else {
4123 * Hmmm, I want to get hostname as well, but I am too lazy for the moment
4125 pid = sys_getpid();
4126 context->netbios_name = malloc(17);
4127 if (!context->netbios_name) {
4128 errno = ENOMEM;
4129 return NULL;
4131 slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
4135 DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
4137 if (!context->workgroup) {
4138 if (lp_workgroup()) {
4139 context->workgroup = strdup(lp_workgroup());
4141 else {
4142 /* TODO: Think about a decent default workgroup */
4143 context->workgroup = strdup("samba");
4147 DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
4149 /* shortest timeout is 1 second */
4150 if (context->timeout > 0 && context->timeout < 1000)
4151 context->timeout = 1000;
4154 * FIXME: Should we check the function pointers here?
4157 context->internal->_initialized = 1;
4159 return context;