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