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