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