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