Merge branch 'master' of /home/tridge/samba/git/combined
[Samba/aatanasov.git] / source3 / libsmb / libsmb_context.c
blob78c9a551a688727764cadc9c31c2f230f7d91e21
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
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.
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.
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/>.
25 #include "includes.h"
26 #include "libsmbclient.h"
27 #include "libsmb_internal.h"
31 * Is the logging working / configfile read ?
33 static bool SMBC_initialized = false;
34 static unsigned int initialized_ctx_count = 0;
35 static void *initialized_ctx_count_mutex = NULL;
38 * Do some module- and library-wide intializations
40 static void
41 SMBC_module_init(void * punused)
43 bool conf_loaded = False;
44 char *home = NULL;
45 TALLOC_CTX *frame = talloc_stackframe();
47 load_case_tables();
49 setup_logging("libsmbclient", True);
51 /* Here we would open the smb.conf file if needed ... */
53 lp_set_in_client(True);
55 home = getenv("HOME");
56 if (home) {
57 char *conf = NULL;
58 if (asprintf(&conf, "%s/.smb/smb.conf", home) > 0) {
59 if (lp_load(conf, True, False, False, True)) {
60 conf_loaded = True;
61 } else {
62 DEBUG(5, ("Could not load config file: %s\n",
63 conf));
65 SAFE_FREE(conf);
69 if (!conf_loaded) {
71 * Well, if that failed, try the get_dyn_CONFIGFILE
72 * Which points to the standard locn, and if that
73 * fails, silently ignore it and use the internal
74 * defaults ...
77 if (!lp_load(get_dyn_CONFIGFILE(), True, False, False, False)) {
78 DEBUG(5, ("Could not load config file: %s\n",
79 get_dyn_CONFIGFILE()));
80 } else if (home) {
81 char *conf;
83 * We loaded the global config file. Now lets
84 * load user-specific modifications to the
85 * global config.
87 if (asprintf(&conf,
88 "%s/.smb/smb.conf.append",
89 home) > 0) {
90 if (!lp_load(conf, True, False, False, False)) {
91 DEBUG(10,
92 ("Could not append config file: "
93 "%s\n",
94 conf));
96 SAFE_FREE(conf);
101 load_interfaces(); /* Load the list of interfaces ... */
103 reopen_logs(); /* Get logging working ... */
106 * Block SIGPIPE (from lib/util_sock.c: write())
107 * It is not needed and should not stop execution
109 BlockSignals(True, SIGPIPE);
111 /* Create the mutex we'll use to protect initialized_ctx_count */
112 if (SMB_THREAD_CREATE_MUTEX("initialized_ctx_count_mutex",
113 initialized_ctx_count_mutex) != 0) {
114 smb_panic("SMBC_module_init: "
115 "failed to create 'initialized_ctx_count' mutex");
119 TALLOC_FREE(frame);
123 static void
124 SMBC_module_terminate(void)
126 secrets_shutdown();
127 gfree_all();
128 SMBC_initialized = false;
133 * Get a new empty handle to fill in with your own info
135 SMBCCTX *
136 smbc_new_context(void)
138 SMBCCTX *context;
140 /* The first call to this function should initialize the module */
141 SMB_THREAD_ONCE(&SMBC_initialized, SMBC_module_init, NULL);
144 * All newly added context fields should be placed in
145 * SMBC_internal_data, not directly in SMBCCTX.
147 context = SMB_MALLOC_P(SMBCCTX);
148 if (!context) {
149 errno = ENOMEM;
150 return NULL;
153 ZERO_STRUCTP(context);
155 context->internal = SMB_MALLOC_P(struct SMBC_internal_data);
156 if (!context->internal) {
157 SAFE_FREE(context);
158 errno = ENOMEM;
159 return NULL;
162 /* Initialize the context and establish reasonable defaults */
163 ZERO_STRUCTP(context->internal);
165 smbc_setDebug(context, 0);
166 smbc_setTimeout(context, 20000);
168 smbc_setOptionFullTimeNames(context, False);
169 smbc_setOptionOpenShareMode(context, SMBC_SHAREMODE_DENY_NONE);
170 smbc_setOptionSmbEncryptionLevel(context, SMBC_ENCRYPTLEVEL_NONE);
171 smbc_setOptionCaseSensitive(context, False);
172 smbc_setOptionBrowseMaxLmbCount(context, 3); /* # LMBs to query */
173 smbc_setOptionUrlEncodeReaddirEntries(context, False);
174 smbc_setOptionOneSharePerServer(context, False);
176 smbc_setFunctionAuthData(context, SMBC_get_auth_data);
177 smbc_setFunctionCheckServer(context, SMBC_check_server);
178 smbc_setFunctionRemoveUnusedServer(context, SMBC_remove_unused_server);
180 smbc_setOptionUserData(context, NULL);
181 smbc_setFunctionAddCachedServer(context, SMBC_add_cached_server);
182 smbc_setFunctionGetCachedServer(context, SMBC_get_cached_server);
183 smbc_setFunctionRemoveCachedServer(context, SMBC_remove_cached_server);
184 smbc_setFunctionPurgeCachedServers(context, SMBC_purge_cached_servers);
186 smbc_setFunctionOpen(context, SMBC_open_ctx);
187 smbc_setFunctionCreat(context, SMBC_creat_ctx);
188 smbc_setFunctionRead(context, SMBC_read_ctx);
189 smbc_setFunctionWrite(context, SMBC_write_ctx);
190 smbc_setFunctionClose(context, SMBC_close_ctx);
191 smbc_setFunctionUnlink(context, SMBC_unlink_ctx);
192 smbc_setFunctionRename(context, SMBC_rename_ctx);
193 smbc_setFunctionLseek(context, SMBC_lseek_ctx);
194 smbc_setFunctionFtruncate(context, SMBC_ftruncate_ctx);
195 smbc_setFunctionStat(context, SMBC_stat_ctx);
196 smbc_setFunctionStatVFS(context, SMBC_statvfs_ctx);
197 smbc_setFunctionFstatVFS(context, SMBC_fstatvfs_ctx);
198 smbc_setFunctionFstat(context, SMBC_fstat_ctx);
199 smbc_setFunctionOpendir(context, SMBC_opendir_ctx);
200 smbc_setFunctionClosedir(context, SMBC_closedir_ctx);
201 smbc_setFunctionReaddir(context, SMBC_readdir_ctx);
202 smbc_setFunctionGetdents(context, SMBC_getdents_ctx);
203 smbc_setFunctionMkdir(context, SMBC_mkdir_ctx);
204 smbc_setFunctionRmdir(context, SMBC_rmdir_ctx);
205 smbc_setFunctionTelldir(context, SMBC_telldir_ctx);
206 smbc_setFunctionLseekdir(context, SMBC_lseekdir_ctx);
207 smbc_setFunctionFstatdir(context, SMBC_fstatdir_ctx);
208 smbc_setFunctionChmod(context, SMBC_chmod_ctx);
209 smbc_setFunctionUtimes(context, SMBC_utimes_ctx);
210 smbc_setFunctionSetxattr(context, SMBC_setxattr_ctx);
211 smbc_setFunctionGetxattr(context, SMBC_getxattr_ctx);
212 smbc_setFunctionRemovexattr(context, SMBC_removexattr_ctx);
213 smbc_setFunctionListxattr(context, SMBC_listxattr_ctx);
215 smbc_setFunctionOpenPrintJob(context, SMBC_open_print_job_ctx);
216 smbc_setFunctionPrintFile(context, SMBC_print_file_ctx);
217 smbc_setFunctionListPrintJobs(context, SMBC_list_print_jobs_ctx);
218 smbc_setFunctionUnlinkPrintJob(context, SMBC_unlink_print_job_ctx);
220 return context;
224 * Free a context
226 * Returns 0 on success. Otherwise returns 1, the SMBCCTX is _not_ freed
227 * and thus you'll be leaking memory if not handled properly.
231 smbc_free_context(SMBCCTX *context,
232 int shutdown_ctx)
234 if (!context) {
235 errno = EBADF;
236 return 1;
239 if (shutdown_ctx) {
240 SMBCFILE * f;
241 DEBUG(1,("Performing aggressive shutdown.\n"));
243 f = context->internal->files;
244 while (f) {
245 smbc_getFunctionClose(context)(context, f);
246 f = f->next;
248 context->internal->files = NULL;
250 /* First try to remove the servers the nice way. */
251 if (smbc_getFunctionPurgeCachedServers(context)(context)) {
252 SMBCSRV * s;
253 SMBCSRV * next;
254 DEBUG(1, ("Could not purge all servers, "
255 "Nice way shutdown failed.\n"));
256 s = context->internal->servers;
257 while (s) {
258 DEBUG(1, ("Forced shutdown: %p (fd=%d)\n",
259 s, s->cli->fd));
260 cli_shutdown(s->cli);
261 smbc_getFunctionRemoveCachedServer(context)(context,
263 next = s->next;
264 DLIST_REMOVE(context->internal->servers, s);
265 SAFE_FREE(s);
266 s = next;
268 context->internal->servers = NULL;
271 else {
272 /* This is the polite way */
273 if (smbc_getFunctionPurgeCachedServers(context)(context)) {
274 DEBUG(1, ("Could not purge all servers, "
275 "free_context failed.\n"));
276 errno = EBUSY;
277 return 1;
279 if (context->internal->servers) {
280 DEBUG(1, ("Active servers in context, "
281 "free_context failed.\n"));
282 errno = EBUSY;
283 return 1;
285 if (context->internal->files) {
286 DEBUG(1, ("Active files in context, "
287 "free_context failed.\n"));
288 errno = EBUSY;
289 return 1;
293 /* Things we have to clean up */
294 free(smbc_getWorkgroup(context));
295 smbc_setWorkgroup(context, NULL);
297 free(smbc_getNetbiosName(context));
298 smbc_setNetbiosName(context, NULL);
300 free(smbc_getUser(context));
301 smbc_setUser(context, NULL);
303 DEBUG(3, ("Context %p successfully freed\n", context));
305 /* Free any DFS auth context. */
306 TALLOC_FREE(context->internal->auth_info);
308 SAFE_FREE(context->internal);
309 SAFE_FREE(context);
311 /* Protect access to the count of contexts in use */
312 if (SMB_THREAD_LOCK(initialized_ctx_count_mutex) != 0) {
313 smb_panic("error locking 'initialized_ctx_count'");
316 if (initialized_ctx_count) {
317 initialized_ctx_count--;
320 if (initialized_ctx_count == 0) {
321 SMBC_module_terminate();
324 /* Unlock the mutex */
325 if (SMB_THREAD_UNLOCK(initialized_ctx_count_mutex) != 0) {
326 smb_panic("error unlocking 'initialized_ctx_count'");
329 return 0;
334 * Deprecated interface. Do not use. Instead, use the various
335 * smbc_setOption*() functions or smbc_setFunctionAuthDataWithContext().
337 void
338 smbc_option_set(SMBCCTX *context,
339 char *option_name,
340 ... /* option_value */)
342 va_list ap;
343 union {
344 int i;
345 bool b;
346 smbc_get_auth_data_with_context_fn auth_fn;
347 void *v;
348 const char *s;
349 } option_value;
351 va_start(ap, option_name);
353 if (strcmp(option_name, "debug_to_stderr") == 0) {
354 option_value.b = (bool) va_arg(ap, int);
355 smbc_setOptionDebugToStderr(context, option_value.b);
357 } else if (strcmp(option_name, "full_time_names") == 0) {
358 option_value.b = (bool) va_arg(ap, int);
359 smbc_setOptionFullTimeNames(context, option_value.b);
361 } else if (strcmp(option_name, "open_share_mode") == 0) {
362 option_value.i = va_arg(ap, int);
363 smbc_setOptionOpenShareMode(context, option_value.i);
365 } else if (strcmp(option_name, "auth_function") == 0) {
366 option_value.auth_fn =
367 va_arg(ap, smbc_get_auth_data_with_context_fn);
368 smbc_setFunctionAuthDataWithContext(context, option_value.auth_fn);
370 } else if (strcmp(option_name, "user_data") == 0) {
371 option_value.v = va_arg(ap, void *);
372 smbc_setOptionUserData(context, option_value.v);
374 } else if (strcmp(option_name, "smb_encrypt_level") == 0) {
375 option_value.s = va_arg(ap, const char *);
376 if (strcmp(option_value.s, "none") == 0) {
377 smbc_setOptionSmbEncryptionLevel(context,
378 SMBC_ENCRYPTLEVEL_NONE);
379 } else if (strcmp(option_value.s, "request") == 0) {
380 smbc_setOptionSmbEncryptionLevel(context,
381 SMBC_ENCRYPTLEVEL_REQUEST);
382 } else if (strcmp(option_value.s, "require") == 0) {
383 smbc_setOptionSmbEncryptionLevel(context,
384 SMBC_ENCRYPTLEVEL_REQUIRE);
387 } else if (strcmp(option_name, "browse_max_lmb_count") == 0) {
388 option_value.i = va_arg(ap, int);
389 smbc_setOptionBrowseMaxLmbCount(context, option_value.i);
391 } else if (strcmp(option_name, "urlencode_readdir_entries") == 0) {
392 option_value.b = (bool) va_arg(ap, int);
393 smbc_setOptionUrlEncodeReaddirEntries(context, option_value.b);
395 } else if (strcmp(option_name, "one_share_per_server") == 0) {
396 option_value.b = (bool) va_arg(ap, int);
397 smbc_setOptionOneSharePerServer(context, option_value.b);
399 } else if (strcmp(option_name, "use_kerberos") == 0) {
400 option_value.b = (bool) va_arg(ap, int);
401 smbc_setOptionUseKerberos(context, option_value.b);
403 } else if (strcmp(option_name, "fallback_after_kerberos") == 0) {
404 option_value.b = (bool) va_arg(ap, int);
405 smbc_setOptionFallbackAfterKerberos(context, option_value.b);
407 } else if (strcmp(option_name, "no_auto_anonymous_login") == 0) {
408 option_value.b = (bool) va_arg(ap, int);
409 smbc_setOptionNoAutoAnonymousLogin(context, option_value.b);
412 va_end(ap);
417 * Deprecated interface. Do not use. Instead, use the various
418 * smbc_getOption*() functions.
420 void *
421 smbc_option_get(SMBCCTX *context,
422 char *option_name)
424 if (strcmp(option_name, "debug_stderr") == 0) {
425 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
426 return (void *) (intptr_t) smbc_getOptionDebugToStderr(context);
427 #else
428 return (void *) smbc_getOptionDebugToStderr(context);
429 #endif
431 } else if (strcmp(option_name, "full_time_names") == 0) {
432 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
433 return (void *) (intptr_t) smbc_getOptionFullTimeNames(context);
434 #else
435 return (void *) smbc_getOptionFullTimeNames(context);
436 #endif
438 } else if (strcmp(option_name, "open_share_mode") == 0) {
439 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
440 return (void *) (intptr_t) smbc_getOptionOpenShareMode(context);
441 #else
442 return (void *) smbc_getOptionOpenShareMode(context);
443 #endif
445 } else if (strcmp(option_name, "auth_function") == 0) {
446 return (void *) smbc_getFunctionAuthDataWithContext(context);
448 } else if (strcmp(option_name, "user_data") == 0) {
449 return smbc_getOptionUserData(context);
451 } else if (strcmp(option_name, "smb_encrypt_level") == 0) {
452 switch(smbc_getOptionSmbEncryptionLevel(context))
454 case 0:
455 return (void *) "none";
456 case 1:
457 return (void *) "request";
458 case 2:
459 return (void *) "require";
462 } else if (strcmp(option_name, "smb_encrypt_on") == 0) {
463 SMBCSRV *s;
464 unsigned int num_servers = 0;
466 for (s = context->internal->servers; s; s = s->next) {
467 num_servers++;
468 if (s->cli->trans_enc_state == NULL) {
469 return (void *)false;
472 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
473 return (void *) (intptr_t) (bool) (num_servers > 0);
474 #else
475 return (void *) (bool) (num_servers > 0);
476 #endif
478 } else if (strcmp(option_name, "browse_max_lmb_count") == 0) {
479 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
480 return (void *) (intptr_t) smbc_getOptionBrowseMaxLmbCount(context);
481 #else
482 return (void *) smbc_getOptionBrowseMaxLmbCount(context);
483 #endif
485 } else if (strcmp(option_name, "urlencode_readdir_entries") == 0) {
486 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
487 return (void *)(intptr_t) smbc_getOptionUrlEncodeReaddirEntries(context);
488 #else
489 return (void *) (bool) smbc_getOptionUrlEncodeReaddirEntries(context);
490 #endif
492 } else if (strcmp(option_name, "one_share_per_server") == 0) {
493 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
494 return (void *) (intptr_t) smbc_getOptionOneSharePerServer(context);
495 #else
496 return (void *) (bool) smbc_getOptionOneSharePerServer(context);
497 #endif
499 } else if (strcmp(option_name, "use_kerberos") == 0) {
500 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
501 return (void *) (intptr_t) smbc_getOptionUseKerberos(context);
502 #else
503 return (void *) (bool) smbc_getOptionUseKerberos(context);
504 #endif
506 } else if (strcmp(option_name, "fallback_after_kerberos") == 0) {
507 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
508 return (void *)(intptr_t) smbc_getOptionFallbackAfterKerberos(context);
509 #else
510 return (void *) (bool) smbc_getOptionFallbackAfterKerberos(context);
511 #endif
513 } else if (strcmp(option_name, "no_auto_anonymous_login") == 0) {
514 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
515 return (void *) (intptr_t) smbc_getOptionNoAutoAnonymousLogin(context);
516 #else
517 return (void *) (bool) smbc_getOptionNoAutoAnonymousLogin(context);
518 #endif
521 return NULL;
526 * Initialize the library, etc.
528 * We accept a struct containing handle information.
529 * valid values for info->debug from 0 to 100,
530 * and insist that info->fn must be non-null.
532 SMBCCTX *
533 smbc_init_context(SMBCCTX *context)
535 int pid;
536 char *user = NULL;
538 if (!context) {
539 errno = EBADF;
540 return NULL;
543 /* Do not initialise the same client twice */
544 if (context->internal->initialized) {
545 return NULL;
548 if (context->internal->debug_stderr) {
550 * Hmmm... Do we want a unique dbf per-thread? For now, we'll just
551 * leave it up to the user. If any one context spefies debug to
552 * stderr then all will be.
554 dbf = x_stderr;
555 x_setbuf(x_stderr, NULL);
558 if ((!smbc_getFunctionAuthData(context) &&
559 !smbc_getFunctionAuthDataWithContext(context)) ||
560 smbc_getDebug(context) < 0 ||
561 smbc_getDebug(context) > 100) {
563 errno = EINVAL;
564 return NULL;
568 if (!smbc_getUser(context)) {
570 * FIXME: Is this the best way to get the user info?
572 user = getenv("USER");
573 /* walk around as "guest" if no username can be found */
574 if (!user) {
575 user = SMB_STRDUP("guest");
576 } else {
577 user = SMB_STRDUP(user);
580 if (!user) {
581 errno = ENOMEM;
582 return NULL;
585 smbc_setUser(context, user);
588 if (!smbc_getNetbiosName(context)) {
590 * We try to get our netbios name from the config. If that
591 * fails we fall back on constructing our netbios name from
592 * our hostname etc
594 char *netbios_name;
595 if (global_myname()) {
596 netbios_name = SMB_STRDUP(global_myname());
597 } else {
599 * Hmmm, I want to get hostname as well, but I am too
600 * lazy for the moment
602 pid = sys_getpid();
603 netbios_name = (char *)SMB_MALLOC(17);
604 if (!netbios_name) {
605 errno = ENOMEM;
606 return NULL;
608 slprintf(netbios_name, 16,
609 "smbc%s%d", smbc_getUser(context), pid);
612 if (!netbios_name) {
613 errno = ENOMEM;
614 return NULL;
617 smbc_setNetbiosName(context, netbios_name);
620 DEBUG(1, ("Using netbios name %s.\n", smbc_getNetbiosName(context)));
622 if (!smbc_getWorkgroup(context)) {
623 char *workgroup;
625 if (lp_workgroup()) {
626 workgroup = SMB_STRDUP(lp_workgroup());
628 else {
629 /* TODO: Think about a decent default workgroup */
630 workgroup = SMB_STRDUP("samba");
633 if (!workgroup) {
634 errno = ENOMEM;
635 return NULL;
638 smbc_setWorkgroup(context, workgroup);
641 DEBUG(1, ("Using workgroup %s.\n", smbc_getWorkgroup(context)));
643 /* shortest timeout is 1 second */
644 if (smbc_getTimeout(context) > 0 && smbc_getTimeout(context) < 1000)
645 smbc_setTimeout(context, 1000);
647 context->internal->initialized = True;
649 /* Protect access to the count of contexts in use */
650 if (SMB_THREAD_LOCK(initialized_ctx_count_mutex) != 0) {
651 smb_panic("error locking 'initialized_ctx_count'");
654 initialized_ctx_count++;
656 /* Unlock the mutex */
657 if (SMB_THREAD_UNLOCK(initialized_ctx_count_mutex) != 0) {
658 smb_panic("error unlocking 'initialized_ctx_count'");
661 return context;
665 /* Return the verion of samba, and thus libsmbclient */
666 const char *
667 smbc_version(void)
669 return samba_version_string();
673 * Set the credentials so DFS will work when following referrals.
674 * This function is broken and must be removed. No SMBCCTX arg...
675 * JRA.
678 void
679 smbc_set_credentials(const char *workgroup,
680 const char *user,
681 const char *password,
682 smbc_bool use_kerberos,
683 const char *signing_state)
685 d_printf("smbc_set_credentials is obsolete. Replace with smbc_set_credentials_with_fallback().\n");
688 void smbc_set_credentials_with_fallback(SMBCCTX *context,
689 const char *workgroup,
690 const char *user,
691 const char *password)
693 smbc_bool use_kerberos = false;
694 const char *signing_state = "off";
695 struct user_auth_info *auth_info = NULL;
697 if (! context) {
699 return;
702 if (! workgroup || ! *workgroup) {
703 workgroup = smbc_getWorkgroup(context);
706 if (! user) {
707 user = smbc_getUser(context);
710 if (! password) {
711 password = "";
714 auth_info = user_auth_info_init(NULL);
716 if (! auth_info) {
717 DEBUG(0, ("smbc_set_credentials_with_fallback: allocation fail\n"));
718 return;
721 if (smbc_getOptionUseKerberos(context)) {
722 use_kerberos = True;
725 if (lp_client_signing()) {
726 signing_state = "on";
729 if (lp_client_signing() == Required) {
730 signing_state = "force";
733 set_cmdline_auth_info_username(auth_info, user);
734 set_cmdline_auth_info_password(auth_info, password);
735 set_cmdline_auth_info_use_kerberos(auth_info, use_kerberos);
736 set_cmdline_auth_info_signing_state(auth_info, signing_state);
737 set_cmdline_auth_info_fallback_after_kerberos(auth_info,
738 smbc_getOptionFallbackAfterKerberos(context));
739 set_global_myworkgroup(workgroup);
741 TALLOC_FREE(context->internal->auth_info);
743 context->internal->auth_info = auth_info;