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