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