r618: Bug #1333. Fix a problem pointed out by coolo where I was trying to ensure
[bbaumbach/samba-autobuild/.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
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26
27 #include "../include/libsmb_internal.h"
28
29 /*
30  * Internal flags for extended attributes
31  */
32
33 /* internal mode values */
34 #define SMBC_XATTR_MODE_ADD          1
35 #define SMBC_XATTR_MODE_REMOVE       2
36 #define SMBC_XATTR_MODE_REMOVE_ALL   3
37 #define SMBC_XATTR_MODE_SET          4
38 #define SMBC_XATTR_MODE_CHOWN        5
39 #define SMBC_XATTR_MODE_CHGRP        6
40
41 #define CREATE_ACCESS_READ      READ_CONTROL_ACCESS
42
43 /*We should test for this in configure ... */
44 #ifndef ENOTSUP
45 #define ENOTSUP EOPNOTSUPP
46 #endif
47
48 /*
49  * Functions exported by libsmb_cache.c that we need here
50  */
51 int smbc_default_cache_functions(SMBCCTX *context);
52
53 /* 
54  * check if an element is part of the list. 
55  * FIXME: Does not belong here !  
56  * Can anyone put this in a macro in dlinklist.h ?
57  * -- Tom
58  */
59 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
60         if (!p || !list) return False;
61         do {
62                 if (p == list) return True;
63                 list = list->next;
64         } while (list);
65         return False;
66 }
67
68 extern BOOL in_client;
69
70 /*
71  * Is the logging working / configfile read ? 
72  */
73 static int smbc_initialized = 0;
74
75 static int 
76 hex2int( unsigned int _char )
77 {
78     if ( _char >= 'A' && _char <='F')
79         return _char - 'A' + 10;
80     if ( _char >= 'a' && _char <='f')
81         return _char - 'a' + 10;
82     if ( _char >= '0' && _char <='9')
83         return _char - '0';
84     return -1;
85 }
86
87 static void 
88 decode_urlpart(char *segment, size_t sizeof_segment)
89 {
90     int old_length = strlen(segment);
91     int new_length = 0;
92     int new_length2 = 0;
93     int i = 0;
94     pstring new_segment;
95     char *new_usegment = 0;
96
97     if ( !old_length ) {
98         return;
99     }
100
101     /* make a copy of the old one */
102     new_usegment = (char*)malloc( old_length * 3 + 1 );
103
104     while( i < old_length ) {
105         int bReencode = False;
106         unsigned char character = segment[ i++ ];
107         if ((character <= ' ') || (character > 127))
108             bReencode = True;
109
110         new_usegment [ new_length2++ ] = character;
111         if (character == '%' ) {
112             int a = i+1 < old_length ? hex2int( segment[i] ) : -1;
113             int b = i+1 < old_length ? hex2int( segment[i+1] ) : -1;
114             if ((a == -1) || (b == -1)) { /* Only replace if sequence is valid */
115                 /* Contains stray %, make sure to re-encode! */
116                 bReencode = True;
117             } else {
118                 /* Valid %xx sequence */
119                 character = a * 16 + b; /* Replace with value of %dd */
120                 if (!character)
121                     break; /* Stop at %00 */
122
123                 new_usegment [ new_length2++ ] = (unsigned char) segment[i++];
124                 new_usegment [ new_length2++ ] = (unsigned char) segment[i++];
125             }
126         }
127         if (bReencode) {
128             unsigned int c = character / 16;
129             new_length2--;
130             new_usegment [ new_length2++ ] = '%';
131
132             c += (c > 9) ? ('A' - 10) : '0';
133             new_usegment[ new_length2++ ] = c;
134
135             c = character % 16;
136             c += (c > 9) ? ('A' - 10) : '0';
137             new_usegment[ new_length2++ ] = c;
138         }
139
140         new_segment [ new_length++ ] = character;
141     }
142     new_segment [ new_length ] = 0;
143
144     free(new_usegment);
145
146     /* realloc it with unix charset */
147     pull_utf8_allocate(&new_usegment, new_segment);
148
149     /* this assumes (very safely) that removing %aa sequences
150        only shortens the string */
151     strncpy(segment, new_usegment, sizeof_segment);
152
153     free(new_usegment);
154 }
155
156 /*
157  * Function to parse a path and turn it into components
158  *
159  * The general format of an SMB URI is explain in Christopher Hertel's CIFS
160  * book, at http://ubiqx.org/cifs/Appendix-D.html.  We accept a subset of the
161  * general format ("smb:" only; we do not look for "cifs:"), and expand on
162  * what he calls "context", herein called "options" to avoid conflict with the
163  * SMBCCTX context used throughout this library.  We add the "mb" keyword
164  * which applies as follows:
165  *
166  *
167  * We accept:
168  *  smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
169  *
170  * Meaning of URLs:
171  *
172  * smb://           show all workgroups known by the first master browser found
173  * smb://?mb=.any   same as smb:// (i.e. without any options)
174  *
175  * smb://?mb=.all   show all workgroups known by every master browser found.
176  *                  Why might you want this?  In an "appliance" application
177  *                  where the workgroup/domain being used on the local network
178  *                  is not known ahead of time, but where one wanted to
179  *                  provide network services via samba, a unique workgroup
180  *                  could be used.  However, when the appliance is first
181  *                  started, the local samba instance's master browser has not
182  *                  synchronized with the other master browser(s) on the
183  *                  network (and might not synchronize for 12 minutes) and
184  *                  therefore is not aware of the workgroup/ domain names
185  *                  available on the network.  This option may be used to
186  *                  overcome the problem of a libsmbclient application
187  *                  arbitrarily selecting the local (still ignorant) master
188  *                  browser to obtain its list of workgroups/domains and
189  *                  getting back a practically emmpty list.  By requesting
190  *                  the list of workgroups/domains from each found master
191  *                  browser on the local network, a complete list of
192  *                  workgroups/domains can be built.
193  *
194  * smb://?mb=name   NOT YET IMPLEMENTED -- show all workgroups known by the
195  *                  master browser whose name is "name"
196  *
197  * smb://name/      if name<1D> or name<1B> exists, list servers in
198  *                  workgroup, else, if name<20> exists, list all shares
199  *                  for server ...
200  *
201  * If "options" are provided, this function returns the entire option list as
202  * a string, for later parsing by the caller.
203  */
204
205 static const char *smbc_prefix = "smb:";
206
207 static int
208 smbc_parse_path(SMBCCTX *context,
209                 const char *fname,
210                 char *server, int server_len,
211                 char *share, int share_len,
212                 char *path, int path_len,
213                 char *user, int user_len,
214                 char *password, int password_len,
215                 char *options, int options_len)
216 {
217         static pstring s;
218         pstring userinfo;
219         const char *p;
220         char *q, *r;
221         int len;
222
223         server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
224         if (options != NULL && options_len > 0) {
225                 options[0] = (char)0;
226         }
227         pstrcpy(s, fname);
228
229         /* see if it has the right prefix */
230         len = strlen(smbc_prefix);
231         if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
232                 return -1; /* What about no smb: ? */
233         }
234
235         p = s + len;
236
237         /* Watch the test below, we are testing to see if we should exit */
238
239         if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
240
241                 DEBUG(1, ("Invalid path (does not begin with smb://"));
242                 return -1;
243
244         }
245
246         p += 2;  /* Skip the double slash */
247
248         /* See if any options were specified */
249         if ( (q = strrchr(p, '?')) != NULL ) {
250                 /* There are options.  Null terminate here and point to them */
251                 *q++ = '\0';
252                 
253                 DEBUG(4, ("Found options '%s'", q));
254
255                 /* Copy the options */
256                 if (options != NULL && options_len > 0) {
257                         safe_strcpy(options, q, options_len - 1);
258                 }
259         }
260
261         if (*p == (char)0)
262             goto decoding;
263
264         if (*p == '/') {
265
266                 strncpy(server, context->workgroup, 
267                         (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
268                 return 0;
269                 
270         }
271
272         /*
273          * ok, its for us. Now parse out the server, share etc. 
274          *
275          * However, we want to parse out [[domain;]user[:password]@] if it
276          * exists ...
277          */
278
279         /* check that '@' occurs before '/', if '/' exists at all */
280         q = strchr_m(p, '@');
281         r = strchr_m(p, '/');
282         if (q && (!r || q < r)) {
283                 pstring username, passwd, domain;
284                 const char *u = userinfo;
285
286                 next_token(&p, userinfo, "@", sizeof(fstring));
287
288                 username[0] = passwd[0] = domain[0] = 0;
289
290                 if (strchr_m(u, ';')) {
291       
292                         next_token(&u, domain, ";", sizeof(fstring));
293
294                 }
295
296                 if (strchr_m(u, ':')) {
297
298                         next_token(&u, username, ":", sizeof(fstring));
299
300                         pstrcpy(passwd, u);
301
302                 }
303                 else {
304
305                         pstrcpy(username, u);
306
307                 }
308
309                 if (username[0])
310                         strncpy(user, username, user_len);  /* FIXME, domain */
311
312                 if (passwd[0])
313                         strncpy(password, passwd, password_len);
314
315         }
316
317         if (!next_token(&p, server, "/", sizeof(fstring))) {
318
319                 return -1;
320
321         }
322
323         if (*p == (char)0) goto decoding;  /* That's it ... */
324   
325         if (!next_token(&p, share, "/", sizeof(fstring))) {
326
327                 return -1;
328
329         }
330
331         safe_strcpy(path, p, path_len - 1);
332
333         all_string_sub(path, "/", "\\", 0);
334
335  decoding:
336         decode_urlpart(path, path_len);
337         decode_urlpart(server, server_len);
338         decode_urlpart(share, share_len);
339         decode_urlpart(user, user_len);
340         decode_urlpart(password, password_len);
341
342         return 0;
343 }
344
345 /*
346  * Verify that the options specified in a URL are valid
347  */
348 static int smbc_check_options(char *server, char *share, char *path, char *options)
349 {
350         DEBUG(4, ("smbc_check_options(): server='%s' share='%s' path='%s' options='%s'\n", server, share, path, options));
351
352         /* No options at all is always ok */
353         if (! *options) return 0;
354
355         /*
356          * For right now, we only support a very few options possibilities.
357          * No options are supported if server, share, or path are not empty.
358          * If all are empty, then we support the following two choices right
359          * now:
360          *
361          *   mb=.any
362          *   mb=.all
363          */
364         if ((*server || *share || *path) && *options) {
365                 /* Invalid: options provided with server, share, or path */
366                 DEBUG(1, ("Found unsupported options (%s) with non-empty server, share, or path\n", options));
367                 return -1;
368         }
369
370         if (strcmp(options, "mb=.any") != 0 &&
371             strcmp(options, "mb=.all") != 0) {
372                 DEBUG(1, ("Found unsupported options (%s)\n", options));
373                 return -1;
374         }
375
376         return 0;
377 }
378
379 /*
380  * Convert an SMB error into a UNIX error ...
381  */
382 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
383 {
384         int ret = cli_errno(c);
385         
386         if (cli_is_dos_error(c)) {
387                 uint8 eclass;
388                 uint32 ecode;
389
390                 cli_dos_error(c, &eclass, &ecode);
391                 
392                 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n", 
393                          (int)eclass, (int)ecode, (int)ecode, ret));
394         } else {
395                 NTSTATUS status;
396
397                 status = cli_nt_error(c);
398
399                 DEBUG(3,("smbc errno %s -> %d\n",
400                          nt_errstr(status), ret));
401         }
402
403         return ret;
404 }
405
406 /* 
407  * Check a server_fd.
408  * returns 0 if the server is in shape. Returns 1 on error 
409  * 
410  * Also useable outside libsmbclient to enable external cache
411  * to do some checks too.
412  */
413 int smbc_check_server(SMBCCTX * context, SMBCSRV * server) 
414 {
415         if ( send_keepalive(server->cli.fd) == False )
416                 return 1;
417
418         /* connection is ok */
419         return 0;
420 }
421
422 /* 
423  * Remove a server from the cached server list it's unused.
424  * On success, 0 is returned. 1 is returned if the server could not be removed.
425  * 
426  * Also useable outside libsmbclient
427  */
428 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
429 {
430         SMBCFILE * file;
431
432         /* are we being fooled ? */
433         if (!context || !context->internal ||
434             !context->internal->_initialized || !srv) return 1;
435
436         
437         /* Check all open files/directories for a relation with this server */
438         for (file = context->internal->_files; file; file=file->next) {
439                 if (file->srv == srv) {
440                         /* Still used */
441                         DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n", 
442                                   srv, file));
443                         return 1;
444                 }
445         }
446
447         DLIST_REMOVE(context->internal->_servers, srv);
448
449         cli_shutdown(&srv->cli);
450
451         DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
452
453         context->callbacks.remove_cached_srv_fn(context, srv);
454         
455         SAFE_FREE(srv);
456         
457         return 0;
458 }
459
460 SMBCSRV *find_server(SMBCCTX *context,
461                      const char *server,
462                      const char *share,
463                      fstring workgroup,
464                      fstring username,
465                      fstring password)
466 {
467         SMBCSRV *srv;
468         int auth_called = 0;
469         
470  check_server_cache:
471
472         srv = context->callbacks.get_cached_srv_fn(context, server, share, 
473                                                    workgroup, username);
474         
475         if (!auth_called && !srv && (!username[0] || !password[0])) {
476                 context->callbacks.auth_fn(server, share,
477                                            workgroup, sizeof(fstring),
478                                            username, sizeof(fstring),
479                                            password, sizeof(fstring));
480                 /*
481                  * However, smbc_auth_fn may have picked up info relating to
482                  * an existing connection, so try for an existing connection
483                  * again ...
484                  */
485                 auth_called = 1;
486                 goto check_server_cache;
487                 
488         }
489         
490         if (srv) {
491                 if (context->callbacks.check_server_fn(context, srv)) {
492                         /*
493                          * This server is no good anymore 
494                          * Try to remove it and check for more possible
495                          * servers in the cache
496                          */
497                         if (context->callbacks.remove_unused_server_fn(context,
498                                                                        srv)) { 
499                                 /*
500                                  * We could not remove the server completely,
501                                  * remove it from the cache so we will not get
502                                  * it again. It will be removed when the last
503                                  * file/dir is closed.
504                                  */
505                                 context->callbacks.remove_cached_srv_fn(context,
506                                                                         srv);
507                         }
508                         
509                         /*
510                          * Maybe there are more cached connections to this
511                          * server
512                          */
513                         goto check_server_cache; 
514                 }
515                 return srv;
516         }
517
518         return NULL;
519 }
520
521 /*
522  * Connect to a server, possibly on an existing connection
523  *
524  * Here, what we want to do is: If the server and username
525  * match an existing connection, reuse that, otherwise, establish a 
526  * new connection.
527  *
528  * If we have to create a new connection, call the auth_fn to get the
529  * info we need, unless the username and password were passed in.
530  */
531
532 SMBCSRV *smbc_server(SMBCCTX *context,
533                      const char *server, const char *share, 
534                      fstring workgroup, fstring username, 
535                      fstring password)
536 {
537         SMBCSRV *srv=NULL;
538         struct cli_state c;
539         struct nmb_name called, calling;
540         const char *server_n = server;
541         pstring ipenv;
542         struct in_addr ip;
543         int tried_reverse = 0;
544   
545         zero_ip(&ip);
546         ZERO_STRUCT(c);
547
548         if (server[0] == 0) {
549                 errno = EPERM;
550                 return NULL;
551         }
552
553         srv = find_server(context, server, share,
554                           workgroup, username, password);
555         if (srv)
556                 return srv;
557
558         make_nmb_name(&calling, context->netbios_name, 0x0);
559         make_nmb_name(&called , server, 0x20);
560
561         DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
562   
563 #if 0 /* djl: obsolete code?  neither group nor p is used beyond here */
564         if ((p=strchr_m(server_n,'#')) && 
565             (strcmp(p+1,"1D")==0 || strcmp(p+1,"01")==0)) {
566     
567                 fstrcpy(group, server_n);
568                 p = strchr_m(group,'#');
569                 *p = 0;
570                 
571         }
572 #endif
573
574         DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
575
576  again:
577         slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
578
579         zero_ip(&ip);
580
581         /* have to open a new connection */
582         if (!cli_initialise(&c)) {
583                 errno = ENOMEM;
584                 return NULL;
585         }
586
587         c.timeout = context->timeout;
588
589         /* Force use of port 139 for first try, so browse lists can work */
590         c.port = 139;
591
592         if (!cli_connect(&c, server_n, &ip)) {
593                 /*
594                  * Port 139 connection failed.  Try port 445 to handle
595                  * connections to newer (e.g. XP) hosts with NetBIOS disabled.
596                  */
597                 c.port = 445;
598                 if (!cli_connect(&c, server_n, &ip)) {
599                         errno = ENETUNREACH;
600                         return NULL;
601                 }
602         }
603
604         if (!cli_session_request(&c, &calling, &called)) {
605                 cli_shutdown(&c);
606                 if (strcmp(called.name, "*SMBSERVER")) {
607                         make_nmb_name(&called , "*SMBSERVER", 0x20);
608                         goto again;
609                 }
610                 else {  /* Try one more time, but ensure we don't loop */
611
612                   /* Only try this if server is an IP address ... */
613
614                   if (is_ipaddress(server) && !tried_reverse) {
615                     fstring remote_name;
616                     struct in_addr rem_ip;
617
618                     if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
619                       DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
620                       errno = ENOENT;
621                       return NULL;
622                     }
623
624                     tried_reverse++; /* Yuck */
625
626                     if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
627                       make_nmb_name(&called, remote_name, 0x20);
628                       goto again;
629                     }
630
631
632                   }
633                 }
634                 errno = ENOENT;
635                 return NULL;
636         }
637   
638         DEBUG(4,(" session request ok\n"));
639   
640         if (!cli_negprot(&c)) {
641                 cli_shutdown(&c);
642                 errno = ENOENT;
643                 return NULL;
644         }
645
646         if (!cli_session_setup(&c, username, 
647                                password, strlen(password),
648                                password, strlen(password),
649                                workgroup) &&
650             /* try an anonymous login if it failed */
651             !cli_session_setup(&c, "", "", 1,"", 0, workgroup)) {
652                 cli_shutdown(&c);
653                 errno = EPERM;
654                 return NULL;
655         }
656
657         DEBUG(4,(" session setup ok\n"));
658
659         if (!cli_send_tconX(&c, share, "?????",
660                             password, strlen(password)+1)) {
661                 errno = smbc_errno(context, &c);
662                 cli_shutdown(&c);
663                 return NULL;
664         }
665   
666         DEBUG(4,(" tconx ok\n"));
667   
668         /*
669          * Ok, we have got a nice connection
670          * Let's find a free server_fd 
671          */
672
673         srv = (SMBCSRV *)malloc(sizeof(*srv));
674         if (!srv) {
675                 errno = ENOMEM;
676                 goto failed;
677         }
678
679         ZERO_STRUCTP(srv);
680         srv->cli = c;
681         srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
682
683         /* now add it to the cache (internal or external)  */
684         /* Let the cache function set errno if it wants to */
685         errno = 0;
686         if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
687                 int saved_errno = errno;
688                 DEBUG(3, (" Failed to add server to cache\n"));
689                 errno = saved_errno;
690                 if (errno == 0) {
691                         errno = ENOMEM;
692                 }
693                 goto failed;
694         }
695         
696         DEBUG(2, ("Server connect ok: //%s/%s: %p\n", 
697                   server, share, srv));
698
699         DLIST_ADD(context->internal->_servers, srv);
700         return srv;
701
702  failed:
703         cli_shutdown(&c);
704         if (!srv) return NULL;
705   
706         SAFE_FREE(srv);
707         return NULL;
708 }
709
710 /*
711  * Connect to a server for getting/setting attributes, possibly on an existing
712  * connection.  This works similarly to smbc_server().
713  */
714 SMBCSRV *smbc_attr_server(SMBCCTX *context,
715                           const char *server, const char *share, 
716                           fstring workgroup,
717                           fstring username, fstring password,
718                           POLICY_HND *pol)
719 {
720         struct in_addr ip;
721         struct cli_state *ipc_cli;
722         NTSTATUS nt_status;
723         SMBCSRV *ipc_srv=NULL;
724
725         /*
726          * See if we've already created this special connection.  Reference
727          * our "special" share name 'IPC$$'.
728          */
729         ipc_srv = find_server(context, server, "IPC$$",
730                               workgroup, username, password);
731         if (!ipc_srv) {
732
733                 /* We didn't find a cached connection.  Get the password */
734                 if (*password == '\0') {
735                         /* ... then retrieve it now. */
736                         context->callbacks.auth_fn(server, share,
737                                                    workgroup, sizeof(fstring),
738                                                    username, sizeof(fstring),
739                                                    password, sizeof(fstring));
740                 }
741         
742                 zero_ip(&ip);
743                 nt_status = cli_full_connection(&ipc_cli,
744                                                 global_myname(), server, 
745                                                 &ip, 0, "IPC$", "?????",  
746                                                 username, workgroup,
747                                                 password, 0,
748                                                 Undefined, NULL);
749                 if (! NT_STATUS_IS_OK(nt_status)) {
750                         DEBUG(1,("cli_full_connection failed! (%s)\n",
751                                  nt_errstr(nt_status)));
752                         errno = ENOTSUP;
753                         return NULL;
754                 }
755
756                 if (!cli_nt_session_open(ipc_cli, PI_LSARPC)) {
757                         DEBUG(1, ("cli_nt_session_open fail!\n"));
758                         errno = ENOTSUP;
759                         cli_shutdown(ipc_cli);
760                         return NULL;
761                 }
762
763                 /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
764                    but NT sends 0x2000000 so we might as well do it too. */
765         
766                 nt_status = cli_lsa_open_policy(ipc_cli,
767                                                 ipc_cli->mem_ctx,
768                                                 True, 
769                                                 GENERIC_EXECUTE_ACCESS,
770                                                 pol);
771         
772                 if (!NT_STATUS_IS_OK(nt_status)) {
773                         errno = smbc_errno(context, ipc_cli);
774                         cli_shutdown(ipc_cli);
775                         return NULL;
776                 }
777
778                 ipc_srv = (SMBCSRV *)malloc(sizeof(*ipc_srv));
779                 if (!ipc_srv) {
780                         errno = ENOMEM;
781                         cli_shutdown(ipc_cli);
782                         return NULL;
783                 }
784
785                 ZERO_STRUCTP(ipc_srv);
786                 ipc_srv->cli = *ipc_cli;
787
788                 free(ipc_cli);
789
790                 /* now add it to the cache (internal or external) */
791
792                 errno = 0;      /* let cache function set errno if it likes */
793                 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
794                                                          server,
795                                                          "IPC$$",
796                                                          workgroup,
797                                                          username)) {
798                         DEBUG(3, (" Failed to add server to cache\n"));
799                         if (errno == 0) {
800                                 errno = ENOMEM;
801                         }
802                         cli_shutdown(&ipc_srv->cli);
803                         free(ipc_srv);
804                         return NULL;
805                 }
806
807                 DLIST_ADD(context->internal->_servers, ipc_srv);
808         }
809
810         return ipc_srv;
811 }
812
813 /*
814  * Routine to open() a file ...
815  */
816
817 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
818 {
819         fstring server, share, user, password, workgroup;
820         pstring path;
821         SMBCSRV *srv   = NULL;
822         SMBCFILE *file = NULL;
823         int fd;
824
825         if (!context || !context->internal ||
826             !context->internal->_initialized) {
827
828                 errno = EINVAL;  /* Best I can think of ... */
829                 return NULL;
830
831         }
832
833         if (!fname) {
834
835                 errno = EINVAL;
836                 return NULL;
837
838         }
839
840         if (smbc_parse_path(context, fname,
841                             server, sizeof(server),
842                             share, sizeof(share),
843                             path, sizeof(path),
844                             user, sizeof(user),
845                             password, sizeof(password),
846                             NULL, 0)) {
847                 errno = EINVAL;
848                 return NULL;
849         }
850
851         if (user[0] == (char)0) fstrcpy(user, context->user);
852
853         fstrcpy(workgroup, context->workgroup);
854
855         srv = smbc_server(context, server, share, workgroup, user, password);
856
857         if (!srv) {
858
859                 if (errno == EPERM) errno = EACCES;
860                 return NULL;  /* smbc_server sets errno */
861     
862         }
863
864         /* Hmmm, the test for a directory is suspect here ... FIXME */
865
866         if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
867     
868                 fd = -1;
869
870         }
871         else {
872           
873                 file = malloc(sizeof(SMBCFILE));
874
875                 if (!file) {
876
877                         errno = ENOMEM;
878                         return NULL;
879
880                 }
881
882                 ZERO_STRUCTP(file);
883
884                 if ((fd = cli_open(&srv->cli, path, flags, DENY_NONE)) < 0) {
885
886                         /* Handle the error ... */
887
888                         SAFE_FREE(file);
889                         errno = smbc_errno(context, &srv->cli);
890                         return NULL;
891
892                 }
893
894                 /* Fill in file struct */
895
896                 file->cli_fd  = fd;
897                 file->fname   = strdup(fname);
898                 file->srv     = srv;
899                 file->offset  = 0;
900                 file->file    = True;
901
902                 DLIST_ADD(context->internal->_files, file);
903                 return file;
904
905         }
906
907         /* Check if opendir needed ... */
908
909         if (fd == -1) {
910                 int eno = 0;
911
912                 eno = smbc_errno(context, &srv->cli);
913                 file = context->opendir(context, fname);
914                 if (!file) errno = eno;
915                 return file;
916
917         }
918
919         errno = EINVAL; /* FIXME, correct errno ? */
920         return NULL;
921
922 }
923
924 /*
925  * Routine to create a file 
926  */
927
928 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
929
930 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
931 {
932
933         if (!context || !context->internal ||
934             !context->internal->_initialized) {
935
936                 errno = EINVAL;
937                 return NULL;
938
939         }
940
941         return smbc_open_ctx(context, path, creat_bits, mode);
942 }
943
944 /*
945  * Routine to read() a file ...
946  */
947
948 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
949 {
950         int ret;
951
952         if (!context || !context->internal ||
953             !context->internal->_initialized) {
954
955                 errno = EINVAL;
956                 return -1;
957
958         }
959
960         DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
961
962         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
963
964                 errno = EBADF;
965                 return -1;
966
967         }
968
969         /* Check that the buffer exists ... */
970
971         if (buf == NULL) {
972
973                 errno = EINVAL;
974                 return -1;
975
976         }
977
978         ret = cli_read(&file->srv->cli, file->cli_fd, buf, file->offset, count);
979
980         if (ret < 0) {
981
982                 errno = smbc_errno(context, &file->srv->cli);
983                 return -1;
984
985         }
986
987         file->offset += ret;
988
989         DEBUG(4, ("  --> %d\n", ret));
990
991         return ret;  /* Success, ret bytes of data ... */
992
993 }
994
995 /*
996  * Routine to write() a file ...
997  */
998
999 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
1000 {
1001         int ret;
1002
1003         if (!context || !context->internal ||
1004             !context->internal->_initialized) {
1005
1006                 errno = EINVAL;
1007                 return -1;
1008
1009         }
1010
1011         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1012
1013                 errno = EBADF;
1014                 return -1;
1015     
1016         }
1017
1018         /* Check that the buffer exists ... */
1019
1020         if (buf == NULL) {
1021
1022                 errno = EINVAL;
1023                 return -1;
1024
1025         }
1026
1027         ret = cli_write(&file->srv->cli, file->cli_fd, 0, buf, file->offset, count);
1028
1029         if (ret <= 0) {
1030
1031                 errno = smbc_errno(context, &file->srv->cli);
1032                 return -1;
1033
1034         }
1035
1036         file->offset += ret;
1037
1038         return ret;  /* Success, 0 bytes of data ... */
1039 }
1040  
1041 /*
1042  * Routine to close() a file ...
1043  */
1044
1045 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
1046 {
1047         SMBCSRV *srv; 
1048
1049         if (!context || !context->internal ||
1050             !context->internal->_initialized) {
1051
1052                 errno = EINVAL;
1053                 return -1;
1054
1055         }
1056
1057         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1058    
1059                 errno = EBADF;
1060                 return -1;
1061
1062         }
1063
1064         /* IS a dir ... */
1065         if (!file->file) {
1066                 
1067                 return context->closedir(context, file);
1068
1069         }
1070
1071         if (!cli_close(&file->srv->cli, file->cli_fd)) {
1072
1073                 DEBUG(3, ("cli_close failed on %s. purging server.\n", 
1074                           file->fname));
1075                 /* Deallocate slot and remove the server 
1076                  * from the server cache if unused */
1077                 errno = smbc_errno(context, &file->srv->cli);  
1078                 srv = file->srv;
1079                 DLIST_REMOVE(context->internal->_files, file);
1080                 SAFE_FREE(file->fname);
1081                 SAFE_FREE(file);
1082                 context->callbacks.remove_unused_server_fn(context, srv);
1083
1084                 return -1;
1085
1086         }
1087
1088         DLIST_REMOVE(context->internal->_files, file);
1089         SAFE_FREE(file->fname);
1090         SAFE_FREE(file);
1091
1092         return 0;
1093 }
1094
1095 /*
1096  * Get info from an SMB server on a file. Use a qpathinfo call first
1097  * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1098  */
1099 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path, 
1100                  uint16 *mode, size_t *size, 
1101                  time_t *c_time, time_t *a_time, time_t *m_time,
1102                  SMB_INO_T *ino)
1103 {
1104
1105         if (!context || !context->internal ||
1106             !context->internal->_initialized) {
1107  
1108                 errno = EINVAL;
1109                 return -1;
1110  
1111         }
1112
1113         DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1114   
1115         if (!srv->no_pathinfo2 &&
1116             cli_qpathinfo2(&srv->cli, path, c_time, a_time, m_time, NULL,
1117                            size, mode, ino)) return True;
1118
1119         /* if this is NT then don't bother with the getatr */
1120         if (srv->cli.capabilities & CAP_NT_SMBS) {
1121                 errno = EPERM;
1122                 return False;
1123         }
1124
1125         if (cli_getatr(&srv->cli, path, mode, size, m_time)) {
1126                 a_time = c_time = m_time;
1127                 srv->no_pathinfo2 = True;
1128                 return True;
1129         }
1130
1131         errno = EPERM;
1132         return False;
1133
1134 }
1135
1136 /*
1137  * Routine to unlink() a file
1138  */
1139
1140 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
1141 {
1142         fstring server, share, user, password, workgroup;
1143         pstring path;
1144         SMBCSRV *srv = NULL;
1145
1146         if (!context || !context->internal ||
1147             !context->internal->_initialized) {
1148
1149                 errno = EINVAL;  /* Best I can think of ... */
1150                 return -1;
1151
1152         }
1153
1154         if (!fname) {
1155
1156                 errno = EINVAL;
1157                 return -1;
1158
1159         }
1160
1161         if (smbc_parse_path(context, fname,
1162                             server, sizeof(server),
1163                             share, sizeof(share),
1164                             path, sizeof(path),
1165                             user, sizeof(user),
1166                             password, sizeof(password),
1167                             NULL, 0)) {
1168                 errno = EINVAL;
1169                 return -1;
1170         }
1171
1172         if (user[0] == (char)0) fstrcpy(user, context->user);
1173
1174         fstrcpy(workgroup, context->workgroup);
1175
1176         srv = smbc_server(context, server, share, workgroup, user, password);
1177
1178         if (!srv) {
1179
1180                 return -1;  /* smbc_server sets errno */
1181
1182         }
1183
1184         /*  if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
1185
1186     int job = smbc_stat_printjob(srv, path, NULL, NULL);
1187     if (job == -1) {
1188
1189       return -1;
1190
1191     }
1192     if ((err = cli_printjob_del(&srv->cli, job)) != 0) {
1193
1194     
1195       return -1;
1196
1197     }
1198     } else */
1199
1200         if (!cli_unlink(&srv->cli, path)) {
1201
1202                 errno = smbc_errno(context, &srv->cli);
1203
1204                 if (errno == EACCES) { /* Check if the file is a directory */
1205
1206                         int saverr = errno;
1207                         size_t size = 0;
1208                         uint16 mode = 0;
1209                         time_t m_time = 0, a_time = 0, c_time = 0;
1210                         SMB_INO_T ino = 0;
1211
1212                         if (!smbc_getatr(context, srv, path, &mode, &size,
1213                                          &c_time, &a_time, &m_time, &ino)) {
1214
1215                                 /* Hmmm, bad error ... What? */
1216
1217                                 errno = smbc_errno(context, &srv->cli);
1218                                 return -1;
1219
1220                         }
1221                         else {
1222
1223                                 if (IS_DOS_DIR(mode))
1224                                         errno = EISDIR;
1225                                 else
1226                                         errno = saverr;  /* Restore this */
1227
1228                         }
1229                 }
1230
1231                 return -1;
1232
1233         }
1234
1235         return 0;  /* Success ... */
1236
1237 }
1238
1239 /*
1240  * Routine to rename() a file
1241  */
1242
1243 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname, 
1244                            SMBCCTX *ncontext, const char *nname)
1245 {
1246         fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
1247         pstring path1, path2;
1248         SMBCSRV *srv = NULL;
1249
1250         if (!ocontext || !ncontext || 
1251             !ocontext->internal || !ncontext->internal ||
1252             !ocontext->internal->_initialized || 
1253             !ncontext->internal->_initialized) {
1254
1255                 errno = EINVAL;  /* Best I can think of ... */
1256                 return -1;
1257
1258         }
1259         
1260         if (!oname || !nname) {
1261
1262                 errno = EINVAL;
1263                 return -1;
1264
1265         }
1266         
1267         DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1268
1269         smbc_parse_path(ocontext, oname,
1270                         server1, sizeof(server1),
1271                         share1, sizeof(share1),
1272                         path1, sizeof(path1),
1273                         user1, sizeof(user1),
1274                         password1, sizeof(password1),
1275                         NULL, 0);
1276
1277         if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1278
1279         smbc_parse_path(ncontext, nname,
1280                         server2, sizeof(server2),
1281                         share2, sizeof(share2),
1282                         path2, sizeof(path2),
1283                         user2, sizeof(user2),
1284                         password2, sizeof(password2),
1285                         NULL, 0);
1286
1287         if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1288
1289         if (strcmp(server1, server2) || strcmp(share1, share2) ||
1290             strcmp(user1, user2)) {
1291
1292                 /* Can't rename across file systems, or users?? */
1293
1294                 errno = EXDEV;
1295                 return -1;
1296
1297         }
1298
1299         fstrcpy(workgroup, ocontext->workgroup);
1300         /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */ 
1301         srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1302         if (!srv) {
1303
1304                 return -1;
1305
1306         }
1307
1308         if (!cli_rename(&srv->cli, path1, path2)) {
1309                 int eno = smbc_errno(ocontext, &srv->cli);
1310
1311                 if (eno != EEXIST ||
1312                     !cli_unlink(&srv->cli, path2) ||
1313                     !cli_rename(&srv->cli, path1, path2)) {
1314
1315                         errno = eno;
1316                         return -1;
1317
1318                 }
1319         }
1320
1321         return 0; /* Success */
1322
1323 }
1324
1325 /*
1326  * A routine to lseek() a file
1327  */
1328
1329 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1330 {
1331         size_t size;
1332
1333         if (!context || !context->internal ||
1334             !context->internal->_initialized) {
1335
1336                 errno = EINVAL;
1337                 return -1;
1338                 
1339         }
1340
1341         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1342
1343                 errno = EBADF;
1344                 return -1;
1345
1346         }
1347
1348         if (!file->file) {
1349
1350                 errno = EINVAL;
1351                 return -1;      /* Can't lseek a dir ... */
1352
1353         }
1354
1355         switch (whence) {
1356         case SEEK_SET:
1357                 file->offset = offset;
1358                 break;
1359
1360         case SEEK_CUR:
1361                 file->offset += offset;
1362                 break;
1363
1364         case SEEK_END:
1365                 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
1366                                    NULL, NULL, NULL)) 
1367                 {
1368                     SMB_BIG_UINT b_size = size;
1369                     if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
1370                                       NULL)) 
1371                     {
1372                         errno = EINVAL;
1373                         return -1;
1374                     } else
1375                         size = b_size;
1376                 }
1377                 file->offset = size + offset;
1378                 break;
1379
1380         default:
1381                 errno = EINVAL;
1382                 break;
1383
1384         }
1385
1386         return file->offset;
1387
1388 }
1389
1390 /* 
1391  * Generate an inode number from file name for those things that need it
1392  */
1393
1394 static
1395 ino_t smbc_inode(SMBCCTX *context, const char *name)
1396 {
1397
1398         if (!context || !context->internal ||
1399             !context->internal->_initialized) {
1400
1401                 errno = EINVAL;
1402                 return -1;
1403
1404         }
1405
1406         if (!*name) return 2; /* FIXME, why 2 ??? */
1407         return (ino_t)str_checksum(name);
1408
1409 }
1410
1411 /*
1412  * Routine to put basic stat info into a stat structure ... Used by stat and
1413  * fstat below.
1414  */
1415
1416 static
1417 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname, size_t size, int mode)
1418 {
1419         
1420         st->st_mode = 0;
1421
1422         if (IS_DOS_DIR(mode)) {
1423                 st->st_mode = SMBC_DIR_MODE;
1424         } else {
1425                 st->st_mode = SMBC_FILE_MODE;
1426         }
1427
1428         if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1429         if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1430         if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1431         if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1432
1433         st->st_size = size;
1434 #ifdef HAVE_STAT_ST_BLKSIZE
1435         st->st_blksize = 512;
1436 #endif
1437 #ifdef HAVE_STAT_ST_BLOCKS
1438         st->st_blocks = (size+511)/512;
1439 #endif
1440         st->st_uid = getuid();
1441         st->st_gid = getgid();
1442
1443         if (IS_DOS_DIR(mode)) {
1444                 st->st_nlink = 2;
1445         } else {
1446                 st->st_nlink = 1;
1447         }
1448
1449         if (st->st_ino == 0) {
1450                 st->st_ino = smbc_inode(context, fname);
1451         }
1452         
1453         return True;  /* FIXME: Is this needed ? */
1454
1455 }
1456
1457 /*
1458  * Routine to stat a file given a name
1459  */
1460
1461 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1462 {
1463         SMBCSRV *srv;
1464         fstring server, share, user, password, workgroup;
1465         pstring path;
1466         time_t m_time = 0, a_time = 0, c_time = 0;
1467         size_t size = 0;
1468         uint16 mode = 0;
1469         SMB_INO_T ino = 0;
1470
1471         if (!context || !context->internal ||
1472             !context->internal->_initialized) {
1473
1474                 errno = EINVAL;  /* Best I can think of ... */
1475                 return -1;
1476     
1477         }
1478
1479         if (!fname) {
1480
1481                 errno = EINVAL;
1482                 return -1;
1483
1484         }
1485   
1486         DEBUG(4, ("smbc_stat(%s)\n", fname));
1487
1488         if (smbc_parse_path(context, fname,
1489                             server, sizeof(server),
1490                             share, sizeof(share),
1491                             path, sizeof(path),
1492                             user, sizeof(user),
1493                             password, sizeof(password),
1494                             NULL, 0)) {
1495                 errno = EINVAL;
1496                 return -1;
1497         }
1498
1499         if (user[0] == (char)0) fstrcpy(user, context->user);
1500
1501         fstrcpy(workgroup, context->workgroup);
1502
1503         srv = smbc_server(context, server, share, workgroup, user, password);
1504
1505         if (!srv) {
1506                 return -1;  /* errno set by smbc_server */
1507         }
1508
1509         if (!smbc_getatr(context, srv, path, &mode, &size, 
1510                          &c_time, &a_time, &m_time, &ino)) {
1511
1512                 errno = smbc_errno(context, &srv->cli);
1513                 return -1;
1514                 
1515         }
1516
1517         st->st_ino = ino;
1518
1519         smbc_setup_stat(context, st, path, size, mode);
1520
1521         st->st_atime = a_time;
1522         st->st_ctime = c_time;
1523         st->st_mtime = m_time;
1524         st->st_dev   = srv->dev;
1525
1526         return 0;
1527
1528 }
1529
1530 /*
1531  * Routine to stat a file given an fd
1532  */
1533
1534 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1535 {
1536         time_t c_time, a_time, m_time;
1537         size_t size;
1538         uint16 mode;
1539         SMB_INO_T ino = 0;
1540
1541         if (!context || !context->internal ||
1542             !context->internal->_initialized) {
1543
1544                 errno = EINVAL;
1545                 return -1;
1546
1547         }
1548
1549         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1550
1551                 errno = EBADF;
1552                 return -1;
1553
1554         }
1555
1556         if (!file->file) {
1557
1558                 return context->fstatdir(context, file, st);
1559
1560         }
1561
1562         if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
1563                            &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
1564             SMB_BIG_UINT b_size = size;
1565             if (!cli_getattrE(&file->srv->cli, file->cli_fd,
1566                           &mode, &b_size, &c_time, &a_time, &m_time)) {
1567
1568                 errno = EINVAL;
1569                 return -1;
1570             } else
1571                 size = b_size;
1572
1573         }
1574
1575         st->st_ino = ino;
1576
1577         smbc_setup_stat(context, st, file->fname, size, mode);
1578
1579         st->st_atime = a_time;
1580         st->st_ctime = c_time;
1581         st->st_mtime = m_time;
1582         st->st_dev = file->srv->dev;
1583
1584         return 0;
1585
1586 }
1587
1588 /*
1589  * Routine to open a directory
1590  * We accept the URL syntax explained in smbc_parse_path(), above.
1591  */
1592
1593 static void smbc_remove_dir(SMBCFILE *dir)
1594 {
1595         struct smbc_dir_list *d,*f;
1596
1597         d = dir->dir_list;
1598         while (d) {
1599
1600                 f = d; d = d->next;
1601
1602                 SAFE_FREE(f->dirent);
1603                 SAFE_FREE(f);
1604
1605         }
1606
1607         dir->dir_list = dir->dir_end = dir->dir_next = NULL;
1608
1609 }
1610
1611 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
1612 {
1613         struct smbc_dirent *dirent;
1614         int size;
1615         char *u_name = NULL, *u_comment = NULL;
1616         size_t u_name_len = 0, u_comment_len = 0;
1617
1618         if (name)
1619             u_name_len = push_utf8_allocate(&u_name, name);
1620         if (comment)
1621             u_comment_len = push_utf8_allocate(&u_comment, comment);
1622
1623         /*
1624          * Allocate space for the dirent, which must be increased by the 
1625          * size of the name and the comment and 1 for the null on the comment.
1626          * The null on the name is already accounted for.
1627          */
1628
1629         size = sizeof(struct smbc_dirent) + u_name_len + u_comment_len + 1;
1630     
1631         dirent = malloc(size);
1632
1633         if (!dirent) {
1634
1635                 dir->dir_error = ENOMEM;
1636                 return -1;
1637
1638         }
1639
1640         ZERO_STRUCTP(dirent);
1641
1642         if (dir->dir_list == NULL) {
1643
1644                 dir->dir_list = malloc(sizeof(struct smbc_dir_list));
1645                 if (!dir->dir_list) {
1646
1647                         SAFE_FREE(dirent);
1648                         dir->dir_error = ENOMEM;
1649                         return -1;
1650
1651                 }
1652                 ZERO_STRUCTP(dir->dir_list);
1653
1654                 dir->dir_end = dir->dir_next = dir->dir_list;
1655         }
1656         else {
1657
1658                 dir->dir_end->next = malloc(sizeof(struct smbc_dir_list));
1659                 
1660                 if (!dir->dir_end->next) {
1661                         
1662                         SAFE_FREE(dirent);
1663                         dir->dir_error = ENOMEM;
1664                         return -1;
1665
1666                 }
1667                 ZERO_STRUCTP(dir->dir_end->next);
1668
1669                 dir->dir_end = dir->dir_end->next;
1670         }
1671
1672         dir->dir_end->next = NULL;
1673         dir->dir_end->dirent = dirent;
1674         
1675         dirent->smbc_type = type;
1676         dirent->namelen = u_name_len;
1677         dirent->commentlen = u_comment_len;
1678         dirent->dirlen = size;
1679   
1680         strncpy(dirent->name, (u_name?u_name:""), dirent->namelen + 1);
1681
1682         dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
1683         strncpy(dirent->comment, (u_comment?u_comment:""), dirent->commentlen + 1);
1684         
1685         SAFE_FREE(u_comment);
1686         SAFE_FREE(u_name);
1687
1688         return 0;
1689
1690 }
1691
1692 static void
1693 list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
1694 {
1695         SMBCFILE *dir = (SMBCFILE *)state;
1696         struct smbc_dir_list *dir_list;
1697         struct smbc_dirent *dirent;
1698         int dirent_type;
1699         int remove = 0;
1700
1701         dirent_type = dir->dir_type;
1702
1703         if (add_dirent(dir, name, comment, dirent_type) < 0) {
1704
1705                 /* An error occurred, what do we do? */
1706                 /* FIXME: Add some code here */
1707         }
1708
1709         /* Point to the one just added */
1710         dirent = dir->dir_end->dirent;
1711
1712         /* See if this was a duplicate */
1713         for (dir_list = dir->dir_list;
1714              dir_list != dir->dir_end;
1715              dir_list = dir_list->next) {
1716                 if (! remove &&
1717                     strcmp(dir_list->dirent->name, dirent->name) == 0) {
1718                         /* Duplicate.  End end of list need to be removed. */
1719                         remove = 1;
1720                 }
1721
1722                 if (remove && dir_list->next == dir->dir_end) {
1723                         /* Found the end of the list.  Remove it. */
1724                         dir->dir_end = dir_list;
1725                         free(dir_list->next);
1726                         dir_list->next = NULL;
1727                         break;
1728                 }
1729         }
1730 }
1731
1732 static void
1733 list_fn(const char *name, uint32 type, const char *comment, void *state)
1734 {
1735         SMBCFILE *dir = (SMBCFILE *)state;
1736         int dirent_type;
1737
1738         /* We need to process the type a little ... */
1739
1740         if (dir->dir_type == SMBC_FILE_SHARE) {
1741                 
1742                 switch (type) {
1743                 case 0: /* Directory tree */
1744                         dirent_type = SMBC_FILE_SHARE;
1745                         break;
1746
1747                 case 1:
1748                         dirent_type = SMBC_PRINTER_SHARE;
1749                         break;
1750
1751                 case 2:
1752                         dirent_type = SMBC_COMMS_SHARE;
1753                         break;
1754
1755                 case 3:
1756                         dirent_type = SMBC_IPC_SHARE;
1757                         break;
1758
1759                 default:
1760                         dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
1761                         break;
1762                 }
1763         }
1764         else dirent_type = dir->dir_type;
1765
1766         if (add_dirent(dir, name, comment, dirent_type) < 0) {
1767
1768                 /* An error occurred, what do we do? */
1769                 /* FIXME: Add some code here */
1770
1771         }
1772 }
1773
1774 static void
1775 dir_list_fn(file_info *finfo, const char *mask, void *state)
1776 {
1777
1778         if (add_dirent((SMBCFILE *)state, finfo->name, "", 
1779                        (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
1780
1781                 /* Handle an error ... */
1782
1783                 /* FIXME: Add some code ... */
1784
1785         } 
1786
1787 }
1788
1789 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
1790 {
1791         fstring server, share, user, password, options;
1792         pstring workgroup;
1793         pstring path;
1794         SMBCSRV *srv  = NULL;
1795         SMBCFILE *dir = NULL;
1796         struct in_addr rem_ip;
1797
1798         if (!context || !context->internal ||
1799             !context->internal->_initialized) {
1800                 DEBUG(4, ("no valid context\n"));
1801                 errno = EINVAL;
1802                 return NULL;
1803
1804         }
1805
1806         if (!fname) {
1807                 DEBUG(4, ("no valid fname\n"));
1808                 errno = EINVAL;
1809                 return NULL;
1810         }
1811
1812         if (smbc_parse_path(context, fname,
1813                             server, sizeof(server),
1814                             share, sizeof(share),
1815                             path, sizeof(path),
1816                             user, sizeof(user),
1817                             password, sizeof(password),
1818                             options, sizeof(options))) {
1819                 DEBUG(4, ("no valid path\n"));
1820                 errno = EINVAL;
1821                 return NULL;
1822         }
1823
1824         DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));
1825
1826         /* Ensure the options are valid */
1827         if (smbc_check_options(server, share, path, options)) {
1828                 DEBUG(4, ("unacceptable options (%s)\n", options));
1829                 errno = EINVAL;
1830                 return NULL;
1831         }
1832
1833         if (user[0] == (char)0) fstrcpy(user, context->user);
1834
1835         pstrcpy(workgroup, context->workgroup);
1836
1837         dir = malloc(sizeof(*dir));
1838
1839         if (!dir) {
1840
1841                 errno = ENOMEM;
1842                 return NULL;
1843
1844         }
1845
1846         ZERO_STRUCTP(dir);
1847
1848         dir->cli_fd   = 0;
1849         dir->fname    = strdup(fname);
1850         dir->srv      = NULL;
1851         dir->offset   = 0;
1852         dir->file     = False;
1853         dir->dir_list = dir->dir_next = dir->dir_end = NULL;
1854
1855         if (server[0] == (char)0 &&
1856             (! *options || strcmp(options, "mb=.any") == 0)) {
1857                 struct in_addr server_ip;
1858                 if (share[0] != (char)0 || path[0] != (char)0) {
1859
1860                         errno = EINVAL;
1861                         if (dir) {
1862                                 SAFE_FREE(dir->fname);
1863                                 SAFE_FREE(dir);
1864                         }
1865                         return NULL;
1866                 }
1867
1868                 /*
1869                  * We have server and share and path empty ... so list the
1870                  * workgroups first try to get the LMB for our workgroup, and
1871                  * if that fails, try the DMB
1872                  */
1873
1874                 pstrcpy(workgroup, lp_workgroup());
1875
1876                 if (!find_master_ip(workgroup, &server_ip)) {
1877                     struct user_auth_info u_info;
1878                     struct cli_state *cli;
1879
1880                     DEBUG(4, ("Unable to find master browser for workgroup %s\n", 
1881                               workgroup));
1882
1883                     /* find the name of the server ... */
1884                     pstrcpy(u_info.username, user);
1885                     pstrcpy(u_info.password, password);
1886
1887                     if (!(cli = get_ipc_connect_master_ip_bcast(workgroup, &u_info))) {
1888                         DEBUG(4, ("Unable to find master browser by "
1889                                   "broadcast\n"));
1890                         errno = ENOENT;
1891                         return NULL;
1892                     }
1893
1894                     fstrcpy(server, cli->desthost);
1895
1896                     cli_shutdown(cli);
1897                 } else {
1898                     /*
1899                      * Do a name status query to find out the name of the
1900                      * master browser.  We use <01><02>__MSBROWSE__<02>#01 if
1901                      * *#00 fails because a domain master browser will not
1902                      * respond to a wildcard query (or, at least, an NT4
1903                      * server acting as the domain master browser will not).
1904                      *
1905                      * We might be able to use ONLY the query on MSBROWSE, but
1906                      * that's not yet been tested with all Windows versions,
1907                      * so until it is, leave the original wildcard query as
1908                      * the first choice and fall back to MSBROWSE if the
1909                      * wildcard query fails.
1910                      */
1911                     if (!name_status_find("*", 0, 0x20, server_ip, server) &&
1912                         !name_status_find(MSBROWSE, 1, 0x1b, server_ip, server)) {
1913                         errno = ENOENT;
1914                         return NULL;
1915                     }
1916                 }       
1917
1918                 DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
1919
1920                 /*
1921                  * Get a connection to IPC$ on the server if we do not already
1922                  * have one
1923                  */
1924                 
1925                 srv = smbc_server(context, server, "IPC$", workgroup, user, password);
1926                 if (!srv) {
1927                     
1928                     if (dir) {
1929                         SAFE_FREE(dir->fname);
1930                         SAFE_FREE(dir);
1931                     }
1932                     return NULL;
1933                 }
1934                 
1935                 dir->srv = srv;
1936                 dir->dir_type = SMBC_WORKGROUP;
1937
1938                 /* Now, list the stuff ... */
1939
1940                 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_fn,
1941                                        (void *)dir)) {
1942
1943                         DEBUG(1, ("Could not enumerate domains using '%s'\n", workgroup));
1944                         if (dir) {
1945                                 SAFE_FREE(dir->fname);
1946                                 SAFE_FREE(dir);
1947                         }
1948
1949                         return NULL;
1950
1951                 }
1952         } else if (server[0] == (char)0 &&
1953                    (! *options || strcmp(options, "mb=.all") == 0)) {
1954
1955                 int i;
1956                 int count;
1957                 struct ip_service *ip_list;
1958                 struct ip_service server_addr;
1959                 struct user_auth_info u_info;
1960                 struct cli_state *cli;
1961
1962                 if (share[0] != (char)0 || path[0] != (char)0) {
1963
1964                         errno = EINVAL;
1965                         if (dir) {
1966                                 SAFE_FREE(dir->fname);
1967                                 SAFE_FREE(dir);
1968                         }
1969                         return NULL;
1970                 }
1971
1972                 pstrcpy(u_info.username, user);
1973                 pstrcpy(u_info.password, password);
1974
1975                 /*
1976                  * We have server and share and path empty but options
1977                  * requesting that we scan all master browsers for their list
1978                  * of workgroups/domains.  This implies that we must first try
1979                  * broadcast queries to find all master browsers, and if that
1980                  * doesn't work, then try our other methods which return only
1981                  * a single master browser.
1982                  */
1983
1984                 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
1985                         if (!find_master_ip(workgroup, &server_addr.ip)) {
1986
1987                                 errno = ENOENT;
1988                                 return NULL;
1989                         }
1990
1991                         ip_list = &server_addr;
1992                         count = 1;
1993                 }
1994
1995                 for (i = 0; i < count; i++) {
1996                         DEBUG(99, ("Found master browser %s\n", inet_ntoa(ip_list[i].ip)));
1997                         
1998                         cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, &u_info);
1999
2000                         /* cli == NULL is the master browser refused to talk or 
2001                            could not be found */
2002                         if ( !cli )
2003                                 continue;
2004
2005                         fstrcpy(server, cli->desthost);
2006                         cli_shutdown(cli);
2007
2008                         DEBUG(4, ("using workgroup %s %s\n", workgroup, server));
2009
2010                         /*
2011                          * For each returned master browser IP address, get a
2012                          * connection to IPC$ on the server if we do not
2013                          * already have one, and determine the
2014                          * workgroups/domains that it knows about.
2015                          */
2016                 
2017                         srv = smbc_server(context, server,
2018                                           "IPC$", workgroup, user, password);
2019                         if (!srv) {
2020                                 
2021                                 if (dir) {
2022                                         SAFE_FREE(dir->fname);
2023                                         SAFE_FREE(dir);
2024                                 }
2025                                 return NULL;
2026                         }
2027                 
2028                         dir->srv = srv;
2029                         dir->dir_type = SMBC_WORKGROUP;
2030
2031                         /* Now, list the stuff ... */
2032                         
2033                         if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_unique_wg_fn,
2034                                                (void *)dir)) {
2035                                 
2036                                 if (dir) {
2037                                         SAFE_FREE(dir->fname);
2038                                         SAFE_FREE(dir);
2039                                 }
2040                                 
2041                                 return NULL;
2042                                 
2043                         }
2044                 }
2045         } else { 
2046                 /*
2047                  * Server not an empty string ... Check the rest and see what
2048                  * gives
2049                  */
2050                 if (share[0] == (char)0) {
2051
2052                         if (path[0] != (char)0) { /* Should not have empty share with path */
2053
2054                                 errno = EINVAL;
2055                                 if (dir) {
2056                                         SAFE_FREE(dir->fname);
2057                                         SAFE_FREE(dir);
2058                                 }
2059                                 return NULL;
2060         
2061                         }
2062
2063                         /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
2064                         /* However, we check to see if <server> is an IP address first */
2065
2066                         if (!is_ipaddress(server) &&  /* Not an IP addr so check next */
2067                             (resolve_name(server, &rem_ip, 0x1d) ||   /* Found LMB */
2068                                     resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
2069                                 fstring buserver;
2070
2071                                 dir->dir_type = SMBC_SERVER;
2072
2073                                 /*
2074                                  * Get the backup list ...
2075                                  */
2076
2077
2078                                 if (!name_status_find(server, 0, 0, rem_ip, buserver)) {
2079
2080                                         DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
2081                                         errno = EPERM;  /* FIXME, is this correct */
2082                                         return NULL;
2083
2084                                 }
2085
2086                                 /*
2087                                  * Get a connection to IPC$ on the server if we do not already have one
2088                                  */
2089
2090                                 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
2091
2092                                 if (!srv) {
2093                                         DEBUG(0, ("got no contact to IPC$\n"));
2094                                         if (dir) {
2095                                                 SAFE_FREE(dir->fname);
2096                                                 SAFE_FREE(dir);
2097                                         }
2098                                         return NULL;
2099
2100                                 }
2101
2102                                 dir->srv = srv;
2103
2104                                 /* Now, list the servers ... */
2105
2106                                 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
2107                                                        (void *)dir)) {
2108
2109                                         if (dir) {
2110                                                 SAFE_FREE(dir->fname);
2111                                                 SAFE_FREE(dir);
2112                                         }
2113                                         return NULL;
2114                                         
2115                                 }
2116                         }
2117                         else {
2118
2119                                 if (resolve_name(server, &rem_ip, 0x20)) {
2120
2121                                         /* Now, list the shares ... */
2122
2123                                         dir->dir_type = SMBC_FILE_SHARE;
2124
2125                                         srv = smbc_server(context, server, "IPC$", workgroup, user, password);
2126
2127                                         if (!srv) {
2128
2129                                                 if (dir) {
2130                                                         SAFE_FREE(dir->fname);
2131                                                         SAFE_FREE(dir);
2132                                                 }
2133                                                 return NULL;
2134
2135                                         }
2136
2137                                         dir->srv = srv;
2138
2139                                         /* Now, list the servers ... */
2140
2141                                         if (cli_RNetShareEnum(&srv->cli, list_fn, 
2142                                                               (void *)dir) < 0) {
2143
2144                                                 errno = cli_errno(&srv->cli);
2145                                                 if (dir) {
2146                                                         SAFE_FREE(dir->fname);
2147                                                         SAFE_FREE(dir);
2148                                                 }
2149                                                 return NULL;
2150
2151                                         }
2152
2153                                 }
2154                                 else {
2155
2156                                         errno = ECONNREFUSED;   /* Neither the workgroup nor server exists */
2157                                         if (dir) {
2158                                                 SAFE_FREE(dir->fname);
2159                                                 SAFE_FREE(dir);
2160                                         }
2161                                         return NULL;
2162
2163                                 }
2164
2165                         }
2166
2167                 }
2168                 else { /* The server and share are specified ... work from there ... */
2169
2170                         /* Well, we connect to the server and list the directory */
2171
2172                         dir->dir_type = SMBC_FILE_SHARE;
2173
2174                         srv = smbc_server(context, server, share, workgroup, user, password);
2175
2176                         if (!srv) {
2177
2178                                 if (dir) {
2179                                         SAFE_FREE(dir->fname);
2180                                         SAFE_FREE(dir);
2181                                 }
2182                                 return NULL;
2183
2184                         }
2185
2186                         dir->srv = srv;
2187
2188                         /* Now, list the files ... */
2189
2190                         pstrcat(path, "\\*");
2191
2192                         if (cli_list(&srv->cli, path, aDIR | aSYSTEM | aHIDDEN, dir_list_fn, 
2193                                      (void *)dir) < 0) {
2194
2195                                 if (dir) {
2196                                         SAFE_FREE(dir->fname);
2197                                         SAFE_FREE(dir);
2198                                 }
2199                                 errno = smbc_errno(context, &srv->cli);
2200                                 return NULL;
2201
2202                         }
2203                 }
2204
2205         }
2206
2207         DLIST_ADD(context->internal->_files, dir);
2208         return dir;
2209
2210 }
2211
2212 /*
2213  * Routine to close a directory
2214  */
2215
2216 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
2217 {
2218
2219         if (!context || !context->internal ||
2220             !context->internal->_initialized) {
2221
2222                 errno = EINVAL;
2223                 return -1;
2224
2225         }
2226
2227         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2228
2229                 errno = EBADF;
2230                 return -1;
2231     
2232         }
2233
2234         smbc_remove_dir(dir); /* Clean it up */
2235
2236         DLIST_REMOVE(context->internal->_files, dir);
2237
2238         if (dir) {
2239
2240                 SAFE_FREE(dir->fname);
2241                 SAFE_FREE(dir);    /* Free the space too */
2242         }
2243
2244         return 0;
2245
2246 }
2247
2248 /*
2249  * Routine to get a directory entry
2250  */
2251
2252 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
2253 {
2254         struct smbc_dirent *dirp, *dirent;
2255
2256         /* Check that all is ok first ... */
2257
2258         if (!context || !context->internal ||
2259             !context->internal->_initialized) {
2260
2261                 errno = EINVAL;
2262                 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
2263                 return NULL;
2264
2265         }
2266
2267         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2268
2269                 errno = EBADF;
2270                 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
2271                 return NULL;
2272
2273         }
2274
2275         if (dir->file != False) { /* FIXME, should be dir, perhaps */
2276
2277                 errno = ENOTDIR;
2278                 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
2279                 return NULL;
2280
2281         }
2282
2283         if (!dir->dir_next) {
2284                 return NULL;
2285         }
2286         else {
2287
2288                 dirent = dir->dir_next->dirent;
2289                 if (!dirent) {
2290
2291                         errno = ENOENT;
2292                         return NULL;
2293
2294                 }
2295
2296                 /* Hmmm, do I even need to copy it? */
2297
2298                 memcpy(context->internal->_dirent, dirent, dirent->dirlen); /* Copy the dirent */
2299                 dirp = (struct smbc_dirent *)context->internal->_dirent;
2300                 dirp->comment = (char *)(&dirp->name + dirent->namelen + 1);
2301                 dir->dir_next = dir->dir_next->next;
2302
2303                 return (struct smbc_dirent *)context->internal->_dirent;
2304         }
2305
2306 }
2307
2308 /*
2309  * Routine to get directory entries
2310  */
2311
2312 static int smbc_getdents_ctx(SMBCCTX *context, SMBCFILE *dir, struct smbc_dirent *dirp, int count)
2313 {
2314         struct smbc_dir_list *dirlist;
2315         int rem = count, reqd;
2316         char *ndir = (char *)dirp;
2317
2318         /* Check that all is ok first ... */
2319
2320         if (!context || !context->internal ||
2321             !context->internal->_initialized) {
2322
2323                 errno = EINVAL;
2324                 return -1;
2325
2326         }
2327
2328         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2329
2330                 errno = EBADF;
2331                 return -1;
2332     
2333         }
2334
2335         if (dir->file != False) { /* FIXME, should be dir, perhaps */
2336
2337                 errno = ENOTDIR;
2338                 return -1;
2339
2340         }
2341
2342         /* 
2343          * Now, retrieve the number of entries that will fit in what was passed
2344          * We have to figure out if the info is in the list, or we need to 
2345          * send a request to the server to get the info.
2346          */
2347
2348         while ((dirlist = dir->dir_next)) {
2349                 struct smbc_dirent *dirent;
2350
2351                 if (!dirlist->dirent) {
2352
2353                         errno = ENOENT;  /* Bad error */
2354                         return -1;
2355
2356                 }
2357
2358                 if (rem < (reqd = (sizeof(struct smbc_dirent) + dirlist->dirent->namelen + 
2359                                    dirlist->dirent->commentlen + 1))) {
2360
2361                         if (rem < count) { /* We managed to copy something */
2362
2363                                 errno = 0;
2364                                 return count - rem;
2365
2366                         }
2367                         else { /* Nothing copied ... */
2368
2369                                 errno = EINVAL;  /* Not enough space ... */
2370                                 return -1;
2371
2372                         }
2373
2374                 }
2375
2376                 dirent = dirlist->dirent;
2377
2378                 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
2379     
2380                 ((struct smbc_dirent *)ndir)->comment = 
2381                         (char *)(&((struct smbc_dirent *)ndir)->name + dirent->namelen + 1);
2382
2383                 ndir += reqd;
2384
2385                 rem -= reqd;
2386
2387                 dir->dir_next = dirlist = dirlist -> next;
2388         }
2389
2390         if (rem == count)
2391                 return 0;
2392         else 
2393                 return count - rem;
2394
2395 }
2396
2397 /*
2398  * Routine to create a directory ...
2399  */
2400
2401 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
2402 {
2403         SMBCSRV *srv;
2404         fstring server, share, user, password, workgroup;
2405         pstring path;
2406
2407         if (!context || !context->internal || 
2408             !context->internal->_initialized) {
2409
2410                 errno = EINVAL;
2411                 return -1;
2412
2413         }
2414
2415         if (!fname) {
2416
2417                 errno = EINVAL;
2418                 return -1;
2419
2420         }
2421   
2422         DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2423
2424         if (smbc_parse_path(context, fname,
2425                             server, sizeof(server),
2426                             share, sizeof(share),
2427                             path, sizeof(path),
2428                             user, sizeof(user),
2429                             password, sizeof(password),
2430                             NULL, 0)) {
2431                 errno = EINVAL;
2432                 return -1;
2433         }
2434
2435         if (user[0] == (char)0) fstrcpy(user, context->user);
2436
2437         fstrcpy(workgroup, context->workgroup);
2438
2439         srv = smbc_server(context, server, share, workgroup, user, password);
2440
2441         if (!srv) {
2442
2443                 return -1;  /* errno set by smbc_server */
2444
2445         }
2446
2447         /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2448
2449            mode = aDIR | aRONLY;
2450
2451            }
2452            else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2453
2454            if (strcmp(path, "\\") == 0) {
2455
2456            mode = aDIR | aRONLY;
2457
2458            }
2459            else {
2460
2461            mode = aRONLY;
2462            smbc_stat_printjob(srv, path, &size, &m_time);
2463            c_time = a_time = m_time;
2464
2465            }
2466            else { */
2467
2468         if (!cli_mkdir(&srv->cli, path)) {
2469
2470                 errno = smbc_errno(context, &srv->cli);
2471                 return -1;
2472
2473         } 
2474
2475         return 0;
2476
2477 }
2478
2479 /*
2480  * Our list function simply checks to see if a directory is not empty
2481  */
2482
2483 static int smbc_rmdir_dirempty = True;
2484
2485 static void rmdir_list_fn(file_info *finfo, const char *mask, void *state)
2486 {
2487
2488         if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2489                 smbc_rmdir_dirempty = False;
2490
2491 }
2492
2493 /*
2494  * Routine to remove a directory
2495  */
2496
2497 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2498 {
2499         SMBCSRV *srv;
2500         fstring server, share, user, password, workgroup;
2501         pstring path;
2502
2503         if (!context || !context->internal || 
2504             !context->internal->_initialized) {
2505
2506                 errno = EINVAL;
2507                 return -1;
2508
2509         }
2510
2511         if (!fname) {
2512
2513                 errno = EINVAL;
2514                 return -1;
2515
2516         }
2517   
2518         DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2519
2520         if (smbc_parse_path(context, fname,
2521                             server, sizeof(server),
2522                             share, sizeof(share),
2523                             path, sizeof(path),
2524                             user, sizeof(user),
2525                             password, sizeof(password),
2526                             NULL, 0))
2527         {
2528                 errno = EINVAL;
2529                 return -1;
2530         }
2531
2532         if (user[0] == (char)0) fstrcpy(user, context->user);
2533
2534         fstrcpy(workgroup, context->workgroup);
2535
2536         srv = smbc_server(context, server, share, workgroup, user, password);
2537
2538         if (!srv) {
2539
2540                 return -1;  /* errno set by smbc_server */
2541
2542         }
2543
2544         /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2545
2546            mode = aDIR | aRONLY;
2547
2548            }
2549            else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2550
2551            if (strcmp(path, "\\") == 0) {
2552
2553            mode = aDIR | aRONLY;
2554
2555            }
2556            else {
2557
2558            mode = aRONLY;
2559            smbc_stat_printjob(srv, path, &size, &m_time);
2560            c_time = a_time = m_time;
2561            
2562            }
2563            else { */
2564
2565         if (!cli_rmdir(&srv->cli, path)) {
2566
2567                 errno = smbc_errno(context, &srv->cli);
2568
2569                 if (errno == EACCES) {  /* Check if the dir empty or not */
2570
2571                         pstring lpath; /* Local storage to avoid buffer overflows */
2572
2573                         smbc_rmdir_dirempty = True;  /* Make this so ... */
2574
2575                         pstrcpy(lpath, path);
2576                         pstrcat(lpath, "\\*");
2577
2578                         if (cli_list(&srv->cli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2579                                      NULL) < 0) {
2580
2581                                 /* Fix errno to ignore latest error ... */
2582
2583                                 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n", 
2584                                           smbc_errno(context, &srv->cli)));
2585                                 errno = EACCES;
2586
2587                         }
2588
2589                         if (smbc_rmdir_dirempty)
2590                                 errno = EACCES;
2591                         else
2592                                 errno = ENOTEMPTY;
2593
2594                 }
2595
2596                 return -1;
2597
2598         } 
2599
2600         return 0;
2601
2602 }
2603
2604 /*
2605  * Routine to return the current directory position
2606  */
2607
2608 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
2609 {
2610         off_t ret_val; /* Squash warnings about cast */
2611
2612         if (!context || !context->internal ||
2613             !context->internal->_initialized) {
2614
2615                 errno = EINVAL;
2616                 return -1;
2617
2618         }
2619
2620         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2621
2622                 errno = EBADF;
2623                 return -1;
2624
2625         }
2626
2627         if (dir->file != False) { /* FIXME, should be dir, perhaps */
2628
2629                 errno = ENOTDIR;
2630                 return -1;
2631
2632         }
2633
2634         /*
2635          * We return the pointer here as the offset
2636          */
2637         ret_val = (int)dir->dir_next;
2638         return ret_val;
2639
2640 }
2641
2642 /*
2643  * A routine to run down the list and see if the entry is OK
2644  */
2645
2646 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list, 
2647                                          struct smbc_dirent *dirent)
2648 {
2649
2650         /* Run down the list looking for what we want */
2651
2652         if (dirent) {
2653
2654                 struct smbc_dir_list *tmp = list;
2655
2656                 while (tmp) {
2657
2658                         if (tmp->dirent == dirent)
2659                                 return tmp;
2660
2661                         tmp = tmp->next;
2662
2663                 }
2664
2665         }
2666
2667         return NULL;  /* Not found, or an error */
2668
2669 }
2670
2671
2672 /*
2673  * Routine to seek on a directory
2674  */
2675
2676 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
2677 {
2678         long int l_offset = offset;  /* Handle problems of size */
2679         struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
2680         struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
2681
2682         if (!context || !context->internal ||
2683             !context->internal->_initialized) {
2684
2685                 errno = EINVAL;
2686                 return -1;
2687
2688         }
2689
2690         if (dir->file != False) { /* FIXME, should be dir, perhaps */
2691
2692                 errno = ENOTDIR;
2693                 return -1;
2694
2695         }
2696
2697         /* Now, check what we were passed and see if it is OK ... */
2698
2699         if (dirent == NULL) {  /* Seek to the begining of the list */
2700
2701                 dir->dir_next = dir->dir_list;
2702                 return 0;
2703
2704         }
2705
2706         /* Now, run down the list and make sure that the entry is OK       */
2707         /* This may need to be changed if we change the format of the list */
2708
2709         if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
2710
2711                 errno = EINVAL;   /* Bad entry */
2712                 return -1;
2713
2714         }
2715
2716         dir->dir_next = list_ent;
2717
2718         return 0; 
2719
2720 }
2721
2722 /*
2723  * Routine to fstat a dir
2724  */
2725
2726 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
2727 {
2728
2729         if (!context || !context->internal || 
2730             !context->internal->_initialized) {
2731
2732                 errno = EINVAL;
2733                 return -1;
2734
2735         }
2736
2737         /* No code yet ... */
2738
2739         return 0;
2740
2741 }
2742
2743 int smbc_chmod_ctx(SMBCCTX *context, const char *fname, mode_t newmode)
2744 {
2745         SMBCSRV *srv;
2746         fstring server, share, user, password, workgroup;
2747         pstring path;
2748         uint16 mode;
2749
2750         if (!context || !context->internal ||
2751             !context->internal->_initialized) {
2752
2753                 errno = EINVAL;  /* Best I can think of ... */
2754                 return -1;
2755     
2756         }
2757
2758         if (!fname) {
2759
2760                 errno = EINVAL;
2761                 return -1;
2762
2763         }
2764   
2765         DEBUG(4, ("smbc_chmod(%s, 0%3o)\n", fname, newmode));
2766
2767         if (smbc_parse_path(context, fname,
2768                             server, sizeof(server),
2769                             share, sizeof(share),
2770                             path, sizeof(path),
2771                             user, sizeof(user),
2772                             password, sizeof(password),
2773                             NULL, 0)) {
2774                 errno = EINVAL;
2775                 return -1;
2776         }
2777
2778         if (user[0] == (char)0) fstrcpy(user, context->user);
2779
2780         fstrcpy(workgroup, context->workgroup);
2781
2782         srv = smbc_server(context, server, share, workgroup, user, password);
2783
2784         if (!srv) {
2785                 return -1;  /* errno set by smbc_server */
2786         }
2787
2788         mode = 0;
2789
2790         if (!(newmode & (S_IWUSR | S_IWGRP | S_IWOTH))) mode |= aRONLY;
2791         if ((newmode & S_IXUSR) && lp_map_archive(-1)) mode |= aARCH;
2792         if ((newmode & S_IXGRP) && lp_map_system(-1)) mode |= aSYSTEM;
2793         if ((newmode & S_IXOTH) && lp_map_hidden(-1)) mode |= aHIDDEN;
2794
2795         if (!cli_setatr(&srv->cli, path, mode, 0)) {
2796                 errno = smbc_errno(context, &srv->cli);
2797                 return -1;
2798         }
2799         
2800         return 0;
2801 }
2802
2803 int smbc_utimes_ctx(SMBCCTX *context, const char *fname, struct timeval *tbuf)
2804 {
2805         SMBCSRV *srv;
2806         fstring server, share, user, password, workgroup;
2807         pstring path;
2808         uint16 mode;
2809         time_t t = (tbuf == NULL ? time(NULL) : tbuf->tv_sec);
2810
2811         if (!context || !context->internal ||
2812             !context->internal->_initialized) {
2813
2814                 errno = EINVAL;  /* Best I can think of ... */
2815                 return -1;
2816     
2817         }
2818
2819         if (!fname) {
2820
2821                 errno = EINVAL;
2822                 return -1;
2823
2824         }
2825   
2826         DEBUG(4, ("smbc_utimes(%s, [%s])\n", fname, ctime(&t)));
2827
2828         if (smbc_parse_path(context, fname,
2829                             server, sizeof(server),
2830                             share, sizeof(share),
2831                             path, sizeof(path),
2832                             user, sizeof(user),
2833                             password, sizeof(password),
2834                             NULL, 0)) {
2835                 errno = EINVAL;
2836                 return -1;
2837         }
2838
2839         if (user[0] == (char)0) fstrcpy(user, context->user);
2840
2841         fstrcpy(workgroup, context->workgroup);
2842
2843         srv = smbc_server(context, server, share, workgroup, user, password);
2844
2845         if (!srv) {
2846                 return -1;  /* errno set by smbc_server */
2847         }
2848
2849         if (!smbc_getatr(context, srv, path,
2850                          &mode, NULL,
2851                          NULL, NULL, NULL,
2852                          NULL)) {
2853                 return -1;
2854         }
2855
2856         if (!cli_setatr(&srv->cli, path, mode, t)) {
2857                 /* some servers always refuse directory changes */
2858                 if (!(mode & aDIR)) {
2859                         errno = smbc_errno(context, &srv->cli);
2860                         return -1;
2861                 }
2862         }
2863
2864         return 0;
2865 }
2866
2867
2868 /* The MSDN is contradictory over the ordering of ACE entries in an ACL.
2869    However NT4 gives a "The information may have been modified by a
2870    computer running Windows NT 5.0" if denied ACEs do not appear before
2871    allowed ACEs. */
2872
2873 static int ace_compare(SEC_ACE *ace1, SEC_ACE *ace2)
2874 {
2875         if (sec_ace_equal(ace1, ace2)) 
2876                 return 0;
2877
2878         if (ace1->type != ace2->type) 
2879                 return ace2->type - ace1->type;
2880
2881         if (sid_compare(&ace1->trustee, &ace2->trustee)) 
2882                 return sid_compare(&ace1->trustee, &ace2->trustee);
2883
2884         if (ace1->flags != ace2->flags) 
2885                 return ace1->flags - ace2->flags;
2886
2887         if (ace1->info.mask != ace2->info.mask) 
2888                 return ace1->info.mask - ace2->info.mask;
2889
2890         if (ace1->size != ace2->size) 
2891                 return ace1->size - ace2->size;
2892
2893         return memcmp(ace1, ace2, sizeof(SEC_ACE));
2894 }
2895
2896
2897 static void sort_acl(SEC_ACL *the_acl)
2898 {
2899         uint32 i;
2900         if (!the_acl) return;
2901
2902         qsort(the_acl->ace, the_acl->num_aces, sizeof(the_acl->ace[0]), QSORT_CAST ace_compare);
2903
2904         for (i=1;i<the_acl->num_aces;) {
2905                 if (sec_ace_equal(&the_acl->ace[i-1], &the_acl->ace[i])) {
2906                         int j;
2907                         for (j=i; j<the_acl->num_aces-1; j++) {
2908                                 the_acl->ace[j] = the_acl->ace[j+1];
2909                         }
2910                         the_acl->num_aces--;
2911                 } else {
2912                         i++;
2913                 }
2914         }
2915 }
2916
2917 /* convert a SID to a string, either numeric or username/group */
2918 static void convert_sid_to_string(struct cli_state *ipc_cli,
2919                                   POLICY_HND *pol,
2920                                   fstring str,
2921                                   BOOL numeric,
2922                                   DOM_SID *sid)
2923 {
2924         char **domains = NULL;
2925         char **names = NULL;
2926         uint32 *types = NULL;
2927
2928         sid_to_string(str, sid);
2929
2930         if (numeric) return;     /* no lookup desired */
2931         
2932         /* Ask LSA to convert the sid to a name */
2933
2934         if (!NT_STATUS_IS_OK(cli_lsa_lookup_sids(ipc_cli, ipc_cli->mem_ctx,  
2935                                                  pol, 1, sid, &domains, 
2936                                                  &names, &types)) ||
2937             !domains || !domains[0] || !names || !names[0]) {
2938                 return;
2939         }
2940
2941         /* Converted OK */
2942
2943         slprintf(str, sizeof(fstring) - 1, "%s%s%s",
2944                  domains[0], lp_winbind_separator(),
2945                  names[0]);
2946 }
2947
2948 /* convert a string to a SID, either numeric or username/group */
2949 static BOOL convert_string_to_sid(struct cli_state *ipc_cli,
2950                                   POLICY_HND *pol,
2951                                   BOOL numeric,
2952                                   DOM_SID *sid,
2953                                   const char *str)
2954 {
2955         uint32 *types = NULL;
2956         DOM_SID *sids = NULL;
2957         BOOL result = True;
2958
2959         if (numeric) {
2960                 if (strncmp(str, "S-", 2) == 0) {
2961                         return string_to_sid(sid, str);
2962                 }
2963
2964                 result = False;
2965                 goto done;
2966         }
2967
2968         if (!NT_STATUS_IS_OK(cli_lsa_lookup_names(ipc_cli, ipc_cli->mem_ctx, 
2969                                                   pol, 1, &str, &sids, 
2970                                                   &types))) {
2971                 result = False;
2972                 goto done;
2973         }
2974
2975         sid_copy(sid, &sids[0]);
2976  done:
2977
2978         return result;
2979 }
2980
2981
2982 /* parse an ACE in the same format as print_ace() */
2983 static BOOL parse_ace(struct cli_state *ipc_cli,
2984                       POLICY_HND *pol,
2985                       SEC_ACE *ace,
2986                       BOOL numeric,
2987                       char *str)
2988 {
2989         char *p;
2990         const char *cp;
2991         fstring tok;
2992         unsigned atype, aflags, amask;
2993         DOM_SID sid;
2994         SEC_ACCESS mask;
2995         const struct perm_value *v;
2996         struct perm_value {
2997                 const char *perm;
2998                 uint32 mask;
2999         };
3000
3001         /* These values discovered by inspection */
3002         static const struct perm_value special_values[] = {
3003                 { "R", 0x00120089 },
3004                 { "W", 0x00120116 },
3005                 { "X", 0x001200a0 },
3006                 { "D", 0x00010000 },
3007                 { "P", 0x00040000 },
3008                 { "O", 0x00080000 },
3009                 { NULL, 0 },
3010         };
3011
3012         static const struct perm_value standard_values[] = {
3013                 { "READ",   0x001200a9 },
3014                 { "CHANGE", 0x001301bf },
3015                 { "FULL",   0x001f01ff },
3016                 { NULL, 0 },
3017         };
3018
3019
3020         ZERO_STRUCTP(ace);
3021         p = strchr_m(str,':');
3022         if (!p) return False;
3023         *p = '\0';
3024         p++;
3025         /* Try to parse numeric form */
3026
3027         if (sscanf(p, "%i/%i/%i", &atype, &aflags, &amask) == 3 &&
3028             convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3029                 goto done;
3030         }
3031
3032         /* Try to parse text form */
3033
3034         if (!convert_string_to_sid(ipc_cli, pol, numeric, &sid, str)) {
3035                 return False;
3036         }
3037
3038         cp = p;
3039         if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3040                 return False;
3041         }
3042
3043         if (StrnCaseCmp(tok, "ALLOWED", strlen("ALLOWED")) == 0) {
3044                 atype = SEC_ACE_TYPE_ACCESS_ALLOWED;
3045         } else if (StrnCaseCmp(tok, "DENIED", strlen("DENIED")) == 0) {
3046                 atype = SEC_ACE_TYPE_ACCESS_DENIED;
3047         } else {
3048                 return False;
3049         }
3050
3051         /* Only numeric form accepted for flags at present */
3052
3053         if (!(next_token(&cp, tok, "/", sizeof(fstring)) &&
3054               sscanf(tok, "%i", &aflags))) {
3055                 return False;
3056         }
3057
3058         if (!next_token(&cp, tok, "/", sizeof(fstring))) {
3059                 return False;
3060         }
3061
3062         if (strncmp(tok, "0x", 2) == 0) {
3063                 if (sscanf(tok, "%i", &amask) != 1) {
3064                         return False;
3065                 }
3066                 goto done;
3067         }
3068
3069         for (v = standard_values; v->perm; v++) {
3070                 if (strcmp(tok, v->perm) == 0) {
3071                         amask = v->mask;
3072                         goto done;
3073                 }
3074         }
3075
3076         p = tok;
3077
3078         while(*p) {
3079                 BOOL found = False;
3080
3081                 for (v = special_values; v->perm; v++) {
3082                         if (v->perm[0] == *p) {
3083                                 amask |= v->mask;
3084                                 found = True;
3085                         }
3086                 }
3087
3088                 if (!found) return False;
3089                 p++;
3090         }
3091
3092         if (*p) {
3093                 return False;
3094         }
3095
3096  done:
3097         mask.mask = amask;
3098         init_sec_ace(ace, &sid, atype, mask, aflags);
3099         return True;
3100 }
3101
3102 /* add an ACE to a list of ACEs in a SEC_ACL */
3103 static BOOL add_ace(SEC_ACL **the_acl, SEC_ACE *ace, TALLOC_CTX *ctx)
3104 {
3105         SEC_ACL *new;
3106         SEC_ACE *aces;
3107         if (! *the_acl) {
3108                 (*the_acl) = make_sec_acl(ctx, 3, 1, ace);
3109                 return True;
3110         }
3111
3112         aces = calloc(1+(*the_acl)->num_aces,sizeof(SEC_ACE));
3113         memcpy(aces, (*the_acl)->ace, (*the_acl)->num_aces * sizeof(SEC_ACE));
3114         memcpy(aces+(*the_acl)->num_aces, ace, sizeof(SEC_ACE));
3115         new = make_sec_acl(ctx,(*the_acl)->revision,1+(*the_acl)->num_aces, aces);
3116         SAFE_FREE(aces);
3117         (*the_acl) = new;
3118         return True;
3119 }
3120
3121
3122 /* parse a ascii version of a security descriptor */
3123 static SEC_DESC *sec_desc_parse(TALLOC_CTX *ctx,
3124                                 struct cli_state *ipc_cli,
3125                                 POLICY_HND *pol,
3126                                 BOOL numeric,
3127                                 char *str)
3128 {
3129         const char *p = str;
3130         fstring tok;
3131         SEC_DESC *ret;
3132         size_t sd_size;
3133         DOM_SID *grp_sid=NULL, *owner_sid=NULL;
3134         SEC_ACL *dacl=NULL;
3135         int revision=1;
3136
3137         while (next_token(&p, tok, "\t,\r\n", sizeof(tok))) {
3138
3139                 if (StrnCaseCmp(tok,"REVISION:", 9) == 0) {
3140                         revision = strtol(tok+9, NULL, 16);
3141                         continue;
3142                 }
3143
3144                 if (StrnCaseCmp(tok,"OWNER:", 6) == 0) {
3145                         owner_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3146                         if (!owner_sid ||
3147                             !convert_string_to_sid(ipc_cli, pol,
3148                                                    numeric,
3149                                                    owner_sid, tok+6)) {
3150                                 DEBUG(5, ("Failed to parse owner sid\n"));
3151                                 return NULL;
3152                         }
3153                         continue;
3154                 }
3155
3156                 if (StrnCaseCmp(tok,"OWNER+:", 7) == 0) {
3157                         owner_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3158                         if (!owner_sid ||
3159                             !convert_string_to_sid(ipc_cli, pol,
3160                                                    False,
3161                                                    owner_sid, tok+7)) {
3162                                 DEBUG(5, ("Failed to parse owner sid\n"));
3163                                 return NULL;
3164                         }
3165                         continue;
3166                 }
3167
3168                 if (StrnCaseCmp(tok,"GROUP:", 6) == 0) {
3169                         grp_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3170                         if (!grp_sid ||
3171                             !convert_string_to_sid(ipc_cli, pol,
3172                                                    numeric,
3173                                                    grp_sid, tok+6)) {
3174                                 DEBUG(5, ("Failed to parse group sid\n"));
3175                                 return NULL;
3176                         }
3177                         continue;
3178                 }
3179
3180                 if (StrnCaseCmp(tok,"GROUP+:", 7) == 0) {
3181                         grp_sid = (DOM_SID *)calloc(1, sizeof(DOM_SID));
3182                         if (!grp_sid ||
3183                             !convert_string_to_sid(ipc_cli, pol,
3184                                                    False,
3185                                                    grp_sid, tok+6)) {
3186                                 DEBUG(5, ("Failed to parse group sid\n"));
3187                                 return NULL;
3188                         }
3189                         continue;
3190                 }
3191
3192                 if (StrnCaseCmp(tok,"ACL:", 4) == 0) {
3193                         SEC_ACE ace;
3194                         if (!parse_ace(ipc_cli, pol, &ace, numeric, tok+4)) {
3195                                 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3196                                 return NULL;
3197                         }
3198                         if(!add_ace(&dacl, &ace, ctx)) {
3199                                 DEBUG(5, ("Failed to add ACL %s\n", tok));
3200                                 return NULL;
3201                         }
3202                         continue;
3203                 }
3204
3205                 if (StrnCaseCmp(tok,"ACL+:", 5) == 0) {
3206                         SEC_ACE ace;
3207                         if (!parse_ace(ipc_cli, pol, &ace, False, tok+5)) {
3208                                 DEBUG(5, ("Failed to parse ACL %s\n", tok));
3209                                 return NULL;
3210                         }
3211                         if(!add_ace(&dacl, &ace, ctx)) {
3212                                 DEBUG(5, ("Failed to add ACL %s\n", tok));
3213                                 return NULL;
3214                         }
3215                         continue;
3216                 }
3217
3218                 DEBUG(5, ("Failed to parse security descriptor\n"));
3219                 return NULL;
3220         }
3221
3222         ret = make_sec_desc(ctx, revision, SEC_DESC_SELF_RELATIVE, 
3223                             owner_sid, grp_sid, NULL, dacl, &sd_size);
3224
3225         SAFE_FREE(grp_sid);
3226         SAFE_FREE(owner_sid);
3227
3228         return ret;
3229 }
3230
3231
3232 /***************************************************** 
3233 retrieve the acls for a file
3234 *******************************************************/
3235 static int cacl_get(TALLOC_CTX *ctx, struct cli_state *cli,
3236                     struct cli_state *ipc_cli, POLICY_HND *pol,
3237                     char *filename, char *name, char *buf, int bufsize)
3238 {
3239         uint32 i;
3240         int n = 0;
3241         int n_used;
3242         BOOL all;
3243         BOOL numeric = True;
3244         BOOL determine_size = (bufsize == 0);
3245         int fnum = -1;
3246         SEC_DESC *sd;
3247         fstring sidstr;
3248         char *p;
3249
3250         fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3251
3252         if (fnum == -1) {
3253                 DEBUG(5, ("cacl_get failed to open %s: %s\n",
3254                           filename, cli_errstr(cli)));
3255                 errno = 0;
3256                 return -1;
3257         }
3258
3259         sd = cli_query_secdesc(cli, fnum, ctx);
3260
3261         if (!sd) {
3262                 DEBUG(5, ("cacl_get Failed to query old descriptor\n"));
3263                 errno = 0;
3264                 return -1;
3265         }
3266
3267         cli_close(cli, fnum);
3268
3269         all = (*name == '*');
3270         numeric = (* (name + strlen(name) - 1) != '+');
3271
3272         n_used = 0;
3273
3274         if (all) {
3275                 if (determine_size) {
3276                         p = talloc_asprintf(ctx,
3277                                             "REVISION:%d", sd->revision);
3278                         if (!p) {
3279                                 errno = ENOMEM;
3280                                 return -1;
3281                         }
3282                         n = strlen(p);
3283                 } else {
3284                         n = snprintf(buf, bufsize,
3285                                      "REVISION:%d", sd->revision);
3286                 }
3287         } else if (StrCaseCmp(name, "revision") == 0) {
3288                 if (determine_size) {
3289                         p = talloc_asprintf(ctx, "%d", sd->revision);
3290                         if (!p) {
3291                                 errno = ENOMEM;
3292                                 return -1;
3293                         }
3294                         n = strlen(p);
3295                 } else {
3296                         n = snprintf(buf, bufsize, "%d", sd->revision);
3297                 }
3298         }
3299         
3300         if (!determine_size && n > bufsize) {
3301                 errno = ERANGE;
3302                 return -1;
3303         }
3304         buf += n;
3305         n_used += n;
3306         bufsize -= n;
3307
3308         /* Get owner and group sid */
3309
3310         if (sd->owner_sid) {
3311                 convert_sid_to_string(ipc_cli, pol,
3312                                       sidstr, numeric, sd->owner_sid);
3313         } else {
3314                 fstrcpy(sidstr, "");
3315         }
3316
3317         if (all) {
3318                 if (determine_size) {
3319                         p = talloc_asprintf(ctx, ",OWNER:%s", sidstr);
3320                         if (!p) {
3321                                 errno = ENOMEM;
3322                                 return -1;
3323                         }
3324                         n = strlen(p);
3325                 } else {
3326                         n = snprintf(buf, bufsize, ",OWNER:%s", sidstr);
3327                 }
3328         } else if (StrnCaseCmp(name, "owner", 5) == 0) {
3329                 if (determine_size) {
3330                         p = talloc_asprintf(ctx, "%s", sidstr);
3331                         if (!p) {
3332                                 errno = ENOMEM;
3333                                 return -1;
3334                         }
3335                         n = strlen(p);
3336                 } else {
3337                         n = snprintf(buf, bufsize, "%s", sidstr);
3338                 }
3339         }
3340
3341         if (!determine_size && n > bufsize) {
3342                 errno = ERANGE;
3343                 return -1;
3344         }
3345         buf += n;
3346         n_used += n;
3347         bufsize -= n;
3348
3349         if (sd->grp_sid) {
3350                 convert_sid_to_string(ipc_cli, pol,
3351                                       sidstr, numeric, sd->grp_sid);
3352         } else {
3353                 fstrcpy(sidstr, "");
3354         }
3355
3356         if (all) {
3357                 if (determine_size) {
3358                         p = talloc_asprintf(ctx, ",GROUP:%s", sidstr);
3359                         if (!p) {
3360                                 errno = ENOMEM;
3361                                 return -1;
3362                         }
3363                         n = strlen(p);
3364                 } else {
3365                         n = snprintf(buf, bufsize, ",GROUP:%s", sidstr);
3366                 }
3367         } else if (StrnCaseCmp(name, "group", 5) == 0) {
3368                 if (determine_size) {
3369                         p = talloc_asprintf(ctx, "%s", sidstr);
3370                         if (!p) {
3371                                 errno = ENOMEM;
3372                                 return -1;
3373                         }
3374                         n = strlen(p);
3375                 } else {
3376                         n = snprintf(buf, bufsize, "%s", sidstr);
3377                 }
3378         }
3379
3380         if (!determine_size && n > bufsize) {
3381                 errno = ERANGE;
3382                 return -1;
3383         }
3384         buf += n;
3385         n_used += n;
3386         bufsize -= n;
3387
3388         /* Add aces to value buffer  */
3389         for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
3390
3391                 SEC_ACE *ace = &sd->dacl->ace[i];
3392                 convert_sid_to_string(ipc_cli, pol,
3393                                       sidstr, numeric, &ace->trustee);
3394
3395                 if (all) {
3396                         if (determine_size) {
3397                                 p = talloc_asprintf(ctx, 
3398                                                     ",ACL:%s:%d/%d/0x%08x", 
3399                                                     sidstr,
3400                                                     ace->type,
3401                                                     ace->flags,
3402                                                     ace->info.mask);
3403                                 if (!p) {
3404                                         errno = ENOMEM;
3405                                         return -1;
3406                                 }
3407                                 n = strlen(p);
3408                         } else {
3409                                 n = snprintf(buf, bufsize,
3410                                              ",ACL:%s:%d/%d/0x%08x", 
3411                                              sidstr,
3412                                              ace->type,
3413                                              ace->flags,
3414                                              ace->info.mask);
3415                         }
3416                 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
3417                             StrCaseCmp(name + 3, sidstr) == 0) ||
3418                            (StrnCaseCmp(name, "acl+", 4) == 0 &&
3419                             StrCaseCmp(name + 4, sidstr) == 0)) {
3420                         if (determine_size) {
3421                                 p = talloc_asprintf(ctx, 
3422                                                     "%d/%d/0x%08x", 
3423                                                     ace->type,
3424                                                     ace->flags,
3425                                                     ace->info.mask);
3426                                 if (!p) {
3427                                         errno = ENOMEM;
3428                                         return -1;
3429                                 }
3430                                 n = strlen(p);
3431                         } else {
3432                                 n = snprintf(buf, bufsize,
3433                                              "%d/%d/0x%08x", 
3434                                              ace->type, ace->flags, ace->info.mask);
3435                         }
3436                 }
3437                 if (n > bufsize) {
3438                         errno = ERANGE;
3439                         return -1;
3440                 }
3441                 buf += n;
3442                 n_used += n;
3443                 bufsize -= n;
3444         }
3445
3446         if (n_used == 0) {
3447                 errno = ENOATTR;
3448                 return -1;
3449         }
3450         return n_used;
3451 }
3452
3453
3454 /***************************************************** 
3455 set the ACLs on a file given an ascii description
3456 *******************************************************/
3457 static int cacl_set(TALLOC_CTX *ctx, struct cli_state *cli,
3458                     struct cli_state *ipc_cli, POLICY_HND *pol,
3459                     const char *filename, const char *the_acl,
3460                     int mode, int flags)
3461 {
3462         int fnum;
3463         int err = 0;
3464         SEC_DESC *sd = NULL, *old;
3465         SEC_ACL *dacl = NULL;
3466         DOM_SID *owner_sid = NULL; 
3467         DOM_SID *grp_sid = NULL;
3468         uint32 i, j;
3469         size_t sd_size;
3470         int ret = 0;
3471         char *p;
3472         BOOL numeric = True;
3473
3474         /* the_acl will be null for REMOVE_ALL operations */
3475         if (the_acl) {
3476                 numeric = ((p = strchr(the_acl, ':')) != NULL &&
3477                            p > the_acl &&
3478                            p[-1] != '+');
3479
3480                 /* if this is to set the entire ACL... */
3481                 if (*the_acl == '*') {
3482                         /* ... then increment past the first colon */
3483                         the_acl = p + 1;
3484                 }
3485
3486                 sd = sec_desc_parse(ctx, ipc_cli, pol,
3487                                     numeric, (char *) the_acl);
3488
3489                 if (!sd) {
3490                         errno = EINVAL;
3491                         return -1;
3492                 }
3493         }
3494
3495         /* The desired access below is the only one I could find that works
3496            with NT4, W2KP and Samba */
3497
3498         fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
3499
3500         if (fnum == -1) {
3501                 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3502                           filename, cli_errstr(cli)));
3503                 errno = 0;
3504                 return -1;
3505         }
3506
3507         old = cli_query_secdesc(cli, fnum, ctx);
3508
3509         if (!old) {
3510                 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
3511                 errno = 0;
3512                 return -1;
3513         }
3514
3515         cli_close(cli, fnum);
3516
3517         switch (mode) {
3518         case SMBC_XATTR_MODE_REMOVE_ALL:
3519                 old->dacl->num_aces = 0;
3520                 SAFE_FREE(old->dacl->ace);
3521                 SAFE_FREE(old->dacl);
3522                 old->off_dacl = 0;
3523                 dacl = old->dacl;
3524                 break;
3525
3526         case SMBC_XATTR_MODE_REMOVE:
3527                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3528                         BOOL found = False;
3529
3530                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3531                                 if (sec_ace_equal(&sd->dacl->ace[i],
3532                                                   &old->dacl->ace[j])) {
3533                                         uint32 k;
3534                                         for (k=j; k<old->dacl->num_aces-1;k++) {
3535                                                 old->dacl->ace[k] = old->dacl->ace[k+1];
3536                                         }
3537                                         old->dacl->num_aces--;
3538                                         if (old->dacl->num_aces == 0) {
3539                                                 SAFE_FREE(old->dacl->ace);
3540                                                 SAFE_FREE(old->dacl);
3541                                                 old->off_dacl = 0;
3542                                         }
3543                                         found = True;
3544                                         dacl = old->dacl;
3545                                         break;
3546                                 }
3547                         }
3548
3549                         if (!found) {
3550                                 err = ENOATTR;
3551                                 ret = -1;
3552                                 goto failed;
3553                         }
3554                 }
3555                 break;
3556
3557         case SMBC_XATTR_MODE_ADD:
3558                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3559                         BOOL found = False;
3560
3561                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
3562                                 if (sid_equal(&sd->dacl->ace[i].trustee,
3563                                               &old->dacl->ace[j].trustee)) {
3564                                         if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
3565                                                 err = EEXIST;
3566                                                 ret = -1;
3567                                                 goto failed;
3568                                         }
3569                                         old->dacl->ace[j] = sd->dacl->ace[i];
3570                                         ret = -1;
3571                                         found = True;
3572                                 }
3573                         }
3574
3575                         if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
3576                                 err = ENOATTR;
3577                                 ret = -1;
3578                                 goto failed;
3579                         }
3580                         
3581                         for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
3582                                 add_ace(&old->dacl, &sd->dacl->ace[i], ctx);
3583                         }
3584                 }
3585                 dacl = old->dacl;
3586                 break;
3587
3588         case SMBC_XATTR_MODE_SET:
3589                 old = sd;
3590                 owner_sid = old->owner_sid;
3591                 grp_sid = old->grp_sid;
3592                 dacl = old->dacl;
3593                 break;
3594
3595         case SMBC_XATTR_MODE_CHOWN:
3596                 owner_sid = sd->owner_sid;
3597                 break;
3598
3599         case SMBC_XATTR_MODE_CHGRP:
3600                 grp_sid = sd->grp_sid;
3601                 break;
3602         }
3603
3604         /* Denied ACE entries must come before allowed ones */
3605         sort_acl(old->dacl);
3606
3607         /* Create new security descriptor and set it */
3608         sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE, 
3609                            owner_sid, grp_sid, NULL, dacl, &sd_size);
3610
3611         fnum = cli_nt_create(cli, filename,
3612                              WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
3613
3614         if (fnum == -1) {
3615                 DEBUG(5, ("cacl_set failed to open %s: %s\n",
3616                           filename, cli_errstr(cli)));
3617                 errno = 0;
3618                 return -1;
3619         }
3620
3621         if (!cli_set_secdesc(cli, fnum, sd)) {
3622                 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
3623                 ret = -1;
3624         }
3625
3626         /* Clean up */
3627
3628  failed:
3629         cli_close(cli, fnum);
3630
3631         if (err != 0) {
3632                 errno = err;
3633         }
3634         
3635         return ret;
3636 }
3637
3638
3639 int smbc_setxattr_ctx(SMBCCTX *context,
3640                       const char *fname,
3641                       const char *name,
3642                       const void *value,
3643                       size_t size,
3644                       int flags)
3645 {
3646         int ret;
3647         SMBCSRV *srv;
3648         SMBCSRV *ipc_srv;
3649         fstring server, share, user, password, workgroup;
3650         pstring path;
3651         TALLOC_CTX *ctx;
3652         POLICY_HND pol;
3653
3654         if (!context || !context->internal ||
3655             !context->internal->_initialized) {
3656
3657                 errno = EINVAL;  /* Best I can think of ... */
3658                 return -1;
3659     
3660         }
3661
3662         if (!fname) {
3663
3664                 errno = EINVAL;
3665                 return -1;
3666
3667         }
3668   
3669         DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
3670                   fname, name, (int) size, (char *) value));
3671
3672         if (smbc_parse_path(context, fname,
3673                             server, sizeof(server),
3674                             share, sizeof(share),
3675                             path, sizeof(path),
3676                             user, sizeof(user),
3677                             password, sizeof(password),
3678                             NULL, 0)) {
3679                 errno = EINVAL;
3680                 return -1;
3681         }
3682
3683         if (user[0] == (char)0) fstrcpy(user, context->user);
3684
3685         fstrcpy(workgroup, context->workgroup);
3686
3687         srv = smbc_server(context, server, share, workgroup, user, password);
3688         if (!srv) {
3689                 return -1;  /* errno set by smbc_server */
3690         }
3691
3692         ipc_srv = smbc_attr_server(context, server, share,
3693                                    workgroup, user, password,
3694                                    &pol);
3695         if (!ipc_srv) {
3696                 return -1;
3697         }
3698         
3699         ctx = talloc_init("smbc_setxattr");
3700         if (!ctx) {
3701                 errno = ENOMEM;
3702                 return -1;
3703         }
3704
3705         /*
3706          * Are they asking to set an access control element or to set
3707          * the entire access control list?
3708          */
3709         if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3710             StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3711             StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3712             StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3713             StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3714
3715                 /* Yup. */
3716                 char *namevalue =
3717                         talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3718                 if (! namevalue) {
3719                         errno = ENOMEM;
3720                         ret = -1;
3721                 } else {
3722                         ret = cacl_set(ctx, &srv->cli,
3723                                        &ipc_srv->cli, &pol, path,
3724                                        namevalue,
3725                                        (*namevalue == '*'
3726                                         ? SMBC_XATTR_MODE_SET
3727                                         : SMBC_XATTR_MODE_ADD),
3728                                        flags);
3729                 }
3730                 talloc_destroy(ctx);
3731                 return ret;
3732         }
3733
3734         /*
3735          * Are they asking to set the owner?
3736          */
3737         if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3738             StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
3739
3740                 /* Yup. */
3741                 char *namevalue =
3742                         talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3743                 if (! namevalue) {
3744                         errno = ENOMEM;
3745                         ret = -1;
3746                 } else {
3747                         ret = cacl_set(ctx, &srv->cli,
3748                                        &ipc_srv->cli, &pol, path,
3749                                        namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3750                 }
3751                 talloc_destroy(ctx);
3752                 return ret;
3753         }
3754
3755         /*
3756          * Are they asking to set the group?
3757          */
3758         if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3759             StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
3760
3761                 /* Yup. */
3762                 char *namevalue =
3763                         talloc_asprintf(ctx, "%s:%s", name+19, (char *) value);
3764                 if (! namevalue) {
3765                         errno = ENOMEM;
3766                         ret = -1;
3767                 } else {
3768                         ret = cacl_set(ctx, &srv->cli,
3769                                        &ipc_srv->cli, &pol, path,
3770                                        namevalue, SMBC_XATTR_MODE_CHOWN, 0);
3771                 }
3772                 talloc_destroy(ctx);
3773                 return ret;
3774         }
3775
3776         /* Unsupported attribute name */
3777         talloc_destroy(ctx);
3778         errno = EINVAL;
3779         return -1;
3780 }
3781
3782 int smbc_getxattr_ctx(SMBCCTX *context,
3783                       const char *fname,
3784                       const char *name,
3785                       const void *value,
3786                       size_t size)
3787 {
3788         int ret;
3789         SMBCSRV *srv;
3790         SMBCSRV *ipc_srv;
3791         fstring server, share, user, password, workgroup;
3792         pstring path;
3793         TALLOC_CTX *ctx;
3794         POLICY_HND pol;
3795
3796         if (!context || !context->internal ||
3797             !context->internal->_initialized) {
3798
3799                 errno = EINVAL;  /* Best I can think of ... */
3800                 return -1;
3801     
3802         }
3803
3804         if (!fname) {
3805
3806                 errno = EINVAL;
3807                 return -1;
3808
3809         }
3810   
3811         DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
3812
3813         if (smbc_parse_path(context, fname,
3814                             server, sizeof(server),
3815                             share, sizeof(share),
3816                             path, sizeof(path),
3817                             user, sizeof(user),
3818                             password, sizeof(password),
3819                             NULL, 0)) {
3820                 errno = EINVAL;
3821                 return -1;
3822         }
3823
3824         if (user[0] == (char)0) fstrcpy(user, context->user);
3825
3826         fstrcpy(workgroup, context->workgroup);
3827
3828         srv = smbc_server(context, server, share, workgroup, user, password);
3829         if (!srv) {
3830                 return -1;  /* errno set by smbc_server */
3831         }
3832
3833         ipc_srv = smbc_attr_server(context, server, share,
3834                                    workgroup, user, password,
3835                                    &pol);
3836         if (!ipc_srv) {
3837                 return -1;
3838         }
3839         
3840         ctx = talloc_init("smbc:getxattr");
3841         if (!ctx) {
3842                 errno = ENOMEM;
3843                 return -1;
3844         }
3845
3846         /* Are they requesting a supported attribute? */
3847         if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3848             StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
3849             StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3850             StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3851             StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3852             StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3853             StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3854             StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3855             StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3856
3857                 /* Yup. */
3858                 ret = cacl_get(ctx, &srv->cli,
3859                                &ipc_srv->cli, &pol, 
3860                                (char *) path, (char *) name + 19,
3861                                (char *) value, size);
3862                 if (ret < 0 && errno == 0) {
3863                         errno = smbc_errno(context, &srv->cli);
3864                 }
3865                 talloc_destroy(ctx);
3866                 return ret;
3867         }
3868
3869         /* Unsupported attribute name */
3870         talloc_destroy(ctx);
3871         errno = EINVAL;
3872         return -1;
3873 }
3874
3875
3876 int smbc_removexattr_ctx(SMBCCTX *context,
3877                       const char *fname,
3878                       const char *name)
3879 {
3880         int ret;
3881         SMBCSRV *srv;
3882         SMBCSRV *ipc_srv;
3883         fstring server, share, user, password, workgroup;
3884         pstring path;
3885         TALLOC_CTX *ctx;
3886         POLICY_HND pol;
3887
3888         if (!context || !context->internal ||
3889             !context->internal->_initialized) {
3890
3891                 errno = EINVAL;  /* Best I can think of ... */
3892                 return -1;
3893     
3894         }
3895
3896         if (!fname) {
3897
3898                 errno = EINVAL;
3899                 return -1;
3900
3901         }
3902   
3903         DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
3904
3905         if (smbc_parse_path(context, fname,
3906                             server, sizeof(server),
3907                             share, sizeof(share),
3908                             path, sizeof(path),
3909                             user, sizeof(user),
3910                             password, sizeof(password),
3911                             NULL, 0)) {
3912                 errno = EINVAL;
3913                 return -1;
3914         }
3915
3916         if (user[0] == (char)0) fstrcpy(user, context->user);
3917
3918         fstrcpy(workgroup, context->workgroup);
3919
3920         srv = smbc_server(context, server, share, workgroup, user, password);
3921         if (!srv) {
3922                 return -1;  /* errno set by smbc_server */
3923         }
3924
3925         ipc_srv = smbc_attr_server(context, server, share,
3926                                    workgroup, user, password,
3927                                    &pol);
3928         if (!ipc_srv) {
3929                 return -1;
3930         }
3931         
3932         ipc_srv = smbc_attr_server(context, server, share,
3933                                    workgroup, user, password,
3934                                    &pol);
3935         if (!ipc_srv) {
3936                 return -1;
3937         }
3938         
3939         ctx = talloc_init("smbc_removexattr");
3940         if (!ctx) {
3941                 errno = ENOMEM;
3942                 return -1;
3943         }
3944
3945         /* Are they asking to set the entire ACL? */
3946         if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
3947             StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
3948
3949                 /* Yup. */
3950                 ret = cacl_set(ctx, &srv->cli,
3951                                &ipc_srv->cli, &pol, path,
3952                                NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
3953                 talloc_destroy(ctx);
3954                 return ret;
3955         }
3956
3957         /*
3958          * Are they asking to remove one or more spceific security descriptor
3959          * attributes?
3960          */
3961         if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
3962             StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
3963             StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
3964             StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
3965             StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
3966             StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
3967             StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
3968
3969                 /* Yup. */
3970                 ret = cacl_set(ctx, &srv->cli,
3971                                &ipc_srv->cli, &pol, path,
3972                                name + 19, SMBC_XATTR_MODE_REMOVE, 0);
3973                 talloc_destroy(ctx);
3974                 return ret;
3975         }
3976
3977         /* Unsupported attribute name */
3978         talloc_destroy(ctx);
3979         errno = EINVAL;
3980         return -1;
3981 }
3982
3983 int smbc_listxattr_ctx(SMBCCTX *context,
3984                        const char *fname,
3985                        char *list,
3986                        size_t size)
3987 {
3988         /*
3989          * This isn't quite what listxattr() is supposed to do.  This returns
3990          * the complete set of attributes, always, rather than only those
3991          * attribute names which actually exist for a file.  Hmmm...
3992          */
3993         const char supported[] =
3994                 "system.nt_sec_desc.revision\0"
3995                 "system.nt_sec_desc.owner\0"
3996                 "system.nt_sec_desc.owner+\0"
3997                 "system.nt_sec_desc.group\0"
3998                 "system.nt_sec_desc.group+\0"
3999                 "system.nt_sec_desc.acl\0"
4000                 "system.nt_sec_desc.acl+\0"
4001                 "system.nt_sec_desc.*\0"
4002                 "system.nt_sec_desc.*+\0"
4003                 ;
4004
4005         if (size == 0) {
4006                 return sizeof(supported);
4007         }
4008
4009         if (sizeof(supported) > size) {
4010                 errno = ERANGE;
4011                 return -1;
4012         }
4013
4014         /* this can't be strcpy() because there are embedded null characters */
4015         memcpy(list, supported, sizeof(supported));
4016         return sizeof(supported);
4017 }
4018
4019
4020 /*
4021  * Open a print file to be written to by other calls
4022  */
4023
4024 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
4025 {
4026         fstring server, share, user, password;
4027         pstring path;
4028         
4029         if (!context || !context->internal ||
4030             !context->internal->_initialized) {
4031
4032                 errno = EINVAL;
4033                 return NULL;
4034     
4035         }
4036
4037         if (!fname) {
4038
4039                 errno = EINVAL;
4040                 return NULL;
4041
4042         }
4043   
4044         DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
4045
4046         if (smbc_parse_path(context, fname,
4047                             server, sizeof(server),
4048                             share, sizeof(share),
4049                             path, sizeof(path),
4050                             user, sizeof(user),
4051                             password, sizeof(password),
4052                             NULL, 0)) {
4053                 errno = EINVAL;
4054                 return NULL;
4055         }
4056
4057         /* What if the path is empty, or the file exists? */
4058
4059         return context->open(context, fname, O_WRONLY, 666);
4060
4061 }
4062
4063 /*
4064  * Routine to print a file on a remote server ...
4065  *
4066  * We open the file, which we assume to be on a remote server, and then
4067  * copy it to a print file on the share specified by printq.
4068  */
4069
4070 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
4071 {
4072         SMBCFILE *fid1, *fid2;
4073         int bytes, saverr, tot_bytes = 0;
4074         char buf[4096];
4075
4076         if (!c_file || !c_file->internal->_initialized || !c_print ||
4077             !c_print->internal->_initialized) {
4078
4079                 errno = EINVAL;
4080                 return -1;
4081
4082         }
4083
4084         if (!fname && !printq) {
4085
4086                 errno = EINVAL;
4087                 return -1;
4088
4089         }
4090
4091         /* Try to open the file for reading ... */
4092
4093         if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
4094                 
4095                 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
4096                 return -1;  /* smbc_open sets errno */
4097                 
4098         }
4099
4100         /* Now, try to open the printer file for writing */
4101
4102         if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
4103
4104                 saverr = errno;  /* Save errno */
4105                 c_file->close(c_file, fid1);
4106                 errno = saverr;
4107                 return -1;
4108
4109         }
4110
4111         while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
4112
4113                 tot_bytes += bytes;
4114
4115                 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
4116
4117                         saverr = errno;
4118                         c_file->close(c_file, fid1);
4119                         c_print->close(c_print, fid2);
4120                         errno = saverr;
4121
4122                 }
4123
4124         }
4125
4126         saverr = errno;
4127
4128         c_file->close(c_file, fid1);  /* We have to close these anyway */
4129         c_print->close(c_print, fid2);
4130
4131         if (bytes < 0) {
4132
4133                 errno = saverr;
4134                 return -1;
4135
4136         }
4137
4138         return tot_bytes;
4139
4140 }
4141
4142 /*
4143  * Routine to list print jobs on a printer share ...
4144  */
4145
4146 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
4147 {
4148         SMBCSRV *srv;
4149         fstring server, share, user, password, workgroup;
4150         pstring path;
4151
4152         if (!context || !context->internal ||
4153             !context->internal->_initialized) {
4154
4155                 errno = EINVAL;
4156                 return -1;
4157
4158         }
4159
4160         if (!fname) {
4161                 
4162                 errno = EINVAL;
4163                 return -1;
4164
4165         }
4166   
4167         DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
4168
4169         if (smbc_parse_path(context, fname,
4170                             server, sizeof(server),
4171                             share, sizeof(share),
4172                             path, sizeof(path),
4173                             user, sizeof(user),
4174                             password, sizeof(password),
4175                             NULL, 0)) {
4176                 errno = EINVAL;
4177                 return -1;
4178         }
4179
4180         if (user[0] == (char)0) fstrcpy(user, context->user);
4181         
4182         fstrcpy(workgroup, context->workgroup);
4183
4184         srv = smbc_server(context, server, share, workgroup, user, password);
4185
4186         if (!srv) {
4187
4188                 return -1;  /* errno set by smbc_server */
4189
4190         }
4191
4192         if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
4193
4194                 errno = smbc_errno(context, &srv->cli);
4195                 return -1;
4196
4197         }
4198         
4199         return 0;
4200
4201 }
4202
4203 /*
4204  * Delete a print job from a remote printer share
4205  */
4206
4207 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
4208 {
4209         SMBCSRV *srv;
4210         fstring server, share, user, password, workgroup;
4211         pstring path;
4212         int err;
4213
4214         if (!context || !context->internal ||
4215             !context->internal->_initialized) {
4216
4217                 errno = EINVAL;
4218                 return -1;
4219
4220         }
4221
4222         if (!fname) {
4223
4224                 errno = EINVAL;
4225                 return -1;
4226
4227         }
4228   
4229         DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
4230
4231         if (smbc_parse_path(context, fname,
4232                             server, sizeof(server),
4233                             share, sizeof(share),
4234                             path, sizeof(path),
4235                             user, sizeof(user),
4236                             password, sizeof(password),
4237                             NULL, 0)) {
4238                 errno = EINVAL;
4239                 return -1;
4240         }
4241
4242         if (user[0] == (char)0) fstrcpy(user, context->user);
4243
4244         fstrcpy(workgroup, context->workgroup);
4245
4246         srv = smbc_server(context, server, share, workgroup, user, password);
4247
4248         if (!srv) {
4249
4250                 return -1;  /* errno set by smbc_server */
4251
4252         }
4253
4254         if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
4255
4256                 if (err < 0)
4257                         errno = smbc_errno(context, &srv->cli);
4258                 else if (err == ERRnosuchprintjob)
4259                         errno = EINVAL;
4260                 return -1;
4261
4262         }
4263
4264         return 0;
4265
4266 }
4267
4268 /*
4269  * Get a new empty handle to fill in with your own info 
4270  */
4271 SMBCCTX * smbc_new_context(void)
4272 {
4273         SMBCCTX * context;
4274
4275         context = malloc(sizeof(SMBCCTX));
4276         if (!context) {
4277                 errno = ENOMEM;
4278                 return NULL;
4279         }
4280
4281         ZERO_STRUCTP(context);
4282
4283         context->internal = malloc(sizeof(struct smbc_internal_data));
4284         if (!context->internal) {
4285                 errno = ENOMEM;
4286                 return NULL;
4287         }
4288
4289         ZERO_STRUCTP(context->internal);
4290
4291         
4292         /* ADD REASONABLE DEFAULTS */
4293         context->debug            = 0;
4294         context->timeout          = 20000; /* 20 seconds */
4295
4296         context->open             = smbc_open_ctx;
4297         context->creat            = smbc_creat_ctx;
4298         context->read             = smbc_read_ctx;
4299         context->write            = smbc_write_ctx;
4300         context->close            = smbc_close_ctx;
4301         context->unlink           = smbc_unlink_ctx;
4302         context->rename           = smbc_rename_ctx;
4303         context->lseek            = smbc_lseek_ctx;
4304         context->stat             = smbc_stat_ctx;
4305         context->fstat            = smbc_fstat_ctx;
4306         context->opendir          = smbc_opendir_ctx;
4307         context->closedir         = smbc_closedir_ctx;
4308         context->readdir          = smbc_readdir_ctx;
4309         context->getdents         = smbc_getdents_ctx;
4310         context->mkdir            = smbc_mkdir_ctx;
4311         context->rmdir            = smbc_rmdir_ctx;
4312         context->telldir          = smbc_telldir_ctx;
4313         context->lseekdir         = smbc_lseekdir_ctx;
4314         context->fstatdir         = smbc_fstatdir_ctx;
4315         context->chmod            = smbc_chmod_ctx;
4316         context->utimes           = smbc_utimes_ctx;
4317         context->setxattr         = smbc_setxattr_ctx;
4318         context->getxattr         = smbc_getxattr_ctx;
4319         context->removexattr      = smbc_removexattr_ctx;
4320         context->listxattr        = smbc_listxattr_ctx;
4321         context->open_print_job   = smbc_open_print_job_ctx;
4322         context->print_file       = smbc_print_file_ctx;
4323         context->list_print_jobs  = smbc_list_print_jobs_ctx;
4324         context->unlink_print_job = smbc_unlink_print_job_ctx;
4325
4326         context->callbacks.check_server_fn      = smbc_check_server;
4327         context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
4328
4329         smbc_default_cache_functions(context);
4330
4331         return context;
4332 }
4333
4334 /* 
4335  * Free a context
4336  *
4337  * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed 
4338  * and thus you'll be leaking memory if not handled properly.
4339  *
4340  */
4341 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
4342 {
4343         if (!context) {
4344                 errno = EBADF;
4345                 return 1;
4346         }
4347         
4348         if (shutdown_ctx) {
4349                 SMBCFILE * f;
4350                 DEBUG(1,("Performing aggressive shutdown.\n"));
4351                 
4352                 f = context->internal->_files;
4353                 while (f) {
4354                         context->close(context, f);
4355                         f = f->next;
4356                 }
4357                 context->internal->_files = NULL;
4358
4359                 /* First try to remove the servers the nice way. */
4360                 if (context->callbacks.purge_cached_fn(context)) {
4361                         SMBCSRV * s;
4362                         SMBCSRV * next;
4363                         DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
4364                         s = context->internal->_servers;
4365                         while (s) {
4366                                 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n", s, s->cli.fd));
4367                                 cli_shutdown(&s->cli);
4368                                 context->callbacks.remove_cached_srv_fn(context, s);
4369                                 next = s->next;
4370                                 DLIST_REMOVE(context->internal->_servers, s);
4371                                 SAFE_FREE(s);
4372                                 s = next;
4373                         }
4374                         context->internal->_servers = NULL;
4375                 }
4376         }
4377         else {
4378                 /* This is the polite way */    
4379                 if (context->callbacks.purge_cached_fn(context)) {
4380                         DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
4381                         errno = EBUSY;
4382                         return 1;
4383                 }
4384                 if (context->internal->_servers) {
4385                         DEBUG(1, ("Active servers in context, free_context failed.\n"));
4386                         errno = EBUSY;
4387                         return 1;
4388                 }
4389                 if (context->internal->_files) {
4390                         DEBUG(1, ("Active files in context, free_context failed.\n"));
4391                         errno = EBUSY;
4392                         return 1;
4393                 }               
4394         }
4395
4396         /* Things we have to clean up */
4397         SAFE_FREE(context->workgroup);
4398         SAFE_FREE(context->netbios_name);
4399         SAFE_FREE(context->user);
4400         
4401         DEBUG(3, ("Context %p succesfully freed\n", context));
4402         SAFE_FREE(context->internal);
4403         SAFE_FREE(context);
4404         return 0;
4405 }
4406
4407
4408 /*
4409  * Initialise the library etc 
4410  *
4411  * We accept a struct containing handle information.
4412  * valid values for info->debug from 0 to 100,
4413  * and insist that info->fn must be non-null.
4414  */
4415 SMBCCTX * smbc_init_context(SMBCCTX * context)
4416 {
4417         pstring conf;
4418         int pid;
4419         char *user = NULL, *home = NULL;
4420
4421         if (!context || !context->internal) {
4422                 errno = EBADF;
4423                 return NULL;
4424         }
4425
4426         /* Do not initialise the same client twice */
4427         if (context->internal->_initialized) { 
4428                 return 0;
4429         }
4430
4431         if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
4432
4433                 errno = EINVAL;
4434                 return NULL;
4435
4436         }
4437
4438         if (!smbc_initialized) {
4439                 /* Do some library wide intialisations the first time we get called */
4440
4441                 /* Set this to what the user wants */
4442                 DEBUGLEVEL = context->debug;
4443                 
4444                 setup_logging( "libsmbclient", True);
4445
4446                 /* Here we would open the smb.conf file if needed ... */
4447                 
4448                 home = getenv("HOME");
4449
4450                 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
4451                 
4452                 load_interfaces();  /* Load the list of interfaces ... */
4453                 
4454                 in_client = True; /* FIXME, make a param */
4455
4456                 if (!lp_load(conf, True, False, False)) {
4457
4458                         /*
4459                          * Well, if that failed, try the dyn_CONFIGFILE
4460                          * Which points to the standard locn, and if that
4461                          * fails, silently ignore it and use the internal
4462                          * defaults ...
4463                          */
4464
4465                    if (!lp_load(dyn_CONFIGFILE, True, False, False)) {
4466                       DEBUG(5, ("Could not load either config file: %s or %s\n",
4467                              conf, dyn_CONFIGFILE));
4468                    }
4469                 }
4470
4471                 reopen_logs();  /* Get logging working ... */
4472         
4473                 /* 
4474                  * Block SIGPIPE (from lib/util_sock.c: write())  
4475                  * It is not needed and should not stop execution 
4476                  */
4477                 BlockSignals(True, SIGPIPE);
4478                 
4479                 /* Done with one-time initialisation */
4480                 smbc_initialized = 1; 
4481
4482         }
4483         
4484         if (!context->user) {
4485                 /*
4486                  * FIXME: Is this the best way to get the user info? 
4487                  */
4488                 user = getenv("USER");
4489                 /* walk around as "guest" if no username can be found */
4490                 if (!user) context->user = strdup("guest");
4491                 else context->user = strdup(user);
4492         }
4493
4494         if (!context->netbios_name) {
4495                 /*
4496                  * We try to get our netbios name from the config. If that fails we fall
4497                  * back on constructing our netbios name from our hostname etc
4498                  */
4499                 if (global_myname()) {
4500                         context->netbios_name = strdup(global_myname());
4501                 }
4502                 else {
4503                         /*
4504                          * Hmmm, I want to get hostname as well, but I am too lazy for the moment
4505                          */
4506                         pid = sys_getpid();
4507                         context->netbios_name = malloc(17);
4508                         if (!context->netbios_name) {
4509                                 errno = ENOMEM;
4510                                 return NULL;
4511                         }
4512                         slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
4513                 }
4514         }
4515
4516         DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
4517
4518         if (!context->workgroup) {
4519                 if (lp_workgroup()) {
4520                         context->workgroup = strdup(lp_workgroup());
4521                 }
4522                 else {
4523                         /* TODO: Think about a decent default workgroup */
4524                         context->workgroup = strdup("samba");
4525                 }
4526         }
4527
4528         DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
4529                                         
4530         /* shortest timeout is 1 second */
4531         if (context->timeout > 0 && context->timeout < 1000) 
4532                 context->timeout = 1000;
4533
4534         /*
4535          * FIXME: Should we check the function pointers here? 
4536          */
4537
4538         context->internal->_initialized = 1;
4539         
4540         return context;
4541 }