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