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