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