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