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