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