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