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