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