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