r22914: - Fixes bug 4599. A missing <code>if</code> statement forced subseqeuent
[ira/wip.git] / source3 / libsmb / libsmbclient.c
1 /* 
2    Unix SMB/Netbios implementation.
3    SMB client library implementation
4    Copyright (C) Andrew Tridgell 1998
5    Copyright (C) Richard Sharpe 2000, 2002
6    Copyright (C) John Terpstra 2000
7    Copyright (C) Tom Jansen (Ninja ISD) 2002 
8    Copyright (C) Derrell Lipman 2003, 2004
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26
27 #include "include/libsmb_internal.h"
28
29 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  *
137  * Convert strings of %xx to their single character equivalent.  Each 'x' must
138  * be a valid hexadecimal digit, or that % sequence is left undecoded.
139  *
140  * dest may, but need not be, the same pointer as src.
141  *
142  * Returns the number of % sequences which could not be converted due to lack
143  * of two following hexadecimal digits.
144  */
145 int
146 smbc_urldecode(char *dest, char * src, size_t max_dest_len)
147 {
148         int old_length = strlen(src);
149         int i = 0;
150         int err_count = 0;
151         pstring temp;
152         char * p;
153
154         if ( old_length == 0 ) {
155                 return 0;
156         }
157
158         p = temp;
159         while ( i < old_length ) {
160                 unsigned char character = src[ i++ ];
161
162                 if (character == '%') {
163                         int a = i+1 < old_length ? hex2int( src[i] ) : -1;
164                         int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;
165
166                         /* Replace valid sequence */
167                         if (a != -1 && b != -1) {
168
169                                 /* Replace valid %xx sequence with %dd */
170                                 character = (a * 16) + b;
171
172                                 if (character == '\0') {
173                                         break; /* Stop at %00 */
174                                 }
175
176                                 i += 2;
177                         } else {
178
179                                 err_count++;
180                         }
181                 }
182
183                 *p++ = character;
184         }
185
186         *p = '\0';
187
188         strncpy(dest, temp, max_dest_len - 1);
189         dest[max_dest_len - 1] = '\0';
190
191         return err_count;
192 }
193
194 /*
195  * smbc_urlencode()
196  *
197  * Convert any characters not specifically allowed in a URL into their %xx
198  * equivalent.
199  *
200  * Returns the remaining buffer length.
201  */
202 int
203 smbc_urlencode(char * dest, char * src, int max_dest_len)
204 {
205         char hex[] = "0123456789ABCDEF";
206
207         for (; *src != '\0' && max_dest_len >= 3; src++) {
208
209                 if ((*src < '0' &&
210                      *src != '-' &&
211                      *src != '.') ||
212                     (*src > '9' &&
213                      *src < 'A') ||
214                     (*src > 'Z' &&
215                      *src < 'a' &&
216                      *src != '_') ||
217                     (*src > 'z')) {
218                         *dest++ = '%';
219                         *dest++ = hex[(*src >> 4) & 0x0f];
220                         *dest++ = hex[*src & 0x0f];
221                         max_dest_len -= 3;
222                 } else {
223                         *dest++ = *src;
224                         max_dest_len--;
225                 }
226         }
227
228         *dest++ = '\0';
229         max_dest_len--;
230         
231         return max_dest_len;
232 }
233
234 /*
235  * Function to parse a path and turn it into components
236  *
237  * The general format of an SMB URI is explain in Christopher Hertel's CIFS
238  * book, at http://ubiqx.org/cifs/Appendix-D.html.  We accept a subset of the
239  * general format ("smb:" only; we do not look for "cifs:").
240  *
241  *
242  * We accept:
243  *  smb://[[[domain;]user[:password]@]server[/share[/path[/file]]]][?options]
244  *
245  * Meaning of URLs:
246  *
247  * smb://           Show all workgroups.
248  *
249  *                  The method of locating the list of workgroups varies
250  *                  depending upon the setting of the context variable
251  *                  context->options.browse_max_lmb_count.  This value
252  *                  determine the maximum number of local master browsers to
253  *                  query for the list of workgroups.  In order to ensure that
254  *                  a complete list of workgroups is obtained, all master
255  *                  browsers must be queried, but if there are many
256  *                  workgroups, the time spent querying can begin to add up.
257  *                  For small networks (not many workgroups), it is suggested
258  *                  that this variable be set to 0, indicating query all local
259  *                  master browsers.  When the network has many workgroups, a
260  *                  reasonable setting for this variable might be around 3.
261  *
262  * smb://name/      if name<1D> or name<1B> exists, list servers in
263  *                  workgroup, else, if name<20> exists, list all shares
264  *                  for server ...
265  *
266  * If "options" are provided, this function returns the entire option list as a
267  * string, for later parsing by the caller.  Note that currently, no options
268  * are supported.
269  */
270
271 static const char *smbc_prefix = "smb:";
272
273 static int
274 smbc_parse_path(SMBCCTX *context,
275                 const char *fname,
276                 char *workgroup, int workgroup_len,
277                 char *server, int server_len,
278                 char *share, int share_len,
279                 char *path, int path_len,
280                 char *user, int user_len,
281                 char *password, int password_len,
282                 char *options, int options_len)
283 {
284         static pstring s;
285         pstring userinfo;
286         const char *p;
287         char *q, *r;
288         int len;
289
290         server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
291
292         /*
293          * Assume we wont find an authentication domain to parse, so default
294          * to the workgroup in the provided context.
295          */
296         if (workgroup != NULL) {
297                 strncpy(workgroup, context->workgroup, workgroup_len - 1);
298                 workgroup[workgroup_len - 1] = '\0';
299         }
300
301         if (options != NULL && options_len > 0) {
302                 options[0] = (char)0;
303         }
304         pstrcpy(s, fname);
305
306         /* see if it has the right prefix */
307         len = strlen(smbc_prefix);
308         if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
309                 return -1; /* What about no smb: ? */
310         }
311
312         p = s + len;
313
314         /* Watch the test below, we are testing to see if we should exit */
315
316         if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
317
318                 DEBUG(1, ("Invalid path (does not begin with smb://"));
319                 return -1;
320
321         }
322
323         p += 2;  /* Skip the double slash */
324
325         /* See if any options were specified */
326         if ((q = strrchr(p, '?')) != NULL ) {
327                 /* There are options.  Null terminate here and point to them */
328                 *q++ = '\0';
329                 
330                 DEBUG(4, ("Found options '%s'", q));
331
332                 /* Copy the options */
333                 if (options != NULL && options_len > 0) {
334                         safe_strcpy(options, q, options_len - 1);
335                 }
336         }
337
338         if (*p == (char)0)
339             goto decoding;
340
341         if (*p == '/') {
342                 int wl = strlen(context->workgroup);
343
344                 if (wl > 16) {
345                         wl = 16;
346                 }
347
348                 strncpy(server, context->workgroup, wl);
349                 server[wl] = '\0';
350                 return 0;
351         }
352
353         /*
354          * ok, its for us. Now parse out the server, share etc. 
355          *
356          * However, we want to parse out [[domain;]user[:password]@] if it
357          * exists ...
358          */
359
360         /* check that '@' occurs before '/', if '/' exists at all */
361         q = strchr_m(p, '@');
362         r = strchr_m(p, '/');
363         if (q && (!r || q < r)) {
364                 pstring username, passwd, domain;
365                 const char *u = userinfo;
366
367                 next_token_no_ltrim(&p, userinfo, "@", sizeof(fstring));
368
369                 username[0] = passwd[0] = domain[0] = 0;
370
371                 if (strchr_m(u, ';')) {
372       
373                         next_token_no_ltrim(&u, domain, ";", sizeof(fstring));
374
375                 }
376
377                 if (strchr_m(u, ':')) {
378
379                         next_token_no_ltrim(&u, username, ":", sizeof(fstring));
380
381                         pstrcpy(passwd, u);
382
383                 }
384                 else {
385
386                         pstrcpy(username, u);
387
388                 }
389
390                 if (domain[0] && workgroup) {
391                         strncpy(workgroup, domain, workgroup_len - 1);
392                         workgroup[workgroup_len - 1] = '\0';
393                 }
394
395                 if (username[0]) {
396                         strncpy(user, username, user_len - 1);
397                         user[user_len - 1] = '\0';
398                 }
399
400                 if (passwd[0]) {
401                         strncpy(password, passwd, password_len - 1);
402                         password[password_len - 1] = '\0';
403                 }
404
405         }
406
407         if (!next_token(&p, server, "/", sizeof(fstring))) {
408
409                 return -1;
410
411         }
412
413         if (*p == (char)0) goto decoding;  /* That's it ... */
414   
415         if (!next_token(&p, share, "/", sizeof(fstring))) {
416
417                 return -1;
418
419         }
420
421         /*
422          * Prepend a leading slash if there's a file path, as required by
423          * NetApp filers.
424          */
425         *path = '\0';
426         if (*p != '\0') {
427                 *path = '/';
428                 safe_strcpy(path + 1, p, path_len - 2);
429         }
430
431         all_string_sub(path, "/", "\\", 0);
432
433  decoding:
434         (void) smbc_urldecode(path, path, path_len);
435         (void) smbc_urldecode(server, server, server_len);
436         (void) smbc_urldecode(share, share, share_len);
437         (void) smbc_urldecode(user, user, user_len);
438         (void) smbc_urldecode(password, password, password_len);
439
440         return 0;
441 }
442
443 /*
444  * Verify that the options specified in a URL are valid
445  */
446 static int
447 smbc_check_options(char *server,
448                    char *share,
449                    char *path,
450                    char *options)
451 {
452         DEBUG(4, ("smbc_check_options(): server='%s' share='%s' "
453                   "path='%s' options='%s'\n",
454                   server, share, path, options));
455
456         /* No options at all is always ok */
457         if (! *options) return 0;
458
459         /* Currently, we don't support any options. */
460         return -1;
461 }
462
463 /*
464  * Convert an SMB error into a UNIX error ...
465  */
466 static int
467 smbc_errno(SMBCCTX *context,
468            struct cli_state *c)
469 {
470         int ret = cli_errno(c);
471         
472         if (cli_is_dos_error(c)) {
473                 uint8 eclass;
474                 uint32 ecode;
475
476                 cli_dos_error(c, &eclass, &ecode);
477                 
478                 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n", 
479                          (int)eclass, (int)ecode, (int)ecode, ret));
480         } else {
481                 NTSTATUS status;
482
483                 status = cli_nt_error(c);
484
485                 DEBUG(3,("smbc errno %s -> %d\n",
486                          nt_errstr(status), ret));
487         }
488
489         return ret;
490 }
491
492 /* 
493  * Check a server for being alive and well.
494  * returns 0 if the server is in shape. Returns 1 on error 
495  * 
496  * Also useable outside libsmbclient to enable external cache
497  * to do some checks too.
498  */
499 static int
500 smbc_check_server(SMBCCTX * context,
501                   SMBCSRV * server) 
502 {
503         size_t size;
504         struct sockaddr addr;
505
506         /*
507          * Although the use of port 139 is not a guarantee that we're using
508          * netbios, we assume so.  We don't want to send a keepalive packet if
509          * not netbios because it's not valid, and Vista, at least,
510          * disconnects the client on such a request.
511          */
512         if (server->cli->port == 139) {
513                 /* Assuming netbios.  Send a keepalive packet */
514                 if ( send_keepalive(server->cli->fd) == False ) {
515                         return 1;
516                 }
517         } else {
518                 /*
519                  * Assuming not netbios.  Try a different method to detect if
520                  * the connection is still alive.
521                  */
522                 size = sizeof(addr);
523                 if (getpeername(server->cli->fd, &addr, &size) == -1) {
524                         return 1;
525                 }
526         }
527
528         /* connection is ok */
529         return 0;
530 }
531
532 /* 
533  * Remove a server from the cached server list it's unused.
534  * On success, 0 is returned. 1 is returned if the server could not be removed.
535  * 
536  * Also useable outside libsmbclient
537  */
538 int
539 smbc_remove_unused_server(SMBCCTX * context,
540                           SMBCSRV * srv)
541 {
542         SMBCFILE * file;
543
544         /* are we being fooled ? */
545         if (!context || !context->internal ||
546             !context->internal->_initialized || !srv) return 1;
547
548         
549         /* Check all open files/directories for a relation with this server */
550         for (file = context->internal->_files; file; file=file->next) {
551                 if (file->srv == srv) {
552                         /* Still used */
553                         DEBUG(3, ("smbc_remove_usused_server: "
554                                   "%p still used by %p.\n", 
555                                   srv, file));
556                         return 1;
557                 }
558         }
559
560         DLIST_REMOVE(context->internal->_servers, srv);
561
562         cli_shutdown(srv->cli);
563         srv->cli = NULL;
564
565         DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
566
567         context->callbacks.remove_cached_srv_fn(context, srv);
568
569         SAFE_FREE(srv);
570         
571         return 0;
572 }
573
574 static SMBCSRV *
575 find_server(SMBCCTX *context,
576             const char *server,
577             const char *share,
578             fstring workgroup,
579             fstring username,
580             fstring password)
581 {
582         SMBCSRV *srv;
583         int auth_called = 0;
584         
585  check_server_cache:
586
587         srv = context->callbacks.get_cached_srv_fn(context, server, share, 
588                                                    workgroup, username);
589
590         if (!auth_called && !srv && (!username[0] || !password[0])) {
591                 if (context->internal->_auth_fn_with_context != NULL) {
592                          context->internal->_auth_fn_with_context(
593                                 context,
594                                 server, share,
595                                 workgroup, sizeof(fstring),
596                                 username, sizeof(fstring),
597                                 password, sizeof(fstring));
598                 } else {
599                         context->callbacks.auth_fn(
600                                 server, share,
601                                 workgroup, sizeof(fstring),
602                                 username, sizeof(fstring),
603                                 password, sizeof(fstring));
604                 }
605
606                 /*
607                  * However, smbc_auth_fn may have picked up info relating to
608                  * an existing connection, so try for an existing connection
609                  * again ...
610                  */
611                 auth_called = 1;
612                 goto check_server_cache;
613                 
614         }
615         
616         if (srv) {
617                 if (context->callbacks.check_server_fn(context, srv)) {
618                         /*
619                          * This server is no good anymore 
620                          * Try to remove it and check for more possible
621                          * servers in the cache
622                          */
623                         if (context->callbacks.remove_unused_server_fn(context,
624                                                                        srv)) { 
625                                 /*
626                                  * We could not remove the server completely,
627                                  * remove it from the cache so we will not get
628                                  * it again. It will be removed when the last
629                                  * file/dir is closed.
630                                  */
631                                 context->callbacks.remove_cached_srv_fn(context,
632                                                                         srv);
633                         }
634                         
635                         /*
636                          * Maybe there are more cached connections to this
637                          * server
638                          */
639                         goto check_server_cache; 
640                 }
641
642                 return srv;
643         }
644
645         return NULL;
646 }
647
648 /*
649  * Connect to a server, possibly on an existing connection
650  *
651  * Here, what we want to do is: If the server and username
652  * match an existing connection, reuse that, otherwise, establish a 
653  * new connection.
654  *
655  * If we have to create a new connection, call the auth_fn to get the
656  * info we need, unless the username and password were passed in.
657  */
658
659 static SMBCSRV *
660 smbc_server(SMBCCTX *context,
661             BOOL connect_if_not_found,
662             const char *server,
663             const char *share, 
664             fstring workgroup,
665             fstring username, 
666             fstring password)
667 {
668         SMBCSRV *srv=NULL;
669         struct cli_state *c;
670         struct nmb_name called, calling;
671         const char *server_n = server;
672         pstring ipenv;
673         struct in_addr ip;
674         int tried_reverse = 0;
675         int port_try_first;
676         int port_try_next;
677         const char *username_used;
678   
679         zero_ip(&ip);
680         ZERO_STRUCT(c);
681
682         if (server[0] == 0) {
683                 errno = EPERM;
684                 return NULL;
685         }
686
687         /* Look for a cached connection */
688         srv = find_server(context, server, share,
689                           workgroup, username, password);
690         
691         /*
692          * If we found a connection and we're only allowed one share per
693          * server...
694          */
695         if (srv && *share != '\0' && context->options.one_share_per_server) {
696
697                 /*
698                  * ... then if there's no current connection to the share,
699                  * connect to it.  find_server(), or rather the function
700                  * pointed to by context->callbacks.get_cached_srv_fn which
701                  * was called by find_server(), will have issued a tree
702                  * disconnect if the requested share is not the same as the
703                  * one that was already connected.
704                  */
705                 if (srv->cli->cnum == (uint16) -1) {
706                         /* Ensure we have accurate auth info */
707                         if (context->internal->_auth_fn_with_context != NULL) {
708                                 context->internal->_auth_fn_with_context(
709                                         context,
710                                         server, share,
711                                         workgroup, sizeof(fstring),
712                                         username, sizeof(fstring),
713                                         password, sizeof(fstring));
714                         } else {
715                                 context->callbacks.auth_fn(
716                                         server, share,
717                                         workgroup, sizeof(fstring),
718                                         username, sizeof(fstring),
719                                         password, sizeof(fstring));
720                         }
721
722                         if (! cli_send_tconX(srv->cli, share, "?????",
723                                              password, strlen(password)+1)) {
724                         
725                                 errno = smbc_errno(context, srv->cli);
726                                 cli_shutdown(srv->cli);
727                                 srv->cli = NULL;
728                                 context->callbacks.remove_cached_srv_fn(context,
729                                                                         srv);
730                                 srv = NULL;
731                         }
732
733                         /*
734                          * Regenerate the dev value since it's based on both
735                          * server and share
736                          */
737                         if (srv) {
738                                 srv->dev = (dev_t)(str_checksum(server) ^
739                                                    str_checksum(share));
740                         }
741                 }
742         }
743         
744         /* If we have a connection... */
745         if (srv) {
746
747                 /* ... then we're done here.  Give 'em what they came for. */
748                 return srv;
749         }
750
751         /* If we're not asked to connect when a connection doesn't exist... */
752         if (! connect_if_not_found) {
753                 /* ... then we're done here. */
754                 return NULL;
755         }
756
757         make_nmb_name(&calling, context->netbios_name, 0x0);
758         make_nmb_name(&called , server, 0x20);
759
760         DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
761   
762         DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
763
764  again:
765         slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
766
767         zero_ip(&ip);
768
769         /* have to open a new connection */
770         if ((c = cli_initialise()) == NULL) {
771                 errno = ENOMEM;
772                 return NULL;
773         }
774
775         if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
776                 c->use_kerberos = True;
777         }
778         if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
779                 c->fallback_after_kerberos = True;
780         }
781
782         c->timeout = context->timeout;
783
784         /*
785          * Force use of port 139 for first try if share is $IPC, empty, or
786          * null, so browse lists can work
787          */
788         if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
789                 port_try_first = 139;
790                 port_try_next = 445;
791         } else {
792                 port_try_first = 445;
793                 port_try_next = 139;
794         }
795
796         c->port = port_try_first;
797
798         if (!cli_connect(c, server_n, &ip)) {
799
800                 /* First connection attempt failed.  Try alternate port. */
801                 c->port = port_try_next;
802
803                 if (!cli_connect(c, server_n, &ip)) {
804                         cli_shutdown(c);
805                         errno = ETIMEDOUT;
806                         return NULL;
807                 }
808         }
809
810         if (!cli_session_request(c, &calling, &called)) {
811                 cli_shutdown(c);
812                 if (strcmp(called.name, "*SMBSERVER")) {
813                         make_nmb_name(&called , "*SMBSERVER", 0x20);
814                         goto again;
815                 } else {  /* Try one more time, but ensure we don't loop */
816
817                         /* Only try this if server is an IP address ... */
818
819                         if (is_ipaddress(server) && !tried_reverse) {
820                                 fstring remote_name;
821                                 struct in_addr rem_ip;
822
823                                 if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
824                                         DEBUG(4, ("Could not convert IP address "
825                                                 "%s to struct in_addr\n", server));
826                                         errno = ETIMEDOUT;
827                                         return NULL;
828                                 }
829
830                                 tried_reverse++; /* Yuck */
831
832                                 if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
833                                         make_nmb_name(&called, remote_name, 0x20);
834                                         goto again;
835                                 }
836                         }
837                 }
838                 errno = ETIMEDOUT;
839                 return NULL;
840         }
841   
842         DEBUG(4,(" session request ok\n"));
843   
844         if (!cli_negprot(c)) {
845                 cli_shutdown(c);
846                 errno = ETIMEDOUT;
847                 return NULL;
848         }
849
850         username_used = username;
851
852         if (!NT_STATUS_IS_OK(cli_session_setup(c, username_used, 
853                                                password, strlen(password),
854                                                password, strlen(password),
855                                                workgroup))) {
856                 
857                 /* Failed.  Try an anonymous login, if allowed by flags. */
858                 username_used = "";
859
860                 if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
861                      !NT_STATUS_IS_OK(cli_session_setup(c, username_used,
862                                                         password, 1,
863                                                         password, 0,
864                                                         workgroup))) {
865
866                         cli_shutdown(c);
867                         errno = EPERM;
868                         return NULL;
869                 }
870         }
871
872         DEBUG(4,(" session setup ok\n"));
873
874         if (!cli_send_tconX(c, share, "?????",
875                             password, strlen(password)+1)) {
876                 errno = smbc_errno(context, c);
877                 cli_shutdown(c);
878                 return NULL;
879         }
880   
881         DEBUG(4,(" tconx ok\n"));
882   
883         /*
884          * Ok, we have got a nice connection
885          * Let's allocate a server structure.
886          */
887
888         srv = SMB_MALLOC_P(SMBCSRV);
889         if (!srv) {
890                 errno = ENOMEM;
891                 goto failed;
892         }
893
894         ZERO_STRUCTP(srv);
895         srv->cli = c;
896         srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
897         srv->no_pathinfo = False;
898         srv->no_pathinfo2 = False;
899         srv->no_nt_session = False;
900
901         /* now add it to the cache (internal or external)  */
902         /* Let the cache function set errno if it wants to */
903         errno = 0;
904         if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
905                 int saved_errno = errno;
906                 DEBUG(3, (" Failed to add server to cache\n"));
907                 errno = saved_errno;
908                 if (errno == 0) {
909                         errno = ENOMEM;
910                 }
911                 goto failed;
912         }
913         
914         DEBUG(2, ("Server connect ok: //%s/%s: %p\n", 
915                   server, share, srv));
916
917         DLIST_ADD(context->internal->_servers, srv);
918         return srv;
919
920  failed:
921         cli_shutdown(c);
922         if (!srv) {
923                 return NULL;
924         }
925   
926         SAFE_FREE(srv);
927         return NULL;
928 }
929
930 /*
931  * Connect to a server for getting/setting attributes, possibly on an existing
932  * connection.  This works similarly to smbc_server().
933  */
934 static SMBCSRV *
935 smbc_attr_server(SMBCCTX *context,
936                  const char *server,
937                  const char *share, 
938                  fstring workgroup,
939                  fstring username,
940                  fstring password,
941                  POLICY_HND *pol)
942 {
943         int flags;
944         struct in_addr ip;
945         struct cli_state *ipc_cli;
946         struct rpc_pipe_client *pipe_hnd;
947         NTSTATUS nt_status;
948         SMBCSRV *ipc_srv=NULL;
949
950         /*
951          * See if we've already created this special connection.  Reference
952          * our "special" share name '*IPC$', which is an impossible real share
953          * name due to the leading asterisk.
954          */
955         ipc_srv = find_server(context, server, "*IPC$",
956                               workgroup, username, password);
957         if (!ipc_srv) {
958
959                 /* We didn't find a cached connection.  Get the password */
960                 if (*password == '\0') {
961                         /* ... then retrieve it now. */
962                         if (context->internal->_auth_fn_with_context != NULL) {
963                                 context->internal->_auth_fn_with_context(
964                                         context,
965                                         server, share,
966                                         workgroup, sizeof(fstring),
967                                         username, sizeof(fstring),
968                                         password, sizeof(fstring));
969                         } else {
970                                 context->callbacks.auth_fn(
971                                         server, share,
972                                         workgroup, sizeof(fstring),
973                                         username, sizeof(fstring),
974                                         password, sizeof(fstring));
975                         }
976                 }
977         
978                 flags = 0;
979                 if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
980                         flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
981                 }
982
983                 zero_ip(&ip);
984                 nt_status = cli_full_connection(&ipc_cli,
985                                                 global_myname(), server, 
986                                                 &ip, 0, "IPC$", "?????",  
987                                                 username, workgroup,
988                                                 password, flags,
989                                                 Undefined, NULL);
990                 if (! NT_STATUS_IS_OK(nt_status)) {
991                         DEBUG(1,("cli_full_connection failed! (%s)\n",
992                                  nt_errstr(nt_status)));
993                         errno = ENOTSUP;
994                         return NULL;
995                 }
996
997                 ipc_srv = SMB_MALLOC_P(SMBCSRV);
998                 if (!ipc_srv) {
999                         errno = ENOMEM;
1000                         cli_shutdown(ipc_cli);
1001                         return NULL;
1002                 }
1003
1004                 ZERO_STRUCTP(ipc_srv);
1005                 ipc_srv->cli = ipc_cli;
1006
1007                 if (pol) {
1008                         pipe_hnd = cli_rpc_pipe_open_noauth(ipc_srv->cli,
1009                                                             PI_LSARPC,
1010                                                             &nt_status);
1011                         if (!pipe_hnd) {
1012                                 DEBUG(1, ("cli_nt_session_open fail!\n"));
1013                                 errno = ENOTSUP;
1014                                 cli_shutdown(ipc_srv->cli);
1015                                 free(ipc_srv);
1016                                 return NULL;
1017                         }
1018
1019                         /*
1020                          * Some systems don't support
1021                          * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
1022                          * so we might as well do it too.
1023                          */
1024         
1025                         nt_status = rpccli_lsa_open_policy(
1026                                 pipe_hnd,
1027                                 ipc_srv->cli->mem_ctx,
1028                                 True, 
1029                                 GENERIC_EXECUTE_ACCESS,
1030                                 pol);
1031         
1032                         if (!NT_STATUS_IS_OK(nt_status)) {
1033                                 errno = smbc_errno(context, ipc_srv->cli);
1034                                 cli_shutdown(ipc_srv->cli);
1035                                 return NULL;
1036                         }
1037                 }
1038
1039                 /* now add it to the cache (internal or external) */
1040
1041                 errno = 0;      /* let cache function set errno if it likes */
1042                 if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
1043                                                          server,
1044                                                          "*IPC$",
1045                                                          workgroup,
1046                                                          username)) {
1047                         DEBUG(3, (" Failed to add server to cache\n"));
1048                         if (errno == 0) {
1049                                 errno = ENOMEM;
1050                         }
1051                         cli_shutdown(ipc_srv->cli);
1052                         free(ipc_srv);
1053                         return NULL;
1054                 }
1055
1056                 DLIST_ADD(context->internal->_servers, ipc_srv);
1057         }
1058
1059         return ipc_srv;
1060 }
1061
1062 /*
1063  * Routine to open() a file ...
1064  */
1065
1066 static SMBCFILE *
1067 smbc_open_ctx(SMBCCTX *context,
1068               const char *fname,
1069               int flags,
1070               mode_t mode)
1071 {
1072         fstring server, share, user, password, workgroup;
1073         pstring path;
1074         pstring targetpath;
1075         struct cli_state *targetcli;
1076         SMBCSRV *srv   = NULL;
1077         SMBCFILE *file = NULL;
1078         int fd;
1079
1080         if (!context || !context->internal ||
1081             !context->internal->_initialized) {
1082
1083                 errno = EINVAL;  /* Best I can think of ... */
1084                 return NULL;
1085
1086         }
1087
1088         if (!fname) {
1089
1090                 errno = EINVAL;
1091                 return NULL;
1092
1093         }
1094
1095         if (smbc_parse_path(context, fname,
1096                             workgroup, sizeof(workgroup),
1097                             server, sizeof(server),
1098                             share, sizeof(share),
1099                             path, sizeof(path),
1100                             user, sizeof(user),
1101                             password, sizeof(password),
1102                             NULL, 0)) {
1103                 errno = EINVAL;
1104                 return NULL;
1105         }
1106
1107         if (user[0] == (char)0) fstrcpy(user, context->user);
1108
1109         srv = smbc_server(context, True,
1110                           server, share, workgroup, user, password);
1111
1112         if (!srv) {
1113
1114                 if (errno == EPERM) errno = EACCES;
1115                 return NULL;  /* smbc_server sets errno */
1116     
1117         }
1118
1119         /* Hmmm, the test for a directory is suspect here ... FIXME */
1120
1121         if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
1122     
1123                 fd = -1;
1124
1125         }
1126         else {
1127           
1128                 file = SMB_MALLOC_P(SMBCFILE);
1129
1130                 if (!file) {
1131
1132                         errno = ENOMEM;
1133                         return NULL;
1134
1135                 }
1136
1137                 ZERO_STRUCTP(file);
1138
1139                 /*d_printf(">>>open: resolving %s\n", path);*/
1140                 if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1141                 {
1142                         d_printf("Could not resolve %s\n", path);
1143                         SAFE_FREE(file);
1144                         return NULL;
1145                 }
1146                 /*d_printf(">>>open: resolved %s as %s\n", path, targetpath);*/
1147                 
1148                 if ((fd = cli_open(targetcli, targetpath, flags,
1149                                    context->internal->_share_mode)) < 0) {
1150
1151                         /* Handle the error ... */
1152
1153                         SAFE_FREE(file);
1154                         errno = smbc_errno(context, targetcli);
1155                         return NULL;
1156
1157                 }
1158
1159                 /* Fill in file struct */
1160
1161                 file->cli_fd  = fd;
1162                 file->fname   = SMB_STRDUP(fname);
1163                 file->srv     = srv;
1164                 file->offset  = 0;
1165                 file->file    = True;
1166
1167                 DLIST_ADD(context->internal->_files, file);
1168
1169                 /*
1170                  * If the file was opened in O_APPEND mode, all write
1171                  * operations should be appended to the file.  To do that,
1172                  * though, using this protocol, would require a getattrE()
1173                  * call for each and every write, to determine where the end
1174                  * of the file is. (There does not appear to be an append flag
1175                  * in the protocol.)  Rather than add all of that overhead of
1176                  * retrieving the current end-of-file offset prior to each
1177                  * write operation, we'll assume that most append operations
1178                  * will continuously write, so we'll just set the offset to
1179                  * the end of the file now and hope that's adequate.
1180                  *
1181                  * Note to self: If this proves inadequate, and O_APPEND
1182                  * should, in some cases, be forced for each write, add a
1183                  * field in the context options structure, for
1184                  * "strict_append_mode" which would select between the current
1185                  * behavior (if FALSE) or issuing a getattrE() prior to each
1186                  * write and forcing the write to the end of the file (if
1187                  * TRUE).  Adding that capability will likely require adding
1188                  * an "append" flag into the _SMBCFILE structure to track
1189                  * whether a file was opened in O_APPEND mode.  -- djl
1190                  */
1191                 if (flags & O_APPEND) {
1192                         if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
1193                                 (void) smbc_close_ctx(context, file);
1194                                 errno = ENXIO;
1195                                 return NULL;
1196                         }
1197                 }
1198
1199                 return file;
1200
1201         }
1202
1203         /* Check if opendir needed ... */
1204
1205         if (fd == -1) {
1206                 int eno = 0;
1207
1208                 eno = smbc_errno(context, srv->cli);
1209                 file = context->opendir(context, fname);
1210                 if (!file) errno = eno;
1211                 return file;
1212
1213         }
1214
1215         errno = EINVAL; /* FIXME, correct errno ? */
1216         return NULL;
1217
1218 }
1219
1220 /*
1221  * Routine to create a file 
1222  */
1223
1224 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
1225
1226 static SMBCFILE *
1227 smbc_creat_ctx(SMBCCTX *context,
1228                const char *path,
1229                mode_t mode)
1230 {
1231
1232         if (!context || !context->internal ||
1233             !context->internal->_initialized) {
1234
1235                 errno = EINVAL;
1236                 return NULL;
1237
1238         }
1239
1240         return smbc_open_ctx(context, path, creat_bits, mode);
1241 }
1242
1243 /*
1244  * Routine to read() a file ...
1245  */
1246
1247 static ssize_t
1248 smbc_read_ctx(SMBCCTX *context,
1249               SMBCFILE *file,
1250               void *buf,
1251               size_t count)
1252 {
1253         int ret;
1254         fstring server, share, user, password;
1255         pstring path, targetpath;
1256         struct cli_state *targetcli;
1257
1258         /*
1259          * offset:
1260          *
1261          * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
1262          * appears to pass file->offset (which is type off_t) differently than
1263          * a local variable of type off_t.  Using local variable "offset" in
1264          * the call to cli_read() instead of file->offset fixes a problem
1265          * retrieving data at an offset greater than 4GB.
1266          */
1267         off_t offset;
1268
1269         if (!context || !context->internal ||
1270             !context->internal->_initialized) {
1271
1272                 errno = EINVAL;
1273                 return -1;
1274
1275         }
1276
1277         DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
1278
1279         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1280
1281                 errno = EBADF;
1282                 return -1;
1283
1284         }
1285
1286         offset = file->offset;
1287
1288         /* Check that the buffer exists ... */
1289
1290         if (buf == NULL) {
1291
1292                 errno = EINVAL;
1293                 return -1;
1294
1295         }
1296
1297         /*d_printf(">>>read: parsing %s\n", file->fname);*/
1298         if (smbc_parse_path(context, file->fname,
1299                             NULL, 0,
1300                             server, sizeof(server),
1301                             share, sizeof(share),
1302                             path, sizeof(path),
1303                             user, sizeof(user),
1304                             password, sizeof(password),
1305                             NULL, 0)) {
1306                 errno = EINVAL;
1307                 return -1;
1308         }
1309         
1310         /*d_printf(">>>read: resolving %s\n", path);*/
1311         if (!cli_resolve_path("", file->srv->cli, path,
1312                               &targetcli, targetpath))
1313         {
1314                 d_printf("Could not resolve %s\n", path);
1315                 return -1;
1316         }
1317         /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
1318         
1319         ret = cli_read(targetcli, file->cli_fd, (char *)buf, offset, count);
1320
1321         if (ret < 0) {
1322
1323                 errno = smbc_errno(context, targetcli);
1324                 return -1;
1325
1326         }
1327
1328         file->offset += ret;
1329
1330         DEBUG(4, ("  --> %d\n", ret));
1331
1332         return ret;  /* Success, ret bytes of data ... */
1333
1334 }
1335
1336 /*
1337  * Routine to write() a file ...
1338  */
1339
1340 static ssize_t
1341 smbc_write_ctx(SMBCCTX *context,
1342                SMBCFILE *file,
1343                void *buf,
1344                size_t count)
1345 {
1346         int ret;
1347         off_t offset;
1348         fstring server, share, user, password;
1349         pstring path, targetpath;
1350         struct cli_state *targetcli;
1351
1352         /* First check all pointers before dereferencing them */
1353         
1354         if (!context || !context->internal ||
1355             !context->internal->_initialized) {
1356
1357                 errno = EINVAL;
1358                 return -1;
1359
1360         }
1361
1362         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1363
1364                 errno = EBADF;
1365                 return -1;
1366     
1367         }
1368
1369         /* Check that the buffer exists ... */
1370
1371         if (buf == NULL) {
1372
1373                 errno = EINVAL;
1374                 return -1;
1375
1376         }
1377
1378         offset = file->offset; /* See "offset" comment in smbc_read_ctx() */
1379
1380         /*d_printf(">>>write: parsing %s\n", file->fname);*/
1381         if (smbc_parse_path(context, file->fname,
1382                             NULL, 0,
1383                             server, sizeof(server),
1384                             share, sizeof(share),
1385                             path, sizeof(path),
1386                             user, sizeof(user),
1387                             password, sizeof(password),
1388                             NULL, 0)) {
1389                 errno = EINVAL;
1390                 return -1;
1391         }
1392         
1393         /*d_printf(">>>write: resolving %s\n", path);*/
1394         if (!cli_resolve_path("", file->srv->cli, path,
1395                               &targetcli, targetpath))
1396         {
1397                 d_printf("Could not resolve %s\n", path);
1398                 return -1;
1399         }
1400         /*d_printf(">>>write: resolved path as %s\n", targetpath);*/
1401
1402
1403         ret = cli_write(targetcli, file->cli_fd, 0, (char *)buf, offset, count);
1404
1405         if (ret <= 0) {
1406
1407                 errno = smbc_errno(context, targetcli);
1408                 return -1;
1409
1410         }
1411
1412         file->offset += ret;
1413
1414         return ret;  /* Success, 0 bytes of data ... */
1415 }
1416  
1417 /*
1418  * Routine to close() a file ...
1419  */
1420
1421 static int
1422 smbc_close_ctx(SMBCCTX *context,
1423                SMBCFILE *file)
1424 {
1425         SMBCSRV *srv; 
1426         fstring server, share, user, password;
1427         pstring path, targetpath;
1428         struct cli_state *targetcli;
1429
1430         if (!context || !context->internal ||
1431             !context->internal->_initialized) {
1432
1433                 errno = EINVAL;
1434                 return -1;
1435
1436         }
1437
1438         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1439    
1440                 errno = EBADF;
1441                 return -1;
1442
1443         }
1444
1445         /* IS a dir ... */
1446         if (!file->file) {
1447                 
1448                 return context->closedir(context, file);
1449
1450         }
1451
1452         /*d_printf(">>>close: parsing %s\n", file->fname);*/
1453         if (smbc_parse_path(context, file->fname,
1454                             NULL, 0,
1455                             server, sizeof(server),
1456                             share, sizeof(share),
1457                             path, sizeof(path),
1458                             user, sizeof(user),
1459                             password, sizeof(password),
1460                             NULL, 0)) {
1461                 errno = EINVAL;
1462                 return -1;
1463         }
1464         
1465         /*d_printf(">>>close: resolving %s\n", path);*/
1466         if (!cli_resolve_path("", file->srv->cli, path,
1467                               &targetcli, targetpath))
1468         {
1469                 d_printf("Could not resolve %s\n", path);
1470                 return -1;
1471         }
1472         /*d_printf(">>>close: resolved path as %s\n", targetpath);*/
1473
1474         if (!cli_close(targetcli, file->cli_fd)) {
1475
1476                 DEBUG(3, ("cli_close failed on %s. purging server.\n", 
1477                           file->fname));
1478                 /* Deallocate slot and remove the server 
1479                  * from the server cache if unused */
1480                 errno = smbc_errno(context, targetcli);
1481                 srv = file->srv;
1482                 DLIST_REMOVE(context->internal->_files, file);
1483                 SAFE_FREE(file->fname);
1484                 SAFE_FREE(file);
1485                 context->callbacks.remove_unused_server_fn(context, srv);
1486
1487                 return -1;
1488
1489         }
1490
1491         DLIST_REMOVE(context->internal->_files, file);
1492         SAFE_FREE(file->fname);
1493         SAFE_FREE(file);
1494
1495         return 0;
1496 }
1497
1498 /*
1499  * Get info from an SMB server on a file. Use a qpathinfo call first
1500  * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
1501  */
1502 static BOOL
1503 smbc_getatr(SMBCCTX * context,
1504             SMBCSRV *srv,
1505             char *path, 
1506             uint16 *mode,
1507             SMB_OFF_T *size, 
1508             struct timespec *create_time_ts,
1509             struct timespec *access_time_ts,
1510             struct timespec *write_time_ts,
1511             struct timespec *change_time_ts,
1512             SMB_INO_T *ino)
1513 {
1514         pstring fixedpath;
1515         pstring targetpath;
1516         struct cli_state *targetcli;
1517         time_t write_time;
1518
1519         if (!context || !context->internal ||
1520             !context->internal->_initialized) {
1521  
1522                 errno = EINVAL;
1523                 return -1;
1524  
1525         }
1526
1527         /* path fixup for . and .. */
1528         if (strequal(path, ".") || strequal(path, ".."))
1529                 pstrcpy(fixedpath, "\\");
1530         else
1531         {
1532                 pstrcpy(fixedpath, path);
1533                 trim_string(fixedpath, NULL, "\\..");
1534                 trim_string(fixedpath, NULL, "\\.");
1535         }
1536         DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
1537   
1538         if (!cli_resolve_path( "", srv->cli, fixedpath, &targetcli, targetpath))
1539         {
1540                 d_printf("Couldn't resolve %s\n", path);
1541                 return False;
1542         }
1543         
1544         if (!srv->no_pathinfo2 &&
1545             cli_qpathinfo2(targetcli, targetpath,
1546                            create_time_ts,
1547                            access_time_ts,
1548                            write_time_ts,
1549                            change_time_ts,
1550                            size, mode, ino)) {
1551             return True;
1552         }
1553
1554         /* if this is NT then don't bother with the getatr */
1555         if (targetcli->capabilities & CAP_NT_SMBS) {
1556                 errno = EPERM;
1557                 return False;
1558         }
1559
1560         if (cli_getatr(targetcli, targetpath, mode, size, &write_time)) {
1561
1562                 struct timespec w_time_ts;
1563
1564                 w_time_ts = convert_time_t_to_timespec(write_time);
1565
1566                 if (write_time_ts != NULL) {
1567                         *write_time_ts = w_time_ts;
1568                 }
1569
1570                 if (create_time_ts != NULL) {
1571                         *create_time_ts = w_time_ts;
1572                 }
1573                 
1574                 if (access_time_ts != NULL) {
1575                         *access_time_ts = w_time_ts;
1576                 }
1577                 
1578                 if (change_time_ts != NULL) {
1579                         *change_time_ts = w_time_ts;
1580                 }
1581
1582                 srv->no_pathinfo2 = True;
1583                 return True;
1584         }
1585
1586         errno = EPERM;
1587         return False;
1588
1589 }
1590
1591 /*
1592  * Set file info on an SMB server.  Use setpathinfo call first.  If that
1593  * fails, use setattrE..
1594  *
1595  * Access and modification time parameters are always used and must be
1596  * provided.  Create time, if zero, will be determined from the actual create
1597  * time of the file.  If non-zero, the create time will be set as well.
1598  *
1599  * "mode" (attributes) parameter may be set to -1 if it is not to be set.
1600  */
1601 static BOOL
1602 smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path, 
1603             time_t create_time,
1604             time_t access_time,
1605             time_t write_time,
1606             time_t change_time,
1607             uint16 mode)
1608 {
1609         int fd;
1610         int ret;
1611
1612         /*
1613          * First, try setpathinfo (if qpathinfo succeeded), for it is the
1614          * modern function for "new code" to be using, and it works given a
1615          * filename rather than requiring that the file be opened to have its
1616          * attributes manipulated.
1617          */
1618         if (srv->no_pathinfo ||
1619             ! cli_setpathinfo(srv->cli, path,
1620                               create_time,
1621                               access_time,
1622                               write_time,
1623                               change_time,
1624                               mode)) {
1625
1626                 /*
1627                  * setpathinfo is not supported; go to plan B. 
1628                  *
1629                  * cli_setatr() does not work on win98, and it also doesn't
1630                  * support setting the access time (only the modification
1631                  * time), so in all cases, we open the specified file and use
1632                  * cli_setattrE() which should work on all OS versions, and
1633                  * supports both times.
1634                  */
1635
1636                 /* Don't try {q,set}pathinfo() again, with this server */
1637                 srv->no_pathinfo = True;
1638
1639                 /* Open the file */
1640                 if ((fd = cli_open(srv->cli, path, O_RDWR, DENY_NONE)) < 0) {
1641
1642                         errno = smbc_errno(context, srv->cli);
1643                         return -1;
1644                 }
1645
1646                 /* Set the new attributes */
1647                 ret = cli_setattrE(srv->cli, fd,
1648                                    change_time,
1649                                    access_time,
1650                                    write_time);
1651
1652                 /* Close the file */
1653                 cli_close(srv->cli, fd);
1654
1655                 /*
1656                  * Unfortunately, setattrE() doesn't have a provision for
1657                  * setting the access mode (attributes).  We'll have to try
1658                  * cli_setatr() for that, and with only this parameter, it
1659                  * seems to work on win98.
1660                  */
1661                 if (ret && mode != (uint16) -1) {
1662                         ret = cli_setatr(srv->cli, path, mode, 0);
1663                 }
1664
1665                 if (! ret) {
1666                         errno = smbc_errno(context, srv->cli);
1667                         return False;
1668                 }
1669         }
1670
1671         return True;
1672 }
1673
1674  /*
1675   * Routine to unlink() a file
1676   */
1677
1678 static int
1679 smbc_unlink_ctx(SMBCCTX *context,
1680                 const char *fname)
1681 {
1682         fstring server, share, user, password, workgroup;
1683         pstring path, targetpath;
1684         struct cli_state *targetcli;
1685         SMBCSRV *srv = NULL;
1686
1687         if (!context || !context->internal ||
1688             !context->internal->_initialized) {
1689
1690                 errno = EINVAL;  /* Best I can think of ... */
1691                 return -1;
1692
1693         }
1694
1695         if (!fname) {
1696
1697                 errno = EINVAL;
1698                 return -1;
1699
1700         }
1701
1702         if (smbc_parse_path(context, fname,
1703                             workgroup, sizeof(workgroup),
1704                             server, sizeof(server),
1705                             share, sizeof(share),
1706                             path, sizeof(path),
1707                             user, sizeof(user),
1708                             password, sizeof(password),
1709                             NULL, 0)) {
1710                 errno = EINVAL;
1711                 return -1;
1712         }
1713
1714         if (user[0] == (char)0) fstrcpy(user, context->user);
1715
1716         srv = smbc_server(context, True,
1717                           server, share, workgroup, user, password);
1718
1719         if (!srv) {
1720
1721                 return -1;  /* smbc_server sets errno */
1722
1723         }
1724
1725         /*d_printf(">>>unlink: resolving %s\n", path);*/
1726         if (!cli_resolve_path( "", srv->cli, path, &targetcli, targetpath))
1727         {
1728                 d_printf("Could not resolve %s\n", path);
1729                 return -1;
1730         }
1731         /*d_printf(">>>unlink: resolved path as %s\n", targetpath);*/
1732
1733         if (!cli_unlink(targetcli, targetpath)) {
1734
1735                 errno = smbc_errno(context, targetcli);
1736
1737                 if (errno == EACCES) { /* Check if the file is a directory */
1738
1739                         int saverr = errno;
1740                         SMB_OFF_T size = 0;
1741                         uint16 mode = 0;
1742                         struct timespec write_time_ts;
1743                         struct timespec access_time_ts;
1744                         struct timespec change_time_ts;
1745                         SMB_INO_T ino = 0;
1746
1747                         if (!smbc_getatr(context, srv, path, &mode, &size,
1748                                          NULL,
1749                                          &access_time_ts,
1750                                          &write_time_ts,
1751                                          &change_time_ts,
1752                                          &ino)) {
1753
1754                                 /* Hmmm, bad error ... What? */
1755
1756                                 errno = smbc_errno(context, targetcli);
1757                                 return -1;
1758
1759                         }
1760                         else {
1761
1762                                 if (IS_DOS_DIR(mode))
1763                                         errno = EISDIR;
1764                                 else
1765                                         errno = saverr;  /* Restore this */
1766
1767                         }
1768                 }
1769
1770                 return -1;
1771
1772         }
1773
1774         return 0;  /* Success ... */
1775
1776 }
1777
1778 /*
1779  * Routine to rename() a file
1780  */
1781
1782 static int
1783 smbc_rename_ctx(SMBCCTX *ocontext,
1784                 const char *oname, 
1785                 SMBCCTX *ncontext,
1786                 const char *nname)
1787 {
1788         fstring server1;
1789         fstring share1;
1790         fstring server2;
1791         fstring share2;
1792         fstring user1;
1793         fstring user2;
1794         fstring password1;
1795         fstring password2;
1796         fstring workgroup;
1797         pstring path1;
1798         pstring path2;
1799         pstring targetpath1;
1800         pstring targetpath2;
1801         struct cli_state *targetcli1;
1802         struct cli_state *targetcli2;
1803         SMBCSRV *srv = NULL;
1804
1805         if (!ocontext || !ncontext || 
1806             !ocontext->internal || !ncontext->internal ||
1807             !ocontext->internal->_initialized || 
1808             !ncontext->internal->_initialized) {
1809
1810                 errno = EINVAL;  /* Best I can think of ... */
1811                 return -1;
1812
1813         }
1814         
1815         if (!oname || !nname) {
1816
1817                 errno = EINVAL;
1818                 return -1;
1819
1820         }
1821         
1822         DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
1823
1824         smbc_parse_path(ocontext, oname,
1825                         workgroup, sizeof(workgroup),
1826                         server1, sizeof(server1),
1827                         share1, sizeof(share1),
1828                         path1, sizeof(path1),
1829                         user1, sizeof(user1),
1830                         password1, sizeof(password1),
1831                         NULL, 0);
1832
1833         if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
1834
1835         smbc_parse_path(ncontext, nname,
1836                         NULL, 0,
1837                         server2, sizeof(server2),
1838                         share2, sizeof(share2),
1839                         path2, sizeof(path2),
1840                         user2, sizeof(user2),
1841                         password2, sizeof(password2),
1842                         NULL, 0);
1843
1844         if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
1845
1846         if (strcmp(server1, server2) || strcmp(share1, share2) ||
1847             strcmp(user1, user2)) {
1848
1849                 /* Can't rename across file systems, or users?? */
1850
1851                 errno = EXDEV;
1852                 return -1;
1853
1854         }
1855
1856         srv = smbc_server(ocontext, True,
1857                           server1, share1, workgroup, user1, password1);
1858         if (!srv) {
1859
1860                 return -1;
1861
1862         }
1863
1864         /*d_printf(">>>rename: resolving %s\n", path1);*/
1865         if (!cli_resolve_path( "", srv->cli, path1, &targetcli1, targetpath1))
1866         {
1867                 d_printf("Could not resolve %s\n", path1);
1868                 return -1;
1869         }
1870         /*d_printf(">>>rename: resolved path as %s\n", targetpath1);*/
1871         /*d_printf(">>>rename: resolving %s\n", path2);*/
1872         if (!cli_resolve_path( "", srv->cli, path2, &targetcli2, targetpath2))
1873         {
1874                 d_printf("Could not resolve %s\n", path2);
1875                 return -1;
1876         }
1877         /*d_printf(">>>rename: resolved path as %s\n", targetpath2);*/
1878         
1879         if (strcmp(targetcli1->desthost, targetcli2->desthost) ||
1880             strcmp(targetcli1->share, targetcli2->share))
1881         {
1882                 /* can't rename across file systems */
1883                 
1884                 errno = EXDEV;
1885                 return -1;
1886         }
1887
1888         if (!cli_rename(targetcli1, targetpath1, targetpath2)) {
1889                 int eno = smbc_errno(ocontext, targetcli1);
1890
1891                 if (eno != EEXIST ||
1892                     !cli_unlink(targetcli1, targetpath2) ||
1893                     !cli_rename(targetcli1, targetpath1, targetpath2)) {
1894
1895                         errno = eno;
1896                         return -1;
1897
1898                 }
1899         }
1900
1901         return 0; /* Success */
1902
1903 }
1904
1905 /*
1906  * A routine to lseek() a file
1907  */
1908
1909 static off_t
1910 smbc_lseek_ctx(SMBCCTX *context,
1911                SMBCFILE *file,
1912                off_t offset,
1913                int whence)
1914 {
1915         SMB_OFF_T size;
1916         fstring server, share, user, password;
1917         pstring path, targetpath;
1918         struct cli_state *targetcli;
1919
1920         if (!context || !context->internal ||
1921             !context->internal->_initialized) {
1922
1923                 errno = EINVAL;
1924                 return -1;
1925                 
1926         }
1927
1928         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1929
1930                 errno = EBADF;
1931                 return -1;
1932
1933         }
1934
1935         if (!file->file) {
1936
1937                 errno = EINVAL;
1938                 return -1;      /* Can't lseek a dir ... */
1939
1940         }
1941
1942         switch (whence) {
1943         case SEEK_SET:
1944                 file->offset = offset;
1945                 break;
1946
1947         case SEEK_CUR:
1948                 file->offset += offset;
1949                 break;
1950
1951         case SEEK_END:
1952                 /*d_printf(">>>lseek: parsing %s\n", file->fname);*/
1953                 if (smbc_parse_path(context, file->fname,
1954                                     NULL, 0,
1955                                     server, sizeof(server),
1956                                     share, sizeof(share),
1957                                     path, sizeof(path),
1958                                     user, sizeof(user),
1959                                     password, sizeof(password),
1960                                     NULL, 0)) {
1961                         
1962                                         errno = EINVAL;
1963                                         return -1;
1964                         }
1965                 
1966                 /*d_printf(">>>lseek: resolving %s\n", path);*/
1967                 if (!cli_resolve_path("", file->srv->cli, path,
1968                                       &targetcli, targetpath))
1969                 {
1970                         d_printf("Could not resolve %s\n", path);
1971                         return -1;
1972                 }
1973                 /*d_printf(">>>lseek: resolved path as %s\n", targetpath);*/
1974                 
1975                 if (!cli_qfileinfo(targetcli, file->cli_fd, NULL,
1976                                    &size, NULL, NULL, NULL, NULL, NULL)) 
1977                 {
1978                     SMB_OFF_T b_size = size;
1979                         if (!cli_getattrE(targetcli, file->cli_fd,
1980                                           NULL, &b_size, NULL, NULL, NULL)) 
1981                     {
1982                         errno = EINVAL;
1983                         return -1;
1984                     } else
1985                         size = b_size;
1986                 }
1987                 file->offset = size + offset;
1988                 break;
1989
1990         default:
1991                 errno = EINVAL;
1992                 break;
1993
1994         }
1995
1996         return file->offset;
1997
1998 }
1999
2000 /* 
2001  * Generate an inode number from file name for those things that need it
2002  */
2003
2004 static ino_t
2005 smbc_inode(SMBCCTX *context,
2006            const char *name)
2007 {
2008
2009         if (!context || !context->internal ||
2010             !context->internal->_initialized) {
2011
2012                 errno = EINVAL;
2013                 return -1;
2014
2015         }
2016
2017         if (!*name) return 2; /* FIXME, why 2 ??? */
2018         return (ino_t)str_checksum(name);
2019
2020 }
2021
2022 /*
2023  * Routine to put basic stat info into a stat structure ... Used by stat and
2024  * fstat below.
2025  */
2026
2027 static int
2028 smbc_setup_stat(SMBCCTX *context,
2029                 struct stat *st,
2030                 char *fname,
2031                 SMB_OFF_T size,
2032                 int mode)
2033 {
2034         
2035         st->st_mode = 0;
2036
2037         if (IS_DOS_DIR(mode)) {
2038                 st->st_mode = SMBC_DIR_MODE;
2039         } else {
2040                 st->st_mode = SMBC_FILE_MODE;
2041         }
2042
2043         if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
2044         if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
2045         if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
2046         if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
2047
2048         st->st_size = size;
2049 #ifdef HAVE_STAT_ST_BLKSIZE
2050         st->st_blksize = 512;
2051 #endif
2052 #ifdef HAVE_STAT_ST_BLOCKS
2053         st->st_blocks = (size+511)/512;
2054 #endif
2055         st->st_uid = getuid();
2056         st->st_gid = getgid();
2057
2058         if (IS_DOS_DIR(mode)) {
2059                 st->st_nlink = 2;
2060         } else {
2061                 st->st_nlink = 1;
2062         }
2063
2064         if (st->st_ino == 0) {
2065                 st->st_ino = smbc_inode(context, fname);
2066         }
2067         
2068         return True;  /* FIXME: Is this needed ? */
2069
2070 }
2071
2072 /*
2073  * Routine to stat a file given a name
2074  */
2075
2076 static int
2077 smbc_stat_ctx(SMBCCTX *context,
2078               const char *fname,
2079               struct stat *st)
2080 {
2081         SMBCSRV *srv;
2082         fstring server;
2083         fstring share;
2084         fstring user;
2085         fstring password;
2086         fstring workgroup;
2087         pstring path;
2088         struct timespec write_time_ts;
2089         struct timespec access_time_ts;
2090         struct timespec change_time_ts;
2091         SMB_OFF_T size = 0;
2092         uint16 mode = 0;
2093         SMB_INO_T ino = 0;
2094
2095         if (!context || !context->internal ||
2096             !context->internal->_initialized) {
2097
2098                 errno = EINVAL;  /* Best I can think of ... */
2099                 return -1;
2100     
2101         }
2102
2103         if (!fname) {
2104
2105                 errno = EINVAL;
2106                 return -1;
2107
2108         }
2109   
2110         DEBUG(4, ("smbc_stat(%s)\n", fname));
2111
2112         if (smbc_parse_path(context, fname,
2113                             workgroup, sizeof(workgroup),
2114                             server, sizeof(server),
2115                             share, sizeof(share),
2116                             path, sizeof(path),
2117                             user, sizeof(user),
2118                             password, sizeof(password),
2119                             NULL, 0)) {
2120                 errno = EINVAL;
2121                 return -1;
2122         }
2123
2124         if (user[0] == (char)0) fstrcpy(user, context->user);
2125
2126         srv = smbc_server(context, True,
2127                           server, share, workgroup, user, password);
2128
2129         if (!srv) {
2130                 return -1;  /* errno set by smbc_server */
2131         }
2132
2133         if (!smbc_getatr(context, srv, path, &mode, &size, 
2134                          NULL,
2135                          &access_time_ts,
2136                          &write_time_ts,
2137                          &change_time_ts,
2138                          &ino)) {
2139
2140                 errno = smbc_errno(context, srv->cli);
2141                 return -1;
2142                 
2143         }
2144
2145         st->st_ino = ino;
2146
2147         smbc_setup_stat(context, st, path, size, mode);
2148
2149         set_atimespec(st, access_time_ts);
2150         set_ctimespec(st, change_time_ts);
2151         set_mtimespec(st, write_time_ts);
2152         st->st_dev   = srv->dev;
2153
2154         return 0;
2155
2156 }
2157
2158 /*
2159  * Routine to stat a file given an fd
2160  */
2161
2162 static int
2163 smbc_fstat_ctx(SMBCCTX *context,
2164                SMBCFILE *file,
2165                struct stat *st)
2166 {
2167         struct timespec change_time_ts;
2168         struct timespec access_time_ts;
2169         struct timespec write_time_ts;
2170         SMB_OFF_T size;
2171         uint16 mode;
2172         fstring server;
2173         fstring share;
2174         fstring user;
2175         fstring password;
2176         pstring path;
2177         pstring targetpath;
2178         struct cli_state *targetcli;
2179         SMB_INO_T ino = 0;
2180
2181         if (!context || !context->internal ||
2182             !context->internal->_initialized) {
2183
2184                 errno = EINVAL;
2185                 return -1;
2186
2187         }
2188
2189         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
2190
2191                 errno = EBADF;
2192                 return -1;
2193
2194         }
2195
2196         if (!file->file) {
2197
2198                 return context->fstatdir(context, file, st);
2199
2200         }
2201
2202         /*d_printf(">>>fstat: parsing %s\n", file->fname);*/
2203         if (smbc_parse_path(context, file->fname,
2204                             NULL, 0,
2205                             server, sizeof(server),
2206                             share, sizeof(share),
2207                             path, sizeof(path),
2208                             user, sizeof(user),
2209                             password, sizeof(password),
2210                             NULL, 0)) {
2211                 errno = EINVAL;
2212                 return -1;
2213         }
2214         
2215         /*d_printf(">>>fstat: resolving %s\n", path);*/
2216         if (!cli_resolve_path("", file->srv->cli, path,
2217                               &targetcli, targetpath))
2218         {
2219                 d_printf("Could not resolve %s\n", path);
2220                 return -1;
2221         }
2222         /*d_printf(">>>fstat: resolved path as %s\n", targetpath);*/
2223
2224         if (!cli_qfileinfo(targetcli, file->cli_fd, &mode, &size,
2225                            NULL,
2226                            &access_time_ts,
2227                            &write_time_ts,
2228                            &change_time_ts,
2229                            &ino)) {
2230
2231                 time_t change_time, access_time, write_time;
2232
2233                 if (!cli_getattrE(targetcli, file->cli_fd, &mode, &size,
2234                                 &change_time, &access_time, &write_time)) {
2235
2236                         errno = EINVAL;
2237                         return -1;
2238                 }
2239
2240                 change_time_ts = convert_time_t_to_timespec(change_time);
2241                 access_time_ts = convert_time_t_to_timespec(access_time);
2242                 write_time_ts = convert_time_t_to_timespec(write_time);
2243         }
2244
2245         st->st_ino = ino;
2246
2247         smbc_setup_stat(context, st, file->fname, size, mode);
2248
2249         set_atimespec(st, access_time_ts);
2250         set_ctimespec(st, change_time_ts);
2251         set_mtimespec(st, write_time_ts);
2252         st->st_dev = file->srv->dev;
2253
2254         return 0;
2255
2256 }
2257
2258 /*
2259  * Routine to open a directory
2260  * We accept the URL syntax explained in smbc_parse_path(), above.
2261  */
2262
2263 static void
2264 smbc_remove_dir(SMBCFILE *dir)
2265 {
2266         struct smbc_dir_list *d,*f;
2267
2268         d = dir->dir_list;
2269         while (d) {
2270
2271                 f = d; d = d->next;
2272
2273                 SAFE_FREE(f->dirent);
2274                 SAFE_FREE(f);
2275
2276         }
2277
2278         dir->dir_list = dir->dir_end = dir->dir_next = NULL;
2279
2280 }
2281
2282 static int
2283 add_dirent(SMBCFILE *dir,
2284            const char *name,
2285            const char *comment,
2286            uint32 type)
2287 {
2288         struct smbc_dirent *dirent;
2289         int size;
2290         int name_length = (name == NULL ? 0 : strlen(name));
2291         int comment_len = (comment == NULL ? 0 : strlen(comment));
2292
2293         /*
2294          * Allocate space for the dirent, which must be increased by the 
2295          * size of the name and the comment and 1 each for the null terminator.
2296          */
2297
2298         size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
2299     
2300         dirent = (struct smbc_dirent *)SMB_MALLOC(size);
2301
2302         if (!dirent) {
2303
2304                 dir->dir_error = ENOMEM;
2305                 return -1;
2306
2307         }
2308
2309         ZERO_STRUCTP(dirent);
2310
2311         if (dir->dir_list == NULL) {
2312
2313                 dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
2314                 if (!dir->dir_list) {
2315
2316                         SAFE_FREE(dirent);
2317                         dir->dir_error = ENOMEM;
2318                         return -1;
2319
2320                 }
2321                 ZERO_STRUCTP(dir->dir_list);
2322
2323                 dir->dir_end = dir->dir_next = dir->dir_list;
2324         }
2325         else {
2326
2327                 dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
2328                 
2329                 if (!dir->dir_end->next) {
2330                         
2331                         SAFE_FREE(dirent);
2332                         dir->dir_error = ENOMEM;
2333                         return -1;
2334
2335                 }
2336                 ZERO_STRUCTP(dir->dir_end->next);
2337
2338                 dir->dir_end = dir->dir_end->next;
2339         }
2340
2341         dir->dir_end->next = NULL;
2342         dir->dir_end->dirent = dirent;
2343         
2344         dirent->smbc_type = type;
2345         dirent->namelen = name_length;
2346         dirent->commentlen = comment_len;
2347         dirent->dirlen = size;
2348   
2349         /*
2350          * dirent->namelen + 1 includes the null (no null termination needed)
2351          * Ditto for dirent->commentlen.
2352          * The space for the two null bytes was allocated.
2353          */
2354         strncpy(dirent->name, (name?name:""), dirent->namelen + 1);
2355         dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
2356         strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
2357         
2358         return 0;
2359
2360 }
2361
2362 static void
2363 list_unique_wg_fn(const char *name,
2364                   uint32 type,
2365                   const char *comment,
2366                   void *state)
2367 {
2368         SMBCFILE *dir = (SMBCFILE *)state;
2369         struct smbc_dir_list *dir_list;
2370         struct smbc_dirent *dirent;
2371         int dirent_type;
2372         int do_remove = 0;
2373
2374         dirent_type = dir->dir_type;
2375
2376         if (add_dirent(dir, name, comment, dirent_type) < 0) {
2377
2378                 /* An error occurred, what do we do? */
2379                 /* FIXME: Add some code here */
2380         }
2381
2382         /* Point to the one just added */
2383         dirent = dir->dir_end->dirent;
2384
2385         /* See if this was a duplicate */
2386         for (dir_list = dir->dir_list;
2387              dir_list != dir->dir_end;
2388              dir_list = dir_list->next) {
2389                 if (! do_remove &&
2390                     strcmp(dir_list->dirent->name, dirent->name) == 0) {
2391                         /* Duplicate.  End end of list need to be removed. */
2392                         do_remove = 1;
2393                 }
2394
2395                 if (do_remove && dir_list->next == dir->dir_end) {
2396                         /* Found the end of the list.  Remove it. */
2397                         dir->dir_end = dir_list;
2398                         free(dir_list->next);
2399                         free(dirent);
2400                         dir_list->next = NULL;
2401                         break;
2402                 }
2403         }
2404 }
2405
2406 static void
2407 list_fn(const char *name,
2408         uint32 type,
2409         const char *comment,
2410         void *state)
2411 {
2412         SMBCFILE *dir = (SMBCFILE *)state;
2413         int dirent_type;
2414
2415         /*
2416          * We need to process the type a little ...
2417          *
2418          * Disk share     = 0x00000000
2419          * Print share    = 0x00000001
2420          * Comms share    = 0x00000002 (obsolete?)
2421          * IPC$ share     = 0x00000003 
2422          *
2423          * administrative shares:
2424          * ADMIN$, IPC$, C$, D$, E$ ...  are type |= 0x80000000
2425          */
2426         
2427         if (dir->dir_type == SMBC_FILE_SHARE) {
2428                 
2429                 switch (type) {
2430                 case 0 | 0x80000000:
2431                 case 0:
2432                         dirent_type = SMBC_FILE_SHARE;
2433                         break;
2434
2435                 case 1:
2436                         dirent_type = SMBC_PRINTER_SHARE;
2437                         break;
2438
2439                 case 2:
2440                         dirent_type = SMBC_COMMS_SHARE;
2441                         break;
2442
2443                 case 3 | 0x80000000:
2444                 case 3:
2445                         dirent_type = SMBC_IPC_SHARE;
2446                         break;
2447
2448                 default:
2449                         dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
2450                         break;
2451                 }
2452         }
2453         else {
2454                 dirent_type = dir->dir_type;
2455         }
2456
2457         if (add_dirent(dir, name, comment, dirent_type) < 0) {
2458
2459                 /* An error occurred, what do we do? */
2460                 /* FIXME: Add some code here */
2461
2462         }
2463 }
2464
2465 static void
2466 dir_list_fn(const char *mnt,
2467             file_info *finfo,
2468             const char *mask,
2469             void *state)
2470 {
2471
2472         if (add_dirent((SMBCFILE *)state, finfo->name, "", 
2473                        (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
2474
2475                 /* Handle an error ... */
2476
2477                 /* FIXME: Add some code ... */
2478
2479         } 
2480
2481 }
2482
2483 static int
2484 net_share_enum_rpc(struct cli_state *cli,
2485                    void (*fn)(const char *name,
2486                               uint32 type,
2487                               const char *comment,
2488                               void *state),
2489                    void *state)
2490 {
2491         int i;
2492         NTSTATUS result;
2493         uint32 enum_hnd;
2494         uint32 info_level = 1;
2495         uint32 preferred_len = 0xffffffff;
2496         struct srvsvc_NetShareCtr1 ctr1;
2497         union srvsvc_NetShareCtr ctr;
2498         void *mem_ctx;
2499         struct rpc_pipe_client *pipe_hnd;
2500         uint32 numentries;
2501         NTSTATUS nt_status;
2502
2503         /* Open the server service pipe */
2504         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &nt_status);
2505         if (!pipe_hnd) {
2506                 DEBUG(1, ("net_share_enum_rpc pipe open fail!\n"));
2507                 return -1;
2508         }
2509
2510         /* Allocate a context for parsing and for the entries in "ctr" */
2511         mem_ctx = talloc_init("libsmbclient: net_share_enum_rpc");
2512         if (mem_ctx == NULL) {
2513                 DEBUG(0, ("out of memory for net_share_enum_rpc!\n"));
2514                 cli_rpc_pipe_close(pipe_hnd);
2515                 return -1; 
2516         }
2517
2518         ZERO_STRUCT(ctr1);
2519         ctr.ctr1 = &ctr1;
2520
2521         /* Issue the NetShareEnum RPC call and retrieve the response */
2522         enum_hnd = 0;
2523         result = rpccli_srvsvc_NetShareEnum(pipe_hnd, mem_ctx, NULL,
2524                                             &info_level, &ctr, preferred_len,
2525                                             &numentries, &enum_hnd);
2526
2527         /* Was it successful? */
2528         if (!NT_STATUS_IS_OK(result) || numentries == 0) {
2529                 /*  Nope.  Go clean up. */
2530                 goto done;
2531         }
2532
2533         /* For each returned entry... */
2534         for (i = 0; i < numentries; i++) {
2535
2536                 /* Add this share to the list */
2537                 (*fn)(ctr.ctr1->array[i].name, 
2538                                           ctr.ctr1->array[i].type, 
2539                                           ctr.ctr1->array[i].comment, state);
2540         }
2541
2542 done:
2543         /* Close the server service pipe */
2544         cli_rpc_pipe_close(pipe_hnd);
2545
2546         /* Free all memory which was allocated for this request */
2547         TALLOC_FREE(mem_ctx);
2548
2549         /* Tell 'em if it worked */
2550         return NT_STATUS_IS_OK(result) ? 0 : -1;
2551 }
2552
2553
2554
2555 static SMBCFILE *
2556 smbc_opendir_ctx(SMBCCTX *context,
2557                  const char *fname)
2558 {
2559         int saved_errno;
2560         fstring server, share, user, password, options;
2561         pstring workgroup;
2562         pstring path;
2563         uint16 mode;
2564         char *p;
2565         SMBCSRV *srv  = NULL;
2566         SMBCFILE *dir = NULL;
2567         struct _smbc_callbacks *cb;
2568         struct in_addr rem_ip;
2569
2570         if (!context || !context->internal ||
2571             !context->internal->_initialized) {
2572                 DEBUG(4, ("no valid context\n"));
2573                 errno = EINVAL + 8192;
2574                 return NULL;
2575
2576         }
2577
2578         if (!fname) {
2579                 DEBUG(4, ("no valid fname\n"));
2580                 errno = EINVAL + 8193;
2581                 return NULL;
2582         }
2583
2584         if (smbc_parse_path(context, fname,
2585                             workgroup, sizeof(workgroup),
2586                             server, sizeof(server),
2587                             share, sizeof(share),
2588                             path, sizeof(path),
2589                             user, sizeof(user),
2590                             password, sizeof(password),
2591                             options, sizeof(options))) {
2592                 DEBUG(4, ("no valid path\n"));
2593                 errno = EINVAL + 8194;
2594                 return NULL;
2595         }
2596
2597         DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' "
2598                   "path='%s' options='%s'\n",
2599                   fname, server, share, path, options));
2600
2601         /* Ensure the options are valid */
2602         if (smbc_check_options(server, share, path, options)) {
2603                 DEBUG(4, ("unacceptable options (%s)\n", options));
2604                 errno = EINVAL + 8195;
2605                 return NULL;
2606         }
2607
2608         if (user[0] == (char)0) fstrcpy(user, context->user);
2609
2610         dir = SMB_MALLOC_P(SMBCFILE);
2611
2612         if (!dir) {
2613
2614                 errno = ENOMEM;
2615                 return NULL;
2616
2617         }
2618
2619         ZERO_STRUCTP(dir);
2620
2621         dir->cli_fd   = 0;
2622         dir->fname    = SMB_STRDUP(fname);
2623         dir->srv      = NULL;
2624         dir->offset   = 0;
2625         dir->file     = False;
2626         dir->dir_list = dir->dir_next = dir->dir_end = NULL;
2627
2628         if (server[0] == (char)0) {
2629
2630                 int i;
2631                 int count;
2632                 int max_lmb_count;
2633                 struct ip_service *ip_list;
2634                 struct ip_service server_addr;
2635                 struct user_auth_info u_info;
2636                 struct cli_state *cli;
2637
2638                 if (share[0] != (char)0 || path[0] != (char)0) {
2639
2640                         errno = EINVAL + 8196;
2641                         if (dir) {
2642                                 SAFE_FREE(dir->fname);
2643                                 SAFE_FREE(dir);
2644                         }
2645                         return NULL;
2646                 }
2647
2648                 /* Determine how many local master browsers to query */
2649                 max_lmb_count = (context->options.browse_max_lmb_count == 0
2650                                  ? INT_MAX
2651                                  : context->options.browse_max_lmb_count);
2652
2653                 pstrcpy(u_info.username, user);
2654                 pstrcpy(u_info.password, password);
2655
2656                 /*
2657                  * We have server and share and path empty but options
2658                  * requesting that we scan all master browsers for their list
2659                  * of workgroups/domains.  This implies that we must first try
2660                  * broadcast queries to find all master browsers, and if that
2661                  * doesn't work, then try our other methods which return only
2662                  * a single master browser.
2663                  */
2664
2665                 ip_list = NULL;
2666                 if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
2667
2668                         SAFE_FREE(ip_list);
2669
2670                         if (!find_master_ip(workgroup, &server_addr.ip)) {
2671
2672                                 if (dir) {
2673                                         SAFE_FREE(dir->fname);
2674                                         SAFE_FREE(dir);
2675                                 }
2676                                 errno = ENOENT;
2677                                 return NULL;
2678                         }
2679
2680                         ip_list = &server_addr;
2681                         count = 1;
2682                 }
2683
2684                 for (i = 0; i < count && i < max_lmb_count; i++) {
2685                         DEBUG(99, ("Found master browser %d of %d: %s\n",
2686                                    i+1, MAX(count, max_lmb_count),
2687                                    inet_ntoa(ip_list[i].ip)));
2688                         
2689                         cli = get_ipc_connect_master_ip(&ip_list[i],
2690                                                         workgroup, &u_info);
2691                         /* cli == NULL is the master browser refused to talk or 
2692                            could not be found */
2693                         if ( !cli )
2694                                 continue;
2695
2696                         fstrcpy(server, cli->desthost);
2697                         cli_shutdown(cli);
2698
2699                         DEBUG(4, ("using workgroup %s %s\n",
2700                                   workgroup, server));
2701
2702                         /*
2703                          * For each returned master browser IP address, get a
2704                          * connection to IPC$ on the server if we do not
2705                          * already have one, and determine the
2706                          * workgroups/domains that it knows about.
2707                          */
2708                 
2709                         srv = smbc_server(context, True, server, "IPC$",
2710                                           workgroup, user, password);
2711                         if (!srv) {
2712                                 continue;
2713                         }
2714                 
2715                         dir->srv = srv;
2716                         dir->dir_type = SMBC_WORKGROUP;
2717
2718                         /* Now, list the stuff ... */
2719                         
2720                         if (!cli_NetServerEnum(srv->cli,
2721                                                workgroup,
2722                                                SV_TYPE_DOMAIN_ENUM,
2723                                                list_unique_wg_fn,
2724                                                (void *)dir)) {
2725                                 continue;
2726                         }
2727                 }
2728
2729                 SAFE_FREE(ip_list);
2730         } else { 
2731                 /*
2732                  * Server not an empty string ... Check the rest and see what
2733                  * gives
2734                  */
2735                 if (*share == '\0') {
2736                         if (*path != '\0') {
2737
2738                                 /* Should not have empty share with path */
2739                                 errno = EINVAL + 8197;
2740                                 if (dir) {
2741                                         SAFE_FREE(dir->fname);
2742                                         SAFE_FREE(dir);
2743                                 }
2744                                 return NULL;
2745         
2746                         }
2747
2748                         /*
2749                          * We don't know if <server> is really a server name
2750                          * or is a workgroup/domain name.  If we already have
2751                          * a server structure for it, we'll use it.
2752                          * Otherwise, check to see if <server><1D>,
2753                          * <server><1B>, or <server><20> translates.  We check
2754                          * to see if <server> is an IP address first.
2755                          */
2756
2757                         /*
2758                          * See if we have an existing server.  Do not
2759                          * establish a connection if one does not already
2760                          * exist.
2761                          */
2762                         srv = smbc_server(context, False, server, "IPC$",
2763                                           workgroup, user, password);
2764
2765                         /*
2766                          * If no existing server and not an IP addr, look for
2767                          * LMB or DMB
2768                          */
2769                         if (!srv &&
2770                             !is_ipaddress(server) &&
2771                             (resolve_name(server, &rem_ip, 0x1d) ||   /* LMB */
2772                              resolve_name(server, &rem_ip, 0x1b) )) { /* DMB */
2773
2774                                 fstring buserver;
2775
2776                                 dir->dir_type = SMBC_SERVER;
2777
2778                                 /*
2779                                  * Get the backup list ...
2780                                  */
2781                                 if (!name_status_find(server, 0, 0,
2782                                                       rem_ip, buserver)) {
2783
2784                                         DEBUG(0, ("Could not get name of "
2785                                                   "local/domain master browser "
2786                                                   "for server %s\n", server));
2787                                         if (dir) {
2788                                                 SAFE_FREE(dir->fname);
2789                                                 SAFE_FREE(dir);
2790                                         }
2791                                         errno = EPERM;
2792                                         return NULL;
2793
2794                                 }
2795
2796                                 /*
2797                                  * Get a connection to IPC$ on the server if
2798                                  * we do not already have one
2799                                  */
2800                                 srv = smbc_server(context, True,
2801                                                   buserver, "IPC$",
2802                                                   workgroup, user, password);
2803                                 if (!srv) {
2804                                         DEBUG(0, ("got no contact to IPC$\n"));
2805                                         if (dir) {
2806                                                 SAFE_FREE(dir->fname);
2807                                                 SAFE_FREE(dir);
2808                                         }
2809                                         return NULL;
2810
2811                                 }
2812
2813                                 dir->srv = srv;
2814
2815                                 /* Now, list the servers ... */
2816                                 if (!cli_NetServerEnum(srv->cli, server,
2817                                                        0x0000FFFE, list_fn,
2818                                                        (void *)dir)) {
2819
2820                                         if (dir) {
2821                                                 SAFE_FREE(dir->fname);
2822                                                 SAFE_FREE(dir);
2823                                         }
2824                                         return NULL;
2825                                 }
2826                         } else if (srv ||
2827                                    (resolve_name(server, &rem_ip, 0x20))) {
2828                                 
2829                                 /* If we hadn't found the server, get one now */
2830                                 if (!srv) {
2831                                         srv = smbc_server(context, True,
2832                                                           server, "IPC$",
2833                                                           workgroup,
2834                                                           user, password);
2835                                 }
2836
2837                                 if (!srv) {
2838                                         if (dir) {
2839                                                 SAFE_FREE(dir->fname);
2840                                                 SAFE_FREE(dir);
2841                                         }
2842                                         return NULL;
2843
2844                                 }
2845
2846                                 dir->dir_type = SMBC_FILE_SHARE;
2847                                 dir->srv = srv;
2848
2849                                 /* List the shares ... */
2850
2851                                 if (net_share_enum_rpc(
2852                                             srv->cli,
2853                                             list_fn,
2854                                             (void *) dir) < 0 &&
2855                                     cli_RNetShareEnum(
2856                                             srv->cli,
2857                                             list_fn, 
2858                                             (void *)dir) < 0) {
2859                                                 
2860                                         errno = cli_errno(srv->cli);
2861                                         if (dir) {
2862                                                 SAFE_FREE(dir->fname);
2863                                                 SAFE_FREE(dir);
2864                                         }
2865                                         return NULL;
2866
2867                                 }
2868                         } else {
2869                                 /* Neither the workgroup nor server exists */
2870                                 errno = ECONNREFUSED;   
2871                                 if (dir) {
2872                                         SAFE_FREE(dir->fname);
2873                                         SAFE_FREE(dir);
2874                                 }
2875                                 return NULL;
2876                         }
2877
2878                 }
2879                 else {
2880                         /*
2881                          * The server and share are specified ... work from
2882                          * there ...
2883                          */
2884                         pstring targetpath;
2885                         struct cli_state *targetcli;
2886
2887                         /* We connect to the server and list the directory */
2888                         dir->dir_type = SMBC_FILE_SHARE;
2889
2890                         srv = smbc_server(context, True, server, share,
2891                                           workgroup, user, password);
2892
2893                         if (!srv) {
2894
2895                                 if (dir) {
2896                                         SAFE_FREE(dir->fname);
2897                                         SAFE_FREE(dir);
2898                                 }
2899                                 return NULL;
2900
2901                         }
2902
2903                         dir->srv = srv;
2904
2905                         /* Now, list the files ... */
2906
2907                         p = path + strlen(path);
2908                         pstrcat(path, "\\*");
2909
2910                         if (!cli_resolve_path("", srv->cli, path,
2911                                               &targetcli, targetpath))
2912                         {
2913                                 d_printf("Could not resolve %s\n", path);
2914                                 if (dir) {
2915                                         SAFE_FREE(dir->fname);
2916                                         SAFE_FREE(dir);
2917                                 }
2918                                 return NULL;
2919                         }
2920                         
2921                         if (cli_list(targetcli, targetpath,
2922                                      aDIR | aSYSTEM | aHIDDEN,
2923                                      dir_list_fn, (void *)dir) < 0) {
2924
2925                                 if (dir) {
2926                                         SAFE_FREE(dir->fname);
2927                                         SAFE_FREE(dir);
2928                                 }
2929                                 saved_errno = smbc_errno(context, targetcli);
2930
2931                                 if (saved_errno == EINVAL) {
2932                                     /*
2933                                      * See if they asked to opendir something
2934                                      * other than a directory.  If so, the
2935                                      * converted error value we got would have
2936                                      * been EINVAL rather than ENOTDIR.
2937                                      */
2938                                     *p = '\0'; /* restore original path */
2939
2940                                     if (smbc_getatr(context, srv, path,
2941                                                     &mode, NULL,
2942                                                     NULL, NULL, NULL, NULL,
2943                                                     NULL) &&
2944                                         ! IS_DOS_DIR(mode)) {
2945
2946                                         /* It is.  Correct the error value */
2947                                         saved_errno = ENOTDIR;
2948                                     }
2949                                 }
2950
2951                                 /*
2952                                  * If there was an error and the server is no
2953                                  * good any more...
2954                                  */
2955                                 cb = &context->callbacks;
2956                                 if (cli_is_error(targetcli) &&
2957                                     cb->check_server_fn(context, srv)) {
2958
2959                                     /* ... then remove it. */
2960                                     if (cb->remove_unused_server_fn(context,
2961                                                                     srv)) { 
2962                                         /*
2963                                          * We could not remove the server
2964                                          * completely, remove it from the
2965                                          * cache so we will not get it
2966                                          * again. It will be removed when the
2967                                          * last file/dir is closed.
2968                                          */
2969                                         cb->remove_cached_srv_fn(context, srv);
2970                                     }
2971                                 }
2972
2973                                 errno = saved_errno;
2974                                 return NULL;
2975                         }
2976                 }
2977
2978         }
2979
2980         DLIST_ADD(context->internal->_files, dir);
2981         return dir;
2982
2983 }
2984
2985 /*
2986  * Routine to close a directory
2987  */
2988
2989 static int
2990 smbc_closedir_ctx(SMBCCTX *context,
2991                   SMBCFILE *dir)
2992 {
2993
2994         if (!context || !context->internal ||
2995             !context->internal->_initialized) {
2996
2997                 errno = EINVAL;
2998                 return -1;
2999
3000         }
3001
3002         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3003
3004                 errno = EBADF;
3005                 return -1;
3006     
3007         }
3008
3009         smbc_remove_dir(dir); /* Clean it up */
3010
3011         DLIST_REMOVE(context->internal->_files, dir);
3012
3013         if (dir) {
3014
3015                 SAFE_FREE(dir->fname);
3016                 SAFE_FREE(dir);    /* Free the space too */
3017         }
3018
3019         return 0;
3020
3021 }
3022
3023 static void
3024 smbc_readdir_internal(SMBCCTX * context,
3025                       struct smbc_dirent *dest,
3026                       struct smbc_dirent *src,
3027                       int max_namebuf_len)
3028 {
3029         if (context->options.urlencode_readdir_entries) {
3030
3031                 /* url-encode the name.  get back remaining buffer space */
3032                 max_namebuf_len =
3033                         smbc_urlencode(dest->name, src->name, max_namebuf_len);
3034
3035                 /* We now know the name length */
3036                 dest->namelen = strlen(dest->name);
3037
3038                 /* Save the pointer to the beginning of the comment */
3039                 dest->comment = dest->name + dest->namelen + 1;
3040
3041                 /* Copy the comment */
3042                 strncpy(dest->comment, src->comment, max_namebuf_len - 1);
3043                 dest->comment[max_namebuf_len - 1] = '\0';
3044
3045                 /* Save other fields */
3046                 dest->smbc_type = src->smbc_type;
3047                 dest->commentlen = strlen(dest->comment);
3048                 dest->dirlen = ((dest->comment + dest->commentlen + 1) -
3049                                 (char *) dest);
3050         } else {
3051
3052                 /* No encoding.  Just copy the entry as is. */
3053                 memcpy(dest, src, src->dirlen);
3054                 dest->comment = (char *)(&dest->name + src->namelen + 1);
3055         }
3056         
3057 }
3058
3059 /*
3060  * Routine to get a directory entry
3061  */
3062
3063 struct smbc_dirent *
3064 smbc_readdir_ctx(SMBCCTX *context,
3065                  SMBCFILE *dir)
3066 {
3067         int maxlen;
3068         struct smbc_dirent *dirp, *dirent;
3069
3070         /* Check that all is ok first ... */
3071
3072         if (!context || !context->internal ||
3073             !context->internal->_initialized) {
3074
3075                 errno = EINVAL;
3076                 DEBUG(0, ("Invalid context in smbc_readdir_ctx()\n"));
3077                 return NULL;
3078
3079         }
3080
3081         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3082
3083                 errno = EBADF;
3084                 DEBUG(0, ("Invalid dir in smbc_readdir_ctx()\n"));
3085                 return NULL;
3086
3087         }
3088
3089         if (dir->file != False) { /* FIXME, should be dir, perhaps */
3090
3091                 errno = ENOTDIR;
3092                 DEBUG(0, ("Found file vs directory in smbc_readdir_ctx()\n"));
3093                 return NULL;
3094
3095         }
3096
3097         if (!dir->dir_next) {
3098                 return NULL;
3099         }
3100
3101         dirent = dir->dir_next->dirent;
3102         if (!dirent) {
3103
3104                 errno = ENOENT;
3105                 return NULL;
3106
3107         }
3108
3109         dirp = (struct smbc_dirent *)context->internal->_dirent;
3110         maxlen = (sizeof(context->internal->_dirent) -
3111                   sizeof(struct smbc_dirent));
3112
3113         smbc_readdir_internal(context, dirp, dirent, maxlen);
3114
3115         dir->dir_next = dir->dir_next->next;
3116
3117         return dirp;
3118 }
3119
3120 /*
3121  * Routine to get directory entries
3122  */
3123
3124 static int
3125 smbc_getdents_ctx(SMBCCTX *context,
3126                   SMBCFILE *dir,
3127                   struct smbc_dirent *dirp,
3128                   int count)
3129 {
3130         int rem = count;
3131         int reqd;
3132         int maxlen;
3133         char *ndir = (char *)dirp;
3134         struct smbc_dir_list *dirlist;
3135
3136         /* Check that all is ok first ... */
3137
3138         if (!context || !context->internal ||
3139             !context->internal->_initialized) {
3140
3141                 errno = EINVAL;
3142                 return -1;
3143
3144         }
3145
3146         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
3147
3148                 errno = EBADF;
3149                 return -1;
3150     
3151         }
3152
3153         if (dir->file != False) { /* FIXME, should be dir, perhaps */
3154
3155                 errno = ENOTDIR;
3156                 return -1;
3157