Merge branch 'v3-2-test' of ssh://git.samba.org/data/git/samba into v3-2-test
[amitay/samba.git] / source3 / libsmb / libsmb_context.c
1 /* 
2    Unix SMB/Netbios implementation.
3    SMB client library implementation
4    Copyright (C) Andrew Tridgell 1998
5    Copyright (C) Richard Sharpe 2000, 2002
6    Copyright (C) John Terpstra 2000
7    Copyright (C) Tom Jansen (Ninja ISD) 2002 
8    Copyright (C) Derrell Lipman 2003-2008
9    Copyright (C) Jeremy Allison 2007, 2008
10    
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15    
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20    
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "libsmbclient.h"
27 #include "libsmb_internal.h"
28
29
30 /*
31  * Is the logging working / configfile read ? 
32  */
33 static int SMBC_initialized = 0;
34
35
36
37 /*
38  * Get a new empty handle to fill in with your own info
39  */
40 SMBCCTX *
41 smbc_new_context(void)
42 {
43         SMBCCTX *context;
44         
45         /*
46          * All newly added context fields should be placed in
47          * SMBC_internal_data, not directly in SMBCCTX.
48          */
49         context = SMB_MALLOC_P(SMBCCTX);
50         if (!context) {
51                 errno = ENOMEM;
52                 return NULL;
53         }
54         
55         ZERO_STRUCTP(context);
56         
57         context->internal = SMB_MALLOC_P(struct SMBC_internal_data);
58         if (!context->internal) {
59                 SAFE_FREE(context);
60                 errno = ENOMEM;
61                 return NULL;
62         }
63         
64         /* Initialize the context and establish reasonable defaults */
65         ZERO_STRUCTP(context->internal);
66         
67         smbc_setDebug(context, 0);
68         smbc_setTimeout(context, 20000);
69         
70         smbc_setOptionFullTimeNames(context, False);
71         smbc_setOptionOpenShareMode(context, SMBC_SHAREMODE_DENY_NONE);
72         smbc_setOptionSmbEncryptionLevel(context, SMBC_ENCRYPTLEVEL_NONE);
73         smbc_setOptionBrowseMaxLmbCount(context, 3);    /* # LMBs to query */
74         smbc_setOptionUrlEncodeReaddirEntries(context, False);
75         smbc_setOptionOneSharePerServer(context, False);
76         
77         smbc_setFunctionAuthData(context, SMBC_get_auth_data);
78         smbc_setFunctionCheckServer(context, SMBC_check_server);
79         smbc_setFunctionRemoveUnusedServer(context, SMBC_remove_unused_server);
80         
81         smbc_setOptionUserData(context, NULL);
82         smbc_setFunctionAddCachedServer(context, SMBC_add_cached_server);
83         smbc_setFunctionGetCachedServer(context, SMBC_get_cached_server);
84         smbc_setFunctionRemoveCachedServer(context, SMBC_remove_cached_server);
85         smbc_setFunctionPurgeCachedServers(context, SMBC_purge_cached_servers);
86         
87         smbc_setFunctionOpen(context, SMBC_open_ctx);
88         smbc_setFunctionCreat(context, SMBC_creat_ctx);
89         smbc_setFunctionRead(context, SMBC_read_ctx);
90         smbc_setFunctionWrite(context, SMBC_write_ctx);
91         smbc_setFunctionClose(context, SMBC_close_ctx);
92         smbc_setFunctionUnlink(context, SMBC_unlink_ctx);
93         smbc_setFunctionRename(context, SMBC_rename_ctx);
94         smbc_setFunctionLseek(context, SMBC_lseek_ctx);
95         smbc_setFunctionFtruncate(context, SMBC_ftruncate_ctx);
96         smbc_setFunctionStat(context, SMBC_stat_ctx);
97         smbc_setFunctionFstat(context, SMBC_fstat_ctx);
98         smbc_setFunctionOpendir(context, SMBC_opendir_ctx);
99         smbc_setFunctionClosedir(context, SMBC_closedir_ctx);
100         smbc_setFunctionReaddir(context, SMBC_readdir_ctx);
101         smbc_setFunctionGetdents(context, SMBC_getdents_ctx);
102         smbc_setFunctionMkdir(context, SMBC_mkdir_ctx);
103         smbc_setFunctionRmdir(context, SMBC_rmdir_ctx);
104         smbc_setFunctionTelldir(context, SMBC_telldir_ctx);
105         smbc_setFunctionLseekdir(context, SMBC_lseekdir_ctx);
106         smbc_setFunctionFstatdir(context, SMBC_fstatdir_ctx);
107         smbc_setFunctionChmod(context, SMBC_chmod_ctx);
108         smbc_setFunctionUtimes(context, SMBC_utimes_ctx);
109         smbc_setFunctionSetxattr(context, SMBC_setxattr_ctx);
110         smbc_setFunctionGetxattr(context, SMBC_getxattr_ctx);
111         smbc_setFunctionRemovexattr(context, SMBC_removexattr_ctx);
112         smbc_setFunctionListxattr(context, SMBC_listxattr_ctx);
113         
114         smbc_setFunctionOpenPrintJob(context, SMBC_open_print_job_ctx);
115         smbc_setFunctionPrintFile(context, SMBC_print_file_ctx);
116         smbc_setFunctionListPrintJobs(context, SMBC_list_print_jobs_ctx);
117         smbc_setFunctionUnlinkPrintJob(context, SMBC_unlink_print_job_ctx);
118         
119         return context;
120 }
121
122 /*
123  * Free a context
124  *
125  * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
126  * and thus you'll be leaking memory if not handled properly.
127  *
128  */
129 int
130 smbc_free_context(SMBCCTX *context,
131                   int shutdown_ctx)
132 {
133         if (!context) {
134                 errno = EBADF;
135                 return 1;
136         }
137         
138         if (shutdown_ctx) {
139                 SMBCFILE * f;
140                 DEBUG(1,("Performing aggressive shutdown.\n"));
141                 
142                 f = context->internal->files;
143                 while (f) {
144                         smbc_getFunctionClose(context)(context, f);
145                         f = f->next;
146                 }
147                 context->internal->files = NULL;
148                 
149                 /* First try to remove the servers the nice way. */
150                 if (smbc_getFunctionPurgeCachedServers(context)(context)) {
151                         SMBCSRV * s;
152                         SMBCSRV * next;
153                         DEBUG(1, ("Could not purge all servers, "
154                                   "Nice way shutdown failed.\n"));
155                         s = context->internal->servers;
156                         while (s) {
157                                 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
158                                           s, s->cli->fd));
159                                 cli_shutdown(s->cli);
160                                 smbc_getFunctionRemoveCachedServer(context)(context,
161                                                                          s);
162                                 next = s->next;
163                                 DLIST_REMOVE(context->internal->servers, s);
164                                 SAFE_FREE(s);
165                                 s = next;
166                         }
167                         context->internal->servers = NULL;
168                 }
169         }
170         else {
171                 /* This is the polite way */
172                 if (smbc_getFunctionPurgeCachedServers(context)(context)) {
173                         DEBUG(1, ("Could not purge all servers, "
174                                   "free_context failed.\n"));
175                         errno = EBUSY;
176                         return 1;
177                 }
178                 if (context->internal->servers) {
179                         DEBUG(1, ("Active servers in context, "
180                                   "free_context failed.\n"));
181                         errno = EBUSY;
182                         return 1;
183                 }
184                 if (context->internal->files) {
185                         DEBUG(1, ("Active files in context, "
186                                   "free_context failed.\n"));
187                         errno = EBUSY;
188                         return 1;
189                 }
190         }
191         
192         /* Things we have to clean up */
193         free(smbc_getWorkgroup(context));
194         smbc_setWorkgroup(context, NULL);
195
196         free(smbc_getNetbiosName(context));
197         smbc_setNetbiosName(context, NULL);
198
199         free(smbc_getUser(context));
200         smbc_setUser(context, NULL);
201         
202         DEBUG(3, ("Context %p successfully freed\n", context));
203         SAFE_FREE(context);
204         return 0;
205 }
206
207
208 /**
209  * Deprecated interface.  Do not use.  Instead, use the various
210  * smbc_setOption*() functions or smbc_setFunctionAuthDataWithContext().
211  */
212 void
213 smbc_option_set(SMBCCTX *context,
214                 char *option_name,
215                 ... /* option_value */)
216 {
217         va_list ap;
218         union {
219                 int i;
220                 bool b;
221                 smbc_get_auth_data_with_context_fn auth_fn;
222                 void *v;
223                 const char *s;
224         } option_value;
225         
226         va_start(ap, option_name);
227         
228         if (strcmp(option_name, "debug_to_stderr") == 0) {
229                 option_value.b = (bool) va_arg(ap, int);
230                 smbc_setOptionDebugToStderr(context, option_value.b);
231                 
232         } else if (strcmp(option_name, "full_time_names") == 0) {
233                 option_value.b = (bool) va_arg(ap, int);
234                 smbc_setOptionFullTimeNames(context, option_value.b);
235                 
236         } else if (strcmp(option_name, "open_share_mode") == 0) {
237                 option_value.i = va_arg(ap, int);
238                 smbc_setOptionOpenShareMode(context, option_value.i);
239                 
240         } else if (strcmp(option_name, "auth_function") == 0) {
241                 option_value.auth_fn =
242                         va_arg(ap, smbc_get_auth_data_with_context_fn);
243                 smbc_setFunctionAuthDataWithContext(context, option_value.auth_fn);
244                 
245         } else if (strcmp(option_name, "user_data") == 0) {
246                 option_value.v = va_arg(ap, void *);
247                 smbc_setOptionUserData(context, option_value.v);
248                 
249         } else if (strcmp(option_name, "smb_encrypt_level") == 0) {
250                 option_value.s = va_arg(ap, const char *);
251                 if (strcmp(option_value.s, "none") == 0) {
252                         smbc_setOptionSmbEncryptionLevel(context,
253                                                          SMBC_ENCRYPTLEVEL_NONE);
254                 } else if (strcmp(option_value.s, "request") == 0) {
255                         smbc_setOptionSmbEncryptionLevel(context,
256                                                          SMBC_ENCRYPTLEVEL_REQUEST);
257                 } else if (strcmp(option_value.s, "require") == 0) {
258                         smbc_setOptionSmbEncryptionLevel(context,
259                                                          SMBC_ENCRYPTLEVEL_REQUIRE);
260                 }
261                 
262         } else if (strcmp(option_name, "browse_max_lmb_count") == 0) {
263                 option_value.i = va_arg(ap, int);
264                 smbc_setOptionBrowseMaxLmbCount(context, option_value.i);
265                 
266         } else if (strcmp(option_name, "urlencode_readdir_entries") == 0) {
267                 option_value.b = (bool) va_arg(ap, int);
268                 smbc_setOptionUrlEncodeReaddirEntries(context, option_value.b);
269                 
270         } else if (strcmp(option_name, "one_share_per_server") == 0) {
271                 option_value.b = (bool) va_arg(ap, int);
272                 smbc_setOptionOneSharePerServer(context, option_value.b);
273                 
274         } else if (strcmp(option_name, "use_kerberos") == 0) {
275                 option_value.b = (bool) va_arg(ap, int);
276                 smbc_setOptionUseKerberos(context, option_value.b);
277                 
278         } else if (strcmp(option_name, "fallback_after_kerberos") == 0) {
279                 option_value.b = (bool) va_arg(ap, int);
280                 smbc_setOptionFallbackAfterKerberos(context, option_value.b);
281                 
282         } else if (strcmp(option_name, "no_auto_anonymous_login") == 0) {
283                 option_value.b = (bool) va_arg(ap, int);
284                 smbc_setOptionNoAutoAnonymousLogin(context, option_value.b);
285         }
286         
287         va_end(ap);
288 }
289
290
291 /*
292  * Deprecated interface.  Do not use.  Instead, use the various
293  * smbc_getOption*() functions.
294  */
295 void *
296 smbc_option_get(SMBCCTX *context,
297                 char *option_name)
298 {
299         if (strcmp(option_name, "debug_stderr") == 0) {
300 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
301                 return (void *) (intptr_t) smbc_getOptionDebugToStderr(context);
302 #else
303                 return (void *) smbc_getOptionDebugToStderr(context);
304 #endif
305                 
306         } else if (strcmp(option_name, "full_time_names") == 0) {
307 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
308                 return (void *) (intptr_t) smbc_getOptionFullTimeNames(context);
309 #else
310                 return (void *) smbc_getOptionFullTimeNames(context);
311 #endif
312                 
313         } else if (strcmp(option_name, "open_share_mode") == 0) {
314 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
315                 return (void *) (intptr_t) smbc_getOptionOpenShareMode(context);
316 #else
317                 return (void *) smbc_getOptionOpenShareMode(context);
318 #endif
319                 
320         } else if (strcmp(option_name, "auth_function") == 0) {
321                 return (void *) smbc_getFunctionAuthDataWithContext(context);
322                 
323         } else if (strcmp(option_name, "user_data") == 0) {
324                 return smbc_getOptionUserData(context);
325                 
326         } else if (strcmp(option_name, "smb_encrypt_level") == 0) {
327                 switch(smbc_getOptionSmbEncryptionLevel(context))
328                 {
329                 case 0:
330                         return (void *) "none";
331                 case 1:
332                         return (void *) "request";
333                 case 2:
334                         return (void *) "require";
335                 }
336                 
337         } else if (strcmp(option_name, "smb_encrypt_on") == 0) {
338                 SMBCSRV *s;
339                 unsigned int num_servers = 0;
340                 
341                 for (s = context->internal->servers; s; s = s->next) {
342                         num_servers++;
343                         if (s->cli->trans_enc_state == NULL) {
344                                 return (void *)false;
345                         }
346                 }
347 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
348                 return (void *) (intptr_t) (bool) (num_servers > 0);
349 #else
350                 return (void *) (bool) (num_servers > 0);
351 #endif
352                 
353         } else if (strcmp(option_name, "browse_max_lmb_count") == 0) {
354 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
355                 return (void *) (intptr_t) smbc_getOptionBrowseMaxLmbCount(context);
356 #else
357                 return (void *) smbc_getOptionBrowseMaxLmbCount(context);
358 #endif
359                 
360         } else if (strcmp(option_name, "urlencode_readdir_entries") == 0) {
361 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
362                 return (void *)(intptr_t) smbc_getOptionUrlEncodeReaddirEntries(context);
363 #else
364                 return (void *) (bool) smbc_getOptionUrlEncodeReaddirEntries(context);
365 #endif
366                 
367         } else if (strcmp(option_name, "one_share_per_server") == 0) {
368 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
369                 return (void *) (intptr_t) smbc_getOptionOneSharePerServer(context);
370 #else
371                 return (void *) (bool) smbc_getOptionOneSharePerServer(context);
372 #endif
373                 
374         } else if (strcmp(option_name, "use_kerberos") == 0) {
375 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
376                 return (void *) (intptr_t) smbc_getOptionUseKerberos(context);
377 #else
378                 return (void *) (bool) smbc_getOptionUseKerberos(context);
379 #endif
380                 
381         } else if (strcmp(option_name, "fallback_after_kerberos") == 0) {
382 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
383                 return (void *)(intptr_t) smbc_getOptionFallbackAfterKerberos(context);
384 #else
385                 return (void *) (bool) smbc_getOptionFallbackAfterKerberos(context);
386 #endif
387                 
388         } else if (strcmp(option_name, "no_auto_anonymous_login") == 0) {
389 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
390                 return (void *) (intptr_t) smbc_getOptionNoAutoAnonymousLogin(context);
391 #else
392                 return (void *) (bool) smbc_getOptionNoAutoAnonymousLogin(context);
393 #endif
394         }
395         
396         return NULL;
397 }
398
399
400 /*
401  * Initialize the library, etc.
402  *
403  * We accept a struct containing handle information.
404  * valid values for info->debug from 0 to 100,
405  * and insist that info->fn must be non-null.
406  */
407 SMBCCTX *
408 smbc_init_context(SMBCCTX *context)
409 {
410         int pid;
411         char *user = NULL;
412         char *home = NULL;
413         extern bool in_client;
414         
415         if (!context) {
416                 errno = EBADF;
417                 return NULL;
418         }
419         
420         /* Do not initialise the same client twice */
421         if (context->internal->initialized) {
422                 return NULL;
423         }
424         
425         if (!smbc_getFunctionAuthData(context) ||
426             smbc_getDebug(context) < 0 ||
427             smbc_getDebug(context) > 100) {
428                 
429                 errno = EINVAL;
430                 return NULL;
431                 
432         }
433         
434         if (!SMBC_initialized) {
435                 /*
436                  * Do some library-wide intializations the first time we get
437                  * called
438                  */
439                 bool conf_loaded = False;
440                 TALLOC_CTX *frame = talloc_stackframe();
441                 
442                 load_case_tables();
443                 
444                 setup_logging("libsmbclient", True);
445                 if (context->internal->debug_stderr) {
446                         dbf = x_stderr;
447                         x_setbuf(x_stderr, NULL);
448                 }
449                 
450                 /* Here we would open the smb.conf file if needed ... */
451                 
452                 in_client = True; /* FIXME, make a param */
453                 
454                 home = getenv("HOME");
455                 if (home) {
456                         char *conf = NULL;
457                         if (asprintf(&conf, "%s/.smb/smb.conf", home) > 0) {
458                                 if (lp_load(conf, True, False, False, True)) {
459                                         conf_loaded = True;
460                                 } else {
461                                         DEBUG(5, ("Could not load config file: %s\n",
462                                                   conf));
463                                 }
464                                 SAFE_FREE(conf);
465                         }
466                 }
467                 
468                 if (!conf_loaded) {
469                         /*
470                          * Well, if that failed, try the get_dyn_CONFIGFILE
471                          * Which points to the standard locn, and if that
472                          * fails, silently ignore it and use the internal
473                          * defaults ...
474                          */
475                         
476                         if (!lp_load(get_dyn_CONFIGFILE(), True, False, False, False)) {
477                                 DEBUG(5, ("Could not load config file: %s\n",
478                                           get_dyn_CONFIGFILE()));
479                         } else if (home) {
480                                 char *conf;
481                                 /*
482                                  * We loaded the global config file.  Now lets
483                                  * load user-specific modifications to the
484                                  * global config.
485                                  */
486                                 if (asprintf(&conf,
487                                              "%s/.smb/smb.conf.append",
488                                              home) > 0) {
489                                         if (!lp_load(conf, True, False, False, False)) {
490                                                 DEBUG(10,
491                                                       ("Could not append config file: "
492                                                        "%s\n",
493                                                        conf));
494                                         }
495                                         SAFE_FREE(conf);
496                                 }
497                         }
498                 }
499                 
500                 load_interfaces();  /* Load the list of interfaces ... */
501                 
502                 reopen_logs();  /* Get logging working ... */
503                 
504                 /*
505                  * Block SIGPIPE (from lib/util_sock.c: write())
506                  * It is not needed and should not stop execution
507                  */
508                 BlockSignals(True, SIGPIPE);
509                 
510                 /* Done with one-time initialisation */
511                 SMBC_initialized = 1;
512                 
513                 TALLOC_FREE(frame);
514         }
515         
516         if (!smbc_getUser(context)) {
517                 /*
518                  * FIXME: Is this the best way to get the user info?
519                  */
520                 user = getenv("USER");
521                 /* walk around as "guest" if no username can be found */
522                 if (!user) {
523                         user = SMB_STRDUP("guest");
524                 } else {
525                         user = SMB_STRDUP(user);
526                 }
527
528                 if (!user) {
529                         errno = ENOMEM;
530                         return NULL;
531                 }
532
533                 smbc_setUser(context, user);
534         }
535         
536         if (!smbc_getNetbiosName(context)) {
537                 /*
538                  * We try to get our netbios name from the config. If that
539                  * fails we fall back on constructing our netbios name from
540                  * our hostname etc
541                  */
542                 char *netbios_name;
543                 if (global_myname()) {
544                         netbios_name = SMB_STRDUP(global_myname());
545                 } else {
546                         /*
547                          * Hmmm, I want to get hostname as well, but I am too
548                          * lazy for the moment
549                          */
550                         pid = sys_getpid();
551                         netbios_name = (char *)SMB_MALLOC(17);
552                         if (!netbios_name) {
553                                 errno = ENOMEM;
554                                 return NULL;
555                         }
556                         slprintf(netbios_name, 16,
557                                  "smbc%s%d", smbc_getUser(context), pid);
558                 }
559
560                 if (!netbios_name) {
561                         errno = ENOMEM;
562                         return NULL;
563                 }
564                 
565                 smbc_setNetbiosName(context, netbios_name);
566         }
567         
568         DEBUG(1, ("Using netbios name %s.\n", smbc_getNetbiosName(context)));
569         
570         if (!smbc_getWorkgroup(context)) {
571                 char *workgroup;
572
573                 if (lp_workgroup()) {
574                         workgroup = SMB_STRDUP(lp_workgroup());
575                 }
576                 else {
577                         /* TODO: Think about a decent default workgroup */
578                         workgroup = SMB_STRDUP("samba");
579                 }
580
581                 if (!workgroup) {
582                         errno = ENOMEM;
583                         return NULL;
584                 }
585
586                 smbc_setWorkgroup(context, workgroup);
587         }
588         
589         DEBUG(1, ("Using workgroup %s.\n", smbc_getWorkgroup(context)));
590         
591         /* shortest timeout is 1 second */
592         if (smbc_getTimeout(context) > 0 && smbc_getTimeout(context) < 1000)
593                 smbc_setTimeout(context, 1000);
594         
595         /*
596          * FIXME: Should we check the function pointers here?
597          */
598         
599         context->internal->initialized = True;
600         
601         return context;
602 }
603
604
605 /* Return the verion of samba, and thus libsmbclient */
606 const char *
607 smbc_version(void)
608 {
609         return samba_version_string();
610 }
611
612