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