fb04d143a588836226f1ad0d0991acc3464dbc28
[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                 POLICY_HND *pol)
1042 {
1043         int flags;
1044         struct sockaddr_storage ss;
1045         struct cli_state *ipc_cli;
1046         struct rpc_pipe_client *pipe_hnd;
1047         NTSTATUS nt_status;
1048         SMBCSRV *ipc_srv=NULL;
1049
1050         /*
1051          * See if we've already created this special connection.  Reference
1052          * our "special" share name '*IPC$', which is an impossible real share
1053          * name due to the leading asterisk.
1054          */
1055         ipc_srv = find_server(ctx, context, server, "*IPC$",
1056                               pp_workgroup, pp_username, pp_password);
1057         if (!ipc_srv) {
1058
1059                 /* We didn't find a cached connection.  Get the password */
1060                 if (!*pp_password || (*pp_password)[0] == '\0') {
1061                         /* ... then retrieve it now. */
1062                         call_auth_fn(ctx, context, server, share,
1063                                 pp_workgroup, pp_username, pp_password);
1064                         if (!*pp_workgroup || !*pp_username || !*pp_password) {
1065                                 errno = ENOMEM;
1066                                 return NULL;
1067                         }
1068                 }
1069
1070                 flags = 0;
1071                 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
1072                         flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
1073                 }
1074
1075                 zero_addr(&ss);
1076                 nt_status = cli_full_connection(&ipc_cli,
1077                                                 global_myname(), server,
1078                                                 &ss, 0, "IPC$", "?????",
1079                                                 *pp_username,
1080                                                 *pp_workgroup,
1081                                                 *pp_password,
1082                                                 flags,
1083                                                 Undefined, NULL);
1084                 if (! NT_STATUS_IS_OK(nt_status)) {
1085                         DEBUG(1,("cli_full_connection failed! (%s)\n",
1086                                  nt_errstr(nt_status)));
1087                         errno = ENOTSUP;
1088                         return NULL;
1089                 }
1090
1091                 if (context->internal->_smb_encryption_level) {
1092                         /* Attempt UNIX smb encryption. */
1093                         if (!NT_STATUS_IS_OK(cli_force_encryption(ipc_cli,
1094                                                 *pp_username,
1095                                                 *pp_password,
1096                                                 *pp_workgroup))) {
1097
1098                                 /*
1099                                  * context->internal->_smb_encryption_level == 1
1100                                  * means don't fail if encryption can't be negotiated,
1101                                  * == 2 means fail if encryption can't be negotiated.
1102                                  */
1103
1104                                 DEBUG(4,(" SMB encrypt failed on IPC$\n"));
1105
1106                                 if (context->internal->_smb_encryption_level == 2) {
1107                                         cli_shutdown(ipc_cli);
1108                                         errno = EPERM;
1109                                         return NULL;
1110                                 }
1111                         }
1112                         DEBUG(4,(" SMB encrypt ok on IPC$\n"));
1113                 }
1114
1115                 ipc_srv = SMB_MALLOC_P(SMBCSRV);
1116                 if (!ipc_srv) {
1117                         errno = ENOMEM;
1118                         cli_shutdown(ipc_cli);
1119                         return NULL;
1120                 }
1121
1122                 ZERO_STRUCTP(ipc_srv);
1123                 ipc_srv->cli = ipc_cli;
1124
1125                 if (pol) {
1126                         pipe_hnd = cli_rpc_pipe_open_noauth(ipc_srv->cli,
1127                                                             PI_LSARPC,
1128                                                             &nt_status);
1129                         if (!pipe_hnd) {
1130                                 DEBUG(1, ("cli_nt_session_open fail!\n"));
1131                                 errno = ENOTSUP;
1132                                 cli_shutdown(ipc_srv->cli);
1133                                 free(ipc_srv);
1134                                 return NULL;
1135                         }
1136
1137                         /*
1138                          * Some systems don't support
1139                          * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
1140                          * so we might as well do it too.
1141                          */
1142
1143                         nt_status = rpccli_lsa_open_policy(
1144                                 pipe_hnd,
1145                                 talloc_tos(),
1146                                 True,
1147                                 GENERIC_EXECUTE_ACCESS,
1148                                 pol);
1149
1150                         if (!NT_STATUS_IS_OK(nt_status)) {
1151                                 errno = smbc_errno(context, ipc_srv->cli);
1152                                 cli_shutdown(ipc_srv->cli);
1153                                 return NULL;
1154                         }
1155                 }
1156
1157                 /* now add it to the cache (internal or external) */
1158
1159                 errno = 0;      /* let cache function set errno if it likes */
1160                 if ((context->callbacks.add_cached_srv_fn)(context, ipc_srv,
1161                                                         server,
1162                                                         "*IPC$",
1163                                                         *pp_workgroup,
1164                                                         *pp_username)) {
1165                         DEBUG(3, (" Failed to add server to cache\n"));
1166                         if (errno == 0) {
1167                                 errno = ENOMEM;
1168                         }
1169                         cli_shutdown(ipc_srv->cli);
1170                         free(ipc_srv);
1171                         return NULL;
1172                 }
1173
1174                 DLIST_ADD(context->internal->_servers, ipc_srv);
1175         }
1176
1177         return ipc_srv;
1178 }
1179
1180 /*
1181  * Routine to open() a file ...
1182  */
1183
1184 static SMBCFILE *
1185 smbc_open_ctx(SMBCCTX *context,
1186               const char *fname,
1187               int flags,
1188               mode_t mode)
1189 {
1190         char *server = NULL, *share = NULL, *user = NULL, *password = NULL, *workgroup = NULL;
1191         char *path = NULL;
1192         char *targetpath = NULL;
1193         struct cli_state *targetcli = NULL;
1194         SMBCSRV *srv   = NULL;
1195         SMBCFILE *file = NULL;
1196         int fd;
1197         TALLOC_CTX *frame = talloc_stackframe();
1198
1199         if (!context || !context->internal ||
1200             !context->internal->_initialized) {
1201
1202                 errno = EINVAL;  /* Best I can think of ... */
1203                 TALLOC_FREE(frame);
1204                 return NULL;
1205
1206         }
1207
1208         if (!fname) {
1209
1210                 errno = EINVAL;
1211                 TALLOC_FREE(frame);
1212                 return NULL;
1213
1214         }
1215
1216         if (smbc_parse_path(frame,
1217                                 context,
1218                                 fname,
1219                                 &workgroup,
1220                                 &server,
1221                                 &share,
1222                                 &path,
1223                                 &user,
1224                                 &password,
1225                                 NULL)) {
1226                 errno = EINVAL;
1227                 TALLOC_FREE(frame);
1228                 return NULL;
1229         }
1230
1231         if (!user || user[0] == (char)0) {
1232                 user = talloc_strdup(frame, context->user);
1233                 if (!user) {
1234                         errno = ENOMEM;
1235                         TALLOC_FREE(frame);
1236                         return NULL;
1237                 }
1238         }
1239
1240         srv = smbc_server(frame, context, True,
1241                           server, share, &workgroup, &user, &password);
1242
1243         if (!srv) {
1244                 if (errno == EPERM) errno = EACCES;
1245                 TALLOC_FREE(frame);
1246                 return NULL;  /* smbc_server sets errno */
1247         }
1248
1249         /* Hmmm, the test for a directory is suspect here ... FIXME */
1250
1251         if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1252                 fd = -1;
1253         } else {
1254                 file = SMB_MALLOC_P(SMBCFILE);
1255
1256                 if (!file) {
1257                         errno = ENOMEM;
1258                         TALLOC_FREE(frame);
1259                         return NULL;
1260                 }
1261
1262                 ZERO_STRUCTP(file);
1263
1264                 /*d_printf(">>>open: resolving %s\n", path);*/
1265                 if (!cli_resolve_path(frame, "", srv->cli, path, &targetcli, &targetpath)) {
1266                         d_printf("Could not resolve %s\n", path);
1267                         SAFE_FREE(file);
1268                         TALLOC_FREE(frame);
1269                         return NULL;
1270                 }
1271                 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1272
1273                 if ((fd = cli_open(targetcli, targetpath, flags,
1274                                    context->internal->_share_mode)) < 0) {
1275
1276                         /* Handle the error ... */
1277
1278                         SAFE_FREE(file);
1279                         errno = smbc_errno(context, targetcli);
1280                         TALLOC_FREE(frame);
1281                         return NULL;
1282
1283                 }
1284
1285                 /* Fill in file struct */
1286
1287                 file->cli_fd  = fd;
1288                 file->fname   = SMB_STRDUP(fname);
1289                 file->srv     = srv;
1290                 file->offset  = 0;
1291                 file->file    = True;
1292
1293                 DLIST_ADD(context->internal->_files, file);
1294
1295                 /*
1296                  * If the file was opened in O_APPEND mode, all write
1297                  * operations should be appended to the file.  To do that,
1298                  * though, using this protocol, would require a getattrE()
1299                  * call for each and every write, to determine where the end
1300                  * of the file is. (There does not appear to be an append flag
1301                  * in the protocol.)  Rather than add all of that overhead of
1302                  * retrieving the current end-of-file offset prior to each
1303                  * write operation, we'll assume that most append operations
1304                  * will continuously write, so we'll just set the offset to
1305                  * the end of the file now and hope that's adequate.
1306                  *
1307                  * Note to self: If this proves inadequate, and O_APPEND
1308                  * should, in some cases, be forced for each write, add a
1309                  * field in the context options structure, for
1310                  * "strict_append_mode" which would select between the current
1311                  * behavior (if FALSE) or issuing a getattrE() prior to each
1312                  * write and forcing the write to the end of the file (if
1313                  * TRUE).  Adding that capability will likely require adding
1314                  * an "append" flag into the _SMBCFILE structure to track
1315                  * whether a file was opened in O_APPEND mode.  -- djl
1316                  */
1317                 if (flags & O_APPEND) {
1318                         if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1319                                 (void) smbc_close_ctx(context, file);
1320                                 errno = ENXIO;
1321                                 TALLOC_FREE(frame);
1322                                 return NULL;
1323                         }
1324                 }
1325
1326                 TALLOC_FREE(frame);
1327                 return file;
1328
1329         }
1330
1331         /* Check if opendir needed ... */
1332
1333         if (fd == -1) {
1334                 int eno = 0;
1335
1336                 eno = smbc_errno(context, srv->cli);
1337                 file = (context->opendir)(context, fname);
1338                 if (!file) errno = eno;
1339                 TALLOC_FREE(frame);
1340                 return file;
1341
1342         }
1343
1344         errno = EINVAL; /* FIXME, correct errno ? */
1345         TALLOC_FREE(frame);
1346         return NULL;
1347
1348 }
1349
1350 /*
1351  * Routine to create a file 
1352  */
1353
1354 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1355
1356 static SMBCFILE *
1357 smbc_creat_ctx(SMBCCTX *context,
1358                const char *path,
1359                mode_t mode)
1360 {
1361
1362         if (!context || !context->internal ||
1363             !context->internal->_initialized) {
1364
1365                 errno = EINVAL;
1366                 return NULL;
1367
1368         }
1369
1370         return smbc_open_ctx(context, path, creat_bits, mode);
1371 }
1372
1373 /*
1374  * Routine to read() a file ...
1375  */
1376
1377 static ssize_t
1378 smbc_read_ctx(SMBCCTX *context,
1379               SMBCFILE *file,
1380               void *buf,
1381               size_t count)
1382 {
1383         int ret;
1384         char *server = NULL, *share = NULL, *user = NULL, *password = NULL;
1385         char *path = NULL;
1386         char *targetpath = NULL;
1387         struct cli_state *targetcli = NULL;
1388         TALLOC_CTX *frame = talloc_stackframe();
1389
1390         /*
1391          * offset:
1392          *
1393          * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1394          * appears to pass file->offset (which is type off_t) differently than
1395          * a local variable of type off_t.  Using local variable "offset" in
1396          * the call to cli_read() instead of file->offset fixes a problem
1397          * retrieving data at an offset greater than 4GB.
1398          */
1399         off_t offset;
1400
1401         if (!context || !context->internal ||
1402             !context->internal->_initialized) {
1403                 errno = EINVAL;
1404                 TALLOC_FREE(frame);
1405                 return -1;
1406
1407         }
1408
1409         DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1410
1411         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1412                 errno = EBADF;
1413                 TALLOC_FREE(frame);
1414                 return -1;
1415
1416         }
1417
1418         offset = file->offset;
1419
1420         /* Check that the buffer exists ... */
1421
1422         if (buf == NULL) {
1423                 errno = EINVAL;
1424                 TALLOC_FREE(frame);
1425                 return -1;
1426
1427         }
1428
1429         /*d_printf(">>>read: parsing %s\n", file->fname);*/
1430         if (smbc_parse_path(frame,
1431                                 context,
1432                                 file->fname,
1433                                 NULL,
1434                                 &server,
1435                                 &share,
1436                                 &path,
1437                                 &user,
1438                                 &password,
1439                                 NULL)) {
1440                 errno = EINVAL;
1441                 TALLOC_FREE(frame);
1442                 return -1;
1443         }
1444
1445         /*d_printf(">>>read: resolving %s\n", path);*/
1446         if (!cli_resolve_path(frame, "", file->srv->cli, path,
1447                               &targetcli, &targetpath)) {
1448                 d_printf("Could not resolve %s\n", path);
1449                 TALLOC_FREE(frame);
1450                 return -1;
1451         }
1452         /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1453
1454         ret = cli_read(targetcli, file->cli_fd, (char *)buf, offset, count);
1455
1456         if (ret < 0) {
1457
1458                 errno = smbc_errno(context, targetcli);
1459                 TALLOC_FREE(frame);
1460                 return -1;
1461
1462         }
1463
1464         file->offset += ret;
1465
1466         DEBUG(4, ("  --> %d\n", ret));
1467
1468         TALLOC_FREE(frame);
1469         return ret;  /* Success, ret bytes of data ... */
1470
1471 }
1472
1473 /*
1474  * Routine to write() a file ...
1475  */
1476
1477 static ssize_t
1478 smbc_write_ctx(SMBCCTX *context,
1479                SMBCFILE *file,
1480                void *buf,
1481                size_t count)
1482 {
1483         int ret;
1484         off_t offset;
1485         char *server = NULL, *share = NULL, *user = NULL, *password = NULL;
1486         char *path = NULL;
1487         char *targetpath = NULL;
1488         struct cli_state *targetcli = NULL;
1489         TALLOC_CTX *frame = talloc_stackframe();
1490
1491         /* First check all pointers before dereferencing them */
1492
1493         if (!context || !context->internal ||
1494             !context->internal->_initialized) {
1495                 errno = EINVAL;
1496                 TALLOC_FREE(frame);
1497                 return -1;
1498
1499         }
1500
1501         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1502                 errno = EBADF;
1503                 TALLOC_FREE(frame);
1504                 return -1;
1505         }
1506
1507         /* Check that the buffer exists ... */
1508
1509         if (buf == NULL) {
1510                 errno = EINVAL;
1511                 TALLOC_FREE(frame);
1512                 return -1;
1513
1514         }
1515
1516         offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1517
1518         /*d_printf(">>>write: parsing %s\n", file->fname);*/
1519         if (smbc_parse_path(frame,
1520                                 context,
1521                                 file->fname,
1522                                 NULL,
1523                                 &server,
1524                                 &share,
1525                                 &path,
1526                                 &user,
1527                                 &password,
1528                                 NULL)) {
1529                 errno = EINVAL;
1530                 TALLOC_FREE(frame);
1531                 return -1;
1532         }
1533
1534         /*d_printf(">>>write: resolving %s\n", path);*/
1535         if (!cli_resolve_path(frame, "", file->srv->cli, path,
1536                               &targetcli, &targetpath)) {
1537                 d_printf("Could not resolve %s\n", path);
1538                 TALLOC_FREE(frame);
1539                 return -1;
1540         }
1541         /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1542
1543         ret = cli_write(targetcli, file->cli_fd, 0, (char *)buf, offset, count);
1544
1545         if (ret <= 0) {
1546                 errno = smbc_errno(context, targetcli);
1547                 TALLOC_FREE(frame);
1548                 return -1;
1549
1550         }
1551
1552         file->offset += ret;
1553
1554         TALLOC_FREE(frame);
1555         return ret;  /* Success, 0 bytes of data ... */
1556 }
1557
1558 /*
1559  * Routine to close() a file ...
1560  */
1561
1562 static int
1563 smbc_close_ctx(SMBCCTX *context,
1564                SMBCFILE *file)
1565 {
1566         SMBCSRV *srv;
1567         char *server = NULL, *share = NULL, *user = NULL, *password = NULL;
1568         char *path = NULL;
1569         char *targetpath = NULL;
1570         struct cli_state *targetcli = NULL;
1571         TALLOC_CTX *frame = talloc_stackframe();
1572
1573         if (!context || !context->internal ||
1574             !context->internal->_initialized) {
1575
1576                 errno = EINVAL;
1577                 TALLOC_FREE(frame);
1578                 return -1;
1579         }
1580
1581         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1582                 errno = EBADF;
1583                 TALLOC_FREE(frame);
1584                 return -1;
1585         }
1586
1587         /* IS a dir ... */
1588         if (!file->file) {
1589                 TALLOC_FREE(frame);
1590                 return (context->closedir)(context, file);
1591         }
1592
1593         /*d_printf(">>>close: parsing %s\n", file->fname);*/
1594         if (smbc_parse_path(frame,
1595                                 context,
1596                                 file->fname,
1597                                 NULL,
1598                                 &server,
1599                                 &share,
1600                                 &path,
1601                                 &user,
1602                                 &password,
1603                                 NULL)) {
1604                 errno = EINVAL;
1605                 TALLOC_FREE(frame);
1606                 return -1;
1607         }
1608
1609         /*d_printf(">>>close: resolving %s\n", path);*/
1610         if (!cli_resolve_path(frame, "", file->srv->cli, path,
1611                               &targetcli, &targetpath)) {
1612                 d_printf("Could not resolve %s\n", path);
1613                 TALLOC_FREE(frame);
1614                 return -1;
1615         }
1616         /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1617
1618         if (!cli_close(targetcli, file->cli_fd)) {
1619
1620                 DEBUG(3, ("cli_close failed on %s. purging server.\n", 
1621                           file->fname));
1622                 /* Deallocate slot and remove the server 
1623                  * from the server cache if unused */
1624                 errno = smbc_errno(context, targetcli);
1625                 srv = file->srv;
1626                 DLIST_REMOVE(context->internal->_files, file);
1627                 SAFE_FREE(file->fname);
1628                 SAFE_FREE(file);
1629                 (context->callbacks.remove_unused_server_fn)(context, srv);
1630                 TALLOC_FREE(frame);
1631                 return -1;
1632
1633         }
1634
1635         DLIST_REMOVE(context->internal->_files, file);
1636         SAFE_FREE(file->fname);
1637         SAFE_FREE(file);
1638         TALLOC_FREE(frame);
1639
1640         return 0;
1641 }
1642
1643 /*
1644  * Get info from an SMB server on a file. Use a qpathinfo call first
1645  * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1646  */
1647 static bool
1648 smbc_getatr(SMBCCTX * context,
1649             SMBCSRV *srv,
1650             char *path,
1651             uint16 *mode,
1652             SMB_OFF_T *size,
1653             struct timespec *create_time_ts,
1654             struct timespec *access_time_ts,
1655             struct timespec *write_time_ts,
1656             struct timespec *change_time_ts,
1657             SMB_INO_T *ino)
1658 {
1659         char *fixedpath = NULL;
1660         char *targetpath = NULL;
1661         struct cli_state *targetcli = NULL;
1662         time_t write_time;
1663         TALLOC_CTX *frame = talloc_stackframe();
1664
1665         if (!context || !context->internal ||
1666             !context->internal->_initialized) {
1667                 errno = EINVAL;
1668                 TALLOC_FREE(frame);
1669                 return -1;
1670         }
1671
1672         /* path fixup for . and .. */
1673         if (strequal(path, ".") || strequal(path, "..")) {
1674                 fixedpath = talloc_strdup(frame, "\\");
1675                 if (!fixedpath) {
1676                         errno = ENOMEM;
1677                         TALLOC_FREE(frame);
1678                         return -1;
1679                 }
1680         } else {
1681                 fixedpath = talloc_strdup(frame, path);
1682                 if (!fixedpath) {
1683                         errno = ENOMEM;
1684                         TALLOC_FREE(frame);
1685                         return -1;
1686                 }
1687                 trim_string(fixedpath, NULL, "\\..");
1688                 trim_string(fixedpath, NULL, "\\.");
1689         }
1690         DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1691
1692         if (!cli_resolve_path(frame, "", srv->cli, fixedpath,
1693                                 &targetcli, &targetpath)) {
1694                 d_printf("Couldn't resolve %s\n", path);
1695                 TALLOC_FREE(frame);
1696                 return False;
1697         }
1698
1699         if (!srv->no_pathinfo2 &&
1700             cli_qpathinfo2(targetcli, targetpath,
1701                            create_time_ts,
1702                            access_time_ts,
1703                            write_time_ts,
1704                            change_time_ts,
1705                            size, mode, ino)) {
1706                 TALLOC_FREE(frame);
1707                 return True;
1708         }
1709
1710         /* if this is NT then don't bother with the getatr */
1711         if (targetcli->capabilities & CAP_NT_SMBS) {
1712                 errno = EPERM;
1713                 TALLOC_FREE(frame);
1714                 return False;
1715         }
1716
1717         if (cli_getatr(targetcli, targetpath, mode, size, &write_time)) {
1718
1719                 struct timespec w_time_ts;
1720
1721                 w_time_ts = convert_time_t_to_timespec(write_time);
1722
1723                 if (write_time_ts != NULL) {
1724                         *write_time_ts = w_time_ts;
1725                 }
1726
1727                 if (create_time_ts != NULL) {
1728                         *create_time_ts = w_time_ts;
1729                 }
1730
1731                 if (access_time_ts != NULL) {
1732                         *access_time_ts = w_time_ts;
1733                 }
1734
1735                 if (change_time_ts != NULL) {
1736                         *change_time_ts = w_time_ts;
1737                 }
1738
1739                 srv->no_pathinfo2 = True;
1740                 TALLOC_FREE(frame);
1741                 return True;
1742         }
1743
1744         errno = EPERM;
1745         TALLOC_FREE(frame);
1746         return False;
1747
1748 }
1749
1750 /*
1751  * Set file info on an SMB server.  Use setpathinfo call first.  If that
1752  * fails, use setattrE..
1753  *
1754  * Access and modification time parameters are always used and must be
1755  * provided.  Create time, if zero, will be determined from the actual create
1756  * time of the file.  If non-zero, the create time will be set as well.
1757  *
1758  * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1759  */
1760 static bool
1761 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path, 
1762             time_t create_time,
1763             time_t access_time,
1764             time_t write_time,
1765             time_t change_time,
1766             uint16 mode)
1767 {
1768         int fd;
1769         int ret;
1770         TALLOC_CTX *frame = talloc_stackframe();
1771
1772         /*
1773          * First, try setpathinfo (if qpathinfo succeeded), for it is the
1774          * modern function for "new code" to be using, and it works given a
1775          * filename rather than requiring that the file be opened to have its
1776          * attributes manipulated.
1777          */
1778         if (srv->no_pathinfo ||
1779             ! cli_setpathinfo(srv->cli, path,
1780                               create_time,
1781                               access_time,
1782                               write_time,
1783                               change_time,
1784                               mode)) {
1785
1786                 /*
1787                  * setpathinfo is not supported; go to plan B. 
1788                  *
1789                  * cli_setatr() does not work on win98, and it also doesn't
1790                  * support setting the access time (only the modification
1791                  * time), so in all cases, we open the specified file and use
1792                  * cli_setattrE() which should work on all OS versions, and
1793                  * supports both times.
1794                  */
1795
1796                 /* Don't try {q,set}pathinfo() again, with this server */
1797                 srv->no_pathinfo = True;
1798
1799                 /* Open the file */
1800                 if ((fd = cli_open(srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1801
1802                         errno = smbc_errno(context, srv->cli);
1803                         TALLOC_FREE(frame);
1804                         return -1;
1805                 }
1806
1807                 /* Set the new attributes */
1808                 ret = cli_setattrE(srv->cli, fd,
1809                                    change_time,
1810                                    access_time,
1811                                    write_time);
1812
1813                 /* Close the file */
1814                 cli_close(srv->cli, fd);
1815
1816                 /*
1817                  * Unfortunately, setattrE() doesn't have a provision for
1818                  * setting the access mode (attributes).  We'll have to try
1819                  * cli_setatr() for that, and with only this parameter, it
1820                  * seems to work on win98.
1821                  */
1822                 if (ret && mode != (uint16) -1) {
1823                         ret = cli_setatr(srv->cli, path, mode, 0);
1824                 }
1825
1826                 if (! ret) {
1827                         errno = smbc_errno(context, srv->cli);
1828                         TALLOC_FREE(frame);
1829                         return False;
1830                 }
1831         }
1832
1833         TALLOC_FREE(frame);
1834         return True;
1835 }
1836
1837  /*
1838   * Routine to unlink() a file
1839   */
1840
1841 static int
1842 smbc_unlink_ctx(SMBCCTX *context,
1843                 const char *fname)
1844 {
1845         char *server = NULL, *share = NULL, *user = NULL, *password = NULL, *workgroup = NULL;
1846         char *path = NULL;
1847         char *targetpath = NULL;
1848         struct cli_state *targetcli = NULL;
1849         SMBCSRV *srv = NULL;
1850         TALLOC_CTX *frame = talloc_stackframe();
1851
1852         if (!context || !context->internal ||
1853             !context->internal->_initialized) {
1854                 errno = EINVAL;  /* Best I can think of ... */
1855                 TALLOC_FREE(frame);
1856                 return -1;
1857
1858         }
1859
1860         if (!fname) {
1861                 errno = EINVAL;
1862                 TALLOC_FREE(frame);
1863                 return -1;
1864
1865         }
1866
1867         if (smbc_parse_path(frame,
1868                                 context,
1869                                 fname,
1870                                 &workgroup,
1871                                 &server,
1872                                 &share,
1873                                 &path,
1874                                 &user,
1875                                 &password,
1876                                 NULL)) {
1877                 errno = EINVAL;
1878                 TALLOC_FREE(frame);
1879                 return -1;
1880         }
1881
1882         if (!user || user[0] == (char)0) {
1883                 user = talloc_strdup(frame, context->user);
1884                 if (!user) {
1885                         errno = ENOMEM;
1886                         TALLOC_FREE(frame);
1887                         return -1;
1888                 }
1889         }
1890
1891         srv = smbc_server(frame, context, True,
1892                           server, share, &workgroup, &user, &password);
1893
1894         if (!srv) {
1895                 TALLOC_FREE(frame);
1896                 return -1;  /* smbc_server sets errno */
1897
1898         }
1899
1900         /*d_printf(">>>unlink: resolving %s\n", path);*/
1901         if (!cli_resolve_path(frame, "", srv->cli, path,
1902                                 &targetcli, &targetpath)) {
1903                 d_printf("Could not resolve %s\n", path);
1904                 TALLOC_FREE(frame);
1905                 return -1;
1906         }
1907         /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1908
1909         if (!cli_unlink(targetcli, targetpath)) {
1910
1911                 errno = smbc_errno(context, targetcli);
1912
1913                 if (errno == EACCES) { /* Check if the file is a directory */
1914
1915                         int saverr = errno;
1916                         SMB_OFF_T size = 0;
1917                         uint16 mode = 0;
1918                         struct timespec write_time_ts;
1919                         struct timespec access_time_ts;
1920                         struct timespec change_time_ts;
1921                         SMB_INO_T ino = 0;
1922
1923                         if (!smbc_getatr(context, srv, path, &mode, &size,
1924                                          NULL,
1925                                          &access_time_ts,
1926                                          &write_time_ts,
1927                                          &change_time_ts,
1928                                          &ino)) {
1929
1930                                 /* Hmmm, bad error ... What? */
1931
1932                                 errno = smbc_errno(context, targetcli);
1933                                 TALLOC_FREE(frame);
1934                                 return -1;
1935
1936                         }
1937                         else {
1938
1939                                 if (IS_DOS_DIR(mode))
1940                                         errno = EISDIR;
1941                                 else
1942                                         errno = saverr;  /* Restore this */
1943
1944                         }
1945                 }
1946
1947                 TALLOC_FREE(frame);
1948                 return -1;
1949
1950         }
1951
1952         TALLOC_FREE(frame);
1953         return 0;  /* Success ... */
1954
1955 }
1956
1957 /*
1958  * Routine to rename() a file
1959  */
1960
1961 static int
1962 smbc_rename_ctx(SMBCCTX *ocontext,
1963                 const char *oname, 
1964                 SMBCCTX *ncontext,
1965                 const char *nname)
1966 {
1967         char *server1 = NULL;
1968         char *share1 = NULL;
1969         char *server2 = NULL;
1970         char *share2 = NULL;
1971         char *user1 = NULL;
1972         char *user2 = NULL;
1973         char *password1 = NULL;
1974         char *password2 = NULL;
1975         char *workgroup = NULL;
1976         char *path1 = NULL;
1977         char *path2 = NULL;
1978         char *targetpath1 = NULL;
1979         char *targetpath2 = NULL;
1980         struct cli_state *targetcli1 = NULL;
1981         struct cli_state *targetcli2 = NULL;
1982         SMBCSRV *srv = NULL;
1983         TALLOC_CTX *frame = talloc_stackframe();
1984
1985         if (!ocontext || !ncontext ||
1986             !ocontext->internal || !ncontext->internal ||
1987             !ocontext->internal->_initialized ||
1988             !ncontext->internal->_initialized) {
1989                 errno = EINVAL;  /* Best I can think of ... */
1990                 TALLOC_FREE(frame);
1991                 return -1;
1992         }
1993
1994         if (!oname || !nname) {
1995                 errno = EINVAL;
1996                 TALLOC_FREE(frame);
1997                 return -1;
1998         }
1999
2000         DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
2001
2002         if (smbc_parse_path(frame,
2003                         ocontext,
2004                         oname,
2005                         &workgroup,
2006                         &server1,
2007                         &share1,
2008                         &path1,
2009                         &user1,
2010                         &password1,
2011                         NULL)) {
2012                 errno = EINVAL;
2013                 TALLOC_FREE(frame);
2014                 return -1;
2015         }
2016
2017         if (!user1 || user1[0] == (char)0) {
2018                 user1 = talloc_strdup(frame, ocontext->user);
2019                 if (!user1) {
2020                         errno = ENOMEM;
2021                         TALLOC_FREE(frame);
2022                         return -1;
2023                 }
2024         }
2025
2026         if (smbc_parse_path(frame,
2027                                 ncontext,
2028                                 nname,
2029                                 NULL,
2030                                 &server2,
2031                                 &share2,
2032                                 &path2,
2033                                 &user2,
2034                                 &password2,
2035                                 NULL)) {
2036                 errno = EINVAL;
2037                 TALLOC_FREE(frame);
2038                 return -1;
2039         }
2040
2041         if (!user2 || user2[0] == (char)0) {
2042                 user2 = talloc_strdup(frame, ncontext->user);
2043                 if (!user2) {
2044                         errno = ENOMEM;
2045                         TALLOC_FREE(frame);
2046                         return -1;
2047                 }
2048         }
2049
2050         if (strcmp(server1, server2) || strcmp(share1, share2) ||
2051             strcmp(user1, user2)) {
2052                 /* Can't rename across file systems, or users?? */
2053                 errno = EXDEV;
2054                 TALLOC_FREE(frame);
2055                 return -1;
2056         }
2057
2058         srv = smbc_server(frame, ocontext, True,
2059                           server1, share1, &workgroup, &user1, &password1);
2060         if (!srv) {
2061                 TALLOC_FREE(frame);
2062                 return -1;
2063
2064         }
2065
2066         /*d_printf(">>>rename: resolving %s\n", path1);*/
2067         if (!cli_resolve_path(frame, "", srv->cli, path1,
2068                                 &targetcli1, &targetpath1)) {
2069                 d_printf("Could not resolve %s\n", path1);
2070                 TALLOC_FREE(frame);
2071                 return -1;
2072         }
2073         /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
2074         /*d_printf(">>>rename: resolving %s\n", path2);*/
2075         if (!cli_resolve_path(frame, "", srv->cli, path2,
2076                                 &targetcli2, &targetpath2)) {
2077                 d_printf("Could not resolve %s\n", path2);
2078                 TALLOC_FREE(frame);
2079                 return -1;
2080         }
2081         /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
2082
2083         if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
2084             strcmp(targetcli1->share, targetcli2->share))
2085         {
2086                 /* can't rename across file systems */
2087                 errno = EXDEV;
2088                 TALLOC_FREE(frame);
2089                 return -1;
2090         }
2091
2092         if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
2093                 int eno = smbc_errno(ocontext, targetcli1);
2094
2095                 if (eno != EEXIST ||
2096                     !cli_unlink(targetcli1, targetpath2) ||
2097                     !cli_rename(targetcli1, targetpath1, targetpath2)) {
2098
2099                         errno = eno;
2100                         TALLOC_FREE(frame);
2101                         return -1;
2102
2103                 }
2104         }
2105
2106         TALLOC_FREE(frame);
2107         return 0; /* Success */
2108 }
2109
2110 /*
2111  * A routine to lseek() a file
2112  */
2113
2114 static off_t
2115 smbc_lseek_ctx(SMBCCTX *context,
2116                SMBCFILE *file,
2117                off_t offset,
2118                int whence)
2119 {
2120         SMB_OFF_T size;
2121         char *server = NULL, *share = NULL, *user = NULL, *password = NULL;
2122         char *path = NULL;
2123         char *targetpath = NULL;
2124         struct cli_state *targetcli = NULL;
2125         TALLOC_CTX *frame = talloc_stackframe();
2126
2127         if (!context || !context->internal ||
2128             !context->internal->_initialized) {
2129                 errno = EINVAL;
2130                 TALLOC_FREE(frame);
2131                 return -1;
2132         }
2133
2134         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2135
2136                 errno = EBADF;
2137                 TALLOC_FREE(frame);
2138                 return -1;
2139
2140         }
2141
2142         if (!file->file) {
2143
2144                 errno = EINVAL;
2145                 TALLOC_FREE(frame);
2146                 return -1;      /* Can't lseek a dir ... */
2147
2148         }
2149
2150         switch (whence) {
2151         case SEEK_SET:
2152                 file->offset = offset;
2153                 break;
2154
2155         case SEEK_CUR:
2156                 file->offset += offset;
2157                 break;
2158
2159         case SEEK_END:
2160                 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
2161                 if (smbc_parse_path(frame,
2162                                         context,
2163                                         file->fname,
2164                                         NULL,
2165                                         &server,
2166                                         &share,
2167                                         &path,
2168                                         &user,
2169                                         &password,
2170                                         NULL)) {
2171                         errno = EINVAL;
2172                         TALLOC_FREE(frame);
2173                         return -1;
2174                 }
2175
2176                 /*d_printf(">>>lseek: resolving %s\n", path);*/
2177                 if (!cli_resolve_path(frame, "", file->srv->cli, path,
2178                                       &targetcli, &targetpath)) {
2179                         d_printf("Could not resolve %s\n", path);
2180                         TALLOC_FREE(frame);
2181                         return -1;
2182                 }
2183                 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
2184
2185                 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
2186                                    &size, NULL, NULL, NULL, NULL, NULL))
2187                 {
2188                     SMB_OFF_T b_size = size;
2189                         if (!cli_getattrE(targetcli, file->cli_fd,
2190                                           NULL, &b_size, NULL, NULL, NULL))
2191                     {
2192                         errno = EINVAL;
2193                         TALLOC_FREE(frame);
2194                         return -1;
2195                     } else
2196                         size = b_size;
2197                 }
2198                 file->offset = size + offset;
2199                 break;
2200
2201         default:
2202                 errno = EINVAL;
2203                 break;
2204
2205         }
2206
2207         TALLOC_FREE(frame);
2208         return file->offset;
2209
2210 }
2211
2212 /* 
2213  * Generate an inode number from file name for those things that need it
2214  */
2215
2216 static ino_t
2217 smbc_inode(SMBCCTX *context,
2218            const char *name)
2219 {
2220         if (!context || !context->internal ||
2221             !context->internal->_initialized) {
2222
2223                 errno = EINVAL;
2224                 return -1;
2225
2226         }
2227
2228         if (!*name) return 2; /* FIXME, why 2 ??? */
2229         return (ino_t)str_checksum(name);
2230
2231 }
2232
2233 /*
2234  * Routine to put basic stat info into a stat structure ... Used by stat and
2235  * fstat below.
2236  */
2237
2238 static int
2239 smbc_setup_stat(SMBCCTX *context,
2240                 struct stat *st,
2241                 char *fname,
2242                 SMB_OFF_T size,
2243                 int mode)
2244 {
2245         TALLOC_CTX *frame = talloc_stackframe();
2246         
2247         st->st_mode = 0;
2248
2249         if (IS_DOS_DIR(mode)) {
2250                 st->st_mode = SMBC_DIR_MODE;
2251         } else {
2252                 st->st_mode = SMBC_FILE_MODE;
2253         }
2254
2255         if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
2256         if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
2257         if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
2258         if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
2259
2260         st->st_size = size;
2261 #ifdef HAVE_STAT_ST_BLKSIZE
2262         st->st_blksize = 512;
2263 #endif
2264 #ifdef HAVE_STAT_ST_BLOCKS
2265         st->st_blocks = (size+511)/512;
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, path, 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                         dad->mode = strtol(tok+5, NULL, 16);
4693                         continue;
4694                 }
4695
4696                 if (StrnCaseCmp(tok, "SIZE:", 5) == 0) {
4697                         dad->size = (SMB_OFF_T)atof(tok+5);
4698                         continue;
4699                 }
4700
4701                 n = strlen(attr_strings.access_time_attr);
4702                 if (StrnCaseCmp(tok, attr_strings.access_time_attr, n) == 0) {
4703                         dad->access_time = (time_t)strtol(tok+n+1, NULL, 10);
4704                         continue;
4705                 }
4706
4707                 n = strlen(attr_strings.change_time_attr);
4708                 if (StrnCaseCmp(tok, attr_strings.change_time_attr, n) == 0) {
4709                         dad->change_time = (time_t)strtol(tok+n+1, NULL, 10);
4710                         continue;
4711                 }
4712
4713                 n = strlen(attr_strings.write_time_attr);
4714                 if (StrnCaseCmp(tok, attr_strings.write_time_attr, n) == 0) {
4715                         dad->write_time = (time_t)strtol(tok+n+1, NULL, 10);
4716                         continue;
4717                 }
4718
4719                 if (attr_strings.create_time_attr != NULL) {
4720                         n = strlen(attr_strings.create_time_attr);
4721                         if (StrnCaseCmp(tok, attr_strings.create_time_attr,
4722                                         n) == 0) {
4723                                 dad->create_time = (time_t)strtol(tok+n+1,
4724                                                                   NULL, 10);
4725                                 continue;
4726                         }
4727                 }
4728
4729                 if (StrnCaseCmp(tok, "INODE:", 6) == 0) {
4730                         dad->inode = (SMB_INO_T)atof(tok+6);
4731                         continue;
4732                 }
4733         }
4734         TALLOC_FREE(frame);
4735 }
4736
4737 /*****************************************************
4738  Retrieve the acls for a file.
4739 *******************************************************/
4740
4741 static int
4742 cacl_get(SMBCCTX *context,
4743          TALLOC_CTX *ctx,
4744          SMBCSRV *srv,
4745          struct cli_state *ipc_cli,
4746          POLICY_HND *pol,
4747          char *filename,
4748          char *attr_name,
4749          char *buf,
4750          int bufsize)
4751 {
4752         uint32 i;
4753         int n = 0;
4754         int n_used;
4755         bool all;
4756         bool all_nt;
4757         bool all_nt_acls;
4758         bool all_dos;
4759         bool some_nt;
4760         bool some_dos;
4761         bool exclude_nt_revision = False;
4762         bool exclude_nt_owner = False;
4763         bool exclude_nt_group = False;
4764         bool exclude_nt_acl = False;
4765         bool exclude_dos_mode = False;
4766         bool exclude_dos_size = False;
4767         bool exclude_dos_create_time = False;
4768         bool exclude_dos_access_time = False;
4769         bool exclude_dos_write_time = False;
4770         bool exclude_dos_change_time = False;
4771         bool exclude_dos_inode = False;
4772         bool numeric = True;
4773         bool determine_size = (bufsize == 0);
4774         int fnum = -1;
4775         SEC_DESC *sd;
4776         fstring sidstr;
4777         fstring name_sandbox;
4778         char *name;
4779         char *pExclude;
4780         char *p;
4781         struct timespec create_time_ts;
4782         struct timespec write_time_ts;
4783         struct timespec access_time_ts;
4784         struct timespec change_time_ts;
4785         time_t create_time = (time_t)0;
4786         time_t write_time = (time_t)0;
4787         time_t access_time = (time_t)0;
4788         time_t change_time = (time_t)0;
4789         SMB_OFF_T size = 0;
4790         uint16 mode = 0;
4791         SMB_INO_T ino = 0;
4792         struct cli_state *cli = srv->cli;
4793         struct {
4794                 const char * create_time_attr;
4795                 const char * access_time_attr;
4796                 const char * write_time_attr;
4797                 const char * change_time_attr;
4798         } attr_strings;
4799         struct {
4800                 const char * create_time_attr;
4801                 const char * access_time_attr;
4802                 const char * write_time_attr;
4803                 const char * change_time_attr;
4804         } excl_attr_strings;
4805
4806         /* Determine whether to use old-style or new-style attribute names */
4807         if (context->internal->_full_time_names) {
4808                 /* new-style names */
4809                 attr_strings.create_time_attr = "CREATE_TIME";
4810                 attr_strings.access_time_attr = "ACCESS_TIME";
4811                 attr_strings.write_time_attr = "WRITE_TIME";
4812                 attr_strings.change_time_attr = "CHANGE_TIME";
4813
4814                 excl_attr_strings.create_time_attr = "CREATE_TIME";
4815                 excl_attr_strings.access_time_attr = "ACCESS_TIME";
4816                 excl_attr_strings.write_time_attr = "WRITE_TIME";
4817                 excl_attr_strings.change_time_attr = "CHANGE_TIME";
4818         } else {
4819                 /* old-style names */
4820                 attr_strings.create_time_attr = NULL;
4821                 attr_strings.access_time_attr = "A_TIME";
4822                 attr_strings.write_time_attr = "M_TIME";
4823                 attr_strings.change_time_attr = "C_TIME";
4824
4825                 excl_attr_strings.create_time_attr = NULL;
4826                 excl_attr_strings.access_time_attr = "dos_attr.A_TIME";
4827                 excl_attr_strings.write_time_attr = "dos_attr.M_TIME";
4828                 excl_attr_strings.change_time_attr = "dos_attr.C_TIME";
4829         }
4830
4831         /* Copy name so we can strip off exclusions (if any are specified) */
4832         strncpy(name_sandbox, attr_name, sizeof(name_sandbox) - 1);
4833
4834         /* Ensure name is null terminated */
4835         name_sandbox[sizeof(name_sandbox) - 1] = '\0';
4836
4837         /* Play in the sandbox */
4838         name = name_sandbox;
4839
4840         /* If there are any exclusions, point to them and mask them from name */
4841         if ((pExclude = strchr(name, '!')) != NULL)
4842         {
4843                 *pExclude++ = '\0';
4844         }
4845
4846         all = (StrnCaseCmp(name, "system.*", 8) == 0);
4847         all_nt = (StrnCaseCmp(name, "system.nt_sec_desc.*", 20) == 0);
4848         all_nt_acls = (StrnCaseCmp(name, "system.nt_sec_desc.acl.*", 24) == 0);
4849         all_dos = (StrnCaseCmp(name, "system.dos_attr.*", 17) == 0);
4850         some_nt = (StrnCaseCmp(name, "system.nt_sec_desc.", 19) == 0);
4851         some_dos = (StrnCaseCmp(name, "system.dos_attr.", 16) == 0);
4852         numeric = (* (name + strlen(name) - 1) != '+');
4853
4854         /* Look for exclusions from "all" requests */
4855         if (all || all_nt || all_dos) {
4856
4857                 /* Exclusions are delimited by '!' */
4858                 for (;
4859                      pExclude != NULL;
4860                      pExclude = (p == NULL ? NULL : p + 1)) {
4861
4862                 /* Find end of this exclusion name */
4863                 if ((p = strchr(pExclude, '!')) != NULL)
4864                 {
4865                     *p = '\0';
4866                 }
4867
4868                 /* Which exclusion name is this? */
4869                 if (StrCaseCmp(pExclude, "nt_sec_desc.revision") == 0) {
4870                     exclude_nt_revision = True;
4871                 }
4872                 else if (StrCaseCmp(pExclude, "nt_sec_desc.owner") == 0) {
4873                     exclude_nt_owner = True;
4874                 }
4875                 else if (StrCaseCmp(pExclude, "nt_sec_desc.group") == 0) {
4876                     exclude_nt_group = True;
4877                 }
4878                 else if (StrCaseCmp(pExclude, "nt_sec_desc.acl") == 0) {
4879                     exclude_nt_acl = True;
4880                 }
4881                 else if (StrCaseCmp(pExclude, "dos_attr.mode") == 0) {
4882                     exclude_dos_mode = True;
4883                 }
4884                 else if (StrCaseCmp(pExclude, "dos_attr.size") == 0) {
4885                     exclude_dos_size = True;
4886                 }
4887                 else if (excl_attr_strings.create_time_attr != NULL &&
4888                          StrCaseCmp(pExclude,
4889                                     excl_attr_strings.change_time_attr) == 0) {
4890                     exclude_dos_create_time = True;
4891                 }
4892                 else if (StrCaseCmp(pExclude,
4893                                     excl_attr_strings.access_time_attr) == 0) {
4894                     exclude_dos_access_time = True;
4895                 }
4896                 else if (StrCaseCmp(pExclude,
4897                                     excl_attr_strings.write_time_attr) == 0) {
4898                     exclude_dos_write_time = True;
4899                 }
4900                 else if (StrCaseCmp(pExclude,
4901                                     excl_attr_strings.change_time_attr) == 0) {
4902                     exclude_dos_change_time = True;
4903                 }
4904                 else if (StrCaseCmp(pExclude, "dos_attr.inode") == 0) {
4905                     exclude_dos_inode = True;
4906                 }
4907                 else {
4908                     DEBUG(5, ("cacl_get received unknown exclusion: %s\n",
4909                               pExclude));
4910                     errno = ENOATTR;
4911                     return -1;
4912                 }
4913             }
4914         }
4915
4916         n_used = 0;
4917
4918         /*
4919          * If we are (possibly) talking to an NT or new system and some NT
4920          * attributes have been requested...
4921          */
4922         if (ipc_cli && (all || some_nt || all_nt_acls)) {
4923                 /* Point to the portion after "system.nt_sec_desc." */
4924                 name += 19;     /* if (all) this will be invalid but unused */
4925
4926                 /* ... then obtain any NT attributes which were requested */
4927                 fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
4928
4929                 if (fnum == -1) {
4930                         DEBUG(5, ("cacl_get failed to open %s: %s\n",
4931                                   filename, cli_errstr(cli)));
4932                         errno = 0;
4933                         return -1;
4934                 }
4935
4936                 sd = cli_query_secdesc(cli, fnum, ctx);
4937
4938                 if (!sd) {
4939                         DEBUG(5,
4940                               ("cacl_get Failed to query old descriptor\n"));
4941                         errno = 0;
4942                         return -1;
4943                 }
4944
4945                 cli_close(cli, fnum);
4946
4947                 if (! exclude_nt_revision) {
4948                         if (all || all_nt) {
4949                                 if (determine_size) {
4950                                         p = talloc_asprintf(ctx,
4951                                                             "REVISION:%d",
4952                                                             sd->revision);
4953                                         if (!p) {
4954                                                 errno = ENOMEM;
4955                                                 return -1;
4956                                         }
4957                                         n = strlen(p);
4958                                 } else {
4959                                         n = snprintf(buf, bufsize,
4960                                                      "REVISION:%d",
4961                                                      sd->revision);
4962                                 }
4963                         } else if (StrCaseCmp(name, "revision") == 0) {
4964                                 if (determine_size) {
4965                                         p = talloc_asprintf(ctx, "%d",
4966                                                             sd->revision);
4967                                         if (!p) {
4968                                                 errno = ENOMEM;
4969                                                 return -1;
4970                                         }
4971                                         n = strlen(p);
4972                                 } else {
4973                                         n = snprintf(buf, bufsize, "%d",
4974                                                      sd->revision);
4975                                 }
4976                         }
4977
4978                         if (!determine_size && n > bufsize) {
4979                                 errno = ERANGE;
4980                                 return -1;
4981                         }
4982                         buf += n;
4983                         n_used += n;
4984                         bufsize -= n;
4985                         n = 0;
4986                 }
4987
4988                 if (! exclude_nt_owner) {
4989                         /* Get owner and group sid */
4990                         if (sd->owner_sid) {
4991                                 convert_sid_to_string(ipc_cli, pol,
4992                                                       sidstr,
4993                                                       numeric,
4994                                                       sd->owner_sid);
4995                         } else {
4996                                 fstrcpy(sidstr, "");
4997                         }
4998
4999                         if (all || all_nt) {
5000                                 if (determine_size) {
5001                                         p = talloc_asprintf(ctx, ",OWNER:%s",
5002                                                             sidstr);
5003                                         if (!p) {
5004                                                 errno = ENOMEM;
5005                                                 return -1;
5006                                         }
5007                                         n = strlen(p);
5008                                 } else if (sidstr[0] != '\0') {
5009                                         n = snprintf(buf, bufsize,
5010                                                      ",OWNER:%s", sidstr);
5011                                 }
5012                         } else if (StrnCaseCmp(name, "owner", 5) == 0) {
5013                                 if (determine_size) {
5014                                         p = talloc_asprintf(ctx, "%s", sidstr);
5015                                         if (!p) {
5016                                                 errno = ENOMEM;
5017                                                 return -1;
5018                                         }
5019                                         n = strlen(p);
5020                                 } else {
5021                                         n = snprintf(buf, bufsize, "%s",
5022                                                      sidstr);
5023                                 }
5024                         }
5025
5026                         if (!determine_size && n > bufsize) {
5027                                 errno = ERANGE;
5028                                 return -1;
5029                         }
5030                         buf += n;
5031                         n_used += n;
5032                         bufsize -= n;
5033                         n = 0;
5034                 }
5035
5036                 if (! exclude_nt_group) {
5037                         if (sd->group_sid) {
5038                                 convert_sid_to_string(ipc_cli, pol,
5039                                                       sidstr, numeric,
5040                                                       sd->group_sid);
5041                         } else {
5042                                 fstrcpy(sidstr, "");
5043                         }
5044
5045                         if (all || all_nt) {
5046                                 if (determine_size) {
5047                                         p = talloc_asprintf(ctx, ",GROUP:%s",
5048                                                             sidstr);
5049                                         if (!p) {
5050                                                 errno = ENOMEM;
5051                                                 return -1;
5052                                         }
5053                                         n = strlen(p);
5054                                 } else if (sidstr[0] != '\0') {
5055                                         n = snprintf(buf, bufsize,
5056                                                      ",GROUP:%s", sidstr);
5057                                 }
5058                         } else if (StrnCaseCmp(name, "group", 5) == 0) {
5059                                 if (determine_size) {
5060                                         p = talloc_asprintf(ctx, "%s", sidstr);
5061                                         if (!p) {
5062                                                 errno = ENOMEM;
5063                                                 return -1;
5064                                         }
5065                                         n = strlen(p);
5066                                 } else {
5067                                         n = snprintf(buf, bufsize,
5068                                                      "%s", sidstr);
5069                                 }
5070                         }
5071
5072                         if (!determine_size && n > bufsize) {
5073                                 errno = ERANGE;
5074                                 return -1;
5075                         }
5076                         buf += n;
5077                         n_used += n;
5078                         bufsize -= n;
5079                         n = 0;
5080                 }
5081
5082                 if (! exclude_nt_acl) {
5083                         /* Add aces to value buffer  */
5084                         for (i = 0; sd->dacl && i < sd->dacl->num_aces; i++) {
5085
5086                                 SEC_ACE *ace = &sd->dacl->aces[i];
5087                                 convert_sid_to_string(ipc_cli, pol,
5088                                                       sidstr, numeric,
5089                                                       &ace->trustee);
5090
5091                                 if (all || all_nt) {
5092                                         if (determine_size) {
5093                                                 p = talloc_asprintf(
5094                                                         ctx, 
5095                                                         ",ACL:"
5096                                                         "%s:%d/%d/0x%08x", 
5097                                                         sidstr,
5098                                                         ace->type,
5099                                                         ace->flags,
5100                                                         ace->access_mask);
5101                                                 if (!p) {
5102                                                         errno = ENOMEM;
5103                                                         return -1;
5104                                                 }
5105                                                 n = strlen(p);
5106                                         } else {
5107                                                 n = snprintf(
5108                                                         buf, bufsize,
5109                                                         ",ACL:%s:%d/%d/0x%08x", 
5110                                                         sidstr,
5111                                                         ace->type,
5112                                                         ace->flags,
5113                                                         ace->access_mask);
5114                                         }
5115                                 } else if ((StrnCaseCmp(name, "acl", 3) == 0 &&
5116                                             StrCaseCmp(name+3, sidstr) == 0) ||
5117                                            (StrnCaseCmp(name, "acl+", 4) == 0 &&
5118                                             StrCaseCmp(name+4, sidstr) == 0)) {
5119                                         if (determine_size) {
5120                                                 p = talloc_asprintf(
5121                                                         ctx, 
5122                                                         "%d/%d/0x%08x", 
5123                                                         ace->type,
5124                                                         ace->flags,
5125                                                         ace->access_mask);
5126                                                 if (!p) {
5127                                                         errno = ENOMEM;
5128                                                         return -1;
5129                                                 }
5130                                                 n = strlen(p);
5131                                         } else {
5132                                                 n = snprintf(buf, bufsize,
5133                                                              "%d/%d/0x%08x", 
5134                                                              ace->type,
5135                                                              ace->flags,
5136                                                              ace->access_mask);
5137                                         }
5138                                 } else if (all_nt_acls) {
5139                                         if (determine_size) {
5140                                                 p = talloc_asprintf(
5141                                                         ctx, 
5142                                                         "%s%s:%d/%d/0x%08x",
5143                                                         i ? "," : "",
5144                                                         sidstr,
5145                                                         ace->type,
5146                                                         ace->flags,
5147                                                         ace->access_mask);
5148                                                 if (!p) {
5149                                                         errno = ENOMEM;
5150                                                         return -1;
5151                                                 }
5152                                                 n = strlen(p);
5153                                         } else {
5154                                                 n = snprintf(buf, bufsize,
5155                                                              "%s%s:%d/%d/0x%08x",
5156                                                              i ? "," : "",
5157                                                              sidstr,
5158                                                              ace->type,
5159                                                              ace->flags,
5160                                                              ace->access_mask);
5161                                         }
5162                                 }
5163                                 if (!determine_size && n > bufsize) {
5164                                         errno = ERANGE;
5165                                         return -1;
5166                                 }
5167                                 buf += n;
5168                                 n_used += n;
5169                                 bufsize -= n;
5170                                 n = 0;
5171                         }
5172                 }
5173
5174                 /* Restore name pointer to its original value */
5175                 name -= 19;
5176         }
5177
5178         if (all || some_dos) {
5179                 /* Point to the portion after "system.dos_attr." */
5180                 name += 16;     /* if (all) this will be invalid but unused */
5181
5182                 /* Obtain the DOS attributes */
5183                 if (!smbc_getatr(context, srv, filename, &mode, &size, 
5184                                  &create_time_ts,
5185                                  &access_time_ts,
5186                                  &write_time_ts,
5187                                  &change_time_ts,
5188                                  &ino)) {
5189
5190                         errno = smbc_errno(context, srv->cli);
5191                         return -1;
5192
5193                 }
5194
5195                 create_time = convert_timespec_to_time_t(create_time_ts);
5196                 access_time = convert_timespec_to_time_t(access_time_ts);
5197                 write_time = convert_timespec_to_time_t(write_time_ts);
5198                 change_time = convert_timespec_to_time_t(change_time_ts);
5199
5200                 if (! exclude_dos_mode) {
5201                         if (all || all_dos) {
5202                                 if (determine_size) {
5203                                         p = talloc_asprintf(ctx,
5204                                                             "%sMODE:0x%x",
5205                                                             (ipc_cli &&
5206                                                              (all || some_nt)
5207                                                              ? ","
5208                                                              : ""),
5209                                                             mode);
5210                                         if (!p) {
5211                                                 errno = ENOMEM;
5212                                                 return -1;
5213                                         }
5214                                         n = strlen(p);
5215                                 } else {
5216                                         n = snprintf(buf, bufsize,
5217                                                      "%sMODE:0x%x",
5218                                                      (ipc_cli &&
5219                                                       (all || some_nt)
5220                                                       ? ","
5221                                                       : ""),
5222                                                      mode);
5223                                 }
5224                         } else if (StrCaseCmp(name, "mode") == 0) {
5225                                 if (determine_size) {
5226                                         p = talloc_asprintf(ctx, "0x%x", mode);
5227                                         if (!p) {
5228                                                 errno = ENOMEM;
5229                                                 return -1;
5230                                         }
5231                                         n = strlen(p);
5232                                 } else {
5233                                         n = snprintf(buf, bufsize,
5234                                                      "0x%x", mode);
5235                                 }
5236                         }
5237
5238                         if (!determine_size && n > bufsize) {
5239                                 errno = ERANGE;
5240                                 return -1;
5241                         }
5242                         buf += n;
5243                         n_used += n;
5244                         bufsize -= n;
5245                         n = 0;
5246                 }
5247
5248                 if (! exclude_dos_size) {
5249                         if (all || all_dos) {
5250                                 if (determine_size) {
5251                                         p = talloc_asprintf(
5252                                                 ctx,
5253                                                 ",SIZE:%.0f",
5254                                                 (double)size);
5255                                         if (!p) {
5256                                                 errno = ENOMEM;
5257                                                 return -1;
5258                                         }
5259                                         n = strlen(p);
5260                                 } else {
5261                                         n = snprintf(buf, bufsize,
5262                                                      ",SIZE:%.0f",
5263                                                      (double)size);
5264                                 }
5265                         } else if (StrCaseCmp(name, "size") == 0) {
5266                                 if (determine_size) {
5267                                         p = talloc_asprintf(
5268                                                 ctx,
5269                                                 "%.0f",
5270                                                 (double)size);
5271                                         if (!p) {
5272                                                 errno = ENOMEM;
5273                                                 return -1;
5274                                         }
5275                                         n = strlen(p);
5276                                 } else {
5277                                         n = snprintf(buf, bufsize,
5278                                                      "%.0f",
5279                                                      (double)size);
5280                                 }
5281                         }
5282
5283                         if (!determine_size && n > bufsize) {
5284                                 errno = ERANGE;
5285                                 return -1;
5286                         }
5287                         buf += n;
5288                         n_used += n;
5289                         bufsize -= n;
5290                         n = 0;
5291                 }
5292
5293                 if (! exclude_dos_create_time &&
5294                     attr_strings.create_time_attr != NULL) {
5295                         if (all || all_dos) {
5296                                 if (determine_size) {
5297                                         p = talloc_asprintf(ctx,
5298                                                             ",%s:%lu",
5299                                                             attr_strings.create_time_attr,
5300                                                             create_time);
5301                                         if (!p) {
5302                                                 errno = ENOMEM;
5303                                                 return -1;
5304                                         }
5305                                         n = strlen(p);
5306                                 } else {
5307                                         n = snprintf(buf, bufsize,
5308                                                      ",%s:%lu",
5309                                                      attr_strings.create_time_attr,
5310                                                      create_time);
5311                                 }
5312                         } else if (StrCaseCmp(name, attr_strings.create_time_attr) == 0) {
5313                                 if (determine_size) {
5314                                         p = talloc_asprintf(ctx, "%lu", create_time);
5315                                         if (!p) {
5316                                                 errno = ENOMEM;
5317                                                 return -1;
5318                                         }
5319                                         n = strlen(p);
5320                                 } else {
5321                                         n = snprintf(buf, bufsize,
5322                                                      "%lu", create_time);
5323                                 }
5324                         }
5325
5326                         if (!determine_size && n > bufsize) {
5327                                 errno = ERANGE;
5328                                 return -1;
5329                         }
5330                         buf += n;
5331                         n_used += n;
5332                         bufsize -= n;
5333                         n = 0;
5334                 }
5335
5336                 if (! exclude_dos_access_time) {
5337                         if (all || all_dos) {
5338                                 if (determine_size) {
5339                                         p = talloc_asprintf(ctx,
5340                                                             ",%s:%lu",
5341                                                             attr_strings.access_time_attr,
5342                                                             access_time);
5343                                         if (!p) {
5344                                                 errno = ENOMEM;
5345                                                 return -1;
5346                                         }
5347                                         n = strlen(p);
5348                                 } else {
5349                                         n = snprintf(buf, bufsize,
5350                                                      ",%s:%lu",
5351                                                      attr_strings.access_time_attr,
5352                                                      access_time);
5353                                 }
5354                         } else if (StrCaseCmp(name, attr_strings.access_time_attr) == 0) {
5355                                 if (determine_size) {
5356                                         p = talloc_asprintf(ctx, "%lu", access_time);
5357                                         if (!p) {
5358                                                 errno = ENOMEM;
5359                                                 return -1;
5360                                         }
5361                                         n = strlen(p);
5362                                 } else {
5363                                         n = snprintf(buf, bufsize,
5364                                                      "%lu", access_time);
5365                                 }
5366                         }
5367
5368                         if (!determine_size && n > bufsize) {
5369                                 errno = ERANGE;
5370                                 return -1;
5371                         }
5372                         buf += n;
5373                         n_used += n;
5374                         bufsize -= n;
5375                         n = 0;
5376                 }
5377
5378                 if (! exclude_dos_write_time) {
5379                         if (all || all_dos) {
5380                                 if (determine_size) {
5381                                         p = talloc_asprintf(ctx,
5382                                                             ",%s:%lu",
5383                                                             attr_strings.write_time_attr,
5384                                                             write_time);
5385                                         if (!p) {
5386                                                 errno = ENOMEM;
5387                                                 return -1;
5388                                         }
5389                                         n = strlen(p);
5390                                 } else {
5391                                         n = snprintf(buf, bufsize,
5392                                                      ",%s:%lu",
5393                                                      attr_strings.write_time_attr,
5394                                                      write_time);
5395                                 }
5396                         } else if (StrCaseCmp(name, attr_strings.write_time_attr) == 0) {
5397                                 if (determine_size) {
5398                                         p = talloc_asprintf(ctx, "%lu", write_time);
5399                                         if (!p) {
5400                                                 errno = ENOMEM;
5401                                                 return -1;
5402                                         }
5403                                         n = strlen(p);
5404                                 } else {
5405                                         n = snprintf(buf, bufsize,
5406                                                      "%lu", write_time);
5407                                 }
5408                         }
5409
5410                         if (!determine_size && n > bufsize) {
5411                                 errno = ERANGE;
5412                                 return -1;
5413                         }
5414                         buf += n;
5415                         n_used += n;
5416                         bufsize -= n;
5417                         n = 0;
5418                 }
5419
5420                 if (! exclude_dos_change_time) {
5421                         if (all || all_dos) {
5422                                 if (determine_size) {
5423                                         p = talloc_asprintf(ctx,
5424                                                             ",%s:%lu",
5425                                                             attr_strings.change_time_attr,
5426                                                             change_time);
5427                                         if (!p) {
5428                                                 errno = ENOMEM;
5429                                                 return -1;
5430                                         }
5431                                         n = strlen(p);
5432                                 } else {
5433                                         n = snprintf(buf, bufsize,
5434                                                      ",%s:%lu",
5435                                                      attr_strings.change_time_attr,
5436                                                      change_time);
5437                                 }
5438                         } else if (StrCaseCmp(name, attr_strings.change_time_attr) == 0) {
5439                                 if (determine_size) {
5440                                         p = talloc_asprintf(ctx, "%lu", change_time);
5441                                         if (!p) {
5442                                                 errno = ENOMEM;
5443                                                 return -1;
5444                                         }
5445                                         n = strlen(p);
5446                                 } else {
5447                                         n = snprintf(buf, bufsize,
5448                                                      "%lu", change_time);
5449                                 }
5450                         }
5451
5452                         if (!determine_size && n > bufsize) {
5453                                 errno = ERANGE;
5454                                 return -1;
5455                         }
5456                         buf += n;
5457                         n_used += n;
5458                         bufsize -= n;
5459                         n = 0;
5460                 }
5461
5462                 if (! exclude_dos_inode) {
5463                         if (all || all_dos) {
5464                                 if (determine_size) {
5465                                         p = talloc_asprintf(
5466                                                 ctx,
5467                                                 ",INODE:%.0f",
5468                                                 (double)ino);
5469                                         if (!p) {
5470                                                 errno = ENOMEM;
5471                                                 return -1;
5472                                         }
5473                                         n = strlen(p);
5474                                 } else {
5475                                         n = snprintf(buf, bufsize,
5476                                                      ",INODE:%.0f",
5477                                                      (double) ino);
5478                                 }
5479                         } else if (StrCaseCmp(name, "inode") == 0) {
5480                                 if (determine_size) {
5481                                         p = talloc_asprintf(
5482                                                 ctx,
5483                                                 "%.0f",
5484                                                 (double) ino);
5485                                         if (!p) {
5486                                                 errno = ENOMEM;
5487                                                 return -1;
5488                                         }
5489                                         n = strlen(p);
5490                                 } else {
5491                                         n = snprintf(buf, bufsize,
5492                                                      "%.0f",
5493                                                      (double) ino);
5494                                 }
5495                         }
5496
5497                         if (!determine_size && n > bufsize) {
5498                                 errno = ERANGE;
5499                                 return -1;
5500                         }
5501                         buf += n;
5502                         n_used += n;
5503                         bufsize -= n;
5504                         n = 0;
5505                 }
5506
5507                 /* Restore name pointer to its original value */
5508                 name -= 16;
5509         }
5510
5511         if (n_used == 0) {
5512                 errno = ENOATTR;
5513                 return -1;
5514         }
5515
5516         return n_used;
5517 }
5518
5519 /*****************************************************
5520 set the ACLs on a file given an ascii description
5521 *******************************************************/
5522 static int
5523 cacl_set(TALLOC_CTX *ctx,
5524          struct cli_state *cli,
5525          struct cli_state *ipc_cli,
5526          POLICY_HND *pol,
5527          const char *filename,
5528          const char *the_acl,
5529          int mode,
5530          int flags)
5531 {
5532         int fnum;
5533         int err = 0;
5534         SEC_DESC *sd = NULL, *old;
5535         SEC_ACL *dacl = NULL;
5536         DOM_SID *owner_sid = NULL;
5537         DOM_SID *group_sid = NULL;
5538         uint32 i, j;
5539         size_t sd_size;
5540         int ret = 0;
5541         char *p;
5542         bool numeric = True;
5543
5544         /* the_acl will be null for REMOVE_ALL operations */
5545         if (the_acl) {
5546                 numeric = ((p = strchr(the_acl, ':')) != NULL &&
5547                            p > the_acl &&
5548                            p[-1] != '+');
5549
5550                 /* if this is to set the entire ACL... */
5551                 if (*the_acl == '*') {
5552                         /* ... then increment past the first colon */
5553                         the_acl = p + 1;
5554                 }
5555
5556                 sd = sec_desc_parse(ctx, ipc_cli, pol, numeric,
5557                                     CONST_DISCARD(char *, the_acl));
5558
5559                 if (!sd) {
5560                         errno = EINVAL;
5561                         return -1;
5562                 }
5563         }
5564
5565         /* SMBC_XATTR_MODE_REMOVE_ALL is the only caller
5566            that doesn't deref sd */
5567
5568         if (!sd && (mode != SMBC_XATTR_MODE_REMOVE_ALL)) {
5569                 errno = EINVAL;
5570                 return -1;
5571         }
5572
5573         /* The desired access below is the only one I could find that works
5574            with NT4, W2KP and Samba */
5575
5576         fnum = cli_nt_create(cli, filename, CREATE_ACCESS_READ);
5577
5578         if (fnum == -1) {
5579                 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5580                           filename, cli_errstr(cli)));
5581                 errno = 0;
5582                 return -1;
5583         }
5584
5585         old = cli_query_secdesc(cli, fnum, ctx);
5586
5587         if (!old) {
5588                 DEBUG(5, ("cacl_set Failed to query old descriptor\n"));
5589                 errno = 0;
5590                 return -1;
5591         }
5592
5593         cli_close(cli, fnum);
5594
5595         switch (mode) {
5596         case SMBC_XATTR_MODE_REMOVE_ALL:
5597                 old->dacl->num_aces = 0;
5598                 dacl = old->dacl;
5599                 break;
5600
5601         case SMBC_XATTR_MODE_REMOVE:
5602                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5603                         bool found = False;
5604
5605                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
5606                                 if (sec_ace_equal(&sd->dacl->aces[i],
5607                                                   &old->dacl->aces[j])) {
5608                                         uint32 k;
5609                                         for (k=j; k<old->dacl->num_aces-1;k++) {
5610                                                 old->dacl->aces[k] =
5611                                                         old->dacl->aces[k+1];
5612                                         }
5613                                         old->dacl->num_aces--;
5614                                         found = True;
5615                                         dacl = old->dacl;
5616                                         break;
5617                                 }
5618                         }
5619
5620                         if (!found) {
5621                                 err = ENOATTR;
5622                                 ret = -1;
5623                                 goto failed;
5624                         }
5625                 }
5626                 break;
5627
5628         case SMBC_XATTR_MODE_ADD:
5629                 for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5630                         bool found = False;
5631
5632                         for (j=0;old->dacl && j<old->dacl->num_aces;j++) {
5633                                 if (sid_equal(&sd->dacl->aces[i].trustee,
5634                                               &old->dacl->aces[j].trustee)) {
5635                                         if (!(flags & SMBC_XATTR_FLAG_CREATE)) {
5636                                                 err = EEXIST;
5637                                                 ret = -1;
5638                                                 goto failed;
5639                                         }
5640                                         old->dacl->aces[j] = sd->dacl->aces[i];
5641                                         ret = -1;
5642                                         found = True;
5643                                 }
5644                         }
5645
5646                         if (!found && (flags & SMBC_XATTR_FLAG_REPLACE)) {
5647                                 err = ENOATTR;
5648                                 ret = -1;
5649                                 goto failed;
5650                         }
5651
5652                         for (i=0;sd->dacl && i<sd->dacl->num_aces;i++) {
5653                                 add_ace(&old->dacl, &sd->dacl->aces[i], ctx);
5654                         }
5655                 }
5656                 dacl = old->dacl;
5657                 break;
5658
5659         case SMBC_XATTR_MODE_SET:
5660                 old = sd;
5661                 owner_sid = old->owner_sid;
5662                 group_sid = old->group_sid;
5663                 dacl = old->dacl;
5664                 break;
5665
5666         case SMBC_XATTR_MODE_CHOWN:
5667                 owner_sid = sd->owner_sid;
5668                 break;
5669
5670         case SMBC_XATTR_MODE_CHGRP:
5671                 group_sid = sd->group_sid;
5672                 break;
5673         }
5674
5675         /* Denied ACE entries must come before allowed ones */
5676         sort_acl(old->dacl);
5677
5678         /* Create new security descriptor and set it */
5679         sd = make_sec_desc(ctx, old->revision, SEC_DESC_SELF_RELATIVE,
5680                            owner_sid, group_sid, NULL, dacl, &sd_size);
5681
5682         fnum = cli_nt_create(cli, filename,
5683                              WRITE_DAC_ACCESS | WRITE_OWNER_ACCESS);
5684
5685         if (fnum == -1) {
5686                 DEBUG(5, ("cacl_set failed to open %s: %s\n",
5687                           filename, cli_errstr(cli)));
5688                 errno = 0;
5689                 return -1;
5690         }
5691
5692         if (!cli_set_secdesc(cli, fnum, sd)) {
5693                 DEBUG(5, ("ERROR: secdesc set failed: %s\n", cli_errstr(cli)));
5694                 ret = -1;
5695         }
5696
5697         /* Clean up */
5698
5699  failed:
5700         cli_close(cli, fnum);
5701
5702         if (err != 0) {
5703                 errno = err;
5704         }
5705
5706         return ret;
5707 }
5708
5709
5710 static int
5711 smbc_setxattr_ctx(SMBCCTX *context,
5712                   const char *fname,
5713                   const char *name,
5714                   const void *value,
5715                   size_t size,
5716                   int flags)
5717 {
5718         int ret;
5719         int ret2;
5720         SMBCSRV *srv = NULL;
5721         SMBCSRV *ipc_srv = NULL;
5722         char *server = NULL;
5723         char *share = NULL;
5724         char *user = NULL;
5725         char *password = NULL;
5726         char *workgroup = NULL;
5727         char *path = NULL;
5728         POLICY_HND pol;
5729         DOS_ATTR_DESC *dad = NULL;
5730         struct {
5731                 const char * create_time_attr;
5732                 const char * access_time_attr;
5733                 const char * write_time_attr;
5734                 const char * change_time_attr;
5735         } attr_strings;
5736         TALLOC_CTX *frame = talloc_stackframe();
5737
5738         if (!context || !context->internal ||
5739             !context->internal->_initialized) {
5740                 errno = EINVAL;  /* Best I can think of ... */
5741                 TALLOC_FREE(frame);
5742                 return -1;
5743         }
5744
5745         if (!fname) {
5746                 errno = EINVAL;
5747                 TALLOC_FREE(frame);
5748                 return -1;
5749         }
5750
5751         DEBUG(4, ("smbc_setxattr(%s, %s, %.*s)\n",
5752                   fname, name, (int) size, (const char*)value));
5753
5754         if (smbc_parse_path(frame,
5755                                 context,
5756                                 fname,
5757                                 &workgroup,
5758                                 &server,
5759                                 &share,
5760                                 &path,
5761                                 &user,
5762                                 &password,
5763                                 NULL)) {
5764                 errno = EINVAL;
5765                 TALLOC_FREE(frame);
5766                 return -1;
5767         }
5768
5769         if (!user || user[0] == (char)0) {
5770                 user = talloc_strdup(frame, context->user);
5771                 if (!user) {
5772                         errno = ENOMEM;
5773                         TALLOC_FREE(frame);
5774                         return -1;
5775                 }
5776         }
5777
5778         srv = smbc_server(frame, context, True,
5779                           server, share, &workgroup, &user, &password);
5780         if (!srv) {
5781                 TALLOC_FREE(frame);
5782                 return -1;  /* errno set by smbc_server */
5783         }
5784
5785         if (! srv->no_nt_session) {
5786                 ipc_srv = smbc_attr_server(frame, context, server, share,
5787                                            &workgroup, &user, &password,
5788                                            &pol);
5789                 if (! ipc_srv) {
5790                         srv->no_nt_session = True;
5791                 }
5792         } else {
5793                 ipc_srv = NULL;
5794         }
5795
5796         /*
5797          * Are they asking to set the entire set of known attributes?
5798          */
5799         if (StrCaseCmp(name, "system.*") == 0 ||
5800             StrCaseCmp(name, "system.*+") == 0) {
5801                 /* Yup. */
5802                 char *namevalue =
5803                         talloc_asprintf(talloc_tos(), "%s:%s",
5804                                         name+7, (const char *) value);
5805                 if (! namevalue) {
5806                         errno = ENOMEM;
5807                         ret = -1;
5808                         TALLOC_FREE(frame);
5809                         return -1;
5810                 }
5811
5812                 if (ipc_srv) {
5813                         ret = cacl_set(talloc_tos(), srv->cli,
5814                                        ipc_srv->cli, &pol, path,
5815                                        namevalue,
5816                                        (*namevalue == '*'
5817                                         ? SMBC_XATTR_MODE_SET
5818                                         : SMBC_XATTR_MODE_ADD),
5819                                        flags);
5820                 } else {
5821                         ret = 0;
5822                 }
5823
5824                 /* get a DOS Attribute Descriptor with current attributes */
5825                 dad = dos_attr_query(context, talloc_tos(), path, srv);
5826                 if (dad) {
5827                         /* Overwrite old with new, using what was provided */
5828                         dos_attr_parse(context, dad, srv, namevalue);
5829
5830                         /* Set the new DOS attributes */
5831                         if (! smbc_setatr(context, srv, path,
5832                                           dad->create_time,
5833                                           dad->access_time,
5834                                           dad->write_time,
5835                                           dad->change_time,
5836                                           dad->mode)) {
5837
5838                                 /* cause failure if NT failed too */
5839                                 dad = NULL; 
5840                         }
5841                 }
5842
5843                 /* we only fail if both NT and DOS sets failed */
5844                 if (ret < 0 && ! dad) {
5845                         ret = -1; /* in case dad was null */
5846                 }
5847                 else {
5848                         ret = 0;
5849                 }
5850
5851                 TALLOC_FREE(frame);
5852                 return ret;
5853         }
5854
5855         /*
5856          * Are they asking to set an access control element or to set
5857          * the entire access control list?
5858          */
5859         if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
5860             StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
5861             StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
5862             StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
5863             StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
5864
5865                 /* Yup. */
5866                 char *namevalue =
5867                         talloc_asprintf(talloc_tos(), "%s:%s",
5868                                         name+19, (const char *) value);
5869
5870                 if (! ipc_srv) {
5871                         ret = -1; /* errno set by smbc_server() */
5872                 }
5873                 else if (! namevalue) {
5874                         errno = ENOMEM;
5875                         ret = -1;
5876                 } else {
5877                         ret = cacl_set(talloc_tos(), srv->cli,
5878                                        ipc_srv->cli, &pol, path,
5879                                        namevalue,
5880                                        (*namevalue == '*'
5881                                         ? SMBC_XATTR_MODE_SET
5882                                         : SMBC_XATTR_MODE_ADD),
5883                                        flags);
5884                 }
5885                 TALLOC_FREE(frame);
5886                 return ret;
5887         }
5888
5889         /*
5890          * Are they asking to set the owner?
5891          */
5892         if (StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
5893             StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0) {
5894
5895                 /* Yup. */
5896                 char *namevalue =
5897                         talloc_asprintf(talloc_tos(), "%s:%s",
5898                                         name+19, (const char *) value);
5899
5900                 if (! ipc_srv) {
5901                         ret = -1; /* errno set by smbc_server() */
5902                 }
5903                 else if (! namevalue) {
5904                         errno = ENOMEM;
5905                         ret = -1;
5906                 } else {
5907                         ret = cacl_set(talloc_tos(), srv->cli,
5908                                        ipc_srv->cli, &pol, path,
5909                                        namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5910                 }
5911                 TALLOC_FREE(frame);
5912                 return ret;
5913         }
5914
5915         /*
5916          * Are they asking to set the group?
5917          */
5918         if (StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
5919             StrCaseCmp(name, "system.nt_sec_desc.group+") == 0) {
5920
5921                 /* Yup. */
5922                 char *namevalue =
5923                         talloc_asprintf(talloc_tos(), "%s:%s",
5924                                         name+19, (const char *) value);
5925
5926                 if (! ipc_srv) {
5927                         /* errno set by smbc_server() */
5928                         ret = -1;
5929                 }
5930                 else if (! namevalue) {
5931                         errno = ENOMEM;
5932                         ret = -1;
5933                 } else {
5934                         ret = cacl_set(talloc_tos(), srv->cli,
5935                                        ipc_srv->cli, &pol, path,
5936                                        namevalue, SMBC_XATTR_MODE_CHOWN, 0);
5937                 }
5938                 TALLOC_FREE(frame);
5939                 return ret;
5940         }
5941
5942         /* Determine whether to use old-style or new-style attribute names */
5943         if (context->internal->_full_time_names) {
5944                 /* new-style names */
5945                 attr_strings.create_time_attr = "system.dos_attr.CREATE_TIME";
5946                 attr_strings.access_time_attr = "system.dos_attr.ACCESS_TIME";
5947                 attr_strings.write_time_attr = "system.dos_attr.WRITE_TIME";
5948                 attr_strings.change_time_attr = "system.dos_attr.CHANGE_TIME";
5949         } else {
5950                 /* old-style names */
5951                 attr_strings.create_time_attr = NULL;
5952                 attr_strings.access_time_attr = "system.dos_attr.A_TIME";
5953                 attr_strings.write_time_attr = "system.dos_attr.M_TIME";
5954                 attr_strings.change_time_attr = "system.dos_attr.C_TIME";
5955         }
5956
5957         /*
5958          * Are they asking to set a DOS attribute?
5959          */
5960         if (StrCaseCmp(name, "system.dos_attr.*") == 0 ||
5961             StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
5962             (attr_strings.create_time_attr != NULL &&
5963              StrCaseCmp(name, attr_strings.create_time_attr) == 0) ||
5964             StrCaseCmp(name, attr_strings.access_time_attr) == 0 ||
5965             StrCaseCmp(name, attr_strings.write_time_attr) == 0 ||
5966             StrCaseCmp(name, attr_strings.change_time_attr) == 0) {
5967
5968                 /* get a DOS Attribute Descriptor with current attributes */
5969                 dad = dos_attr_query(context, talloc_tos(), path, srv);
5970                 if (dad) {
5971                         char *namevalue =
5972                                 talloc_asprintf(talloc_tos(), "%s:%s",
5973                                                 name+16, (const char *) value);
5974                         if (! namevalue) {
5975                                 errno = ENOMEM;
5976                                 ret = -1;
5977                         } else {
5978                                 /* Overwrite old with provided new params */
5979                                 dos_attr_parse(context, dad, srv, namevalue);
5980
5981                                 /* Set the new DOS attributes */
5982                                 ret2 = smbc_setatr(context, srv, path,
5983                                                    dad->create_time,
5984                                                    dad->access_time,
5985                                                    dad->write_time,
5986                                                    dad->change_time,
5987                                                    dad->mode);
5988
5989                                 /* ret2 has True (success) / False (failure) */
5990                                 if (ret2) {
5991                                         ret = 0;
5992                                 } else {
5993                                         ret = -1;
5994                                 }
5995                         }
5996                 } else {
5997                         ret = -1;
5998                 }
5999
6000                 TALLOC_FREE(frame);
6001                 return ret;
6002         }
6003
6004         /* Unsupported attribute name */
6005         errno = EINVAL;
6006         TALLOC_FREE(frame);
6007         return -1;
6008 }
6009
6010 static int
6011 smbc_getxattr_ctx(SMBCCTX *context,
6012                   const char *fname,
6013                   const char *name,
6014                   const void *value,
6015                   size_t size)
6016 {
6017         int ret;
6018         SMBCSRV *srv = NULL;
6019         SMBCSRV *ipc_srv = NULL;
6020         char *server = NULL;
6021         char *share = NULL;
6022         char *user = NULL;
6023         char *password = NULL;
6024         char *workgroup = NULL;
6025         char *path = NULL;
6026         POLICY_HND pol;
6027         struct {
6028                 const char * create_time_attr;
6029                 const char * access_time_attr;
6030                 const char * write_time_attr;
6031                 const char * change_time_attr;
6032         } attr_strings;
6033         TALLOC_CTX *frame = talloc_stackframe();
6034
6035         if (!context || !context->internal ||
6036             !context->internal->_initialized) {
6037                 errno = EINVAL;  /* Best I can think of ... */
6038                 TALLOC_FREE(frame);
6039                 return -1;
6040         }
6041
6042         if (!fname) {
6043                 errno = EINVAL;
6044                 TALLOC_FREE(frame);
6045                 return -1;
6046         }
6047
6048         DEBUG(4, ("smbc_getxattr(%s, %s)\n", fname, name));
6049
6050         if (smbc_parse_path(frame,
6051                                 context,
6052                                 fname,
6053                                 &workgroup,
6054                                 &server,
6055                                 &share,
6056                                 &path,
6057                                 &user,
6058                                 &password,
6059                                 NULL)) {
6060                 errno = EINVAL;
6061                 TALLOC_FREE(frame);
6062                 return -1;
6063         }
6064
6065         if (!user || user[0] == (char)0) {
6066                 user = talloc_strdup(frame, context->user);
6067                 if (!user) {
6068                         errno = ENOMEM;
6069                         TALLOC_FREE(frame);
6070                         return -1;
6071                 }
6072         }
6073
6074         srv = smbc_server(frame, context, True,
6075                           server, share, &workgroup, &user, &password);
6076         if (!srv) {
6077                 TALLOC_FREE(frame);
6078                 return -1;  /* errno set by smbc_server */
6079         }
6080
6081         if (! srv->no_nt_session) {
6082                 ipc_srv = smbc_attr_server(frame, context, server, share,
6083                                            &workgroup, &user, &password,
6084                                            &pol);
6085                 if (! ipc_srv) {
6086                         srv->no_nt_session = True;
6087                 }
6088         } else {
6089                 ipc_srv = NULL;
6090         }
6091
6092         /* Determine whether to use old-style or new-style attribute names */
6093         if (context->internal->_full_time_names) {
6094                 /* new-style names */
6095                 attr_strings.create_time_attr = "system.dos_attr.CREATE_TIME";
6096                 attr_strings.access_time_attr = "system.dos_attr.ACCESS_TIME";
6097                 attr_strings.write_time_attr = "system.dos_attr.WRITE_TIME";
6098                 attr_strings.change_time_attr = "system.dos_attr.CHANGE_TIME";
6099         } else {
6100                 /* old-style names */
6101                 attr_strings.create_time_attr = NULL;
6102                 attr_strings.access_time_attr = "system.dos_attr.A_TIME";
6103                 attr_strings.write_time_attr = "system.dos_attr.M_TIME";
6104                 attr_strings.change_time_attr = "system.dos_attr.C_TIME";
6105         }
6106
6107         /* Are they requesting a supported attribute? */
6108         if (StrCaseCmp(name, "system.*") == 0 ||
6109             StrnCaseCmp(name, "system.*!", 9) == 0 ||
6110             StrCaseCmp(name, "system.*+") == 0 ||
6111             StrnCaseCmp(name, "system.*+!", 10) == 0 ||
6112             StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
6113             StrnCaseCmp(name, "system.nt_sec_desc.*!", 21) == 0 ||
6114             StrCaseCmp(name, "system.nt_sec_desc.*+") == 0 ||
6115             StrnCaseCmp(name, "system.nt_sec_desc.*+!", 22) == 0 ||
6116             StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
6117             StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
6118             StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
6119             StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
6120             StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
6121             StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
6122             StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0 ||
6123             StrCaseCmp(name, "system.dos_attr.*") == 0 ||
6124             StrnCaseCmp(name, "system.dos_attr.*!", 18) == 0 ||
6125             StrCaseCmp(name, "system.dos_attr.mode") == 0 ||
6126             StrCaseCmp(name, "system.dos_attr.size") == 0 ||
6127             (attr_strings.create_time_attr != NULL &&
6128              StrCaseCmp(name, attr_strings.create_time_attr) == 0) ||
6129             StrCaseCmp(name, attr_strings.access_time_attr) == 0 ||
6130             StrCaseCmp(name, attr_strings.write_time_attr) == 0 ||
6131             StrCaseCmp(name, attr_strings.change_time_attr) == 0 ||
6132             StrCaseCmp(name, "system.dos_attr.inode") == 0) {
6133
6134                 /* Yup. */
6135                 ret = cacl_get(context, talloc_tos(), srv,
6136                                ipc_srv == NULL ? NULL : ipc_srv->cli, 
6137                                &pol, path,
6138                                CONST_DISCARD(char *, name),
6139                                CONST_DISCARD(char *, value), size);
6140                 if (ret < 0 && errno == 0) {
6141                         errno = smbc_errno(context, srv->cli);
6142                 }
6143                 TALLOC_FREE(frame);
6144                 return ret;
6145         }
6146
6147         /* Unsupported attribute name */
6148         errno = EINVAL;
6149         TALLOC_FREE(frame);
6150         return -1;
6151 }
6152
6153
6154 static int
6155 smbc_removexattr_ctx(SMBCCTX *context,
6156                      const char *fname,
6157                      const char *name)
6158 {
6159         int ret;
6160         SMBCSRV *srv = NULL;
6161         SMBCSRV *ipc_srv = NULL;
6162         char *server = NULL;
6163         char *share = NULL;
6164         char *user = NULL;
6165         char *password = NULL;
6166         char *workgroup = NULL;
6167         char *path = NULL;
6168         POLICY_HND pol;
6169         TALLOC_CTX *frame = talloc_stackframe();
6170
6171         if (!context || !context->internal ||
6172             !context->internal->_initialized) {
6173                 errno = EINVAL;  /* Best I can think of ... */
6174                 TALLOC_FREE(frame);
6175                 return -1;
6176         }
6177
6178         if (!fname) {
6179                 errno = EINVAL;
6180                 TALLOC_FREE(frame);
6181                 return -1;
6182         }
6183
6184         DEBUG(4, ("smbc_removexattr(%s, %s)\n", fname, name));
6185
6186         if (smbc_parse_path(frame,
6187                                 context,
6188                                 fname,
6189                                 &workgroup,
6190                                 &server,
6191                                 &share,
6192                                 &path,
6193                                 &user,
6194                                 &password,
6195                                 NULL)) {
6196                 errno = EINVAL;
6197                 TALLOC_FREE(frame);
6198                 return -1;
6199         }
6200
6201         if (!user || user[0] == (char)0) {
6202                 user = talloc_strdup(frame, context->user);
6203                 if (!user) {
6204                         errno = ENOMEM;
6205                         TALLOC_FREE(frame);
6206                         return -1;
6207                 }
6208         }
6209
6210         srv = smbc_server(frame, context, True,
6211                           server, share, &workgroup, &user, &password);
6212         if (!srv) {
6213                 TALLOC_FREE(frame);
6214                 return -1;  /* errno set by smbc_server */
6215         }
6216
6217         if (! srv->no_nt_session) {
6218                 ipc_srv = smbc_attr_server(frame, context, server, share,
6219                                            &workgroup, &user, &password,
6220                                            &pol);
6221                 if (! ipc_srv) {
6222                         srv->no_nt_session = True;
6223                 }
6224         } else {
6225                 ipc_srv = NULL;
6226         }
6227
6228         if (! ipc_srv) {
6229                 TALLOC_FREE(frame);
6230                 return -1; /* errno set by smbc_attr_server */
6231         }
6232
6233         /* Are they asking to set the entire ACL? */
6234         if (StrCaseCmp(name, "system.nt_sec_desc.*") == 0 ||
6235             StrCaseCmp(name, "system.nt_sec_desc.*+") == 0) {
6236
6237                 /* Yup. */
6238                 ret = cacl_set(talloc_tos(), srv->cli,
6239                                ipc_srv->cli, &pol, path,
6240                                NULL, SMBC_XATTR_MODE_REMOVE_ALL, 0);
6241                 TALLOC_FREE(frame);
6242                 return ret;
6243         }
6244
6245         /*
6246          * Are they asking to remove one or more spceific security descriptor
6247          * attributes?
6248          */
6249         if (StrCaseCmp(name, "system.nt_sec_desc.revision") == 0 ||
6250             StrCaseCmp(name, "system.nt_sec_desc.owner") == 0 ||
6251             StrCaseCmp(name, "system.nt_sec_desc.owner+") == 0 ||
6252             StrCaseCmp(name, "system.nt_sec_desc.group") == 0 ||
6253             StrCaseCmp(name, "system.nt_sec_desc.group+") == 0 ||
6254             StrnCaseCmp(name, "system.nt_sec_desc.acl", 22) == 0 ||
6255             StrnCaseCmp(name, "system.nt_sec_desc.acl+", 23) == 0) {
6256
6257                 /* Yup. */
6258                 ret = cacl_set(talloc_tos(), srv->cli,
6259                                ipc_srv->cli, &pol, path,
6260                                name + 19, SMBC_XATTR_MODE_REMOVE, 0);
6261                 TALLOC_FREE(frame);
6262                 return ret;
6263         }
6264
6265         /* Unsupported attribute name */
6266         errno = EINVAL;
6267         TALLOC_FREE(frame);
6268         return -1;
6269 }
6270
6271 static int
6272 smbc_listxattr_ctx(SMBCCTX *context,
6273                    const char *fname,
6274                    char *list,
6275                    size_t size)
6276 {
6277         /*
6278          * This isn't quite what listxattr() is supposed to do.  This returns
6279          * the complete set of attribute names, always, rather than only those
6280          * attribute names which actually exist for a file.  Hmmm...
6281          */
6282         size_t retsize;
6283         const char supported_old[] =
6284                 "system.*\0"
6285                 "system.*+\0"
6286                 "system.nt_sec_desc.revision\0"
6287                 "system.nt_sec_desc.owner\0"
6288                 "system.nt_sec_desc.owner+\0"
6289                 "system.nt_sec_desc.group\0"
6290                 "system.nt_sec_desc.group+\0"
6291                 "system.nt_sec_desc.acl.*\0"
6292                 "system.nt_sec_desc.acl\0"
6293                 "system.nt_sec_desc.acl+\0"
6294                 "system.nt_sec_desc.*\0"
6295                 "system.nt_sec_desc.*+\0"
6296                 "system.dos_attr.*\0"
6297                 "system.dos_attr.mode\0"
6298                 "system.dos_attr.c_time\0"
6299                 "system.dos_attr.a_time\0"
6300                 "system.dos_attr.m_time\0"
6301                 ;
6302         const char supported_new[] =
6303                 "system.*\0"
6304                 "system.*+\0"
6305                 "system.nt_sec_desc.revision\0"
6306                 "system.nt_sec_desc.owner\0"
6307                 "system.nt_sec_desc.owner+\0"
6308                 "system.nt_sec_desc.group\0"
6309                 "system.nt_sec_desc.group+\0"
6310                 "system.nt_sec_desc.acl.*\0"
6311                 "system.nt_sec_desc.acl\0"
6312                 "system.nt_sec_desc.acl+\0"
6313                 "system.nt_sec_desc.*\0"
6314                 "system.nt_sec_desc.*+\0"
6315                 "system.dos_attr.*\0"
6316                 "system.dos_attr.mode\0"
6317                 "system.dos_attr.create_time\0"
6318                 "system.dos_attr.access_time\0"
6319                 "system.dos_attr.write_time\0"
6320                 "system.dos_attr.change_time\0"
6321                 ;
6322         const char * supported;
6323
6324         if (context->internal->_full_time_names) {
6325                 supported = supported_new;
6326                 retsize = sizeof(supported_new);
6327         } else {
6328                 supported = supported_old;
6329                 retsize = sizeof(supported_old);
6330         }
6331
6332         if (size == 0) {
6333                 return retsize;
6334         }
6335
6336         if (retsize > size) {
6337                 errno = ERANGE;
6338                 return -1;
6339         }
6340
6341         /* this can't be strcpy() because there are embedded null characters */
6342         memcpy(list, supported, retsize);
6343         return retsize;
6344 }
6345
6346
6347 /*
6348  * Open a print file to be written to by other calls
6349  */
6350
6351 static SMBCFILE *
6352 smbc_open_print_job_ctx(SMBCCTX *context,
6353                         const char *fname)
6354 {
6355         char *server = NULL;
6356         char *share = NULL;
6357         char *user = NULL;
6358         char *password = NULL;
6359         char *path = NULL;
6360         TALLOC_CTX *frame = talloc_stackframe();
6361
6362         if (!context || !context->internal ||
6363             !context->internal->_initialized) {
6364                 errno = EINVAL;
6365                 TALLOC_FREE(frame);
6366                 return NULL;
6367         }
6368
6369         if (!fname) {
6370                 errno = EINVAL;
6371                 TALLOC_FREE(frame);
6372                 return NULL;
6373         }
6374
6375         DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
6376
6377         if (smbc_parse_path(frame,
6378                                 context,
6379                                 fname,
6380                                 NULL,
6381                                 &server,
6382                                 &share,
6383                                 &path,
6384                                 &user,
6385                                 &password,
6386                                 NULL)) {
6387                 errno = EINVAL;
6388                 TALLOC_FREE(frame);
6389                 return NULL;
6390         }
6391
6392         /* What if the path is empty, or the file exists? */
6393
6394         TALLOC_FREE(frame);
6395         return (context->open)(context, fname, O_WRONLY, 666);
6396 }
6397
6398 /*
6399  * Routine to print a file on a remote server ...
6400  *
6401  * We open the file, which we assume to be on a remote server, and then
6402  * copy it to a print file on the share specified by printq.
6403  */
6404
6405 static int
6406 smbc_print_file_ctx(SMBCCTX *c_file,
6407                     const char *fname,
6408                     SMBCCTX *c_print,
6409                     const char *printq)
6410 {
6411         SMBCFILE *fid1;
6412         SMBCFILE *fid2;
6413         int bytes;
6414         int saverr;
6415         int tot_bytes = 0;
6416         char buf[4096];
6417         TALLOC_CTX *frame = talloc_stackframe();
6418
6419         if (!c_file || !c_file->internal->_initialized || !c_print ||
6420             !c_print->internal->_initialized) {
6421
6422                 errno = EINVAL;
6423                 TALLOC_FREE(frame);
6424                 return -1;
6425
6426         }
6427
6428         if (!fname && !printq) {
6429
6430                 errno = EINVAL;
6431                 TALLOC_FREE(frame);
6432                 return -1;
6433
6434         }
6435
6436         /* Try to open the file for reading ... */
6437
6438         if ((long)(fid1 = (c_file->open)(c_file, fname, O_RDONLY, 0666)) < 0) {
6439                 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
6440                 TALLOC_FREE(frame);
6441                 return -1;  /* smbc_open sets errno */
6442         }
6443
6444         /* Now, try to open the printer file for writing */
6445
6446         if ((long)(fid2 = (c_print->open_print_job)(c_print, printq)) < 0) {
6447
6448                 saverr = errno;  /* Save errno */
6449                 (c_file->close_fn)(c_file, fid1);
6450                 errno = saverr;
6451                 TALLOC_FREE(frame);
6452                 return -1;
6453
6454         }
6455
6456         while ((bytes = (c_file->read)(c_file, fid1, buf, sizeof(buf))) > 0) {
6457
6458                 tot_bytes += bytes;
6459
6460                 if (((c_print->write)(c_print, fid2, buf, bytes)) < 0) {
6461
6462                         saverr = errno;
6463                         (c_file->close_fn)(c_file, fid1);
6464                         (c_print->close_fn)(c_print, fid2);
6465                         errno = saverr;
6466
6467                 }
6468
6469         }
6470
6471         saverr = errno;
6472
6473         (c_file->close_fn)(c_file, fid1);  /* We have to close these anyway */
6474         (c_print->close_fn)(c_print, fid2);
6475
6476         if (bytes < 0) {
6477
6478                 errno = saverr;
6479                 TALLOC_FREE(frame);
6480                 return -1;
6481
6482         }
6483
6484         TALLOC_FREE(frame);
6485         return tot_bytes;
6486
6487 }
6488
6489 /*
6490  * Routine to list print jobs on a printer share ...
6491  */
6492
6493 static int
6494 smbc_list_print_jobs_ctx(SMBCCTX *context,
6495                          const char *fname,
6496                          smbc_list_print_job_fn fn)
6497 {
6498         SMBCSRV *srv = NULL;
6499         char *server = NULL;
6500         char *share = NULL;
6501         char *user = NULL;
6502         char *password = NULL;
6503         char *workgroup = NULL;
6504         char *path = NULL;
6505         TALLOC_CTX *frame = talloc_stackframe();
6506
6507         if (!context || !context->internal ||
6508             !context->internal->_initialized) {
6509                 errno = EINVAL;
6510                 TALLOC_FREE(frame);
6511                 return -1;
6512         }
6513
6514         if (!fname) {
6515                 errno = EINVAL;
6516                 TALLOC_FREE(frame);
6517                 return -1;
6518         }
6519
6520         DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
6521
6522         if (smbc_parse_path(frame,
6523                                 context,
6524                                 fname,
6525                                 &workgroup,
6526                                 &server,
6527                                 &share,
6528                                 &path,
6529                                 &user,
6530                                 &password,
6531                                 NULL)) {
6532                 errno = EINVAL;
6533                 TALLOC_FREE(frame);
6534                 return -1;
6535         }
6536
6537         if (!user || user[0] == (char)0) {
6538                 user = talloc_strdup(frame, context->user);
6539                 if (!user) {
6540                         errno = ENOMEM;
6541                         TALLOC_FREE(frame);
6542                         return -1;
6543                 }
6544         }
6545
6546         srv = smbc_server(frame, context, True,
6547                           server, share, &workgroup, &user, &password);
6548
6549         if (!srv) {
6550                 TALLOC_FREE(frame);
6551                 return -1;  /* errno set by smbc_server */
6552         }
6553
6554         if (cli_print_queue(srv->cli,
6555                             (void (*)(struct print_job_info *))fn) < 0) {
6556                 errno = smbc_errno(context, srv->cli);
6557                 TALLOC_FREE(frame);
6558                 return -1;
6559         }
6560
6561         TALLOC_FREE(frame);
6562         return 0;
6563
6564 }
6565
6566 /*
6567  * Delete a print job from a remote printer share
6568  */
6569
6570 static int
6571 smbc_unlink_print_job_ctx(SMBCCTX *context,
6572                           const char *fname,
6573                           int id)
6574 {
6575         SMBCSRV *srv = NULL;
6576         char *server = NULL;
6577         char *share = NULL;
6578         char *user = NULL;
6579         char *password = NULL;
6580         char *workgroup = NULL;
6581         char *path = NULL;
6582         int err;
6583         TALLOC_CTX *frame = talloc_stackframe();
6584
6585         if (!context || !context->internal ||
6586             !context->internal->_initialized) {
6587                 errno = EINVAL;
6588                 TALLOC_FREE(frame);
6589                 return -1;
6590         }
6591
6592         if (!fname) {
6593                 errno = EINVAL;
6594                 TALLOC_FREE(frame);
6595                 return -1;
6596         }
6597
6598         DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
6599
6600         if (smbc_parse_path(frame,
6601                                 context,
6602                                 fname,
6603                                 &workgroup,
6604                                 &server,
6605                                 &share,
6606                                 &path,
6607                                 &user,
6608                                 &password,
6609                                 NULL)) {
6610                 errno = EINVAL;
6611                 TALLOC_FREE(frame);
6612                 return -1;
6613         }
6614
6615         if (!user || user[0] == (char)0) {
6616                 user = talloc_strdup(frame, context->user);
6617                 if (!user) {
6618                         errno = ENOMEM;
6619                         TALLOC_FREE(frame);
6620                         return -1;
6621                 }
6622         }
6623
6624         srv = smbc_server(frame, context, True,
6625                           server, share, &workgroup, &user, &password);
6626
6627         if (!srv) {
6628
6629                 TALLOC_FREE(frame);
6630                 return -1;  /* errno set by smbc_server */
6631
6632         }
6633
6634         if ((err = cli_printjob_del(srv->cli, id)) != 0) {
6635
6636                 if (err < 0)
6637                         errno = smbc_errno(context, srv->cli);
6638                 else if (err == ERRnosuchprintjob)
6639                         errno = EINVAL;
6640                 TALLOC_FREE(frame);
6641                 return -1;
6642
6643         }
6644
6645         TALLOC_FREE(frame);
6646         return 0;
6647
6648 }
6649
6650 /*
6651  * Get a new empty handle to fill in with your own info
6652  */
6653 SMBCCTX *
6654 smbc_new_context(void)
6655 {
6656         SMBCCTX *context;
6657
6658         context = SMB_MALLOC_P(SMBCCTX);
6659         if (!context) {
6660                 errno = ENOMEM;
6661                 return NULL;
6662         }
6663
6664         ZERO_STRUCTP(context);
6665
6666         context->internal = SMB_MALLOC_P(struct smbc_internal_data);
6667         if (!context->internal) {
6668                 SAFE_FREE(context);
6669                 errno = ENOMEM;
6670                 return NULL;
6671         }
6672
6673         ZERO_STRUCTP(context->internal);
6674
6675         /* ADD REASONABLE DEFAULTS */
6676         context->debug            = 0;
6677         context->timeout          = 20000; /* 20 seconds */
6678
6679         context->options.browse_max_lmb_count      = 3;    /* # LMBs to query */
6680         context->options.urlencode_readdir_entries = False;/* backward compat */
6681         context->options.one_share_per_server      = False;/* backward compat */
6682         context->internal->_share_mode             = SMBC_SHAREMODE_DENY_NONE;
6683                                 /* backward compat */
6684
6685         context->open                              = smbc_open_ctx;
6686         context->creat                             = smbc_creat_ctx;
6687         context->read                              = smbc_read_ctx;
6688         context->write                             = smbc_write_ctx;
6689         context->close_fn                          = smbc_close_ctx;
6690         context->unlink                            = smbc_unlink_ctx;
6691         context->rename                            = smbc_rename_ctx;
6692         context->lseek                             = smbc_lseek_ctx;
6693         context->stat                              = smbc_stat_ctx;
6694         context->fstat                             = smbc_fstat_ctx;
6695         context->opendir                           = smbc_opendir_ctx;
6696         context->closedir                          = smbc_closedir_ctx;
6697         context->readdir                           = smbc_readdir_ctx;
6698         context->getdents                          = smbc_getdents_ctx;
6699         context->mkdir                             = smbc_mkdir_ctx;
6700         context->rmdir                             = smbc_rmdir_ctx;
6701         context->telldir                           = smbc_telldir_ctx;
6702         context->lseekdir                          = smbc_lseekdir_ctx;
6703         context->fstatdir                          = smbc_fstatdir_ctx;
6704         context->chmod                             = smbc_chmod_ctx;
6705         context->utimes                            = smbc_utimes_ctx;
6706         context->setxattr                          = smbc_setxattr_ctx;
6707         context->getxattr                          = smbc_getxattr_ctx;
6708         context->removexattr                       = smbc_removexattr_ctx;
6709         context->listxattr                         = smbc_listxattr_ctx;
6710         context->open_print_job                    = smbc_open_print_job_ctx;
6711         context->print_file                        = smbc_print_file_ctx;
6712         context->list_print_jobs                   = smbc_list_print_jobs_ctx;
6713         context->unlink_print_job                  = smbc_unlink_print_job_ctx;
6714
6715         context->callbacks.check_server_fn         = smbc_check_server;
6716         context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
6717
6718         smbc_default_cache_functions(context);
6719
6720         return context;
6721 }
6722
6723 /*
6724  * Free a context
6725  *
6726  * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
6727  * and thus you'll be leaking memory if not handled properly.
6728  *
6729  */
6730 int
6731 smbc_free_context(SMBCCTX *context,
6732                   int shutdown_ctx)
6733 {
6734         if (!context) {
6735                 errno = EBADF;
6736                 return 1;
6737         }
6738
6739         if (shutdown_ctx) {
6740                 SMBCFILE * f;
6741                 DEBUG(1,("Performing aggressive shutdown.\n"));
6742
6743                 f = context->internal->_files;
6744                 while (f) {
6745                         (context->close_fn)(context, f);
6746                         f = f->next;
6747                 }
6748                 context->internal->_files = NULL;
6749
6750                 /* First try to remove the servers the nice way. */
6751                 if (context->callbacks.purge_cached_fn(context)) {
6752                         SMBCSRV * s;
6753                         SMBCSRV * next;
6754                         DEBUG(1, ("Could not purge all servers, "
6755                                   "Nice way shutdown failed.\n"));
6756                         s = context->internal->_servers;
6757                         while (s) {
6758                                 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
6759                                           s, s->cli->fd));
6760                                 cli_shutdown(s->cli);
6761                                 (context->callbacks.remove_cached_srv_fn)(context,
6762                                                                           s);
6763                                 next = s->next;
6764                                 DLIST_REMOVE(context->internal->_servers, s);
6765                                 SAFE_FREE(s);
6766                                 s = next;
6767                         }
6768                         context->internal->_servers = NULL;
6769                 }
6770         }
6771         else {
6772                 /* This is the polite way */
6773                 if ((context->callbacks.purge_cached_fn)(context)) {
6774                         DEBUG(1, ("Could not purge all servers, "
6775                                   "free_context failed.\n"));
6776                         errno = EBUSY;
6777                         return 1;
6778                 }
6779                 if (context->internal->_servers) {
6780                         DEBUG(1, ("Active servers in context, "
6781                                   "free_context failed.\n"));
6782                         errno = EBUSY;
6783                         return 1;
6784                 }
6785                 if (context->internal->_files) {
6786                         DEBUG(1, ("Active files in context, "
6787                                   "free_context failed.\n"));
6788                         errno = EBUSY;
6789                         return 1;
6790                 }
6791         }
6792
6793         /* Things we have to clean up */
6794         SAFE_FREE(context->workgroup);
6795         SAFE_FREE(context->netbios_name);
6796         SAFE_FREE(context->user);
6797
6798         DEBUG(3, ("Context %p succesfully freed\n", context));
6799         SAFE_FREE(context->internal);
6800         SAFE_FREE(context);
6801         return 0;
6802 }
6803
6804
6805 /*
6806  * Each time the context structure is changed, we have binary backward
6807  * compatibility issues.  Instead of modifying the public portions of the
6808  * context structure to add new options, instead, we put them in the internal
6809  * portion of the context structure and provide a set function for these new
6810  * options.
6811  */
6812 void
6813 smbc_option_set(SMBCCTX *context,
6814                 char *option_name,
6815                 ... /* option_value */)
6816 {
6817         va_list ap;
6818         union {
6819                 int i;
6820                 bool b;
6821                 smbc_get_auth_data_with_context_fn auth_fn;
6822                 void *v;
6823                 const char *s;
6824         } option_value;
6825
6826         va_start(ap, option_name);
6827
6828         if (strcmp(option_name, "debug_to_stderr") == 0) {
6829                 /*
6830                  * Log to standard error instead of standard output.
6831                  */
6832                 option_value.b = (bool) va_arg(ap, int);
6833                 context->internal->_debug_stderr = option_value.b;
6834
6835         } else if (strcmp(option_name, "full_time_names") == 0) {
6836                 /*
6837                  * Use new-style time attribute names, e.g. WRITE_TIME rather
6838                  * than the old-style names such as M_TIME.  This allows also
6839                  * setting/getting CREATE_TIME which was previously
6840                  * unimplemented.  (Note that the old C_TIME was supposed to
6841                  * be CHANGE_TIME but was confused and sometimes referred to
6842                  * CREATE_TIME.)
6843                  */
6844                 option_value.b = (bool) va_arg(ap, int);
6845                 context->internal->_full_time_names = option_value.b;
6846
6847         } else if (strcmp(option_name, "open_share_mode") == 0) {
6848                 /*
6849                  * The share mode to use for files opened with
6850                  * smbc_open_ctx().  The default is SMBC_SHAREMODE_DENY_NONE.
6851                  */
6852                 option_value.i = va_arg(ap, int);
6853                 context->internal->_share_mode =
6854                         (smbc_share_mode) option_value.i;
6855
6856         } else if (strcmp(option_name, "auth_function") == 0) {
6857                 /*
6858                  * Use the new-style authentication function which includes
6859                  * the context.
6860                  */
6861                 option_value.auth_fn =
6862                         va_arg(ap, smbc_get_auth_data_with_context_fn);
6863                 context->internal->_auth_fn_with_context =
6864                         option_value.auth_fn;
6865         } else if (strcmp(option_name, "user_data") == 0) {
6866                 /*
6867                  * Save a user data handle which may be retrieved by the user
6868                  * with smbc_option_get()
6869                  */
6870                 option_value.v = va_arg(ap, void *);
6871                 context->internal->_user_data = option_value.v;
6872         } else if (strcmp(option_name, "smb_encrypt_level") == 0) {
6873                 /*
6874                  * Save an encoded value for encryption level.
6875                  * 0 = off, 1 = attempt, 2 = required.
6876                  */
6877                 option_value.s = va_arg(ap, const char *);
6878                 if (strcmp(option_value.s, "none") == 0) {
6879                         context->internal->_smb_encryption_level = 0;
6880                 } else if (strcmp(option_value.s, "request") == 0) {
6881                         context->internal->_smb_encryption_level = 1;
6882                 } else if (strcmp(option_value.s, "require") == 0) {
6883                         context->internal->_smb_encryption_level = 2;
6884                 }
6885         }
6886
6887         va_end(ap);
6888 }
6889
6890
6891 /*
6892  * Retrieve the current value of an option
6893  */
6894 void *
6895 smbc_option_get(SMBCCTX *context,
6896                 char *option_name)
6897 {
6898         if (strcmp(option_name, "debug_stderr") == 0) {
6899                 /*
6900                  * Log to standard error instead of standard output.
6901                  */
6902 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6903                 return (void *) (intptr_t) context->internal->_debug_stderr;
6904 #else
6905                 return (void *) context->internal->_debug_stderr;
6906 #endif
6907         } else if (strcmp(option_name, "full_time_names") == 0) {
6908                 /*
6909                  * Use new-style time attribute names, e.g. WRITE_TIME rather
6910                  * than the old-style names such as M_TIME.  This allows also
6911                  * setting/getting CREATE_TIME which was previously
6912                  * unimplemented.  (Note that the old C_TIME was supposed to
6913                  * be CHANGE_TIME but was confused and sometimes referred to
6914                  * CREATE_TIME.)
6915                  */
6916 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
6917                 return (void *) (intptr_t) context->internal->_full_time_names;
6918 #else
6919                 return (void *) context->internal->_full_time_names;
6920 #endif
6921
6922         } else if (strcmp(option_name, "auth_function") == 0) {
6923                 /*
6924                  * Use the new-style authentication function which includes
6925                  * the context.
6926                  */
6927                 return (void *) context->internal->_auth_fn_with_context;
6928         } else if (strcmp(option_name, "user_data") == 0) {
6929                 /*
6930                  * Save a user data handle which may be retrieved by the user
6931                  * with smbc_option_get()
6932                  */
6933                 return context->internal->_user_data;
6934         } else if (strcmp(option_name, "smb_encrypt_level") == 0) {
6935                 /*
6936                  * Return the current smb encrypt negotiate option as a string.
6937                  */
6938                 switch (context->internal->_smb_encryption_level) {
6939                 case 0:
6940                         return (void *) "none";
6941                 case 1:
6942                         return (void *) "request";
6943                 case 2:
6944                         return (void *) "require";
6945                 }
6946         } else if (strcmp(option_name, "smb_encrypt_on") == 0) {
6947                 /*
6948                  * Return the current smb encrypt status option as a bool.
6949                  * false = off, true = on. We don't know what server is
6950                  * being requested, so we only return true if all servers
6951                  * are using an encrypted connection.
6952                  */
6953                 SMBCSRV *s;
6954                 unsigned int num_servers = 0;
6955
6956                 for (s = context->internal->_servers; s; s = s->next) {
6957                         num_servers++;
6958                         if (s->cli->trans_enc_state == NULL) {
6959                                 return (void *)false;
6960                         }
6961                 }
6962                 return (void *) (bool) (num_servers > 0);
6963         }
6964
6965         return NULL;
6966 }
6967
6968
6969 /*
6970  * Initialise the library etc
6971  *
6972  * We accept a struct containing handle information.
6973  * valid values for info->debug from 0 to 100,
6974  * and insist that info->fn must be non-null.
6975  */
6976 SMBCCTX *
6977 smbc_init_context(SMBCCTX *context)
6978 {
6979         int pid;
6980         char *user = NULL;
6981         char *home = NULL;
6982
6983         if (!context || !context->internal) {
6984                 errno = EBADF;
6985                 return NULL;
6986         }
6987
6988         /* Do not initialise the same client twice */
6989         if (context->internal->_initialized) {
6990                 return 0;
6991         }
6992
6993         if ((!context->callbacks.auth_fn &&
6994              !context->internal->_auth_fn_with_context) ||
6995             context->debug < 0 ||
6996             context->debug > 100) {
6997
6998                 errno = EINVAL;
6999                 return NULL;
7000
7001         }
7002
7003         if (!smbc_initialized) {
7004                 /*
7005                  * Do some library-wide intializations the first time we get
7006                  * called
7007                  */
7008                 bool conf_loaded = False;
7009                 TALLOC_CTX *frame = talloc_stackframe();
7010
7011                 /* Set this to what the user wants */
7012                 DEBUGLEVEL = context->debug;
7013
7014                 load_case_tables();
7015
7016                 setup_logging("libsmbclient", True);
7017                 if (context->internal->_debug_stderr) {
7018                         dbf = x_stderr;
7019                         x_setbuf(x_stderr, NULL);
7020                 }
7021
7022                 /* Here we would open the smb.conf file if needed ... */
7023
7024                 in_client = True; /* FIXME, make a param */
7025
7026                 home = getenv("HOME");
7027                 if (home) {
7028                         char *conf = NULL;
7029                         if (asprintf(&conf, "%s/.smb/smb.conf", home) > 0) {
7030                                 if (lp_load(conf, True, False, False, True)) {
7031                                         conf_loaded = True;
7032                                 } else {
7033                                         DEBUG(5, ("Could not load config file: %s\n",
7034                                                 conf));
7035                                 }
7036                                 SAFE_FREE(conf);
7037                         }
7038                 }
7039
7040                 if (!conf_loaded) {
7041                         /*
7042                          * Well, if that failed, try the get_dyn_CONFIGFILE
7043                          * Which points to the standard locn, and if that
7044                          * fails, silently ignore it and use the internal
7045                          * defaults ...
7046                          */
7047
7048                         if (!lp_load(get_dyn_CONFIGFILE(), True, False, False, False)) {
7049                                 DEBUG(5, ("Could not load config file: %s\n",
7050                                           get_dyn_CONFIGFILE()));
7051                         } else if (home) {
7052                                 char *conf;
7053                                 /*
7054                                  * We loaded the global config file.  Now lets
7055                                  * load user-specific modifications to the
7056                                  * global config.
7057                                  */
7058                                 if (asprintf(&conf,
7059                                                 "%s/.smb/smb.conf.append",
7060                                                 home) > 0) {
7061                                         if (!lp_load(conf, True, False, False, False)) {
7062                                                 DEBUG(10,
7063                                                 ("Could not append config file: "
7064                                                 "%s\n",
7065                                                 conf));
7066                                         }
7067                                         SAFE_FREE(conf);
7068                                 }
7069                         }
7070                 }
7071
7072                 load_interfaces();  /* Load the list of interfaces ... */
7073
7074                 reopen_logs();  /* Get logging working ... */
7075
7076                 /*
7077                  * Block SIGPIPE (from lib/util_sock.c: write())
7078                  * It is not needed and should not stop execution
7079                  */
7080                 BlockSignals(True, SIGPIPE);
7081
7082                 /* Done with one-time initialisation */
7083                 smbc_initialized = 1;
7084
7085                 TALLOC_FREE(frame);
7086         }
7087
7088         if (!context->user) {
7089                 /*
7090                  * FIXME: Is this the best way to get the user info?
7091                  */
7092                 user = getenv("USER");
7093                 /* walk around as "guest" if no username can be found */
7094                 if (!user) context->user = SMB_STRDUP("guest");
7095                 else context->user = SMB_STRDUP(user);
7096         }
7097
7098         if (!context->netbios_name) {
7099                 /*
7100                  * We try to get our netbios name from the config. If that
7101                  * fails we fall back on constructing our netbios name from
7102                  * our hostname etc
7103                  */
7104                 if (global_myname()) {
7105                         context->netbios_name = SMB_STRDUP(global_myname());
7106                 }
7107                 else {
7108                         /*
7109                          * Hmmm, I want to get hostname as well, but I am too
7110                          * lazy for the moment
7111                          */
7112                         pid = sys_getpid();
7113                         context->netbios_name = (char *)SMB_MALLOC(17);
7114                         if (!context->netbios_name) {
7115                                 errno = ENOMEM;
7116                                 return NULL;
7117                         }
7118                         slprintf(context->netbios_name, 16,
7119                                  "smbc%s%d", context->user, pid);
7120                 }
7121         }
7122
7123         DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
7124
7125         if (!context->workgroup) {
7126                 if (lp_workgroup()) {
7127                         context->workgroup = SMB_STRDUP(lp_workgroup());
7128                 }
7129                 else {
7130                         /* TODO: Think about a decent default workgroup */
7131                         context->workgroup = SMB_STRDUP("samba");
7132                 }
7133         }
7134
7135         DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
7136
7137         /* shortest timeout is 1 second */
7138         if (context->timeout > 0 && context->timeout < 1000)
7139                 context->timeout = 1000;
7140
7141         /*
7142          * FIXME: Should we check the function pointers here?
7143          */
7144
7145         context->internal->_initialized = True;
7146
7147         return context;
7148 }
7149
7150
7151 /* Return the verion of samba, and thus libsmbclient */
7152 const char *
7153 smbc_version(void)
7154 {
7155         return samba_version_string();
7156 }