libsmbclient: Allow server (NetApp) to return STATUS_INVALID_PARAMETER from an echo.
[nivanova/samba-autobuild/.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    Copyright (C) SATOH Fumiyasu <fumiyas@osstech.co.jp> 2009.
11
12    This program is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3 of the License, or
15    (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 */
25
26 #include "includes.h"
27 #include "libsmb/libsmb.h"
28 #include "libsmbclient.h"
29 #include "libsmb_internal.h"
30 #include "../librpc/gen_ndr/ndr_lsa.h"
31 #include "rpc_client/cli_pipe.h"
32 #include "rpc_client/cli_lsarpc.h"
33 #include "libcli/security/security.h"
34 #include "libsmb/nmblib.h"
35 #include "../libcli/smb/smbXcli_base.h"
36
37 /*
38  * Check a server for being alive and well.
39  * returns 0 if the server is in shape. Returns 1 on error
40  *
41  * Also useable outside libsmbclient to enable external cache
42  * to do some checks too.
43  */
44 int
45 SMBC_check_server(SMBCCTX * context,
46                   SMBCSRV * server)
47 {
48         time_t now;
49
50         if (!cli_state_is_connected(server->cli)) {
51                 return 1;
52         }
53
54         now = time_mono(NULL);
55
56         if (server->last_echo_time == (time_t)0 ||
57                         now > server->last_echo_time +
58                                 (server->cli->timeout/1000)) {
59                 unsigned char data[16] = {0};
60                 NTSTATUS status = cli_echo(server->cli,
61                                         1,
62                                         data_blob_const(data, sizeof(data)));
63                 if (!NT_STATUS_IS_OK(status)) {
64                         /*
65                          * Some NetApp servers return
66                          * NT_STATUS_INVALID_PARAMETER.That's OK, they still
67                          * replied.
68                          * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13007
69                          */
70                         if (!NT_STATUS_EQUAL(status,
71                                         NT_STATUS_INVALID_PARAMETER)) {
72                                 return 1;
73                         }
74                 }
75                 server->last_echo_time = now;
76         }
77         return 0;
78 }
79
80 /*
81  * Remove a server from the cached server list it's unused.
82  * On success, 0 is returned. 1 is returned if the server could not be removed.
83  *
84  * Also useable outside libsmbclient
85  */
86 int
87 SMBC_remove_unused_server(SMBCCTX * context,
88                           SMBCSRV * srv)
89 {
90         SMBCFILE * file;
91
92         /* are we being fooled ? */
93         if (!context || !context->internal->initialized || !srv) {
94                 return 1;
95         }
96
97         /* Check all open files/directories for a relation with this server */
98         for (file = context->internal->files; file; file = file->next) {
99                 if (file->srv == srv) {
100                         /* Still used */
101                         DEBUG(3, ("smbc_remove_usused_server: "
102                                   "%p still used by %p.\n",
103                                   srv, file));
104                         return 1;
105                 }
106         }
107
108         DLIST_REMOVE(context->internal->servers, srv);
109
110         cli_shutdown(srv->cli);
111         srv->cli = NULL;
112
113         DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
114
115         smbc_getFunctionRemoveCachedServer(context)(context, srv);
116
117         SAFE_FREE(srv);
118         return 0;
119 }
120
121 /****************************************************************
122  * Call the auth_fn with fixed size (fstring) buffers.
123  ***************************************************************/
124 static void
125 SMBC_call_auth_fn(TALLOC_CTX *ctx,
126                   SMBCCTX *context,
127                   const char *server,
128                   const char *share,
129                   char **pp_workgroup,
130                   char **pp_username,
131                   char **pp_password)
132 {
133         fstring workgroup = { 0 };
134         fstring username = { 0 };
135         fstring password = { 0 };
136         smbc_get_auth_data_with_context_fn auth_with_context_fn;
137
138         if (*pp_workgroup != NULL) {
139                 strlcpy(workgroup, *pp_workgroup, sizeof(workgroup));
140         }
141         if (*pp_username != NULL) {
142                 strlcpy(username, *pp_username, sizeof(username));
143         }
144         if (*pp_password != NULL) {
145                 strlcpy(password, *pp_password, sizeof(password));
146         }
147
148         /* See if there's an authentication with context function provided */
149         auth_with_context_fn = smbc_getFunctionAuthDataWithContext(context);
150         if (auth_with_context_fn)
151         {
152             (* auth_with_context_fn)(context,
153                                      server, share,
154                                      workgroup, sizeof(workgroup),
155                                      username, sizeof(username),
156                                      password, sizeof(password));
157         }
158         else
159         {
160             smbc_getFunctionAuthData(context)(server, share,
161                                               workgroup, sizeof(workgroup),
162                                               username, sizeof(username),
163                                               password, sizeof(password));
164         }
165
166         TALLOC_FREE(*pp_workgroup);
167         TALLOC_FREE(*pp_username);
168         TALLOC_FREE(*pp_password);
169
170         *pp_workgroup = talloc_strdup(ctx, workgroup);
171         *pp_username = talloc_strdup(ctx, username);
172         *pp_password = talloc_strdup(ctx, password);
173 }
174
175
176 void
177 SMBC_get_auth_data(const char *server, const char *share,
178                    char *workgroup_buf, int workgroup_buf_len,
179                    char *username_buf, int username_buf_len,
180                    char *password_buf, int password_buf_len)
181 {
182         /* Default function just uses provided data.  Nothing to do. */
183 }
184
185
186
187 SMBCSRV *
188 SMBC_find_server(TALLOC_CTX *ctx,
189                  SMBCCTX *context,
190                  const char *server,
191                  const char *share,
192                  char **pp_workgroup,
193                  char **pp_username,
194                  char **pp_password)
195 {
196         SMBCSRV *srv;
197         int auth_called = 0;
198
199         if (!pp_workgroup || !pp_username || !pp_password) {
200                 return NULL;
201         }
202
203 check_server_cache:
204
205         srv = smbc_getFunctionGetCachedServer(context)(context,
206                                                        server, share,
207                                                        *pp_workgroup,
208                                                        *pp_username);
209
210         if (!auth_called && !srv && (!*pp_username || !(*pp_username)[0] ||
211                                      !*pp_password || !(*pp_password)[0])) {
212                 SMBC_call_auth_fn(ctx, context, server, share,
213                                   pp_workgroup, pp_username, pp_password);
214
215                 /*
216                  * However, smbc_auth_fn may have picked up info relating to
217                  * an existing connection, so try for an existing connection
218                  * again ...
219                  */
220                 auth_called = 1;
221                 goto check_server_cache;
222
223         }
224
225         if (srv) {
226                 if (smbc_getFunctionCheckServer(context)(context, srv)) {
227                         /*
228                          * This server is no good anymore
229                          * Try to remove it and check for more possible
230                          * servers in the cache
231                          */
232                         if (smbc_getFunctionRemoveUnusedServer(context)(context,
233                                                                         srv)) {
234                                 /*
235                                  * We could not remove the server completely,
236                                  * remove it from the cache so we will not get
237                                  * it again. It will be removed when the last
238                                  * file/dir is closed.
239                                  */
240                                 smbc_getFunctionRemoveCachedServer(context)(context,
241                                                                             srv);
242                         }
243
244                         /*
245                          * Maybe there are more cached connections to this
246                          * server
247                          */
248                         goto check_server_cache;
249                 }
250
251                 return srv;
252         }
253
254         return NULL;
255 }
256
257 /*
258  * Connect to a server, possibly on an existing connection
259  *
260  * Here, what we want to do is: If the server and username
261  * match an existing connection, reuse that, otherwise, establish a
262  * new connection.
263  *
264  * If we have to create a new connection, call the auth_fn to get the
265  * info we need, unless the username and password were passed in.
266  */
267
268 static SMBCSRV *
269 SMBC_server_internal(TALLOC_CTX *ctx,
270             SMBCCTX *context,
271             bool connect_if_not_found,
272             const char *server,
273             uint16_t port,
274             const char *share,
275             char **pp_workgroup,
276             char **pp_username,
277             char **pp_password,
278             bool *in_cache)
279 {
280         SMBCSRV *srv=NULL;
281         char *workgroup = NULL;
282         struct cli_state *c = NULL;
283         const char *server_n = server;
284         int is_ipc = (share != NULL && strcmp(share, "IPC$") == 0);
285         uint32_t fs_attrs = 0;
286         const char *username_used = NULL;
287         const char *password_used = NULL;
288         NTSTATUS status;
289         char *newserver, *newshare;
290         int flags = 0;
291         struct smbXcli_tcon *tcon = NULL;
292         int signing_state = SMB_SIGNING_DEFAULT;
293         struct cli_credentials *creds = NULL;
294         bool use_kerberos = false;
295         bool fallback_after_kerberos = false;
296         bool use_ccache = false;
297         bool pw_nt_hash = false;
298
299         ZERO_STRUCT(c);
300         *in_cache = false;
301
302         if (server[0] == 0) {
303                 errno = EPERM;
304                 return NULL;
305         }
306
307         /* Look for a cached connection */
308         srv = SMBC_find_server(ctx, context, server, share,
309                                pp_workgroup, pp_username, pp_password);
310
311         /*
312          * If we found a connection and we're only allowed one share per
313          * server...
314          */
315         if (srv &&
316             share != NULL && *share != '\0' &&
317             smbc_getOptionOneSharePerServer(context)) {
318
319                 /*
320                  * ... then if there's no current connection to the share,
321                  * connect to it.  SMBC_find_server(), or rather the function
322                  * pointed to by context->get_cached_srv_fn which
323                  * was called by SMBC_find_server(), will have issued a tree
324                  * disconnect if the requested share is not the same as the
325                  * one that was already connected.
326                  */
327
328                 /*
329                  * Use srv->cli->desthost and srv->cli->share instead of
330                  * server and share below to connect to the actual share,
331                  * i.e., a normal share or a referred share from
332                  * 'msdfs proxy' share.
333                  */
334                 if (!cli_state_has_tcon(srv->cli)) {
335                         /* Ensure we have accurate auth info */
336                         SMBC_call_auth_fn(ctx, context,
337                                           smbXcli_conn_remote_name(srv->cli->conn),
338                                           srv->cli->share,
339                                           pp_workgroup,
340                                           pp_username,
341                                           pp_password);
342
343                         if (!*pp_workgroup || !*pp_username || !*pp_password) {
344                                 errno = ENOMEM;
345                                 cli_shutdown(srv->cli);
346                                 srv->cli = NULL;
347                                 smbc_getFunctionRemoveCachedServer(context)(context,
348                                                                             srv);
349                                 return NULL;
350                         }
351
352                         /*
353                          * We don't need to renegotiate encryption
354                          * here as the encryption context is not per
355                          * tid.
356                          */
357
358                         status = cli_tree_connect(srv->cli,
359                                                   srv->cli->share,
360                                                   "?????",
361                                                   *pp_password);
362                         if (!NT_STATUS_IS_OK(status)) {
363                                 cli_shutdown(srv->cli);
364                                 errno = map_errno_from_nt_status(status);
365                                 srv->cli = NULL;
366                                 smbc_getFunctionRemoveCachedServer(context)(context,
367                                                                             srv);
368                                 srv = NULL;
369                         }
370
371                         /* Determine if this share supports case sensitivity */
372                         if (is_ipc) {
373                                 DEBUG(4,
374                                       ("IPC$ so ignore case sensitivity\n"));
375                                 status = NT_STATUS_OK;
376                         } else {
377                                 status = cli_get_fs_attr_info(c, &fs_attrs);
378                         }
379
380                         if (!NT_STATUS_IS_OK(status)) {
381                                 DEBUG(4, ("Could not retrieve "
382                                           "case sensitivity flag: %s.\n",
383                                           nt_errstr(status)));
384
385                                 /*
386                                  * We can't determine the case sensitivity of
387                                  * the share. We have no choice but to use the
388                                  * user-specified case sensitivity setting.
389                                  */
390                                 if (smbc_getOptionCaseSensitive(context)) {
391                                         cli_set_case_sensitive(c, True);
392                                 } else {
393                                         cli_set_case_sensitive(c, False);
394                                 }
395                         } else if (!is_ipc) {
396                                 DEBUG(4,
397                                       ("Case sensitive: %s\n",
398                                        (fs_attrs & FILE_CASE_SENSITIVE_SEARCH
399                                         ? "True"
400                                         : "False")));
401                                 cli_set_case_sensitive(
402                                         c,
403                                         (fs_attrs & FILE_CASE_SENSITIVE_SEARCH
404                                          ? True
405                                          : False));
406                         }
407
408                         /*
409                          * Regenerate the dev value since it's based on both
410                          * server and share
411                          */
412                         if (srv) {
413                                 const char *remote_name =
414                                         smbXcli_conn_remote_name(srv->cli->conn);
415
416                                 srv->dev = (dev_t)(str_checksum(remote_name) ^
417                                                    str_checksum(srv->cli->share));
418                         }
419                 }
420         }
421
422         /* If we have a connection... */
423         if (srv) {
424
425                 /* ... then we're done here.  Give 'em what they came for. */
426                 *in_cache = true;
427                 goto done;
428         }
429
430         /* If we're not asked to connect when a connection doesn't exist... */
431         if (! connect_if_not_found) {
432                 /* ... then we're done here. */
433                 return NULL;
434         }
435
436         if (!*pp_workgroup || !*pp_username || !*pp_password) {
437                 errno = ENOMEM;
438                 return NULL;
439         }
440
441         DEBUG(4,("SMBC_server: server_n=[%s] server=[%s]\n", server_n, server));
442
443         DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
444
445         status = NT_STATUS_UNSUCCESSFUL;
446
447         if (smbc_getOptionUseKerberos(context)) {
448                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
449                 use_kerberos = true;
450         }
451
452         if (smbc_getOptionFallbackAfterKerberos(context)) {
453                 flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
454                 fallback_after_kerberos = true;
455         }
456
457         if (smbc_getOptionUseCCache(context)) {
458                 flags |= CLI_FULL_CONNECTION_USE_CCACHE;
459                 use_ccache = true;
460         }
461
462         if (smbc_getOptionUseNTHash(context)) {
463                 flags |= CLI_FULL_CONNECTION_USE_NT_HASH;
464                 pw_nt_hash = true;
465         }
466
467         if (context->internal->smb_encryption_level != SMBC_ENCRYPTLEVEL_NONE) {
468                 signing_state = SMB_SIGNING_REQUIRED;
469         }
470
471         if (port == 0) {
472                 if (share == NULL || *share == '\0' || is_ipc) {
473                         /*
474                          * Try 139 first for IPC$
475                          */
476                         status = cli_connect_nb(server_n, NULL, NBT_SMB_PORT, 0x20,
477                                         smbc_getNetbiosName(context),
478                                         signing_state, flags, &c);
479                 }
480         }
481
482         if (!NT_STATUS_IS_OK(status)) {
483                 /*
484                  * No IPC$ or 139 did not work
485                  */
486                 status = cli_connect_nb(server_n, NULL, port, 0x20,
487                                         smbc_getNetbiosName(context),
488                                         signing_state, flags, &c);
489         }
490
491         if (!NT_STATUS_IS_OK(status)) {
492                 errno = map_errno_from_nt_status(status);
493                 return NULL;
494         }
495
496         cli_set_timeout(c, smbc_getTimeout(context));
497
498         status = smbXcli_negprot(c->conn, c->timeout,
499                                  lp_client_min_protocol(),
500                                  lp_client_max_protocol());
501         if (!NT_STATUS_IS_OK(status)) {
502                 cli_shutdown(c);
503                 errno = ETIMEDOUT;
504                 return NULL;
505         }
506
507         if (smbXcli_conn_protocol(c->conn) >= PROTOCOL_SMB2_02) {
508                 /* Ensure we ask for some initial credits. */
509                 smb2cli_conn_set_max_credits(c->conn, DEFAULT_SMB2_MAX_CREDITS);
510         }
511
512         username_used = *pp_username;
513         password_used = *pp_password;
514
515         creds = cli_session_creds_init(c,
516                                        username_used,
517                                        *pp_workgroup,
518                                        NULL, /* realm */
519                                        password_used,
520                                        use_kerberos,
521                                        fallback_after_kerberos,
522                                        use_ccache,
523                                        pw_nt_hash);
524         if (creds == NULL) {
525                 cli_shutdown(c);
526                 errno = ENOMEM;
527                 return NULL;
528         }
529
530         status = cli_session_setup_creds(c, creds);
531         if (!NT_STATUS_IS_OK(status)) {
532
533                 /* Failed.  Try an anonymous login, if allowed by flags. */
534                 username_used = "";
535                 password_used = "";
536
537                 if (smbc_getOptionNoAutoAnonymousLogin(context) ||
538                     !NT_STATUS_IS_OK(cli_session_setup_anon(c))) {
539
540                         cli_shutdown(c);
541                         errno = EPERM;
542                         return NULL;
543                 }
544         }
545
546         DEBUG(4,(" session setup ok\n"));
547
548         /* here's the fun part....to support 'msdfs proxy' shares
549            (on Samba or windows) we have to issues a TRANS_GET_DFS_REFERRAL
550            here before trying to connect to the original share.
551            cli_check_msdfs_proxy() will fail if it is a normal share. */
552
553         if (smbXcli_conn_dfs_supported(c->conn) &&
554                         cli_check_msdfs_proxy(ctx, c, share,
555                                 &newserver, &newshare,
556                                 /* FIXME: cli_check_msdfs_proxy() does
557                                    not support smbc_smb_encrypt_level type */
558                                 context->internal->smb_encryption_level ?
559                                         true : false,
560                                 creds)) {
561                 cli_shutdown(c);
562                 srv = SMBC_server_internal(ctx, context, connect_if_not_found,
563                                 newserver, port, newshare, pp_workgroup,
564                                 pp_username, pp_password, in_cache);
565                 TALLOC_FREE(newserver);
566                 TALLOC_FREE(newshare);
567                 return srv;
568         }
569
570         /* must be a normal share */
571
572         status = cli_tree_connect_creds(c, share, "?????", creds);
573         if (!NT_STATUS_IS_OK(status)) {
574                 cli_shutdown(c);
575                 errno = map_errno_from_nt_status(status);
576                 return NULL;
577         }
578
579         DEBUG(4,(" tconx ok\n"));
580
581         if (smbXcli_conn_protocol(c->conn) >= PROTOCOL_SMB2_02) {
582                 tcon = c->smb2.tcon;
583         } else {
584                 tcon = c->smb1.tcon;
585         }
586
587         /* Determine if this share supports case sensitivity */
588         if (is_ipc) {
589                 DEBUG(4, ("IPC$ so ignore case sensitivity\n"));
590                 status = NT_STATUS_OK;
591         } else {
592                 status = cli_get_fs_attr_info(c, &fs_attrs);
593         }
594
595         if (!NT_STATUS_IS_OK(status)) {
596                 DEBUG(4, ("Could not retrieve case sensitivity flag: %s.\n",
597                           nt_errstr(status)));
598
599                 /*
600                  * We can't determine the case sensitivity of the share. We
601                  * have no choice but to use the user-specified case
602                  * sensitivity setting.
603                  */
604                 if (smbc_getOptionCaseSensitive(context)) {
605                         cli_set_case_sensitive(c, True);
606                 } else {
607                         cli_set_case_sensitive(c, False);
608                 }
609         } else if (!is_ipc) {
610                 DEBUG(4, ("Case sensitive: %s\n",
611                           (fs_attrs & FILE_CASE_SENSITIVE_SEARCH
612                            ? "True"
613                            : "False")));
614                 smbXcli_tcon_set_fs_attributes(tcon, fs_attrs);
615         }
616
617         if (context->internal->smb_encryption_level) {
618                 /* Attempt encryption. */
619                 status = cli_cm_force_encryption_creds(c,
620                                                        creds,
621                                                        share);
622                 if (!NT_STATUS_IS_OK(status)) {
623
624                         /*
625                          * context->smb_encryption_level == 1
626                          * means don't fail if encryption can't be negotiated,
627                          * == 2 means fail if encryption can't be negotiated.
628                          */
629
630                         DEBUG(4,(" SMB encrypt failed\n"));
631
632                         if (context->internal->smb_encryption_level == 2) {
633                                 cli_shutdown(c);
634                                 errno = EPERM;
635                                 return NULL;
636                         }
637                 }
638                 DEBUG(4,(" SMB encrypt ok\n"));
639         }
640
641         /*
642          * Ok, we have got a nice connection
643          * Let's allocate a server structure.
644          */
645
646         srv = SMB_MALLOC_P(SMBCSRV);
647         if (!srv) {
648                 cli_shutdown(c);
649                 errno = ENOMEM;
650                 return NULL;
651         }
652
653         ZERO_STRUCTP(srv);
654         DLIST_ADD(srv->cli, c);
655         srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
656         srv->no_pathinfo = False;
657         srv->no_pathinfo2 = False;
658         srv->no_pathinfo3 = False;
659         srv->no_nt_session = False;
660
661 done:
662         if (!pp_workgroup || !*pp_workgroup || !**pp_workgroup) {
663                 workgroup = talloc_strdup(ctx, smbc_getWorkgroup(context));
664         } else {
665                 workgroup = *pp_workgroup;
666         }
667         if(!workgroup) {
668                 if (c != NULL) {
669                         cli_shutdown(c);
670                 }
671                 SAFE_FREE(srv);
672                 return NULL;
673         }
674
675         /* set the credentials to make DFS work */
676         smbc_set_credentials_with_fallback(context,
677                                            workgroup,
678                                            *pp_username,
679                                            *pp_password);
680
681         return srv;
682 }
683
684 SMBCSRV *
685 SMBC_server(TALLOC_CTX *ctx,
686                 SMBCCTX *context,
687                 bool connect_if_not_found,
688                 const char *server,
689                 uint16_t port,
690                 const char *share,
691                 char **pp_workgroup,
692                 char **pp_username,
693                 char **pp_password)
694 {
695         SMBCSRV *srv=NULL;
696         bool in_cache = false;
697
698         srv = SMBC_server_internal(ctx, context, connect_if_not_found,
699                         server, port, share, pp_workgroup,
700                         pp_username, pp_password, &in_cache);
701
702         if (!srv) {
703                 return NULL;
704         }
705         if (in_cache) {
706                 return srv;
707         }
708
709         /* Now add it to the cache (internal or external)  */
710         /* Let the cache function set errno if it wants to */
711         errno = 0;
712         if (smbc_getFunctionAddCachedServer(context)(context, srv,
713                                                 server, share,
714                                                 *pp_workgroup,
715                                                 *pp_username)) {
716                 int saved_errno = errno;
717                 DEBUG(3, (" Failed to add server to cache\n"));
718                 errno = saved_errno;
719                 if (errno == 0) {
720                         errno = ENOMEM;
721                 }
722                 SAFE_FREE(srv);
723                 return NULL;
724         }
725
726         DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
727                 server, share, srv));
728
729         DLIST_ADD(context->internal->servers, srv);
730         return srv;
731 }
732
733 /*
734  * Connect to a server for getting/setting attributes, possibly on an existing
735  * connection.  This works similarly to SMBC_server().
736  */
737 SMBCSRV *
738 SMBC_attr_server(TALLOC_CTX *ctx,
739                  SMBCCTX *context,
740                  const char *server,
741                  uint16_t port,
742                  const char *share,
743                  char **pp_workgroup,
744                  char **pp_username,
745                  char **pp_password)
746 {
747         int flags;
748         struct cli_state *ipc_cli = NULL;
749         struct rpc_pipe_client *pipe_hnd = NULL;
750         NTSTATUS nt_status;
751         SMBCSRV *srv=NULL;
752         SMBCSRV *ipc_srv=NULL;
753
754         /*
755          * Use srv->cli->desthost and srv->cli->share instead of
756          * server and share below to connect to the actual share,
757          * i.e., a normal share or a referred share from
758          * 'msdfs proxy' share.
759          */
760         srv = SMBC_server(ctx, context, true, server, port, share,
761                         pp_workgroup, pp_username, pp_password);
762         if (!srv) {
763                 return NULL;
764         }
765         server = smbXcli_conn_remote_name(srv->cli->conn);
766         share = srv->cli->share;
767
768         /*
769          * See if we've already created this special connection.  Reference
770          * our "special" share name '*IPC$', which is an impossible real share
771          * name due to the leading asterisk.
772          */
773         ipc_srv = SMBC_find_server(ctx, context, server, "*IPC$",
774                                    pp_workgroup, pp_username, pp_password);
775         if (!ipc_srv) {
776                 int signing_state = SMB_SIGNING_DEFAULT;
777
778                 /* We didn't find a cached connection.  Get the password */
779                 if (!*pp_password || (*pp_password)[0] == '\0') {
780                         /* ... then retrieve it now. */
781                         SMBC_call_auth_fn(ctx, context, server, share,
782                                           pp_workgroup,
783                                           pp_username,
784                                           pp_password);
785                         if (!*pp_workgroup || !*pp_username || !*pp_password) {
786                                 errno = ENOMEM;
787                                 return NULL;
788                         }
789                 }
790
791                 flags = 0;
792                 if (smbc_getOptionUseKerberos(context)) {
793                         flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
794                 }
795                 if (smbc_getOptionUseCCache(context)) {
796                         flags |= CLI_FULL_CONNECTION_USE_CCACHE;
797                 }
798                 if (context->internal->smb_encryption_level != SMBC_ENCRYPTLEVEL_NONE) {
799                         signing_state = SMB_SIGNING_REQUIRED;
800                 }
801
802                 nt_status = cli_full_connection(&ipc_cli,
803                                                 lp_netbios_name(), server,
804                                                 NULL, 0, "IPC$", "?????",
805                                                 *pp_username,
806                                                 *pp_workgroup,
807                                                 *pp_password,
808                                                 flags,
809                                                 signing_state);
810                 if (! NT_STATUS_IS_OK(nt_status)) {
811                         DEBUG(1,("cli_full_connection failed! (%s)\n",
812                                  nt_errstr(nt_status)));
813                         errno = ENOTSUP;
814                         return NULL;
815                 }
816
817                 if (context->internal->smb_encryption_level) {
818                         /* Attempt encryption. */
819                         nt_status = cli_cm_force_encryption(ipc_cli,
820                                                             *pp_username,
821                                                             *pp_password,
822                                                             *pp_workgroup,
823                                                             "IPC$");
824                         if (!NT_STATUS_IS_OK(nt_status)) {
825
826                                 /*
827                                  * context->smb_encryption_level ==
828                                  * 1 means don't fail if encryption can't be
829                                  * negotiated, == 2 means fail if encryption
830                                  * can't be negotiated.
831                                  */
832
833                                 DEBUG(4,(" SMB encrypt failed on IPC$\n"));
834
835                                 if (context->internal->smb_encryption_level == 2) {
836                                         cli_shutdown(ipc_cli);
837                                         errno = EPERM;
838                                         return NULL;
839                                 }
840                         }
841                         DEBUG(4,(" SMB encrypt ok on IPC$\n"));
842                 }
843
844                 ipc_srv = SMB_MALLOC_P(SMBCSRV);
845                 if (!ipc_srv) {
846                         errno = ENOMEM;
847                         cli_shutdown(ipc_cli);
848                         return NULL;
849                 }
850
851                 ZERO_STRUCTP(ipc_srv);
852                 DLIST_ADD(ipc_srv->cli, ipc_cli);
853
854                 nt_status = cli_rpc_pipe_open_noauth(
855                         ipc_srv->cli, &ndr_table_lsarpc, &pipe_hnd);
856                 if (!NT_STATUS_IS_OK(nt_status)) {
857                         DEBUG(1, ("cli_nt_session_open fail!\n"));
858                         errno = ENOTSUP;
859                         cli_shutdown(ipc_srv->cli);
860                         free(ipc_srv);
861                         return NULL;
862                 }
863
864                 /*
865                  * Some systems don't support
866                  * SEC_FLAG_MAXIMUM_ALLOWED, but NT sends 0x2000000
867                  * so we might as well do it too.
868                  */
869
870                 nt_status = rpccli_lsa_open_policy(
871                         pipe_hnd,
872                         talloc_tos(),
873                         True,
874                         GENERIC_EXECUTE_ACCESS,
875                         &ipc_srv->pol);
876
877                 if (!NT_STATUS_IS_OK(nt_status)) {
878                         errno = SMBC_errno(context, ipc_srv->cli);
879                         cli_shutdown(ipc_srv->cli);
880                         free(ipc_srv);
881                         return NULL;
882                 }
883
884                 /* now add it to the cache (internal or external) */
885
886                 errno = 0;      /* let cache function set errno if it likes */
887                 if (smbc_getFunctionAddCachedServer(context)(context, ipc_srv,
888                                                              server,
889                                                              "*IPC$",
890                                                              *pp_workgroup,
891                                                              *pp_username)) {
892                         DEBUG(3, (" Failed to add server to cache\n"));
893                         if (errno == 0) {
894                                 errno = ENOMEM;
895                         }
896                         cli_shutdown(ipc_srv->cli);
897                         free(ipc_srv);
898                         return NULL;
899                 }
900
901                 DLIST_ADD(context->internal->servers, ipc_srv);
902         }
903
904         return ipc_srv;
905 }