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