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