r18009: Fixes bug 4026.
[samba.git] / source / libsmb / libsmbclient.c
1 /* 
2    Unix SMB/Netbios implementation.
3    SMB client library implementation
4    Copyright (C) Andrew Tridgell 1998
5    Copyright (C) Richard Sharpe 2000, 2002
6    Copyright (C) John Terpstra 2000
7    Copyright (C) Tom Jansen (Ninja ISD) 2002 
8    Copyright (C) Derrell Lipman 2003, 2004
9    
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.
14    
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.
19    
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.
23 */
24
25 #include "includes.h"
26
27 #include "include/libsmb_internal.h"
28
29
30 /*
31  * DOS Attribute values (used internally)
32  */
33 typedef struct DOS_ATTR_DESC {
34         int mode;
35         SMB_OFF_T size;
36         time_t create_time;
37         time_t access_time;
38         time_t write_time;
39         time_t change_time;
40         SMB_INO_T inode;
41 } DOS_ATTR_DESC;
42
43
44 /*
45  * Internal flags for extended attributes
46  */
47
48 /* internal mode values */
49 #define SMBC_XATTR_MODE_ADD          1
50 #define SMBC_XATTR_MODE_REMOVE       2
51 #define SMBC_XATTR_MODE_REMOVE_ALL   3
52 #define SMBC_XATTR_MODE_SET          4
53 #define SMBC_XATTR_MODE_CHOWN        5
54 #define SMBC_XATTR_MODE_CHGRP        6
55
56 #define CREATE_ACCESS_READ      READ_CONTROL_ACCESS
57
58 /*We should test for this in configure ... */
59 #ifndef ENOTSUP
60 #define ENOTSUP EOPNOTSUPP
61 #endif
62
63 /*
64  * Functions exported by libsmb_cache.c that we need here
65  */
66 int smbc_default_cache_functions(SMBCCTX *context);
67
68 /* 
69  * check if an element is part of the list. 
70  * FIXME: Does not belong here !  
71  * Can anyone put this in a macro in dlinklist.h ?
72  * -- Tom
73  */
74 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
75         if (!p || !list) return False;
76         do {
77                 if (p == list) return True;
78                 list = list->next;
79         } while (list);
80         return False;
81 }
82
83 /*
84  * Find an lsa pipe handle associated with a cli struct.
85  */
86 static struct rpc_pipe_client *
87 find_lsa_pipe_hnd(struct cli_state *ipc_cli)
88 {
89         struct rpc_pipe_client *pipe_hnd;
90
91         for (pipe_hnd = ipc_cli->pipe_list;
92              pipe_hnd;
93              pipe_hnd = pipe_hnd->next) {
94             
95                 if (pipe_hnd->pipe_idx == PI_LSARPC) {
96                         return pipe_hnd;
97                 }
98         }
99
100         return NULL;
101 }
102
103 static int
104 smbc_close_ctx(SMBCCTX *context,
105                SMBCFILE *file);
106 static off_t
107 smbc_lseek_ctx(SMBCCTX *context,
108                SMBCFILE *file,
109                off_t offset,
110                int whence);
111
112 extern BOOL in_client;
113
114 /*
115  * Is the logging working / configfile read ? 
116  */
117 static int smbc_initialized = 0;
118
119 static int 
120 hex2int( unsigned int _char )
121 {
122     if ( _char >= 'A' && _char <='F')
123         return _char - 'A' + 10;
124     if ( _char >= 'a' && _char <='f')
125         return _char - 'a' + 10;
126     if ( _char >= '0' && _char <='9')
127         return _char - '0';
128     return -1;
129 }
130
131 /*
132  * smbc_urldecode()
133  *
134  * Convert strings of %xx to their single character equivalent.  Each 'x' must
135  * be a valid hexadecimal digit, or that % sequence is left undecoded.
136  *
137  * dest may, but need not be, the same pointer as src.
138  *
139  * Returns the number of % sequences which could not be converted due to lack
140  * of two following hexadecimal digits.
141  */
142 int
143 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
144 {
145         int old_length = strlen(src);
146         int i = 0;
147         int err_count = 0;
148         pstring temp;
149         char * p;
150
151         if ( old_length == 0 ) {
152                 return 0;
153         }
154
155         p = temp;
156         while ( i < old_length ) {
157                 unsigned char character = src[ i++ ];
158
159                 if (character == '%') {
160                         int a = i+1 < old_length ? hex2int( src[i] ) : -1;
161                         int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
162
163                         /* Replace valid sequence */
164                         if (a != -1 && b != -1) {
165
166                                 /* Replace valid %xx sequence with %dd */
167                                 character = (a * 16) + b;
168
169                                 if (character == '\0') {
170                                         break; /* Stop at %00 */
171                                 }
172
173                                 i += 2;
174                         } else {
175
176                                 err_count++;
177                         }
178                 }
179
180                 *p++ = character;
181         }
182
183         *p = '\0';
184
185         strncpy(dest, temp, max_dest_len - 1);
186         dest[max_dest_len - 1] = '\0';
187
188         return err_count;
189 }
190
191 /*
192  * smbc_urlencode()
193  *
194  * Convert any characters not specifically allowed in a URL into their %xx
195  * equivalent.
196  *
197  * Returns the remaining buffer length.
198  */
199 int
200 smbc_urlencode(char * dest, char * src, int max_dest_len)
201 {
202         char hex[] = "0123456789ABCDEF";
203
204         for (; *src != '\0' && max_dest_len >= 3; src++) {
205
206                 if ((*src < '0' &&
207                      *src != '-' &&
208                      *src != '.') ||
209                     (*src > '9' &&
210                      *src < 'A') ||
211                     (*src > 'Z' &&
212                      *src < 'a' &&
213                      *src != '_') ||
214                     (*src > 'z')) {
215                         *dest++ = '%';
216                         *dest++ = hex[(*src >> 4) & 0x0f];
217                         *dest++ = hex[*src & 0x0f];
218                         max_dest_len -= 3;
219                 } else {
220                         *dest++ = *src;
221                         max_dest_len--;
222                 }
223         }
224
225         *dest++ = '\0';
226         max_dest_len--;
227         
228         return max_dest_len;
229 }
230
231 /*
232  * Function to parse a path and turn it into components
233  *
234  * The general format of an SMB URI is explain in Christopher Hertel's CIFS
235  * book, at http://ubiqx.org/cifs/Appendix-D.html.  We accept a subset of the
236  * general format ("smb:" only; we do not look for "cifs:").
237  *
238  *
239  * We accept:
240  *  smb://[[[domain;]user[:password]@]server[/share[/path[/file]]]][?options]
241  *
242  * Meaning of URLs:
243  *
244  * smb://           Show all workgroups.
245  *
246  *                  The method of locating the list of workgroups varies
247  *                  depending upon the setting of the context variable
248  *                  context->options.browse_max_lmb_count.  This value
249  *                  determine the maximum number of local master browsers to
250  *                  query for the list of workgroups.  In order to ensure that
251  *                  a complete list of workgroups is obtained, all master
252  *                  browsers must be queried, but if there are many
253  *                  workgroups, the time spent querying can begin to add up.
254  *                  For small networks (not many workgroups), it is suggested
255  *                  that this variable be set to 0, indicating query all local
256  *                  master browsers.  When the network has many workgroups, a
257  *                  reasonable setting for this variable might be around 3.
258  *
259  * smb://name/      if name<1D> or name<1B> exists, list servers in
260  *                  workgroup, else, if name<20> exists, list all shares
261  *                  for server ...
262  *
263  * If "options" are provided, this function returns the entire option list as a
264  * string, for later parsing by the caller.  Note that currently, no options
265  * are supported.
266  */
267
268 static const char *smbc_prefix = "smb:";
269
270 static int
271 smbc_parse_path(SMBCCTX *context,
272                 const char *fname,
273                 char *workgroup, int workgroup_len,
274                 char *server, int server_len,
275                 char *share, int share_len,
276                 char *path, int path_len,
277                 char *user, int user_len,
278                 char *password, int password_len,
279                 char *options, int options_len)
280 {
281         static pstring s;
282         pstring userinfo;
283         const char *p;
284         char *q, *r;
285         int len;
286
287         server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
288
289         /*
290          * Assume we wont find an authentication domain to parse, so default
291          * to the workgroup in the provided context.
292          */
293         if (workgroup != NULL) {
294                 strncpy(workgroup, context->workgroup, workgroup_len - 1);
295                 workgroup[workgroup_len - 1] = '\0';
296         }
297
298         if (options != NULL && options_len > 0) {
299                 options[0] = (char)0;
300         }
301         pstrcpy(s, fname);
302
303         /* see if it has the right prefix */
304         len = strlen(smbc_prefix);
305         if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
306                 return -1; /* What about no smb: ? */
307         }
308
309         p = s + len;
310
311         /* Watch the test below, we are testing to see if we should exit */
312
313         if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
314
315                 DEBUG(1, ("Invalid path (does not begin with smb://"));
316                 return -1;
317
318         }
319
320         p += 2;  /* Skip the double slash */
321
322         /* See if any options were specified */
323         if ((q = strrchr(p, '?')) != NULL ) {
324                 /* There are options.  Null terminate here and point to them */
325                 *q++ = '\0';
326                 
327                 DEBUG(4, ("Found options '%s'", q));
328
329                 /* Copy the options */
330                 if (options != NULL && options_len > 0) {
331                         safe_strcpy(options, q, options_len - 1);
332                 }
333         }
334
335         if (*p == (char)0)
336             goto decoding;
337
338         if (*p == '/') {
339
340                 strncpy(server, context->workgroup, 
341                         ((strlen(context->workgroup) < 16)
342                          ? strlen(context->workgroup)
343                          : 16));
344                 server[server_len - 1] = '\0';
345                 return 0;
346                 
347         }
348
349         /*
350          * ok, its for us. Now parse out the server, share etc. 
351          *
352          * However, we want to parse out [[domain;]user[:password]@] if it
353          * exists ...
354          */
355
356         /* check that '@' occurs before '/', if '/' exists at all */
357         q = strchr_m(p, '@');
358         r = strchr_m(p, '/');
359         if (q && (!r || q < r)) {
360                 pstring username, passwd, domain;
361                 const char *u = userinfo;
362
363                 next_token_no_ltrim(&p, userinfo, "@", sizeof(fstring));
364
365                 username[0] = passwd[0] = domain[0] = 0;
366
367                 if (strchr_m(u, ';')) {
368       
369                         next_token_no_ltrim(&u, domain, ";", sizeof(fstring));
370
371                 }
372
373                 if (strchr_m(u, ':')) {
374
375                         next_token_no_ltrim(&u, username, ":", sizeof(fstring));
376
377                         pstrcpy(passwd, u);
378
379                 }
380                 else {
381
382                         pstrcpy(username, u);
383
384                 }
385
386                 if (domain[0] && workgroup) {
387                         strncpy(workgroup, domain, workgroup_len - 1);
388                         workgroup[workgroup_len - 1] = '\0';
389                 }
390
391                 if (username[0]) {
392                         strncpy(user, username, user_len - 1);
393                         user[user_len - 1] = '\0';
394                 }
395
396                 if (passwd[0]) {
397                         strncpy(password, passwd, password_len - 1);
398                         password[password_len - 1] = '\0';
399                 }
400
401         }
402
403         if (!next_token(&p, server, "/", sizeof(fstring))) {
404
405                 return -1;
406
407         }
408
409         if (*p == (char)0) goto decoding;  /* That's it ... */
410   
411         if (!next_token(&p, share, "/", sizeof(fstring))) {
412
413                 return -1;
414
415         }
416
417         safe_strcpy(path, p, path_len - 1);
418
419         all_string_sub(path, "/", "\\", 0);
420
421  decoding:
422         (void) smbc_urldecode(path, path, path_len);
423         (void) smbc_urldecode(server, server, server_len);
424         (void) smbc_urldecode(share, share, share_len);
425         (void) smbc_urldecode(user, user, user_len);
426         (void) smbc_urldecode(password, password, password_len);
427
428         return 0;
429 }
430
431 /*
432  * Verify that the options specified in a URL are valid
433  */
434 static int
435 smbc_check_options(char *server,
436                    char *share,
437                    char *path,
438                    char *options)
439 {
440         DEBUG(4, ("smbc_check_options(): server='%s' share='%s' "
441                   "path='%s' options='%s'\n",
442                   server, share, path, options));
443
444         /* No options at all is always ok */
445         if (! *options) return 0;
446
447         /* Currently, we don't support any options. */
448         return -1;
449 }
450
451 /*
452  * Convert an SMB error into a UNIX error ...
453  */
454 static int
455 smbc_errno(SMBCCTX *context,
456            struct cli_state *c)
457 {
458         int ret = cli_errno(c);
459         
460         if (cli_is_dos_error(c)) {
461                 uint8 eclass;
462                 uint32 ecode;
463
464                 cli_dos_error(c, &eclass, &ecode);
465                 
466                 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n", 
467                          (int)eclass, (int)ecode, (int)ecode, ret));
468         } else {
469                 NTSTATUS status;
470
471                 status = cli_nt_error(c);
472
473                 DEBUG(3,("smbc errno %s -> %d\n",
474                          nt_errstr(status), ret));
475         }
476
477         return ret;
478 }
479
480 /* 
481  * Check a server for being alive and well.
482  * returns 0 if the server is in shape. Returns 1 on error 
483  * 
484  * Also useable outside libsmbclient to enable external cache
485  * to do some checks too.
486  */
487 static int
488 smbc_check_server(SMBCCTX * context,
489                   SMBCSRV * server) 
490 {
491         if ( send_keepalive(server->cli->fd) == False )
492                 return 1;
493
494         /* connection is ok */
495         return 0;
496 }
497
498 /* 
499  * Remove a server from the cached server list it's unused.
500  * On success, 0 is returned. 1 is returned if the server could not be removed.
501  * 
502  * Also useable outside libsmbclient
503  */
504 int
505 smbc_remove_unused_server(SMBCCTX * context,
506                           SMBCSRV * srv)
507 {
508         SMBCFILE * file;
509
510         /* are we being fooled ? */
511         if (!context || !context->internal ||
512             !context->internal->_initialized || !srv) return 1;
513
514         
515         /* Check all open files/directories for a relation with this server */
516         for (file = context->internal->_files; file; file=file->next) {
517                 if (file->srv == srv) {
518                         /* Still used */
519                         DEBUG(3, ("smbc_remove_usused_server: "
520                                   "%p still used by %p.\n", 
521                                   srv, file));
522                         return 1;
523                 }
524         }
525
526         DLIST_REMOVE(context->internal->_servers, srv);
527
528         cli_shutdown(srv->cli);
529         srv->cli = NULL;
530
531         DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
532
533         context->callbacks.remove_cached_srv_fn(context, srv);
534
535         SAFE_FREE(srv);
536         
537         return 0;
538 }
539
540 static SMBCSRV *
541 find_server(SMBCCTX *context,
542             const char *server,
543             const char *share,
544             fstring workgroup,
545             fstring username,
546             fstring password)
547 {
548         SMBCSRV *srv;
549         int auth_called = 0;
550         
551  check_server_cache:
552
553         srv = context->callbacks.get_cached_srv_fn(context, server, share, 
554                                                    workgroup, username);
555
556         if (!auth_called && !srv && (!username[0] || !password[0])) {
557                 if (context->internal->_auth_fn_with_context != NULL) {
558                          context->internal->_auth_fn_with_context(
559                                 context,
560                                 server, share,
561                                 workgroup, sizeof(fstring),
562                                 username, sizeof(fstring),
563                                 password, sizeof(fstring));
564                 } else {
565                         context->callbacks.auth_fn(
566                                 server, share,
567                                 workgroup, sizeof(fstring),
568                                 username, sizeof(fstring),
569                                 password, sizeof(fstring));
570                 }
571
572                 /*
573                  * However, smbc_auth_fn may have picked up info relating to
574                  * an existing connection, so try for an existing connection
575                  * again ...
576                  */
577                 auth_called = 1;
578                 goto check_server_cache;
579                 
580         }
581         
582         if (srv) {
583                 if (context->callbacks.check_server_fn(context, srv)) {
584                         /*
585                          * This server is no good anymore 
586                          * Try to remove it and check for more possible
587                          * servers in the cache
588                          */
589                         if (context->callbacks.remove_unused_server_fn(context,
590                                                                        srv)) { 
591                                 /*
592                                  * We could not remove the server completely,
593                                  * remove it from the cache so we will not get
594                                  * it again. It will be removed when the last
595                                  * file/dir is closed.
596                                  */
597                                 context->callbacks.remove_cached_srv_fn(context,
598                                                                         srv);
599                         }
600                         
601                         /*
602                          * Maybe there are more cached connections to this
603                          * server
604                          */
605                         goto check_server_cache; 
606                 }
607
608                 return srv;
609         }
610
611         return NULL;
612 }
613
614 /*
615  * Connect to a server, possibly on an existing connection
616  *
617  * Here, what we want to do is: If the server and username
618  * match an existing connection, reuse that, otherwise, establish a 
619  * new connection.
620  *
621  * If we have to create a new connection, call the auth_fn to get the
622  * info we need, unless the username and password were passed in.
623  */
624
625 static SMBCSRV *
626 smbc_server(SMBCCTX *context,
627             BOOL connect_if_not_found,
628             const char *server,
629             const char *share, 
630             fstring workgroup,
631             fstring username, 
632             fstring password)
633 {
634         SMBCSRV *srv=NULL;
635         struct cli_state *c;
636         struct nmb_name called, calling;
637         const char *server_n = server;
638         pstring ipenv;
639         struct in_addr ip;
640         int tried_reverse = 0;
641         int port_try_first;
642         int port_try_next;
643         const char *username_used;
644   
645         zero_ip(&ip);
646         ZERO_STRUCT(c);
647
648         if (server[0] == 0) {
649                 errno = EPERM;
650                 return NULL;
651         }
652
653         /* Look for a cached connection */
654         srv = find_server(context, server, share,
655                           workgroup, username, password);
656         
657         /*
658          * If we found a connection and we're only allowed one share per
659          * server...
660          */
661         if (srv && *share != '\0' && context->options.one_share_per_server) {
662
663                 /*
664                  * ... then if there's no current connection to the share,
665                  * connect to it.  find_server(), or rather the function
666                  * pointed to by context->callbacks.get_cached_srv_fn which
667                  * was called by find_server(), will have issued a tree
668                  * disconnect if the requested share is not the same as the
669                  * one that was already connected.
670                  */
671                 if (srv->cli->cnum == (uint16) -1) {
672                         /* Ensure we have accurate auth info */
673                         if (context->internal->_auth_fn_with_context != NULL) {
674                                 context->internal->_auth_fn_with_context(
675                                         context,
676                                         server, share,
677                                         workgroup, sizeof(fstring),
678                                         username, sizeof(fstring),
679                                         password, sizeof(fstring));
680                         } else {
681                                 context->callbacks.auth_fn(
682                                         server, share,
683                                         workgroup, sizeof(fstring),
684                                         username, sizeof(fstring),
685                                         password, sizeof(fstring));
686                         }
687
688                         if (! cli_send_tconX(srv->cli, share, "?????",
689                                              password, strlen(password)+1)) {
690                         
691                                 errno = smbc_errno(context, srv->cli);
692                                 cli_shutdown(srv->cli);
693                                 srv->cli = NULL;
694                                 context->callbacks.remove_cached_srv_fn(context,
695                                                                         srv);
696                                 srv = NULL;
697                         }
698
699                         /*
700                          * Regenerate the dev value since it's based on both
701                          * server and share
702                          */
703                         if (srv) {
704                                 srv->dev = (dev_t)(str_checksum(server) ^
705                                                    str_checksum(share));
706                         }
707                 }
708         }
709         
710         /* If we have a connection... */
711         if (srv) {
712
713                 /* ... then we're done here.  Give 'em what they came for. */
714                 return srv;
715         }
716
717         /* If we're not asked to connect when a connection doesn't exist... */
718         if (! connect_if_not_found) {
719                 /* ... then we're done here. */
720                 return NULL;
721         }
722
723         make_nmb_name(&calling, context->netbios_name, 0x0);
724         make_nmb_name(&called , server, 0x20);
725
726         DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
727   
728         DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
729
730  again:
731         slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
732
733         zero_ip(&ip);
734
735         /* have to open a new connection */
736         if ((c = cli_initialise()) == NULL) {
737                 errno = ENOMEM;
738                 return NULL;
739         }
740
741         if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
742                 c->use_kerberos = True;
743         }
744         if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
745                 c->fallback_after_kerberos = True;
746         }
747
748         c->timeout = context->timeout;
749
750         /*
751          * Force use of port 139 for first try if share is $IPC, empty, or
752          * null, so browse lists can work
753          */
754         if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
755                 port_try_first = 139;
756                 port_try_next = 445;
757         } else {
758                 port_try_first = 445;
759                 port_try_next = 139;
760         }
761
762         c->port = port_try_first;
763
764         if (!cli_connect(c, server_n, &ip)) {
765
766                 /* First connection attempt failed.  Try alternate port. */
767                 c->port = port_try_next;
768
769                 if (!cli_connect(c, server_n, &ip)) {
770                         cli_shutdown(c);
771                         errno = ETIMEDOUT;
772                         return NULL;
773                 }
774         }
775
776         if (!cli_session_request(c, &calling, &called)) {
777                 cli_shutdown(c);
778                 if (strcmp(called.name, "*SMBSERVER")) {
779                         make_nmb_name(&called , "*SMBSERVER", 0x20);
780                         goto again;
781                 } else {  /* Try one more time, but ensure we don't loop */
782
783                         /* Only try this if server is an IP address ... */
784
785                         if (is_ipaddress(server) && !tried_reverse) {
786                                 fstring remote_name;
787                                 struct in_addr rem_ip;
788
789                                 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
790                                         DEBUG(4, ("Could not convert IP address "
791                                                 "%s to struct in_addr\n", server));
792                                         errno = ETIMEDOUT;
793                                         return NULL;
794                                 }
795
796                                 tried_reverse++; /* Yuck */
797
798                                 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
799                                         make_nmb_name(&called, remote_name, 0x20);
800                                         goto again;
801                                 }
802                         }
803                 }
804                 errno = ETIMEDOUT;
805                 return NULL;
806         }
807   
808         DEBUG(4,(" session request ok\n"));
809   
810         if (!cli_negprot(c)) {
811                 cli_shutdown(c);
812                 errno = ETIMEDOUT;
813                 return NULL;
814         }
815
816         username_used = username;
817
818         if (!NT_STATUS_IS_OK(cli_session_setup(c, username_used, 
819                                                password, strlen(password),
820                                                password, strlen(password),
821                                                workgroup))) {
822                 
823                 /* Failed.  Try an anonymous login, if allowed by flags. */
824                 username_used = "";
825
826                 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
827                      !NT_STATUS_IS_OK(cli_session_setup(c, username_used,
828                                                         password, 1,
829                                                         password, 0,
830                                                         workgroup))) {
831
832                         cli_shutdown(c);
833                         errno = EPERM;
834                         return NULL;
835                 }
836         }
837
838         DEBUG(4,(" session setup ok\n"));
839
840         if (!cli_send_tconX(c, share, "?????",
841                             password, strlen(password)+1)) {
842                 errno = smbc_errno(context, c);
843                 cli_shutdown(c);
844                 return NULL;
845         }
846   
847         DEBUG(4,(" tconx ok\n"));
848   
849         /*
850          * Ok, we have got a nice connection
851          * Let's allocate a server structure.
852          */
853
854         srv = SMB_MALLOC_P(SMBCSRV);
855         if (!srv) {
856                 errno = ENOMEM;
857                 goto failed;
858         }
859
860         ZERO_STRUCTP(srv);
861         srv->cli = c;
862         srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
863         srv->no_pathinfo = False;
864         srv->no_pathinfo2 = False;
865         srv->no_nt_session = False;
866
867         /* now add it to the cache (internal or external)  */
868         /* Let the cache function set errno if it wants to */
869         errno = 0;
870         if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
871                 int saved_errno = errno;
872                 DEBUG(3, (" Failed to add server to cache\n"));
873                 errno = saved_errno;
874                 if (errno == 0) {
875                         errno = ENOMEM;
876                 }
877                 goto failed;
878         }
879         
880         DEBUG(2, ("Server connect ok: //%s/%s: %p\n", 
881                   server, share, srv));
882
883         DLIST_ADD(context->internal->_servers, srv);
884         return srv;
885
886  failed:
887         cli_shutdown(c);
888         if (!srv) {
889                 return NULL;
890         }
891   
892         SAFE_FREE(srv);
893         return NULL;
894 }
895
896 /*
897  * Connect to a server for getting/setting attributes, possibly on an existing
898  * connection.  This works similarly to smbc_server().
899  */
900 static SMBCSRV *
901 smbc_attr_server(SMBCCTX *context,
902                  const char *server,
903                  const char *share, 
904                  fstring workgroup,
905                  fstring username,
906                  fstring password,
907                  POLICY_HND *pol)
908 {
909         struct in_addr ip;
910         struct cli_state *ipc_cli;
911         struct rpc_pipe_client *pipe_hnd;
912         NTSTATUS nt_status;
913         SMBCSRV *ipc_srv=NULL;
914
915         /*
916          * See if we've already created this special connection.  Reference
917          * our "special" share name '*IPC$', which is an impossible real share
918          * name due to the leading asterisk.
919          */
920         ipc_srv = find_server(context, server, "*IPC$",
921                               workgroup, username, password);
922         if (!ipc_srv) {
923
924                 /* We didn't find a cached connection.  Get the password */
925                 if (*password == '\0') {
926                         /* ... then retrieve it now. */
927                         if (context->internal->_auth_fn_with_context != NULL) {
928                                 context->internal->_auth_fn_with_context(
929                                         context,
930                                         server, share,
931                                         workgroup, sizeof(fstring),
932                                         username, sizeof(fstring),
933                                         password, sizeof(fstring));
934                         } else {
935                                 context->callbacks.auth_fn(
936                                         server, share,
937                                         workgroup, sizeof(fstring),
938                                         username, sizeof(fstring),
939                                         password, sizeof(fstring));
940                         }
941                 }
942         
943                 zero_ip(&ip);
944                 nt_status = cli_full_connection(&ipc_cli,
945                                                 global_myname(), server, 
946                                                 &ip, 0, "IPC$", "?????",  
947                                                 username, workgroup,
948                                                 password, 0,
949                                                 Undefined, NULL);
950                 if (! NT_STATUS_IS_OK(nt_status)) {
951                         DEBUG(1,("cli_full_connection failed! (%s)\n",
952                                  nt_errstr(nt_status)));
953                         errno = ENOTSUP;
954                         return NULL;
955                 }
956
957                 ipc_srv = SMB_MALLOC_P(SMBCSRV);
958                 if (!ipc_srv) {
959                         errno = ENOMEM;
960                         cli_shutdown(ipc_cli);
961                         return NULL;
962                 }
963
964                 ZERO_STRUCTP(ipc_srv);
965                 ipc_srv->cli = ipc_cli;
966
967                 if (pol) {
968                         pipe_hnd = cli_rpc_pipe_open_noauth(ipc_srv->cli,
969                                                             PI_LSARPC,
970                                                             &nt_status);
971                         if (!pipe_hnd) {
972                                 DEBUG(1, ("cli_nt_session_open fail!\n"));
973                                 errno = ENOTSUP;
974                                 cli_shutdown(ipc_srv->cli);
975                                 free(ipc_srv);
976                                 return NULL;
977                         }
978
979                         /*
980                          * Some systems don't support
981                          * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
982                          * so we might as well do it too.
983                          */
984         
985                         nt_status = rpccli_lsa_open_policy(
986                                 pipe_hnd,
987                                 ipc_srv->cli->mem_ctx,
988                                 True, 
989                                 GENERIC_EXECUTE_ACCESS,
990                                 pol);
991         
992                         if (!NT_STATUS_IS_OK(nt_status)) {
993                                 errno = smbc_errno(context, ipc_srv->cli);
994                                 cli_shutdown(ipc_srv->cli);
995                                 return NULL;
996                         }
997                 }
998
999                 /* now add it to the cache (internal or external) */
1000
1001                 errno = 0;      /* let cache function set errno if it likes */
1002                 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
1003                                                          server,
1004                                                          "*IPC$",
1005                                                          workgroup,
1006                                                          username)) {
1007                         DEBUG(3, (" Failed to add server to cache\n"));
1008                         if (errno == 0) {
1009                                 errno = ENOMEM;
1010                         }
1011                         cli_shutdown(ipc_srv->cli);
1012                         free(ipc_srv);
1013                         return NULL;
1014                 }
1015
1016                 DLIST_ADD(context->internal->_servers, ipc_srv);
1017         }
1018
1019         return ipc_srv;
1020 }
1021
1022 /*
1023  * Routine to open() a file ...
1024  */
1025
1026 static SMBCFILE *
1027 smbc_open_ctx(SMBCCTX *context,
1028               const char *fname,
1029               int flags,
1030               mode_t mode)
1031 {
1032         fstring server, share, user, password, workgroup;
1033         pstring path;
1034         pstring targetpath;
1035         struct cli_state *targetcli;
1036         SMBCSRV *srv   = NULL;
1037         SMBCFILE *file = NULL;
1038         int fd;
1039
1040         if (!context || !context->internal ||
1041             !context->internal->_initialized) {
1042
1043                 errno = EINVAL;  /* Best I can think of ... */
1044                 return NULL;
1045
1046         }
1047
1048         if (!fname) {
1049
1050                 errno = EINVAL;
1051                 return NULL;
1052
1053         }
1054
1055         if (smbc_parse_path(context, fname,
1056                             workgroup, sizeof(workgroup),
1057                             server, sizeof(server),
1058                             share, sizeof(share),
1059                             path, sizeof(path),
1060                             user, sizeof(user),
1061                             password, sizeof(password),
1062                             NULL, 0)) {
1063                 errno = EINVAL;
1064                 return NULL;
1065         }
1066
1067         if (user[0] == (char)0) fstrcpy(user, context->user);
1068
1069         srv = smbc_server(context, True,
1070                           server, share, workgroup, user, password);
1071
1072         if (!srv) {
1073
1074                 if (errno == EPERM) errno = EACCES;
1075                 return NULL;  /* smbc_server sets errno */
1076     
1077         }
1078
1079         /* Hmmm, the test for a directory is suspect here ... FIXME */
1080
1081         if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1082     
1083                 fd = -1;
1084
1085         }
1086         else {
1087           
1088                 file = SMB_MALLOC_P(SMBCFILE);
1089
1090                 if (!file) {
1091
1092                         errno = ENOMEM;
1093                         return NULL;
1094
1095                 }
1096
1097                 ZERO_STRUCTP(file);
1098
1099                 /*d_printf(">>>open: resolving %s\n", path);*/
1100                 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1101                 {
1102                         d_printf("Could not resolve %s\n", path);
1103                         SAFE_FREE(file);
1104                         return NULL;
1105                 }
1106                 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1107                 
1108                 if ( targetcli->dfsroot )
1109                 {
1110                         pstring temppath;
1111                         pstrcpy(temppath, targetpath);
1112                         cli_dfs_make_full_path( targetpath, targetcli->desthost, targetcli->share, temppath);
1113                 }
1114                 
1115                 if ((fd = cli_open(targetcli, targetpath, flags, DENY_NONE)) < 0) {
1116
1117                         /* Handle the error ... */
1118
1119                         SAFE_FREE(file);
1120                         errno = smbc_errno(context, targetcli);
1121                         return NULL;
1122
1123                 }
1124
1125                 /* Fill in file struct */
1126
1127                 file->cli_fd  = fd;
1128                 file->fname   = SMB_STRDUP(fname);
1129                 file->srv     = srv;
1130                 file->offset  = 0;
1131                 file->file    = True;
1132
1133                 DLIST_ADD(context->internal->_files, file);
1134
1135                 /*
1136                  * If the file was opened in O_APPEND mode, all write
1137                  * operations should be appended to the file.  To do that,
1138                  * though, using this protocol, would require a getattrE()
1139                  * call for each and every write, to determine where the end
1140                  * of the file is. (There does not appear to be an append flag
1141                  * in the protocol.)  Rather than add all of that overhead of
1142                  * retrieving the current end-of-file offset prior to each
1143                  * write operation, we'll assume that most append operations
1144                  * will continuously write, so we'll just set the offset to
1145                  * the end of the file now and hope that's adequate.
1146                  *
1147                  * Note to self: If this proves inadequate, and O_APPEND
1148                  * should, in some cases, be forced for each write, add a
1149                  * field in the context options structure, for
1150                  * "strict_append_mode" which would select between the current
1151                  * behavior (if FALSE) or issuing a getattrE() prior to each
1152                  * write and forcing the write to the end of the file (if
1153                  * TRUE).  Adding that capability will likely require adding
1154                  * an "append" flag into the _SMBCFILE structure to track
1155                  * whether a file was opened in O_APPEND mode.  -- djl
1156                  */
1157                 if (flags & O_APPEND) {
1158                         if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1159                                 (void) smbc_close_ctx(context, file);
1160                                 errno = ENXIO;
1161                                 return NULL;
1162                         }
1163                 }
1164
1165                 return file;
1166
1167         }
1168
1169         /* Check if opendir needed ... */
1170
1171         if (fd == -1) {
1172                 int eno = 0;
1173
1174                 eno = smbc_errno(context, srv->cli);
1175                 file = context->opendir(context, fname);
1176                 if (!file) errno = eno;
1177                 return file;
1178
1179         }
1180
1181         errno = EINVAL; /* FIXME, correct errno ? */
1182         return NULL;
1183
1184 }
1185
1186 /*
1187  * Routine to create a file 
1188  */
1189
1190 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1191
1192 static SMBCFILE *
1193 smbc_creat_ctx(SMBCCTX *context,
1194                const char *path,
1195                mode_t mode)
1196 {
1197
1198         if (!context || !context->internal ||
1199             !context->internal->_initialized) {
1200
1201                 errno = EINVAL;
1202                 return NULL;
1203
1204         }
1205
1206         return smbc_open_ctx(context, path, creat_bits, mode);
1207 }
1208
1209 /*
1210  * Routine to read() a file ...
1211  */
1212
1213 static ssize_t
1214 smbc_read_ctx(SMBCCTX *context,
1215               SMBCFILE *file,
1216               void *buf,
1217               size_t count)
1218 {
1219         int ret;
1220         fstring server, share, user, password;
1221         pstring path, targetpath;
1222         struct cli_state *targetcli;
1223
1224         /*
1225          * offset:
1226          *
1227          * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1228          * appears to pass file->offset (which is type off_t) differently than
1229          * a local variable of type off_t.  Using local variable "offset" in
1230          * the call to cli_read() instead of file->offset fixes a problem
1231          * retrieving data at an offset greater than 4GB.
1232          */
1233         off_t offset;
1234
1235         if (!context || !context->internal ||
1236             !context->internal->_initialized) {
1237
1238                 errno = EINVAL;
1239                 return -1;
1240
1241         }
1242
1243         DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1244
1245         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1246
1247                 errno = EBADF;
1248                 return -1;
1249
1250         }
1251
1252         offset = file->offset;
1253
1254         /* Check that the buffer exists ... */
1255
1256         if (buf == NULL) {
1257
1258                 errno = EINVAL;
1259                 return -1;
1260
1261         }
1262
1263         /*d_printf(">>>read: parsing %s\n", file->fname);*/
1264         if (smbc_parse_path(context, file->fname,
1265                             NULL, 0,
1266                             server, sizeof(server),
1267                             share, sizeof(share),
1268                             path, sizeof(path),
1269                             user, sizeof(user),
1270                             password, sizeof(password),
1271                             NULL, 0)) {
1272                 errno = EINVAL;
1273                 return -1;
1274         }
1275         
1276         /*d_printf(">>>read: resolving %s\n", path);*/
1277         if (!cli_resolve_path("", file->srv->cli, path,
1278                               &targetcli, targetpath))
1279         {
1280                 d_printf("Could not resolve %s\n", path);
1281                 return -1;
1282         }
1283         /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1284         
1285         ret = cli_read(targetcli, file->cli_fd, (char *)buf, offset, count);
1286
1287         if (ret < 0) {
1288
1289                 errno = smbc_errno(context, targetcli);
1290                 return -1;
1291
1292         }
1293
1294         file->offset += ret;
1295
1296         DEBUG(4, ("  --> %d\n", ret));
1297
1298         return ret;  /* Success, ret bytes of data ... */
1299
1300 }
1301
1302 /*
1303  * Routine to write() a file ...
1304  */
1305
1306 static ssize_t
1307 smbc_write_ctx(SMBCCTX *context,
1308                SMBCFILE *file,
1309                void *buf,
1310                size_t count)
1311 {
1312         int ret;
1313         off_t offset;
1314         fstring server, share, user, password;
1315         pstring path, targetpath;
1316         struct cli_state *targetcli;
1317
1318         /* First check all pointers before dereferencing them */
1319         
1320         if (!context || !context->internal ||
1321             !context->internal->_initialized) {
1322
1323                 errno = EINVAL;
1324                 return -1;
1325
1326         }
1327
1328         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1329
1330                 errno = EBADF;
1331                 return -1;
1332     
1333         }
1334
1335         /* Check that the buffer exists ... */
1336
1337         if (buf == NULL) {
1338
1339                 errno = EINVAL;
1340                 return -1;
1341
1342         }
1343
1344         offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1345
1346         /*d_printf(">>>write: parsing %s\n", file->fname);*/
1347         if (smbc_parse_path(context, file->fname,
1348                             NULL, 0,
1349                             server, sizeof(server),
1350                             share, sizeof(share),
1351                             path, sizeof(path),
1352                             user, sizeof(user),
1353                             password, sizeof(password),
1354                             NULL, 0)) {
1355                 errno = EINVAL;
1356                 return -1;
1357         }
1358         
1359         /*d_printf(">>>write: resolving %s\n", path);*/
1360         if (!cli_resolve_path("", file->srv->cli, path,
1361                               &targetcli, targetpath))
1362         {
1363                 d_printf("Could not resolve %s\n", path);
1364                 return -1;
1365         }
1366         /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1367
1368
1369         ret = cli_write(targetcli, file->cli_fd, 0, (char *)buf, offset, count);
1370
1371         if (ret <= 0) {
1372
1373                 errno = smbc_errno(context, targetcli);
1374                 return -1;
1375
1376         }
1377
1378         file->offset += ret;
1379
1380         return ret;  /* Success, 0 bytes of data ... */
1381 }
1382  
1383 /*
1384  * Routine to close() a file ...
1385  */
1386
1387 static int
1388 smbc_close_ctx(SMBCCTX *context,
1389                SMBCFILE *file)
1390 {
1391         SMBCSRV *srv; 
1392         fstring server, share, user, password;
1393         pstring path, targetpath;
1394         struct cli_state *targetcli;
1395
1396         if (!context || !context->internal ||
1397             !context->internal->_initialized) {
1398
1399                 errno = EINVAL;
1400                 return -1;
1401
1402         }
1403
1404         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1405    
1406                 errno = EBADF;
1407                 return -1;
1408
1409         }
1410
1411         /* IS a dir ... */
1412         if (!file->file) {
1413                 
1414                 return context->closedir(context, file);
1415
1416         }
1417
1418         /*d_printf(">>>close: parsing %s\n", file->fname);*/
1419         if (smbc_parse_path(context, file->fname,
1420                             NULL, 0,
1421                             server, sizeof(server),
1422                             share, sizeof(share),
1423                             path, sizeof(path),
1424                             user, sizeof(user),
1425                             password, sizeof(password),
1426                             NULL, 0)) {
1427                 errno = EINVAL;
1428                 return -1;
1429         }
1430         
1431         /*d_printf(">>>close: resolving %s\n", path);*/
1432         if (!cli_resolve_path("", file->srv->cli, path,
1433                               &targetcli, targetpath))
1434         {
1435                 d_printf("Could not resolve %s\n", path);
1436                 return -1;
1437         }
1438         /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1439
1440         if (!cli_close(targetcli, file->cli_fd)) {
1441
1442                 DEBUG(3, ("cli_close failed on %s. purging server.\n", 
1443                           file->fname));
1444                 /* Deallocate slot and remove the server 
1445                  * from the server cache if unused */
1446                 errno = smbc_errno(context, targetcli);
1447                 srv = file->srv;
1448                 DLIST_REMOVE(context->internal->_files, file);
1449                 SAFE_FREE(file->fname);
1450                 SAFE_FREE(file);
1451                 context->callbacks.remove_unused_server_fn(context, srv);
1452
1453                 return -1;
1454
1455         }
1456
1457         DLIST_REMOVE(context->internal->_files, file);
1458         SAFE_FREE(file->fname);
1459         SAFE_FREE(file);
1460
1461         return 0;
1462 }
1463
1464 /*
1465  * Get info from an SMB server on a file. Use a qpathinfo call first
1466  * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1467  */
1468 static BOOL
1469 smbc_getatr(SMBCCTX * context,
1470             SMBCSRV *srv,
1471             char *path, 
1472             uint16 *mode,
1473             SMB_OFF_T *size, 
1474             struct timespec *create_time_ts,
1475             struct timespec *access_time_ts,
1476             struct timespec *write_time_ts,
1477             struct timespec *change_time_ts,
1478             SMB_INO_T *ino)
1479 {
1480         pstring fixedpath;
1481         pstring targetpath;
1482         struct cli_state *targetcli;
1483         time_t write_time;
1484
1485         if (!context || !context->internal ||
1486             !context->internal->_initialized) {
1487  
1488                 errno = EINVAL;
1489                 return -1;
1490  
1491         }
1492
1493         /* path fixup for . and .. */
1494         if (strequal(path, ".") || strequal(path, ".."))
1495                 pstrcpy(fixedpath, "\\");
1496         else
1497         {
1498                 pstrcpy(fixedpath, path);
1499                 trim_string(fixedpath, NULL, "\\..");
1500                 trim_string(fixedpath, NULL, "\\.");
1501         }
1502         DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1503   
1504         if (!cli_resolve_path( "", srv->cli, fixedpath, &targetcli, targetpath))
1505         {
1506                 d_printf("Couldn't resolve %s\n", path);
1507                 return False;
1508         }
1509         
1510         if ( targetcli->dfsroot )
1511         {
1512                 pstring temppath;
1513                 pstrcpy(temppath, targetpath);
1514                 cli_dfs_make_full_path(targetpath, targetcli->desthost,
1515                                        targetcli->share, temppath);
1516         }
1517   
1518         if (!srv->no_pathinfo2 &&
1519             cli_qpathinfo2(targetcli, targetpath,
1520                            create_time_ts,
1521                            access_time_ts,
1522                            write_time_ts,
1523                            change_time_ts,
1524                            size, mode, ino)) {
1525             return True;
1526         }
1527
1528         /* if this is NT then don't bother with the getatr */
1529         if (targetcli->capabilities & CAP_NT_SMBS) {
1530                 errno = EPERM;
1531                 return False;
1532         }
1533
1534         if (cli_getatr(targetcli, targetpath, mode, size, &write_time)) {
1535
1536                 struct timespec w_time_ts;
1537
1538                 w_time_ts = convert_time_t_to_timespec(write_time);
1539
1540                 if (write_time_ts != NULL) {
1541                         *write_time_ts = w_time_ts;
1542                 }
1543
1544                 if (create_time_ts != NULL) {
1545                         *create_time_ts = w_time_ts;
1546                 }
1547                 
1548                 if (access_time_ts != NULL) {
1549                         *access_time_ts = w_time_ts;
1550                 }
1551                 
1552                 if (change_time_ts != NULL) {
1553                         *change_time_ts = w_time_ts;
1554                 }
1555
1556                 srv->no_pathinfo2 = True;
1557                 return True;
1558         }
1559
1560         errno = EPERM;
1561         return False;
1562
1563 }
1564
1565 /*
1566  * Set file info on an SMB server.  Use setpathinfo call first.  If that
1567  * fails, use setattrE..
1568  *
1569  * Access and modification time parameters are always used and must be
1570  * provided.  Create time, if zero, will be determined from the actual create
1571  * time of the file.  If non-zero, the create time will be set as well.
1572  *
1573  * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1574  */
1575 static BOOL
1576 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path, 
1577             time_t create_time,
1578             time_t access_time,
1579             time_t write_time,
1580             time_t change_time,
1581             uint16 mode)
1582 {
1583         int fd;
1584         int ret;
1585
1586         /*
1587          * First, try setpathinfo (if qpathinfo succeeded), for it is the
1588          * modern function for "new code" to be using, and it works given a
1589          * filename rather than requiring that the file be opened to have its
1590          * attributes manipulated.
1591          */
1592         if (srv->no_pathinfo ||
1593             ! cli_setpathinfo(srv->cli, path,
1594                               create_time,
1595                               access_time,
1596                               write_time,
1597                               change_time,
1598                               mode)) {
1599
1600                 /*
1601                  * setpathinfo is not supported; go to plan B. 
1602                  *
1603                  * cli_setatr() does not work on win98, and it also doesn't
1604                  * support setting the access time (only the modification
1605                  * time), so in all cases, we open the specified file and use
1606                  * cli_setattrE() which should work on all OS versions, and
1607                  * supports both times.
1608                  */
1609
1610                 /* Don't try {q,set}pathinfo() again, with this server */
1611                 srv->no_pathinfo = True;
1612
1613                 /* Open the file */
1614                 if ((fd = cli_open(srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1615
1616                         errno = smbc_errno(context, srv->cli);
1617                         return -1;
1618                 }
1619
1620                 /* Set the new attributes */
1621                 ret = cli_setattrE(srv->cli, fd,
1622                                    change_time,
1623                                    access_time,
1624                                    write_time);
1625
1626                 /* Close the file */
1627                 cli_close(srv->cli, fd);
1628
1629                 /*
1630                  * Unfortunately, setattrE() doesn't have a provision for
1631                  * setting the access mode (attributes).  We'll have to try
1632                  * cli_setatr() for that, and with only this parameter, it
1633                  * seems to work on win98.
1634                  */
1635                 if (ret && mode != (uint16) -1) {
1636                         ret = cli_setatr(srv->cli, path, mode, 0);
1637                 }
1638
1639                 if (! ret) {
1640                         errno = smbc_errno(context, srv->cli);
1641                         return False;
1642                 }
1643         }
1644
1645         return True;
1646 }
1647
1648  /*
1649   * Routine to unlink() a file
1650   */
1651
1652 static int
1653 smbc_unlink_ctx(SMBCCTX *context,
1654                 const char *fname)
1655 {
1656         fstring server, share, user, password, workgroup;
1657         pstring path, targetpath;
1658         struct cli_state *targetcli;
1659         SMBCSRV *srv = NULL;
1660
1661         if (!context || !context->internal ||
1662             !context->internal->_initialized) {
1663
1664                 errno = EINVAL;  /* Best I can think of ... */
1665                 return -1;
1666
1667         }
1668
1669         if (!fname) {
1670
1671                 errno = EINVAL;
1672                 return -1;
1673
1674         }
1675
1676         if (smbc_parse_path(context, fname,
1677                             workgroup, sizeof(workgroup),
1678                             server, sizeof(server),
1679                             share, sizeof(share),
1680                             path, sizeof(path),
1681                             user, sizeof(user),
1682                             password, sizeof(password),
1683                             NULL, 0)) {
1684                 errno = EINVAL;
1685                 return -1;
1686         }
1687
1688         if (user[0] == (char)0) fstrcpy(user, context->user);
1689
1690         srv = smbc_server(context, True,
1691                           server, share, workgroup, user, password);
1692
1693         if (!srv) {
1694
1695                 return -1;  /* smbc_server sets errno */
1696
1697         }
1698
1699         /*d_printf(">>>unlink: resolving %s\n", path);*/
1700         if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1701         {
1702                 d_printf("Could not resolve %s\n", path);
1703                 return -1;
1704         }
1705         /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1706
1707         if (!cli_unlink(targetcli, targetpath)) {
1708
1709                 errno = smbc_errno(context, targetcli);
1710
1711                 if (errno == EACCES) { /* Check if the file is a directory */
1712
1713                         int saverr = errno;
1714                         SMB_OFF_T size = 0;
1715                         uint16 mode = 0;
1716                         struct timespec write_time_ts;
1717                         struct timespec access_time_ts;
1718                         struct timespec change_time_ts;
1719                         SMB_INO_T ino = 0;
1720
1721                         if (!smbc_getatr(context, srv, path, &mode, &size,
1722                                          NULL,
1723                                          &access_time_ts,
1724                                          &write_time_ts,
1725                                          &change_time_ts,
1726                                          &ino)) {
1727
1728                                 /* Hmmm, bad error ... What? */
1729
1730                                 errno = smbc_errno(context, targetcli);
1731                                 return -1;
1732
1733                         }
1734                         else {
1735
1736                                 if (IS_DOS_DIR(mode))
1737                                         errno = EISDIR;
1738                                 else
1739                                         errno = saverr;  /* Restore this */
1740
1741                         }
1742                 }
1743
1744                 return -1;
1745
1746         }
1747
1748         return 0;  /* Success ... */
1749
1750 }
1751
1752 /*
1753  * Routine to rename() a file
1754  */
1755
1756 static int
1757 smbc_rename_ctx(SMBCCTX *ocontext,
1758                 const char *oname, 
1759                 SMBCCTX *ncontext,
1760                 const char *nname)
1761 {
1762         fstring server1;
1763         fstring share1;
1764         fstring server2;
1765         fstring share2;
1766         fstring user1;
1767         fstring user2;
1768         fstring password1;
1769         fstring password2;
1770         fstring workgroup;
1771         pstring path1;
1772         pstring path2;
1773         pstring targetpath1;
1774         pstring targetpath2;
1775         struct cli_state *targetcli1;
1776         struct cli_state *targetcli2;
1777         SMBCSRV *srv = NULL;
1778
1779         if (!ocontext || !ncontext || 
1780             !ocontext->internal || !ncontext->internal ||
1781             !ocontext->internal->_initialized || 
1782             !ncontext->internal->_initialized) {
1783
1784                 errno = EINVAL;  /* Best I can think of ... */
1785                 return -1;
1786
1787         }
1788         
1789         if (!oname || !nname) {
1790
1791                 errno = EINVAL;
1792                 return -1;
1793
1794         }
1795         
1796         DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1797
1798         smbc_parse_path(ocontext, oname,
1799                         workgroup, sizeof(workgroup),
1800                         server1, sizeof(server1),
1801                         share1, sizeof(share1),
1802                         path1, sizeof(path1),
1803                         user1, sizeof(user1),
1804                         password1, sizeof(password1),
1805                         NULL, 0);
1806
1807         if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1808
1809         smbc_parse_path(ncontext, nname,
1810                         NULL, 0,
1811                         server2, sizeof(server2),
1812                         share2, sizeof(share2),
1813                         path2, sizeof(path2),
1814                         user2, sizeof(user2),
1815                         password2, sizeof(password2),
1816                         NULL, 0);
1817
1818         if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1819
1820         if (strcmp(server1, server2) || strcmp(share1, share2) ||
1821             strcmp(user1, user2)) {
1822
1823                 /* Can't rename across file systems, or users?? */
1824
1825                 errno = EXDEV;
1826                 return -1;
1827
1828         }
1829
1830         srv = smbc_server(ocontext, True,
1831                           server1, share1, workgroup, user1, password1);
1832         if (!srv) {
1833
1834                 return -1;
1835
1836         }
1837
1838         /*d_printf(">>>rename: resolving %s\n", path1);*/
1839         if (!cli_resolve_path( "", srv->cli, path1, &targetcli1, targetpath1))
1840         {
1841                 d_printf("Could not resolve %s\n", path1);
1842                 return -1;
1843         }
1844         /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1845         /*d_printf(">>>rename: resolving %s\n", path2);*/
1846         if (!cli_resolve_path( "", srv->cli, path2, &targetcli2, targetpath2))
1847         {
1848                 d_printf("Could not resolve %s\n", path2);
1849                 return -1;
1850         }
1851         /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1852         
1853         if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1854             strcmp(targetcli1->share, targetcli2->share))
1855         {
1856                 /* can't rename across file systems */
1857                 
1858                 errno = EXDEV;
1859                 return -1;
1860         }
1861
1862         if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1863                 int eno = smbc_errno(ocontext, targetcli1);
1864
1865                 if (eno != EEXIST ||
1866                     !cli_unlink(targetcli1, targetpath2) ||
1867                     !cli_rename(targetcli1, targetpath1, targetpath2)) {
1868
1869                         errno = eno;
1870                         return -1;
1871
1872                 }
1873         }
1874
1875         return 0; /* Success */
1876
1877 }
1878
1879 /*
1880  * A routine to lseek() a file
1881  */
1882
1883 static off_t
1884 smbc_lseek_ctx(SMBCCTX *context,
1885                SMBCFILE *file,
1886                off_t offset,
1887                int whence)
1888 {
1889         SMB_OFF_T size;
1890         fstring server, share, user, password;
1891         pstring path, targetpath;
1892         struct cli_state *targetcli;
1893
1894         if (!context || !context->internal ||
1895             !context->internal->_initialized) {
1896
1897                 errno = EINVAL;
1898                 return -1;
1899                 
1900         }
1901
1902         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1903
1904                 errno = EBADF;
1905                 return -1;
1906
1907         }
1908
1909         if (!file->file) {
1910
1911                 errno = EINVAL;
1912                 return -1;      /* Can't lseek a dir ... */
1913
1914         }
1915
1916         switch (whence) {
1917         case SEEK_SET:
1918                 file->offset = offset;
1919                 break;
1920
1921         case SEEK_CUR:
1922                 file->offset += offset;
1923                 break;
1924
1925         case SEEK_END:
1926                 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1927                 if (smbc_parse_path(context, file->fname,
1928                                     NULL, 0,
1929                                     server, sizeof(server),
1930                                     share, sizeof(share),
1931                                     path, sizeof(path),
1932                                     user, sizeof(user),
1933                                     password, sizeof(password),
1934                                     NULL, 0)) {
1935                         
1936                                         errno = EINVAL;
1937                                         return -1;
1938                         }
1939                 
1940                 /*d_printf(">>>lseek: resolving %s\n", path);*/
1941                 if (!cli_resolve_path("", file->srv->cli, path,
1942                                       &targetcli, targetpath))
1943                 {
1944                         d_printf("Could not resolve %s\n", path);
1945                         return -1;
1946                 }
1947                 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1948                 
1949                 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1950                                    &size, NULL, NULL, NULL, NULL, NULL)) 
1951                 {
1952                     SMB_OFF_T b_size = size;
1953                         if (!cli_getattrE(targetcli, file->cli_fd,
1954                                           NULL, &b_size, NULL, NULL, NULL)) 
1955                     {
1956                         errno = EINVAL;
1957                         return -1;
1958                     } else
1959                         size = b_size;
1960                 }
1961                 file->offset = size + offset;
1962                 break;
1963
1964         default:
1965                 errno = EINVAL;
1966                 break;
1967
1968         }
1969
1970         return file->offset;
1971
1972 }
1973
1974 /* 
1975  * Generate an inode number from file name for those things that need it
1976  */
1977
1978 static ino_t
1979 smbc_inode(SMBCCTX *context,
1980            const char *name)
1981 {
1982
1983         if (!context || !context->internal ||
1984             !context->internal->_initialized) {
1985
1986                 errno = EINVAL;
1987                 return -1;
1988
1989         }
1990
1991         if (!*name) return 2; /* FIXME, why 2 ??? */
1992         return (ino_t)str_checksum(name);
1993
1994 }
1995
1996 /*
1997  * Routine to put basic stat info into a stat structure ... Used by stat and
1998  * fstat below.
1999  */
2000
2001 static int
2002 smbc_setup_stat(SMBCCTX *context,
2003                 struct stat *st,
2004                 char *fname,
2005                 SMB_OFF_T size,
2006                 int mode)
2007 {
2008         
2009         st->st_mode = 0;
2010
2011         if (IS_DOS_DIR(mode)) {
2012                 st->st_mode = SMBC_DIR_MODE;
2013         } else {
2014                 st->st_mode = SMBC_FILE_MODE;
2015         }
2016
2017         if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
2018         if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
2019         if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
2020         if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
2021
2022         st->st_size = size;
2023 #ifdef HAVE_STAT_ST_BLKSIZE
2024         st->st_blksize = 512;
2025 #endif
2026 #ifdef HAVE_STAT_ST_BLOCKS
2027         st->st_blocks = (size+511)/512;
2028 #endif
2029         st->st_uid = getuid();
2030         st->st_gid = getgid();
2031
2032         if (IS_DOS_DIR(mode)) {
2033                 st->st_nlink = 2;
2034         } else {
2035                 st->st_nlink = 1;
2036         }
2037
2038         if (st->st_ino == 0) {
2039                 st->st_ino = smbc_inode(context, fname);
2040         }
2041         
2042         return True;  /* FIXME: Is this needed ? */
2043
2044 }
2045
2046 /*
2047  * Routine to stat a file given a name
2048  */
2049
2050 static int
2051 smbc_stat_ctx(SMBCCTX *context,
2052               const char *fname,
2053               struct stat *st)
2054 {
2055         SMBCSRV *srv;
2056         fstring server;
2057         fstring share;
2058         fstring user;
2059         fstring password;
2060         fstring workgroup;
2061         pstring path;
2062         struct timespec write_time_ts;
2063         struct timespec access_time_ts;
2064         struct timespec change_time_ts;
2065         SMB_OFF_T size = 0;
2066         uint16 mode = 0;
2067         SMB_INO_T ino = 0;
2068
2069         if (!context || !context->internal ||
2070             !context->internal->_initialized) {
2071
2072                 errno = EINVAL;  /* Best I can think of ... */
2073                 return -1;
2074     
2075         }
2076
2077         if (!fname) {
2078
2079                 errno = EINVAL;
2080                 return -1;
2081
2082         }
2083   
2084         DEBUG(4, ("smbc_stat(%s)\n", fname));
2085
2086         if (smbc_parse_path(context, fname,
2087                             workgroup, sizeof(workgroup),
2088                             server, sizeof(server),
2089                             share, sizeof(share),
2090                             path, sizeof(path),
2091                             user, sizeof(user),
2092                             password, sizeof(password),
2093                             NULL, 0)) {
2094                 errno = EINVAL;
2095                 return -1;
2096         }
2097
2098         if (user[0] == (char)0) fstrcpy(user, context->user);
2099
2100         srv = smbc_server(context, True,
2101                           server, share, workgroup, user, password);
2102
2103         if (!srv) {
2104                 return -1;  /* errno set by smbc_server */
2105         }
2106
2107         if (!smbc_getatr(context, srv, path, &mode, &size, 
2108                          NULL,
2109                          &access_time_ts,
2110                          &write_time_ts,
2111                          &change_time_ts,
2112                          &ino)) {
2113
2114                 errno = smbc_errno(context, srv->cli);
2115                 return -1;
2116                 
2117         }
2118
2119         st->st_ino = ino;
2120
2121         smbc_setup_stat(context, st, path, size, mode);
2122
2123         set_atimespec(st, access_time_ts);
2124         set_ctimespec(st, change_time_ts);
2125         set_mtimespec(st, write_time_ts);
2126         st->st_dev   = srv->dev;
2127
2128         return 0;
2129
2130 }
2131
2132 /*
2133  * Routine to stat a file given an fd
2134  */
2135
2136 static int
2137 smbc_fstat_ctx(SMBCCTX *context,
2138                SMBCFILE *file,
2139                struct stat *st)
2140 {
2141         struct timespec change_time_ts;
2142         struct timespec access_time_ts;
2143         struct timespec write_time_ts;
2144         SMB_OFF_T size;
2145         uint16 mode;
2146         fstring server;
2147         fstring share;
2148         fstring user;
2149         fstring password;
2150         pstring path;
2151         pstring targetpath;
2152         struct cli_state *targetcli;
2153         SMB_INO_T ino = 0;
2154
2155         if (!context || !context->internal ||
2156             !context->internal->_initialized) {
2157
2158                 errno = EINVAL;
2159                 return -1;
2160
2161         }
2162
2163         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2164
2165                 errno = EBADF;
2166                 return -1;
2167
2168         }
2169
2170         if (!file->file) {
2171
2172                 return context->fstatdir(context, file, st);
2173
2174         }
2175
2176         /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2177         if (smbc_parse_path(context, file->fname,
2178                             NULL, 0,
2179                             server, sizeof(server),
2180                             share, sizeof(share),
2181                             path, sizeof(path),
2182                             user, sizeof(user),
2183                             password, sizeof(password),
2184                             NULL, 0)) {
2185                 errno = EINVAL;
2186                 return -1;
2187         }
2188         
2189         /*d_printf(">>>fstat: resolving %s\n", path);*/
2190         if (!cli_resolve_path("", file->srv->cli, path,
2191                               &targetcli, targetpath))
2192         {
2193                 d_printf("Could not resolve %s\n", path);
2194                 return -1;
2195         }
2196         /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2197
2198         if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2199                            NULL,
2200                            &access_time_ts,
2201                            &write_time_ts,
2202                            &change_time_ts,
2203                            &ino)) {
2204
2205                 time_t change_time, access_time, write_time;
2206
2207                 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2208                                 &change_time, &access_time, &write_time)) {
2209
2210                         errno = EINVAL;
2211                         return -1;
2212                 }
2213
2214                 change_time_ts = convert_time_t_to_timespec(change_time);
2215                 access_time_ts = convert_time_t_to_timespec(access_time);
2216                 write_time_ts = convert_time_t_to_timespec(write_time);
2217         }
2218
2219         st->st_ino = ino;
2220
2221         smbc_setup_stat(context, st, file->fname, size, mode);
2222
2223         set_atimespec(st, access_time_ts);
2224         set_ctimespec(st, change_time_ts);
2225         set_mtimespec(st, write_time_ts);
2226         st->st_dev = file->srv->dev;
2227
2228         return 0;
2229
2230 }
2231
2232 /*
2233  * Routine to open a directory
2234  * We accept the URL syntax explained in smbc_parse_path(), above.
2235  */
2236
2237 static void
2238 smbc_remove_dir(SMBCFILE *dir)
2239 {
2240         struct smbc_dir_list *d,*f;
2241
2242         d = dir->dir_list;
2243         while (d) {
2244
2245                 f = d; d = d->next;
2246
2247                 SAFE_FREE(f->dirent);
2248                 SAFE_FREE(f);
2249
2250         }
2251
2252         dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2253
2254 }
2255
2256 static int
2257 add_dirent(SMBCFILE *dir,
2258            const char *name,
2259            const char *comment,
2260            uint32 type)
2261 {
2262         struct smbc_dirent *dirent;
2263         int size;
2264         int name_length = (name == NULL ? 0 : strlen(name));
2265         int comment_len = (comment == NULL ? 0 : strlen(comment));
2266
2267         /*
2268          * Allocate space for the dirent, which must be increased by the 
2269          * size of the name and the comment and 1 each for the null terminator.
2270          */
2271
2272         size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2273     
2274         dirent = (struct smbc_dirent *)SMB_MALLOC(size);
2275
2276         if (!dirent) {
2277
2278                 dir->dir_error = ENOMEM;
2279                 return -1;
2280
2281         }
2282
2283         ZERO_STRUCTP(dirent);
2284
2285         if (dir->dir_list == NULL) {
2286
2287                 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2288                 if (!dir->dir_list) {
2289
2290                         SAFE_FREE(dirent);
2291                         dir->dir_error = ENOMEM;
2292                         return -1;
2293
2294                 }
2295                 ZERO_STRUCTP(dir->dir_list);
2296
2297                 dir->dir_end = dir->dir_next = dir->dir_list;
2298         }
2299         else {
2300
2301                 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2302                 
2303                 if (!dir->dir_end->next) {
2304                         
2305                         SAFE_FREE(dirent);
2306                         dir->dir_error = ENOMEM;
2307                         return -1;
2308
2309                 }
2310                 ZERO_STRUCTP(dir->dir_end->next);
2311
2312                 dir->dir_end = dir->dir_end->next;
2313         }
2314
2315         dir->dir_end->next = NULL;
2316         dir->dir_end->dirent = dirent;
2317         
2318         dirent->smbc_type = type;
2319         dirent->namelen = name_length;
2320         dirent->commentlen = comment_len;
2321         dirent->dirlen = size;
2322   
2323         /*
2324          * dirent->namelen + 1 includes the null (no null termination needed)
2325          * Ditto for dirent->commentlen.
2326          * The space for the two null bytes was allocated.
2327          */
2328         strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2329         dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2330         strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2331         
2332         return 0;
2333
2334 }
2335
2336 static void
2337 list_unique_wg_fn(const char *name,
2338                   uint32 type,
2339                   const char *comment,
2340                   void *state)
2341 {
2342         SMBCFILE *dir = (SMBCFILE *)state;
2343         struct smbc_dir_list *dir_list;
2344         struct smbc_dirent *dirent;
2345         int dirent_type;
2346         int do_remove = 0;
2347
2348         dirent_type = dir->dir_type;
2349
2350         if (add_dirent(dir, name, comment, dirent_type) < 0) {
2351
2352                 /* An error occurred, what do we do? */
2353                 /* FIXME: Add some code here */
2354         }
2355
2356         /* Point to the one just added */
2357         dirent = dir->dir_end->dirent;
2358
2359         /* See if this was a duplicate */
2360         for (dir_list = dir->dir_list;
2361              dir_list != dir->dir_end;
2362              dir_list = dir_list->next) {
2363                 if (! do_remove &&
2364                     strcmp(dir_list->dirent->name, dirent->name) == 0) {
2365                         /* Duplicate.  End end of list need to be removed. */
2366                         do_remove = 1;
2367                 }
2368
2369                 if (do_remove && dir_list->next == dir->dir_end) {
2370                         /* Found the end of the list.  Remove it. */
2371                         dir->dir_end = dir_list;
2372                         free(dir_list->next);
2373                         free(dirent);
2374                         dir_list->next = NULL;
2375                         break;
2376                 }
2377         }
2378 }
2379
2380 static void
2381 list_fn(const char *name,
2382         uint32 type,
2383         const char *comment,
2384         void *state)
2385 {
2386         SMBCFILE *dir = (SMBCFILE *)state;
2387         int dirent_type;
2388
2389         /*
2390          * We need to process the type a little ...
2391          *
2392          * Disk share     = 0x00000000
2393          * Print share    = 0x00000001
2394          * Comms share    = 0x00000002 (obsolete?)
2395          * IPC$ share     = 0x00000003 
2396          *
2397          * administrative shares:
2398          * ADMIN$, IPC$, C$, D$, E$ ...  are type |= 0x80000000
2399          */
2400         
2401         if (dir->dir_type == SMBC_FILE_SHARE) {
2402                 
2403                 switch (type) {
2404                 case 0 | 0x80000000:
2405                 case 0:
2406                         dirent_type = SMBC_FILE_SHARE;
2407                         break;
2408
2409                 case 1:
2410                         dirent_type = SMBC_PRINTER_SHARE;
2411                         break;
2412
2413                 case 2:
2414                         dirent_type = SMBC_COMMS_SHARE;
2415                         break;
2416
2417                 case 3 | 0x80000000:
2418                 case 3:
2419                         dirent_type = SMBC_IPC_SHARE;
2420                         break;
2421
2422                 default:
2423                         dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2424                         break;
2425                 }
2426         }
2427         else {
2428                 dirent_type = dir->dir_type;
2429         }
2430
2431         if (add_dirent(dir, name, comment, dirent_type) < 0) {
2432
2433                 /* An error occurred, what do we do? */
2434                 /* FIXME: Add some code here */
2435
2436         }
2437 }
2438
2439 static void
2440 dir_list_fn(const char *mnt,
2441             file_info *finfo,
2442             const char *mask,
2443             void *state)
2444 {
2445
2446         if (add_dirent((SMBCFILE *)state, finfo->name, "", 
2447                        (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2448
2449                 /* Handle an error ... */
2450
2451                 /* FIXME: Add some code ... */
2452
2453         } 
2454
2455 }
2456
2457 static int
2458 net_share_enum_rpc(struct cli_state *cli,
2459                    void (*fn)(const char *name,
2460                               uint32 type,
2461                               const char *comment,
2462                               void *state),
2463                    void *state)
2464 {
2465         int i;
2466         WERROR result;
2467         ENUM_HND enum_hnd;
2468         uint32 info_level = 1;
2469         uint32 preferred_len = 0xffffffff;
2470         uint32 type;
2471         SRV_SHARE_INFO_CTR ctr;
2472         fstring name = "";
2473         fstring comment = "";
2474         void *mem_ctx;
2475         struct rpc_pipe_client *pipe_hnd;
2476         NTSTATUS nt_status;
2477
2478         /* Open the server service pipe */
2479         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2480         if (!pipe_hnd) {
2481                 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2482                 return -1;
2483         }
2484
2485         /* Allocate a context for parsing and for the entries in "ctr" */
2486         mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2487         if (mem_ctx == NULL) {
2488                 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2489                 cli_rpc_pipe_close(pipe_hnd);
2490                 return -1; 
2491         }
2492
2493         /* Issue the NetShareEnum RPC call and retrieve the response */
2494         init_enum_hnd(&enum_hnd, 0);
2495         result = rpccli_srvsvc_net_share_enum(pipe_hnd,
2496                                               mem_ctx,
2497                                               info_level,
2498                                               &ctr,
2499                                               preferred_len,
2500                                               &enum_hnd);
2501
2502         /* Was it successful? */
2503         if (!W_ERROR_IS_OK(result) || ctr.num_entries == 0) {
2504                 /*  Nope.  Go clean up. */
2505                 goto done;
2506         }
2507
2508         /* For each returned entry... */
2509         for (i = 0; i < ctr.num_entries; i++) {
2510
2511                 /* pull out the share name */
2512                 rpcstr_pull_unistr2_fstring(
2513                         name, &ctr.share.info1[i].info_1_str.uni_netname);
2514
2515                 /* pull out the share's comment */
2516                 rpcstr_pull_unistr2_fstring(
2517                         comment, &ctr.share.info1[i].info_1_str.uni_remark);
2518
2519                 /* Get the type value */
2520                 type = ctr.share.info1[i].info_1.type;
2521
2522                 /* Add this share to the list */
2523                 (*fn)(name, type, comment, state);
2524         }
2525
2526 done:
2527         /* Close the server service pipe */
2528         cli_rpc_pipe_close(pipe_hnd);
2529
2530         /* Free all memory which was allocated for this request */
2531         TALLOC_FREE(mem_ctx);
2532
2533         /* Tell 'em if it worked */
2534         return W_ERROR_IS_OK(result) ? 0 : -1;
2535 }
2536
2537
2538
2539 static SMBCFILE *
2540 smbc_opendir_ctx(SMBCCTX *context,
2541                  const char *fname)
2542 {
2543         fstring server, share, user, password, options;
2544         pstring workgroup;
2545         pstring path;
2546         uint16 mode;
2547         char *p;
2548         SMBCSRV *srv  = NULL;
2549         SMBCFILE *dir = NULL;
2550         struct in_addr rem_ip;
2551
2552         if (!context || !context->internal ||
2553             !context->internal->_initialized) {
2554                 DEBUG(4, ("no valid context\n"));
2555                 errno = EINVAL + 8192;
2556                 return NULL;
2557
2558         }
2559
2560         if (!fname) {
2561                 DEBUG(4, ("no valid fname\n"));
2562                 errno = EINVAL + 8193;
2563                 return NULL;
2564         }
2565
2566         if (smbc_parse_path(context, fname,
2567                             workgroup, sizeof(workgroup),
2568                             server, sizeof(server),
2569                             share, sizeof(share),
2570                             path, sizeof(path),
2571                             user, sizeof(user),
2572                             password, sizeof(password),
2573                             options, sizeof(options))) {
2574                 DEBUG(4, ("no valid path\n"));
2575                 errno = EINVAL + 8194;
2576                 return NULL;
2577         }
2578
2579         DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2580                   "path='%s' options='%s'\n",
2581                   fname, server, share, path, options));
2582
2583         /* Ensure the options are valid */
2584         if (smbc_check_options(server, share, path, options)) {
2585                 DEBUG(4, ("unacceptable options (%s)\n", options));
2586                 errno = EINVAL + 8195;
2587                 return NULL;
2588         }
2589
2590         if (user[0] == (char)0) fstrcpy(user, context->user);
2591
2592         dir = SMB_MALLOC_P(SMBCFILE);
2593
2594         if (!dir) {
2595
2596                 errno = ENOMEM;
2597                 return NULL;
2598
2599         }
2600
2601         ZERO_STRUCTP(dir);
2602
2603         dir->cli_fd   = 0;
2604         dir->fname    = SMB_STRDUP(fname);
2605         dir->srv      = NULL;
2606         dir->offset   = 0;
2607         dir->file     = False;
2608         dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2609
2610         if (server[0] == (char)0) {
2611
2612                 int i;
2613                 int count;
2614                 int max_lmb_count;
2615                 struct ip_service *ip_list;
2616                 struct ip_service server_addr;
2617                 struct user_auth_info u_info;
2618                 struct cli_state *cli;
2619
2620                 if (share[0] != (char)0 || path[0] != (char)0) {
2621
2622                         errno = EINVAL + 8196;
2623                         if (dir) {
2624                                 SAFE_FREE(dir->fname);
2625                                 SAFE_FREE(dir);
2626                         }
2627                         return NULL;
2628                 }
2629
2630                 /* Determine how many local master browsers to query */
2631                 max_lmb_count = (context->options.browse_max_lmb_count == 0
2632                                  ? INT_MAX
2633                                  : context->options.browse_max_lmb_count);
2634
2635                 pstrcpy(u_info.username, user);
2636                 pstrcpy(u_info.password, password);
2637
2638                 /*
2639                  * We have server and share and path empty but options
2640                  * requesting that we scan all master browsers for their list
2641                  * of workgroups/domains.  This implies that we must first try
2642                  * broadcast queries to find all master browsers, and if that
2643                  * doesn't work, then try our other methods which return only
2644                  * a single master browser.
2645                  */
2646
2647                 ip_list = NULL;
2648                 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2649
2650                         SAFE_FREE(ip_list);
2651
2652                         if (!find_master_ip(workgroup, &server_addr.ip)) {
2653
2654                                 if (dir) {
2655                                         SAFE_FREE(dir->fname);
2656                                         SAFE_FREE(dir);
2657                                 }
2658                                 errno = ENOENT;
2659                                 return NULL;
2660                         }
2661
2662                         ip_list = &server_addr;
2663                         count = 1;
2664                 }
2665
2666                 for (i = 0; i < count && i < max_lmb_count; i++) {
2667                         DEBUG(99, ("Found master browser %d of %d: %s\n",
2668                                    i+1, MAX(count, max_lmb_count),
2669                                    inet_ntoa(ip_list[i].ip)));
2670                         
2671                         cli = get_ipc_connect_master_ip(&ip_list[i],
2672                                                         workgroup, &u_info);
2673                         /* cli == NULL is the master browser refused to talk or 
2674                            could not be found */
2675                         if ( !cli )
2676                                 continue;
2677
2678                         fstrcpy(server, cli->desthost);
2679                         cli_shutdown(cli);
2680
2681                         DEBUG(4, ("using workgroup %s %s\n",
2682                                   workgroup, server));
2683
2684                         /*
2685                          * For each returned master browser IP address, get a
2686                          * connection to IPC$ on the server if we do not
2687                          * already have one, and determine the
2688                          * workgroups/domains that it knows about.
2689                          */
2690                 
2691                         srv = smbc_server(context, True, server, "IPC$",
2692                                           workgroup, user, password);
2693                         if (!srv) {
2694                                 continue;
2695                         }
2696                 
2697                         dir->srv = srv;
2698                         dir->dir_type = SMBC_WORKGROUP;
2699
2700                         /* Now, list the stuff ... */
2701                         
2702                         if (!cli_NetServerEnum(srv->cli,
2703                                                workgroup,
2704                                                SV_TYPE_DOMAIN_ENUM,
2705                                                list_unique_wg_fn,
2706                                                (void *)dir)) {
2707                                 continue;
2708                         }
2709                 }
2710
2711                 SAFE_FREE(ip_list);
2712         } else { 
2713                 /*
2714                  * Server not an empty string ... Check the rest and see what
2715                  * gives
2716                  */
2717                 if (*share == '\0') {
2718                         if (*path != '\0') {
2719
2720                                 /* Should not have empty share with path */
2721                                 errno = EINVAL + 8197;
2722                                 if (dir) {
2723                                         SAFE_FREE(dir->fname);
2724                                         SAFE_FREE(dir);
2725                                 }
2726                                 return NULL;
2727         
2728                         }
2729
2730                         /*
2731                          * We don't know if <server> is really a server name
2732                          * or is a workgroup/domain name.  If we already have
2733                          * a server structure for it, we'll use it.
2734                          * Otherwise, check to see if <server><1D>,
2735                          * <server><1B>, or <server><20> translates.  We check
2736                          * to see if <server> is an IP address first.
2737                          */
2738
2739                         /*
2740                          * See if we have an existing server.  Do not
2741                          * establish a connection if one does not already
2742                          * exist.
2743                          */
2744                         srv = smbc_server(context, False, server, "IPC$",
2745                                           workgroup, user, password);
2746
2747                         /*
2748                          * If no existing server and not an IP addr, look for
2749                          * LMB or DMB
2750                          */
2751                         if (!srv &&
2752                             !is_ipaddress(server) &&
2753                             (resolve_name(server, &rem_ip, 0x1d) ||   /* LMB */
2754                              resolve_name(server, &rem_ip, 0x1b) )) { /* DMB */
2755
2756                                 fstring buserver;
2757
2758                                 dir->dir_type = SMBC_SERVER;
2759
2760                                 /*
2761                                  * Get the backup list ...
2762                                  */
2763                                 if (!name_status_find(server, 0, 0,
2764                                                       rem_ip, buserver)) {
2765
2766                                         DEBUG(0, ("Could not get name of "
2767                                                   "local/domain master browser "
2768                                                   "for server %s\n", server));
2769                                         if (dir) {
2770                                                 SAFE_FREE(dir->fname);
2771                                                 SAFE_FREE(dir);
2772                                         }
2773                                         errno = EPERM;
2774                                         return NULL;
2775
2776                                 }
2777
2778                                 /*
2779                                  * Get a connection to IPC$ on the server if
2780                                  * we do not already have one
2781                                  */
2782                                 srv = smbc_server(context, True,
2783                                                   buserver, "IPC$",
2784                                                   workgroup, user, password);
2785                                 if (!srv) {
2786                                         DEBUG(0, ("got no contact to IPC$\n"));
2787                                         if (dir) {
2788                                                 SAFE_FREE(dir->fname);
2789                                                 SAFE_FREE(dir);
2790                                         }
2791                                         return NULL;
2792
2793                                 }
2794
2795                                 dir->srv = srv;
2796
2797                                 /* Now, list the servers ... */
2798                                 if (!cli_NetServerEnum(srv->cli, server,
2799                                                        0x0000FFFE, list_fn,
2800                                                        (void *)dir)) {
2801
2802                                         if (dir) {
2803                                                 SAFE_FREE(dir->fname);
2804                                                 SAFE_FREE(dir);
2805                                         }
2806                                         return NULL;
2807                                 }
2808                         } else if (srv ||
2809                                    (resolve_name(server, &rem_ip, 0x20))) {
2810                                 
2811                                 /* If we hadn't found the server, get one now */
2812                                 if (!srv) {
2813                                         srv = smbc_server(context, True,
2814                                                           server, "IPC$",
2815                                                           workgroup,
2816                                                           user, password);
2817                                 }
2818
2819                                 if (!srv) {
2820                                         if (dir) {
2821                                                 SAFE_FREE(dir->fname);
2822                                                 SAFE_FREE(dir);
2823                                         }
2824                                         return NULL;
2825
2826                                 }
2827
2828                                 dir->dir_type = SMBC_FILE_SHARE;
2829                                 dir->srv = srv;
2830
2831                                 /* List the shares ... */
2832
2833                                 if (net_share_enum_rpc(
2834                                             srv->cli,
2835                                             list_fn,
2836                                             (void *) dir) < 0 &&
2837                                     cli_RNetShareEnum(
2838                                             srv->cli,
2839                                             list_fn, 
2840                                             (void *)dir) < 0) {
2841                                                 
2842                                         errno = cli_errno(srv->cli);
2843                                         if (dir) {
2844                                                 SAFE_FREE(dir->fname);
2845                                                 SAFE_FREE(dir);
2846                                         }
2847                                         return NULL;
2848
2849                                 }
2850                         } else {
2851                                 /* Neither the workgroup nor server exists */
2852                                 errno = ECONNREFUSED;   
2853                                 if (dir) {
2854                                         SAFE_FREE(dir->fname);
2855                                         SAFE_FREE(dir);
2856                                 }
2857                                 return NULL;
2858                         }
2859
2860                 }
2861                 else {
2862                         /*
2863                          * The server and share are specified ... work from
2864                          * there ...
2865                          */
2866                         pstring targetpath;
2867                         struct cli_state *targetcli;
2868
2869                         /* We connect to the server and list the directory */
2870                         dir->dir_type = SMBC_FILE_SHARE;
2871
2872                         srv = smbc_server(context, True, server, share,
2873                                           workgroup, user, password);
2874
2875                         if (!srv) {
2876
2877                                 if (dir) {
2878                                         SAFE_FREE(dir->fname);
2879                                         SAFE_FREE(dir);
2880                                 }
2881                                 return NULL;
2882
2883                         }
2884
2885                         dir->srv = srv;
2886
2887                         /* Now, list the files ... */
2888
2889                         p = path + strlen(path);
2890                         pstrcat(path, "\\*");
2891
2892                         if (!cli_resolve_path("", srv->cli, path,
2893                                               &targetcli, targetpath))
2894                         {
2895                                 d_printf("Could not resolve %s\n", path);
2896                                 if (dir) {
2897                                         SAFE_FREE(dir->fname);
2898                                         SAFE_FREE(dir);
2899                                 }
2900                                 return NULL;
2901                         }
2902                         
2903                         if (cli_list(targetcli, targetpath,
2904                                      aDIR | aSYSTEM | aHIDDEN,
2905                                      dir_list_fn, (void *)dir) < 0) {
2906
2907                                 if (dir) {
2908                                         SAFE_FREE(dir->fname);
2909                                         SAFE_FREE(dir);
2910                                 }
2911                                 errno = smbc_errno(context, targetcli);
2912
2913                                 if (errno == EINVAL) {
2914                                     /*
2915                                      * See if they asked to opendir something
2916                                      * other than a directory.  If so, the
2917                                      * converted error value we got would have
2918                                      * been EINVAL rather than ENOTDIR.
2919                                      */
2920                                     *p = '\0'; /* restore original path */
2921
2922                                     if (smbc_getatr(context, srv, path,
2923                                                     &mode, NULL,
2924                                                     NULL, NULL, NULL, NULL,
2925                                                     NULL) &&
2926                                         ! IS_DOS_DIR(mode)) {
2927
2928                                         /* It is.  Correct the error value */
2929                                         errno = ENOTDIR;
2930                                     }
2931                                 }
2932
2933                                 return NULL;
2934
2935                         }
2936                 }
2937
2938         }
2939
2940         DLIST_ADD(context->internal->_files, dir);
2941         return dir;
2942
2943 }
2944
2945 /*
2946  * Routine to close a directory
2947  */
2948
2949 static int
2950 smbc_closedir_ctx(SMBCCTX *context,
2951                   SMBCFILE *dir)
2952 {
2953
2954         if (!context || !context->internal ||
2955             !context->internal->_initialized) {
2956
2957                 errno = EINVAL;
2958                 return -1;
2959
2960         }
2961
2962         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2963
2964                 errno = EBADF;
2965                 return -1;
2966     
2967         }
2968
2969         smbc_remove_dir(dir); /* Clean it up */
2970
2971         DLIST_REMOVE(context->internal->_files, dir);
2972
2973         if (dir) {
2974
2975                 SAFE_FREE(dir->fname);
2976                 SAFE_FREE(dir);    /* Free the space too */
2977         }
2978
2979         return 0;
2980
2981 }
2982
2983 static void
2984 smbc_readdir_internal(SMBCCTX * context,
2985                       struct smbc_dirent *dest,
2986                       struct smbc_dirent *src,
2987                       int max_namebuf_len)
2988 {
2989         if (context->options.urlencode_readdir_entries) {
2990
2991                 /* url-encode the name.  get back remaining buffer space */
2992                 max_namebuf_len =
2993                         smbc_urlencode(dest->name, src->name, max_namebuf_len);
2994
2995                 /* We now know the name length */
2996                 dest->namelen = strlen(dest->name);
2997
2998                 /* Save the pointer to the beginning of the comment */
2999                 dest->comment = dest->name + dest->namelen + 1;
3000
3001                 /* Copy the comment */
3002                 strncpy(dest->comment, src->comment, max_namebuf_len - 1);
3003                 dest->comment[max_namebuf_len - 1] = '\0';
3004
3005                 /* Save other fields */
3006                 dest->smbc_type = src->smbc_type;
3007                 dest->commentlen = strlen(dest->comment);
3008                 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
3009                                 (char *) dest);
3010         } else {
3011
3012                 /* No encoding.  Just copy the entry as is. */
3013                 memcpy(dest, src, src->dirlen);
3014                 dest->comment = (char *)(&dest->name + src->namelen + 1);
3015         }
3016         
3017 }
3018
3019 /*
3020  * Routine to get a directory entry
3021  */
3022
3023 struct smbc_dirent *
3024 smbc_readdir_ctx(SMBCCTX *context,
3025                  SMBCFILE *dir)
3026 {
3027         int maxlen;
3028         struct smbc_dirent *dirp, *dirent;
3029
3030         /* Check that all is ok first ... */
3031
3032         if (!context || !context->internal ||
3033             !context->internal->_initialized) {
3034
3035                 errno = EINVAL;
3036                 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
3037                 return NULL;
3038
3039         }
3040
3041         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3042
3043                 errno = EBADF;
3044                 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
3045                 return NULL;
3046
3047         }
3048
3049         if (dir->file != False) { /* FIXME, should be dir, perhaps */
3050
3051                 errno = ENOTDIR;
3052                 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
3053                 return NULL;
3054
3055         }
3056
3057         if (!dir->dir_next) {
3058                 return NULL;
3059         }
3060
3061         dirent = dir->dir_next->dirent;
3062         if (!dirent) {
3063
3064                 errno = ENOENT;
3065                 return NULL;
3066
3067         }
3068
3069         dirp = (struct smbc_dirent *)context->internal->_dirent;
3070         maxlen = (sizeof(context->internal->_dirent) -
3071                   sizeof(struct smbc_dirent));
3072
3073         smbc_readdir_internal(context, dirp, dirent, maxlen);
3074
3075         dir->dir_next = dir->dir_next->next;
3076
3077         return dirp;
3078 }
3079
3080 /*
3081  * Routine to get directory entries
3082  */
3083
3084 static int
3085 smbc_getdents_ctx(SMBCCTX *context,
3086                   SMBCFILE *dir,
3087                   struct smbc_dirent *dirp,
3088                   int count)
3089 {
3090         int rem = count;
3091         int reqd;
3092         int maxlen;
3093         char *ndir = (char *)dirp;
3094         struct smbc_dir_list *dirlist;
3095
3096         /* Check that all is ok first ... */
3097
3098         if (!context || !context->internal ||
3099             !context->internal->_initialized) {
3100
3101                 errno = EINVAL;
3102                 return -1;
3103
3104         }
3105
3106         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3107
3108                 errno = EBADF;
3109                 return -1;
3110     
3111         }
3112
3113         if (dir->file != False) { /* FIXME, should be dir, perhaps */
3114
3115                 errno = ENOTDIR;
3116                 return -1;
3117
3118         }
3119
3120         /* 
3121          * Now, retrieve the number of entries that will fit in what was passed
3122          * We have to figure out if the info is in the list, or we need to 
3123          * send a request to the server to get the info.
3124          */
3125
3126         while ((dirlist = dir->dir_next)) {
3127                 struct smbc_dirent *dirent;
3128
3129                 if (!dirlist->dirent) {
3130
3131                         errno = ENOENT;  /* Bad error */
3132                         return -1;
3133
3134                 }
3135
3136                 /* Do urlencoding of next entry, if so selected */
3137                 dirent = (struct smbc_dirent *)context->internal->_dirent;
3138                 maxlen = (sizeof(context->internal->_dirent) -
3139                           sizeof(struct smbc_dirent));
3140                 smbc_readdir_internal(context, dirent, dirlist->dirent, maxlen);
3141
3142                 reqd = dirent->dirlen;
3143
3144                 if (rem < reqd) {
3145
3146                         if (rem < count) { /* We managed to copy something */
3147
3148                                 errno = 0;
3149                                 return count - rem;
3150
3151                         }
3152                         else { /* Nothing copied ... */
3153
3154                                 errno = EINVAL;  /* Not enough space ... */
3155                                 return -1;
3156
3157                         }
3158
3159                 }
3160
3161                 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
3162     
3163                 ((struct smbc_dirent *)ndir)->comment = 
3164                         (char *)(&((struct smbc_dirent *)ndir)->name +
3165                                  dirent->namelen +
3166                                  1);
3167
3168                 ndir += reqd;
3169
3170                 rem -= reqd;
3171
3172                 dir->dir_next = dirlist = dirlist -> next;
3173         }
3174
3175         if (rem == count)
3176                 return 0;
3177         else 
3178                 return count - rem;
3179
3180 }
3181
3182 /*
3183  * Routine to create a directory ...
3184  */
3185
3186 static int
3187 smbc_mkdir_ctx(SMBCCTX *context,
3188                const char *fname,
3189                mode_t mode)
3190 {
3191         SMBCSRV *srv;
3192         fstring server;
3193         fstring share;
3194         fstring user;
3195         fstring password;
3196         fstring workgroup;
3197         pstring path, targetpath;
3198         struct cli_state *targetcli;
3199
3200         if (!context || !context->internal || 
3201             !context->internal->_initialized) {
3202
3203                 errno = EINVAL;
3204                 return -1;
3205
3206         }
3207
3208         if (!fname) {
3209
3210                 errno = EINVAL;
3211                 return -1;
3212
3213         }
3214   
3215         DEBUG(4, ("smbc_mkdir(%s)\n", fname));
3216
3217         if (smbc_parse_path(context, fname,
3218                             workgroup, sizeof(workgroup),
3219                             server, sizeof(server),
3220                             share, sizeof(share),
3221                             path, sizeof(path),
3222                             user, sizeof(user),
3223                             password, sizeof(password),
3224                             NULL, 0)) {
3225                 errno = EINVAL;
3226                 return -1;
3227         }
3228
3229         if (user[0] == (char)0) fstrcpy(user, context->user);
3230
3231         srv = smbc_server(context, True,
3232                           server, share, workgroup, user, password);
3233
3234         if (!srv) {
3235
3236                 return -1;  /* errno set by smbc_server */
3237
3238         }
3239
3240         /*d_printf(">>>mkdir: resolving %s\n", path);*/
3241         if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
3242         {
3243                 d_printf("Could not resolve %s\n", path);
3244                 return -1;
3245         }
3246         /*d_printf(">>>mkdir: resolved path as %s\n", targetpath);*/
3247
3248         if (!cli_mkdir(targetcli, targetpath)) {
3249
3250                 errno = smbc_errno(context, targetcli);
3251                 return -1;
3252
3253         } 
3254
3255         return 0;
3256
3257 }
3258
3259 /*
3260  * Our list function simply checks to see if a directory is not empty
3261  */
3262
3263 static int smbc_rmdir_dirempty = True;
3264
3265 static void
3266 rmdir_list_fn(const char *mnt,
3267               file_info *finfo,
3268               const char *mask,
3269               void *state)
3270 {
3271         if (strncmp(finfo->name, ".", 1) != 0 &&
3272             strncmp(finfo->name, "..", 2) != 0) {
3273                 
3274                 smbc_rmdir_dirempty = False;
3275         }
3276 }
3277
3278 /*
3279  * Routine to remove a directory
3280  */
3281
3282 static int
3283 smbc_rmdir_ctx(SMBCCTX *context,
3284                const char *fname)
3285 {
3286         SMBCSRV *srv;
3287         fstring server;
3288         fstring share;
3289         fstring user;
3290         fstring password;
3291         fstring workgroup;
3292         pstring path;
3293         pstring targetpath;
3294         struct cli_state *targetcli;
3295
3296         if (!context || !context->internal || 
3297             !context->internal->_initialized) {
3298
3299                 errno = EINVAL;
3300                 return -1;
3301
3302         }
3303
3304         if (!fname) {
3305
3306                 errno = EINVAL;
3307                 return -1;
3308
3309         }
3310   
3311         DEBUG(4, ("smbc_rmdir(%s)\n", fname));
3312
3313         if (smbc_parse_path(context, fname,
3314                             workgroup, sizeof(workgroup),
3315                             server, sizeof(server),
3316                             share, sizeof(share),
3317                             path, sizeof(path),
3318                             user, sizeof(user),
3319                             password, sizeof(password),
3320                             NULL, 0))
3321         {
3322                 errno = EINVAL;
3323                 return -1;
3324         }
3325
3326         if (user[0] == (char)0) fstrcpy(user, context->user);
3327
3328         srv = smbc_server(context, True,
3329                           server, share, workgroup, user, password);
3330
3331         if (!srv) {
3332
3333                 return -1;  /* errno set by smbc_server */
3334
3335         }
3336
3337         /*d_printf(">>>rmdir: resolving %s\n", path);*/
3338         if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
3339         {
3340                 d_printf("Could not resolve %s\n", path);
3341                 return -1;
3342         }
3343         /*d_printf(">>>rmdir: resolved path as %s\n", targetpath);*/
3344
3345
3346         if (!cli_rmdir(targetcli, targetpath)) {
3347
3348                 errno = smbc_errno(context, targetcli);
3349
3350                 if (errno == EACCES) {  /* Check if the dir empty or not */
3351
3352                         /* Local storage to avoid buffer overflows */
3353                         pstring lpath; 
3354
3355                         smbc_rmdir_dirempty = True;  /* Make this so ... */
3356
3357                         pstrcpy(lpath, targetpath);
3358                         pstrcat(lpath, "\\*");
3359
3360                         if (cli_list(targetcli, lpath,
3361                                      aDIR | aSYSTEM | aHIDDEN,
3362                                      rmdir_list_fn, NULL) < 0) {
3363
3364                                 /* Fix errno to ignore latest error ... */
3365                                 DEBUG(5, ("smbc_rmdir: "
3366                                           "cli_list returned an error: %d\n", 
3367                                           smbc_errno(context, targetcli)));
3368                                 errno = EACCES;
3369
3370                         }
3371
3372                         if (smbc_rmdir_dirempty)
3373                                 errno = EACCES;
3374                         else
3375                                 errno = ENOTEMPTY;
3376
3377                 }
3378
3379                 return -1;
3380
3381         } 
3382
3383         return 0;
3384
3385 }
3386
3387 /*
3388  * Routine to return the current directory position
3389  */
3390
3391 static off_t
3392 smbc_telldir_ctx(SMBCCTX *context,
3393                  SMBCFILE *dir)
3394 {
3395         off_t ret_val; /* Squash warnings about cast */
3396
3397         if (!context || !context->internal ||
3398             !context->internal->_initialized) {
3399
3400                 errno = EINVAL;
3401                 return -1;
3402
3403         }
3404
3405         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3406
3407                 errno = EBADF;
3408                 return -1;
3409
3410         }
3411
3412         if (dir->file != False) { /* FIXME, should be dir, perhaps */
3413
3414                 errno = ENOTDIR;
3415                 return -1;
3416
3417         }
3418
3419         /*
3420          * We return the pointer here as the offset
3421          */
3422         ret_val = (off_t)(long)dir->dir_next;
3423         return ret_val;
3424
3425 }
3426
3427 /*
3428  * A routine to run down the list and see if the entry is OK
3429  */
3430
3431 struct smbc_dir_list *
3432 smbc_check_dir_ent(struct smbc_dir_list *list, 
3433                    struct smbc_dirent *dirent)
3434 {
3435
3436         /* Run down the list looking for what we want */
3437
3438         if (dirent) {
3439
3440                 struct smbc_dir_list *tmp = list;
3441
3442                 while (tmp) {
3443
3444                         if (tmp->dirent == dirent)
3445                                 return tmp;
3446
3447                         tmp = tmp->next;
3448
3449                 }
3450
3451         }
3452
3453         return NULL;  /* Not found, or an error */
3454
3455 }
3456
3457
3458 /*
3459  * Routine to seek on a directory
3460  */
3461
3462 static int
3463 smbc_lseekdir_ctx(SMBCCTX *context,
3464                   SMBCFILE *dir,
3465                   off_t offset)
3466 {
3467         long int l_offset = offset;  /* Handle problems of size */
3468         struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
3469         struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
3470
3471         if (!context || !context->internal ||
3472             !context->internal->_initialized) {
3473
3474                 errno = EINVAL;
3475                 return -1;
3476
3477         }
3478
3479         if (dir->file != False) { /* FIXME, should be dir, perhaps */
3480
3481                 errno = ENOTDIR;
3482                 return -1;
3483
3484         }
3485
3486         /* Now, check what we were passed and see if it is OK ... */
3487
3488         if (dirent == NULL) {  /* Seek to the begining of the list */
3489
3490                 dir->dir_next = dir->dir_list;
3491                 return 0;
3492
3493         }
3494
3495         /* Now, run down the list and make sure that the entry is OK       */
3496         /* This may need to be changed if we change the format of the list */
3497
3498         if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
3499
3500                 errno = EINVAL;   /* Bad entry */
3501                 return -1;
3502
3503         }
3504
3505         dir->dir_next = list_ent;
3506
3507         return 0; 
3508
3509 }
3510
3511 /*
3512  * Routine to fstat a dir
3513  */
3514
3515 static int
3516 smbc_fstatdir_ctx(SMBCCTX *context,
3517                   SMBCFILE *dir,
3518                   struct stat *st)
3519 {
3520
3521         if (!context || !context->internal || 
3522             !context->internal->_initialized) {
3523
3524                 errno = EINVAL;
3525                 return -1;
3526
3527         }
3528
3529         /* No code yet ... */
3530
3531         return 0;
3532
3533 }
3534
3535 static int
3536 smbc_chmod_ctx(SMBCCTX *context,
3537                const char *fname,
3538                mode_t newmode)
3539 {
3540         SMBCSRV *srv;
3541         fstring server;
3542         fstring share;
3543         fstring user;
3544         fstring password;
3545         fstring workgroup;
3546         pstring path;
3547         uint16 mode;
3548
3549         if (!context || !context->internal ||
3550             !context->internal->_initialized) {
3551
3552                 errno = EINVAL;  /* Best I can think of ... */
3553                 return -1;
3554     
3555         }
3556
3557         if (!fname) {
3558
3559                 errno = EINVAL;
3560                 return -1;
3561
3562         }
3563   
3564         DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
3565
3566         if (smbc_parse_path(context, fname,
3567                             workgroup, sizeof(workgroup),
3568                             server, sizeof(server),
3569                             share, sizeof(share),
3570                             path, sizeof(path),
3571                             user, sizeof(user),
3572                             password, sizeof(password),
3573                             NULL, 0)) {
3574                 errno = EINVAL;
3575                 return -1;
3576         }
3577
3578         if (user[0] == (char)0) fstrcpy(user, context->user);
3579
3580         srv = smbc_server(context, True,
3581                           server, share, workgroup, user, password);
3582
3583         if (!srv) {
3584                 return -1;  /* errno set by smbc_server */
3585         }
3586
3587         mode = 0;
3588
3589         if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
3590         if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
3591         if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
3592         if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
3593
3594         if (!cli_setatr(srv->cli, path, mode, 0)) {
3595                 errno = smbc_errno(context, srv->cli);
3596                 return -1;
3597         }
3598         
3599         return 0;
3600 }
3601
3602 static int
3603 smbc_utimes_ctx(SMBCCTX *context,
3604                 const char *fname,
3605                 struct timeval *tbuf)
3606 {
3607         SMBCSRV *srv;
3608         fstring server;
3609         fstring share;
3610         fstring user;
3611         fstring password;
3612         fstring workgroup;
3613         pstring path;
3614         time_t access_time;
3615         time_t write_time;
3616
3617         if (!context || !context->internal ||
3618             !context->internal->_initialized) {
3619
3620                 errno = EINVAL;  /* Best I can think of ... */
3621                 return -1;
3622     
3623         }
3624
3625         if (!fname) {
3626
3627                 errno = EINVAL;
3628                 return -1;
3629
3630         }
3631   
3632         if (tbuf == NULL) {
3633                 access_time = write_time = time(NULL);
3634         } else {
3635                 access_time = tbuf[0].tv_sec;
3636                 write_time = tbuf[1].tv_sec;
3637         }
3638
3639         if (DEBUGLVL(4)) 
3640         {
3641                 char *p;
3642                 char atimebuf[32];
3643                 char mtimebuf[32];
3644
3645                 strncpy(atimebuf, ctime(&access_time), sizeof(atimebuf) - 1);
3646                 atimebuf[sizeof(atimebuf) - 1] = '\0';
3647                 if ((p = strchr(atimebuf, '\n')) != NULL) {
3648                         *p = '\0';
3649                 }
3650
3651                 strncpy(mtimebuf, ctime(&write_time), sizeof(mtimebuf) - 1);
3652                 mtimebuf[sizeof(mtimebuf) - 1] = '\0';
3653                 if ((p = strchr(mtimebuf, '\n')) != NULL) {
3654                         *p = '\0';
3655                 }
3656
3657                 dbgtext("smbc_utimes(%s, atime = %s mtime = %s)\n",
3658                         fname, atimebuf, mtimebuf);
3659         }
3660
3661         if (smbc_parse_path(context, fname,
3662                             workgroup, sizeof(workgroup),
3663                             server, sizeof(server),
3664                             share, sizeof(share),
3665                             path, sizeof(path),
3666                             user, sizeof(user),
3667                             password, sizeof(password),
3668                             NULL, 0)) {
3669                 errno = EINVAL;
3670                 return -1;
3671         }
3672
3673         if (user[0] == (char)0) fstrcpy(user, context->user);
3674
3675         srv = smbc_server(context, True,
3676                           server, share, workgroup, user, password);
3677
3678         if (!srv) {
3679                 return -1;      /* errno set by smbc_server */
3680         }
3681
3682         if (!smbc_setatr(context, srv, path,
3683                          0, access_time, write_time, 0, 0)) {
3684                 return -1;      /* errno set by smbc_setatr */
3685         }
3686
3687         return 0;
3688 }
3689
3690
3691 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
3692    However NT4 gives a "The information may have been modified by a
3693    computer running Windows NT 5.0" if denied ACEs do not appear before
3694    allowed ACEs. */
3695
3696 static int
3697 ace_compare(SEC_ACE *ace1,
3698             SEC_ACE *ace2)
3699 {
3700         if (sec_ace_equal(ace1, ace2)) 
3701                 return 0;
3702
3703         if (ace1->type != ace2->type) 
3704                 return ace2->type - ace1->type;
3705
3706         if (sid_compare(&ace1->trustee, &ace2->trustee)) 
3707                 return sid_compare(&ace1->trustee, &ace2->trustee);
3708
3709         if (ace1->flags != ace2->flags) 
3710                 return ace1->flags - ace2->flags;
3711
3712         if (ace1->info.mask != ace2->info.mask) 
3713                 return ace1->info.mask - ace2->info.mask;
3714
3715         if (ace1->size != ace2->size) 
3716                 return ace1->size - ace2->size;
3717
3718         return memcmp(ace1, ace2, sizeof(SEC_ACE));
3719 }
3720
3721
3722 static void
3723 sort_acl(SEC_ACL *the_acl)
3724 {
3725         uint32 i;
3726         if (!the_acl) return;
3727
3728         qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]),
3729               QSORT_CAST ace_compare);
3730
3731         for (i=1;i<the_acl->num_aces;) {
3732                 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
3733                         int j;
3734                         for (j=i; j<the_acl->num_aces-1; j++) {
3735                                 the_acl->ace[j] = the_acl->ace[j+1];
3736                         }
3737                         the_acl->num_aces--;
3738                 } else {
3739                         i++;
3740                 }
3741         }
3742 }
3743
3744 /* convert a SID to a string, either numeric or username/group */
3745 static void
3746 convert_sid_to_string(struct cli_state *ipc_cli,
3747                       POLICY_HND *pol,
3748                       fstring str,
3749                       BOOL numeric,
3750                       DOM_SID *sid)
3751 {
3752         char **domains = NULL;
3753         char **names = NULL;
3754         enum SID_NAME_USE *types = NULL;
3755         struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3756         sid_to_string(str, sid);
3757
3758         if (numeric) {
3759                 return;     /* no lookup desired */
3760         }
3761        
3762         if (!pipe_hnd) {
3763                 return;
3764         }
3765  
3766         /* Ask LSA to convert the sid to a name */
3767
3768         if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_sids(pipe_hnd, ipc_cli->mem_ctx,  
3769                                                  pol, 1, sid, &domains, 
3770                                                  &names, &types)) ||
3771             !domains || !domains[0] || !names || !names[0]) {
3772                 return;
3773         }
3774
3775         /* Converted OK */
3776
3777         slprintf(str, sizeof(fstring) - 1, "%s%s%s",
3778                  domains[0], lp_winbind_separator(),
3779                  names[0]);
3780 }
3781
3782 /* convert a string to a SID, either numeric or username/group */
3783 static BOOL
3784 convert_string_to_sid(struct cli_state *ipc_cli,
3785                       POLICY_HND *pol,
3786                       BOOL numeric,
3787                       DOM_SID *sid,
3788                       const char *str)
3789 {
3790         enum SID_NAME_USE *types = NULL;
3791         DOM_SID *sids = NULL;
3792         BOOL result = True;
3793         struct rpc_pipe_client *pipe_hnd = find_lsa_pipe_hnd(ipc_cli);
3794
3795         if (!pipe_hnd) {
3796                 return False;
3797         }
3798
3799         if (numeric) {
3800                 if (strncmp(str, "S-", 2) == 0) {
3801                         return string_to_sid(sid, str);
3802                 }
3803
3804                 result = False;
3805                 goto done;
3806         }
3807
3808         if (!NT_STATUS_IS_OK(rpccli_lsa_lookup_names(pipe_hnd, ipc_cli->mem_ctx, 
3809                                                   pol, 1, &str, NULL, &sids, 
3810                                                   &types))) {
3811                 result = False;
3812                 goto done;
3813         }
3814
3815         sid_copy(sid, &sids[0]);
3816  done:
3817
3818         return result;
3819 }
3820
3821
3822 /* parse an ACE in the same format as print_ace() */
3823 static BOOL
3824 parse_ace(struct cli_state *ipc_cli,
3825           POLICY_HND *pol,
3826           SEC_ACE *ace,
3827           BOOL numeric,
3828           char *str)
3829 {
3830         char *p;
3831         const char *cp;
3832         fstring tok;
3833         unsigned int atype;
3834         unsigned int aflags;
3835         unsigned int amask;
3836         DOM_SID sid;
3837         SEC_ACCESS mask;
3838         const struct perm_value *v;
3839         struct perm_value {
3840                 const char *perm;
3841                 uint32 mask;
3842         };
3843
3844         /* These values discovered by inspection */
3845         static const struct perm_value special_values[] = {
3846                 { "R", 0x00120089 },
3847                 { "W", 0x00120116 },
3848                 { "X", 0x001200a0 },
3849                 { "D", 0x00010000 },
3850                 { "P", 0x00040000 },
3851                 { "O", 0x00080000 },
3852                 { NULL, 0 },
3853         };
3854
3855         static const struct perm_value standard_values[] = {
3856                 { "READ",   0x001200a9 },
3857                 { "CHANGE", 0x001301bf },
3858                 { "FULL",   0x001f01ff },
3859                 { NULL, 0 },
3860         };
3861
3862
3863         ZERO_STRUCTP(ace);
3864         p = strchr_m(str,':');
3865         if (!p) return False;
3866         *p = '\0';
3867         p++;
3868         /* Try to parse numeric form */
3869
3870         if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3871             convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3872                 goto done;
3873         }
3874
3875         /* Try to parse text form */
3876
3877         if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3878                 return False;
3879         }
3880
3881         cp = p;
3882         if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3883                 return False;
3884         }
3885
3886         if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3887                 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3888         } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3889                 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3890         } else {
3891                 return False;
3892         }
3893
3894         /* Only numeric form accepted for flags at present */
3895
3896         if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3897               sscanf(tok, "%i", &aflags))) {
3898                 return False;
3899         }
3900
3901         if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3902                 return False;
3903         }
3904
3905         if (strncmp(tok, "0x", 2) == 0) {
3906                 if (sscanf(tok, "%i", &amask) != 1) {
3907                         return False;
3908                 }
3909                 goto done;
3910         }
3911
3912         for (v = standard_values; v->perm; v++) {
3913                 if (strcmp(tok, v->perm) == 0) {
3914                         amask = v->mask;
3915                         goto done;
3916                 }
3917         }
3918
3919         p = tok;
3920
3921         while(*p) {
3922                 BOOL found = False;
3923
3924                 for (v = special_values; v->perm; v++) {
3925                         if (v->perm[0] == *p) {
3926                                 amask |= v->mask;
3927                                 found = True;
3928                         }
3929                 }
3930
3931                 if (!found) return False;
3932                 p++;
3933         }
3934
3935         if (*p) {
3936                 return False;
3937         }
3938
3939  done:
3940         mask.mask = amask;
3941         init_sec_ace(ace, &sid, atype, mask, aflags);
3942         return True;
3943 }
3944
3945 /* add an ACE to a list of ACEs in a SEC_ACL */
3946 static BOOL
3947 add_ace(SEC_ACL **the_acl,
3948         SEC_ACE *ace,
3949         TALLOC_CTX *ctx)
3950 {
3951         SEC_ACL *newacl;
3952         SEC_ACE *aces;
3953
3954         if (! *the_acl) {
3955                 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3956                 return True;
3957         }
3958
3959         if ((aces = SMB_CALLOC_ARRAY(SEC_ACE, 1+(*the_acl)->num_aces)) == NULL) {
3960                 return False;
3961         }
3962         memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3963         memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3964         newacl = make_sec_acl(ctx, (*the_acl)->revision,
3965                               1+(*the_acl)->num_aces, aces);
3966         SAFE_FREE(aces);
3967         (*the_acl) = newacl;
3968         return True;
3969 }
3970
3971
3972 /* parse a ascii version of a security descriptor */
3973 static SEC_DESC *
3974 sec_desc_parse(TALLOC_CTX *ctx,
3975                struct cli_state *ipc_cli,
3976                POLICY_HND *pol,
3977                BOOL numeric,
3978                char *str)
3979 {
3980         const char *p = str;
3981         fstring tok;
3982         SEC_DESC *ret = NULL;
3983         size_t sd_size;
3984         DOM_SID *grp_sid=NULL;
3985         DOM_SID *owner_sid=NULL;
3986         SEC_ACL *dacl=NULL;
3987         int revision=1;
3988
3989         while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3990
3991                 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3992                         revision = strtol(tok+9, NULL, 16);
3993                         continue;
3994                 }
3995
3996                 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3997                         if (owner_sid) {
3998                                 DEBUG(5, ("OWNER specified more than once!\n"));
3999                                 goto done;
4000                         }
4001                         owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4002                         if (!owner_sid ||
4003                             !convert_string_to_sid(ipc_cli, pol,
4004                                                    numeric,
4005                                                    owner_sid, tok+6)) {
4006                                 DEBUG(5, ("Failed to parse owner sid\n"));
4007                                 goto done;
4008                         }
4009                         continue;
4010                 }
4011
4012                 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
4013                         if (owner_sid) {
4014                                 DEBUG(5, ("OWNER specified more than once!\n"));
4015                                 goto done;
4016                         }
4017                         owner_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4018                         if (!owner_sid ||
4019                             !convert_string_to_sid(ipc_cli, pol,
4020                                                    False,
4021                                                    owner_sid, tok+7)) {
4022                                 DEBUG(5, ("Failed to parse owner sid\n"));
4023                                 goto done;
4024                         }
4025                         continue;
4026                 }
4027
4028                 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
4029                         if (grp_sid) {
4030                                 DEBUG(5, ("GROUP specified more than once!\n"));
4031                                 goto done;
4032                         }
4033                         grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4034                         if (!grp_sid ||
4035                             !convert_string_to_sid(ipc_cli, pol,
4036                                                    numeric,
4037                                                    grp_sid, tok+6)) {
4038                                 DEBUG(5, ("Failed to parse group sid\n"));
4039                                 goto done;
4040                         }
4041                         continue;
4042                 }
4043
4044                 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
4045                         if (grp_sid) {
4046                                 DEBUG(5, ("GROUP specified more than once!\n"));
4047                                 goto done;
4048                         }
4049                         grp_sid = SMB_CALLOC_ARRAY(DOM_SID, 1);
4050                         if (!grp_sid ||
4051                             !convert_string_to_sid(ipc_cli, pol,
4052                                                    False,
4053                                                    grp_sid, tok+6)) {
4054                                 DEBUG(5, ("Failed to parse group sid\n"));
4055                                 goto done;
4056                         }
4057                         continue;
4058                 }
4059
4060                 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
4061                         SEC_ACE ace;
4062                         if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
4063                                 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4064                                 goto done;
4065                         }
4066                         if(!add_ace(&dacl, &ace, ctx)) {
4067                                 DEBUG(5, ("Failed to add ACL %s\n", tok));
4068                                 goto done;
4069                         }
4070                         continue;
4071                 }
4072
4073                 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
4074                         SEC_ACE ace;
4075                         if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
4076                                 DEBUG(5, ("Failed to parse ACL %s\n", tok));
4077                                 goto done;
4078                         }
4079                         if(!add_ace(&dacl, &ace, ctx)) {
4080                                 DEBUG(5, ("Failed to add ACL %s\n", tok));
4081                                 goto done;
4082                         }
4083                         continue;
4084                 }
4085
4086                 DEBUG(5, ("Failed to parse security descriptor\n"));
4087                 goto done;
4088         }
4089
4090         ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE, 
4091                             owner_sid, grp_sid, NULL, dacl, &sd_size);
4092
4093   done:
4094         SAFE_FREE(grp_sid);
4095         SAFE_FREE(owner_sid);
4096
4097         return ret;
4098 }
4099
4100
4101 /* Obtain the current dos attributes */
4102 static DOS_ATTR_DESC *
4103 dos_attr_query(SMBCCTX *context,
4104                TALLOC_CTX *ctx,
4105                const char *filename,
4106                SMBCSRV *srv)
4107 {
4108         struct timespec create_time_ts;
4109         struct timespec write_time_ts;
4110         struct timespec access_time_ts;
4111         struct timespec change_time_ts;
4112         SMB_OFF_T size = 0;
4113         uint16 mode = 0;
4114         SMB_INO_T inode = 0;
4115         DOS_ATTR_DESC *ret;
4116     
4117         ret = TALLOC_P(ctx, DOS_ATTR_DESC);
4118         if (!ret) {
4119                 errno = ENOMEM;
4120                 return NULL;
4121         }
4122
4123         /* Obtain the DOS attributes */
4124         if (!smbc_getatr(context, srv, CONST_DISCARD(char *, filename),
4125                          &mode, &size, 
4126                          &create_time_ts,
4127                          &access_time_ts,
4128                          &write_time_ts,
4129                          &change_time_ts, 
4130                          &inode)) {
4131         
4132                 errno = smbc_errno(context, srv->cli);
4133                 DEBUG(5, ("dos_attr_query Failed to query old attributes\n"));
4134                 return NULL;
4135         
4136         }
4137                 
4138         ret->mode = mode;
4139         ret->size = size;
4140         ret->create_time = convert_timespec_to_time_t(create_time_ts);
4141         ret->access_time = convert_timespec_to_time_t(access_time_ts);
4142         ret->write_time = convert_timespec_to_time_t(write_time_ts);
4143         ret->change_time = convert_timespec_to_time_t(change_time_ts);
4144         ret->inode = inode;
4145
4146         return ret;
4147 }
4148
4149
4150 /* parse a ascii version of a security descriptor */
4151 static void
4152 dos_attr_parse(SMBCCTX *context,
4153                DOS_ATTR_DESC *dad,
4154                SMBCSRV *srv,
4155                char *str)
4156 {
4157         int n;
4158         const char *p = str;
4159         fstring tok;
4160         struct {
4161                 const char * create_time_attr;
4162                 const char * access_time_attr;
4163                 const char * write_time_attr;
4164                 const char * change_time_attr;
4165         } attr_strings;
4166
4167         /* Determine whether to use old-style or new-style attribute names */
4168         if (context->internal->_full_time_names) {
4169                 /* new-style names */
4170                 attr_strings.create_time_attr = "CREATE_TIME";
4171                 attr_strings.access_time_attr = "ACCESS_TIME";
4172                 attr_strings.write_time_attr = "WRITE_TIME";
4173                 attr_strings.change_time_attr = "CHANGE_TIME";
4174         } else {
4175                 /* old-style names */
4176                 attr_strings.create_time_attr = NULL;
4177                 attr_strings.access_time_attr = "A_TIME";
4178                 attr_strings.write_time_attr = "M_TIME";
4179                 attr_strings.change_time_attr = "C_TIME";
4180         }
4181
4182         /* if this is to set the entire ACL... */
4183         if (*str == '*') {
4184                 /* ... then increment past the first colon if there is one */
4185                 if ((p = strchr(str, ':')) != NULL) {
4186                         ++p;
4187                 } else {
4188                         p = str;
4189                 }
4190         }
4191
4192         while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
4193
4194                 if (StrnCaseCmp(tok, "MODE:", 5) == 0) {
4195                         dad->mode = strtol(tok+5, NULL, 16);
4196                         continue;
4197                 }
4198
4199                 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4200                         dad->size = (SMB_OFF_T)atof(tok+5);
4201                         continue;
4202                 }
4203
4204                 n = strlen(attr_strings.access_time_attr);
4205                 if (StrnCaseCmp(tok, attr_strings.access_time_attr, n) == 0) {
4206                         dad->access_time = (time_t)strtol(tok+n+1, NULL, 10);
4207                         continue;
4208                 }
4209
4210                 n = strlen(attr_strings.change_time_attr);
4211                 if (StrnCaseCmp(tok, attr_strings.change_time_attr, n) == 0) {
4212                         dad->change_time = (time_t)strtol(tok+n+1, NULL, 10);
4213                         continue;
4214                 }
4215
4216                 n = strlen(attr_strings.write_time_attr);
4217                 if (StrnCaseCmp(tok, attr_strings.write_time_attr, n) == 0) {
4218                         dad->write_time = (time_t)strtol(tok+n+1, NULL, 10);
4219                         continue;
4220                 }
4221
4222                 n = strlen(attr_strings.create_time_attr);
4223                 if (attr_strings.create_time_attr != NULL &&
4224                     StrnCaseCmp(tok, attr_strings.create_time_attr, n) == 0) {
4225                         dad->create_time = (time_t)strtol(tok+n+1, NULL, 10);
4226                         continue;
4227                 }
4228
4229                 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4230                         dad->inode = (SMB_INO_T)atof(tok+6);
4231                         continue;
4232                 }
4233         }
4234 }
4235
4236 /***************************************************** 
4237  Retrieve the acls for a file.
4238 *******************************************************/
4239
4240 static int
4241 cacl_get(SMBCCTX *context,
4242          TALLOC_CTX *ctx,
4243          SMBCSRV *srv,
4244          struct cli_state *ipc_cli,
4245          POLICY_HND *pol,
4246          char *filename,
4247          char *attr_name,
4248          char *buf,
4249          int bufsize)
4250 {
4251         uint32 i;
4252         int n = 0;
4253         int n_used;
4254         BOOL all;
4255         BOOL all_nt;
4256         BOOL all_nt_acls;
4257         BOOL all_dos;
4258         BOOL some_nt;
4259         BOOL some_dos;
4260         BOOL exclude_nt_revision = False;
4261         BOOL exclude_nt_owner = False;
4262         BOOL exclude_nt_group = False;
4263         BOOL exclude_nt_acl = False;
4264         BOOL exclude_dos_mode = False;
4265         BOOL exclude_dos_size = False;
4266         BOOL exclude_dos_create_time = False;
4267         BOOL exclude_dos_access_time = False;
4268         BOOL exclude_dos_write_time = False;
4269         BOOL exclude_dos_change_time = False;
4270         BOOL exclude_dos_inode = False;
4271         BOOL numeric = True;
4272         BOOL determine_size = (bufsize == 0);
4273         int fnum = -1;
4274         SEC_DESC *sd;
4275         fstring sidstr;
4276         fstring name_sandbox;
4277         char *name;
4278         char *pExclude;
4279         char *p;
4280         struct timespec create_time_ts;
4281         struct timespec write_time_ts;
4282         struct timespec access_time_ts;
4283         struct timespec change_time_ts;
4284         time_t create_time = (time_t)0;
4285         time_t write_time = (time_t)0;
4286         time_t access_time = (time_t)0;
4287         time_t change_time = (time_t)0;
4288         SMB_OFF_T size = 0;
4289         uint16 mode = 0;
4290         SMB_INO_T ino = 0;
4291         struct cli_state *cli = srv->cli;
4292         struct {
4293                 const char * create_time_attr;
4294                 const char * access_time_attr;
4295                 const char * write_time_attr;
4296                 const char * change_time_attr;
4297         } attr_strings;
4298         struct {
4299                 const char * create_time_attr;
4300                 const char * access_time_attr;
4301                 const char * write_time_attr;
4302                 const char * change_time_attr;
4303         } excl_attr_strings;
4304
4305         /* Determine whether to use old-style or new-style attribute names */
4306         if (context->internal->_full_time_names) {
4307                 /* new-style names */
4308                 attr_strings.create_time_attr = "CREATE_TIME";
4309                 attr_strings.access_time_attr = "ACCESS_TIME";
4310                 attr_strings.write_time_attr = "WRITE_TIME";
4311                 attr_strings.change_time_attr = "CHANGE_TIME";
4312
4313                 excl_attr_strings.create_time_attr = "CREATE_TIME";
4314                 excl_attr_strings.access_time_attr = "ACCESS_TIME";
4315                 excl_attr_strings.write_time_attr = "WRITE_TIME";
4316                 excl_attr_strings.change_time_attr = "CHANGE_TIME";
4317         } else {
4318                 /* old-style names */
4319                 attr_strings.create_time_attr = NULL;
4320                 attr_strings.access_time_attr = "A_TIME";
4321                 attr_strings.write_time_attr = "M_TIME";
4322                 attr_strings.change_time_attr = "C_TIME";
4323
4324                 excl_attr_strings.create_time_attr = NULL;
4325                 excl_attr_strings.access_time_attr = "dos_attr.A_TIME";
4326                 excl_attr_strings.write_time_attr = "dos_attr.M_TIME";
4327                 excl_attr_strings.change_time_attr = "dos_attr.C_TIME";
4328         }
4329
4330         /* Copy name so we can strip off exclusions (if any are specified) */
4331         strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4332
4333         /* Ensure name is null terminated */
4334         name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4335
4336         /* Play in the sandbox */
4337         name = name_sandbox;
4338
4339         /* If there are any exclusions, point to them and mask them from name */
4340         if ((pExclude = strchr(name, '!')) != NULL)
4341         {
4342                 *pExclude++ = '\0';
4343         }
4344
4345         all = (StrnCaseCmp(name, "system.*", 8) == 0);
4346         all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4347         all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4348         all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4349         some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4350         some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4351         numeric = (* (name + strlen(name) - 1) != '+');
4352
4353         /* Look for exclusions from "all" requests */
4354         if (all || all_nt || all_dos) {
4355
4356                 /* Exclusions are delimited by '!' */
4357                 for (;
4358                      pExclude != NULL;
4359                      pExclude = (p == NULL ? NULL : p + 1)) {
4360
4361                 /* Find end of this exclusion name */
4362                 if ((p = strchr(pExclude, '!')) != NULL)
4363                 {
4364                     *p = '\0';
4365                 }
4366
4367                 /* Which exclusion name is this? */
4368                 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4369                     exclude_nt_revision = True;
4370                 }
4371                 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4372                     exclude_nt_owner = True;
4373                 }
4374                 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4375                     exclude_nt_group = True;
4376                 }
4377                 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4378                     exclude_nt_acl = True;
4379                 }
4380                 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4381                     exclude_dos_mode = True;
4382                 }
4383                 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4384                     exclude_dos_size = True;
4385                 }
4386                 else if (excl_attr_strings.create_time_attr != NULL &&
4387                          StrCaseCmp(pExclude,
4388                                     excl_attr_strings.change_time_attr) == 0) {
4389                     exclude_dos_create_time = True;
4390                 }
4391                 else if (StrCaseCmp(pExclude,
4392                                     excl_attr_strings.access_time_attr) == 0) {
4393                     exclude_dos_access_time = True;
4394                 }
4395                 else if (StrCaseCmp(pExclude,
4396                                     excl_attr_strings.write_time_attr) == 0) {
4397                     exclude_dos_write_time = True;
4398                 }
4399                 else if (StrCaseCmp(pExclude,
4400                                     excl_attr_strings.change_time_attr) == 0) {
4401                     exclude_dos_change_time = True;
4402                 }
4403                 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4404                     exclude_dos_inode = True;
4405                 }
4406                 else {
4407                     DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4408                               pExclude));
4409                     errno = ENOATTR;
4410                     return -1;
4411                 }
4412             }
4413         }
4414
4415         n_used = 0;
4416
4417         /*
4418          * If we are (possibly) talking to an NT or new system and some NT
4419          * attributes have been requested...
4420          */
4421         if (ipc_cli && (all || some_nt || all_nt_acls)) {
4422                 /* Point to the portion after "system.nt_sec_desc." */
4423                 name += 19;     /* if (all) this will be invalid but unused */
4424
4425                 /* ... then obtain any NT attributes which were requested */
4426                 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4427
4428                 if (fnum == -1) {
4429                         DEBUG(5, ("cacl_get failed to open %s: %s\n",
4430                                   filename, cli_errstr(cli)));
4431                         errno = 0;
4432                         return -1;
4433                 }
4434
4435                 sd = cli_query_secdesc(cli, fnum, ctx);
4436
4437                 if (!sd) {
4438                         DEBUG(5,
4439                               ("cacl_get Failed to query old descriptor\n"));
4440                         errno = 0;
4441                         return -1;
4442                 }
4443
4444                 cli_close(cli, fnum);
4445
4446                 if (! exclude_nt_revision) {
4447                         if (all || all_nt) {
4448                                 if (determine_size) {
4449                                         p = talloc_asprintf(ctx,
4450                                                             "REVISION:%d",
4451                                                             sd->revision);
4452                                         if (!p) {
4453                                                 errno = ENOMEM;
4454                                                 return -1;
4455                                         }
4456                                         n = strlen(p);
4457                                 } else {
4458                                         n = snprintf(buf, bufsize,
4459                                                      "REVISION:%d",
4460                                                      sd->revision);
4461                                 }
4462                         } else if (StrCaseCmp(name, "revision") == 0) {
4463                                 if (determine_size) {
4464                                         p = talloc_asprintf(ctx, "%d",
4465                                                             sd->revision);
4466                                         if (!p) {
4467                                                 errno = ENOMEM;
4468                                                 return -1;
4469                                         }
4470                                         n = strlen(p);
4471                                 } else {
4472                                         n = snprintf(buf, bufsize, "%d",
4473                                                      sd->revision);
4474                                 }
4475                         }
4476         
4477                         if (!determine_size && n > bufsize) {
4478                                 errno = ERANGE;
4479                                 return -1;
4480                         }
4481                         buf += n;
4482                         n_used += n;
4483                         bufsize -= n;
4484                 }
4485
4486                 if (! exclude_nt_owner) {
4487                         /* Get owner and group sid */
4488                         if (sd->owner_sid) {
4489                                 convert_sid_to_string(ipc_cli, pol,
4490                                                       sidstr,
4491                                                       numeric,
4492                                                       sd->owner_sid);
4493                         } else {
4494                                 fstrcpy(sidstr, "");
4495                         }
4496
4497                         if (all || all_nt) {
4498                                 if (determine_size) {
4499                                         p = talloc_asprintf(ctx, ",OWNER:%s",
4500                                                             sidstr);
4501                                         if (!p) {
4502                                                 errno = ENOMEM;
4503                                                 return -1;
4504                                         }
4505                                         n = strlen(p);
4506                                 } else {
4507                                         n = snprintf(buf, bufsize,
4508                                                      ",OWNER:%s", sidstr);
4509                                 }
4510                         } else if (StrnCaseCmp(name, "owner", 5) == 0) {
4511                                 if (determine_size) {
4512                                         p = talloc_asprintf(ctx, "%s", sidstr);
4513                                         if (!p) {
4514                                                 errno = ENOMEM;
4515                                                 return -1;
4516                                         }
4517                                         n = strlen(p);
4518                                 } else {
4519                                         n = snprintf(buf, bufsize, "%s",
4520                                                      sidstr);
4521                                 }
4522                         }
4523
4524                         if (!determine_size && n > bufsize) {
4525                                 errno = ERANGE;
4526                                 return -1;
4527                         }
4528                         buf += n;
4529                         n_used += n;
4530                         bufsize -= n;
4531                 }
4532
4533                 if (! exclude_nt_group) {
4534                         if (sd->grp_sid) {
4535                                 convert_sid_to_string(ipc_cli, pol,
4536                                                       sidstr, numeric,
4537                                                       sd->grp_sid);
4538                         } else {
4539                                 fstrcpy(sidstr, "");
4540                         }
4541
4542                         if (all || all_nt) {
4543                                 if (determine_size) {
4544                                         p = talloc_asprintf(ctx, ",GROUP:%s",
4545                                                             sidstr);
4546                                         if (!p) {
4547                                                 errno = ENOMEM;
4548                                                 return -1;
4549                                         }
4550                                         n = strlen(p);
4551                                 } else {
4552                                         n = snprintf(buf, bufsize,
4553                                                      ",GROUP:%s", sidstr);
4554                                 }
4555                         } else if (StrnCaseCmp(name, "group", 5) == 0) {
4556                                 if (determine_size) {
4557                                         p = talloc_asprintf(ctx, "%s", sidstr);
4558                                         if (!p) {
4559                                                 errno = ENOMEM;
4560                                                 return -1;
4561                                         }
4562                                         n = strlen(p);
4563                                 } else {
4564                                         n = snprintf(buf, bufsize,
4565                                                      "%s", sidstr);
4566                                 }
4567                         }
4568
4569                         if (!determine_size && n > bufsize) {
4570                                 errno = ERANGE;
4571                                 return -1;
4572                         }
4573                         buf += n;
4574                         n_used += n;
4575                         bufsize -= n;
4576                 }
4577
4578                 if (! exclude_nt_acl) {
4579                         /* Add aces to value buffer  */
4580                         for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
4581
4582                                 SEC_ACE *ace = &sd->dacl->ace[i];
4583                                 convert_sid_to_string(ipc_cli, pol,
4584                                                       sidstr, numeric,
4585                                                       &ace->trustee);
4586
4587                                 if (all || all_nt) {
4588                                         if (determine_size) {
4589                                                 p = talloc_asprintf(
4590                                                         ctx, 
4591                                                         ",ACL:"
4592                                                         "%s:%d/%d/0x%08x", 
4593                                                         sidstr,
4594                                                         ace->type,
4595                                                         ace->flags,
4596                                                         ace->info.mask);
4597                                                 if (!p) {
4598                                                         errno = ENOMEM;
4599                                                         return -1;
4600                                                 }
4601                                                 n = strlen(p);
4602                                         } else {
4603                                                 n = snprintf(
4604                                                         buf, bufsize,
4605                                                         ",ACL:%s:%d/%d/0x%08x", 
4606                                                         sidstr,
4607                                                         ace->type,
4608                                                         ace->flags,
4609                                                         ace->info.mask);
4610                                         }
4611                                 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
4612                                             StrCaseCmp(name+3, sidstr) == 0) ||
4613                                            (StrnCaseCmp(name, "acl+", 4) == 0 &&
4614                                             StrCaseCmp(name+4, sidstr) == 0)) {
4615                                         if (determine_size) {
4616                                                 p = talloc_asprintf(
4617                                                         ctx, 
4618                                                         "%d/%d/0x%08x", 
4619                                                         ace->type,
4620                                                         ace->flags,
4621                                                         ace->info.mask);
4622                                                 if (!p) {
4623                                                         errno = ENOMEM;
4624                                                         return -1;
4625                                                 }
4626                                                 n = strlen(p);
4627                                         } else {
4628                                                 n = snprintf(buf, bufsize,
4629                                                              "%d/%d/0x%08x", 
4630                                                              ace->type,
4631                                                              ace->flags,
4632                                                              ace->info.mask);
4633                                         }
4634                                 } else if (all_nt_acls) {
4635                                         if (determine_size) {
4636                                                 p = talloc_asprintf(
4637                                                         ctx, 
4638                                                         "%s%s:%d/%d/0x%08x",
4639                                                         i ? "," : "",
4640                                                         sidstr,
4641                                                         ace->type,
4642                                                         ace->flags,
4643                                                         ace->info.mask);
4644                                                 if (!p) {
4645                                                         errno = ENOMEM;
4646                                                         return -1;
4647                                                 }
4648                                                 n = strlen(p);
4649                                         } else {
4650                                                 n = snprintf(buf, bufsize,
4651                                                              "%s%s:%d/%d/0x%08x",
4652                                                              i ? "," : "",
4653                                                              sidstr,
4654                                                              ace->type,
4655                                                              ace->flags,
4656                                                              ace->info.mask);
4657                                         }
4658                                 }
4659                                 if (n > bufsize) {
4660                                         errno = ERANGE;
4661                                         return -1;
4662                                 }
4663                                 buf += n;
4664                                 n_used += n;
4665                                 bufsize -= n;
4666                         }
4667                 }
4668
4669                 /* Restore name pointer to its original value */
4670                 name -= 19;
4671         }
4672
4673         if (all || some_dos) {
4674                 /* Point to the portion after "system.dos_attr." */
4675                 name += 16;     /* if (all) this will be invalid but unused */
4676
4677                 /* Obtain the DOS attributes */
4678                 if (!smbc_getatr(context, srv, filename, &mode, &size, 
4679                                  &create_time_ts,
4680                                  &access_time_ts,
4681                                  &write_time_ts,
4682                                  &change_time_ts,
4683                                  &ino)) {
4684                         
4685                         errno = smbc_errno(context, srv->cli);
4686                         return -1;
4687                         
4688                 }
4689
4690                 create_time = convert_timespec_to_time_t(create_time_ts);
4691                 access_time = convert_timespec_to_time_t(access_time_ts);
4692                 write_time = convert_timespec_to_time_t(write_time_ts);
4693                 change_time = convert_timespec_to_time_t(change_time_ts);
4694
4695                 if (! exclude_dos_mode) {
4696                         if (all || all_dos) {
4697                                 if (determine_size) {
4698                                         p = talloc_asprintf(ctx,
4699                                                             "%sMODE:0x%x",
4700                                                             (ipc_cli &&
4701                                                              (all || some_nt)
4702                                                              ? ","
4703                                                              : ""),
4704                                                             mode);
4705                                         if (!p) {
4706                                                 errno = ENOMEM;
4707                                                 return -1;
4708                                         }
4709                                         n = strlen(p);
4710                                 } else {
4711                                         n = snprintf(buf, bufsize,
4712                                                      "%sMODE:0x%x",
4713                                                      (ipc_cli &&
4714                                                       (all || some_nt)
4715                                                       ? ","
4716                                                       : ""),
4717                                                      mode);
4718                                 }
4719                         } else if (StrCaseCmp(name, "mode") == 0) {
4720                                 if (determine_size) {
4721                                         p = talloc_asprintf(ctx, "0x%x", mode);
4722                                         if (!p) {
4723                                                 errno = ENOMEM;
4724                                                 return -1;
4725                                         }
4726                                         n = strlen(p);
4727                                 } else {
4728                                         n = snprintf(buf, bufsize,
4729                                                      "0x%x", mode);
4730                                 }
4731                         }
4732         
4733                         if (!determine_size && n > bufsize) {
4734                                 errno = ERANGE;
4735                                 return -1;
4736                         }
4737                         buf += n;
4738                         n_used += n;
4739                         bufsize -= n;
4740                 }
4741
4742                 if (! exclude_dos_size) {
4743                         if (all || all_dos) {
4744                                 if (determine_size) {
4745                                         p = talloc_asprintf(
4746                                                 ctx,
4747                                                 ",SIZE:%.0f",
4748                                                 (double)size);
4749                                         if (!p) {
4750                                                 errno = ENOMEM;
4751                                                 return -1;
4752                                         }
4753                                         n = strlen(p);
4754                                 } else {
4755                                         n = snprintf(buf, bufsize,
4756                                                      ",SIZE:%.0f",
4757                                                      (double)size);
4758                                 }
4759                         } else if (StrCaseCmp(name, "size") == 0) {
4760                                 if (determine_size) {
4761                                         p = talloc_asprintf(
4762                                                 ctx,
4763                                                 "%.0f",
4764                                                 (double)size);
4765                                         if (!p) {
4766                                                 errno = ENOMEM;
4767                                                 return -1;
4768                                         }
4769                                         n = strlen(p);
4770                                 } else {
4771                                         n = snprintf(buf, bufsize,
4772                                                      "%.0f",
4773                                                      (double)size);
4774                                 }
4775                         }
4776         
4777                         if (!determine_size && n > bufsize) {
4778                                 errno = ERANGE;
4779                                 return -1;
4780                         }
4781                         buf += n;
4782                         n_used += n;
4783                         bufsize -= n;
4784                 }
4785
4786                 if (! exclude_dos_create_time &&
4787                     attr_strings.create_time_attr != NULL) {
4788                         if (all || all_dos) {
4789                                 if (determine_size) {
4790                                         p = talloc_asprintf(ctx,
4791                                                             ",%s:%lu",
4792                                                             attr_strings.create_time_attr,
4793                                                             create_time);
4794                                         if (!p) {
4795                                                 errno = ENOMEM;
4796                                                 return -1;
4797                                         }
4798                                         n = strlen(p);
4799                                 } else {
4800                                         n = snprintf(buf, bufsize,
4801                                                      ",%s:%lu",
4802                                                      attr_strings.create_time_attr,
4803                                                      create_time);
4804                                 }
4805                         } else if (StrCaseCmp(name, attr_strings.create_time_attr) == 0) {
4806                                 if (determine_size) {
4807                                         p = talloc_asprintf(ctx, "%lu", create_time);
4808                                         if (!p) {
4809                                                 errno = ENOMEM;
4810                                                 return -1;
4811                                         }
4812                                         n = strlen(p);
4813                                 } else {
4814                                         n = snprintf(buf, bufsize,
4815                                                      "%lu", create_time);
4816                                 }
4817                         }
4818         
4819                         if (!determine_size && n > bufsize) {
4820                                 errno = ERANGE;
4821                                 return -1;
4822                         }
4823                         buf += n;
4824                         n_used += n;
4825                         bufsize -= n;
4826                 }
4827
4828                 if (! exclude_dos_access_time) {
4829                         if (all || all_dos) {
4830                                 if (determine_size) {
4831                                         p = talloc_asprintf(ctx,
4832                                                             ",%s:%lu",
4833                                                             attr_strings.access_time_attr,
4834                                                             access_time);
4835                                         if (!p) {
4836                                                 errno = ENOMEM;
4837                                                 return -1;
4838                                         }
4839                                         n = strlen(p);
4840                                 } else {
4841                                         n = snprintf(buf, bufsize,
4842                                                      ",%s:%lu",
4843                                                      attr_strings.access_time_attr,
4844                                                      access_time);
4845                                 }
4846                         } else if (StrCaseCmp(name, attr_strings.access_time_attr) == 0) {
4847                                 if (determine_size) {
4848                                         p = talloc_asprintf(ctx, "%lu", access_time);
4849                                         if (!p) {
4850                                                 errno = ENOMEM;
4851                                                 return -1;
4852                                         }
4853                                         n = strlen(p);
4854                                 } else {
4855                                         n = snprintf(buf, bufsize,
4856                                                      "%lu", access_time);
4857                                 }
4858                         }
4859         
4860                         if (!determine_size && n > bufsize) {
4861                                 errno = ERANGE;
4862                                 return -1;
4863                         }
4864                         buf += n;
4865                         n_used += n;
4866                         bufsize -= n;
4867                 }
4868
4869                 if (! exclude_dos_write_time) {
4870                         if (all || all_dos) {
4871                                 if (determine_size) {
4872                                         p = talloc_asprintf(ctx,
4873                                                             ",%s:%lu",
4874                                                             attr_strings.write_time_attr,
4875                                                             write_time);
4876                                         if (!p) {
4877                                                 errno = ENOMEM;
4878                                                 return -1;
4879                                         }
4880                                         n = strlen(p);
4881                                 } else {
4882                                         n = snprintf(buf, bufsize,
4883                                                      ",%s:%lu",
4884                                                      attr_strings.write_time_attr,
4885                                                      write_time);
4886                                 }
4887                         } else if (StrCaseCmp(name, attr_strings.write_time_attr) == 0) {
4888                                 if (determine_size) {
4889                                         p = talloc_asprintf(ctx, "%lu", write_time);
4890                                         if (!p) {
4891                                                 errno = ENOMEM;
4892                                                 return -1;
4893                                         }
4894                                         n = strlen(p);
4895                                 } else {
4896                                         n = snprintf(buf, bufsize,
4897                                                      "%lu", write_time);
4898                                 }
4899                         }
4900         
4901                         if (!determine_size && n > bufsize) {
4902                                 errno = ERANGE;
4903                                 return -1;
4904                         }
4905                         buf += n;
4906                         n_used += n;
4907                         bufsize -= n;
4908                 }
4909
4910                 if (! exclude_dos_change_time) {
4911                         if (all || all_dos) {
4912                                 if (determine_size) {
4913                                         p = talloc_asprintf(ctx,
4914                                                             ",%s:%lu",
4915                                                             attr_strings.change_time_attr,
4916                                                             change_time);
4917                                         if (!p) {
4918                                                 errno = ENOMEM;
4919                                                 return -1;
4920                                         }
4921                                         n = strlen(p);
4922                                 } else {
4923                                         n = snprintf(buf, bufsize,
4924                                                      ",%s:%lu",
4925                                                      attr_strings.change_time_attr,
4926                                                      change_time);
4927                                 }
4928                         } else if (StrCaseCmp(name, attr_strings.change_time_attr) == 0) {
4929                                 if (determine_size) {
4930                                         p = talloc_asprintf(ctx, "%lu", change_time);
4931                                         if (!p) {
4932                                                 errno = ENOMEM;
4933                                                 return -1;
4934                                         }
4935                                         n = strlen(p);
4936                                 } else {
4937                                         n = snprintf(buf, bufsize,
4938                                                      "%lu", change_time);
4939                                 }
4940                         }
4941         
4942                         if (!determine_size && n > bufsize) {
4943                                 errno = ERANGE;
4944                                 return -1;
4945                         }
4946                         buf += n;
4947                         n_used += n;
4948                         bufsize -= n;
4949                 }
4950
4951                 if (! exclude_dos_inode) {
4952                         if (all || all_dos) {
4953                                 if (determine_size) {
4954                                         p = talloc_asprintf(
4955                                                 ctx,
4956                                                 ",INODE:%.0f",
4957                                                 (double)ino);
4958                                         if (!p) {
4959                                                 errno = ENOMEM;
4960                                                 return -1;
4961                                         }
4962                                         n = strlen(p);
4963                                 } else {
4964                                         n = snprintf(buf, bufsize,
4965                                                      ",INODE:%.0f",
4966                                                      (double) ino);
4967                                 }
4968                         } else if (StrCaseCmp(name, "inode") == 0) {
4969                                 if (determine_size) {
4970                                         p = talloc_asprintf(
4971                                                 ctx,
4972                                                 "%.0f",
4973                                                 (double) ino);
4974                                         if (!p) {
4975                                                 errno = ENOMEM;
4976                                                 return -1;
4977                                         }
4978                                         n = strlen(p);
4979                                 } else {
4980                                         n = snprintf(buf, bufsize,
4981                                                      "%.0f",
4982                                                      (double) ino);
4983                                 }
4984                         }
4985         
4986                         if (!determine_size && n > bufsize) {
4987                                 errno = ERANGE;
4988                                 return -1;
4989                         }
4990                         buf += n;
4991                         n_used += n;
4992                         bufsize -= n;
4993                 }
4994
4995                 /* Restore name pointer to its original value */
4996                 name -= 16;
4997         }
4998
4999         if (n_used == 0) {
5000                 errno = ENOATTR;
5001                 return -1;
5002         }
5003
5004         return n_used;
5005 }
5006
5007
5008 /***************************************************** 
5009 set the ACLs on a file given an ascii description
5010 *******************************************************/
5011 static int
5012 cacl_set(TALLOC_CTX *ctx,
5013          struct cli_state *cli,
5014          struct cli_state *ipc_cli,
5015          POLICY_HND *pol,
5016          const char *filename,
5017          const char *the_acl,
5018          int mode,
5019          int flags)
5020 {
5021         int fnum;
5022         int err = 0;
5023         SEC_DESC *sd = NULL, *old;
5024         SEC_ACL *dacl = NULL;
5025         DOM_SID *owner_sid = NULL; 
5026         DOM_SID *grp_sid = NULL;
5027         uint32 i, j;
5028         size_t sd_size;
5029         int ret = 0;
5030         char *p;
5031         BOOL numeric = True;
5032
5033         /* the_acl will be null for REMOVE_ALL operations */
5034         if (the_acl) {
5035                 numeric = ((p = strchr(the_acl, ':')) != NULL &&
5036                            p > the_acl &&
5037                            p[-1] != '+');
5038
5039                 /* if this is to set the entire ACL... */
5040                 if (*the_acl == '*') {
5041                         /* ... then increment past the first colon */
5042                         the_acl = p + 1;
5043                 }
5044
5045                 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
5046                                     CONST_DISCARD(char *, the_acl));
5047
5048                 if (!sd) {
5049                         errno = EINVAL;
5050                         return -1;
5051                 }
5052         }
5053
5054         /* SMBC_XATTR_MODE_REMOVE_ALL is the only caller
5055            that doesn't deref sd */
5056
5057         if (!sd && (mode != SMBC_XATTR_MODE_REMOVE_ALL)) {
5058                 errno = EINVAL;
5059                 return -1;
5060         }
5061
5062         /* The desired access below is the only one I could find that works
5063            with NT4, W2KP and Samba */
5064
5065         fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
5066
5067         if (fnum == -1) {
5068                 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5069                           filename, cli_errstr(cli)));
5070                 errno = 0;
5071                 return -1;
5072         }
5073
5074         old = cli_query_secdesc(cli, fnum, ctx);
5075
5076         if (!old) {
5077                 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
5078                 errno = 0;
5079                 return -1;
5080         }
5081
5082         cli_close(cli, fnum);
5083
5084         switch (mode) {
5085         case SMBC_XATTR_MODE_REMOVE_ALL:
5086                 old->dacl->num_aces = 0;
5087                 SAFE_FREE(old->dacl->ace);
5088                 SAFE_FREE(old->dacl);
5089                 old->off_dacl = 0;
5090                 dacl = old->dacl;
5091                 break;
5092
5093         case SMBC_XATTR_MODE_REMOVE:
5094                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5095                         BOOL found = False;
5096
5097                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
5098                                 if (sec_ace_equal(&sd->dacl->ace[i],
5099                                                   &old->dacl->ace[j])) {
5100                                         uint32 k;
5101                                         for (k=j; k<old->dacl->num_aces-1;k++) {
5102                                                 old->dacl->ace[k] =
5103                                                         old->dacl->ace[k+1];
5104                                         }
5105                                         old->dacl->num_aces--;
5106                                         if (old->dacl->num_aces == 0) {
5107                                                 SAFE_FREE(old->dacl->ace);
5108                                                 SAFE_FREE(old->dacl);
5109                                                 old->off_dacl = 0;
5110                                         }
5111                                         found = True;
5112                                         dacl = old->dacl;
5113                                         break;
5114                                 }
5115                         }
5116
5117                         if (!found) {
5118                                 err = ENOATTR;
5119                                 ret = -1;
5120                                 goto failed;
5121                         }
5122                 }
5123                 break;
5124
5125         case SMBC_XATTR_MODE_ADD:
5126                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5127                         BOOL found = False;
5128
5129                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
5130                                 if (sid_equal(&sd->dacl->ace[i].trustee,
5131                                               &old->dacl->ace[j].trustee)) {
5132                                         if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
5133                                                 err = EEXIST;
5134                                                 ret = -1;
5135                                                 goto failed;
5136                                         }
5137                                         old->dacl->ace[j] = sd->dacl->ace[i];
5138                                         ret = -1;
5139                                         found = True;
5140                                 }
5141                         }
5142
5143                         if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
5144                                 err = ENOATTR;
5145                                 ret = -1;
5146                                 goto failed;
5147                         }
5148                         
5149                         for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5150                                 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
5151                         }
5152                 }
5153                 dacl = old->dacl;
5154                 break;
5155
5156         case SMBC_XATTR_MODE_SET:
5157                 old = sd;
5158                 owner_sid = old->owner_sid;
5159                 grp_sid = old->grp_sid;
5160                 dacl = old->dacl;
5161                 break;
5162
5163         case SMBC_XATTR_MODE_CHOWN:
5164                 owner_sid = sd->owner_sid;
5165                 break;
5166
5167         case SMBC_XATTR_MODE_CHGRP:
5168                 grp_sid = sd->grp_sid;
5169                 break;
5170         }
5171
5172         /* Denied ACE entries must come before allowed ones */
5173         sort_acl(old->dacl);
5174
5175         /* Create new security descriptor and set it */
5176         sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE, 
5177                            owner_sid, grp_sid, NULL, dacl, &sd_size);
5178
5179         fnum = cli_nt_create(cli, filename,
5180                              WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
5181
5182         if (fnum == -1) {
5183                 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5184                           filename, cli_errstr(cli)));
5185                 errno = 0;
5186                 return -1;
5187         }
5188
5189         if (!cli_set_secdesc(cli, fnum, sd)) {
5190                 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
5191                 ret = -1;
5192         }
5193
5194         /* Clean up */
5195
5196  failed:
5197         cli_close(cli, fnum);
5198
5199         if (err != 0) {
5200                 errno = err;
5201         }
5202         
5203         return ret;
5204 }
5205
5206
5207 static int
5208 smbc_setxattr_ctx(SMBCCTX *context,
5209                   const char *fname,
5210                   const char *name,
5211                   const void *value,
5212                   size_t size,
5213                   int flags)
5214 {
5215         int ret;
5216         int ret2;
5217         SMBCSRV *srv;
5218         SMBCSRV *ipc_srv;
5219         fstring server;
5220         fstring share;
5221         fstring user;
5222         fstring password;
5223         fstring workgroup;
5224         pstring path;
5225         TALLOC_CTX *ctx;
5226         POLICY_HND pol;
5227         DOS_ATTR_DESC *dad;
5228         struct {
5229                 const char * create_time_attr;
5230                 const char * access_time_attr;
5231                 const char * write_time_attr;
5232                 const char * change_time_attr;
5233         } attr_strings;
5234
5235         if (!context || !context->internal ||
5236             !context->internal->_initialized) {
5237
5238                 errno = EINVAL;  /* Best I can think of ... */
5239                 return -1;
5240     
5241         }
5242
5243         if (!fname) {
5244
5245                 errno = EINVAL;
5246                 return -1;
5247
5248         }
5249   
5250         DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
5251                   fname, name, (int) size, (const char*)value));
5252
5253         if (smbc_parse_path(context, fname,
5254                             workgroup, sizeof(workgroup),
5255                             server, sizeof(server),
5256                             share, sizeof(share),
5257                             path, sizeof(path),
5258                             user, sizeof(user),
5259                             password, sizeof(password),
5260                             NULL, 0)) {
5261                 errno = EINVAL;
5262                 return -1;
5263         }
5264
5265         if (user[0] == (char)0) fstrcpy(user, context->user);
5266
5267         srv = smbc_server(context, True,
5268                           server, share, workgroup, user, password);
5269         if (!srv) {
5270                 return -1;  /* errno set by smbc_server */
5271         }
5272
5273         if (! srv->no_nt_session) {
5274                 ipc_srv = smbc_attr_server(context, server, share,
5275                                            workgroup, user, password,
5276                                            &pol);
5277                 srv->no_nt_session = True;
5278         } else {
5279                 ipc_srv = NULL;
5280         }
5281         
5282         ctx = talloc_init("smbc_setxattr");
5283         if (!ctx) {
5284                 errno = ENOMEM;
5285                 return -1;
5286         }
5287
5288         /*
5289          * Are they asking to set the entire set of known attributes?
5290          */
5291         if (StrCaseCmp(name, "system.*") == 0 ||
5292             StrCaseCmp(name, "system.*+") == 0) {
5293                 /* Yup. */
5294                 char *namevalue =
5295                         talloc_asprintf(ctx, "%s:%s",
5296                                         name+7, (const char *) value);
5297                 if (! namevalue) {
5298                         errno = ENOMEM;
5299                         ret = -1;
5300                         return -1;
5301                 }
5302
5303                 if (ipc_srv) {
5304                         ret = cacl_set(ctx, srv->cli,
5305                                        ipc_srv->cli, &pol, path,
5306                                        namevalue,
5307                                        (*namevalue == '*'
5308                                         ? SMBC_XATTR_MODE_SET
5309                                         : SMBC_XATTR_MODE_ADD),
5310                                        flags);
5311                 } else {
5312                         ret = 0;
5313                 }
5314
5315                 /* get a DOS Attribute Descriptor with current attributes */
5316                 dad = dos_attr_query(context, ctx, path, srv);
5317                 if (dad) {
5318                         /* Overwrite old with new, using what was provided */
5319                         dos_attr_parse(context, dad, srv, namevalue);
5320
5321                         /* Set the new DOS attributes */
5322                         if (! smbc_setatr(context, srv, path,
5323                                           dad->create_time,
5324                                           dad->access_time,
5325                                           dad->write_time,
5326                                           dad->change_time,
5327                                           dad->mode)) {
5328
5329                                 /* cause failure if NT failed too */
5330                                 dad = NULL; 
5331                         }
5332                 }
5333
5334                 /* we only fail if both NT and DOS sets failed */
5335                 if (ret < 0 && ! dad) {
5336                         ret = -1; /* in case dad was null */
5337                 }
5338                 else {
5339                         ret = 0;
5340                 }
5341
5342                 talloc_destroy(ctx);
5343                 return ret;
5344         }
5345
5346         /*
5347          * Are they asking to set an access control element or to set
5348          * the entire access control list?
5349          */
5350         if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5351             StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5352             StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5353             StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5354             StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5355
5356                 /* Yup. */
5357                 char *namevalue =
5358                         talloc_asprintf(ctx, "%s:%s",
5359                                         name+19, (const char *) value);
5360
5361                 if (! ipc_srv) {
5362                         ret = -1; /* errno set by smbc_server() */
5363                 }
5364                 else if (! namevalue) {
5365                         errno = ENOMEM;
5366                         ret = -1;
5367                 } else {
5368                         ret = cacl_set(ctx, srv->cli,
5369                                        ipc_srv->cli, &pol, path,
5370                                        namevalue,
5371                                        (*namevalue == '*'
5372                                         ? SMBC_XATTR_MODE_SET
5373                                         : SMBC_XATTR_MODE_ADD),
5374                                        flags);
5375                 }
5376                 talloc_destroy(ctx);
5377                 return ret;
5378         }
5379
5380         /*
5381          * Are they asking to set the owner?
5382          */
5383         if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5384             StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5385
5386                 /* Yup. */
5387                 char *namevalue =
5388                         talloc_asprintf(ctx, "%s:%s",
5389                                         name+19, (const char *) value);
5390
5391                 if (! ipc_srv) {
5392                         
5393                         ret = -1; /* errno set by smbc_server() */
5394                 }
5395                 else if (! namevalue) {
5396                         errno = ENOMEM;
5397                         ret = -1;
5398                 } else {
5399                         ret = cacl_set(ctx, srv->cli,
5400                                        ipc_srv->cli, &pol, path,
5401                                        namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5402                 }
5403                 talloc_destroy(ctx);
5404                 return ret;
5405         }
5406
5407         /*
5408          * Are they asking to set the group?
5409          */
5410         if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5411             StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5412
5413                 /* Yup. */
5414                 char *namevalue =
5415                         talloc_asprintf(ctx, "%s:%s",
5416                                         name+19, (const char *) value);
5417
5418                 if (! ipc_srv) {
5419                         /* errno set by smbc_server() */
5420                         ret = -1;
5421                 }
5422                 else if (! namevalue) {
5423                         errno = ENOMEM;
5424                         ret = -1;
5425                 } else {
5426                         ret = cacl_set(ctx, srv->cli,
5427                                        ipc_srv->cli, &pol, path,
5428                                        namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5429                 }
5430                 talloc_destroy(ctx);
5431                 return ret;
5432         }
5433
5434         /* Determine whether to use old-style or new-style attribute names */
5435         if (context->internal->_full_time_names) {
5436                 /* new-style names */
5437                 attr_strings.create_time_attr = "system.dos_attr.CREATE_TIME";
5438                 attr_strings.access_time_attr = "system.dos_attr.ACCESS_TIME";
5439                 attr_strings.write_time_attr = "system.dos_attr.WRITE_TIME";
5440                 attr_strings.change_time_attr = "system.dos_attr.CHANGE_TIME";
5441         } else {
5442                 /* old-style names */
5443                 attr_strings.create_time_attr = NULL;
5444                 attr_strings.access_time_attr = "system.dos_attr.A_TIME";
5445                 attr_strings.write_time_attr = "system.dos_attr.M_TIME";
5446                 attr_strings.change_time_attr = "system.dos_attr.C_TIME";
5447         }
5448
5449         /*
5450          * Are they asking to set a DOS attribute?
5451          */
5452         if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5453             StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5454             (attr_strings.create_time_attr != NULL &&
5455              StrCaseCmp(name, attr_strings.create_time_attr) == 0) ||
5456             StrCaseCmp(name, attr_strings.access_time_attr) == 0 ||
5457             StrCaseCmp(name, attr_strings.write_time_attr) == 0 ||
5458             StrCaseCmp(name, attr_strings.change_time_attr) == 0) {
5459
5460                 /* get a DOS Attribute Descriptor with current attributes */
5461                 dad = dos_attr_query(context, ctx, path, srv);
5462                 if (dad) {
5463                         char *namevalue =
5464                                 talloc_asprintf(ctx, "%s:%s",
5465                                                 name+16, (const char *) value);
5466                         if (! namevalue) {
5467                                 errno = ENOMEM;
5468                                 ret = -1;
5469                         } else {
5470                                 /* Overwrite old with provided new params */
5471                                 dos_attr_parse(context, dad, srv, namevalue);
5472
5473                                 /* Set the new DOS attributes */
5474                                 ret2 = smbc_setatr(context, srv, path,
5475                                                    dad->create_time,
5476                                                    dad->access_time,
5477                                                    dad->write_time,
5478                                                    dad->change_time,
5479                                                    dad->mode);
5480
5481                                 /* ret2 has True (success) / False (failure) */
5482                                 if (ret2) {
5483                                         ret = 0;
5484                                 } else {
5485                                         ret = -1;
5486                                 }
5487                         }
5488                 } else {
5489                         ret = -1;
5490                 }
5491
5492                 talloc_destroy(ctx);
5493                 return ret;
5494         }
5495
5496         /* Unsupported attribute name */
5497         talloc_destroy(ctx);
5498         errno = EINVAL;
5499         return -1;
5500 }
5501
5502 static int
5503 smbc_getxattr_ctx(SMBCCTX *context,
5504                   const char *fname,
5505                   const char *name,
5506                   const void *value,
5507                   size_t size)
5508 {
5509         int ret;
5510         SMBCSRV *srv;
5511         SMBCSRV *ipc_srv;
5512         fstring server;
5513         fstring share;
5514         fstring user;
5515         fstring password;
5516         fstring workgroup;
5517         pstring path;
5518         TALLOC_CTX *ctx;
5519         POLICY_HND pol;
5520         struct {
5521                 const char * create_time_attr;
5522                 const char * access_time_attr;
5523                 const char * write_time_attr;
5524                 const char * change_time_attr;
5525         } attr_strings;
5526
5527
5528         if (!context || !context->internal ||
5529             !context->internal->_initialized) {
5530
5531                 errno = EINVAL;  /* Best I can think of ... */
5532                 return -1;
5533     
5534         }
5535
5536         if (!fname) {
5537
5538                 errno = EINVAL;
5539                 return -1;
5540
5541         }
5542   
5543         DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
5544
5545         if (smbc_parse_path(context, fname,
5546                             workgroup, sizeof(workgroup),
5547                             server, sizeof(server),
5548                             share, sizeof(share),
5549                             path, sizeof(path),
5550                             user, sizeof(user),
5551                             password, sizeof(password),
5552                             NULL, 0)) {
5553                 errno = EINVAL;
5554                 return -1;
5555         }
5556
5557         if (user[0] == (char)0) fstrcpy(user, context->user);
5558
5559         srv = smbc_server(context, True,
5560                           server, share, workgroup, user, password);
5561         if (!srv) {
5562                 return -1;  /* errno set by smbc_server */
5563         }
5564
5565         if (! srv->no_nt_session) {
5566                 ipc_srv = smbc_attr_server(context, server, share,
5567                                            workgroup, user, password,
5568                                            &pol);
5569                 if (! ipc_srv) {
5570                         srv->no_nt_session = True;
5571                 }
5572         } else {
5573                 ipc_srv = NULL;
5574         }
5575         
5576         ctx = talloc_init("smbc:getxattr");
5577         if (!ctx) {
5578                 errno = ENOMEM;
5579                 return -1;
5580         }
5581
5582         /* Determine whether to use old-style or new-style attribute names */
5583         if (context->internal->_full_time_names) {
5584                 /* new-style names */
5585                 attr_strings.create_time_attr = "system.dos_attr.CREATE_TIME";
5586                 attr_strings.access_time_attr = "system.dos_attr.ACCESS_TIME";
5587                 attr_strings.write_time_attr = "system.dos_attr.WRITE_TIME";
5588                 attr_strings.change_time_attr = "system.dos_attr.CHANGE_TIME";
5589         } else {
5590                 /* old-style names */
5591                 attr_strings.create_time_attr = NULL;
5592                 attr_strings.access_time_attr = "system.dos_attr.A_TIME";
5593                 attr_strings.write_time_attr = "system.dos_attr.M_TIME";
5594                 attr_strings.change_time_attr = "system.dos_attr.C_TIME";
5595         }
5596
5597         /* Are they requesting a supported attribute? */
5598         if (StrCaseCmp(name, "system.*") == 0 ||
5599             StrnCaseCmp(name, "system.*!", 9) == 0 ||
5600             StrCaseCmp(name, "system.*+") == 0 ||
5601             StrnCaseCmp(name, "system.*+!", 10) == 0 ||
5602             StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5603             StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
5604             StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5605             StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
5606             StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5607             StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5608             StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5609             StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5610             StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5611             StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5612             StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
5613             StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5614             StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
5615             StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5616             StrCaseCmp(name, "system.dos_attr.size") == 0 ||
5617             (attr_strings.create_time_attr != NULL &&
5618              StrCaseCmp(name, attr_strings.create_time_attr) == 0) ||
5619             StrCaseCmp(name, attr_strings.access_time_attr) == 0 ||
5620             StrCaseCmp(name, attr_strings.write_time_attr) == 0 ||
5621             StrCaseCmp(name, attr_strings.change_time_attr) == 0 ||
5622             StrCaseCmp(name, "system.dos_attr.inode") == 0) {
5623
5624                 /* Yup. */
5625                 ret = cacl_get(context, ctx, srv,
5626                                ipc_srv == NULL ? NULL : ipc_srv->cli, 
5627                                &pol, path,
5628                                CONST_DISCARD(char *, name),
5629                                CONST_DISCARD(char *, value), size);
5630                 if (ret < 0 && errno == 0) {
5631                         errno = smbc_errno(context, srv->cli);
5632                 }
5633                 talloc_destroy(ctx);
5634                 return ret;
5635         }
5636
5637         /* Unsupported attribute name */
5638         talloc_destroy(ctx);
5639         errno = EINVAL;
5640         return -1;
5641 }
5642
5643
5644 static int
5645 smbc_removexattr_ctx(SMBCCTX *context,
5646                      const char *fname,
5647                      const char *name)
5648 {
5649         int ret;
5650         SMBCSRV *srv;
5651         SMBCSRV *ipc_srv;
5652         fstring server;
5653         fstring share;
5654         fstring user;
5655         fstring password;
5656         fstring workgroup;
5657         pstring path;
5658         TALLOC_CTX *ctx;
5659         POLICY_HND pol;
5660
5661         if (!context || !context->internal ||
5662             !context->internal->_initialized) {
5663
5664                 errno = EINVAL;  /* Best I can think of ... */
5665                 return -1;
5666     
5667         }
5668
5669         if (!fname) {
5670
5671                 errno = EINVAL;
5672                 return -1;
5673
5674         }
5675   
5676         DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
5677
5678         if (smbc_parse_path(context, fname,
5679                             workgroup, sizeof(workgroup),
5680                             server, sizeof(server),
5681                             share, sizeof(share),
5682                             path, sizeof(path),
5683                             user, sizeof(user),
5684                             password, sizeof(password),
5685                             NULL, 0)) {
5686                 errno = EINVAL;
5687                 return -1;
5688         }
5689
5690         if (user[0] == (char)0) fstrcpy(user, context->user);
5691
5692         srv = smbc_server(context, True,
5693                           server, share, workgroup, user, password);
5694         if (!srv) {
5695                 return -1;  /* errno set by smbc_server */
5696         }
5697
5698         if (! srv->no_nt_session) {
5699                 ipc_srv = smbc_attr_server(context, server, share,
5700                                            workgroup, user, password,
5701                                            &pol);
5702                 srv->no_nt_session = True;
5703         } else {
5704                 ipc_srv = NULL;
5705         }
5706         
5707         if (! ipc_srv) {
5708                 return -1; /* errno set by smbc_attr_server */
5709         }
5710
5711         ctx = talloc_init("smbc_removexattr");
5712         if (!ctx) {
5713                 errno = ENOMEM;
5714                 return -1;
5715         }
5716
5717         /* Are they asking to set the entire ACL? */
5718         if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5719             StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
5720
5721                 /* Yup. */
5722                 ret = cacl_set(ctx, srv->cli,
5723                                ipc_srv->cli, &pol, path,
5724                                NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
5725                 talloc_destroy(ctx);
5726                 return ret;
5727         }
5728
5729         /*
5730          * Are they asking to remove one or more spceific security descriptor
5731          * attributes?
5732          */
5733         if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5734             StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5735             StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
5736             StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5737             StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
5738             StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5739             StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5740
5741                 /* Yup. */
5742                 ret = cacl_set(ctx, srv->cli,
5743                                ipc_srv->cli, &pol, path,
5744                                name + 19, SMBC_XATTR_MODE_REMOVE, 0);
5745                 talloc_destroy(ctx);
5746                 return ret;
5747         }
5748
5749         /* Unsupported attribute name */
5750         talloc_destroy(ctx);
5751         errno = EINVAL;
5752         return -1;
5753 }
5754
5755 static int
5756 smbc_listxattr_ctx(SMBCCTX *context,
5757                    const char *fname,
5758                    char *list,
5759                    size_t size)
5760 {
5761         /*
5762          * This isn't quite what listxattr() is supposed to do.  This returns
5763          * the complete set of attribute names, always, rather than only those
5764          * attribute names which actually exist for a file.  Hmmm...
5765          */
5766         const char supported_old[] =
5767                 "system.*\0"
5768                 "system.*+\0"
5769                 "system.nt_sec_desc.revision\0"
5770                 "system.nt_sec_desc.owner\0"
5771                 "system.nt_sec_desc.owner+\0"
5772                 "system.nt_sec_desc.group\0"
5773                 "system.nt_sec_desc.group+\0"
5774                 "system.nt_sec_desc.acl.*\0"
5775                 "system.nt_sec_desc.acl\0"
5776                 "system.nt_sec_desc.acl+\0"
5777                 "system.nt_sec_desc.*\0"
5778                 "system.nt_sec_desc.*+\0"
5779                 "system.dos_attr.*\0"
5780                 "system.dos_attr.mode\0"
5781                 "system.dos_attr.c_time\0"
5782                 "system.dos_attr.a_time\0"
5783                 "system.dos_attr.m_time\0"
5784                 ;
5785         const char supported_new[] =
5786                 "system.*\0"
5787                 "system.*+\0"
5788                 "system.nt_sec_desc.revision\0"
5789                 "system.nt_sec_desc.owner\0"
5790                 "system.nt_sec_desc.owner+\0"
5791                 "system.nt_sec_desc.group\0"
5792                 "system.nt_sec_desc.group+\0"
5793                 "system.nt_sec_desc.acl.*\0"
5794                 "system.nt_sec_desc.acl\0"
5795                 "system.nt_sec_desc.acl+\0"
5796                 "system.nt_sec_desc.*\0"
5797                 "system.nt_sec_desc.*+\0"
5798                 "system.dos_attr.*\0"
5799                 "system.dos_attr.mode\0"
5800                 "system.dos_attr.create_time\0"
5801                 "system.dos_attr.access_time\0"
5802                 "system.dos_attr.write_time\0"
5803                 "system.dos_attr.change_time\0"
5804                 ;
5805         const char * supported;
5806
5807         if (context->internal->_full_time_names) {
5808                 supported = supported_new;
5809         } else {
5810                 supported = supported_old;
5811         }
5812
5813         if (size == 0) {
5814                 return sizeof(supported);
5815         }
5816
5817         if (sizeof(supported) > size) {
5818                 errno = ERANGE;
5819                 return -1;
5820         }
5821
5822         /* this can't be strcpy() because there are embedded null characters */
5823         memcpy(list, supported, sizeof(supported));
5824         return sizeof(supported);
5825 }
5826
5827
5828 /*
5829  * Open a print file to be written to by other calls
5830  */
5831
5832 static SMBCFILE *
5833 smbc_open_print_job_ctx(SMBCCTX *context,
5834                         const char *fname)
5835 {
5836         fstring server;
5837         fstring share;
5838         fstring user;
5839         fstring password;
5840         pstring path;
5841         
5842         if (!context || !context->internal ||
5843             !context->internal->_initialized) {
5844
5845                 errno = EINVAL;
5846                 return NULL;
5847     
5848         }
5849
5850         if (!fname) {
5851
5852                 errno = EINVAL;
5853                 return NULL;
5854
5855         }
5856   
5857         DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
5858
5859         if (smbc_parse_path(context, fname,
5860                             NULL, 0,
5861                             server, sizeof(server),
5862                             share, sizeof(share),
5863                             path, sizeof(path),
5864                             user, sizeof(user),
5865                             password, sizeof(password),
5866                             NULL, 0)) {
5867                 errno = EINVAL;
5868                 return NULL;
5869         }
5870
5871         /* What if the path is empty, or the file exists? */
5872
5873         return context->open(context, fname, O_WRONLY, 666);
5874
5875 }
5876
5877 /*
5878  * Routine to print a file on a remote server ...
5879  *
5880  * We open the file, which we assume to be on a remote server, and then
5881  * copy it to a print file on the share specified by printq.
5882  */
5883
5884 static int
5885 smbc_print_file_ctx(SMBCCTX *c_file,
5886                     const char *fname,
5887                     SMBCCTX *c_print,
5888                     const char *printq)
5889 {
5890         SMBCFILE *fid1;
5891         SMBCFILE *fid2;
5892         int bytes;
5893         int saverr;
5894         int tot_bytes = 0;
5895         char buf[4096];
5896
5897         if (!c_file || !c_file->internal->_initialized || !c_print ||
5898             !c_print->internal->_initialized) {
5899
5900                 errno = EINVAL;
5901                 return -1;
5902
5903         }
5904
5905         if (!fname && !printq) {
5906
5907                 errno = EINVAL;
5908                 return -1;
5909
5910         }
5911
5912         /* Try to open the file for reading ... */
5913
5914         if ((long)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
5915                 
5916                 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
5917                 return -1;  /* smbc_open sets errno */
5918                 
5919         }
5920
5921         /* Now, try to open the printer file for writing */
5922
5923         if ((long)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
5924
5925                 saverr = errno;  /* Save errno */
5926                 c_file->close_fn(c_file, fid1);
5927                 errno = saverr;
5928                 return -1;
5929
5930         }
5931
5932         while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
5933
5934                 tot_bytes += bytes;
5935
5936                 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
5937
5938                         saverr = errno;
5939                         c_file->close_fn(c_file, fid1);
5940                         c_print->close_fn(c_print, fid2);
5941                         errno = saverr;
5942
5943                 }
5944
5945         }
5946
5947         saverr = errno;
5948
5949         c_file->close_fn(c_file, fid1);  /* We have to close these anyway */
5950         c_print->close_fn(c_print, fid2);
5951
5952         if (bytes < 0) {
5953
5954                 errno = saverr;
5955                 return -1;
5956
5957         }
5958
5959         return tot_bytes;
5960
5961 }
5962
5963 /*
5964  * Routine to list print jobs on a printer share ...
5965  */
5966
5967 static int
5968 smbc_list_print_jobs_ctx(SMBCCTX *context,
5969                          const char *fname,
5970                          smbc_list_print_job_fn fn)
5971 {
5972         SMBCSRV *srv;
5973         fstring server;
5974         fstring share;
5975         fstring user;
5976         fstring password;
5977         fstring workgroup;
5978         pstring path;
5979
5980         if (!context || !context->internal ||
5981             !context->internal->_initialized) {
5982
5983                 errno = EINVAL;
5984                 return -1;
5985
5986         }
5987
5988         if (!fname) {
5989                 
5990                 errno = EINVAL;
5991                 return -1;
5992
5993         }
5994   
5995         DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
5996
5997         if (smbc_parse_path(context, fname,
5998                             workgroup, sizeof(workgroup),
5999                             server, sizeof(server),
6000                             share, sizeof(share),
6001                             path, sizeof(path),
6002                             user, sizeof(user),
6003                             password, sizeof(password),
6004                             NULL, 0)) {
6005                 errno = EINVAL;
6006                 return -1;
6007         }
6008
6009         if (user[0] == (char)0) fstrcpy(user, context->user);
6010         
6011         srv = smbc_server(context, True,
6012                           server, share, workgroup, user, password);
6013
6014         if (!srv) {
6015
6016                 return -1;  /* errno set by smbc_server */
6017
6018         }
6019
6020         if (cli_print_queue(srv->cli,
6021                             (void (*)(struct print_job_info *))fn) < 0) {
6022
6023                 errno = smbc_errno(context, srv->cli);
6024                 return -1;
6025
6026         }
6027         
6028         return 0;
6029
6030 }
6031
6032 /*
6033  * Delete a print job from a remote printer share
6034  */
6035
6036 static int
6037 smbc_unlink_print_job_ctx(SMBCCTX *context,
6038                           const char *fname,
6039                           int id)
6040 {
6041         SMBCSRV *srv;
6042         fstring server;
6043         fstring share;
6044         fstring user;
6045         fstring password;
6046         fstring workgroup;
6047         pstring path;
6048         int err;
6049
6050         if (!context || !context->internal ||
6051             !context->internal->_initialized) {
6052
6053                 errno = EINVAL;
6054                 return -1;
6055
6056         }
6057
6058         if (!fname) {
6059
6060                 errno = EINVAL;
6061                 return -1;
6062
6063         }
6064   
6065         DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
6066
6067         if (smbc_parse_path(context, fname,
6068                             workgroup, sizeof(workgroup),
6069                             server, sizeof(server),
6070                             share, sizeof(share),
6071                             path, sizeof(path),
6072                             user, sizeof(user),
6073                             password, sizeof(password),
6074                             NULL, 0)) {
6075                 errno = EINVAL;
6076                 return -1;
6077         }
6078
6079         if (user[0] == (char)0) fstrcpy(user, context->user);
6080
6081         srv = smbc_server(context, True,
6082                           server, share, workgroup, user, password);
6083
6084         if (!srv) {
6085
6086                 return -1;  /* errno set by smbc_server */
6087
6088         }
6089
6090         if ((err = cli_printjob_del(srv->cli, id)) != 0) {
6091
6092                 if (err < 0)
6093                         errno = smbc_errno(context, srv->cli);
6094                 else if (err == ERRnosuchprintjob)
6095                         errno = EINVAL;
6096                 return -1;
6097
6098         }
6099
6100         return 0;
6101
6102 }
6103
6104 /*
6105  * Get a new empty handle to fill in with your own info 
6106  */
6107 SMBCCTX *
6108 smbc_new_context(void)
6109 {
6110         SMBCCTX *context;
6111
6112         context = SMB_MALLOC_P(SMBCCTX);
6113         if (!context) {
6114                 errno = ENOMEM;
6115                 return NULL;
6116         }
6117
6118         ZERO_STRUCTP(context);
6119
6120         context->internal = SMB_MALLOC_P(struct smbc_internal_data);
6121         if (!context->internal) {
6122                 SAFE_FREE(context);
6123                 errno = ENOMEM;
6124                 return NULL;
6125         }
6126
6127         ZERO_STRUCTP(context->internal);
6128
6129         
6130         /* ADD REASONABLE DEFAULTS */
6131         context->debug            = 0;
6132         context->timeout          = 20000; /* 20 seconds */
6133
6134         context->options.browse_max_lmb_count      = 3;    /* # LMBs to query */
6135         context->options.urlencode_readdir_entries = False;/* backward compat */
6136         context->options.one_share_per_server      = False;/* backward compat */
6137
6138         context->open                              = smbc_open_ctx;
6139         context->creat                             = smbc_creat_ctx;
6140         context->read                              = smbc_read_ctx;
6141         context->write                             = smbc_write_ctx;
6142         context->close_fn                          = smbc_close_ctx;
6143         context->unlink                            = smbc_unlink_ctx;
6144         context->rename                            = smbc_rename_ctx;
6145         context->lseek                             = smbc_lseek_ctx;
6146         context->stat                              = smbc_stat_ctx;
6147         context->fstat                             = smbc_fstat_ctx;
6148         context->opendir                           = smbc_opendir_ctx;
6149         context->closedir                          = smbc_closedir_ctx;
6150         context->readdir                           = smbc_readdir_ctx;
6151         context->getdents                          = smbc_getdents_ctx;
6152         context->mkdir                             = smbc_mkdir_ctx;
6153         context->rmdir                             = smbc_rmdir_ctx;
6154         context->telldir                           = smbc_telldir_ctx;
6155         context->lseekdir                          = smbc_lseekdir_ctx;
6156         context->fstatdir                          = smbc_fstatdir_ctx;
6157         context->chmod                             = smbc_chmod_ctx;
6158         context->utimes                            = smbc_utimes_ctx;
6159         context->setxattr                          = smbc_setxattr_ctx;
6160         context->getxattr                          = smbc_getxattr_ctx;
6161         context->removexattr                       = smbc_removexattr_ctx;
6162         context->listxattr                         = smbc_listxattr_ctx;
6163         context->open_print_job                    = smbc_open_print_job_ctx;
6164         context->print_file                        = smbc_print_file_ctx;
6165         context->list_print_jobs                   = smbc_list_print_jobs_ctx;
6166         context->unlink_print_job                  = smbc_unlink_print_job_ctx;
6167
6168         context->callbacks.check_server_fn         = smbc_check_server;
6169         context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
6170
6171         smbc_default_cache_functions(context);
6172
6173         return context;
6174 }
6175
6176 /* 
6177  * Free a context
6178  *
6179  * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed 
6180  * and thus you'll be leaking memory if not handled properly.
6181  *
6182  */
6183 int
6184 smbc_free_context(SMBCCTX *context,
6185                   int shutdown_ctx)
6186 {
6187         if (!context) {
6188                 errno = EBADF;
6189                 return 1;
6190         }
6191         
6192         if (shutdown_ctx) {
6193                 SMBCFILE * f;
6194                 DEBUG(1,("Performing aggressive shutdown.\n"));
6195                 
6196                 f = context->internal->_files;
6197                 while (f) {
6198                         context->close_fn(context, f);
6199                         f = f->next;
6200                 }
6201                 context->internal->_files = NULL;
6202
6203                 /* First try to remove the servers the nice way. */
6204                 if (context->callbacks.purge_cached_fn(context)) {
6205                         SMBCSRV * s;
6206                         SMBCSRV * next;
6207                         DEBUG(1, ("Could not purge all servers, "
6208                                   "Nice way shutdown failed.\n"));
6209                         s = context->internal->_servers;
6210                         while (s) {
6211                                 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
6212                                           s, s->cli->fd));
6213                                 cli_shutdown(s->cli);
6214                                 context->callbacks.remove_cached_srv_fn(context,
6215                                                                         s);
6216                                 next = s->next;
6217                                 DLIST_REMOVE(context->internal->_servers, s);
6218                                 SAFE_FREE(s);
6219                                 s = next;
6220                         }
6221                         context->internal->_servers = NULL;
6222                 }
6223         }
6224         else {
6225                 /* This is the polite way */    
6226                 if (context->callbacks.purge_cached_fn(context)) {
6227                         DEBUG(1, ("Could not purge all servers, "
6228                                   "free_context failed.\n"));
6229                         errno = EBUSY;
6230                         return 1;
6231                 }
6232                 if (context->internal->_servers) {
6233                         DEBUG(1, ("Active servers in context, "
6234                                   "free_context failed.\n"));
6235                         errno = EBUSY;
6236                         return 1;
6237                 }
6238                 if (context->internal->_files) {
6239                         DEBUG(1, ("Active files in context, "
6240                                   "free_context failed.\n"));
6241                         errno = EBUSY;
6242                         return 1;
6243                 }               
6244         }
6245
6246         /* Things we have to clean up */
6247         SAFE_FREE(context->workgroup);
6248         SAFE_FREE(context->netbios_name);
6249         SAFE_FREE(context->user);
6250         
6251         DEBUG(3, ("Context %p succesfully freed\n", context));
6252         SAFE_FREE(context->internal);
6253         SAFE_FREE(context);
6254         return 0;
6255 }
6256
6257
6258 /*
6259  * Each time the context structure is changed, we have binary backward
6260  * compatibility issues.  Instead of modifying the public portions of the
6261  * context structure to add new options, instead, we put them in the internal
6262  * portion of the context structure and provide a set function for these new
6263  * options.
6264  */
6265 void
6266 smbc_option_set(SMBCCTX *context,
6267                 char *option_name,
6268                 ... /* option_value */)
6269 {
6270         va_list ap;
6271         union {
6272                 BOOL b;
6273                 smbc_get_auth_data_with_context_fn auth_fn;
6274                 void *v;
6275         } option_value;
6276
6277         va_start(ap, option_name);
6278
6279         if (strcmp(option_name, "debug_to_stderr") == 0) {
6280                 /*
6281                  * Log to standard error instead of standard output.
6282                  */
6283                 option_value.b = (BOOL) va_arg(ap, int);
6284                 context->internal->_debug_stderr = option_value.b;
6285
6286         } else if (strcmp(option_name, "full_time_names") == 0) {
6287                 /*
6288                  * Use new-style time attribute names, e.g. WRITE_TIME rather
6289                  * than the old-style names such as M_TIME.  This allows also
6290                  * setting/getting CREATE_TIME which was previously
6291                  * unimplemented.  (Note that the old C_TIME was supposed to
6292                  * be CHANGE_TIME but was confused and sometimes referred to
6293                  * CREATE_TIME.)
6294                  */
6295                 option_value.b = (BOOL) va_arg(ap, int);
6296                 context->internal->_full_time_names = option_value.b;
6297
6298         } else if (strcmp(option_name, "auth_function") == 0) {
6299                 /*
6300                  * Use the new-style authentication function which includes
6301                  * the context.
6302                  */
6303                 option_value.auth_fn =
6304                         va_arg(ap, smbc_get_auth_data_with_context_fn);
6305                 context->internal->_auth_fn_with_context =
6306                         option_value.auth_fn;
6307         } else if (strcmp(option_name, "user_data") == 0) {
6308                 /*
6309                  * Save a user data handle which may be retrieved by the user
6310                  * with smbc_option_get()
6311                  */
6312                 option_value.v = va_arg(ap, void *);
6313                 context->internal->_user_data = option_value.v;
6314         }
6315
6316         va_end(ap);
6317 }
6318
6319
6320 /*
6321  * Retrieve the current value of an option
6322  */
6323 void *
6324 smbc_option_get(SMBCCTX *context,
6325                 char *option_name)
6326 {
6327         if (strcmp(option_name, "debug_stderr") == 0) {
6328                 /*
6329                  * Log to standard error instead of standard output.
6330                  */
6331 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6332                 return (void *) (intptr_t) context->internal->_debug_stderr;
6333 #else
6334                 return (void *) context->internal->_debug_stderr;
6335 #endif
6336         } else if (strcmp(option_name, "full_time_names") == 0) {
6337                 /*
6338                  * Use new-style time attribute names, e.g. WRITE_TIME rather
6339                  * than the old-style names such as M_TIME.  This allows also
6340                  * setting/getting CREATE_TIME which was previously
6341                  * unimplemented.  (Note that the old C_TIME was supposed to
6342                  * be CHANGE_TIME but was confused and sometimes referred to
6343                  * CREATE_TIME.)
6344                  */
6345 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6346                 return (void *) (intptr_t) context->internal->_full_time_names;
6347 #else
6348                 return (void *) context->internal->_full_time_names;
6349 #endif
6350
6351         } else if (strcmp(option_name, "auth_function") == 0) {
6352                 /*
6353                  * Use the new-style authentication function which includes
6354                  * the context.
6355                  */
6356                 return (void *) context->internal->_auth_fn_with_context;
6357         } else if (strcmp(option_name, "user_data") == 0) {
6358                 /*
6359                  * Save a user data handle which may be retrieved by the user
6360                  * with smbc_option_get()
6361                  */
6362                 return context->internal->_user_data;
6363         }
6364
6365         return NULL;
6366 }
6367
6368
6369 /*
6370  * Initialise the library etc 
6371  *
6372  * We accept a struct containing handle information.
6373  * valid values for info->debug from 0 to 100,
6374  * and insist that info->fn must be non-null.
6375  */
6376 SMBCCTX *
6377 smbc_init_context(SMBCCTX *context)
6378 {
6379         pstring conf;
6380         int pid;
6381         char *user = NULL;
6382         char *home = NULL;
6383
6384         if (!context || !context->internal) {
6385                 errno = EBADF;
6386                 return NULL;
6387         }
6388
6389         /* Do not initialise the same client twice */
6390         if (context->internal->_initialized) { 
6391                 return 0;
6392         }
6393
6394         if ((!context->callbacks.auth_fn &&
6395              !context->internal->_auth_fn_with_context) ||
6396             context->debug < 0 ||
6397             context->debug > 100) {
6398
6399                 errno = EINVAL;
6400                 return NULL;
6401
6402         }
6403
6404         if (!smbc_initialized) {
6405                 /*
6406                  * Do some library-wide intializations the first time we get
6407                  * called
6408                  */
6409                 BOOL conf_loaded = False;
6410
6411                 /* Set this to what the user wants */
6412                 DEBUGLEVEL = context->debug;
6413                 
6414                 load_case_tables();
6415
6416                 setup_logging("libsmbclient", True);
6417                 if (context->internal->_debug_stderr) {
6418                         dbf = x_stderr;
6419                         x_setbuf(x_stderr, NULL);
6420                 }
6421
6422                 /* Here we would open the smb.conf file if needed ... */
6423                 
6424                 in_client = True; /* FIXME, make a param */
6425
6426                 home = getenv("HOME");
6427                 if (home) {
6428                         slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
6429                         if (lp_load(conf, True, False, False, True)) {
6430                                 conf_loaded = True;
6431                         } else {
6432                                 DEBUG(5, ("Could not load config file: %s\n",
6433                                           conf));
6434                         }
6435                 }
6436  
6437                 if (!conf_loaded) {
6438                         /*
6439                          * Well, if that failed, try the dyn_CONFIGFILE
6440                          * Which points to the standard locn, and if that
6441                          * fails, silently ignore it and use the internal
6442                          * defaults ...
6443                          */
6444
6445                         if (!lp_load(dyn_CONFIGFILE, True, False, False, False)) {
6446                                 DEBUG(5, ("Could not load config file: %s\n",
6447                                           dyn_CONFIGFILE));
6448                         } else if (home) {
6449                                 /*
6450                                  * We loaded the global config file.  Now lets
6451                                  * load user-specific modifications to the
6452                                  * global config.
6453                                  */
6454                                 slprintf(conf, sizeof(conf),
6455                                          "%s/.smb/smb.conf.append", home);
6456                                 if (!lp_load(conf, True, False, False, False)) {
6457                                         DEBUG(10,
6458                                               ("Could not append config file: "
6459                                                "%s\n",
6460                                                conf));
6461                                 }
6462                         }
6463                 }
6464
6465                 load_interfaces();  /* Load the list of interfaces ... */
6466                 
6467                 reopen_logs();  /* Get logging working ... */
6468         
6469                 /* 
6470                  * Block SIGPIPE (from lib/util_sock.c: write())  
6471                  * It is not needed and should not stop execution 
6472                  */
6473                 BlockSignals(True, SIGPIPE);
6474                 
6475                 /* Done with one-time initialisation */
6476                 smbc_initialized = 1; 
6477
6478         }
6479         
6480         if (!context->user) {
6481                 /*
6482                  * FIXME: Is this the best way to get the user info? 
6483                  */
6484                 user = getenv("USER");
6485                 /* walk around as "guest" if no username can be found */
6486                 if (!user) context->user = SMB_STRDUP("guest");
6487                 else context->user = SMB_STRDUP(user);
6488         }
6489
6490         if (!context->netbios_name) {
6491                 /*
6492                  * We try to get our netbios name from the config. If that
6493                  * fails we fall back on constructing our netbios name from
6494                  * our hostname etc
6495                  */
6496                 if (global_myname()) {
6497                         context->netbios_name = SMB_STRDUP(global_myname());
6498                 }
6499                 else {
6500                         /*
6501                          * Hmmm, I want to get hostname as well, but I am too
6502                          * lazy for the moment
6503                          */
6504                         pid = sys_getpid();
6505                         context->netbios_name = (char *)SMB_MALLOC(17);
6506                         if (!context->netbios_name) {
6507                                 errno = ENOMEM;
6508                                 return NULL;
6509                         }
6510                         slprintf(context->netbios_name, 16,
6511                                  "smbc%s%d", context->user, pid);
6512                 }
6513         }
6514
6515         DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
6516
6517         if (!context->workgroup) {
6518                 if (lp_workgroup()) {
6519                         context->workgroup = SMB_STRDUP(lp_workgroup());
6520                 }
6521                 else {
6522                         /* TODO: Think about a decent default workgroup */
6523                         context->workgroup = SMB_STRDUP("samba");
6524                 }
6525         }
6526
6527         DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
6528                                         
6529         /* shortest timeout is 1 second */
6530         if (context->timeout > 0 && context->timeout < 1000) 
6531                 context->timeout = 1000;
6532
6533         /*
6534          * FIXME: Should we check the function pointers here? 
6535          */
6536
6537         context->internal->_initialized = True;
6538         
6539         return context;
6540 }
6541
6542
6543 /* Return the verion of samba, and thus libsmbclient */
6544 const char *
6545 smbc_version(void)
6546 {
6547         return samba_version_string();
6548 }