Some castiness for Don McCall.
[ira/wip.git] / source3 / libsmb / libsmbclient.c
1 /* 
2    Unix SMB/Netbios implementation.
3    SMB client library implementation
4    Copyright (C) Andrew Tridgell 1998
5    Copyright (C) Richard Sharpe 2000, 2002
6    Copyright (C) John Terpstra 2000
7    Copyright (C) Tom Jansen (Ninja ISD) 2002 
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25
26 #include "../include/libsmb_internal.h"
27
28 /*
29  * Functions exported by libsmb_cache.c that we need here
30  */
31 int smbc_default_cache_functions(SMBCCTX *context);
32
33 /* 
34  * check if an element is part of the list. 
35  * FIXME: Does not belong here !  
36  * Can anyone put this in a macro in dlinklist.h ?
37  * -- Tom
38  */
39 static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
40         if (!p || !list) return False;
41         do {
42                 if (p == list) return True;
43                 list = list->next;
44         } while (list);
45         return False;
46 }
47
48 extern BOOL in_client;
49
50 /*
51  * Is the logging working / configfile read ? 
52  */
53 static int smbc_initialized = 0;
54
55 static int 
56 hex2int( unsigned int _char )
57 {
58     if ( _char >= 'A' && _char <='F')
59         return _char - 'A' + 10;
60     if ( _char >= 'a' && _char <='f')
61         return _char - 'a' + 10;
62     if ( _char >= '0' && _char <='9')
63         return _char - '0';
64     return -1;
65 }
66
67 static void 
68 decode_urlpart(char *segment, size_t sizeof_segment)
69 {
70     int old_length = strlen(segment);
71     int new_length = 0;
72     int new_length2 = 0;
73     int i = 0;
74     pstring new_segment;
75     char *new_usegment = 0;
76
77     if ( !old_length ) {
78         return;
79     }
80
81     /* make a copy of the old one */
82     new_usegment = (char*)malloc( old_length * 3 + 1 );
83
84     while( i < old_length ) {
85         int bReencode = False;
86         unsigned char character = segment[ i++ ];
87         if ((character <= ' ') || (character > 127))
88             bReencode = True;
89
90         new_usegment [ new_length2++ ] = character;
91         if (character == '%' ) {
92             int a = i+1 < old_length ? hex2int( segment[i] ) : -1;
93             int b = i+1 < old_length ? hex2int( segment[i+1] ) : -1;
94             if ((a == -1) || (b == -1)) { /* Only replace if sequence is valid */
95                 /* Contains stray %, make sure to re-encode! */
96                 bReencode = True;
97             } else {
98                 /* Valid %xx sequence */
99                 character = a * 16 + b; /* Replace with value of %dd */
100                 if (!character)
101                     break; /* Stop at %00 */
102
103                 new_usegment [ new_length2++ ] = (unsigned char) segment[i++];
104                 new_usegment [ new_length2++ ] = (unsigned char) segment[i++];
105             }
106         }
107         if (bReencode) {
108             unsigned int c = character / 16;
109             new_length2--;
110             new_usegment [ new_length2++ ] = '%';
111
112             c += (c > 9) ? ('A' - 10) : '0';
113             new_usegment[ new_length2++ ] = c;
114
115             c = character % 16;
116             c += (c > 9) ? ('A' - 10) : '0';
117             new_usegment[ new_length2++ ] = c;
118         }
119
120         new_segment [ new_length++ ] = character;
121     }
122     new_segment [ new_length ] = 0;
123
124     free(new_usegment);
125
126     /* realloc it with unix charset */
127     pull_utf8_allocate((void**)&new_usegment, new_segment);
128
129     /* this assumes (very safely) that removing %aa sequences
130        only shortens the string */
131     strncpy(segment, new_usegment, sizeof_segment);
132
133     free(new_usegment);
134 }
135
136 /*
137  * Function to parse a path and turn it into components
138  *
139  * We accept smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]]
140  * 
141  * smb://       means show all the workgroups
142  * smb://name/  means, if name<1D> or name<1B> exists, list servers in workgroup,
143  *              else, if name<20> exists, list all shares for server ...
144  */
145
146 static const char *smbc_prefix = "smb:";
147
148 static int
149 smbc_parse_path(SMBCCTX *context, const char *fname, char *server, char *share, char *path,
150                 char *user, char *password) /* FIXME, lengths of strings */
151 {
152         static pstring s;
153         pstring userinfo;
154         const char *p;
155         char *q, *r;
156         int len;
157
158         server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
159         pstrcpy(s, fname);
160
161         /*  clean_fname(s);  causing problems ... */
162
163         /* see if it has the right prefix */
164         len = strlen(smbc_prefix);
165         if (strncmp(s,smbc_prefix,len) || 
166             (s[len] != '/' && s[len] != 0)) return -1; /* What about no smb: ? */
167
168         p = s + len;
169
170         /* Watch the test below, we are testing to see if we should exit */
171
172         if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {
173
174                 return -1;
175
176         }
177
178         p += 2;  /* Skip the // or \\  */
179
180         if (*p == (char)0)
181             goto decoding;
182
183         if (*p == '/') {
184
185                 strncpy(server, context->workgroup, 
186                         (strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
187                 return 0;
188                 
189         }
190
191         /*
192          * ok, its for us. Now parse out the server, share etc. 
193          *
194          * However, we want to parse out [[domain;]user[:password]@] if it
195          * exists ...
196          */
197
198         /* check that '@' occurs before '/', if '/' exists at all */
199         q = strchr_m(p, '@');
200         r = strchr_m(p, '/');
201         if (q && (!r || q < r)) {
202                 pstring username, passwd, domain;
203                 const char *u = userinfo;
204
205                 next_token(&p, userinfo, "@", sizeof(fstring));
206
207                 username[0] = passwd[0] = domain[0] = 0;
208
209                 if (strchr_m(u, ';')) {
210       
211                         next_token(&u, domain, ";", sizeof(fstring));
212
213                 }
214
215                 if (strchr_m(u, ':')) {
216
217                         next_token(&u, username, ":", sizeof(fstring));
218
219                         pstrcpy(passwd, u);
220
221                 }
222                 else {
223
224                         pstrcpy(username, u);
225
226                 }
227
228                 if (username[0])
229                         strncpy(user, username, sizeof(fstring));  /* FIXME, size and domain */
230
231                 if (passwd[0])
232                         strncpy(password, passwd, sizeof(fstring)); /* FIXME, size */
233
234         }
235
236         if (!next_token(&p, server, "/", sizeof(fstring))) {
237
238                 return -1;
239
240         }
241
242         if (*p == (char)0) goto decoding;  /* That's it ... */
243   
244         if (!next_token(&p, share, "/", sizeof(fstring))) {
245
246                 return -1;
247
248         }
249
250         pstrcpy(path, p);
251
252         all_string_sub(path, "/", "\\", 0);
253
254  decoding:
255         decode_urlpart(path, sizeof(pstring));
256         decode_urlpart(server, sizeof(fstring));
257         decode_urlpart(share, sizeof(fstring));
258         decode_urlpart(user, sizeof(fstring));
259         decode_urlpart(password, sizeof(fstring));
260
261         return 0;
262 }
263
264 /*
265  * Convert an SMB error into a UNIX error ...
266  */
267
268 static int smbc_errno(SMBCCTX *context, struct cli_state *c)
269 {
270         int ret = cli_errno(c);
271         
272         if (cli_is_dos_error(c)) {
273                 uint8 eclass;
274                 uint32 ecode;
275
276                 cli_dos_error(c, &eclass, &ecode);
277                 
278                 DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n", 
279                          (int)eclass, (int)ecode, (int)ecode, ret));
280         } else {
281                 NTSTATUS status;
282
283                 status = cli_nt_error(c);
284
285                 DEBUG(3,("smbc errno %s -> %d\n",
286                          nt_errstr(status), ret));
287         }
288
289         return ret;
290 }
291
292 /* 
293  * Check a server_fd.
294  * returns 0 if the server is in shape. Returns 1 on error 
295  * 
296  * Also useable outside libsmbclient to enable external cache
297  * to do some checks too.
298  */
299 int smbc_check_server(SMBCCTX * context, SMBCSRV * server) 
300 {
301         if ( send_keepalive(server->cli.fd) == False )
302                 return 1;
303
304         /* connection is ok */
305         return 0;
306 }
307
308 /* 
309  * Remove a server from the cached server list it's unused.
310  * On success, 0 is returned. 1 is returned if the server could not be removed.
311  * 
312  * Also useable outside libsmbclient
313  */
314 int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
315 {
316         SMBCFILE * file;
317
318         /* are we being fooled ? */
319         if (!context || !context->internal ||
320             !context->internal->_initialized || !srv) return 1;
321
322         
323         /* Check all open files/directories for a relation with this server */
324         for (file = context->internal->_files; file; file=file->next) {
325                 if (file->srv == srv) {
326                         /* Still used */
327                         DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n", 
328                                   srv, file));
329                         return 1;
330                 }
331         }
332
333         DLIST_REMOVE(context->internal->_servers, srv);
334
335         cli_shutdown(&srv->cli);
336
337         DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
338
339         context->callbacks.remove_cached_srv_fn(context, srv);
340         
341         SAFE_FREE(srv);
342         
343         return 0;
344 }
345
346 /*
347  * Connect to a server, possibly on an existing connection
348  *
349  * Here, what we want to do is: If the server and username
350  * match an existing connection, reuse that, otherwise, establish a 
351  * new connection.
352  *
353  * If we have to create a new connection, call the auth_fn to get the
354  * info we need, unless the username and password were passed in.
355  */
356
357 SMBCSRV *smbc_server(SMBCCTX *context,
358                      const char *server, const char *share, 
359                      fstring workgroup, fstring username, 
360                      fstring password)
361 {
362         SMBCSRV *srv=NULL;
363         int auth_called = 0;
364         struct cli_state c;
365         struct nmb_name called, calling;
366         char *p;
367         const char *server_n = server;
368         fstring group;
369         pstring ipenv;
370         struct in_addr ip;
371         int tried_reverse = 0;
372   
373         zero_ip(&ip);
374         ZERO_STRUCT(c);
375
376         if (server[0] == 0) {
377                 errno = EPERM;
378                 return NULL;
379         }
380
381  check_server_cache:
382
383         srv = context->callbacks.get_cached_srv_fn(context, server, share, 
384                                                    workgroup, username);
385         
386         if (!auth_called && !srv && (!username[0] || !password[0])) {
387                 context->callbacks.auth_fn(server, share, workgroup, sizeof(fstring),
388                              username, sizeof(fstring), password, sizeof(fstring));
389                 /* 
390                  * However, smbc_auth_fn may have picked up info relating to an 
391                  * existing connection, so try for an existing connection again ...
392                  */
393                 auth_called = 1;
394                 goto check_server_cache;
395                 
396         }
397         
398         if (srv) {
399                 if (context->callbacks.check_server_fn(context, srv)) {
400                         /* 
401                          * This server is no good anymore 
402                          * Try to remove it and check for more possible servers in the cache 
403                          */
404                         if (context->callbacks.remove_unused_server_fn(context, srv)) { 
405                                 /* 
406                                  * We could not remove the server completely, remove it from the cache
407                                  * so we will not get it again. It will be removed when the last file/dir
408                                  * is closed.
409                                  */
410                                 context->callbacks.remove_cached_srv_fn(context, srv);
411                         }
412                         
413                         /* 
414                          * Maybe there are more cached connections to this server 
415                          */
416                         goto check_server_cache; 
417                 }
418                 return srv;
419         }
420
421         make_nmb_name(&calling, context->netbios_name, 0x0);
422         make_nmb_name(&called , server, 0x20);
423
424         DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
425   
426         if ((p=strchr_m(server_n,'#')) && 
427             (strcmp(p+1,"1D")==0 || strcmp(p+1,"01")==0)) {
428     
429                 fstrcpy(group, server_n);
430                 p = strchr_m(group,'#');
431                 *p = 0;
432                 
433         }
434
435         DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
436
437  again:
438         slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);
439
440         zero_ip(&ip);
441
442         /* have to open a new connection */
443         if (!cli_initialise(&c)) {
444                 errno = ENOENT;
445                 return NULL;
446         }
447
448         c.timeout = context->timeout;
449
450         if (!cli_connect(&c, server_n, &ip)) {
451                 cli_shutdown(&c);
452                 errno = ENOENT;
453                 return NULL;
454         }
455
456         if (!cli_session_request(&c, &calling, &called)) {
457                 cli_shutdown(&c);
458                 if (strcmp(called.name, "*SMBSERVER")) {
459                         make_nmb_name(&called , "*SMBSERVER", 0x20);
460                         goto again;
461                 }
462                 else {  /* Try one more time, but ensure we don't loop */
463
464                   /* Only try this if server is an IP address ... */
465
466                   if (is_ipaddress(server) && !tried_reverse) {
467                     fstring remote_name;
468                     struct in_addr rem_ip;
469
470                     if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
471                       DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
472                       errno = ENOENT;
473                       return NULL;
474                     }
475
476                     tried_reverse++; /* Yuck */
477
478                     if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
479                       make_nmb_name(&called, remote_name, 0x20);
480                       goto again;
481                     }
482
483
484                   }
485                 }
486                 errno = ENOENT;
487                 return NULL;
488         }
489   
490         DEBUG(4,(" session request ok\n"));
491   
492         if (!cli_negprot(&c)) {
493                 cli_shutdown(&c);
494                 errno = ENOENT;
495                 return NULL;
496         }
497
498         if (!cli_session_setup(&c, username, 
499                                password, strlen(password),
500                                password, strlen(password),
501                                workgroup) &&
502             /* try an anonymous login if it failed */
503             !cli_session_setup(&c, "", "", 1,"", 0, workgroup)) {
504                 cli_shutdown(&c);
505                 errno = EPERM;
506                 return NULL;
507         }
508
509         DEBUG(4,(" session setup ok\n"));
510
511         if (!cli_send_tconX(&c, share, "?????",
512                             password, strlen(password)+1)) {
513                 errno = smbc_errno(context, &c);
514                 cli_shutdown(&c);
515                 return NULL;
516         }
517   
518         DEBUG(4,(" tconx ok\n"));
519   
520         /*
521          * Ok, we have got a nice connection
522          * Let's find a free server_fd 
523          */
524
525         srv = (SMBCSRV *)malloc(sizeof(*srv));
526         if (!srv) {
527                 errno = ENOMEM;
528                 goto failed;
529         }
530
531         ZERO_STRUCTP(srv);
532         srv->cli = c;
533         srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
534
535         /* now add it to the cache (internal or external) */
536         if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username)) {
537                 DEBUG(3, (" Failed to add server to cache\n"));
538                 goto failed;
539         }
540
541         
542         DEBUG(2, ("Server connect ok: //%s/%s: %p\n", 
543                   server, share, srv));
544
545         return srv;
546
547  failed:
548         cli_shutdown(&c);
549         if (!srv) return NULL;
550   
551         SAFE_FREE(srv);
552         return NULL;
553 }
554
555 /*
556  * Routine to open() a file ...
557  */
558
559 static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
560 {
561         fstring server, share, user, password, workgroup;
562         pstring path;
563         SMBCSRV *srv   = NULL;
564         SMBCFILE *file = NULL;
565         int fd;
566
567         if (!context || !context->internal ||
568             !context->internal->_initialized) {
569
570                 errno = EINVAL;  /* Best I can think of ... */
571                 return NULL;
572
573         }
574
575         if (!fname) {
576
577                 errno = EINVAL;
578                 return NULL;
579
580         }
581
582         smbc_parse_path(context, fname, server, share, path, user, password); /* FIXME, check errors */
583
584         if (user[0] == (char)0) fstrcpy(user, context->user);
585
586         fstrcpy(workgroup, context->workgroup);
587
588         srv = smbc_server(context, server, share, workgroup, user, password);
589
590         if (!srv) {
591
592                 if (errno == EPERM) errno = EACCES;
593                 return NULL;  /* smbc_server sets errno */
594     
595         }
596
597         /* Hmmm, the test for a directory is suspect here ... FIXME */
598
599         if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
600     
601                 fd = -1;
602
603         }
604         else {
605           
606                 file = malloc(sizeof(SMBCFILE));
607
608                 if (!file) {
609
610                         errno = ENOMEM;
611                         return NULL;
612
613                 }
614
615                 ZERO_STRUCTP(file);
616
617                 if ((fd = cli_open(&srv->cli, path, flags, DENY_NONE)) < 0) {
618
619                         /* Handle the error ... */
620
621                         SAFE_FREE(file);
622                         errno = smbc_errno(context, &srv->cli);
623                         return NULL;
624
625                 }
626
627                 /* Fill in file struct */
628
629                 file->cli_fd  = fd;
630                 file->fname   = strdup(fname);
631                 file->srv     = srv;
632                 file->offset  = 0;
633                 file->file    = True;
634
635                 DLIST_ADD(context->internal->_files, file);
636                 return file;
637
638         }
639
640         /* Check if opendir needed ... */
641
642         if (fd == -1) {
643                 int eno = 0;
644
645                 eno = smbc_errno(context, &srv->cli);
646                 file = context->opendir(context, fname);
647                 if (!file) errno = eno;
648                 return file;
649
650         }
651
652         errno = EINVAL; /* FIXME, correct errno ? */
653         return NULL;
654
655 }
656
657 /*
658  * Routine to create a file 
659  */
660
661 static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */
662
663 static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
664 {
665
666         if (!context || !context->internal ||
667             !context->internal->_initialized) {
668
669                 errno = EINVAL;
670                 return NULL;
671
672         }
673
674         return smbc_open_ctx(context, path, creat_bits, mode);
675 }
676
677 /*
678  * Routine to read() a file ...
679  */
680
681 static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
682 {
683         int ret;
684
685         if (!context || !context->internal ||
686             !context->internal->_initialized) {
687
688                 errno = EINVAL;
689                 return -1;
690
691         }
692
693         DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));
694
695         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
696
697                 errno = EBADF;
698                 return -1;
699
700         }
701
702         /* Check that the buffer exists ... */
703
704         if (buf == NULL) {
705
706                 errno = EINVAL;
707                 return -1;
708
709         }
710
711         ret = cli_read(&file->srv->cli, file->cli_fd, buf, file->offset, count);
712
713         if (ret < 0) {
714
715                 errno = smbc_errno(context, &file->srv->cli);
716                 return -1;
717
718         }
719
720         file->offset += ret;
721
722         DEBUG(4, ("  --> %d\n", ret));
723
724         return ret;  /* Success, ret bytes of data ... */
725
726 }
727
728 /*
729  * Routine to write() a file ...
730  */
731
732 static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
733 {
734         int ret;
735
736         if (!context || !context->internal ||
737             !context->internal->_initialized) {
738
739                 errno = EINVAL;
740                 return -1;
741
742         }
743
744         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
745
746                 errno = EBADF;
747                 return -1;
748     
749         }
750
751         /* Check that the buffer exists ... */
752
753         if (buf == NULL) {
754
755                 errno = EINVAL;
756                 return -1;
757
758         }
759
760         ret = cli_write(&file->srv->cli, file->cli_fd, 0, buf, file->offset, count);
761
762         if (ret <= 0) {
763
764                 errno = smbc_errno(context, &file->srv->cli);
765                 return -1;
766
767         }
768
769         file->offset += ret;
770
771         return ret;  /* Success, 0 bytes of data ... */
772 }
773  
774 /*
775  * Routine to close() a file ...
776  */
777
778 static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
779 {
780         SMBCSRV *srv; 
781
782         if (!context || !context->internal ||
783             !context->internal->_initialized) {
784
785                 errno = EINVAL;
786                 return -1;
787
788         }
789
790         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
791    
792                 errno = EBADF;
793                 return -1;
794
795         }
796
797         /* IS a dir ... */
798         if (!file->file) {
799                 
800                 return context->closedir(context, file);
801
802         }
803
804         if (!cli_close(&file->srv->cli, file->cli_fd)) {
805
806                 DEBUG(3, ("cli_close failed on %s. purging server.\n", 
807                           file->fname));
808                 /* Deallocate slot and remove the server 
809                  * from the server cache if unused */
810                 errno = smbc_errno(context, &file->srv->cli);  
811                 srv = file->srv;
812                 DLIST_REMOVE(context->internal->_files, file);
813                 SAFE_FREE(file->fname);
814                 SAFE_FREE(file);
815                 context->callbacks.remove_unused_server_fn(context, srv);
816
817                 return -1;
818
819         }
820
821         DLIST_REMOVE(context->internal->_files, file);
822         SAFE_FREE(file->fname);
823         SAFE_FREE(file);
824
825         return 0;
826 }
827
828 /*
829  * Get info from an SMB server on a file. Use a qpathinfo call first
830  * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
831  */
832 static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path, 
833                  uint16 *mode, size_t *size, 
834                  time_t *c_time, time_t *a_time, time_t *m_time,
835                  SMB_INO_T *ino)
836 {
837
838         if (!context || !context->internal ||
839             !context->internal->_initialized) {
840  
841                 errno = EINVAL;
842                 return -1;
843  
844         }
845
846         DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
847   
848         if (!srv->no_pathinfo2 &&
849             cli_qpathinfo2(&srv->cli, path, c_time, a_time, m_time, NULL,
850                            size, mode, ino)) return True;
851
852         /* if this is NT then don't bother with the getatr */
853         if (srv->cli.capabilities & CAP_NT_SMBS) return False;
854
855         if (cli_getatr(&srv->cli, path, mode, size, m_time)) {
856                 a_time = c_time = m_time;
857                 srv->no_pathinfo2 = True;
858                 return True;
859         }
860
861         return False;
862
863 }
864
865 /*
866  * Routine to unlink() a file
867  */
868
869 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
870 {
871         fstring server, share, user, password, workgroup;
872         pstring path;
873         SMBCSRV *srv = NULL;
874
875         if (!context || !context->internal ||
876             !context->internal->_initialized) {
877
878                 errno = EINVAL;  /* Best I can think of ... */
879                 return -1;
880
881         }
882
883         if (!fname) {
884
885                 errno = EINVAL;
886                 return -1;
887
888         }
889
890         smbc_parse_path(context, fname, server, share, path, user, password); /* FIXME, check errors */
891
892         if (user[0] == (char)0) fstrcpy(user, context->user);
893
894         fstrcpy(workgroup, context->workgroup);
895
896         srv = smbc_server(context, server, share, workgroup, user, password);
897
898         if (!srv) {
899
900                 return -1;  /* smbc_server sets errno */
901
902         }
903
904         /*  if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
905
906     int job = smbc_stat_printjob(srv, path, NULL, NULL);
907     if (job == -1) {
908
909       return -1;
910
911     }
912     if ((err = cli_printjob_del(&srv->cli, job)) != 0) {
913
914     
915       return -1;
916
917     }
918     } else */
919
920         if (!cli_unlink(&srv->cli, path)) {
921
922                 errno = smbc_errno(context, &srv->cli);
923
924                 if (errno == EACCES) { /* Check if the file is a directory */
925
926                         int saverr = errno;
927                         size_t size = 0;
928                         uint16 mode = 0;
929                         time_t m_time = 0, a_time = 0, c_time = 0;
930                         SMB_INO_T ino = 0;
931
932                         if (!smbc_getatr(context, srv, path, &mode, &size,
933                                          &c_time, &a_time, &m_time, &ino)) {
934
935                                 /* Hmmm, bad error ... What? */
936
937                                 errno = smbc_errno(context, &srv->cli);
938                                 return -1;
939
940                         }
941                         else {
942
943                                 if (IS_DOS_DIR(mode))
944                                         errno = EISDIR;
945                                 else
946                                         errno = saverr;  /* Restore this */
947
948                         }
949                 }
950
951                 return -1;
952
953         }
954
955         return 0;  /* Success ... */
956
957 }
958
959 /*
960  * Routine to rename() a file
961  */
962
963 static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname, 
964                            SMBCCTX *ncontext, const char *nname)
965 {
966         fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
967         pstring path1, path2;
968         SMBCSRV *srv = NULL;
969
970         if (!ocontext || !ncontext || 
971             !ocontext->internal || !ncontext->internal ||
972             !ocontext->internal->_initialized || 
973             !ncontext->internal->_initialized) {
974
975                 errno = EINVAL;  /* Best I can think of ... */
976                 return -1;
977
978         }
979         
980         if (!oname || !nname) {
981
982                 errno = EINVAL;
983                 return -1;
984
985         }
986         
987         DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));
988
989         smbc_parse_path(ocontext, oname, server1, share1, path1, user1, password1);
990
991         if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);
992
993         smbc_parse_path(ncontext, nname, server2, share2, path2, user2, password2);
994
995         if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);
996
997         if (strcmp(server1, server2) || strcmp(share1, share2) ||
998             strcmp(user1, user2)) {
999
1000                 /* Can't rename across file systems, or users?? */
1001
1002                 errno = EXDEV;
1003                 return -1;
1004
1005         }
1006
1007         fstrcpy(workgroup, ocontext->workgroup);
1008         /* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */ 
1009         srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
1010         if (!srv) {
1011
1012                 return -1;
1013
1014         }
1015
1016         if (!cli_rename(&srv->cli, path1, path2)) {
1017                 int eno = smbc_errno(ocontext, &srv->cli);
1018
1019                 if (eno != EEXIST ||
1020                     !cli_unlink(&srv->cli, path2) ||
1021                     !cli_rename(&srv->cli, path1, path2)) {
1022
1023                         errno = eno;
1024                         return -1;
1025
1026                 }
1027         }
1028
1029         return 0; /* Success */
1030
1031 }
1032
1033 /*
1034  * A routine to lseek() a file
1035  */
1036
1037 static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
1038 {
1039         size_t size;
1040
1041         if (!context || !context->internal ||
1042             !context->internal->_initialized) {
1043
1044                 errno = EINVAL;
1045                 return -1;
1046                 
1047         }
1048
1049         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1050
1051                 errno = EBADF;
1052                 return -1;
1053
1054         }
1055
1056         if (!file->file) {
1057
1058                 errno = EINVAL;
1059                 return -1;      /* Can't lseek a dir ... */
1060
1061         }
1062
1063         switch (whence) {
1064         case SEEK_SET:
1065                 file->offset = offset;
1066                 break;
1067
1068         case SEEK_CUR:
1069                 file->offset += offset;
1070                 break;
1071
1072         case SEEK_END:
1073                 if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
1074                                    NULL, NULL, NULL)) 
1075                 {
1076                     SMB_BIG_UINT b_size = size;
1077                     if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
1078                                       NULL)) 
1079                     {
1080                         errno = EINVAL;
1081                         return -1;
1082                     } else
1083                         size = b_size;
1084                 }
1085                 file->offset = size + offset;
1086                 break;
1087
1088         default:
1089                 errno = EINVAL;
1090                 break;
1091
1092         }
1093
1094         return file->offset;
1095
1096 }
1097
1098 /* 
1099  * Generate an inode number from file name for those things that need it
1100  */
1101
1102 static
1103 ino_t smbc_inode(SMBCCTX *context, const char *name)
1104 {
1105
1106         if (!context || !context->internal ||
1107             !context->internal->_initialized) {
1108
1109                 errno = EINVAL;
1110                 return -1;
1111
1112         }
1113
1114         if (!*name) return 2; /* FIXME, why 2 ??? */
1115         return (ino_t)str_checksum(name);
1116
1117 }
1118
1119 /*
1120  * Routine to put basic stat info into a stat structure ... Used by stat and
1121  * fstat below.
1122  */
1123
1124 static
1125 int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname, size_t size, int mode)
1126 {
1127         
1128         st->st_mode = 0;
1129
1130         if (IS_DOS_DIR(mode)) {
1131                 st->st_mode = SMBC_DIR_MODE;
1132         } else {
1133                 st->st_mode = SMBC_FILE_MODE;
1134         }
1135
1136         if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
1137         if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
1138         if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
1139         if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;
1140
1141         st->st_size = size;
1142         st->st_blksize = 512;
1143         st->st_blocks = (size+511)/512;
1144         st->st_uid = getuid();
1145         st->st_gid = getgid();
1146
1147         if (IS_DOS_DIR(mode)) {
1148                 st->st_nlink = 2;
1149         } else {
1150                 st->st_nlink = 1;
1151         }
1152
1153         if (st->st_ino == 0) {
1154                 st->st_ino = smbc_inode(context, fname);
1155         }
1156         
1157         return True;  /* FIXME: Is this needed ? */
1158
1159 }
1160
1161 /*
1162  * Routine to stat a file given a name
1163  */
1164
1165 static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
1166 {
1167         SMBCSRV *srv;
1168         fstring server, share, user, password, workgroup;
1169         pstring path;
1170         time_t m_time = 0, a_time = 0, c_time = 0;
1171         size_t size = 0;
1172         uint16 mode = 0;
1173         SMB_INO_T ino = 0;
1174
1175         if (!context || !context->internal ||
1176             !context->internal->_initialized) {
1177
1178                 errno = EINVAL;  /* Best I can think of ... */
1179                 return -1;
1180     
1181         }
1182
1183         if (!fname) {
1184
1185                 errno = EINVAL;
1186                 return -1;
1187
1188         }
1189   
1190         DEBUG(4, ("smbc_stat(%s)\n", fname));
1191
1192         smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
1193
1194         if (user[0] == (char)0) fstrcpy(user, context->user);
1195
1196         fstrcpy(workgroup, context->workgroup);
1197
1198         srv = smbc_server(context, server, share, workgroup, user, password);
1199
1200         if (!srv) {
1201
1202                 return -1;  /* errno set by smbc_server */
1203
1204         }
1205
1206         /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
1207
1208            mode = aDIR | aRONLY;
1209
1210            }
1211            else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
1212            
1213            if (strcmp(path, "\\") == 0) {
1214            
1215            mode = aDIR | aRONLY;
1216
1217            }
1218            else {
1219
1220            mode = aRONLY;
1221            smbc_stat_printjob(srv, path, &size, &m_time);
1222            c_time = a_time = m_time;
1223
1224            }
1225            else { */
1226
1227         if (!smbc_getatr(context, srv, path, &mode, &size, 
1228                          &c_time, &a_time, &m_time, &ino)) {
1229
1230                 errno = smbc_errno(context, &srv->cli);
1231                 return -1;
1232                 
1233         }
1234
1235         st->st_ino = ino;
1236
1237         smbc_setup_stat(context, st, path, size, mode);
1238
1239         st->st_atime = a_time;
1240         st->st_ctime = c_time;
1241         st->st_mtime = m_time;
1242         st->st_dev   = srv->dev;
1243
1244         return 0;
1245
1246 }
1247
1248 /*
1249  * Routine to stat a file given an fd
1250  */
1251
1252 static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
1253 {
1254         time_t c_time, a_time, m_time;
1255         size_t size;
1256         uint16 mode;
1257         SMB_INO_T ino = 0;
1258
1259         if (!context || !context->internal ||
1260             !context->internal->_initialized) {
1261
1262                 errno = EINVAL;
1263                 return -1;
1264
1265         }
1266
1267         if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
1268
1269                 errno = EBADF;
1270                 return -1;
1271
1272         }
1273
1274         if (!file->file) {
1275
1276                 return context->fstatdir(context, file, st);
1277
1278         }
1279
1280         if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
1281                            &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
1282             SMB_BIG_UINT b_size = size;
1283             if (!cli_getattrE(&file->srv->cli, file->cli_fd,
1284                           &mode, &b_size, &c_time, &a_time, &m_time)) {
1285
1286                 errno = EINVAL;
1287                 return -1;
1288             } else
1289                 size = b_size;
1290
1291         }
1292
1293         st->st_ino = ino;
1294
1295         smbc_setup_stat(context, st, file->fname, size, mode);
1296
1297         st->st_atime = a_time;
1298         st->st_ctime = c_time;
1299         st->st_mtime = m_time;
1300         st->st_dev = file->srv->dev;
1301
1302         return 0;
1303
1304 }
1305
1306 /*
1307  * Routine to open a directory
1308  *
1309  * We want to allow:
1310  *
1311  * smb: which should list all the workgroups available
1312  * smb:workgroup
1313  * smb:workgroup//server
1314  * smb://server
1315  * smb://server/share
1316  * smb://<IP-addr> which should list shares on server
1317  * smb://<IP-addr>/share which should list files on share
1318  */
1319
1320 static void smbc_remove_dir(SMBCFILE *dir)
1321 {
1322         struct smbc_dir_list *d,*f;
1323
1324         d = dir->dir_list;
1325         while (d) {
1326
1327                 f = d; d = d->next;
1328
1329                 SAFE_FREE(f->dirent);
1330                 SAFE_FREE(f);
1331
1332         }
1333
1334         dir->dir_list = dir->dir_end = dir->dir_next = NULL;
1335
1336 }
1337
1338 static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
1339 {
1340         struct smbc_dirent *dirent;
1341         int size;
1342         char *u_name = NULL, *u_comment = NULL;
1343         size_t u_name_len = 0, u_comment_len = 0;
1344
1345         if (name)
1346             u_name_len = push_utf8_allocate(&u_name, name);
1347         if (comment)
1348             u_comment_len = push_utf8_allocate(&u_comment, comment);
1349
1350         /*
1351          * Allocate space for the dirent, which must be increased by the 
1352          * size of the name and the comment and 1 for the null on the comment.
1353          * The null on the name is already accounted for.
1354          */
1355
1356         size = sizeof(struct smbc_dirent) + u_name_len + u_comment_len + 1;
1357     
1358         dirent = malloc(size);
1359
1360         if (!dirent) {
1361
1362                 dir->dir_error = ENOMEM;
1363                 return -1;
1364
1365         }
1366
1367         ZERO_STRUCTP(dirent);
1368
1369         if (dir->dir_list == NULL) {
1370
1371                 dir->dir_list = malloc(sizeof(struct smbc_dir_list));
1372                 if (!dir->dir_list) {
1373
1374                         SAFE_FREE(dirent);
1375                         dir->dir_error = ENOMEM;
1376                         return -1;
1377
1378                 }
1379                 ZERO_STRUCTP(dir->dir_list);
1380
1381                 dir->dir_end = dir->dir_next = dir->dir_list;
1382   
1383         }
1384         else {
1385
1386                 dir->dir_end->next = malloc(sizeof(struct smbc_dir_list));
1387                 
1388                 if (!dir->dir_end->next) {
1389                         
1390                         SAFE_FREE(dirent);
1391                         dir->dir_error = ENOMEM;
1392                         return -1;
1393
1394                 }
1395                 ZERO_STRUCTP(dir->dir_end->next);
1396
1397                 dir->dir_end = dir->dir_end->next;
1398
1399         }
1400
1401         dir->dir_end->next = NULL;
1402         dir->dir_end->dirent = dirent;
1403         
1404         dirent->smbc_type = type;
1405         dirent->namelen = u_name_len;
1406         dirent->commentlen = u_comment_len;
1407         dirent->dirlen = size;
1408   
1409         strncpy(dirent->name, (u_name?u_name:""), dirent->namelen + 1);
1410
1411         dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
1412         strncpy(dirent->comment, (u_comment?u_comment:""), dirent->commentlen + 1);
1413         
1414         SAFE_FREE(u_comment);
1415         SAFE_FREE(u_name);
1416
1417         return 0;
1418
1419 }
1420
1421 static void
1422 list_fn(const char *name, uint32 type, const char *comment, void *state)
1423 {
1424         SMBCFILE *dir = (SMBCFILE *)state;
1425         int dirent_type;
1426
1427         /* We need to process the type a little ... */
1428
1429         if (dir->dir_type == SMBC_FILE_SHARE) {
1430                 
1431                 switch (type) {
1432                 case 0: /* Directory tree */
1433                         dirent_type = SMBC_FILE_SHARE;
1434                         break;
1435
1436                 case 1:
1437                         dirent_type = SMBC_PRINTER_SHARE;
1438                         break;
1439
1440                 case 2:
1441                         dirent_type = SMBC_COMMS_SHARE;
1442                         break;
1443
1444                 case 3:
1445                         dirent_type = SMBC_IPC_SHARE;
1446                         break;
1447
1448                 default:
1449                         dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
1450                         break;
1451                 }
1452         }
1453         else dirent_type = dir->dir_type;
1454
1455         if (add_dirent(dir, name, comment, dirent_type) < 0) {
1456
1457                 /* An error occurred, what do we do? */
1458                 /* FIXME: Add some code here */
1459
1460         }
1461
1462 }
1463
1464 static void
1465 dir_list_fn(file_info *finfo, const char *mask, void *state)
1466 {
1467
1468         if (add_dirent((SMBCFILE *)state, finfo->name, "", 
1469                        (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {
1470
1471                 /* Handle an error ... */
1472
1473                 /* FIXME: Add some code ... */
1474
1475         } 
1476
1477 }
1478
1479
1480 /* Return the IP address and workgroup of a master browser on the 
1481    network. */
1482
1483 static BOOL find_master_ip_bcast(pstring workgroup, struct in_addr *server_ip)
1484 {
1485         struct in_addr *ip_list;
1486         int i, count;
1487
1488         /* Go looking for workgroups by broadcasting on the local network */ 
1489
1490         if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
1491                 return False;
1492         }
1493
1494         for (i = count-1; i < count; i++) {
1495                 static fstring name;
1496
1497                 DEBUG(0, ("name_status_find %d %s\n", i, inet_ntoa(ip_list[i])));
1498
1499                 if (!name_status_find("*", 0, 0x1d, ip_list[i], name))
1500                         continue;
1501
1502                 if (!find_master_ip(name, server_ip))
1503                         continue;
1504
1505                 pstrcpy(workgroup, name);
1506
1507                 DEBUG(4, ("found master browser %s, %s\n", 
1508                           name, inet_ntoa(ip_list[i])));
1509
1510                 return True;
1511         }
1512
1513         return False;
1514 }
1515
1516 static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
1517 {
1518         fstring server, share, user, password;
1519         pstring workgroup;
1520         pstring path;
1521         SMBCSRV *srv  = NULL;
1522         SMBCFILE *dir = NULL;
1523         struct in_addr rem_ip;
1524
1525         if (!context || !context->internal ||
1526             !context->internal->_initialized) {
1527                 DEBUG(4, ("no valid context\n"));
1528                 errno = EINVAL;
1529                 return NULL;
1530
1531         }
1532
1533         if (!fname) {
1534                 DEBUG(4, ("no valid fname\n"));
1535                 errno = EINVAL;
1536                 return NULL;
1537         }
1538
1539         if (smbc_parse_path(context, fname, server, share, path, user, password)) {
1540                 DEBUG(4, ("no valid path\n"));
1541                 errno = EINVAL;
1542                 return NULL;
1543         }
1544
1545         DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s'\n", fname, server, share, path));
1546
1547         if (user[0] == (char)0) fstrcpy(user, context->user);
1548
1549         pstrcpy(workgroup, context->workgroup);
1550
1551         dir = malloc(sizeof(*dir));
1552
1553         if (!dir) {
1554
1555                 errno = ENOMEM;
1556                 return NULL;
1557
1558         }
1559
1560         ZERO_STRUCTP(dir);
1561
1562         dir->cli_fd   = 0;
1563         dir->fname    = strdup(fname);
1564         dir->srv      = NULL;
1565         dir->offset   = 0;
1566         dir->file     = False;
1567         dir->dir_list = dir->dir_next = dir->dir_end = NULL;
1568
1569         if (server[0] == (char)0) {
1570             struct in_addr server_ip;
1571                 DEBUG(4, ("empty server\n"));
1572                 if (share[0] != (char)0 || path[0] != (char)0) {
1573                     DEBUG(4,("share %d path %d\n", share[0], path[0]));
1574                         errno = EINVAL;
1575                         if (dir) {
1576                                 SAFE_FREE(dir->fname);
1577                                 SAFE_FREE(dir);
1578                         }
1579                         return NULL;
1580                 }
1581
1582                 /* We have server and share and path empty ... so list the workgroups */
1583                 /* first try to get the LMB for our workgroup, and if that fails,     */
1584                 /* try the DMB                                                        */
1585
1586                 pstrcpy(workgroup, lp_workgroup());
1587
1588                 if (!find_master_ip(lp_workgroup(), &server_ip)) {
1589                     DEBUG(4, ("Unable to find master browser for workgroup %s\n", 
1590                               workgroup));
1591                     if (!find_master_ip_bcast(workgroup, &server_ip)) {
1592                         DEBUG(4, ("Unable to find master browser by "
1593                                   "broadcast\n"));
1594                         errno = ENOENT;
1595                         return NULL;
1596                     }
1597                 }       
1598
1599                /*
1600                 * Get a connection to IPC$ on the server if we do not already have one
1601                 */
1602
1603                srv = smbc_server(context, inet_ntoa(server_ip), "IPC$", workgroup, user, password);
1604
1605                if (!srv) {
1606                    
1607                    if (dir) {
1608                        SAFE_FREE(dir->fname);
1609                        SAFE_FREE(dir);
1610                    }
1611                    return NULL;
1612                }
1613                    
1614                 dir->srv = srv;
1615                 dir->dir_type = SMBC_WORKGROUP;
1616
1617                 /* Now, list the stuff ... */
1618
1619                 if (!cli_NetServerEnum(&srv->cli, workgroup, SV_TYPE_DOMAIN_ENUM, list_fn,
1620                                        (void *)dir)) {
1621
1622                         if (dir) {
1623                                 SAFE_FREE(dir->fname);
1624                                 SAFE_FREE(dir);
1625                         }
1626                         errno = cli_errno(&srv->cli);
1627
1628                         return NULL;
1629
1630                 }
1631         }
1632         else { /* Server not an empty string ... Check the rest and see what gives */
1633
1634                 if (share[0] == (char)0) {
1635
1636                         if (path[0] != (char)0) { /* Should not have empty share with path */
1637
1638                                 errno = EINVAL;
1639                                 if (dir) {
1640                                         SAFE_FREE(dir->fname);
1641                                         SAFE_FREE(dir);
1642                                 }
1643                                 return NULL;
1644         
1645                         }
1646
1647                         /* Check to see if <server><1D>, <server><1B>, or <server><20> translates */
1648                         /* However, we check to see if <server> is an IP address first */
1649
1650                         if (!is_ipaddress(server) &&  /* Not an IP addr so check next */
1651                             (resolve_name(server, &rem_ip, 0x1d) ||   /* Found LMB */
1652                                     resolve_name(server, &rem_ip, 0x1b) )) { /* Found DMB */
1653                                 pstring buserver;
1654
1655                                 dir->dir_type = SMBC_SERVER;
1656
1657                                 /*
1658                                  * Get the backup list ...
1659                                  */
1660
1661
1662                                 if (!name_status_find("*", 0, 0, rem_ip, buserver)) {
1663
1664                                         DEBUG(0, ("Could not get name of local/domain master browser for server %s\n", server));
1665                                         errno = EPERM;  /* FIXME, is this correct */
1666                                         return NULL;
1667
1668                                 }
1669
1670                                 /*
1671                                  * Get a connection to IPC$ on the server if we do not already have one
1672                                  */
1673
1674                                 srv = smbc_server(context, buserver, "IPC$", workgroup, user, password);
1675
1676                                 if (!srv) {
1677                                         DEBUG(0, ("got no contact to IPC$\n"));
1678                                         if (dir) {
1679                                                 SAFE_FREE(dir->fname);
1680                                                 SAFE_FREE(dir);
1681                                         }
1682                                         return NULL;
1683
1684                                 }
1685
1686                                 dir->srv = srv;
1687
1688                                 /* Now, list the servers ... */
1689
1690                                 if (!cli_NetServerEnum(&srv->cli, server, 0x0000FFFE, list_fn,
1691                                                        (void *)dir)) {
1692
1693                                         if (dir) {
1694                                                 SAFE_FREE(dir->fname);
1695                                                 SAFE_FREE(dir);
1696                                         }
1697                                         errno = cli_errno(&srv->cli);
1698                                         return NULL;
1699                                         
1700                                 }
1701
1702                         }
1703                         else {
1704
1705                                 if (resolve_name(server, &rem_ip, 0x20)) {
1706
1707                                         /* Now, list the shares ... */
1708
1709                                         dir->dir_type = SMBC_FILE_SHARE;
1710
1711                                         srv = smbc_server(context, server, "IPC$", workgroup, user, password);
1712
1713                                         if (!srv) {
1714
1715                                                 if (dir) {
1716                                                         SAFE_FREE(dir->fname);
1717                                                         SAFE_FREE(dir);
1718                                                 }
1719                                                 return NULL;
1720
1721                                         }
1722
1723                                         dir->srv = srv;
1724
1725                                         /* Now, list the servers ... */
1726
1727                                         if (cli_RNetShareEnum(&srv->cli, list_fn, 
1728                                                               (void *)dir) < 0) {
1729
1730                                                 errno = cli_errno(&srv->cli);
1731                                                 if (dir) {
1732                                                         SAFE_FREE(dir->fname);
1733                                                         SAFE_FREE(dir);
1734                                                 }
1735                                                 return NULL;
1736
1737                                         }
1738
1739                                 }
1740                                 else {
1741
1742                                         errno = ENODEV;   /* Neither the workgroup nor server exists */
1743                                         if (dir) {
1744                                                 SAFE_FREE(dir->fname);
1745                                                 SAFE_FREE(dir);
1746                                         }
1747                                         return NULL;
1748
1749                                 }
1750
1751                         }
1752
1753                 }
1754                 else { /* The server and share are specified ... work from there ... */
1755
1756                         /* Well, we connect to the server and list the directory */
1757
1758                         dir->dir_type = SMBC_FILE_SHARE;
1759
1760                         srv = smbc_server(context, server, share, workgroup, user, password);
1761
1762                         if (!srv) {
1763
1764                                 if (dir) {
1765                                         SAFE_FREE(dir->fname);
1766                                         SAFE_FREE(dir);
1767                                 }
1768                                 return NULL;
1769
1770                         }
1771
1772                         dir->srv = srv;
1773
1774                         /* Now, list the files ... */
1775
1776                         pstrcat(path, "\\*");
1777
1778                         if (cli_list(&srv->cli, path, aDIR | aSYSTEM | aHIDDEN, dir_list_fn, 
1779                                      (void *)dir) < 0) {
1780
1781                                 if (dir) {
1782                                         SAFE_FREE(dir->fname);
1783                                         SAFE_FREE(dir);
1784                                 }
1785                                 errno = smbc_errno(context, &srv->cli);
1786                                 return NULL;
1787
1788                         }
1789                 }
1790
1791         }
1792
1793         DLIST_ADD(context->internal->_files, dir);
1794         return dir;
1795
1796 }
1797
1798 /*
1799  * Routine to close a directory
1800  */
1801
1802 static int smbc_closedir_ctx(SMBCCTX *context, SMBCFILE *dir)
1803 {
1804
1805         if (!context || !context->internal ||
1806             !context->internal->_initialized) {
1807
1808                 errno = EINVAL;
1809                 return -1;
1810
1811         }
1812
1813         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
1814
1815                 errno = EBADF;
1816                 return -1;
1817     
1818         }
1819
1820         smbc_remove_dir(dir); /* Clean it up */
1821
1822         DLIST_REMOVE(context->internal->_files, dir);
1823
1824         if (dir) {
1825
1826                 SAFE_FREE(dir->fname);
1827                 SAFE_FREE(dir);    /* Free the space too */
1828
1829         }
1830
1831         return 0;
1832
1833 }
1834
1835 /*
1836  * Routine to get a directory entry
1837  */
1838
1839 struct smbc_dirent *smbc_readdir_ctx(SMBCCTX *context, SMBCFILE *dir)
1840 {
1841         struct smbc_dirent *dirp, *dirent;
1842
1843         /* Check that all is ok first ... */
1844
1845         if (!context || !context->internal ||
1846             !context->internal->_initialized) {
1847
1848                 errno = EINVAL;
1849                 return NULL;
1850
1851         }
1852
1853         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
1854
1855                 errno = EBADF;
1856                 return NULL;
1857
1858         }
1859
1860         if (dir->file != False) { /* FIXME, should be dir, perhaps */
1861
1862                 errno = ENOTDIR;
1863                 return NULL;
1864
1865         }
1866
1867         if (!dir->dir_next)
1868                 return NULL;
1869         else {
1870
1871                 dirent = dir->dir_next->dirent;
1872
1873                 if (!dirent) {
1874
1875                         errno = ENOENT;
1876                         return NULL;
1877
1878                 }
1879
1880                 /* Hmmm, do I even need to copy it? */
1881
1882                 memcpy(context->internal->_dirent, dirent, dirent->dirlen); /* Copy the dirent */
1883                 dirp = (struct smbc_dirent *)context->internal->_dirent;
1884                 dirp->comment = (char *)(&dirp->name + dirent->namelen + 1);
1885                 dir->dir_next = dir->dir_next->next;
1886
1887                 return (struct smbc_dirent *)context->internal->_dirent;
1888         }
1889
1890 }
1891
1892 /*
1893  * Routine to get directory entries
1894  */
1895
1896 static int smbc_getdents_ctx(SMBCCTX *context, SMBCFILE *dir, struct smbc_dirent *dirp, int count)
1897 {
1898         struct smbc_dir_list *dirlist;
1899         int rem = count, reqd;
1900         char *ndir = (char *)dirp;
1901
1902         /* Check that all is ok first ... */
1903
1904         if (!context || !context->internal ||
1905             !context->internal->_initialized) {
1906
1907                 errno = EINVAL;
1908                 return -1;
1909
1910         }
1911
1912         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
1913
1914                 errno = EBADF;
1915                 return -1;
1916     
1917         }
1918
1919         if (dir->file != False) { /* FIXME, should be dir, perhaps */
1920
1921                 errno = ENOTDIR;
1922                 return -1;
1923
1924         }
1925
1926         /* 
1927          * Now, retrieve the number of entries that will fit in what was passed
1928          * We have to figure out if the info is in the list, or we need to 
1929          * send a request to the server to get the info.
1930          */
1931
1932         while ((dirlist = dir->dir_next)) {
1933                 struct smbc_dirent *dirent;
1934
1935                 if (!dirlist->dirent) {
1936
1937                         errno = ENOENT;  /* Bad error */
1938                         return -1;
1939
1940                 }
1941
1942                 if (rem < (reqd = (sizeof(struct smbc_dirent) + dirlist->dirent->namelen + 
1943                                    dirlist->dirent->commentlen + 1))) {
1944
1945                         if (rem < count) { /* We managed to copy something */
1946
1947                                 errno = 0;
1948                                 return count - rem;
1949
1950                         }
1951                         else { /* Nothing copied ... */
1952
1953                                 errno = EINVAL;  /* Not enough space ... */
1954                                 return -1;
1955
1956                         }
1957
1958                 }
1959
1960                 dirent = dirlist->dirent;
1961
1962                 memcpy(ndir, dirent, reqd); /* Copy the data in ... */
1963     
1964                 ((struct smbc_dirent *)ndir)->comment = 
1965                         (char *)(&((struct smbc_dirent *)ndir)->name + dirent->namelen + 1);
1966
1967                 ndir += reqd;
1968
1969                 rem -= reqd;
1970
1971                 dir->dir_next = dirlist = dirlist -> next;
1972         }
1973
1974         if (rem == count)
1975                 return 0;
1976         else 
1977                 return count - rem;
1978
1979 }
1980
1981 /*
1982  * Routine to create a directory ...
1983  */
1984
1985 static int smbc_mkdir_ctx(SMBCCTX *context, const char *fname, mode_t mode)
1986 {
1987         SMBCSRV *srv;
1988         fstring server, share, user, password, workgroup;
1989         pstring path;
1990
1991         if (!context || !context->internal || 
1992             !context->internal->_initialized) {
1993
1994                 errno = EINVAL;
1995                 return -1;
1996
1997         }
1998
1999         if (!fname) {
2000
2001                 errno = EINVAL;
2002                 return -1;
2003
2004         }
2005   
2006         DEBUG(4, ("smbc_mkdir(%s)\n", fname));
2007
2008         smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
2009
2010         if (user[0] == (char)0) fstrcpy(user, context->user);
2011
2012         fstrcpy(workgroup, context->workgroup);
2013
2014         srv = smbc_server(context, server, share, workgroup, user, password);
2015
2016         if (!srv) {
2017
2018                 return -1;  /* errno set by smbc_server */
2019
2020         }
2021
2022         /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2023
2024            mode = aDIR | aRONLY;
2025
2026            }
2027            else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2028
2029            if (strcmp(path, "\\") == 0) {
2030
2031            mode = aDIR | aRONLY;
2032
2033            }
2034            else {
2035
2036            mode = aRONLY;
2037            smbc_stat_printjob(srv, path, &size, &m_time);
2038            c_time = a_time = m_time;
2039
2040            }
2041            else { */
2042
2043         if (!cli_mkdir(&srv->cli, path)) {
2044
2045                 errno = smbc_errno(context, &srv->cli);
2046                 return -1;
2047
2048         } 
2049
2050         return 0;
2051
2052 }
2053
2054 /*
2055  * Our list function simply checks to see if a directory is not empty
2056  */
2057
2058 static int smbc_rmdir_dirempty = True;
2059
2060 static void rmdir_list_fn(file_info *finfo, const char *mask, void *state)
2061 {
2062
2063         if (strncmp(finfo->name, ".", 1) != 0 && strncmp(finfo->name, "..", 2) != 0)
2064                 smbc_rmdir_dirempty = False;
2065
2066 }
2067
2068 /*
2069  * Routine to remove a directory
2070  */
2071
2072 static int smbc_rmdir_ctx(SMBCCTX *context, const char *fname)
2073 {
2074         SMBCSRV *srv;
2075         fstring server, share, user, password, workgroup;
2076         pstring path;
2077
2078         if (!context || !context->internal || 
2079             !context->internal->_initialized) {
2080
2081                 errno = EINVAL;
2082                 return -1;
2083
2084         }
2085
2086         if (!fname) {
2087
2088                 errno = EINVAL;
2089                 return -1;
2090
2091         }
2092   
2093         DEBUG(4, ("smbc_rmdir(%s)\n", fname));
2094
2095         smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
2096
2097         if (user[0] == (char)0) fstrcpy(user, context->user);
2098
2099         fstrcpy(workgroup, context->workgroup);
2100
2101         srv = smbc_server(context, server, share, workgroup, user, password);
2102
2103         if (!srv) {
2104
2105                 return -1;  /* errno set by smbc_server */
2106
2107         }
2108
2109         /* if (strncmp(srv->cli.dev, "IPC", 3) == 0) {
2110
2111            mode = aDIR | aRONLY;
2112
2113            }
2114            else if (strncmp(srv->cli.dev, "LPT", 3) == 0) {
2115
2116            if (strcmp(path, "\\") == 0) {
2117
2118            mode = aDIR | aRONLY;
2119
2120            }
2121            else {
2122
2123            mode = aRONLY;
2124            smbc_stat_printjob(srv, path, &size, &m_time);
2125            c_time = a_time = m_time;
2126            
2127            }
2128            else { */
2129
2130         if (!cli_rmdir(&srv->cli, path)) {
2131
2132                 errno = smbc_errno(context, &srv->cli);
2133
2134                 if (errno == EACCES) {  /* Check if the dir empty or not */
2135
2136                         pstring lpath; /* Local storage to avoid buffer overflows */
2137
2138                         smbc_rmdir_dirempty = True;  /* Make this so ... */
2139
2140                         pstrcpy(lpath, path);
2141                         pstrcat(lpath, "\\*");
2142
2143                         if (cli_list(&srv->cli, lpath, aDIR | aSYSTEM | aHIDDEN, rmdir_list_fn,
2144                                      NULL) < 0) {
2145
2146                                 /* Fix errno to ignore latest error ... */
2147
2148                                 DEBUG(5, ("smbc_rmdir: cli_list returned an error: %d\n", 
2149                                           smbc_errno(context, &srv->cli)));
2150                                 errno = EACCES;
2151
2152                         }
2153
2154                         if (smbc_rmdir_dirempty)
2155                                 errno = EACCES;
2156                         else
2157                                 errno = ENOTEMPTY;
2158
2159                 }
2160
2161                 return -1;
2162
2163         } 
2164
2165         return 0;
2166
2167 }
2168
2169 /*
2170  * Routine to return the current directory position
2171  */
2172
2173 static off_t smbc_telldir_ctx(SMBCCTX *context, SMBCFILE *dir)
2174 {
2175         off_t ret_val; /* Squash warnings about cast */
2176
2177         if (!context || !context->internal ||
2178             !context->internal->_initialized) {
2179
2180                 errno = EINVAL;
2181                 return -1;
2182
2183         }
2184
2185         if (!dir || !DLIST_CONTAINS(context->internal->_files, dir)) {
2186
2187                 errno = EBADF;
2188                 return -1;
2189
2190         }
2191
2192         if (dir->file != False) { /* FIXME, should be dir, perhaps */
2193
2194                 errno = ENOTDIR;
2195                 return -1;
2196
2197         }
2198
2199         /*
2200          * We return the pointer here as the offset
2201          */
2202         ret_val = (int)dir->dir_next;
2203         return ret_val;
2204
2205 }
2206
2207 /*
2208  * A routine to run down the list and see if the entry is OK
2209  */
2210
2211 struct smbc_dir_list *smbc_check_dir_ent(struct smbc_dir_list *list, 
2212                                          struct smbc_dirent *dirent)
2213 {
2214
2215         /* Run down the list looking for what we want */
2216
2217         if (dirent) {
2218
2219                 struct smbc_dir_list *tmp = list;
2220
2221                 while (tmp) {
2222
2223                         if (tmp->dirent == dirent)
2224                                 return tmp;
2225
2226                         tmp = tmp->next;
2227
2228                 }
2229
2230         }
2231
2232         return NULL;  /* Not found, or an error */
2233
2234 }
2235
2236
2237 /*
2238  * Routine to seek on a directory
2239  */
2240
2241 static int smbc_lseekdir_ctx(SMBCCTX *context, SMBCFILE *dir, off_t offset)
2242 {
2243         long int l_offset = offset;  /* Handle problems of size */
2244         struct smbc_dirent *dirent = (struct smbc_dirent *)l_offset;
2245         struct smbc_dir_list *list_ent = (struct smbc_dir_list *)NULL;
2246
2247         if (!context || !context->internal ||
2248             !context->internal->_initialized) {
2249
2250                 errno = EINVAL;
2251                 return -1;
2252
2253         }
2254
2255         if (dir->file != False) { /* FIXME, should be dir, perhaps */
2256
2257                 errno = ENOTDIR;
2258                 return -1;
2259
2260         }
2261
2262         /* Now, check what we were passed and see if it is OK ... */
2263
2264         if (dirent == NULL) {  /* Seek to the begining of the list */
2265
2266                 dir->dir_next = dir->dir_list;
2267                 return 0;
2268
2269         }
2270
2271         /* Now, run down the list and make sure that the entry is OK       */
2272         /* This may need to be changed if we change the format of the list */
2273
2274         if ((list_ent = smbc_check_dir_ent(dir->dir_list, dirent)) == NULL) {
2275
2276                 errno = EINVAL;   /* Bad entry */
2277                 return -1;
2278
2279         }
2280
2281         dir->dir_next = list_ent;
2282
2283         return 0; 
2284
2285 }
2286
2287 /*
2288  * Routine to fstat a dir
2289  */
2290
2291 static int smbc_fstatdir_ctx(SMBCCTX *context, SMBCFILE *dir, struct stat *st)
2292 {
2293
2294         if (!context || !context->internal || 
2295             !context->internal->_initialized) {
2296
2297                 errno = EINVAL;
2298                 return -1;
2299
2300         }
2301
2302         /* No code yet ... */
2303
2304         return 0;
2305
2306 }
2307
2308 /*
2309  * Open a print file to be written to by other calls
2310  */
2311
2312 static SMBCFILE *smbc_open_print_job_ctx(SMBCCTX *context, const char *fname)
2313 {
2314         fstring server, share, user, password;
2315         pstring path;
2316         
2317         if (!context || !context->internal ||
2318             !context->internal->_initialized) {
2319
2320                 errno = EINVAL;
2321                 return NULL;
2322     
2323         }
2324
2325         if (!fname) {
2326
2327                 errno = EINVAL;
2328                 return NULL;
2329
2330         }
2331   
2332         DEBUG(4, ("smbc_open_print_job_ctx(%s)\n", fname));
2333
2334         smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
2335
2336         /* What if the path is empty, or the file exists? */
2337
2338         return context->open(context, fname, O_WRONLY, 666);
2339
2340 }
2341
2342 /*
2343  * Routine to print a file on a remote server ...
2344  *
2345  * We open the file, which we assume to be on a remote server, and then
2346  * copy it to a print file on the share specified by printq.
2347  */
2348
2349 static int smbc_print_file_ctx(SMBCCTX *c_file, const char *fname, SMBCCTX *c_print, const char *printq)
2350 {
2351         SMBCFILE *fid1, *fid2;
2352         int bytes, saverr, tot_bytes = 0;
2353         char buf[4096];
2354
2355         if (!c_file || !c_file->internal->_initialized || !c_print ||
2356             !c_print->internal->_initialized) {
2357
2358                 errno = EINVAL;
2359                 return -1;
2360
2361         }
2362
2363         if (!fname && !printq) {
2364
2365                 errno = EINVAL;
2366                 return -1;
2367
2368         }
2369
2370         /* Try to open the file for reading ... */
2371
2372         if ((int)(fid1 = c_file->open(c_file, fname, O_RDONLY, 0666)) < 0) {
2373                 
2374                 DEBUG(3, ("Error, fname=%s, errno=%i\n", fname, errno));
2375                 return -1;  /* smbc_open sets errno */
2376                 
2377         }
2378
2379         /* Now, try to open the printer file for writing */
2380
2381         if ((int)(fid2 = c_print->open_print_job(c_print, printq)) < 0) {
2382
2383                 saverr = errno;  /* Save errno */
2384                 c_file->close(c_file, fid1);
2385                 errno = saverr;
2386                 return -1;
2387
2388         }
2389
2390         while ((bytes = c_file->read(c_file, fid1, buf, sizeof(buf))) > 0) {
2391
2392                 tot_bytes += bytes;
2393
2394                 if ((c_print->write(c_print, fid2, buf, bytes)) < 0) {
2395
2396                         saverr = errno;
2397                         c_file->close(c_file, fid1);
2398                         c_print->close(c_print, fid2);
2399                         errno = saverr;
2400
2401                 }
2402
2403         }
2404
2405         saverr = errno;
2406
2407         c_file->close(c_file, fid1);  /* We have to close these anyway */
2408         c_print->close(c_print, fid2);
2409
2410         if (bytes < 0) {
2411
2412                 errno = saverr;
2413                 return -1;
2414
2415         }
2416
2417         return tot_bytes;
2418
2419 }
2420
2421 /*
2422  * Routine to list print jobs on a printer share ...
2423  */
2424
2425 static int smbc_list_print_jobs_ctx(SMBCCTX *context, const char *fname, smbc_list_print_job_fn fn)
2426 {
2427         SMBCSRV *srv;
2428         fstring server, share, user, password, workgroup;
2429         pstring path;
2430
2431         if (!context || !context->internal ||
2432             !context->internal->_initialized) {
2433
2434                 errno = EINVAL;
2435                 return -1;
2436
2437         }
2438
2439         if (!fname) {
2440                 
2441                 errno = EINVAL;
2442                 return -1;
2443
2444         }
2445   
2446         DEBUG(4, ("smbc_list_print_jobs(%s)\n", fname));
2447
2448         smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
2449
2450         if (user[0] == (char)0) fstrcpy(user, context->user);
2451         
2452         fstrcpy(workgroup, context->workgroup);
2453
2454         srv = smbc_server(context, server, share, workgroup, user, password);
2455
2456         if (!srv) {
2457
2458                 return -1;  /* errno set by smbc_server */
2459
2460         }
2461
2462         if (cli_print_queue(&srv->cli, (void (*)(struct print_job_info *))fn) < 0) {
2463
2464                 errno = smbc_errno(context, &srv->cli);
2465                 return -1;
2466
2467         }
2468         
2469         return 0;
2470
2471 }
2472
2473 /*
2474  * Delete a print job from a remote printer share
2475  */
2476
2477 static int smbc_unlink_print_job_ctx(SMBCCTX *context, const char *fname, int id)
2478 {
2479         SMBCSRV *srv;
2480         fstring server, share, user, password, workgroup;
2481         pstring path;
2482         int err;
2483
2484         if (!context || !context->internal ||
2485             !context->internal->_initialized) {
2486
2487                 errno = EINVAL;
2488                 return -1;
2489
2490         }
2491
2492         if (!fname) {
2493
2494                 errno = EINVAL;
2495                 return -1;
2496
2497         }
2498   
2499         DEBUG(4, ("smbc_unlink_print_job(%s)\n", fname));
2500
2501         smbc_parse_path(context, fname, server, share, path, user, password); /*FIXME, errors*/
2502
2503         if (user[0] == (char)0) fstrcpy(user, context->user);
2504
2505         fstrcpy(workgroup, context->workgroup);
2506
2507         srv = smbc_server(context, server, share, workgroup, user, password);
2508
2509         if (!srv) {
2510
2511                 return -1;  /* errno set by smbc_server */
2512
2513         }
2514
2515         if ((err = cli_printjob_del(&srv->cli, id)) != 0) {
2516
2517                 if (err < 0)
2518                         errno = smbc_errno(context, &srv->cli);
2519                 else if (err == ERRnosuchprintjob)
2520                         errno = EINVAL;
2521                 return -1;
2522
2523         }
2524
2525         return 0;
2526
2527 }
2528
2529 /*
2530  * Get a new empty handle to fill in with your own info 
2531  */
2532 SMBCCTX * smbc_new_context(void)
2533 {
2534         SMBCCTX * context;
2535
2536         context = malloc(sizeof(SMBCCTX));
2537         if (!context) {
2538                 errno = ENOMEM;
2539                 return NULL;
2540         }
2541
2542         ZERO_STRUCTP(context);
2543
2544         context->internal = malloc(sizeof(struct smbc_internal_data));
2545         if (!context->internal) {
2546                 errno = ENOMEM;
2547                 return NULL;
2548         }
2549
2550         ZERO_STRUCTP(context->internal);
2551
2552         
2553         /* ADD REASONABLE DEFAULTS */
2554         context->debug            = 0;
2555         context->timeout          = 20000; /* 20 seconds */
2556
2557         context->open             = smbc_open_ctx;
2558         context->creat            = smbc_creat_ctx;
2559         context->read             = smbc_read_ctx;
2560         context->write            = smbc_write_ctx;
2561         context->close            = smbc_close_ctx;
2562         context->unlink           = smbc_unlink_ctx;
2563         context->rename           = smbc_rename_ctx;
2564         context->lseek            = smbc_lseek_ctx;
2565         context->stat             = smbc_stat_ctx;
2566         context->fstat            = smbc_fstat_ctx;
2567         context->opendir          = smbc_opendir_ctx;
2568         context->closedir         = smbc_closedir_ctx;
2569         context->readdir          = smbc_readdir_ctx;
2570         context->getdents         = smbc_getdents_ctx;
2571         context->mkdir            = smbc_mkdir_ctx;
2572         context->rmdir            = smbc_rmdir_ctx;
2573         context->telldir          = smbc_telldir_ctx;
2574         context->lseekdir         = smbc_lseekdir_ctx;
2575         context->fstatdir         = smbc_fstatdir_ctx;
2576         context->open_print_job   = smbc_open_print_job_ctx;
2577         context->print_file       = smbc_print_file_ctx;
2578         context->list_print_jobs  = smbc_list_print_jobs_ctx;
2579         context->unlink_print_job = smbc_unlink_print_job_ctx;
2580
2581         context->callbacks.check_server_fn      = smbc_check_server;
2582         context->callbacks.remove_unused_server_fn = smbc_remove_unused_server;
2583
2584         smbc_default_cache_functions(context);
2585
2586         return context;
2587 }
2588
2589 /* 
2590  * Free a context
2591  *
2592  * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed 
2593  * and thus you'll be leaking memory if not handled properly.
2594  *
2595  */
2596 int smbc_free_context(SMBCCTX * context, int shutdown_ctx)
2597 {
2598         if (!context) {
2599                 errno = EBADF;
2600                 return 1;
2601         }
2602         
2603         if (shutdown_ctx) {
2604                 SMBCFILE * f;
2605                 DEBUG(1,("Performing aggressive shutdown.\n"));
2606                 
2607                 f = context->internal->_files;
2608                 while (f) {
2609                         context->close(context, f);
2610                         f = f->next;
2611                 }
2612                 context->internal->_files = NULL;
2613
2614                 /* First try to remove the servers the nice way. */
2615                 if (context->callbacks.purge_cached_fn(context)) {
2616                         SMBCSRV * s;
2617                         DEBUG(1, ("Could not purge all servers, Nice way shutdown failed.\n"));
2618                         s = context->internal->_servers;
2619                         while (s) {
2620                                 cli_shutdown(&s->cli);
2621                                 context->callbacks.remove_cached_srv_fn(context, s);
2622                                 SAFE_FREE(s);
2623                                 s = s->next;
2624                         }
2625                         context->internal->_servers = NULL;
2626                 }
2627         }
2628         else {
2629                 /* This is the polite way */    
2630                 if (context->callbacks.purge_cached_fn(context)) {
2631                         DEBUG(1, ("Could not purge all servers, free_context failed.\n"));
2632                         errno = EBUSY;
2633                         return 1;
2634                 }
2635                 if (context->internal->_servers) {
2636                         DEBUG(1, ("Active servers in context, free_context failed.\n"));
2637                         errno = EBUSY;
2638                         return 1;
2639                 }
2640                 if (context->internal->_files) {
2641                         DEBUG(1, ("Active files in context, free_context failed.\n"));
2642                         errno = EBUSY;
2643                         return 1;
2644                 }               
2645         }
2646
2647         /* Things we have to clean up */
2648         SAFE_FREE(context->workgroup);
2649         SAFE_FREE(context->netbios_name);
2650         SAFE_FREE(context->user);
2651         
2652         DEBUG(3, ("Context %p succesfully freed\n", context));
2653         SAFE_FREE(context->internal);
2654         SAFE_FREE(context);
2655         return 0;
2656 }
2657
2658
2659 /*
2660  * Initialise the library etc 
2661  *
2662  * We accept a struct containing handle information.
2663  * valid values for info->debug from 0 to 100,
2664  * and insist that info->fn must be non-null.
2665  */
2666 SMBCCTX * smbc_init_context(SMBCCTX * context)
2667 {
2668         pstring conf;
2669         int pid;
2670         char *user = NULL, *home = NULL;
2671
2672         if (!context || !context->internal) {
2673                 errno = EBADF;
2674                 return NULL;
2675         }
2676
2677         /* Do not initialise the same client twice */
2678         if (context->internal->_initialized) { 
2679                 return 0;
2680         }
2681
2682         if (!context->callbacks.auth_fn || context->debug < 0 || context->debug > 100) {
2683
2684                 errno = EINVAL;
2685                 return NULL;
2686
2687         }
2688
2689         if (!smbc_initialized) {
2690                 /* Do some library wide intialisations the first time we get called */
2691
2692                 /* Do we still need this ? */
2693                 DEBUGLEVEL = 10;
2694                 
2695                 setup_logging( "libsmbclient", True);
2696
2697                 /* Here we would open the smb.conf file if needed ... */
2698                 
2699                 home = getenv("HOME");
2700
2701                 slprintf(conf, sizeof(conf), "%s/.smb/smb.conf", home);
2702                 
2703                 load_interfaces();  /* Load the list of interfaces ... */
2704                 
2705                 in_client = True; /* FIXME, make a param */
2706
2707                 if (!lp_load(conf, True, False, False)) {
2708
2709                         /*
2710                          * Hmmm, what the hell do we do here ... we could not parse the
2711                          * config file ... We must return an error ... and keep info around
2712                          * about why we failed
2713                          */
2714                         
2715                         errno = ENOENT; /* FIXME: Figure out the correct error response */
2716                         return NULL;
2717                 }
2718
2719                 reopen_logs();  /* Get logging working ... */
2720         
2721                 /* 
2722                  * Block SIGPIPE (from lib/util_sock.c: write())  
2723                  * It is not needed and should not stop execution 
2724                  */
2725                 BlockSignals(True, SIGPIPE);
2726                 
2727                 /* Done with one-time initialisation */
2728                 smbc_initialized = 1; 
2729
2730         }
2731         
2732         if (!context->user) {
2733                 /*
2734                  * FIXME: Is this the best way to get the user info? 
2735                  */
2736                 user = getenv("USER");
2737                 /* walk around as "guest" if no username can be found */
2738                 if (!user) context->user = strdup("guest");
2739                 else context->user = strdup(user);
2740         }
2741
2742         if (!context->netbios_name) {
2743                 /*
2744                  * We try to get our netbios name from the config. If that fails we fall
2745                  * back on constructing our netbios name from our hostname etc
2746                  */
2747                 if (global_myname()) {
2748                         context->netbios_name = strdup(global_myname());
2749                 }
2750                 else {
2751                         /*
2752                          * Hmmm, I want to get hostname as well, but I am too lazy for the moment
2753                          */
2754                         pid = sys_getpid();
2755                         context->netbios_name = malloc(17);
2756                         if (!context->netbios_name) {
2757                                 errno = ENOMEM;
2758                                 return NULL;
2759                         }
2760                         slprintf(context->netbios_name, 16, "smbc%s%d", context->user, pid);
2761                 }
2762         }
2763
2764         DEBUG(1, ("Using netbios name %s.\n", context->netbios_name));
2765
2766         if (!context->workgroup) {
2767                 if (lp_workgroup()) {
2768                         context->workgroup = strdup(lp_workgroup());
2769                 }
2770                 else {
2771                         /* TODO: Think about a decent default workgroup */
2772                         context->workgroup = strdup("samba");
2773                 }
2774         }
2775
2776         DEBUG(1, ("Using workgroup %s.\n", context->workgroup));
2777                                         
2778         /* shortest timeout is 1 second */
2779         if (context->timeout > 0 && context->timeout < 1000) 
2780                 context->timeout = 1000;
2781
2782         /*
2783          * FIXME: Should we check the function pointers here? 
2784          */
2785
2786         context->internal->_initialized = 1;
2787         
2788         return context;
2789 }