Treat file names in POSIX-like case-sensitive fashion by default
[samba.git] / source3 / libsmb / libsmb_server.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  * Check a server for being alive and well.
32  * returns 0 if the server is in shape. Returns 1 on error 
33  * 
34  * Also useable outside libsmbclient to enable external cache
35  * to do some checks too.
36  */
37 int
38 SMBC_check_server(SMBCCTX * context,
39                   SMBCSRV * server) 
40 {
41         socklen_t size;
42         struct sockaddr addr;
43
44         size = sizeof(addr);
45         return (getpeername(server->cli->fd, &addr, &size) == -1);
46 }
47
48 /* 
49  * Remove a server from the cached server list it's unused.
50  * On success, 0 is returned. 1 is returned if the server could not be removed.
51  * 
52  * Also useable outside libsmbclient
53  */
54 int
55 SMBC_remove_unused_server(SMBCCTX * context,
56                           SMBCSRV * srv)
57 {
58         SMBCFILE * file;
59
60         /* are we being fooled ? */
61         if (!context || !context->internal->initialized || !srv) {
62                 return 1;
63         }
64
65         /* Check all open files/directories for a relation with this server */
66         for (file = context->internal->files; file; file = file->next) {
67                 if (file->srv == srv) {
68                         /* Still used */
69                         DEBUG(3, ("smbc_remove_usused_server: "
70                                   "%p still used by %p.\n",
71                                   srv, file));
72                         return 1;
73                 }
74         }
75
76         DLIST_REMOVE(context->internal->servers, srv);
77
78         cli_shutdown(srv->cli);
79         srv->cli = NULL;
80
81         DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
82
83         smbc_getFunctionRemoveCachedServer(context)(context, srv);
84
85         SAFE_FREE(srv);
86         return 0;
87 }
88
89 /****************************************************************
90  * Call the auth_fn with fixed size (fstring) buffers.
91  ***************************************************************/
92 void
93 SMBC_call_auth_fn(TALLOC_CTX *ctx,
94                   SMBCCTX *context,
95                   const char *server,
96                   const char *share,
97                   char **pp_workgroup,
98                   char **pp_username,
99                   char **pp_password)
100 {
101         fstring workgroup;
102         fstring username;
103         fstring password;
104         smbc_get_auth_data_with_context_fn auth_with_context_fn;
105
106         strlcpy(workgroup, *pp_workgroup, sizeof(workgroup));
107         strlcpy(username, *pp_username, sizeof(username));
108         strlcpy(password, *pp_password, sizeof(password));
109
110         /* See if there's an authentication with context function provided */
111         auth_with_context_fn = smbc_getFunctionAuthDataWithContext(context);
112         if (auth_with_context_fn)
113         {
114             (* auth_with_context_fn)(context,
115                                      server, share,
116                                      workgroup, sizeof(workgroup),
117                                      username, sizeof(username),
118                                      password, sizeof(password));
119         }
120         else
121         {
122             smbc_getFunctionAuthData(context)(server, share,
123                                               workgroup, sizeof(workgroup),
124                                               username, sizeof(username),
125                                               password, sizeof(password));
126         }
127
128         TALLOC_FREE(*pp_workgroup);
129         TALLOC_FREE(*pp_username);
130         TALLOC_FREE(*pp_password);
131
132         *pp_workgroup = talloc_strdup(ctx, workgroup);
133         *pp_username = talloc_strdup(ctx, username);
134         *pp_password = talloc_strdup(ctx, password);
135 }
136
137
138 void
139 SMBC_get_auth_data(const char *server, const char *share,
140                    char *workgroup_buf, int workgroup_buf_len,
141                    char *username_buf, int username_buf_len,
142                    char *password_buf, int password_buf_len)
143 {
144         /* Default function just uses provided data.  Nothing to do. */
145 }
146
147
148
149 SMBCSRV *
150 SMBC_find_server(TALLOC_CTX *ctx,
151                  SMBCCTX *context,
152                  const char *server,
153                  const char *share,
154                  char **pp_workgroup,
155                  char **pp_username,
156                  char **pp_password)
157 {
158         SMBCSRV *srv;
159         int auth_called = 0;
160
161         if (!pp_workgroup || !pp_username || !pp_password) {
162                 return NULL;
163         }
164
165 check_server_cache:
166
167         srv = smbc_getFunctionGetCachedServer(context)(context,
168                                                        server, share,
169                                                        *pp_workgroup,
170                                                        *pp_username);
171
172         if (!auth_called && !srv && (!*pp_username || !(*pp_username)[0] ||
173                                      !*pp_password || !(*pp_password)[0])) {
174                 SMBC_call_auth_fn(ctx, context, server, share,
175                                   pp_workgroup, pp_username, pp_password);
176
177                 /*
178                  * However, smbc_auth_fn may have picked up info relating to
179                  * an existing connection, so try for an existing connection
180                  * again ...
181                  */
182                 auth_called = 1;
183                 goto check_server_cache;
184
185         }
186
187         if (srv) {
188                 if (smbc_getFunctionCheckServer(context)(context, srv)) {
189                         /*
190                          * This server is no good anymore
191                          * Try to remove it and check for more possible
192                          * servers in the cache
193                          */
194                         if (smbc_getFunctionRemoveUnusedServer(context)(context,
195                                                                         srv)) { 
196                                 /*
197                                  * We could not remove the server completely,
198                                  * remove it from the cache so we will not get
199                                  * it again. It will be removed when the last
200                                  * file/dir is closed.
201                                  */
202                                 smbc_getFunctionRemoveCachedServer(context)(context,
203                                                                             srv);
204                         }
205
206                         /*
207                          * Maybe there are more cached connections to this
208                          * server
209                          */
210                         goto check_server_cache;
211                 }
212
213                 return srv;
214         }
215
216         return NULL;
217 }
218
219 /*
220  * Connect to a server, possibly on an existing connection
221  *
222  * Here, what we want to do is: If the server and username
223  * match an existing connection, reuse that, otherwise, establish a
224  * new connection.
225  *
226  * If we have to create a new connection, call the auth_fn to get the
227  * info we need, unless the username and password were passed in.
228  */
229
230 SMBCSRV *
231 SMBC_server(TALLOC_CTX *ctx,
232             SMBCCTX *context,
233             bool connect_if_not_found,
234             const char *server,
235             const char *share,
236             char **pp_workgroup,
237             char **pp_username,
238             char **pp_password)
239 {
240         SMBCSRV *srv=NULL;
241         struct cli_state *c;
242         struct nmb_name called, calling;
243         const char *server_n = server;
244         struct sockaddr_storage ss;
245         int tried_reverse = 0;
246         int port_try_first;
247         int port_try_next;
248         const char *username_used;
249         NTSTATUS status;
250
251         zero_sockaddr(&ss);
252         ZERO_STRUCT(c);
253
254         if (server[0] == 0) {
255                 errno = EPERM;
256                 return NULL;
257         }
258
259         /* Look for a cached connection */
260         srv = SMBC_find_server(ctx, context, server, share,
261                                pp_workgroup, pp_username, pp_password);
262
263         /*
264          * If we found a connection and we're only allowed one share per
265          * server...
266          */
267         if (srv &&
268             *share != '\0' &&
269             smbc_getOptionOneSharePerServer(context)) {
270
271                 /*
272                  * ... then if there's no current connection to the share,
273                  * connect to it.  SMBC_find_server(), or rather the function
274                  * pointed to by context->get_cached_srv_fn which
275                  * was called by SMBC_find_server(), will have issued a tree
276                  * disconnect if the requested share is not the same as the
277                  * one that was already connected.
278                  */
279                 if (srv->cli->cnum == (uint16) -1) {
280                         /* Ensure we have accurate auth info */
281                         SMBC_call_auth_fn(ctx, context, server, share,
282                                           pp_workgroup,
283                                           pp_username,
284                                           pp_password);
285
286                         if (!*pp_workgroup || !*pp_username || !*pp_password) {
287                                 errno = ENOMEM;
288                                 cli_shutdown(srv->cli);
289                                 srv->cli = NULL;
290                                 smbc_getFunctionRemoveCachedServer(context)(context,
291                                                                             srv);
292                                 return NULL;
293                         }
294
295                         /*
296                          * We don't need to renegotiate encryption
297                          * here as the encryption context is not per
298                          * tid.
299                          */
300
301                         if (!cli_send_tconX(srv->cli, share, "?????",
302                                             *pp_password,
303                                             strlen(*pp_password)+1)) {
304
305                                 errno = SMBC_errno(context, srv->cli);
306                                 cli_shutdown(srv->cli);
307                                 srv->cli = NULL;
308                                 smbc_getFunctionRemoveCachedServer(context)(context,
309                                                                             srv);
310                                 srv = NULL;
311                         }
312
313                         /*
314                          * Regenerate the dev value since it's based on both
315                          * server and share
316                          */
317                         if (srv) {
318                                 srv->dev = (dev_t)(str_checksum(server) ^
319                                                    str_checksum(share));
320                         }
321                 }
322         }
323
324         /* If we have a connection... */
325         if (srv) {
326
327                 /* ... then we're done here.  Give 'em what they came for. */
328                 return srv;
329         }
330
331         /* If we're not asked to connect when a connection doesn't exist... */
332         if (! connect_if_not_found) {
333                 /* ... then we're done here. */
334                 return NULL;
335         }
336
337         if (!*pp_workgroup || !*pp_username || !*pp_password) {
338                 errno = ENOMEM;
339                 return NULL;
340         }
341
342         make_nmb_name(&calling, smbc_getNetbiosName(context), 0x0);
343         make_nmb_name(&called , server, 0x20);
344
345         DEBUG(4,("SMBC_server: server_n=[%s] server=[%s]\n", server_n, server));
346
347         DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
348
349 again:
350
351         zero_sockaddr(&ss);
352
353         /* have to open a new connection */
354         if ((c = cli_initialise()) == NULL) {
355                 errno = ENOMEM;
356                 return NULL;
357         }
358
359         /* POSIX-like - always request case-sensitivity by default. */        
360         if (smbc_getOptionCaseSensitive(context)) {
361             cli_set_case_sensitive(c, True);
362         } else {
363             cli_set_case_sensitive(c, False);
364         }
365
366         if (smbc_getOptionUseKerberos(context)) {
367                 c->use_kerberos = True;
368         }
369
370         if (smbc_getOptionFallbackAfterKerberos(context)) {
371                 c->fallback_after_kerberos = True;
372         }
373
374         c->timeout = smbc_getTimeout(context);
375
376         /*
377          * Force use of port 139 for first try if share is $IPC, empty, or
378          * null, so browse lists can work
379          */
380         if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
381                 port_try_first = 139;
382                 port_try_next = 445;
383         } else {
384                 port_try_first = 445;
385                 port_try_next = 139;
386         }
387
388         c->port = port_try_first;
389
390         status = cli_connect(c, server_n, &ss);
391         if (!NT_STATUS_IS_OK(status)) {
392
393                 /* First connection attempt failed.  Try alternate port. */
394                 c->port = port_try_next;
395
396                 status = cli_connect(c, server_n, &ss);
397                 if (!NT_STATUS_IS_OK(status)) {
398                         cli_shutdown(c);
399                         errno = ETIMEDOUT;
400                         return NULL;
401                 }
402         }
403
404         if (!cli_session_request(c, &calling, &called)) {
405                 cli_shutdown(c);
406                 if (strcmp(called.name, "*SMBSERVER")) {
407                         make_nmb_name(&called , "*SMBSERVER", 0x20);
408                         goto again;
409                 } else {  /* Try one more time, but ensure we don't loop */
410
411                         /* Only try this if server is an IP address ... */
412
413                         if (is_ipaddress(server) && !tried_reverse) {
414                                 fstring remote_name;
415                                 struct sockaddr_storage rem_ss;
416
417                                 if (!interpret_string_addr(&rem_ss, server,
418                                                            NI_NUMERICHOST)) {
419                                         DEBUG(4, ("Could not convert IP address "
420                                                   "%s to struct sockaddr_storage\n",
421                                                   server));
422                                         errno = ETIMEDOUT;
423                                         return NULL;
424                                 }
425
426                                 tried_reverse++; /* Yuck */
427
428                                 if (name_status_find("*", 0, 0,
429                                                      &rem_ss, remote_name)) {
430                                         make_nmb_name(&called,
431                                                       remote_name,
432                                                       0x20);
433                                         goto again;
434                                 }
435                         }
436                 }
437                 errno = ETIMEDOUT;
438                 return NULL;
439         }
440
441         DEBUG(4,(" session request ok\n"));
442
443         status = cli_negprot(c);
444
445         if (!NT_STATUS_IS_OK(status)) {
446                 cli_shutdown(c);
447                 errno = ETIMEDOUT;
448                 return NULL;
449         }
450
451         username_used = *pp_username;
452
453         if (!NT_STATUS_IS_OK(cli_session_setup(c, username_used,
454                                                *pp_password,
455                                                strlen(*pp_password),
456                                                *pp_password,
457                                                strlen(*pp_password),
458                                                *pp_workgroup))) {
459
460                 /* Failed.  Try an anonymous login, if allowed by flags. */
461                 username_used = "";
462
463                 if (smbc_getOptionNoAutoAnonymousLogin(context) ||
464                     !NT_STATUS_IS_OK(cli_session_setup(c, username_used,
465                                                        *pp_password, 1,
466                                                        *pp_password, 0,
467                                                        *pp_workgroup))) {
468
469                         cli_shutdown(c);
470                         errno = EPERM;
471                         return NULL;
472                 }
473         }
474
475         DEBUG(4,(" session setup ok\n"));
476
477         if (!cli_send_tconX(c, share, "?????",
478                             *pp_password, strlen(*pp_password)+1)) {
479                 errno = SMBC_errno(context, c);
480                 cli_shutdown(c);
481                 return NULL;
482         }
483
484         DEBUG(4,(" tconx ok\n"));
485
486         if (context->internal->smb_encryption_level) {
487                 /* Attempt UNIX smb encryption. */
488                 if (!NT_STATUS_IS_OK(cli_force_encryption(c,
489                                                           username_used,
490                                                           *pp_password,
491                                                           *pp_workgroup))) {
492
493                         /*
494                          * context->smb_encryption_level == 1
495                          * means don't fail if encryption can't be negotiated,
496                          * == 2 means fail if encryption can't be negotiated.
497                          */
498
499                         DEBUG(4,(" SMB encrypt failed\n"));
500
501                         if (context->internal->smb_encryption_level == 2) {
502                                 cli_shutdown(c);
503                                 errno = EPERM;
504                                 return NULL;
505                         }
506                 }
507                 DEBUG(4,(" SMB encrypt ok\n"));
508         }
509
510         /*
511          * Ok, we have got a nice connection
512          * Let's allocate a server structure.
513          */
514
515         srv = SMB_MALLOC_P(SMBCSRV);
516         if (!srv) {
517                 errno = ENOMEM;
518                 goto failed;
519         }
520
521         ZERO_STRUCTP(srv);
522         srv->cli = c;
523         srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
524         srv->no_pathinfo = False;
525         srv->no_pathinfo2 = False;
526         srv->no_nt_session = False;
527
528         /* now add it to the cache (internal or external)  */
529         /* Let the cache function set errno if it wants to */
530         errno = 0;
531         if (smbc_getFunctionAddCachedServer(context)(context, srv,
532                                                      server, share,
533                                                      *pp_workgroup,
534                                                      *pp_username)) {
535                 int saved_errno = errno;
536                 DEBUG(3, (" Failed to add server to cache\n"));
537                 errno = saved_errno;
538                 if (errno == 0) {
539                         errno = ENOMEM;
540                 }
541                 goto failed;
542         }
543
544         DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
545                   server, share, srv));
546
547         DLIST_ADD(context->internal->servers, srv);
548         return srv;
549
550 failed:
551         cli_shutdown(c);
552         if (!srv) {
553                 return NULL;
554         }
555
556         SAFE_FREE(srv);
557         return NULL;
558 }
559
560 /*
561  * Connect to a server for getting/setting attributes, possibly on an existing
562  * connection.  This works similarly to SMBC_server().
563  */
564 SMBCSRV *
565 SMBC_attr_server(TALLOC_CTX *ctx,
566                  SMBCCTX *context,
567                  const char *server,
568                  const char *share,
569                  char **pp_workgroup,
570                  char **pp_username,
571                  char **pp_password)
572 {
573         int flags;
574         struct sockaddr_storage ss;
575         struct cli_state *ipc_cli;
576         struct rpc_pipe_client *pipe_hnd;
577         NTSTATUS nt_status;
578         SMBCSRV *ipc_srv=NULL;
579
580         /*
581          * See if we've already created this special connection.  Reference
582          * our "special" share name '*IPC$', which is an impossible real share
583          * name due to the leading asterisk.
584          */
585         ipc_srv = SMBC_find_server(ctx, context, server, "*IPC$",
586                                    pp_workgroup, pp_username, pp_password);
587         if (!ipc_srv) {
588
589                 /* We didn't find a cached connection.  Get the password */
590                 if (!*pp_password || (*pp_password)[0] == '\0') {
591                         /* ... then retrieve it now. */
592                         SMBC_call_auth_fn(ctx, context, server, share,
593                                           pp_workgroup,
594                                           pp_username,
595                                           pp_password);
596                         if (!*pp_workgroup || !*pp_username || !*pp_password) {
597                                 errno = ENOMEM;
598                                 return NULL;
599                         }
600                 }
601
602                 flags = 0;
603                 if (smbc_getOptionUseKerberos(context)) {
604                         flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
605                 }
606
607                 zero_sockaddr(&ss);
608                 nt_status = cli_full_connection(&ipc_cli,
609                                                 global_myname(), server,
610                                                 &ss, 0, "IPC$", "?????",
611                                                 *pp_username,
612                                                 *pp_workgroup,
613                                                 *pp_password,
614                                                 flags,
615                                                 Undefined, NULL);
616                 if (! NT_STATUS_IS_OK(nt_status)) {
617                         DEBUG(1,("cli_full_connection failed! (%s)\n",
618                                  nt_errstr(nt_status)));
619                         errno = ENOTSUP;
620                         return NULL;
621                 }
622
623                 if (context->internal->smb_encryption_level) {
624                         /* Attempt UNIX smb encryption. */
625                         if (!NT_STATUS_IS_OK(cli_force_encryption(ipc_cli,
626                                                                   *pp_username,
627                                                                   *pp_password,
628                                                                   *pp_workgroup))) {
629
630                                 /*
631                                  * context->smb_encryption_level ==
632                                  * 1 means don't fail if encryption can't be
633                                  * negotiated, == 2 means fail if encryption
634                                  * can't be negotiated.
635                                  */
636
637                                 DEBUG(4,(" SMB encrypt failed on IPC$\n"));
638
639                                 if (context->internal->smb_encryption_level == 2) {
640                                         cli_shutdown(ipc_cli);
641                                         errno = EPERM;
642                                         return NULL;
643                                 }
644                         }
645                         DEBUG(4,(" SMB encrypt ok on IPC$\n"));
646                 }
647
648                 ipc_srv = SMB_MALLOC_P(SMBCSRV);
649                 if (!ipc_srv) {
650                         errno = ENOMEM;
651                         cli_shutdown(ipc_cli);
652                         return NULL;
653                 }
654
655                 ZERO_STRUCTP(ipc_srv);
656                 ipc_srv->cli = ipc_cli;
657
658                 nt_status = cli_rpc_pipe_open_noauth(
659                         ipc_srv->cli, &ndr_table_lsarpc.syntax_id, &pipe_hnd);
660                 if (!NT_STATUS_IS_OK(nt_status)) {
661                         DEBUG(1, ("cli_nt_session_open fail!\n"));
662                         errno = ENOTSUP;
663                         cli_shutdown(ipc_srv->cli);
664                         free(ipc_srv);
665                         return NULL;
666                 }
667
668                 /*
669                  * Some systems don't support
670                  * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
671                  * so we might as well do it too.
672                  */
673
674                 nt_status = rpccli_lsa_open_policy(
675                         pipe_hnd,
676                         talloc_tos(),
677                         True,
678                         GENERIC_EXECUTE_ACCESS,
679                         &ipc_srv->pol);
680
681                 if (!NT_STATUS_IS_OK(nt_status)) {
682                         errno = SMBC_errno(context, ipc_srv->cli);
683                         cli_shutdown(ipc_srv->cli);
684                         return NULL;
685                 }
686
687                 /* now add it to the cache (internal or external) */
688
689                 errno = 0;      /* let cache function set errno if it likes */
690                 if (smbc_getFunctionAddCachedServer(context)(context, ipc_srv,
691                                                              server,
692                                                              "*IPC$",
693                                                              *pp_workgroup,
694                                                              *pp_username)) {
695                         DEBUG(3, (" Failed to add server to cache\n"));
696                         if (errno == 0) {
697                                 errno = ENOMEM;
698                         }
699                         cli_shutdown(ipc_srv->cli);
700                         free(ipc_srv);
701                         return NULL;
702                 }
703
704                 DLIST_ADD(context->internal->servers, ipc_srv);
705         }
706
707         return ipc_srv;
708 }