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