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