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