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