Use the macro to call samba_version_string().
[tprouty/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
204         gfree_names();
205         gfree_loadparm();
206         gfree_case_tables();
207         gfree_charcnv();
208         gfree_interfaces();
209
210         gencache_shutdown();
211         secrets_shutdown();
212
213         /* release the talloc null_context memory last */
214         talloc_disable_null_tracking();
215
216         gfree_debugsyms();
217
218         SAFE_FREE(context->internal);
219         SAFE_FREE(context);
220         return 0;
221 }
222
223
224 /**
225  * Deprecated interface.  Do not use.  Instead, use the various
226  * smbc_setOption*() functions or smbc_setFunctionAuthDataWithContext().
227  */
228 void
229 smbc_option_set(SMBCCTX *context,
230                 char *option_name,
231                 ... /* option_value */)
232 {
233         va_list ap;
234         union {
235                 int i;
236                 bool b;
237                 smbc_get_auth_data_with_context_fn auth_fn;
238                 void *v;
239                 const char *s;
240         } option_value;
241         
242         va_start(ap, option_name);
243         
244         if (strcmp(option_name, "debug_to_stderr") == 0) {
245                 option_value.b = (bool) va_arg(ap, int);
246                 smbc_setOptionDebugToStderr(context, option_value.b);
247                 
248         } else if (strcmp(option_name, "full_time_names") == 0) {
249                 option_value.b = (bool) va_arg(ap, int);
250                 smbc_setOptionFullTimeNames(context, option_value.b);
251                 
252         } else if (strcmp(option_name, "open_share_mode") == 0) {
253                 option_value.i = va_arg(ap, int);
254                 smbc_setOptionOpenShareMode(context, option_value.i);
255                 
256         } else if (strcmp(option_name, "auth_function") == 0) {
257                 option_value.auth_fn =
258                         va_arg(ap, smbc_get_auth_data_with_context_fn);
259                 smbc_setFunctionAuthDataWithContext(context, option_value.auth_fn);
260                 
261         } else if (strcmp(option_name, "user_data") == 0) {
262                 option_value.v = va_arg(ap, void *);
263                 smbc_setOptionUserData(context, option_value.v);
264                 
265         } else if (strcmp(option_name, "smb_encrypt_level") == 0) {
266                 option_value.s = va_arg(ap, const char *);
267                 if (strcmp(option_value.s, "none") == 0) {
268                         smbc_setOptionSmbEncryptionLevel(context,
269                                                          SMBC_ENCRYPTLEVEL_NONE);
270                 } else if (strcmp(option_value.s, "request") == 0) {
271                         smbc_setOptionSmbEncryptionLevel(context,
272                                                          SMBC_ENCRYPTLEVEL_REQUEST);
273                 } else if (strcmp(option_value.s, "require") == 0) {
274                         smbc_setOptionSmbEncryptionLevel(context,
275                                                          SMBC_ENCRYPTLEVEL_REQUIRE);
276                 }
277                 
278         } else if (strcmp(option_name, "browse_max_lmb_count") == 0) {
279                 option_value.i = va_arg(ap, int);
280                 smbc_setOptionBrowseMaxLmbCount(context, option_value.i);
281                 
282         } else if (strcmp(option_name, "urlencode_readdir_entries") == 0) {
283                 option_value.b = (bool) va_arg(ap, int);
284                 smbc_setOptionUrlEncodeReaddirEntries(context, option_value.b);
285                 
286         } else if (strcmp(option_name, "one_share_per_server") == 0) {
287                 option_value.b = (bool) va_arg(ap, int);
288                 smbc_setOptionOneSharePerServer(context, option_value.b);
289                 
290         } else if (strcmp(option_name, "use_kerberos") == 0) {
291                 option_value.b = (bool) va_arg(ap, int);
292                 smbc_setOptionUseKerberos(context, option_value.b);
293                 
294         } else if (strcmp(option_name, "fallback_after_kerberos") == 0) {
295                 option_value.b = (bool) va_arg(ap, int);
296                 smbc_setOptionFallbackAfterKerberos(context, option_value.b);
297                 
298         } else if (strcmp(option_name, "no_auto_anonymous_login") == 0) {
299                 option_value.b = (bool) va_arg(ap, int);
300                 smbc_setOptionNoAutoAnonymousLogin(context, option_value.b);
301         }
302         
303         va_end(ap);
304 }
305
306
307 /*
308  * Deprecated interface.  Do not use.  Instead, use the various
309  * smbc_getOption*() functions.
310  */
311 void *
312 smbc_option_get(SMBCCTX *context,
313                 char *option_name)
314 {
315         if (strcmp(option_name, "debug_stderr") == 0) {
316 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
317                 return (void *) (intptr_t) smbc_getOptionDebugToStderr(context);
318 #else
319                 return (void *) smbc_getOptionDebugToStderr(context);
320 #endif
321                 
322         } else if (strcmp(option_name, "full_time_names") == 0) {
323 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
324                 return (void *) (intptr_t) smbc_getOptionFullTimeNames(context);
325 #else
326                 return (void *) smbc_getOptionFullTimeNames(context);
327 #endif
328                 
329         } else if (strcmp(option_name, "open_share_mode") == 0) {
330 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
331                 return (void *) (intptr_t) smbc_getOptionOpenShareMode(context);
332 #else
333                 return (void *) smbc_getOptionOpenShareMode(context);
334 #endif
335                 
336         } else if (strcmp(option_name, "auth_function") == 0) {
337                 return (void *) smbc_getFunctionAuthDataWithContext(context);
338                 
339         } else if (strcmp(option_name, "user_data") == 0) {
340                 return smbc_getOptionUserData(context);
341                 
342         } else if (strcmp(option_name, "smb_encrypt_level") == 0) {
343                 switch(smbc_getOptionSmbEncryptionLevel(context))
344                 {
345                 case 0:
346                         return (void *) "none";
347                 case 1:
348                         return (void *) "request";
349                 case 2:
350                         return (void *) "require";
351                 }
352                 
353         } else if (strcmp(option_name, "smb_encrypt_on") == 0) {
354                 SMBCSRV *s;
355                 unsigned int num_servers = 0;
356                 
357                 for (s = context->internal->servers; s; s = s->next) {
358                         num_servers++;
359                         if (s->cli->trans_enc_state == NULL) {
360                                 return (void *)false;
361                         }
362                 }
363 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
364                 return (void *) (intptr_t) (bool) (num_servers > 0);
365 #else
366                 return (void *) (bool) (num_servers > 0);
367 #endif
368                 
369         } else if (strcmp(option_name, "browse_max_lmb_count") == 0) {
370 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
371                 return (void *) (intptr_t) smbc_getOptionBrowseMaxLmbCount(context);
372 #else
373                 return (void *) smbc_getOptionBrowseMaxLmbCount(context);
374 #endif
375                 
376         } else if (strcmp(option_name, "urlencode_readdir_entries") == 0) {
377 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
378                 return (void *)(intptr_t) smbc_getOptionUrlEncodeReaddirEntries(context);
379 #else
380                 return (void *) (bool) smbc_getOptionUrlEncodeReaddirEntries(context);
381 #endif
382                 
383         } else if (strcmp(option_name, "one_share_per_server") == 0) {
384 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
385                 return (void *) (intptr_t) smbc_getOptionOneSharePerServer(context);
386 #else
387                 return (void *) (bool) smbc_getOptionOneSharePerServer(context);
388 #endif
389                 
390         } else if (strcmp(option_name, "use_kerberos") == 0) {
391 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
392                 return (void *) (intptr_t) smbc_getOptionUseKerberos(context);
393 #else
394                 return (void *) (bool) smbc_getOptionUseKerberos(context);
395 #endif
396                 
397         } else if (strcmp(option_name, "fallback_after_kerberos") == 0) {
398 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
399                 return (void *)(intptr_t) smbc_getOptionFallbackAfterKerberos(context);
400 #else
401                 return (void *) (bool) smbc_getOptionFallbackAfterKerberos(context);
402 #endif
403                 
404         } else if (strcmp(option_name, "no_auto_anonymous_login") == 0) {
405 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
406                 return (void *) (intptr_t) smbc_getOptionNoAutoAnonymousLogin(context);
407 #else
408                 return (void *) (bool) smbc_getOptionNoAutoAnonymousLogin(context);
409 #endif
410         }
411         
412         return NULL;
413 }
414
415
416 /*
417  * Initialize the library, etc.
418  *
419  * We accept a struct containing handle information.
420  * valid values for info->debug from 0 to 100,
421  * and insist that info->fn must be non-null.
422  */
423 SMBCCTX *
424 smbc_init_context(SMBCCTX *context)
425 {
426         int pid;
427         char *user = NULL;
428         char *home = NULL;
429         
430         /* track talloc null_context memory */
431         talloc_enable_null_tracking();
432
433         if (!context) {
434                 errno = EBADF;
435                 return NULL;
436         }
437         
438         /* Do not initialise the same client twice */
439         if (context->internal->initialized) {
440                 return NULL;
441         }
442         
443         if ((!smbc_getFunctionAuthData(context) &&
444              !smbc_getFunctionAuthDataWithContext(context)) ||
445             smbc_getDebug(context) < 0 ||
446             smbc_getDebug(context) > 100) {
447                 
448                 errno = EINVAL;
449                 return NULL;
450                 
451         }
452         
453         if (!SMBC_initialized) {
454                 /*
455                  * Do some library-wide intializations the first time we get
456                  * called
457                  */
458                 bool conf_loaded = False;
459                 TALLOC_CTX *frame = talloc_stackframe();
460                 
461                 load_case_tables();
462                 
463                 setup_logging("libsmbclient", True);
464                 if (context->internal->debug_stderr) {
465                         dbf = x_stderr;
466                         x_setbuf(x_stderr, NULL);
467                 }
468                 
469                 /* Here we would open the smb.conf file if needed ... */
470                 
471                 lp_set_in_client(True);
472                 
473                 home = getenv("HOME");
474                 if (home) {
475                         char *conf = NULL;
476                         if (asprintf(&conf, "%s/.smb/smb.conf", home) > 0) {
477                                 if (lp_load(conf, True, False, False, True)) {
478                                         conf_loaded = True;
479                                 } else {
480                                         DEBUG(5, ("Could not load config file: %s\n",
481                                                   conf));
482                                 }
483                                 SAFE_FREE(conf);
484                         }
485                 }
486                 
487                 if (!conf_loaded) {
488                         /*
489                          * Well, if that failed, try the get_dyn_CONFIGFILE
490                          * Which points to the standard locn, and if that
491                          * fails, silently ignore it and use the internal
492                          * defaults ...
493                          */
494                         
495                         if (!lp_load(get_dyn_CONFIGFILE(), True, False, False, False)) {
496                                 DEBUG(5, ("Could not load config file: %s\n",
497                                           get_dyn_CONFIGFILE()));
498                         } else if (home) {
499                                 char *conf;
500                                 /*
501                                  * We loaded the global config file.  Now lets
502                                  * load user-specific modifications to the
503                                  * global config.
504                                  */
505                                 if (asprintf(&conf,
506                                              "%s/.smb/smb.conf.append",
507                                              home) > 0) {
508                                         if (!lp_load(conf, True, False, False, False)) {
509                                                 DEBUG(10,
510                                                       ("Could not append config file: "
511                                                        "%s\n",
512                                                        conf));
513                                         }
514                                         SAFE_FREE(conf);
515                                 }
516                         }
517                 }
518                 
519                 load_interfaces();  /* Load the list of interfaces ... */
520                 
521                 reopen_logs();  /* Get logging working ... */
522                 
523                 /*
524                  * Block SIGPIPE (from lib/util_sock.c: write())
525                  * It is not needed and should not stop execution
526                  */
527                 BlockSignals(True, SIGPIPE);
528                 
529                 /* Done with one-time initialisation */
530                 SMBC_initialized = 1;
531                 
532                 TALLOC_FREE(frame);
533         }
534         
535         if (!smbc_getUser(context)) {
536                 /*
537                  * FIXME: Is this the best way to get the user info?
538                  */
539                 user = getenv("USER");
540                 /* walk around as "guest" if no username can be found */
541                 if (!user) {
542                         user = SMB_STRDUP("guest");
543                 } else {
544                         user = SMB_STRDUP(user);
545                 }
546
547                 if (!user) {
548                         errno = ENOMEM;
549                         return NULL;
550                 }
551
552                 smbc_setUser(context, user);
553         }
554         
555         if (!smbc_getNetbiosName(context)) {
556                 /*
557                  * We try to get our netbios name from the config. If that
558                  * fails we fall back on constructing our netbios name from
559                  * our hostname etc
560                  */
561                 char *netbios_name;
562                 if (global_myname()) {
563                         netbios_name = SMB_STRDUP(global_myname());
564                 } else {
565                         /*
566                          * Hmmm, I want to get hostname as well, but I am too
567                          * lazy for the moment
568                          */
569                         pid = sys_getpid();
570                         netbios_name = (char *)SMB_MALLOC(17);
571                         if (!netbios_name) {
572                                 errno = ENOMEM;
573                                 return NULL;
574                         }
575                         slprintf(netbios_name, 16,
576                                  "smbc%s%d", smbc_getUser(context), pid);
577                 }
578
579                 if (!netbios_name) {
580                         errno = ENOMEM;
581                         return NULL;
582                 }
583                 
584                 smbc_setNetbiosName(context, netbios_name);
585         }
586         
587         DEBUG(1, ("Using netbios name %s.\n", smbc_getNetbiosName(context)));
588         
589         if (!smbc_getWorkgroup(context)) {
590                 char *workgroup;
591
592                 if (lp_workgroup()) {
593                         workgroup = SMB_STRDUP(lp_workgroup());
594                 }
595                 else {
596                         /* TODO: Think about a decent default workgroup */
597                         workgroup = SMB_STRDUP("samba");
598                 }
599
600                 if (!workgroup) {
601                         errno = ENOMEM;
602                         return NULL;
603                 }
604
605                 smbc_setWorkgroup(context, workgroup);
606         }
607         
608         DEBUG(1, ("Using workgroup %s.\n", smbc_getWorkgroup(context)));
609         
610         /* shortest timeout is 1 second */
611         if (smbc_getTimeout(context) > 0 && smbc_getTimeout(context) < 1000)
612                 smbc_setTimeout(context, 1000);
613         
614         /*
615          * FIXME: Should we check the function pointers here?
616          */
617         
618         context->internal->initialized = True;
619         
620         return context;
621 }
622
623
624 /* Return the verion of samba, and thus libsmbclient */
625 const char *
626 smbc_version(void)
627 {
628         return SAMBA_VERSION_STRING;
629 }
630
631
632 /*
633  * Set the credentials so DFS will work when following referrals.
634  */
635 void
636 smbc_set_credentials(char *workgroup,
637                      char *user,
638                      char *password,
639                      smbc_bool use_kerberos,
640                      char *signing_state)
641 {
642         
643         set_cmdline_auth_info_username(user);
644         set_cmdline_auth_info_password(password);
645         set_cmdline_auth_info_use_kerberos(use_kerberos);
646         if (! set_cmdline_auth_info_signing_state(signing_state)) {
647                 DEBUG(0, ("Invalid signing state: %s", signing_state));
648         }
649         set_global_myworkgroup(workgroup);
650         cli_cm_set_credentials();
651 }