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