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