1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   Copyright (C) International Business Machines  Corp., 2002,2011
5  *   Author(s): Steve French (sfrench@us.ibm.com)
6  *
7  */
8 #include <linux/fs.h>
9 #include <linux/net.h>
10 #include <linux/string.h>
11 #include <linux/sched/mm.h>
12 #include <linux/sched/signal.h>
13 #include <linux/list.h>
14 #include <linux/wait.h>
15 #include <linux/slab.h>
16 #include <linux/pagemap.h>
17 #include <linux/ctype.h>
18 #include <linux/utsname.h>
19 #include <linux/mempool.h>
20 #include <linux/delay.h>
21 #include <linux/completion.h>
22 #include <linux/kthread.h>
23 #include <linux/pagevec.h>
24 #include <linux/freezer.h>
25 #include <linux/namei.h>
26 #include <linux/uuid.h>
27 #include <linux/uaccess.h>
28 #include <asm/processor.h>
29 #include <linux/inet.h>
30 #include <linux/module.h>
31 #include <keys/user-type.h>
32 #include <net/ipv6.h>
33 #include <linux/parser.h>
34 #include <linux/bvec.h>
35 #include "cifspdu.h"
36 #include "cifsglob.h"
37 #include "cifsproto.h"
38 #include "cifs_unicode.h"
39 #include "cifs_debug.h"
40 #include "cifs_fs_sb.h"
41 #include "ntlmssp.h"
42 #include "nterr.h"
43 #include "rfc1002pdu.h"
44 #include "fscache.h"
45 #include "smb2proto.h"
46 #include "smbdirect.h"
47 #include "dns_resolve.h"
48 #ifdef CONFIG_CIFS_DFS_UPCALL
49 #include "dfs_cache.h"
50 #endif
51 #include "fs_context.h"
52 #include "cifs_swn.h"
53 
54 extern mempool_t *cifs_req_poolp;
55 extern bool disable_legacy_dialects;
56 
57 /* FIXME: should these be tunable? */
58 #define TLINK_ERROR_EXPIRE	(1 * HZ)
59 #define TLINK_IDLE_EXPIRE	(600 * HZ)
60 
61 /* Drop the connection to not overload the server */
62 #define NUM_STATUS_IO_TIMEOUT   5
63 
64 struct mount_ctx {
65 	struct cifs_sb_info *cifs_sb;
66 	struct smb3_fs_context *fs_ctx;
67 	unsigned int xid;
68 	struct TCP_Server_Info *server;
69 	struct cifs_ses *ses;
70 	struct cifs_tcon *tcon;
71 #ifdef CONFIG_CIFS_DFS_UPCALL
72 	struct cifs_ses *root_ses;
73 	uuid_t mount_id;
74 	char *origin_fullpath, *leaf_fullpath;
75 #endif
76 };
77 
78 static int ip_connect(struct TCP_Server_Info *server);
79 static int generic_ip_connect(struct TCP_Server_Info *server);
80 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
81 static void cifs_prune_tlinks(struct work_struct *work);
82 
83 /*
84  * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
85  * get their ip addresses changed at some point.
86  *
87  * This should be called with server->srv_mutex held.
88  */
reconn_set_ipaddr_from_hostname(struct TCP_Server_Info * server)89 static int reconn_set_ipaddr_from_hostname(struct TCP_Server_Info *server)
90 {
91 	int rc;
92 	int len;
93 	char *unc, *ipaddr = NULL;
94 	time64_t expiry, now;
95 	unsigned long ttl = SMB_DNS_RESOLVE_INTERVAL_DEFAULT;
96 
97 	if (!server->hostname)
98 		return -EINVAL;
99 
100 	/* if server hostname isn't populated, there's nothing to do here */
101 	if (server->hostname[0] == '\0')
102 		return 0;
103 
104 	len = strlen(server->hostname) + 3;
105 
106 	unc = kmalloc(len, GFP_KERNEL);
107 	if (!unc) {
108 		cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
109 		return -ENOMEM;
110 	}
111 	scnprintf(unc, len, "\\\\%s", server->hostname);
112 
113 	rc = dns_resolve_server_name_to_ip(unc, &ipaddr, &expiry);
114 	kfree(unc);
115 
116 	if (rc < 0) {
117 		cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
118 			 __func__, server->hostname, rc);
119 		goto requeue_resolve;
120 	}
121 
122 	spin_lock(&server->srv_lock);
123 	rc = cifs_convert_address((struct sockaddr *)&server->dstaddr, ipaddr,
124 				  strlen(ipaddr));
125 	spin_unlock(&server->srv_lock);
126 	kfree(ipaddr);
127 
128 	/* rc == 1 means success here */
129 	if (rc) {
130 		now = ktime_get_real_seconds();
131 		if (expiry && expiry > now)
132 			/*
133 			 * To make sure we don't use the cached entry, retry 1s
134 			 * after expiry.
135 			 */
136 			ttl = max_t(unsigned long, expiry - now, SMB_DNS_RESOLVE_INTERVAL_MIN) + 1;
137 	}
138 	rc = !rc ? -1 : 0;
139 
140 requeue_resolve:
141 	cifs_dbg(FYI, "%s: next dns resolution scheduled for %lu seconds in the future\n",
142 		 __func__, ttl);
143 	mod_delayed_work(cifsiod_wq, &server->resolve, (ttl * HZ));
144 
145 	return rc;
146 }
147 
smb2_query_server_interfaces(struct work_struct * work)148 static void smb2_query_server_interfaces(struct work_struct *work)
149 {
150 	int rc;
151 	struct cifs_tcon *tcon = container_of(work,
152 					struct cifs_tcon,
153 					query_interfaces.work);
154 
155 	/*
156 	 * query server network interfaces, in case they change
157 	 */
158 	rc = SMB3_request_interfaces(0, tcon, false);
159 	if (rc) {
160 		cifs_dbg(FYI, "%s: failed to query server interfaces: %d\n",
161 				__func__, rc);
162 	}
163 
164 	queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
165 			   (SMB_INTERFACE_POLL_INTERVAL * HZ));
166 }
167 
cifs_resolve_server(struct work_struct * work)168 static void cifs_resolve_server(struct work_struct *work)
169 {
170 	int rc;
171 	struct TCP_Server_Info *server = container_of(work,
172 					struct TCP_Server_Info, resolve.work);
173 
174 	cifs_server_lock(server);
175 
176 	/*
177 	 * Resolve the hostname again to make sure that IP address is up-to-date.
178 	 */
179 	rc = reconn_set_ipaddr_from_hostname(server);
180 	if (rc) {
181 		cifs_dbg(FYI, "%s: failed to resolve hostname: %d\n",
182 				__func__, rc);
183 	}
184 
185 	cifs_server_unlock(server);
186 }
187 
188 /*
189  * Update the tcpStatus for the server.
190  * This is used to signal the cifsd thread to call cifs_reconnect
191  * ONLY cifsd thread should call cifs_reconnect. For any other
192  * thread, use this function
193  *
194  * @server: the tcp ses for which reconnect is needed
195  * @all_channels: if this needs to be done for all channels
196  */
197 void
cifs_signal_cifsd_for_reconnect(struct TCP_Server_Info * server,bool all_channels)198 cifs_signal_cifsd_for_reconnect(struct TCP_Server_Info *server,
199 				bool all_channels)
200 {
201 	struct TCP_Server_Info *pserver;
202 	struct cifs_ses *ses;
203 	int i;
204 
205 	/* If server is a channel, select the primary channel */
206 	pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
207 
208 	spin_lock(&pserver->srv_lock);
209 	if (!all_channels) {
210 		pserver->tcpStatus = CifsNeedReconnect;
211 		spin_unlock(&pserver->srv_lock);
212 		return;
213 	}
214 	spin_unlock(&pserver->srv_lock);
215 
216 	spin_lock(&cifs_tcp_ses_lock);
217 	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
218 		spin_lock(&ses->chan_lock);
219 		for (i = 0; i < ses->chan_count; i++) {
220 			spin_lock(&ses->chans[i].server->srv_lock);
221 			ses->chans[i].server->tcpStatus = CifsNeedReconnect;
222 			spin_unlock(&ses->chans[i].server->srv_lock);
223 		}
224 		spin_unlock(&ses->chan_lock);
225 	}
226 	spin_unlock(&cifs_tcp_ses_lock);
227 }
228 
229 /*
230  * Mark all sessions and tcons for reconnect.
231  * IMPORTANT: make sure that this gets called only from
232  * cifsd thread. For any other thread, use
233  * cifs_signal_cifsd_for_reconnect
234  *
235  * @server: the tcp ses for which reconnect is needed
236  * @server needs to be previously set to CifsNeedReconnect.
237  * @mark_smb_session: whether even sessions need to be marked
238  */
239 void
cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info * server,bool mark_smb_session)240 cifs_mark_tcp_ses_conns_for_reconnect(struct TCP_Server_Info *server,
241 				      bool mark_smb_session)
242 {
243 	struct TCP_Server_Info *pserver;
244 	struct cifs_ses *ses, *nses;
245 	struct cifs_tcon *tcon;
246 
247 	/*
248 	 * before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they
249 	 * are not used until reconnected.
250 	 */
251 	cifs_dbg(FYI, "%s: marking necessary sessions and tcons for reconnect\n", __func__);
252 
253 	/* If server is a channel, select the primary channel */
254 	pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
255 
256 
257 	spin_lock(&cifs_tcp_ses_lock);
258 	list_for_each_entry_safe(ses, nses, &pserver->smb_ses_list, smb_ses_list) {
259 		/* check if iface is still active */
260 		if (!cifs_chan_is_iface_active(ses, server))
261 			cifs_chan_update_iface(ses, server);
262 
263 		spin_lock(&ses->chan_lock);
264 		if (!mark_smb_session && cifs_chan_needs_reconnect(ses, server))
265 			goto next_session;
266 
267 		if (mark_smb_session)
268 			CIFS_SET_ALL_CHANS_NEED_RECONNECT(ses);
269 		else
270 			cifs_chan_set_need_reconnect(ses, server);
271 
272 		/* If all channels need reconnect, then tcon needs reconnect */
273 		if (!mark_smb_session && !CIFS_ALL_CHANS_NEED_RECONNECT(ses))
274 			goto next_session;
275 
276 		ses->ses_status = SES_NEED_RECON;
277 
278 		list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
279 			tcon->need_reconnect = true;
280 			tcon->status = TID_NEED_RECON;
281 		}
282 		if (ses->tcon_ipc) {
283 			ses->tcon_ipc->need_reconnect = true;
284 			ses->tcon_ipc->status = TID_NEED_RECON;
285 		}
286 
287 next_session:
288 		spin_unlock(&ses->chan_lock);
289 	}
290 	spin_unlock(&cifs_tcp_ses_lock);
291 }
292 
293 static void
cifs_abort_connection(struct TCP_Server_Info * server)294 cifs_abort_connection(struct TCP_Server_Info *server)
295 {
296 	struct mid_q_entry *mid, *nmid;
297 	struct list_head retry_list;
298 
299 	server->maxBuf = 0;
300 	server->max_read = 0;
301 
302 	/* do not want to be sending data on a socket we are freeing */
303 	cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
304 	cifs_server_lock(server);
305 	if (server->ssocket) {
306 		cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n", server->ssocket->state,
307 			 server->ssocket->flags);
308 		kernel_sock_shutdown(server->ssocket, SHUT_WR);
309 		cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n", server->ssocket->state,
310 			 server->ssocket->flags);
311 		sock_release(server->ssocket);
312 		server->ssocket = NULL;
313 	}
314 	server->sequence_number = 0;
315 	server->session_estab = false;
316 	kfree_sensitive(server->session_key.response);
317 	server->session_key.response = NULL;
318 	server->session_key.len = 0;
319 	server->lstrp = jiffies;
320 
321 	/* mark submitted MIDs for retry and issue callback */
322 	INIT_LIST_HEAD(&retry_list);
323 	cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
324 	spin_lock(&server->mid_lock);
325 	list_for_each_entry_safe(mid, nmid, &server->pending_mid_q, qhead) {
326 		kref_get(&mid->refcount);
327 		if (mid->mid_state == MID_REQUEST_SUBMITTED)
328 			mid->mid_state = MID_RETRY_NEEDED;
329 		list_move(&mid->qhead, &retry_list);
330 		mid->mid_flags |= MID_DELETED;
331 	}
332 	spin_unlock(&server->mid_lock);
333 	cifs_server_unlock(server);
334 
335 	cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
336 	list_for_each_entry_safe(mid, nmid, &retry_list, qhead) {
337 		list_del_init(&mid->qhead);
338 		mid->callback(mid);
339 		release_mid(mid);
340 	}
341 
342 	if (cifs_rdma_enabled(server)) {
343 		cifs_server_lock(server);
344 		smbd_destroy(server);
345 		cifs_server_unlock(server);
346 	}
347 }
348 
cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info * server,int num_targets)349 static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
350 {
351 	spin_lock(&server->srv_lock);
352 	server->nr_targets = num_targets;
353 	if (server->tcpStatus == CifsExiting) {
354 		/* the demux thread will exit normally next time through the loop */
355 		spin_unlock(&server->srv_lock);
356 		wake_up(&server->response_q);
357 		return false;
358 	}
359 
360 	cifs_dbg(FYI, "Mark tcp session as need reconnect\n");
361 	trace_smb3_reconnect(server->CurrentMid, server->conn_id,
362 			     server->hostname);
363 	server->tcpStatus = CifsNeedReconnect;
364 
365 	spin_unlock(&server->srv_lock);
366 	return true;
367 }
368 
369 /*
370  * cifs tcp session reconnection
371  *
372  * mark tcp session as reconnecting so temporarily locked
373  * mark all smb sessions as reconnecting for tcp session
374  * reconnect tcp session
375  * wake up waiters on reconnection? - (not needed currently)
376  *
377  * if mark_smb_session is passed as true, unconditionally mark
378  * the smb session (and tcon) for reconnect as well. This value
379  * doesn't really matter for non-multichannel scenario.
380  *
381  */
__cifs_reconnect(struct TCP_Server_Info * server,bool mark_smb_session)382 static int __cifs_reconnect(struct TCP_Server_Info *server,
383 			    bool mark_smb_session)
384 {
385 	int rc = 0;
386 
387 	if (!cifs_tcp_ses_needs_reconnect(server, 1))
388 		return 0;
389 
390 	cifs_mark_tcp_ses_conns_for_reconnect(server, mark_smb_session);
391 
392 	cifs_abort_connection(server);
393 
394 	do {
395 		try_to_freeze();
396 		cifs_server_lock(server);
397 
398 		if (!cifs_swn_set_server_dstaddr(server)) {
399 			/* resolve the hostname again to make sure that IP address is up-to-date */
400 			rc = reconn_set_ipaddr_from_hostname(server);
401 			cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
402 		}
403 
404 		if (cifs_rdma_enabled(server))
405 			rc = smbd_reconnect(server);
406 		else
407 			rc = generic_ip_connect(server);
408 		if (rc) {
409 			cifs_server_unlock(server);
410 			cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
411 			msleep(3000);
412 		} else {
413 			atomic_inc(&tcpSesReconnectCount);
414 			set_credits(server, 1);
415 			spin_lock(&server->srv_lock);
416 			if (server->tcpStatus != CifsExiting)
417 				server->tcpStatus = CifsNeedNegotiate;
418 			spin_unlock(&server->srv_lock);
419 			cifs_swn_reset_server_dstaddr(server);
420 			cifs_server_unlock(server);
421 			mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
422 		}
423 	} while (server->tcpStatus == CifsNeedReconnect);
424 
425 	spin_lock(&server->srv_lock);
426 	if (server->tcpStatus == CifsNeedNegotiate)
427 		mod_delayed_work(cifsiod_wq, &server->echo, 0);
428 	spin_unlock(&server->srv_lock);
429 
430 	wake_up(&server->response_q);
431 	return rc;
432 }
433 
434 #ifdef CONFIG_CIFS_DFS_UPCALL
__reconnect_target_unlocked(struct TCP_Server_Info * server,const char * target)435 static int __reconnect_target_unlocked(struct TCP_Server_Info *server, const char *target)
436 {
437 	int rc;
438 	char *hostname;
439 
440 	if (!cifs_swn_set_server_dstaddr(server)) {
441 		if (server->hostname != target) {
442 			hostname = extract_hostname(target);
443 			if (!IS_ERR(hostname)) {
444 				kfree(server->hostname);
445 				server->hostname = hostname;
446 			} else {
447 				cifs_dbg(FYI, "%s: couldn't extract hostname or address from dfs target: %ld\n",
448 					 __func__, PTR_ERR(hostname));
449 				cifs_dbg(FYI, "%s: default to last target server: %s\n", __func__,
450 					 server->hostname);
451 			}
452 		}
453 		/* resolve the hostname again to make sure that IP address is up-to-date. */
454 		rc = reconn_set_ipaddr_from_hostname(server);
455 		cifs_dbg(FYI, "%s: reconn_set_ipaddr_from_hostname: rc=%d\n", __func__, rc);
456 	}
457 	/* Reconnect the socket */
458 	if (cifs_rdma_enabled(server))
459 		rc = smbd_reconnect(server);
460 	else
461 		rc = generic_ip_connect(server);
462 
463 	return rc;
464 }
465 
reconnect_target_unlocked(struct TCP_Server_Info * server,struct dfs_cache_tgt_list * tl,struct dfs_cache_tgt_iterator ** target_hint)466 static int reconnect_target_unlocked(struct TCP_Server_Info *server, struct dfs_cache_tgt_list *tl,
467 				     struct dfs_cache_tgt_iterator **target_hint)
468 {
469 	int rc;
470 	struct dfs_cache_tgt_iterator *tit;
471 
472 	*target_hint = NULL;
473 
474 	/* If dfs target list is empty, then reconnect to last server */
475 	tit = dfs_cache_get_tgt_iterator(tl);
476 	if (!tit)
477 		return __reconnect_target_unlocked(server, server->hostname);
478 
479 	/* Otherwise, try every dfs target in @tl */
480 	for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
481 		rc = __reconnect_target_unlocked(server, dfs_cache_get_tgt_name(tit));
482 		if (!rc) {
483 			*target_hint = tit;
484 			break;
485 		}
486 	}
487 	return rc;
488 }
489 
reconnect_dfs_server(struct TCP_Server_Info * server)490 static int reconnect_dfs_server(struct TCP_Server_Info *server)
491 {
492 	int rc = 0;
493 	const char *refpath = server->current_fullpath + 1;
494 	struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
495 	struct dfs_cache_tgt_iterator *target_hint = NULL;
496 	int num_targets = 0;
497 
498 	/*
499 	 * Determine the number of dfs targets the referral path in @cifs_sb resolves to.
500 	 *
501 	 * smb2_reconnect() needs to know how long it should wait based upon the number of dfs
502 	 * targets (server->nr_targets).  It's also possible that the cached referral was cleared
503 	 * through /proc/fs/cifs/dfscache or the target list is empty due to server settings after
504 	 * refreshing the referral, so, in this case, default it to 1.
505 	 */
506 	if (!dfs_cache_noreq_find(refpath, NULL, &tl))
507 		num_targets = dfs_cache_get_nr_tgts(&tl);
508 	if (!num_targets)
509 		num_targets = 1;
510 
511 	if (!cifs_tcp_ses_needs_reconnect(server, num_targets))
512 		return 0;
513 
514 	/*
515 	 * Unconditionally mark all sessions & tcons for reconnect as we might be connecting to a
516 	 * different server or share during failover.  It could be improved by adding some logic to
517 	 * only do that in case it connects to a different server or share, though.
518 	 */
519 	cifs_mark_tcp_ses_conns_for_reconnect(server, true);
520 
521 	cifs_abort_connection(server);
522 
523 	do {
524 		try_to_freeze();
525 		cifs_server_lock(server);
526 
527 		rc = reconnect_target_unlocked(server, &tl, &target_hint);
528 		if (rc) {
529 			/* Failed to reconnect socket */
530 			cifs_server_unlock(server);
531 			cifs_dbg(FYI, "%s: reconnect error %d\n", __func__, rc);
532 			msleep(3000);
533 			continue;
534 		}
535 		/*
536 		 * Socket was created.  Update tcp session status to CifsNeedNegotiate so that a
537 		 * process waiting for reconnect will know it needs to re-establish session and tcon
538 		 * through the reconnected target server.
539 		 */
540 		atomic_inc(&tcpSesReconnectCount);
541 		set_credits(server, 1);
542 		spin_lock(&server->srv_lock);
543 		if (server->tcpStatus != CifsExiting)
544 			server->tcpStatus = CifsNeedNegotiate;
545 		spin_unlock(&server->srv_lock);
546 		cifs_swn_reset_server_dstaddr(server);
547 		cifs_server_unlock(server);
548 		mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
549 	} while (server->tcpStatus == CifsNeedReconnect);
550 
551 	if (target_hint)
552 		dfs_cache_noreq_update_tgthint(refpath, target_hint);
553 
554 	dfs_cache_free_tgts(&tl);
555 
556 	/* Need to set up echo worker again once connection has been established */
557 	spin_lock(&server->srv_lock);
558 	if (server->tcpStatus == CifsNeedNegotiate)
559 		mod_delayed_work(cifsiod_wq, &server->echo, 0);
560 	spin_unlock(&server->srv_lock);
561 
562 	wake_up(&server->response_q);
563 	return rc;
564 }
565 
cifs_reconnect(struct TCP_Server_Info * server,bool mark_smb_session)566 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
567 {
568 	/* If tcp session is not an dfs connection, then reconnect to last target server */
569 	spin_lock(&server->srv_lock);
570 	if (!server->is_dfs_conn) {
571 		spin_unlock(&server->srv_lock);
572 		return __cifs_reconnect(server, mark_smb_session);
573 	}
574 	spin_unlock(&server->srv_lock);
575 
576 	mutex_lock(&server->refpath_lock);
577 	if (!server->origin_fullpath || !server->leaf_fullpath) {
578 		mutex_unlock(&server->refpath_lock);
579 		return __cifs_reconnect(server, mark_smb_session);
580 	}
581 	mutex_unlock(&server->refpath_lock);
582 
583 	return reconnect_dfs_server(server);
584 }
585 #else
cifs_reconnect(struct TCP_Server_Info * server,bool mark_smb_session)586 int cifs_reconnect(struct TCP_Server_Info *server, bool mark_smb_session)
587 {
588 	return __cifs_reconnect(server, mark_smb_session);
589 }
590 #endif
591 
592 static void
cifs_echo_request(struct work_struct * work)593 cifs_echo_request(struct work_struct *work)
594 {
595 	int rc;
596 	struct TCP_Server_Info *server = container_of(work,
597 					struct TCP_Server_Info, echo.work);
598 
599 	/*
600 	 * We cannot send an echo if it is disabled.
601 	 * Also, no need to ping if we got a response recently.
602 	 */
603 
604 	if (server->tcpStatus == CifsNeedReconnect ||
605 	    server->tcpStatus == CifsExiting ||
606 	    server->tcpStatus == CifsNew ||
607 	    (server->ops->can_echo && !server->ops->can_echo(server)) ||
608 	    time_before(jiffies, server->lstrp + server->echo_interval - HZ))
609 		goto requeue_echo;
610 
611 	rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
612 	if (rc)
613 		cifs_dbg(FYI, "Unable to send echo request to server: %s\n",
614 			 server->hostname);
615 
616 	/* Check witness registrations */
617 	cifs_swn_check();
618 
619 requeue_echo:
620 	queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
621 }
622 
623 static bool
allocate_buffers(struct TCP_Server_Info * server)624 allocate_buffers(struct TCP_Server_Info *server)
625 {
626 	if (!server->bigbuf) {
627 		server->bigbuf = (char *)cifs_buf_get();
628 		if (!server->bigbuf) {
629 			cifs_server_dbg(VFS, "No memory for large SMB response\n");
630 			msleep(3000);
631 			/* retry will check if exiting */
632 			return false;
633 		}
634 	} else if (server->large_buf) {
635 		/* we are reusing a dirty large buf, clear its start */
636 		memset(server->bigbuf, 0, HEADER_SIZE(server));
637 	}
638 
639 	if (!server->smallbuf) {
640 		server->smallbuf = (char *)cifs_small_buf_get();
641 		if (!server->smallbuf) {
642 			cifs_server_dbg(VFS, "No memory for SMB response\n");
643 			msleep(1000);
644 			/* retry will check if exiting */
645 			return false;
646 		}
647 		/* beginning of smb buffer is cleared in our buf_get */
648 	} else {
649 		/* if existing small buf clear beginning */
650 		memset(server->smallbuf, 0, HEADER_SIZE(server));
651 	}
652 
653 	return true;
654 }
655 
656 static bool
server_unresponsive(struct TCP_Server_Info * server)657 server_unresponsive(struct TCP_Server_Info *server)
658 {
659 	/*
660 	 * We need to wait 3 echo intervals to make sure we handle such
661 	 * situations right:
662 	 * 1s  client sends a normal SMB request
663 	 * 2s  client gets a response
664 	 * 30s echo workqueue job pops, and decides we got a response recently
665 	 *     and don't need to send another
666 	 * ...
667 	 * 65s kernel_recvmsg times out, and we see that we haven't gotten
668 	 *     a response in >60s.
669 	 */
670 	spin_lock(&server->srv_lock);
671 	if ((server->tcpStatus == CifsGood ||
672 	    server->tcpStatus == CifsNeedNegotiate) &&
673 	    (!server->ops->can_echo || server->ops->can_echo(server)) &&
674 	    time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
675 		spin_unlock(&server->srv_lock);
676 		cifs_server_dbg(VFS, "has not responded in %lu seconds. Reconnecting...\n",
677 			 (3 * server->echo_interval) / HZ);
678 		cifs_reconnect(server, false);
679 		return true;
680 	}
681 	spin_unlock(&server->srv_lock);
682 
683 	return false;
684 }
685 
686 static inline bool
zero_credits(struct TCP_Server_Info * server)687 zero_credits(struct TCP_Server_Info *server)
688 {
689 	int val;
690 
691 	spin_lock(&server->req_lock);
692 	val = server->credits + server->echo_credits + server->oplock_credits;
693 	if (server->in_flight == 0 && val == 0) {
694 		spin_unlock(&server->req_lock);
695 		return true;
696 	}
697 	spin_unlock(&server->req_lock);
698 	return false;
699 }
700 
701 static int
cifs_readv_from_socket(struct TCP_Server_Info * server,struct msghdr * smb_msg)702 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
703 {
704 	int length = 0;
705 	int total_read;
706 
707 	for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
708 		try_to_freeze();
709 
710 		/* reconnect if no credits and no requests in flight */
711 		if (zero_credits(server)) {
712 			cifs_reconnect(server, false);
713 			return -ECONNABORTED;
714 		}
715 
716 		if (server_unresponsive(server))
717 			return -ECONNABORTED;
718 		if (cifs_rdma_enabled(server) && server->smbd_conn)
719 			length = smbd_recv(server->smbd_conn, smb_msg);
720 		else
721 			length = sock_recvmsg(server->ssocket, smb_msg, 0);
722 
723 		spin_lock(&server->srv_lock);
724 		if (server->tcpStatus == CifsExiting) {
725 			spin_unlock(&server->srv_lock);
726 			return -ESHUTDOWN;
727 		}
728 
729 		if (server->tcpStatus == CifsNeedReconnect) {
730 			spin_unlock(&server->srv_lock);
731 			cifs_reconnect(server, false);
732 			return -ECONNABORTED;
733 		}
734 		spin_unlock(&server->srv_lock);
735 
736 		if (length == -ERESTARTSYS ||
737 		    length == -EAGAIN ||
738 		    length == -EINTR) {
739 			/*
740 			 * Minimum sleep to prevent looping, allowing socket
741 			 * to clear and app threads to set tcpStatus
742 			 * CifsNeedReconnect if server hung.
743 			 */
744 			usleep_range(1000, 2000);
745 			length = 0;
746 			continue;
747 		}
748 
749 		if (length <= 0) {
750 			cifs_dbg(FYI, "Received no data or error: %d\n", length);
751 			cifs_reconnect(server, false);
752 			return -ECONNABORTED;
753 		}
754 	}
755 	return total_read;
756 }
757 
758 int
cifs_read_from_socket(struct TCP_Server_Info * server,char * buf,unsigned int to_read)759 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
760 		      unsigned int to_read)
761 {
762 	struct msghdr smb_msg = {};
763 	struct kvec iov = {.iov_base = buf, .iov_len = to_read};
764 	iov_iter_kvec(&smb_msg.msg_iter, READ, &iov, 1, to_read);
765 
766 	return cifs_readv_from_socket(server, &smb_msg);
767 }
768 
769 ssize_t
cifs_discard_from_socket(struct TCP_Server_Info * server,size_t to_read)770 cifs_discard_from_socket(struct TCP_Server_Info *server, size_t to_read)
771 {
772 	struct msghdr smb_msg = {};
773 
774 	/*
775 	 *  iov_iter_discard already sets smb_msg.type and count and iov_offset
776 	 *  and cifs_readv_from_socket sets msg_control and msg_controllen
777 	 *  so little to initialize in struct msghdr
778 	 */
779 	iov_iter_discard(&smb_msg.msg_iter, READ, to_read);
780 
781 	return cifs_readv_from_socket(server, &smb_msg);
782 }
783 
784 int
cifs_read_page_from_socket(struct TCP_Server_Info * server,struct page * page,unsigned int page_offset,unsigned int to_read)785 cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
786 	unsigned int page_offset, unsigned int to_read)
787 {
788 	struct msghdr smb_msg = {};
789 	struct bio_vec bv = {
790 		.bv_page = page, .bv_len = to_read, .bv_offset = page_offset};
791 	iov_iter_bvec(&smb_msg.msg_iter, READ, &bv, 1, to_read);
792 	return cifs_readv_from_socket(server, &smb_msg);
793 }
794 
795 static bool
is_smb_response(struct TCP_Server_Info * server,unsigned char type)796 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
797 {
798 	/*
799 	 * The first byte big endian of the length field,
800 	 * is actually not part of the length but the type
801 	 * with the most common, zero, as regular data.
802 	 */
803 	switch (type) {
804 	case RFC1002_SESSION_MESSAGE:
805 		/* Regular SMB response */
806 		return true;
807 	case RFC1002_SESSION_KEEP_ALIVE:
808 		cifs_dbg(FYI, "RFC 1002 session keep alive\n");
809 		break;
810 	case RFC1002_POSITIVE_SESSION_RESPONSE:
811 		cifs_dbg(FYI, "RFC 1002 positive session response\n");
812 		break;
813 	case RFC1002_NEGATIVE_SESSION_RESPONSE:
814 		/*
815 		 * We get this from Windows 98 instead of an error on
816 		 * SMB negprot response.
817 		 */
818 		cifs_dbg(FYI, "RFC 1002 negative session response\n");
819 		/* give server a second to clean up */
820 		msleep(1000);
821 		/*
822 		 * Always try 445 first on reconnect since we get NACK
823 		 * on some if we ever connected to port 139 (the NACK
824 		 * is since we do not begin with RFC1001 session
825 		 * initialize frame).
826 		 */
827 		cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
828 		cifs_reconnect(server, true);
829 		break;
830 	default:
831 		cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
832 		cifs_reconnect(server, true);
833 	}
834 
835 	return false;
836 }
837 
838 void
dequeue_mid(struct mid_q_entry * mid,bool malformed)839 dequeue_mid(struct mid_q_entry *mid, bool malformed)
840 {
841 #ifdef CONFIG_CIFS_STATS2
842 	mid->when_received = jiffies;
843 #endif
844 	spin_lock(&mid->server->mid_lock);
845 	if (!malformed)
846 		mid->mid_state = MID_RESPONSE_RECEIVED;
847 	else
848 		mid->mid_state = MID_RESPONSE_MALFORMED;
849 	/*
850 	 * Trying to handle/dequeue a mid after the send_recv()
851 	 * function has finished processing it is a bug.
852 	 */
853 	if (mid->mid_flags & MID_DELETED) {
854 		spin_unlock(&mid->server->mid_lock);
855 		pr_warn_once("trying to dequeue a deleted mid\n");
856 	} else {
857 		list_del_init(&mid->qhead);
858 		mid->mid_flags |= MID_DELETED;
859 		spin_unlock(&mid->server->mid_lock);
860 	}
861 }
862 
863 static unsigned int
smb2_get_credits_from_hdr(char * buffer,struct TCP_Server_Info * server)864 smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
865 {
866 	struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
867 
868 	/*
869 	 * SMB1 does not use credits.
870 	 */
871 	if (is_smb1(server))
872 		return 0;
873 
874 	return le16_to_cpu(shdr->CreditRequest);
875 }
876 
877 static void
handle_mid(struct mid_q_entry * mid,struct TCP_Server_Info * server,char * buf,int malformed)878 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
879 	   char *buf, int malformed)
880 {
881 	if (server->ops->check_trans2 &&
882 	    server->ops->check_trans2(mid, server, buf, malformed))
883 		return;
884 	mid->credits_received = smb2_get_credits_from_hdr(buf, server);
885 	mid->resp_buf = buf;
886 	mid->large_buf = server->large_buf;
887 	/* Was previous buf put in mpx struct for multi-rsp? */
888 	if (!mid->multiRsp) {
889 		/* smb buffer will be freed by user thread */
890 		if (server->large_buf)
891 			server->bigbuf = NULL;
892 		else
893 			server->smallbuf = NULL;
894 	}
895 	dequeue_mid(mid, malformed);
896 }
897 
898 int
cifs_enable_signing(struct TCP_Server_Info * server,bool mnt_sign_required)899 cifs_enable_signing(struct TCP_Server_Info *server, bool mnt_sign_required)
900 {
901 	bool srv_sign_required = server->sec_mode & server->vals->signing_required;
902 	bool srv_sign_enabled = server->sec_mode & server->vals->signing_enabled;
903 	bool mnt_sign_enabled;
904 
905 	/*
906 	 * Is signing required by mnt options? If not then check
907 	 * global_secflags to see if it is there.
908 	 */
909 	if (!mnt_sign_required)
910 		mnt_sign_required = ((global_secflags & CIFSSEC_MUST_SIGN) ==
911 						CIFSSEC_MUST_SIGN);
912 
913 	/*
914 	 * If signing is required then it's automatically enabled too,
915 	 * otherwise, check to see if the secflags allow it.
916 	 */
917 	mnt_sign_enabled = mnt_sign_required ? mnt_sign_required :
918 				(global_secflags & CIFSSEC_MAY_SIGN);
919 
920 	/* If server requires signing, does client allow it? */
921 	if (srv_sign_required) {
922 		if (!mnt_sign_enabled) {
923 			cifs_dbg(VFS, "Server requires signing, but it's disabled in SecurityFlags!\n");
924 			return -EOPNOTSUPP;
925 		}
926 		server->sign = true;
927 	}
928 
929 	/* If client requires signing, does server allow it? */
930 	if (mnt_sign_required) {
931 		if (!srv_sign_enabled) {
932 			cifs_dbg(VFS, "Server does not support signing!\n");
933 			return -EOPNOTSUPP;
934 		}
935 		server->sign = true;
936 	}
937 
938 	if (cifs_rdma_enabled(server) && server->sign)
939 		cifs_dbg(VFS, "Signing is enabled, and RDMA read/write will be disabled\n");
940 
941 	return 0;
942 }
943 
944 
clean_demultiplex_info(struct TCP_Server_Info * server)945 static void clean_demultiplex_info(struct TCP_Server_Info *server)
946 {
947 	int length;
948 
949 	/* take it off the list, if it's not already */
950 	spin_lock(&server->srv_lock);
951 	list_del_init(&server->tcp_ses_list);
952 	spin_unlock(&server->srv_lock);
953 
954 	cancel_delayed_work_sync(&server->echo);
955 	cancel_delayed_work_sync(&server->resolve);
956 
957 	spin_lock(&server->srv_lock);
958 	server->tcpStatus = CifsExiting;
959 	spin_unlock(&server->srv_lock);
960 	wake_up_all(&server->response_q);
961 
962 	/* check if we have blocked requests that need to free */
963 	spin_lock(&server->req_lock);
964 	if (server->credits <= 0)
965 		server->credits = 1;
966 	spin_unlock(&server->req_lock);
967 	/*
968 	 * Although there should not be any requests blocked on this queue it
969 	 * can not hurt to be paranoid and try to wake up requests that may
970 	 * haven been blocked when more than 50 at time were on the wire to the
971 	 * same server - they now will see the session is in exit state and get
972 	 * out of SendReceive.
973 	 */
974 	wake_up_all(&server->request_q);
975 	/* give those requests time to exit */
976 	msleep(125);
977 	if (cifs_rdma_enabled(server))
978 		smbd_destroy(server);
979 	if (server->ssocket) {
980 		sock_release(server->ssocket);
981 		server->ssocket = NULL;
982 	}
983 
984 	if (!list_empty(&server->pending_mid_q)) {
985 		struct list_head dispose_list;
986 		struct mid_q_entry *mid_entry;
987 		struct list_head *tmp, *tmp2;
988 
989 		INIT_LIST_HEAD(&dispose_list);
990 		spin_lock(&server->mid_lock);
991 		list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
992 			mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
993 			cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
994 			kref_get(&mid_entry->refcount);
995 			mid_entry->mid_state = MID_SHUTDOWN;
996 			list_move(&mid_entry->qhead, &dispose_list);
997 			mid_entry->mid_flags |= MID_DELETED;
998 		}
999 		spin_unlock(&server->mid_lock);
1000 
1001 		/* now walk dispose list and issue callbacks */
1002 		list_for_each_safe(tmp, tmp2, &dispose_list) {
1003 			mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
1004 			cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
1005 			list_del_init(&mid_entry->qhead);
1006 			mid_entry->callback(mid_entry);
1007 			release_mid(mid_entry);
1008 		}
1009 		/* 1/8th of sec is more than enough time for them to exit */
1010 		msleep(125);
1011 	}
1012 
1013 	if (!list_empty(&server->pending_mid_q)) {
1014 		/*
1015 		 * mpx threads have not exited yet give them at least the smb
1016 		 * send timeout time for long ops.
1017 		 *
1018 		 * Due to delays on oplock break requests, we need to wait at
1019 		 * least 45 seconds before giving up on a request getting a
1020 		 * response and going ahead and killing cifsd.
1021 		 */
1022 		cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
1023 		msleep(46000);
1024 		/*
1025 		 * If threads still have not exited they are probably never
1026 		 * coming home not much else we can do but free the memory.
1027 		 */
1028 	}
1029 
1030 #ifdef CONFIG_CIFS_DFS_UPCALL
1031 	kfree(server->origin_fullpath);
1032 	kfree(server->leaf_fullpath);
1033 #endif
1034 	kfree(server);
1035 
1036 	length = atomic_dec_return(&tcpSesAllocCount);
1037 	if (length > 0)
1038 		mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1039 }
1040 
1041 static int
standard_receive3(struct TCP_Server_Info * server,struct mid_q_entry * mid)1042 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1043 {
1044 	int length;
1045 	char *buf = server->smallbuf;
1046 	unsigned int pdu_length = server->pdu_size;
1047 
1048 	/* make sure this will fit in a large buffer */
1049 	if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
1050 	    HEADER_PREAMBLE_SIZE(server)) {
1051 		cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
1052 		cifs_reconnect(server, true);
1053 		return -ECONNABORTED;
1054 	}
1055 
1056 	/* switch to large buffer if too big for a small one */
1057 	if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
1058 		server->large_buf = true;
1059 		memcpy(server->bigbuf, buf, server->total_read);
1060 		buf = server->bigbuf;
1061 	}
1062 
1063 	/* now read the rest */
1064 	length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
1065 				       pdu_length - MID_HEADER_SIZE(server));
1066 
1067 	if (length < 0)
1068 		return length;
1069 	server->total_read += length;
1070 
1071 	dump_smb(buf, server->total_read);
1072 
1073 	return cifs_handle_standard(server, mid);
1074 }
1075 
1076 int
cifs_handle_standard(struct TCP_Server_Info * server,struct mid_q_entry * mid)1077 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1078 {
1079 	char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
1080 	int rc;
1081 
1082 	/*
1083 	 * We know that we received enough to get to the MID as we
1084 	 * checked the pdu_length earlier. Now check to see
1085 	 * if the rest of the header is OK.
1086 	 *
1087 	 * 48 bytes is enough to display the header and a little bit
1088 	 * into the payload for debugging purposes.
1089 	 */
1090 	rc = server->ops->check_message(buf, server->total_read, server);
1091 	if (rc)
1092 		cifs_dump_mem("Bad SMB: ", buf,
1093 			min_t(unsigned int, server->total_read, 48));
1094 
1095 	if (server->ops->is_session_expired &&
1096 	    server->ops->is_session_expired(buf)) {
1097 		cifs_reconnect(server, true);
1098 		return -1;
1099 	}
1100 
1101 	if (server->ops->is_status_pending &&
1102 	    server->ops->is_status_pending(buf, server))
1103 		return -1;
1104 
1105 	if (!mid)
1106 		return rc;
1107 
1108 	handle_mid(mid, server, buf, rc);
1109 	return 0;
1110 }
1111 
1112 static void
smb2_add_credits_from_hdr(char * buffer,struct TCP_Server_Info * server)1113 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
1114 {
1115 	struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
1116 	int scredits, in_flight;
1117 
1118 	/*
1119 	 * SMB1 does not use credits.
1120 	 */
1121 	if (is_smb1(server))
1122 		return;
1123 
1124 	if (shdr->CreditRequest) {
1125 		spin_lock(&server->req_lock);
1126 		server->credits += le16_to_cpu(shdr->CreditRequest);
1127 		scredits = server->credits;
1128 		in_flight = server->in_flight;
1129 		spin_unlock(&server->req_lock);
1130 		wake_up(&server->request_q);
1131 
1132 		trace_smb3_hdr_credits(server->CurrentMid,
1133 				server->conn_id, server->hostname, scredits,
1134 				le16_to_cpu(shdr->CreditRequest), in_flight);
1135 		cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
1136 				__func__, le16_to_cpu(shdr->CreditRequest),
1137 				scredits);
1138 	}
1139 }
1140 
1141 
1142 static int
cifs_demultiplex_thread(void * p)1143 cifs_demultiplex_thread(void *p)
1144 {
1145 	int i, num_mids, length;
1146 	struct TCP_Server_Info *server = p;
1147 	unsigned int pdu_length;
1148 	unsigned int next_offset;
1149 	char *buf = NULL;
1150 	struct task_struct *task_to_wake = NULL;
1151 	struct mid_q_entry *mids[MAX_COMPOUND];
1152 	char *bufs[MAX_COMPOUND];
1153 	unsigned int noreclaim_flag, num_io_timeout = 0;
1154 
1155 	noreclaim_flag = memalloc_noreclaim_save();
1156 	cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1157 
1158 	length = atomic_inc_return(&tcpSesAllocCount);
1159 	if (length > 1)
1160 		mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1161 
1162 	set_freezable();
1163 	allow_kernel_signal(SIGKILL);
1164 	while (server->tcpStatus != CifsExiting) {
1165 		if (try_to_freeze())
1166 			continue;
1167 
1168 		if (!allocate_buffers(server))
1169 			continue;
1170 
1171 		server->large_buf = false;
1172 		buf = server->smallbuf;
1173 		pdu_length = 4; /* enough to get RFC1001 header */
1174 
1175 		length = cifs_read_from_socket(server, buf, pdu_length);
1176 		if (length < 0)
1177 			continue;
1178 
1179 		if (is_smb1(server))
1180 			server->total_read = length;
1181 		else
1182 			server->total_read = 0;
1183 
1184 		/*
1185 		 * The right amount was read from socket - 4 bytes,
1186 		 * so we can now interpret the length field.
1187 		 */
1188 		pdu_length = get_rfc1002_length(buf);
1189 
1190 		cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1191 		if (!is_smb_response(server, buf[0]))
1192 			continue;
1193 next_pdu:
1194 		server->pdu_size = pdu_length;
1195 
1196 		/* make sure we have enough to get to the MID */
1197 		if (server->pdu_size < MID_HEADER_SIZE(server)) {
1198 			cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1199 				 server->pdu_size);
1200 			cifs_reconnect(server, true);
1201 			continue;
1202 		}
1203 
1204 		/* read down to the MID */
1205 		length = cifs_read_from_socket(server,
1206 			     buf + HEADER_PREAMBLE_SIZE(server),
1207 			     MID_HEADER_SIZE(server));
1208 		if (length < 0)
1209 			continue;
1210 		server->total_read += length;
1211 
1212 		if (server->ops->next_header) {
1213 			next_offset = server->ops->next_header(buf);
1214 			if (next_offset)
1215 				server->pdu_size = next_offset;
1216 		}
1217 
1218 		memset(mids, 0, sizeof(mids));
1219 		memset(bufs, 0, sizeof(bufs));
1220 		num_mids = 0;
1221 
1222 		if (server->ops->is_transform_hdr &&
1223 		    server->ops->receive_transform &&
1224 		    server->ops->is_transform_hdr(buf)) {
1225 			length = server->ops->receive_transform(server,
1226 								mids,
1227 								bufs,
1228 								&num_mids);
1229 		} else {
1230 			mids[0] = server->ops->find_mid(server, buf);
1231 			bufs[0] = buf;
1232 			num_mids = 1;
1233 
1234 			if (!mids[0] || !mids[0]->receive)
1235 				length = standard_receive3(server, mids[0]);
1236 			else
1237 				length = mids[0]->receive(server, mids[0]);
1238 		}
1239 
1240 		if (length < 0) {
1241 			for (i = 0; i < num_mids; i++)
1242 				if (mids[i])
1243 					release_mid(mids[i]);
1244 			continue;
1245 		}
1246 
1247 		if (server->ops->is_status_io_timeout &&
1248 		    server->ops->is_status_io_timeout(buf)) {
1249 			num_io_timeout++;
1250 			if (num_io_timeout > NUM_STATUS_IO_TIMEOUT) {
1251 				cifs_reconnect(server, false);
1252 				num_io_timeout = 0;
1253 				continue;
1254 			}
1255 		}
1256 
1257 		server->lstrp = jiffies;
1258 
1259 		for (i = 0; i < num_mids; i++) {
1260 			if (mids[i] != NULL) {
1261 				mids[i]->resp_buf_size = server->pdu_size;
1262 
1263 				if (bufs[i] && server->ops->is_network_name_deleted)
1264 					server->ops->is_network_name_deleted(bufs[i],
1265 									server);
1266 
1267 				if (!mids[i]->multiRsp || mids[i]->multiEnd)
1268 					mids[i]->callback(mids[i]);
1269 
1270 				release_mid(mids[i]);
1271 			} else if (server->ops->is_oplock_break &&
1272 				   server->ops->is_oplock_break(bufs[i],
1273 								server)) {
1274 				smb2_add_credits_from_hdr(bufs[i], server);
1275 				cifs_dbg(FYI, "Received oplock break\n");
1276 			} else {
1277 				cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1278 						atomic_read(&mid_count));
1279 				cifs_dump_mem("Received Data is: ", bufs[i],
1280 					      HEADER_SIZE(server));
1281 				smb2_add_credits_from_hdr(bufs[i], server);
1282 #ifdef CONFIG_CIFS_DEBUG2
1283 				if (server->ops->dump_detail)
1284 					server->ops->dump_detail(bufs[i],
1285 								 server);
1286 				cifs_dump_mids(server);
1287 #endif /* CIFS_DEBUG2 */
1288 			}
1289 		}
1290 
1291 		if (pdu_length > server->pdu_size) {
1292 			if (!allocate_buffers(server))
1293 				continue;
1294 			pdu_length -= server->pdu_size;
1295 			server->total_read = 0;
1296 			server->large_buf = false;
1297 			buf = server->smallbuf;
1298 			goto next_pdu;
1299 		}
1300 	} /* end while !EXITING */
1301 
1302 	/* buffer usually freed in free_mid - need to free it here on exit */
1303 	cifs_buf_release(server->bigbuf);
1304 	if (server->smallbuf) /* no sense logging a debug message if NULL */
1305 		cifs_small_buf_release(server->smallbuf);
1306 
1307 	task_to_wake = xchg(&server->tsk, NULL);
1308 	clean_demultiplex_info(server);
1309 
1310 	/* if server->tsk was NULL then wait for a signal before exiting */
1311 	if (!task_to_wake) {
1312 		set_current_state(TASK_INTERRUPTIBLE);
1313 		while (!signal_pending(current)) {
1314 			schedule();
1315 			set_current_state(TASK_INTERRUPTIBLE);
1316 		}
1317 		set_current_state(TASK_RUNNING);
1318 	}
1319 
1320 	memalloc_noreclaim_restore(noreclaim_flag);
1321 	module_put_and_kthread_exit(0);
1322 }
1323 
1324 /*
1325  * Returns true if srcaddr isn't specified and rhs isn't specified, or
1326  * if srcaddr is specified and matches the IP address of the rhs argument
1327  */
1328 bool
cifs_match_ipaddr(struct sockaddr * srcaddr,struct sockaddr * rhs)1329 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1330 {
1331 	switch (srcaddr->sa_family) {
1332 	case AF_UNSPEC:
1333 		return (rhs->sa_family == AF_UNSPEC);
1334 	case AF_INET: {
1335 		struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1336 		struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1337 		return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1338 	}
1339 	case AF_INET6: {
1340 		struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1341 		struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1342 		return ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr);
1343 	}
1344 	default:
1345 		WARN_ON(1);
1346 		return false; /* don't expect to be here */
1347 	}
1348 }
1349 
1350 /*
1351  * If no port is specified in addr structure, we try to match with 445 port
1352  * and if it fails - with 139 ports. It should be called only if address
1353  * families of server and addr are equal.
1354  */
1355 static bool
match_port(struct TCP_Server_Info * server,struct sockaddr * addr)1356 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1357 {
1358 	__be16 port, *sport;
1359 
1360 	/* SMBDirect manages its own ports, don't match it here */
1361 	if (server->rdma)
1362 		return true;
1363 
1364 	switch (addr->sa_family) {
1365 	case AF_INET:
1366 		sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1367 		port = ((struct sockaddr_in *) addr)->sin_port;
1368 		break;
1369 	case AF_INET6:
1370 		sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1371 		port = ((struct sockaddr_in6 *) addr)->sin6_port;
1372 		break;
1373 	default:
1374 		WARN_ON(1);
1375 		return false;
1376 	}
1377 
1378 	if (!port) {
1379 		port = htons(CIFS_PORT);
1380 		if (port == *sport)
1381 			return true;
1382 
1383 		port = htons(RFC1001_PORT);
1384 	}
1385 
1386 	return port == *sport;
1387 }
1388 
1389 static bool
match_address(struct TCP_Server_Info * server,struct sockaddr * addr,struct sockaddr * srcaddr)1390 match_address(struct TCP_Server_Info *server, struct sockaddr *addr,
1391 	      struct sockaddr *srcaddr)
1392 {
1393 	switch (addr->sa_family) {
1394 	case AF_INET: {
1395 		struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
1396 		struct sockaddr_in *srv_addr4 =
1397 					(struct sockaddr_in *)&server->dstaddr;
1398 
1399 		if (addr4->sin_addr.s_addr != srv_addr4->sin_addr.s_addr)
1400 			return false;
1401 		break;
1402 	}
1403 	case AF_INET6: {
1404 		struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
1405 		struct sockaddr_in6 *srv_addr6 =
1406 					(struct sockaddr_in6 *)&server->dstaddr;
1407 
1408 		if (!ipv6_addr_equal(&addr6->sin6_addr,
1409 				     &srv_addr6->sin6_addr))
1410 			return false;
1411 		if (addr6->sin6_scope_id != srv_addr6->sin6_scope_id)
1412 			return false;
1413 		break;
1414 	}
1415 	default:
1416 		WARN_ON(1);
1417 		return false; /* don't expect to be here */
1418 	}
1419 
1420 	if (!cifs_match_ipaddr(srcaddr, (struct sockaddr *)&server->srcaddr))
1421 		return false;
1422 
1423 	return true;
1424 }
1425 
1426 static bool
match_security(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)1427 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1428 {
1429 	/*
1430 	 * The select_sectype function should either return the ctx->sectype
1431 	 * that was specified, or "Unspecified" if that sectype was not
1432 	 * compatible with the given NEGOTIATE request.
1433 	 */
1434 	if (server->ops->select_sectype(server, ctx->sectype)
1435 	     == Unspecified)
1436 		return false;
1437 
1438 	/*
1439 	 * Now check if signing mode is acceptable. No need to check
1440 	 * global_secflags at this point since if MUST_SIGN is set then
1441 	 * the server->sign had better be too.
1442 	 */
1443 	if (ctx->sign && !server->sign)
1444 		return false;
1445 
1446 	return true;
1447 }
1448 
1449 /* this function must be called with srv_lock held */
match_server(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)1450 static int match_server(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1451 {
1452 	struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1453 
1454 	if (ctx->nosharesock)
1455 		return 0;
1456 
1457 	/* this server does not share socket */
1458 	if (server->nosharesock)
1459 		return 0;
1460 
1461 	/* If multidialect negotiation see if existing sessions match one */
1462 	if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1463 		if (server->vals->protocol_id < SMB30_PROT_ID)
1464 			return 0;
1465 	} else if (strcmp(ctx->vals->version_string,
1466 		   SMBDEFAULT_VERSION_STRING) == 0) {
1467 		if (server->vals->protocol_id < SMB21_PROT_ID)
1468 			return 0;
1469 	} else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1470 		return 0;
1471 
1472 	if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1473 		return 0;
1474 
1475 	if (strcasecmp(server->hostname, ctx->server_hostname))
1476 		return 0;
1477 
1478 	if (!match_address(server, addr,
1479 			   (struct sockaddr *)&ctx->srcaddr))
1480 		return 0;
1481 
1482 	if (!match_port(server, addr))
1483 		return 0;
1484 
1485 	if (!match_security(server, ctx))
1486 		return 0;
1487 
1488 	if (server->echo_interval != ctx->echo_interval * HZ)
1489 		return 0;
1490 
1491 	if (server->rdma != ctx->rdma)
1492 		return 0;
1493 
1494 	if (server->ignore_signature != ctx->ignore_signature)
1495 		return 0;
1496 
1497 	if (server->min_offload != ctx->min_offload)
1498 		return 0;
1499 
1500 	return 1;
1501 }
1502 
1503 struct TCP_Server_Info *
cifs_find_tcp_session(struct smb3_fs_context * ctx)1504 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1505 {
1506 	struct TCP_Server_Info *server;
1507 
1508 	spin_lock(&cifs_tcp_ses_lock);
1509 	list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1510 		spin_lock(&server->srv_lock);
1511 #ifdef CONFIG_CIFS_DFS_UPCALL
1512 		/*
1513 		 * DFS failover implementation in cifs_reconnect() requires unique tcp sessions for
1514 		 * DFS connections to do failover properly, so avoid sharing them with regular
1515 		 * shares or even links that may connect to same server but having completely
1516 		 * different failover targets.
1517 		 */
1518 		if (server->is_dfs_conn) {
1519 			spin_unlock(&server->srv_lock);
1520 			continue;
1521 		}
1522 #endif
1523 		/*
1524 		 * Skip ses channels since they're only handled in lower layers
1525 		 * (e.g. cifs_send_recv).
1526 		 */
1527 		if (CIFS_SERVER_IS_CHAN(server) || !match_server(server, ctx)) {
1528 			spin_unlock(&server->srv_lock);
1529 			continue;
1530 		}
1531 		spin_unlock(&server->srv_lock);
1532 
1533 		++server->srv_count;
1534 		spin_unlock(&cifs_tcp_ses_lock);
1535 		cifs_dbg(FYI, "Existing tcp session with server found\n");
1536 		return server;
1537 	}
1538 	spin_unlock(&cifs_tcp_ses_lock);
1539 	return NULL;
1540 }
1541 
1542 void
cifs_put_tcp_session(struct TCP_Server_Info * server,int from_reconnect)1543 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1544 {
1545 	struct task_struct *task;
1546 
1547 	spin_lock(&cifs_tcp_ses_lock);
1548 	if (--server->srv_count > 0) {
1549 		spin_unlock(&cifs_tcp_ses_lock);
1550 		return;
1551 	}
1552 
1553 	/* srv_count can never go negative */
1554 	WARN_ON(server->srv_count < 0);
1555 
1556 	put_net(cifs_net_ns(server));
1557 
1558 	list_del_init(&server->tcp_ses_list);
1559 	spin_unlock(&cifs_tcp_ses_lock);
1560 
1561 	/* For secondary channels, we pick up ref-count on the primary server */
1562 	if (CIFS_SERVER_IS_CHAN(server))
1563 		cifs_put_tcp_session(server->primary_server, from_reconnect);
1564 
1565 	cancel_delayed_work_sync(&server->echo);
1566 	cancel_delayed_work_sync(&server->resolve);
1567 
1568 	if (from_reconnect)
1569 		/*
1570 		 * Avoid deadlock here: reconnect work calls
1571 		 * cifs_put_tcp_session() at its end. Need to be sure
1572 		 * that reconnect work does nothing with server pointer after
1573 		 * that step.
1574 		 */
1575 		cancel_delayed_work(&server->reconnect);
1576 	else
1577 		cancel_delayed_work_sync(&server->reconnect);
1578 
1579 	spin_lock(&server->srv_lock);
1580 	server->tcpStatus = CifsExiting;
1581 	spin_unlock(&server->srv_lock);
1582 
1583 	cifs_crypto_secmech_release(server);
1584 
1585 	kfree_sensitive(server->session_key.response);
1586 	server->session_key.response = NULL;
1587 	server->session_key.len = 0;
1588 	kfree(server->hostname);
1589 	server->hostname = NULL;
1590 
1591 	task = xchg(&server->tsk, NULL);
1592 	if (task)
1593 		send_sig(SIGKILL, task, 1);
1594 }
1595 
1596 struct TCP_Server_Info *
cifs_get_tcp_session(struct smb3_fs_context * ctx,struct TCP_Server_Info * primary_server)1597 cifs_get_tcp_session(struct smb3_fs_context *ctx,
1598 		     struct TCP_Server_Info *primary_server)
1599 {
1600 	struct TCP_Server_Info *tcp_ses = NULL;
1601 	int rc;
1602 
1603 	cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1604 
1605 	/* see if we already have a matching tcp_ses */
1606 	tcp_ses = cifs_find_tcp_session(ctx);
1607 	if (tcp_ses)
1608 		return tcp_ses;
1609 
1610 	tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1611 	if (!tcp_ses) {
1612 		rc = -ENOMEM;
1613 		goto out_err;
1614 	}
1615 
1616 	tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1617 	if (!tcp_ses->hostname) {
1618 		rc = -ENOMEM;
1619 		goto out_err;
1620 	}
1621 
1622 	if (ctx->nosharesock)
1623 		tcp_ses->nosharesock = true;
1624 
1625 	tcp_ses->ops = ctx->ops;
1626 	tcp_ses->vals = ctx->vals;
1627 	cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1628 
1629 	tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1630 	tcp_ses->noblockcnt = ctx->rootfs;
1631 	tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1632 	tcp_ses->noautotune = ctx->noautotune;
1633 	tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1634 	tcp_ses->rdma = ctx->rdma;
1635 	tcp_ses->in_flight = 0;
1636 	tcp_ses->max_in_flight = 0;
1637 	tcp_ses->credits = 1;
1638 	if (primary_server) {
1639 		spin_lock(&cifs_tcp_ses_lock);
1640 		++primary_server->srv_count;
1641 		spin_unlock(&cifs_tcp_ses_lock);
1642 		tcp_ses->primary_server = primary_server;
1643 	}
1644 	init_waitqueue_head(&tcp_ses->response_q);
1645 	init_waitqueue_head(&tcp_ses->request_q);
1646 	INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1647 	mutex_init(&tcp_ses->_srv_mutex);
1648 	memcpy(tcp_ses->workstation_RFC1001_name,
1649 		ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1650 	memcpy(tcp_ses->server_RFC1001_name,
1651 		ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1652 	tcp_ses->session_estab = false;
1653 	tcp_ses->sequence_number = 0;
1654 	tcp_ses->reconnect_instance = 1;
1655 	tcp_ses->lstrp = jiffies;
1656 	tcp_ses->compress_algorithm = cpu_to_le16(ctx->compression);
1657 	spin_lock_init(&tcp_ses->req_lock);
1658 	spin_lock_init(&tcp_ses->srv_lock);
1659 	spin_lock_init(&tcp_ses->mid_lock);
1660 	INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1661 	INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1662 	INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1663 	INIT_DELAYED_WORK(&tcp_ses->resolve, cifs_resolve_server);
1664 	INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1665 	mutex_init(&tcp_ses->reconnect_mutex);
1666 #ifdef CONFIG_CIFS_DFS_UPCALL
1667 	mutex_init(&tcp_ses->refpath_lock);
1668 #endif
1669 	memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1670 	       sizeof(tcp_ses->srcaddr));
1671 	memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1672 		sizeof(tcp_ses->dstaddr));
1673 	if (ctx->use_client_guid)
1674 		memcpy(tcp_ses->client_guid, ctx->client_guid,
1675 		       SMB2_CLIENT_GUID_SIZE);
1676 	else
1677 		generate_random_uuid(tcp_ses->client_guid);
1678 	/*
1679 	 * at this point we are the only ones with the pointer
1680 	 * to the struct since the kernel thread not created yet
1681 	 * no need to spinlock this init of tcpStatus or srv_count
1682 	 */
1683 	tcp_ses->tcpStatus = CifsNew;
1684 	++tcp_ses->srv_count;
1685 
1686 	if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1687 		ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1688 		tcp_ses->echo_interval = ctx->echo_interval * HZ;
1689 	else
1690 		tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1691 	if (tcp_ses->rdma) {
1692 #ifndef CONFIG_CIFS_SMB_DIRECT
1693 		cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1694 		rc = -ENOENT;
1695 		goto out_err_crypto_release;
1696 #endif
1697 		tcp_ses->smbd_conn = smbd_get_connection(
1698 			tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1699 		if (tcp_ses->smbd_conn) {
1700 			cifs_dbg(VFS, "RDMA transport established\n");
1701 			rc = 0;
1702 			goto smbd_connected;
1703 		} else {
1704 			rc = -ENOENT;
1705 			goto out_err_crypto_release;
1706 		}
1707 	}
1708 	rc = ip_connect(tcp_ses);
1709 	if (rc < 0) {
1710 		cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1711 		goto out_err_crypto_release;
1712 	}
1713 smbd_connected:
1714 	/*
1715 	 * since we're in a cifs function already, we know that
1716 	 * this will succeed. No need for try_module_get().
1717 	 */
1718 	__module_get(THIS_MODULE);
1719 	tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1720 				  tcp_ses, "cifsd");
1721 	if (IS_ERR(tcp_ses->tsk)) {
1722 		rc = PTR_ERR(tcp_ses->tsk);
1723 		cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1724 		module_put(THIS_MODULE);
1725 		goto out_err_crypto_release;
1726 	}
1727 	tcp_ses->min_offload = ctx->min_offload;
1728 	/*
1729 	 * at this point we are the only ones with the pointer
1730 	 * to the struct since the kernel thread not created yet
1731 	 * no need to spinlock this update of tcpStatus
1732 	 */
1733 	spin_lock(&tcp_ses->srv_lock);
1734 	tcp_ses->tcpStatus = CifsNeedNegotiate;
1735 	spin_unlock(&tcp_ses->srv_lock);
1736 
1737 	if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1738 		tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1739 	else
1740 		tcp_ses->max_credits = ctx->max_credits;
1741 
1742 	tcp_ses->nr_targets = 1;
1743 	tcp_ses->ignore_signature = ctx->ignore_signature;
1744 	/* thread spawned, put it on the list */
1745 	spin_lock(&cifs_tcp_ses_lock);
1746 	list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1747 	spin_unlock(&cifs_tcp_ses_lock);
1748 
1749 	/* queue echo request delayed work */
1750 	queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1751 
1752 	/* queue dns resolution delayed work */
1753 	cifs_dbg(FYI, "%s: next dns resolution scheduled for %d seconds in the future\n",
1754 		 __func__, SMB_DNS_RESOLVE_INTERVAL_DEFAULT);
1755 
1756 	queue_delayed_work(cifsiod_wq, &tcp_ses->resolve, (SMB_DNS_RESOLVE_INTERVAL_DEFAULT * HZ));
1757 
1758 	return tcp_ses;
1759 
1760 out_err_crypto_release:
1761 	cifs_crypto_secmech_release(tcp_ses);
1762 
1763 	put_net(cifs_net_ns(tcp_ses));
1764 
1765 out_err:
1766 	if (tcp_ses) {
1767 		if (CIFS_SERVER_IS_CHAN(tcp_ses))
1768 			cifs_put_tcp_session(tcp_ses->primary_server, false);
1769 		kfree(tcp_ses->hostname);
1770 		if (tcp_ses->ssocket)
1771 			sock_release(tcp_ses->ssocket);
1772 		kfree(tcp_ses);
1773 	}
1774 	return ERR_PTR(rc);
1775 }
1776 
1777 /* this function must be called with ses_lock held */
match_session(struct cifs_ses * ses,struct smb3_fs_context * ctx)1778 static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1779 {
1780 	if (ctx->sectype != Unspecified &&
1781 	    ctx->sectype != ses->sectype)
1782 		return 0;
1783 
1784 	/*
1785 	 * If an existing session is limited to less channels than
1786 	 * requested, it should not be reused
1787 	 */
1788 	spin_lock(&ses->chan_lock);
1789 	if (ses->chan_max < ctx->max_channels) {
1790 		spin_unlock(&ses->chan_lock);
1791 		return 0;
1792 	}
1793 	spin_unlock(&ses->chan_lock);
1794 
1795 	switch (ses->sectype) {
1796 	case Kerberos:
1797 		if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1798 			return 0;
1799 		break;
1800 	default:
1801 		/* NULL username means anonymous session */
1802 		if (ses->user_name == NULL) {
1803 			if (!ctx->nullauth)
1804 				return 0;
1805 			break;
1806 		}
1807 
1808 		/* anything else takes username/password */
1809 		if (strncmp(ses->user_name,
1810 			    ctx->username ? ctx->username : "",
1811 			    CIFS_MAX_USERNAME_LEN))
1812 			return 0;
1813 		if ((ctx->username && strlen(ctx->username) != 0) &&
1814 		    ses->password != NULL &&
1815 		    strncmp(ses->password,
1816 			    ctx->password ? ctx->password : "",
1817 			    CIFS_MAX_PASSWORD_LEN))
1818 			return 0;
1819 	}
1820 	return 1;
1821 }
1822 
1823 /**
1824  * cifs_setup_ipc - helper to setup the IPC tcon for the session
1825  * @ses: smb session to issue the request on
1826  * @ctx: the superblock configuration context to use for building the
1827  *       new tree connection for the IPC (interprocess communication RPC)
1828  *
1829  * A new IPC connection is made and stored in the session
1830  * tcon_ipc. The IPC tcon has the same lifetime as the session.
1831  */
1832 static int
cifs_setup_ipc(struct cifs_ses * ses,struct smb3_fs_context * ctx)1833 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1834 {
1835 	int rc = 0, xid;
1836 	struct cifs_tcon *tcon;
1837 	char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1838 	bool seal = false;
1839 	struct TCP_Server_Info *server = ses->server;
1840 
1841 	/*
1842 	 * If the mount request that resulted in the creation of the
1843 	 * session requires encryption, force IPC to be encrypted too.
1844 	 */
1845 	if (ctx->seal) {
1846 		if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1847 			seal = true;
1848 		else {
1849 			cifs_server_dbg(VFS,
1850 				 "IPC: server doesn't support encryption\n");
1851 			return -EOPNOTSUPP;
1852 		}
1853 	}
1854 
1855 	tcon = tconInfoAlloc();
1856 	if (tcon == NULL)
1857 		return -ENOMEM;
1858 
1859 	scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1860 
1861 	xid = get_xid();
1862 	tcon->ses = ses;
1863 	tcon->ipc = true;
1864 	tcon->seal = seal;
1865 	rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
1866 	free_xid(xid);
1867 
1868 	if (rc) {
1869 		cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
1870 		tconInfoFree(tcon);
1871 		goto out;
1872 	}
1873 
1874 	cifs_dbg(FYI, "IPC tcon rc=%d ipc tid=0x%x\n", rc, tcon->tid);
1875 
1876 	spin_lock(&tcon->tc_lock);
1877 	tcon->status = TID_GOOD;
1878 	spin_unlock(&tcon->tc_lock);
1879 	ses->tcon_ipc = tcon;
1880 out:
1881 	return rc;
1882 }
1883 
1884 /**
1885  * cifs_free_ipc - helper to release the session IPC tcon
1886  * @ses: smb session to unmount the IPC from
1887  *
1888  * Needs to be called everytime a session is destroyed.
1889  *
1890  * On session close, the IPC is closed and the server must release all tcons of the session.
1891  * No need to send a tree disconnect here.
1892  *
1893  * Besides, it will make the server to not close durable and resilient files on session close, as
1894  * specified in MS-SMB2 3.3.5.6 Receiving an SMB2 LOGOFF Request.
1895  */
1896 static int
cifs_free_ipc(struct cifs_ses * ses)1897 cifs_free_ipc(struct cifs_ses *ses)
1898 {
1899 	struct cifs_tcon *tcon = ses->tcon_ipc;
1900 
1901 	if (tcon == NULL)
1902 		return 0;
1903 
1904 	tconInfoFree(tcon);
1905 	ses->tcon_ipc = NULL;
1906 	return 0;
1907 }
1908 
1909 static struct cifs_ses *
cifs_find_smb_ses(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)1910 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1911 {
1912 	struct cifs_ses *ses;
1913 
1914 	spin_lock(&cifs_tcp_ses_lock);
1915 	list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
1916 		spin_lock(&ses->ses_lock);
1917 		if (ses->ses_status == SES_EXITING) {
1918 			spin_unlock(&ses->ses_lock);
1919 			continue;
1920 		}
1921 		if (!match_session(ses, ctx)) {
1922 			spin_unlock(&ses->ses_lock);
1923 			continue;
1924 		}
1925 		spin_unlock(&ses->ses_lock);
1926 
1927 		++ses->ses_count;
1928 		spin_unlock(&cifs_tcp_ses_lock);
1929 		return ses;
1930 	}
1931 	spin_unlock(&cifs_tcp_ses_lock);
1932 	return NULL;
1933 }
1934 
cifs_put_smb_ses(struct cifs_ses * ses)1935 void cifs_put_smb_ses(struct cifs_ses *ses)
1936 {
1937 	unsigned int rc, xid;
1938 	unsigned int chan_count;
1939 	struct TCP_Server_Info *server = ses->server;
1940 
1941 	spin_lock(&ses->ses_lock);
1942 	if (ses->ses_status == SES_EXITING) {
1943 		spin_unlock(&ses->ses_lock);
1944 		return;
1945 	}
1946 	spin_unlock(&ses->ses_lock);
1947 
1948 	cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
1949 	cifs_dbg(FYI,
1950 		 "%s: ses ipc: %s\n", __func__, ses->tcon_ipc ? ses->tcon_ipc->tree_name : "NONE");
1951 
1952 	spin_lock(&cifs_tcp_ses_lock);
1953 	if (--ses->ses_count > 0) {
1954 		spin_unlock(&cifs_tcp_ses_lock);
1955 		return;
1956 	}
1957 	spin_unlock(&cifs_tcp_ses_lock);
1958 
1959 	/* ses_count can never go negative */
1960 	WARN_ON(ses->ses_count < 0);
1961 
1962 	if (ses->ses_status == SES_GOOD)
1963 		ses->ses_status = SES_EXITING;
1964 
1965 	cifs_free_ipc(ses);
1966 
1967 	if (ses->ses_status == SES_EXITING && server->ops->logoff) {
1968 		xid = get_xid();
1969 		rc = server->ops->logoff(xid, ses);
1970 		if (rc)
1971 			cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
1972 				__func__, rc);
1973 		_free_xid(xid);
1974 	}
1975 
1976 	spin_lock(&cifs_tcp_ses_lock);
1977 	list_del_init(&ses->smb_ses_list);
1978 	spin_unlock(&cifs_tcp_ses_lock);
1979 
1980 	chan_count = ses->chan_count;
1981 
1982 	/* close any extra channels */
1983 	if (chan_count > 1) {
1984 		int i;
1985 
1986 		for (i = 1; i < chan_count; i++) {
1987 			if (ses->chans[i].iface) {
1988 				kref_put(&ses->chans[i].iface->refcount, release_iface);
1989 				ses->chans[i].iface = NULL;
1990 			}
1991 			cifs_put_tcp_session(ses->chans[i].server, 0);
1992 			ses->chans[i].server = NULL;
1993 		}
1994 	}
1995 
1996 	sesInfoFree(ses);
1997 	cifs_put_tcp_session(server, 0);
1998 }
1999 
2000 #ifdef CONFIG_KEYS
2001 
2002 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
2003 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
2004 
2005 /* Populate username and pw fields from keyring if possible */
2006 static int
cifs_set_cifscreds(struct smb3_fs_context * ctx,struct cifs_ses * ses)2007 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
2008 {
2009 	int rc = 0;
2010 	int is_domain = 0;
2011 	const char *delim, *payload;
2012 	char *desc;
2013 	ssize_t len;
2014 	struct key *key;
2015 	struct TCP_Server_Info *server = ses->server;
2016 	struct sockaddr_in *sa;
2017 	struct sockaddr_in6 *sa6;
2018 	const struct user_key_payload *upayload;
2019 
2020 	desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
2021 	if (!desc)
2022 		return -ENOMEM;
2023 
2024 	/* try to find an address key first */
2025 	switch (server->dstaddr.ss_family) {
2026 	case AF_INET:
2027 		sa = (struct sockaddr_in *)&server->dstaddr;
2028 		sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
2029 		break;
2030 	case AF_INET6:
2031 		sa6 = (struct sockaddr_in6 *)&server->dstaddr;
2032 		sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
2033 		break;
2034 	default:
2035 		cifs_dbg(FYI, "Bad ss_family (%hu)\n",
2036 			 server->dstaddr.ss_family);
2037 		rc = -EINVAL;
2038 		goto out_err;
2039 	}
2040 
2041 	cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2042 	key = request_key(&key_type_logon, desc, "");
2043 	if (IS_ERR(key)) {
2044 		if (!ses->domainName) {
2045 			cifs_dbg(FYI, "domainName is NULL\n");
2046 			rc = PTR_ERR(key);
2047 			goto out_err;
2048 		}
2049 
2050 		/* didn't work, try to find a domain key */
2051 		sprintf(desc, "cifs:d:%s", ses->domainName);
2052 		cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2053 		key = request_key(&key_type_logon, desc, "");
2054 		if (IS_ERR(key)) {
2055 			rc = PTR_ERR(key);
2056 			goto out_err;
2057 		}
2058 		is_domain = 1;
2059 	}
2060 
2061 	down_read(&key->sem);
2062 	upayload = user_key_payload_locked(key);
2063 	if (IS_ERR_OR_NULL(upayload)) {
2064 		rc = upayload ? PTR_ERR(upayload) : -EINVAL;
2065 		goto out_key_put;
2066 	}
2067 
2068 	/* find first : in payload */
2069 	payload = upayload->data;
2070 	delim = strnchr(payload, upayload->datalen, ':');
2071 	cifs_dbg(FYI, "payload=%s\n", payload);
2072 	if (!delim) {
2073 		cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
2074 			 upayload->datalen);
2075 		rc = -EINVAL;
2076 		goto out_key_put;
2077 	}
2078 
2079 	len = delim - payload;
2080 	if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
2081 		cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
2082 			 len);
2083 		rc = -EINVAL;
2084 		goto out_key_put;
2085 	}
2086 
2087 	ctx->username = kstrndup(payload, len, GFP_KERNEL);
2088 	if (!ctx->username) {
2089 		cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
2090 			 len);
2091 		rc = -ENOMEM;
2092 		goto out_key_put;
2093 	}
2094 	cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
2095 
2096 	len = key->datalen - (len + 1);
2097 	if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
2098 		cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
2099 		rc = -EINVAL;
2100 		kfree(ctx->username);
2101 		ctx->username = NULL;
2102 		goto out_key_put;
2103 	}
2104 
2105 	++delim;
2106 	ctx->password = kstrndup(delim, len, GFP_KERNEL);
2107 	if (!ctx->password) {
2108 		cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
2109 			 len);
2110 		rc = -ENOMEM;
2111 		kfree(ctx->username);
2112 		ctx->username = NULL;
2113 		goto out_key_put;
2114 	}
2115 
2116 	/*
2117 	 * If we have a domain key then we must set the domainName in the
2118 	 * for the request.
2119 	 */
2120 	if (is_domain && ses->domainName) {
2121 		ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
2122 		if (!ctx->domainname) {
2123 			cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
2124 				 len);
2125 			rc = -ENOMEM;
2126 			kfree(ctx->username);
2127 			ctx->username = NULL;
2128 			kfree_sensitive(ctx->password);
2129 			ctx->password = NULL;
2130 			goto out_key_put;
2131 		}
2132 	}
2133 
2134 	strscpy(ctx->workstation_name, ses->workstation_name, sizeof(ctx->workstation_name));
2135 
2136 out_key_put:
2137 	up_read(&key->sem);
2138 	key_put(key);
2139 out_err:
2140 	kfree(desc);
2141 	cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2142 	return rc;
2143 }
2144 #else /* ! CONFIG_KEYS */
2145 static inline int
cifs_set_cifscreds(struct smb3_fs_context * ctx,struct cifs_ses * ses)2146 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
2147 		   struct cifs_ses *ses __attribute__((unused)))
2148 {
2149 	return -ENOSYS;
2150 }
2151 #endif /* CONFIG_KEYS */
2152 
2153 /**
2154  * cifs_get_smb_ses - get a session matching @ctx data from @server
2155  * @server: server to setup the session to
2156  * @ctx: superblock configuration context to use to setup the session
2157  *
2158  * This function assumes it is being called from cifs_mount() where we
2159  * already got a server reference (server refcount +1). See
2160  * cifs_get_tcon() for refcount explanations.
2161  */
2162 struct cifs_ses *
cifs_get_smb_ses(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)2163 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2164 {
2165 	int rc = 0;
2166 	unsigned int xid;
2167 	struct cifs_ses *ses;
2168 	struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2169 	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2170 
2171 	xid = get_xid();
2172 
2173 	ses = cifs_find_smb_ses(server, ctx);
2174 	if (ses) {
2175 		cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2176 			 ses->ses_status);
2177 
2178 		spin_lock(&ses->chan_lock);
2179 		if (cifs_chan_needs_reconnect(ses, server)) {
2180 			spin_unlock(&ses->chan_lock);
2181 			cifs_dbg(FYI, "Session needs reconnect\n");
2182 
2183 			mutex_lock(&ses->session_mutex);
2184 			rc = cifs_negotiate_protocol(xid, ses, server);
2185 			if (rc) {
2186 				mutex_unlock(&ses->session_mutex);
2187 				/* problem -- put our ses reference */
2188 				cifs_put_smb_ses(ses);
2189 				free_xid(xid);
2190 				return ERR_PTR(rc);
2191 			}
2192 
2193 			rc = cifs_setup_session(xid, ses, server,
2194 						ctx->local_nls);
2195 			if (rc) {
2196 				mutex_unlock(&ses->session_mutex);
2197 				/* problem -- put our reference */
2198 				cifs_put_smb_ses(ses);
2199 				free_xid(xid);
2200 				return ERR_PTR(rc);
2201 			}
2202 			mutex_unlock(&ses->session_mutex);
2203 
2204 			spin_lock(&ses->chan_lock);
2205 		}
2206 		spin_unlock(&ses->chan_lock);
2207 
2208 		/* existing SMB ses has a server reference already */
2209 		cifs_put_tcp_session(server, 0);
2210 		free_xid(xid);
2211 		return ses;
2212 	}
2213 
2214 	rc = -ENOMEM;
2215 
2216 	cifs_dbg(FYI, "Existing smb sess not found\n");
2217 	ses = sesInfoAlloc();
2218 	if (ses == NULL)
2219 		goto get_ses_fail;
2220 
2221 	/* new SMB session uses our server ref */
2222 	ses->server = server;
2223 	if (server->dstaddr.ss_family == AF_INET6)
2224 		sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2225 	else
2226 		sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2227 
2228 	if (ctx->username) {
2229 		ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2230 		if (!ses->user_name)
2231 			goto get_ses_fail;
2232 	}
2233 
2234 	/* ctx->password freed at unmount */
2235 	if (ctx->password) {
2236 		ses->password = kstrdup(ctx->password, GFP_KERNEL);
2237 		if (!ses->password)
2238 			goto get_ses_fail;
2239 	}
2240 	if (ctx->domainname) {
2241 		ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2242 		if (!ses->domainName)
2243 			goto get_ses_fail;
2244 	}
2245 
2246 	strscpy(ses->workstation_name, ctx->workstation_name, sizeof(ses->workstation_name));
2247 
2248 	if (ctx->domainauto)
2249 		ses->domainAuto = ctx->domainauto;
2250 	ses->cred_uid = ctx->cred_uid;
2251 	ses->linux_uid = ctx->linux_uid;
2252 
2253 	ses->sectype = ctx->sectype;
2254 	ses->sign = ctx->sign;
2255 
2256 	/* add server as first channel */
2257 	spin_lock(&ses->chan_lock);
2258 	ses->chans[0].server = server;
2259 	ses->chan_count = 1;
2260 	ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2261 	ses->chans_need_reconnect = 1;
2262 	spin_unlock(&ses->chan_lock);
2263 
2264 	mutex_lock(&ses->session_mutex);
2265 	rc = cifs_negotiate_protocol(xid, ses, server);
2266 	if (!rc)
2267 		rc = cifs_setup_session(xid, ses, server, ctx->local_nls);
2268 	mutex_unlock(&ses->session_mutex);
2269 
2270 	/* each channel uses a different signing key */
2271 	spin_lock(&ses->chan_lock);
2272 	memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2273 	       sizeof(ses->smb3signingkey));
2274 	spin_unlock(&ses->chan_lock);
2275 
2276 	if (rc)
2277 		goto get_ses_fail;
2278 
2279 	/*
2280 	 * success, put it on the list and add it as first channel
2281 	 * note: the session becomes active soon after this. So you'll
2282 	 * need to lock before changing something in the session.
2283 	 */
2284 	spin_lock(&cifs_tcp_ses_lock);
2285 	list_add(&ses->smb_ses_list, &server->smb_ses_list);
2286 	spin_unlock(&cifs_tcp_ses_lock);
2287 
2288 	cifs_setup_ipc(ses, ctx);
2289 
2290 	free_xid(xid);
2291 
2292 	return ses;
2293 
2294 get_ses_fail:
2295 	sesInfoFree(ses);
2296 	free_xid(xid);
2297 	return ERR_PTR(rc);
2298 }
2299 
2300 /* this function must be called with tc_lock held */
match_tcon(struct cifs_tcon * tcon,struct smb3_fs_context * ctx)2301 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2302 {
2303 	if (tcon->status == TID_EXITING)
2304 		return 0;
2305 	if (strncmp(tcon->tree_name, ctx->UNC, MAX_TREE_SIZE))
2306 		return 0;
2307 	if (tcon->seal != ctx->seal)
2308 		return 0;
2309 	if (tcon->snapshot_time != ctx->snapshot_time)
2310 		return 0;
2311 	if (tcon->handle_timeout != ctx->handle_timeout)
2312 		return 0;
2313 	if (tcon->no_lease != ctx->no_lease)
2314 		return 0;
2315 	if (tcon->nodelete != ctx->nodelete)
2316 		return 0;
2317 	return 1;
2318 }
2319 
2320 static struct cifs_tcon *
cifs_find_tcon(struct cifs_ses * ses,struct smb3_fs_context * ctx)2321 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2322 {
2323 	struct cifs_tcon *tcon;
2324 
2325 	spin_lock(&cifs_tcp_ses_lock);
2326 	list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2327 		spin_lock(&tcon->tc_lock);
2328 		if (!match_tcon(tcon, ctx)) {
2329 			spin_unlock(&tcon->tc_lock);
2330 			continue;
2331 		}
2332 		++tcon->tc_count;
2333 		spin_unlock(&tcon->tc_lock);
2334 		spin_unlock(&cifs_tcp_ses_lock);
2335 		return tcon;
2336 	}
2337 	spin_unlock(&cifs_tcp_ses_lock);
2338 	return NULL;
2339 }
2340 
2341 void
cifs_put_tcon(struct cifs_tcon * tcon)2342 cifs_put_tcon(struct cifs_tcon *tcon)
2343 {
2344 	unsigned int xid;
2345 	struct cifs_ses *ses;
2346 
2347 	/*
2348 	 * IPC tcon share the lifetime of their session and are
2349 	 * destroyed in the session put function
2350 	 */
2351 	if (tcon == NULL || tcon->ipc)
2352 		return;
2353 
2354 	ses = tcon->ses;
2355 	cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2356 	spin_lock(&cifs_tcp_ses_lock);
2357 	spin_lock(&tcon->tc_lock);
2358 	if (--tcon->tc_count > 0) {
2359 		spin_unlock(&tcon->tc_lock);
2360 		spin_unlock(&cifs_tcp_ses_lock);
2361 		return;
2362 	}
2363 
2364 	/* tc_count can never go negative */
2365 	WARN_ON(tcon->tc_count < 0);
2366 
2367 	list_del_init(&tcon->tcon_list);
2368 	spin_unlock(&tcon->tc_lock);
2369 	spin_unlock(&cifs_tcp_ses_lock);
2370 
2371 	/* cancel polling of interfaces */
2372 	cancel_delayed_work_sync(&tcon->query_interfaces);
2373 
2374 	if (tcon->use_witness) {
2375 		int rc;
2376 
2377 		rc = cifs_swn_unregister(tcon);
2378 		if (rc < 0) {
2379 			cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2380 					__func__, rc);
2381 		}
2382 	}
2383 
2384 	xid = get_xid();
2385 	if (ses->server->ops->tree_disconnect)
2386 		ses->server->ops->tree_disconnect(xid, tcon);
2387 	_free_xid(xid);
2388 
2389 	cifs_fscache_release_super_cookie(tcon);
2390 	tconInfoFree(tcon);
2391 	cifs_put_smb_ses(ses);
2392 }
2393 
2394 /**
2395  * cifs_get_tcon - get a tcon matching @ctx data from @ses
2396  * @ses: smb session to issue the request on
2397  * @ctx: the superblock configuration context to use for building the
2398  *
2399  * - tcon refcount is the number of mount points using the tcon.
2400  * - ses refcount is the number of tcon using the session.
2401  *
2402  * 1. This function assumes it is being called from cifs_mount() where
2403  *    we already got a session reference (ses refcount +1).
2404  *
2405  * 2. Since we're in the context of adding a mount point, the end
2406  *    result should be either:
2407  *
2408  * a) a new tcon already allocated with refcount=1 (1 mount point) and
2409  *    its session refcount incremented (1 new tcon). This +1 was
2410  *    already done in (1).
2411  *
2412  * b) an existing tcon with refcount+1 (add a mount point to it) and
2413  *    identical ses refcount (no new tcon). Because of (1) we need to
2414  *    decrement the ses refcount.
2415  */
2416 static struct cifs_tcon *
cifs_get_tcon(struct cifs_ses * ses,struct smb3_fs_context * ctx)2417 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2418 {
2419 	int rc, xid;
2420 	struct cifs_tcon *tcon;
2421 
2422 	tcon = cifs_find_tcon(ses, ctx);
2423 	if (tcon) {
2424 		/*
2425 		 * tcon has refcount already incremented but we need to
2426 		 * decrement extra ses reference gotten by caller (case b)
2427 		 */
2428 		cifs_dbg(FYI, "Found match on UNC path\n");
2429 		cifs_put_smb_ses(ses);
2430 		return tcon;
2431 	}
2432 
2433 	if (!ses->server->ops->tree_connect) {
2434 		rc = -ENOSYS;
2435 		goto out_fail;
2436 	}
2437 
2438 	tcon = tconInfoAlloc();
2439 	if (tcon == NULL) {
2440 		rc = -ENOMEM;
2441 		goto out_fail;
2442 	}
2443 
2444 	if (ctx->snapshot_time) {
2445 		if (ses->server->vals->protocol_id == 0) {
2446 			cifs_dbg(VFS,
2447 			     "Use SMB2 or later for snapshot mount option\n");
2448 			rc = -EOPNOTSUPP;
2449 			goto out_fail;
2450 		} else
2451 			tcon->snapshot_time = ctx->snapshot_time;
2452 	}
2453 
2454 	if (ctx->handle_timeout) {
2455 		if (ses->server->vals->protocol_id == 0) {
2456 			cifs_dbg(VFS,
2457 			     "Use SMB2.1 or later for handle timeout option\n");
2458 			rc = -EOPNOTSUPP;
2459 			goto out_fail;
2460 		} else
2461 			tcon->handle_timeout = ctx->handle_timeout;
2462 	}
2463 
2464 	tcon->ses = ses;
2465 	if (ctx->password) {
2466 		tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2467 		if (!tcon->password) {
2468 			rc = -ENOMEM;
2469 			goto out_fail;
2470 		}
2471 	}
2472 
2473 	if (ctx->seal) {
2474 		if (ses->server->vals->protocol_id == 0) {
2475 			cifs_dbg(VFS,
2476 				 "SMB3 or later required for encryption\n");
2477 			rc = -EOPNOTSUPP;
2478 			goto out_fail;
2479 		} else if (tcon->ses->server->capabilities &
2480 					SMB2_GLOBAL_CAP_ENCRYPTION)
2481 			tcon->seal = true;
2482 		else {
2483 			cifs_dbg(VFS, "Encryption is not supported on share\n");
2484 			rc = -EOPNOTSUPP;
2485 			goto out_fail;
2486 		}
2487 	}
2488 
2489 	if (ctx->linux_ext) {
2490 		if (ses->server->posix_ext_supported) {
2491 			tcon->posix_extensions = true;
2492 			pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2493 		} else if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
2494 		    (strcmp(ses->server->vals->version_string,
2495 		     SMB3ANY_VERSION_STRING) == 0) ||
2496 		    (strcmp(ses->server->vals->version_string,
2497 		     SMBDEFAULT_VERSION_STRING) == 0)) {
2498 			cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2499 			rc = -EOPNOTSUPP;
2500 			goto out_fail;
2501 		} else {
2502 			cifs_dbg(VFS, "Check vers= mount option. SMB3.11 "
2503 				"disabled but required for POSIX extensions\n");
2504 			rc = -EOPNOTSUPP;
2505 			goto out_fail;
2506 		}
2507 	}
2508 
2509 	xid = get_xid();
2510 	rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2511 					    ctx->local_nls);
2512 	free_xid(xid);
2513 	cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2514 	if (rc)
2515 		goto out_fail;
2516 
2517 	tcon->use_persistent = false;
2518 	/* check if SMB2 or later, CIFS does not support persistent handles */
2519 	if (ctx->persistent) {
2520 		if (ses->server->vals->protocol_id == 0) {
2521 			cifs_dbg(VFS,
2522 			     "SMB3 or later required for persistent handles\n");
2523 			rc = -EOPNOTSUPP;
2524 			goto out_fail;
2525 		} else if (ses->server->capabilities &
2526 			   SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2527 			tcon->use_persistent = true;
2528 		else /* persistent handles requested but not supported */ {
2529 			cifs_dbg(VFS,
2530 				"Persistent handles not supported on share\n");
2531 			rc = -EOPNOTSUPP;
2532 			goto out_fail;
2533 		}
2534 	} else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2535 	     && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2536 	     && (ctx->nopersistent == false)) {
2537 		cifs_dbg(FYI, "enabling persistent handles\n");
2538 		tcon->use_persistent = true;
2539 	} else if (ctx->resilient) {
2540 		if (ses->server->vals->protocol_id == 0) {
2541 			cifs_dbg(VFS,
2542 			     "SMB2.1 or later required for resilient handles\n");
2543 			rc = -EOPNOTSUPP;
2544 			goto out_fail;
2545 		}
2546 		tcon->use_resilient = true;
2547 	}
2548 
2549 	tcon->use_witness = false;
2550 	if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2551 		if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2552 			if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2553 				/*
2554 				 * Set witness in use flag in first place
2555 				 * to retry registration in the echo task
2556 				 */
2557 				tcon->use_witness = true;
2558 				/* And try to register immediately */
2559 				rc = cifs_swn_register(tcon);
2560 				if (rc < 0) {
2561 					cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2562 					goto out_fail;
2563 				}
2564 			} else {
2565 				/* TODO: try to extend for non-cluster uses (eg multichannel) */
2566 				cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2567 				rc = -EOPNOTSUPP;
2568 				goto out_fail;
2569 			}
2570 		} else {
2571 			cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2572 			rc = -EOPNOTSUPP;
2573 			goto out_fail;
2574 		}
2575 	}
2576 
2577 	/* If the user really knows what they are doing they can override */
2578 	if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2579 		if (ctx->cache_ro)
2580 			cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2581 		else if (ctx->cache_rw)
2582 			cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2583 	}
2584 
2585 	if (ctx->no_lease) {
2586 		if (ses->server->vals->protocol_id == 0) {
2587 			cifs_dbg(VFS,
2588 				"SMB2 or later required for nolease option\n");
2589 			rc = -EOPNOTSUPP;
2590 			goto out_fail;
2591 		} else
2592 			tcon->no_lease = ctx->no_lease;
2593 	}
2594 
2595 	/*
2596 	 * We can have only one retry value for a connection to a share so for
2597 	 * resources mounted more than once to the same server share the last
2598 	 * value passed in for the retry flag is used.
2599 	 */
2600 	tcon->retry = ctx->retry;
2601 	tcon->nocase = ctx->nocase;
2602 	tcon->broken_sparse_sup = ctx->no_sparse;
2603 	if (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING)
2604 		tcon->nohandlecache = ctx->nohandlecache;
2605 	else
2606 		tcon->nohandlecache = true;
2607 	tcon->nodelete = ctx->nodelete;
2608 	tcon->local_lease = ctx->local_lease;
2609 	INIT_LIST_HEAD(&tcon->pending_opens);
2610 	tcon->status = TID_GOOD;
2611 
2612 	INIT_DELAYED_WORK(&tcon->query_interfaces,
2613 			  smb2_query_server_interfaces);
2614 	if (ses->server->dialect >= SMB30_PROT_ID &&
2615 	    (ses->server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
2616 		/* schedule query interfaces poll */
2617 		queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
2618 				   (SMB_INTERFACE_POLL_INTERVAL * HZ));
2619 	}
2620 
2621 	spin_lock(&cifs_tcp_ses_lock);
2622 	list_add(&tcon->tcon_list, &ses->tcon_list);
2623 	spin_unlock(&cifs_tcp_ses_lock);
2624 
2625 	return tcon;
2626 
2627 out_fail:
2628 	tconInfoFree(tcon);
2629 	return ERR_PTR(rc);
2630 }
2631 
2632 void
cifs_put_tlink(struct tcon_link * tlink)2633 cifs_put_tlink(struct tcon_link *tlink)
2634 {
2635 	if (!tlink || IS_ERR(tlink))
2636 		return;
2637 
2638 	if (!atomic_dec_and_test(&tlink->tl_count) ||
2639 	    test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2640 		tlink->tl_time = jiffies;
2641 		return;
2642 	}
2643 
2644 	if (!IS_ERR(tlink_tcon(tlink)))
2645 		cifs_put_tcon(tlink_tcon(tlink));
2646 	kfree(tlink);
2647 	return;
2648 }
2649 
2650 static int
compare_mount_options(struct super_block * sb,struct cifs_mnt_data * mnt_data)2651 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2652 {
2653 	struct cifs_sb_info *old = CIFS_SB(sb);
2654 	struct cifs_sb_info *new = mnt_data->cifs_sb;
2655 	unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2656 	unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2657 
2658 	if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2659 		return 0;
2660 
2661 	if (old->mnt_cifs_serverino_autodisabled)
2662 		newflags &= ~CIFS_MOUNT_SERVER_INUM;
2663 
2664 	if (oldflags != newflags)
2665 		return 0;
2666 
2667 	/*
2668 	 * We want to share sb only if we don't specify an r/wsize or
2669 	 * specified r/wsize is greater than or equal to existing one.
2670 	 */
2671 	if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2672 		return 0;
2673 
2674 	if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2675 		return 0;
2676 
2677 	if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2678 	    !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2679 		return 0;
2680 
2681 	if (old->ctx->file_mode != new->ctx->file_mode ||
2682 	    old->ctx->dir_mode != new->ctx->dir_mode)
2683 		return 0;
2684 
2685 	if (strcmp(old->local_nls->charset, new->local_nls->charset))
2686 		return 0;
2687 
2688 	if (old->ctx->acregmax != new->ctx->acregmax)
2689 		return 0;
2690 	if (old->ctx->acdirmax != new->ctx->acdirmax)
2691 		return 0;
2692 	if (old->ctx->closetimeo != new->ctx->closetimeo)
2693 		return 0;
2694 
2695 	return 1;
2696 }
2697 
2698 static int
match_prepath(struct super_block * sb,struct cifs_mnt_data * mnt_data)2699 match_prepath(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2700 {
2701 	struct cifs_sb_info *old = CIFS_SB(sb);
2702 	struct cifs_sb_info *new = mnt_data->cifs_sb;
2703 	bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2704 		old->prepath;
2705 	bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2706 		new->prepath;
2707 
2708 	if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2709 		return 1;
2710 	else if (!old_set && !new_set)
2711 		return 1;
2712 
2713 	return 0;
2714 }
2715 
2716 int
cifs_match_super(struct super_block * sb,void * data)2717 cifs_match_super(struct super_block *sb, void *data)
2718 {
2719 	struct cifs_mnt_data *mnt_data = data;
2720 	struct smb3_fs_context *ctx;
2721 	struct cifs_sb_info *cifs_sb;
2722 	struct TCP_Server_Info *tcp_srv;
2723 	struct cifs_ses *ses;
2724 	struct cifs_tcon *tcon;
2725 	struct tcon_link *tlink;
2726 	int rc = 0;
2727 
2728 	spin_lock(&cifs_tcp_ses_lock);
2729 	cifs_sb = CIFS_SB(sb);
2730 	tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2731 	if (tlink == NULL) {
2732 		/* can not match superblock if tlink were ever null */
2733 		spin_unlock(&cifs_tcp_ses_lock);
2734 		return 0;
2735 	}
2736 	tcon = tlink_tcon(tlink);
2737 	ses = tcon->ses;
2738 	tcp_srv = ses->server;
2739 
2740 	ctx = mnt_data->ctx;
2741 
2742 	spin_lock(&tcp_srv->srv_lock);
2743 	spin_lock(&ses->ses_lock);
2744 	spin_lock(&tcon->tc_lock);
2745 	if (!match_server(tcp_srv, ctx) ||
2746 	    !match_session(ses, ctx) ||
2747 	    !match_tcon(tcon, ctx) ||
2748 	    !match_prepath(sb, mnt_data)) {
2749 		rc = 0;
2750 		goto out;
2751 	}
2752 
2753 	rc = compare_mount_options(sb, mnt_data);
2754 out:
2755 	spin_unlock(&tcon->tc_lock);
2756 	spin_unlock(&ses->ses_lock);
2757 	spin_unlock(&tcp_srv->srv_lock);
2758 
2759 	spin_unlock(&cifs_tcp_ses_lock);
2760 	cifs_put_tlink(tlink);
2761 	return rc;
2762 }
2763 
2764 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2765 static struct lock_class_key cifs_key[2];
2766 static struct lock_class_key cifs_slock_key[2];
2767 
2768 static inline void
cifs_reclassify_socket4(struct socket * sock)2769 cifs_reclassify_socket4(struct socket *sock)
2770 {
2771 	struct sock *sk = sock->sk;
2772 	BUG_ON(!sock_allow_reclassification(sk));
2773 	sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2774 		&cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2775 }
2776 
2777 static inline void
cifs_reclassify_socket6(struct socket * sock)2778 cifs_reclassify_socket6(struct socket *sock)
2779 {
2780 	struct sock *sk = sock->sk;
2781 	BUG_ON(!sock_allow_reclassification(sk));
2782 	sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2783 		&cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2784 }
2785 #else
2786 static inline void
cifs_reclassify_socket4(struct socket * sock)2787 cifs_reclassify_socket4(struct socket *sock)
2788 {
2789 }
2790 
2791 static inline void
cifs_reclassify_socket6(struct socket * sock)2792 cifs_reclassify_socket6(struct socket *sock)
2793 {
2794 }
2795 #endif
2796 
2797 /* See RFC1001 section 14 on representation of Netbios names */
rfc1002mangle(char * target,char * source,unsigned int length)2798 static void rfc1002mangle(char *target, char *source, unsigned int length)
2799 {
2800 	unsigned int i, j;
2801 
2802 	for (i = 0, j = 0; i < (length); i++) {
2803 		/* mask a nibble at a time and encode */
2804 		target[j] = 'A' + (0x0F & (source[i] >> 4));
2805 		target[j+1] = 'A' + (0x0F & source[i]);
2806 		j += 2;
2807 	}
2808 
2809 }
2810 
2811 static int
bind_socket(struct TCP_Server_Info * server)2812 bind_socket(struct TCP_Server_Info *server)
2813 {
2814 	int rc = 0;
2815 	if (server->srcaddr.ss_family != AF_UNSPEC) {
2816 		/* Bind to the specified local IP address */
2817 		struct socket *socket = server->ssocket;
2818 		rc = socket->ops->bind(socket,
2819 				       (struct sockaddr *) &server->srcaddr,
2820 				       sizeof(server->srcaddr));
2821 		if (rc < 0) {
2822 			struct sockaddr_in *saddr4;
2823 			struct sockaddr_in6 *saddr6;
2824 			saddr4 = (struct sockaddr_in *)&server->srcaddr;
2825 			saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
2826 			if (saddr6->sin6_family == AF_INET6)
2827 				cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
2828 					 &saddr6->sin6_addr, rc);
2829 			else
2830 				cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
2831 					 &saddr4->sin_addr.s_addr, rc);
2832 		}
2833 	}
2834 	return rc;
2835 }
2836 
2837 static int
ip_rfc1001_connect(struct TCP_Server_Info * server)2838 ip_rfc1001_connect(struct TCP_Server_Info *server)
2839 {
2840 	int rc = 0;
2841 	/*
2842 	 * some servers require RFC1001 sessinit before sending
2843 	 * negprot - BB check reconnection in case where second
2844 	 * sessinit is sent but no second negprot
2845 	 */
2846 	struct rfc1002_session_packet *ses_init_buf;
2847 	unsigned int req_noscope_len;
2848 	struct smb_hdr *smb_buf;
2849 
2850 	ses_init_buf = kzalloc(sizeof(struct rfc1002_session_packet),
2851 			       GFP_KERNEL);
2852 
2853 	if (ses_init_buf) {
2854 		ses_init_buf->trailer.session_req.called_len = 32;
2855 
2856 		if (server->server_RFC1001_name[0] != 0)
2857 			rfc1002mangle(ses_init_buf->trailer.
2858 				      session_req.called_name,
2859 				      server->server_RFC1001_name,
2860 				      RFC1001_NAME_LEN_WITH_NULL);
2861 		else
2862 			rfc1002mangle(ses_init_buf->trailer.
2863 				      session_req.called_name,
2864 				      DEFAULT_CIFS_CALLED_NAME,
2865 				      RFC1001_NAME_LEN_WITH_NULL);
2866 
2867 		ses_init_buf->trailer.session_req.calling_len = 32;
2868 
2869 		/*
2870 		 * calling name ends in null (byte 16) from old smb
2871 		 * convention.
2872 		 */
2873 		if (server->workstation_RFC1001_name[0] != 0)
2874 			rfc1002mangle(ses_init_buf->trailer.
2875 				      session_req.calling_name,
2876 				      server->workstation_RFC1001_name,
2877 				      RFC1001_NAME_LEN_WITH_NULL);
2878 		else
2879 			rfc1002mangle(ses_init_buf->trailer.
2880 				      session_req.calling_name,
2881 				      "LINUX_CIFS_CLNT",
2882 				      RFC1001_NAME_LEN_WITH_NULL);
2883 
2884 		ses_init_buf->trailer.session_req.scope1 = 0;
2885 		ses_init_buf->trailer.session_req.scope2 = 0;
2886 		smb_buf = (struct smb_hdr *)ses_init_buf;
2887 
2888 		/* sizeof RFC1002_SESSION_REQUEST with no scopes */
2889 		req_noscope_len = sizeof(struct rfc1002_session_packet) - 2;
2890 
2891 		/* == cpu_to_be32(0x81000044) */
2892 		smb_buf->smb_buf_length =
2893 			cpu_to_be32((RFC1002_SESSION_REQUEST << 24) | req_noscope_len);
2894 		rc = smb_send(server, smb_buf, 0x44);
2895 		kfree(ses_init_buf);
2896 		/*
2897 		 * RFC1001 layer in at least one server
2898 		 * requires very short break before negprot
2899 		 * presumably because not expecting negprot
2900 		 * to follow so fast.  This is a simple
2901 		 * solution that works without
2902 		 * complicating the code and causes no
2903 		 * significant slowing down on mount
2904 		 * for everyone else
2905 		 */
2906 		usleep_range(1000, 2000);
2907 	}
2908 	/*
2909 	 * else the negprot may still work without this
2910 	 * even though malloc failed
2911 	 */
2912 
2913 	return rc;
2914 }
2915 
2916 static int
generic_ip_connect(struct TCP_Server_Info * server)2917 generic_ip_connect(struct TCP_Server_Info *server)
2918 {
2919 	int rc = 0;
2920 	__be16 sport;
2921 	int slen, sfamily;
2922 	struct socket *socket = server->ssocket;
2923 	struct sockaddr *saddr;
2924 
2925 	saddr = (struct sockaddr *) &server->dstaddr;
2926 
2927 	if (server->dstaddr.ss_family == AF_INET6) {
2928 		struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
2929 
2930 		sport = ipv6->sin6_port;
2931 		slen = sizeof(struct sockaddr_in6);
2932 		sfamily = AF_INET6;
2933 		cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
2934 				ntohs(sport));
2935 	} else {
2936 		struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
2937 
2938 		sport = ipv4->sin_port;
2939 		slen = sizeof(struct sockaddr_in);
2940 		sfamily = AF_INET;
2941 		cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
2942 				ntohs(sport));
2943 	}
2944 
2945 	if (socket == NULL) {
2946 		rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
2947 				   IPPROTO_TCP, &socket, 1);
2948 		if (rc < 0) {
2949 			cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
2950 			server->ssocket = NULL;
2951 			return rc;
2952 		}
2953 
2954 		/* BB other socket options to set KEEPALIVE, NODELAY? */
2955 		cifs_dbg(FYI, "Socket created\n");
2956 		server->ssocket = socket;
2957 		socket->sk->sk_allocation = GFP_NOFS;
2958 		if (sfamily == AF_INET6)
2959 			cifs_reclassify_socket6(socket);
2960 		else
2961 			cifs_reclassify_socket4(socket);
2962 	}
2963 
2964 	rc = bind_socket(server);
2965 	if (rc < 0)
2966 		return rc;
2967 
2968 	/*
2969 	 * Eventually check for other socket options to change from
2970 	 * the default. sock_setsockopt not used because it expects
2971 	 * user space buffer
2972 	 */
2973 	socket->sk->sk_rcvtimeo = 7 * HZ;
2974 	socket->sk->sk_sndtimeo = 5 * HZ;
2975 
2976 	/* make the bufsizes depend on wsize/rsize and max requests */
2977 	if (server->noautotune) {
2978 		if (socket->sk->sk_sndbuf < (200 * 1024))
2979 			socket->sk->sk_sndbuf = 200 * 1024;
2980 		if (socket->sk->sk_rcvbuf < (140 * 1024))
2981 			socket->sk->sk_rcvbuf = 140 * 1024;
2982 	}
2983 
2984 	if (server->tcp_nodelay)
2985 		tcp_sock_set_nodelay(socket->sk);
2986 
2987 	cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
2988 		 socket->sk->sk_sndbuf,
2989 		 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
2990 
2991 	rc = socket->ops->connect(socket, saddr, slen,
2992 				  server->noblockcnt ? O_NONBLOCK : 0);
2993 	/*
2994 	 * When mounting SMB root file systems, we do not want to block in
2995 	 * connect. Otherwise bail out and then let cifs_reconnect() perform
2996 	 * reconnect failover - if possible.
2997 	 */
2998 	if (server->noblockcnt && rc == -EINPROGRESS)
2999 		rc = 0;
3000 	if (rc < 0) {
3001 		cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3002 		trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
3003 		sock_release(socket);
3004 		server->ssocket = NULL;
3005 		return rc;
3006 	}
3007 	trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
3008 	if (sport == htons(RFC1001_PORT))
3009 		rc = ip_rfc1001_connect(server);
3010 
3011 	return rc;
3012 }
3013 
3014 static int
ip_connect(struct TCP_Server_Info * server)3015 ip_connect(struct TCP_Server_Info *server)
3016 {
3017 	__be16 *sport;
3018 	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3019 	struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3020 
3021 	if (server->dstaddr.ss_family == AF_INET6)
3022 		sport = &addr6->sin6_port;
3023 	else
3024 		sport = &addr->sin_port;
3025 
3026 	if (*sport == 0) {
3027 		int rc;
3028 
3029 		/* try with 445 port at first */
3030 		*sport = htons(CIFS_PORT);
3031 
3032 		rc = generic_ip_connect(server);
3033 		if (rc >= 0)
3034 			return rc;
3035 
3036 		/* if it failed, try with 139 port */
3037 		*sport = htons(RFC1001_PORT);
3038 	}
3039 
3040 	return generic_ip_connect(server);
3041 }
3042 
3043 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
reset_cifs_unix_caps(unsigned int xid,struct cifs_tcon * tcon,struct cifs_sb_info * cifs_sb,struct smb3_fs_context * ctx)3044 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3045 			  struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3046 {
3047 	/*
3048 	 * If we are reconnecting then should we check to see if
3049 	 * any requested capabilities changed locally e.g. via
3050 	 * remount but we can not do much about it here
3051 	 * if they have (even if we could detect it by the following)
3052 	 * Perhaps we could add a backpointer to array of sb from tcon
3053 	 * or if we change to make all sb to same share the same
3054 	 * sb as NFS - then we only have one backpointer to sb.
3055 	 * What if we wanted to mount the server share twice once with
3056 	 * and once without posixacls or posix paths?
3057 	 */
3058 	__u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3059 
3060 	if (ctx && ctx->no_linux_ext) {
3061 		tcon->fsUnixInfo.Capability = 0;
3062 		tcon->unix_ext = 0; /* Unix Extensions disabled */
3063 		cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3064 		return;
3065 	} else if (ctx)
3066 		tcon->unix_ext = 1; /* Unix Extensions supported */
3067 
3068 	if (!tcon->unix_ext) {
3069 		cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3070 		return;
3071 	}
3072 
3073 	if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3074 		__u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3075 		cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3076 		/*
3077 		 * check for reconnect case in which we do not
3078 		 * want to change the mount behavior if we can avoid it
3079 		 */
3080 		if (ctx == NULL) {
3081 			/*
3082 			 * turn off POSIX ACL and PATHNAMES if not set
3083 			 * originally at mount time
3084 			 */
3085 			if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3086 				cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3087 			if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3088 				if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3089 					cifs_dbg(VFS, "POSIXPATH support change\n");
3090 				cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3091 			} else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3092 				cifs_dbg(VFS, "possible reconnect error\n");
3093 				cifs_dbg(VFS, "server disabled POSIX path support\n");
3094 			}
3095 		}
3096 
3097 		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3098 			cifs_dbg(VFS, "per-share encryption not supported yet\n");
3099 
3100 		cap &= CIFS_UNIX_CAP_MASK;
3101 		if (ctx && ctx->no_psx_acl)
3102 			cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3103 		else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3104 			cifs_dbg(FYI, "negotiated posix acl support\n");
3105 			if (cifs_sb)
3106 				cifs_sb->mnt_cifs_flags |=
3107 					CIFS_MOUNT_POSIXACL;
3108 		}
3109 
3110 		if (ctx && ctx->posix_paths == 0)
3111 			cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3112 		else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3113 			cifs_dbg(FYI, "negotiate posix pathnames\n");
3114 			if (cifs_sb)
3115 				cifs_sb->mnt_cifs_flags |=
3116 					CIFS_MOUNT_POSIX_PATHS;
3117 		}
3118 
3119 		cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3120 #ifdef CONFIG_CIFS_DEBUG2
3121 		if (cap & CIFS_UNIX_FCNTL_CAP)
3122 			cifs_dbg(FYI, "FCNTL cap\n");
3123 		if (cap & CIFS_UNIX_EXTATTR_CAP)
3124 			cifs_dbg(FYI, "EXTATTR cap\n");
3125 		if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3126 			cifs_dbg(FYI, "POSIX path cap\n");
3127 		if (cap & CIFS_UNIX_XATTR_CAP)
3128 			cifs_dbg(FYI, "XATTR cap\n");
3129 		if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3130 			cifs_dbg(FYI, "POSIX ACL cap\n");
3131 		if (cap & CIFS_UNIX_LARGE_READ_CAP)
3132 			cifs_dbg(FYI, "very large read cap\n");
3133 		if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3134 			cifs_dbg(FYI, "very large write cap\n");
3135 		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3136 			cifs_dbg(FYI, "transport encryption cap\n");
3137 		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3138 			cifs_dbg(FYI, "mandatory transport encryption cap\n");
3139 #endif /* CIFS_DEBUG2 */
3140 		if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3141 			if (ctx == NULL)
3142 				cifs_dbg(FYI, "resetting capabilities failed\n");
3143 			else
3144 				cifs_dbg(VFS, "Negotiating Unix capabilities with the server failed. Consider mounting with the Unix Extensions disabled if problems are found by specifying the nounix mount option.\n");
3145 
3146 		}
3147 	}
3148 }
3149 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3150 
cifs_setup_cifs_sb(struct cifs_sb_info * cifs_sb)3151 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
3152 {
3153 	struct smb3_fs_context *ctx = cifs_sb->ctx;
3154 
3155 	INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3156 
3157 	spin_lock_init(&cifs_sb->tlink_tree_lock);
3158 	cifs_sb->tlink_tree = RB_ROOT;
3159 
3160 	cifs_dbg(FYI, "file mode: %04ho  dir mode: %04ho\n",
3161 		 ctx->file_mode, ctx->dir_mode);
3162 
3163 	/* this is needed for ASCII cp to Unicode converts */
3164 	if (ctx->iocharset == NULL) {
3165 		/* load_nls_default cannot return null */
3166 		cifs_sb->local_nls = load_nls_default();
3167 	} else {
3168 		cifs_sb->local_nls = load_nls(ctx->iocharset);
3169 		if (cifs_sb->local_nls == NULL) {
3170 			cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3171 				 ctx->iocharset);
3172 			return -ELIBACC;
3173 		}
3174 	}
3175 	ctx->local_nls = cifs_sb->local_nls;
3176 
3177 	smb3_update_mnt_flags(cifs_sb);
3178 
3179 	if (ctx->direct_io)
3180 		cifs_dbg(FYI, "mounting share using direct i/o\n");
3181 	if (ctx->cache_ro) {
3182 		cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
3183 		cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
3184 	} else if (ctx->cache_rw) {
3185 		cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
3186 		cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
3187 					    CIFS_MOUNT_RW_CACHE);
3188 	}
3189 
3190 	if ((ctx->cifs_acl) && (ctx->dynperm))
3191 		cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3192 
3193 	if (ctx->prepath) {
3194 		cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
3195 		if (cifs_sb->prepath == NULL)
3196 			return -ENOMEM;
3197 		cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3198 	}
3199 
3200 	return 0;
3201 }
3202 
3203 /* Release all succeed connections */
mount_put_conns(struct mount_ctx * mnt_ctx)3204 static inline void mount_put_conns(struct mount_ctx *mnt_ctx)
3205 {
3206 	int rc = 0;
3207 
3208 	if (mnt_ctx->tcon)
3209 		cifs_put_tcon(mnt_ctx->tcon);
3210 	else if (mnt_ctx->ses)
3211 		cifs_put_smb_ses(mnt_ctx->ses);
3212 	else if (mnt_ctx->server)
3213 		cifs_put_tcp_session(mnt_ctx->server, 0);
3214 	mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3215 	free_xid(mnt_ctx->xid);
3216 }
3217 
3218 /* Get connections for tcp, ses and tcon */
mount_get_conns(struct mount_ctx * mnt_ctx)3219 static int mount_get_conns(struct mount_ctx *mnt_ctx)
3220 {
3221 	int rc = 0;
3222 	struct TCP_Server_Info *server = NULL;
3223 	struct cifs_ses *ses = NULL;
3224 	struct cifs_tcon *tcon = NULL;
3225 	struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3226 	struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3227 	unsigned int xid;
3228 
3229 	xid = get_xid();
3230 
3231 	/* get a reference to a tcp session */
3232 	server = cifs_get_tcp_session(ctx, NULL);
3233 	if (IS_ERR(server)) {
3234 		rc = PTR_ERR(server);
3235 		server = NULL;
3236 		goto out;
3237 	}
3238 
3239 	/* get a reference to a SMB session */
3240 	ses = cifs_get_smb_ses(server, ctx);
3241 	if (IS_ERR(ses)) {
3242 		rc = PTR_ERR(ses);
3243 		ses = NULL;
3244 		goto out;
3245 	}
3246 
3247 	if ((ctx->persistent == true) && (!(ses->server->capabilities &
3248 					    SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
3249 		cifs_server_dbg(VFS, "persistent handles not supported by server\n");
3250 		rc = -EOPNOTSUPP;
3251 		goto out;
3252 	}
3253 
3254 	/* search for existing tcon to this server share */
3255 	tcon = cifs_get_tcon(ses, ctx);
3256 	if (IS_ERR(tcon)) {
3257 		rc = PTR_ERR(tcon);
3258 		tcon = NULL;
3259 		goto out;
3260 	}
3261 
3262 	/* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
3263 	if (tcon->posix_extensions)
3264 		cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3265 
3266 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3267 	/* tell server which Unix caps we support */
3268 	if (cap_unix(tcon->ses)) {
3269 		/*
3270 		 * reset of caps checks mount to see if unix extensions disabled
3271 		 * for just this mount.
3272 		 */
3273 		reset_cifs_unix_caps(xid, tcon, cifs_sb, ctx);
3274 		spin_lock(&tcon->ses->server->srv_lock);
3275 		if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3276 		    (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3277 		     CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3278 			spin_unlock(&tcon->ses->server->srv_lock);
3279 			rc = -EACCES;
3280 			goto out;
3281 		}
3282 		spin_unlock(&tcon->ses->server->srv_lock);
3283 	} else
3284 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3285 		tcon->unix_ext = 0; /* server does not support them */
3286 
3287 	/* do not care if a following call succeed - informational */
3288 	if (!tcon->pipe && server->ops->qfs_tcon) {
3289 		server->ops->qfs_tcon(xid, tcon, cifs_sb);
3290 		if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3291 			if (tcon->fsDevInfo.DeviceCharacteristics &
3292 			    cpu_to_le32(FILE_READ_ONLY_DEVICE))
3293 				cifs_dbg(VFS, "mounted to read only share\n");
3294 			else if ((cifs_sb->mnt_cifs_flags &
3295 				  CIFS_MOUNT_RW_CACHE) == 0)
3296 				cifs_dbg(VFS, "read only mount of RW share\n");
3297 			/* no need to log a RW mount of a typical RW share */
3298 		}
3299 	}
3300 
3301 	/*
3302 	 * Clamp the rsize/wsize mount arguments if they are too big for the server
3303 	 * and set the rsize/wsize to the negotiated values if not passed in by
3304 	 * the user on mount
3305 	 */
3306 	if ((cifs_sb->ctx->wsize == 0) ||
3307 	    (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx)))
3308 		cifs_sb->ctx->wsize = server->ops->negotiate_wsize(tcon, ctx);
3309 	if ((cifs_sb->ctx->rsize == 0) ||
3310 	    (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3311 		cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3312 
3313 	/*
3314 	 * The cookie is initialized from volume info returned above.
3315 	 * Inside cifs_fscache_get_super_cookie it checks
3316 	 * that we do not get super cookie twice.
3317 	 */
3318 	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE)
3319 		cifs_fscache_get_super_cookie(tcon);
3320 
3321 out:
3322 	mnt_ctx->server = server;
3323 	mnt_ctx->ses = ses;
3324 	mnt_ctx->tcon = tcon;
3325 	mnt_ctx->xid = xid;
3326 
3327 	return rc;
3328 }
3329 
mount_setup_tlink(struct cifs_sb_info * cifs_sb,struct cifs_ses * ses,struct cifs_tcon * tcon)3330 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3331 			     struct cifs_tcon *tcon)
3332 {
3333 	struct tcon_link *tlink;
3334 
3335 	/* hang the tcon off of the superblock */
3336 	tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3337 	if (tlink == NULL)
3338 		return -ENOMEM;
3339 
3340 	tlink->tl_uid = ses->linux_uid;
3341 	tlink->tl_tcon = tcon;
3342 	tlink->tl_time = jiffies;
3343 	set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3344 	set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3345 
3346 	cifs_sb->master_tlink = tlink;
3347 	spin_lock(&cifs_sb->tlink_tree_lock);
3348 	tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3349 	spin_unlock(&cifs_sb->tlink_tree_lock);
3350 
3351 	queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3352 				TLINK_IDLE_EXPIRE);
3353 	return 0;
3354 }
3355 
3356 #ifdef CONFIG_CIFS_DFS_UPCALL
3357 /* Get unique dfs connections */
mount_get_dfs_conns(struct mount_ctx * mnt_ctx)3358 static int mount_get_dfs_conns(struct mount_ctx *mnt_ctx)
3359 {
3360 	int rc;
3361 
3362 	mnt_ctx->fs_ctx->nosharesock = true;
3363 	rc = mount_get_conns(mnt_ctx);
3364 	if (mnt_ctx->server) {
3365 		cifs_dbg(FYI, "%s: marking tcp session as a dfs connection\n", __func__);
3366 		spin_lock(&mnt_ctx->server->srv_lock);
3367 		mnt_ctx->server->is_dfs_conn = true;
3368 		spin_unlock(&mnt_ctx->server->srv_lock);
3369 	}
3370 	return rc;
3371 }
3372 
3373 /*
3374  * cifs_build_path_to_root returns full path to root when we do not have an
3375  * existing connection (tcon)
3376  */
3377 static char *
build_unc_path_to_root(const struct smb3_fs_context * ctx,const struct cifs_sb_info * cifs_sb,bool useppath)3378 build_unc_path_to_root(const struct smb3_fs_context *ctx,
3379 		       const struct cifs_sb_info *cifs_sb, bool useppath)
3380 {
3381 	char *full_path, *pos;
3382 	unsigned int pplen = useppath && ctx->prepath ?
3383 		strlen(ctx->prepath) + 1 : 0;
3384 	unsigned int unc_len = strnlen(ctx->UNC, MAX_TREE_SIZE + 1);
3385 
3386 	if (unc_len > MAX_TREE_SIZE)
3387 		return ERR_PTR(-EINVAL);
3388 
3389 	full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL);
3390 	if (full_path == NULL)
3391 		return ERR_PTR(-ENOMEM);
3392 
3393 	memcpy(full_path, ctx->UNC, unc_len);
3394 	pos = full_path + unc_len;
3395 
3396 	if (pplen) {
3397 		*pos = CIFS_DIR_SEP(cifs_sb);
3398 		memcpy(pos + 1, ctx->prepath, pplen);
3399 		pos += pplen;
3400 	}
3401 
3402 	*pos = '\0'; /* add trailing null */
3403 	convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb));
3404 	cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path);
3405 	return full_path;
3406 }
3407 
3408 /*
3409  * expand_dfs_referral - Update cifs_sb from dfs referral path
3410  *
3411  * cifs_sb->ctx->mount_options will be (re-)allocated to a string containing updated options for the
3412  * submount.  Otherwise it will be left untouched.
3413  */
expand_dfs_referral(struct mount_ctx * mnt_ctx,const char * full_path,struct dfs_info3_param * referral)3414 static int expand_dfs_referral(struct mount_ctx *mnt_ctx, const char *full_path,
3415 			       struct dfs_info3_param *referral)
3416 {
3417 	int rc;
3418 	struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3419 	struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3420 	char *fake_devname = NULL, *mdata = NULL;
3421 
3422 	mdata = cifs_compose_mount_options(cifs_sb->ctx->mount_options, full_path + 1, referral,
3423 					   &fake_devname);
3424 	if (IS_ERR(mdata)) {
3425 		rc = PTR_ERR(mdata);
3426 		mdata = NULL;
3427 	} else {
3428 		/*
3429 		 * We can not clear out the whole structure since we no longer have an explicit
3430 		 * function to parse a mount-string. Instead we need to clear out the individual
3431 		 * fields that are no longer valid.
3432 		 */
3433 		kfree(ctx->prepath);
3434 		ctx->prepath = NULL;
3435 		rc = cifs_setup_volume_info(ctx, mdata, fake_devname);
3436 	}
3437 	kfree(fake_devname);
3438 	kfree(cifs_sb->ctx->mount_options);
3439 	cifs_sb->ctx->mount_options = mdata;
3440 
3441 	return rc;
3442 }
3443 #endif
3444 
3445 /* TODO: all callers to this are broken. We are not parsing mount_options here
3446  * we should pass a clone of the original context?
3447  */
3448 int
cifs_setup_volume_info(struct smb3_fs_context * ctx,const char * mntopts,const char * devname)3449 cifs_setup_volume_info(struct smb3_fs_context *ctx, const char *mntopts, const char *devname)
3450 {
3451 	int rc;
3452 
3453 	if (devname) {
3454 		cifs_dbg(FYI, "%s: devname=%s\n", __func__, devname);
3455 		rc = smb3_parse_devname(devname, ctx);
3456 		if (rc) {
3457 			cifs_dbg(VFS, "%s: failed to parse %s: %d\n", __func__, devname, rc);
3458 			return rc;
3459 		}
3460 	}
3461 
3462 	if (mntopts) {
3463 		char *ip;
3464 
3465 		rc = smb3_parse_opt(mntopts, "ip", &ip);
3466 		if (rc) {
3467 			cifs_dbg(VFS, "%s: failed to parse ip options: %d\n", __func__, rc);
3468 			return rc;
3469 		}
3470 
3471 		rc = cifs_convert_address((struct sockaddr *)&ctx->dstaddr, ip, strlen(ip));
3472 		kfree(ip);
3473 		if (!rc) {
3474 			cifs_dbg(VFS, "%s: failed to convert ip address\n", __func__);
3475 			return -EINVAL;
3476 		}
3477 	}
3478 
3479 	if (ctx->nullauth) {
3480 		cifs_dbg(FYI, "Anonymous login\n");
3481 		kfree(ctx->username);
3482 		ctx->username = NULL;
3483 	} else if (ctx->username) {
3484 		/* BB fixme parse for domain name here */
3485 		cifs_dbg(FYI, "Username: %s\n", ctx->username);
3486 	} else {
3487 		cifs_dbg(VFS, "No username specified\n");
3488 	/* In userspace mount helper we can get user name from alternate
3489 	   locations such as env variables and files on disk */
3490 		return -EINVAL;
3491 	}
3492 
3493 	return 0;
3494 }
3495 
3496 static int
cifs_are_all_path_components_accessible(struct TCP_Server_Info * server,unsigned int xid,struct cifs_tcon * tcon,struct cifs_sb_info * cifs_sb,char * full_path,int added_treename)3497 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3498 					unsigned int xid,
3499 					struct cifs_tcon *tcon,
3500 					struct cifs_sb_info *cifs_sb,
3501 					char *full_path,
3502 					int added_treename)
3503 {
3504 	int rc;
3505 	char *s;
3506 	char sep, tmp;
3507 	int skip = added_treename ? 1 : 0;
3508 
3509 	sep = CIFS_DIR_SEP(cifs_sb);
3510 	s = full_path;
3511 
3512 	rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3513 	while (rc == 0) {
3514 		/* skip separators */
3515 		while (*s == sep)
3516 			s++;
3517 		if (!*s)
3518 			break;
3519 		/* next separator */
3520 		while (*s && *s != sep)
3521 			s++;
3522 		/*
3523 		 * if the treename is added, we then have to skip the first
3524 		 * part within the separators
3525 		 */
3526 		if (skip) {
3527 			skip = 0;
3528 			continue;
3529 		}
3530 		/*
3531 		 * temporarily null-terminate the path at the end of
3532 		 * the current component
3533 		 */
3534 		tmp = *s;
3535 		*s = 0;
3536 		rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3537 						     full_path);
3538 		*s = tmp;
3539 	}
3540 	return rc;
3541 }
3542 
3543 /*
3544  * Check if path is remote (i.e. a DFS share).
3545  *
3546  * Return -EREMOTE if it is, otherwise 0 or -errno.
3547  */
is_path_remote(struct mount_ctx * mnt_ctx)3548 static int is_path_remote(struct mount_ctx *mnt_ctx)
3549 {
3550 	int rc;
3551 	struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3552 	struct TCP_Server_Info *server = mnt_ctx->server;
3553 	unsigned int xid = mnt_ctx->xid;
3554 	struct cifs_tcon *tcon = mnt_ctx->tcon;
3555 	struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3556 	char *full_path;
3557 
3558 	if (!server->ops->is_path_accessible)
3559 		return -EOPNOTSUPP;
3560 
3561 	/*
3562 	 * cifs_build_path_to_root works only when we have a valid tcon
3563 	 */
3564 	full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3565 					    tcon->Flags & SMB_SHARE_IS_IN_DFS);
3566 	if (full_path == NULL)
3567 		return -ENOMEM;
3568 
3569 	cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3570 
3571 	rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3572 					     full_path);
3573 	if (rc != 0 && rc != -EREMOTE)
3574 		goto out;
3575 
3576 	if (rc != -EREMOTE) {
3577 		rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3578 			cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3579 		if (rc != 0) {
3580 			cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3581 			cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3582 			rc = 0;
3583 		}
3584 	}
3585 
3586 out:
3587 	kfree(full_path);
3588 	return rc;
3589 }
3590 
3591 #ifdef CONFIG_CIFS_DFS_UPCALL
set_root_ses(struct mount_ctx * mnt_ctx)3592 static void set_root_ses(struct mount_ctx *mnt_ctx)
3593 {
3594 	if (mnt_ctx->ses) {
3595 		spin_lock(&cifs_tcp_ses_lock);
3596 		mnt_ctx->ses->ses_count++;
3597 		spin_unlock(&cifs_tcp_ses_lock);
3598 		dfs_cache_add_refsrv_session(&mnt_ctx->mount_id, mnt_ctx->ses);
3599 	}
3600 	mnt_ctx->root_ses = mnt_ctx->ses;
3601 }
3602 
is_dfs_mount(struct mount_ctx * mnt_ctx,bool * isdfs,struct dfs_cache_tgt_list * root_tl)3603 static int is_dfs_mount(struct mount_ctx *mnt_ctx, bool *isdfs, struct dfs_cache_tgt_list *root_tl)
3604 {
3605 	int rc;
3606 	struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3607 	struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3608 
3609 	*isdfs = true;
3610 
3611 	rc = mount_get_conns(mnt_ctx);
3612 	/*
3613 	 * If called with 'nodfs' mount option, then skip DFS resolving.  Otherwise unconditionally
3614 	 * try to get an DFS referral (even cached) to determine whether it is an DFS mount.
3615 	 *
3616 	 * Skip prefix path to provide support for DFS referrals from w2k8 servers which don't seem
3617 	 * to respond with PATH_NOT_COVERED to requests that include the prefix.
3618 	 */
3619 	if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
3620 	    dfs_cache_find(mnt_ctx->xid, mnt_ctx->ses, cifs_sb->local_nls, cifs_remap(cifs_sb),
3621 			   ctx->UNC + 1, NULL, root_tl)) {
3622 		if (rc)
3623 			return rc;
3624 		/* Check if it is fully accessible and then mount it */
3625 		rc = is_path_remote(mnt_ctx);
3626 		if (!rc)
3627 			*isdfs = false;
3628 		else if (rc != -EREMOTE)
3629 			return rc;
3630 	}
3631 	return 0;
3632 }
3633 
connect_dfs_target(struct mount_ctx * mnt_ctx,const char * full_path,const char * ref_path,struct dfs_cache_tgt_iterator * tit)3634 static int connect_dfs_target(struct mount_ctx *mnt_ctx, const char *full_path,
3635 			      const char *ref_path, struct dfs_cache_tgt_iterator *tit)
3636 {
3637 	int rc;
3638 	struct dfs_info3_param ref = {};
3639 	struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3640 	char *oldmnt = cifs_sb->ctx->mount_options;
3641 
3642 	cifs_dbg(FYI, "%s: full_path=%s ref_path=%s target=%s\n", __func__, full_path, ref_path,
3643 		 dfs_cache_get_tgt_name(tit));
3644 
3645 	rc = dfs_cache_get_tgt_referral(ref_path, tit, &ref);
3646 	if (rc)
3647 		goto out;
3648 
3649 	rc = expand_dfs_referral(mnt_ctx, full_path, &ref);
3650 	if (rc)
3651 		goto out;
3652 
3653 	/* Connect to new target only if we were redirected (e.g. mount options changed) */
3654 	if (oldmnt != cifs_sb->ctx->mount_options) {
3655 		mount_put_conns(mnt_ctx);
3656 		rc = mount_get_dfs_conns(mnt_ctx);
3657 	}
3658 	if (!rc) {
3659 		if (cifs_is_referral_server(mnt_ctx->tcon, &ref))
3660 			set_root_ses(mnt_ctx);
3661 		rc = dfs_cache_update_tgthint(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3662 					      cifs_remap(cifs_sb), ref_path, tit);
3663 	}
3664 
3665 out:
3666 	free_dfs_info_param(&ref);
3667 	return rc;
3668 }
3669 
connect_dfs_root(struct mount_ctx * mnt_ctx,struct dfs_cache_tgt_list * root_tl)3670 static int connect_dfs_root(struct mount_ctx *mnt_ctx, struct dfs_cache_tgt_list *root_tl)
3671 {
3672 	int rc;
3673 	char *full_path;
3674 	struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3675 	struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3676 	struct dfs_cache_tgt_iterator *tit;
3677 
3678 	/* Put initial connections as they might be shared with other mounts.  We need unique dfs
3679 	 * connections per mount to properly failover, so mount_get_dfs_conns() must be used from
3680 	 * now on.
3681 	 */
3682 	mount_put_conns(mnt_ctx);
3683 	mount_get_dfs_conns(mnt_ctx);
3684 	set_root_ses(mnt_ctx);
3685 
3686 	full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3687 	if (IS_ERR(full_path))
3688 		return PTR_ERR(full_path);
3689 
3690 	mnt_ctx->origin_fullpath = dfs_cache_canonical_path(ctx->UNC, cifs_sb->local_nls,
3691 							    cifs_remap(cifs_sb));
3692 	if (IS_ERR(mnt_ctx->origin_fullpath)) {
3693 		rc = PTR_ERR(mnt_ctx->origin_fullpath);
3694 		mnt_ctx->origin_fullpath = NULL;
3695 		goto out;
3696 	}
3697 
3698 	/* Try all dfs root targets */
3699 	for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(root_tl);
3700 	     tit; tit = dfs_cache_get_next_tgt(root_tl, tit)) {
3701 		rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->origin_fullpath + 1, tit);
3702 		if (!rc) {
3703 			mnt_ctx->leaf_fullpath = kstrdup(mnt_ctx->origin_fullpath, GFP_KERNEL);
3704 			if (!mnt_ctx->leaf_fullpath)
3705 				rc = -ENOMEM;
3706 			break;
3707 		}
3708 	}
3709 
3710 out:
3711 	kfree(full_path);
3712 	return rc;
3713 }
3714 
__follow_dfs_link(struct mount_ctx * mnt_ctx)3715 static int __follow_dfs_link(struct mount_ctx *mnt_ctx)
3716 {
3717 	int rc;
3718 	struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3719 	struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3720 	char *full_path;
3721 	struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3722 	struct dfs_cache_tgt_iterator *tit;
3723 
3724 	full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3725 	if (IS_ERR(full_path))
3726 		return PTR_ERR(full_path);
3727 
3728 	kfree(mnt_ctx->leaf_fullpath);
3729 	mnt_ctx->leaf_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3730 							  cifs_remap(cifs_sb));
3731 	if (IS_ERR(mnt_ctx->leaf_fullpath)) {
3732 		rc = PTR_ERR(mnt_ctx->leaf_fullpath);
3733 		mnt_ctx->leaf_fullpath = NULL;
3734 		goto out;
3735 	}
3736 
3737 	/* Get referral from dfs link */
3738 	rc = dfs_cache_find(mnt_ctx->xid, mnt_ctx->root_ses, cifs_sb->local_nls,
3739 			    cifs_remap(cifs_sb), mnt_ctx->leaf_fullpath + 1, NULL, &tl);
3740 	if (rc)
3741 		goto out;
3742 
3743 	/* Try all dfs link targets.  If an I/O fails from currently connected DFS target with an
3744 	 * error other than STATUS_PATH_NOT_COVERED (-EREMOTE), then retry it from other targets as
3745 	 * specified in MS-DFSC "3.1.5.2 I/O Operation to Target Fails with an Error Other Than
3746 	 * STATUS_PATH_NOT_COVERED."
3747 	 */
3748 	for (rc = -ENOENT, tit = dfs_cache_get_tgt_iterator(&tl);
3749 	     tit; tit = dfs_cache_get_next_tgt(&tl, tit)) {
3750 		rc = connect_dfs_target(mnt_ctx, full_path, mnt_ctx->leaf_fullpath + 1, tit);
3751 		if (!rc) {
3752 			rc = is_path_remote(mnt_ctx);
3753 			if (!rc || rc == -EREMOTE)
3754 				break;
3755 		}
3756 	}
3757 
3758 out:
3759 	kfree(full_path);
3760 	dfs_cache_free_tgts(&tl);
3761 	return rc;
3762 }
3763 
follow_dfs_link(struct mount_ctx * mnt_ctx)3764 static int follow_dfs_link(struct mount_ctx *mnt_ctx)
3765 {
3766 	int rc;
3767 	struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3768 	struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3769 	char *full_path;
3770 	int num_links = 0;
3771 
3772 	full_path = build_unc_path_to_root(ctx, cifs_sb, true);
3773 	if (IS_ERR(full_path))
3774 		return PTR_ERR(full_path);
3775 
3776 	kfree(mnt_ctx->origin_fullpath);
3777 	mnt_ctx->origin_fullpath = dfs_cache_canonical_path(full_path, cifs_sb->local_nls,
3778 							    cifs_remap(cifs_sb));
3779 	kfree(full_path);
3780 
3781 	if (IS_ERR(mnt_ctx->origin_fullpath)) {
3782 		rc = PTR_ERR(mnt_ctx->origin_fullpath);
3783 		mnt_ctx->origin_fullpath = NULL;
3784 		return rc;
3785 	}
3786 
3787 	do {
3788 		rc = __follow_dfs_link(mnt_ctx);
3789 		if (!rc || rc != -EREMOTE)
3790 			break;
3791 	} while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
3792 
3793 	return rc;
3794 }
3795 
3796 /* Set up DFS referral paths for failover */
setup_server_referral_paths(struct mount_ctx * mnt_ctx)3797 static void setup_server_referral_paths(struct mount_ctx *mnt_ctx)
3798 {
3799 	struct TCP_Server_Info *server = mnt_ctx->server;
3800 
3801 	mutex_lock(&server->refpath_lock);
3802 	server->origin_fullpath = mnt_ctx->origin_fullpath;
3803 	server->leaf_fullpath = mnt_ctx->leaf_fullpath;
3804 	server->current_fullpath = mnt_ctx->leaf_fullpath;
3805 	mutex_unlock(&server->refpath_lock);
3806 	mnt_ctx->origin_fullpath = mnt_ctx->leaf_fullpath = NULL;
3807 }
3808 
cifs_mount(struct cifs_sb_info * cifs_sb,struct smb3_fs_context * ctx)3809 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3810 {
3811 	int rc;
3812 	struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3813 	struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
3814 	bool isdfs;
3815 
3816 	rc = is_dfs_mount(&mnt_ctx, &isdfs, &tl);
3817 	if (rc)
3818 		goto error;
3819 	if (!isdfs)
3820 		goto out;
3821 
3822 	/* proceed as DFS mount */
3823 	uuid_gen(&mnt_ctx.mount_id);
3824 	rc = connect_dfs_root(&mnt_ctx, &tl);
3825 	dfs_cache_free_tgts(&tl);
3826 
3827 	if (rc)
3828 		goto error;
3829 
3830 	rc = is_path_remote(&mnt_ctx);
3831 	if (rc)
3832 		rc = follow_dfs_link(&mnt_ctx);
3833 	if (rc)
3834 		goto error;
3835 
3836 	setup_server_referral_paths(&mnt_ctx);
3837 	/*
3838 	 * After reconnecting to a different server, unique ids won't match anymore, so we disable
3839 	 * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3840 	 */
3841 	cifs_autodisable_serverino(cifs_sb);
3842 	/*
3843 	 * Force the use of prefix path to support failover on DFS paths that resolve to targets
3844 	 * that have different prefix paths.
3845 	 */
3846 	cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3847 	kfree(cifs_sb->prepath);
3848 	cifs_sb->prepath = ctx->prepath;
3849 	ctx->prepath = NULL;
3850 	uuid_copy(&cifs_sb->dfs_mount_id, &mnt_ctx.mount_id);
3851 
3852 out:
3853 	cifs_try_adding_channels(cifs_sb, mnt_ctx.ses);
3854 	rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3855 	if (rc)
3856 		goto error;
3857 
3858 	free_xid(mnt_ctx.xid);
3859 	return rc;
3860 
3861 error:
3862 	dfs_cache_put_refsrv_sessions(&mnt_ctx.mount_id);
3863 	kfree(mnt_ctx.origin_fullpath);
3864 	kfree(mnt_ctx.leaf_fullpath);
3865 	mount_put_conns(&mnt_ctx);
3866 	return rc;
3867 }
3868 #else
cifs_mount(struct cifs_sb_info * cifs_sb,struct smb3_fs_context * ctx)3869 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3870 {
3871 	int rc = 0;
3872 	struct mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3873 
3874 	rc = mount_get_conns(&mnt_ctx);
3875 	if (rc)
3876 		goto error;
3877 
3878 	if (mnt_ctx.tcon) {
3879 		rc = is_path_remote(&mnt_ctx);
3880 		if (rc == -EREMOTE)
3881 			rc = -EOPNOTSUPP;
3882 		if (rc)
3883 			goto error;
3884 	}
3885 
3886 	rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3887 	if (rc)
3888 		goto error;
3889 
3890 	free_xid(mnt_ctx.xid);
3891 	return rc;
3892 
3893 error:
3894 	mount_put_conns(&mnt_ctx);
3895 	return rc;
3896 }
3897 #endif
3898 
3899 /*
3900  * Issue a TREE_CONNECT request.
3901  */
3902 int
CIFSTCon(const unsigned int xid,struct cifs_ses * ses,const char * tree,struct cifs_tcon * tcon,const struct nls_table * nls_codepage)3903 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3904 	 const char *tree, struct cifs_tcon *tcon,
3905 	 const struct nls_table *nls_codepage)
3906 {
3907 	struct smb_hdr *smb_buffer;
3908 	struct smb_hdr *smb_buffer_response;
3909 	TCONX_REQ *pSMB;
3910 	TCONX_RSP *pSMBr;
3911 	unsigned char *bcc_ptr;
3912 	int rc = 0;
3913 	int length;
3914 	__u16 bytes_left, count;
3915 
3916 	if (ses == NULL)
3917 		return -EIO;
3918 
3919 	smb_buffer = cifs_buf_get();
3920 	if (smb_buffer == NULL)
3921 		return -ENOMEM;
3922 
3923 	smb_buffer_response = smb_buffer;
3924 
3925 	header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3926 			NULL /*no tid */ , 4 /*wct */ );
3927 
3928 	smb_buffer->Mid = get_next_mid(ses->server);
3929 	smb_buffer->Uid = ses->Suid;
3930 	pSMB = (TCONX_REQ *) smb_buffer;
3931 	pSMBr = (TCONX_RSP *) smb_buffer_response;
3932 
3933 	pSMB->AndXCommand = 0xFF;
3934 	pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3935 	bcc_ptr = &pSMB->Password[0];
3936 
3937 	pSMB->PasswordLength = cpu_to_le16(1);	/* minimum */
3938 	*bcc_ptr = 0; /* password is null byte */
3939 	bcc_ptr++;              /* skip password */
3940 	/* already aligned so no need to do it below */
3941 
3942 	if (ses->server->sign)
3943 		smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3944 
3945 	if (ses->capabilities & CAP_STATUS32) {
3946 		smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3947 	}
3948 	if (ses->capabilities & CAP_DFS) {
3949 		smb_buffer->Flags2 |= SMBFLG2_DFS;
3950 	}
3951 	if (ses->capabilities & CAP_UNICODE) {
3952 		smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3953 		length =
3954 		    cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3955 			6 /* max utf8 char length in bytes */ *
3956 			(/* server len*/ + 256 /* share len */), nls_codepage);
3957 		bcc_ptr += 2 * length;	/* convert num 16 bit words to bytes */
3958 		bcc_ptr += 2;	/* skip trailing null */
3959 	} else {		/* ASCII */
3960 		strcpy(bcc_ptr, tree);
3961 		bcc_ptr += strlen(tree) + 1;
3962 	}
3963 	strcpy(bcc_ptr, "?????");
3964 	bcc_ptr += strlen("?????");
3965 	bcc_ptr += 1;
3966 	count = bcc_ptr - &pSMB->Password[0];
3967 	be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
3968 	pSMB->ByteCount = cpu_to_le16(count);
3969 
3970 	rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3971 			 0);
3972 
3973 	/* above now done in SendReceive */
3974 	if (rc == 0) {
3975 		bool is_unicode;
3976 
3977 		tcon->tid = smb_buffer_response->Tid;
3978 		bcc_ptr = pByteArea(smb_buffer_response);
3979 		bytes_left = get_bcc(smb_buffer_response);
3980 		length = strnlen(bcc_ptr, bytes_left - 2);
3981 		if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3982 			is_unicode = true;
3983 		else
3984 			is_unicode = false;
3985 
3986 
3987 		/* skip service field (NB: this field is always ASCII) */
3988 		if (length == 3) {
3989 			if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3990 			    (bcc_ptr[2] == 'C')) {
3991 				cifs_dbg(FYI, "IPC connection\n");
3992 				tcon->ipc = true;
3993 				tcon->pipe = true;
3994 			}
3995 		} else if (length == 2) {
3996 			if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3997 				/* the most common case */
3998 				cifs_dbg(FYI, "disk share connection\n");
3999 			}
4000 		}
4001 		bcc_ptr += length + 1;
4002 		bytes_left -= (length + 1);
4003 		strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
4004 
4005 		/* mostly informational -- no need to fail on error here */
4006 		kfree(tcon->nativeFileSystem);
4007 		tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
4008 						      bytes_left, is_unicode,
4009 						      nls_codepage);
4010 
4011 		cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
4012 
4013 		if ((smb_buffer_response->WordCount == 3) ||
4014 			 (smb_buffer_response->WordCount == 7))
4015 			/* field is in same location */
4016 			tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
4017 		else
4018 			tcon->Flags = 0;
4019 		cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
4020 	}
4021 
4022 	cifs_buf_release(smb_buffer);
4023 	return rc;
4024 }
4025 
delayed_free(struct rcu_head * p)4026 static void delayed_free(struct rcu_head *p)
4027 {
4028 	struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
4029 
4030 	unload_nls(cifs_sb->local_nls);
4031 	smb3_cleanup_fs_context(cifs_sb->ctx);
4032 	kfree(cifs_sb);
4033 }
4034 
4035 void
cifs_umount(struct cifs_sb_info * cifs_sb)4036 cifs_umount(struct cifs_sb_info *cifs_sb)
4037 {
4038 	struct rb_root *root = &cifs_sb->tlink_tree;
4039 	struct rb_node *node;
4040 	struct tcon_link *tlink;
4041 
4042 	cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
4043 
4044 	spin_lock(&cifs_sb->tlink_tree_lock);
4045 	while ((node = rb_first(root))) {
4046 		tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4047 		cifs_get_tlink(tlink);
4048 		clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4049 		rb_erase(node, root);
4050 
4051 		spin_unlock(&cifs_sb->tlink_tree_lock);
4052 		cifs_put_tlink(tlink);
4053 		spin_lock(&cifs_sb->tlink_tree_lock);
4054 	}
4055 	spin_unlock(&cifs_sb->tlink_tree_lock);
4056 
4057 	kfree(cifs_sb->prepath);
4058 #ifdef CONFIG_CIFS_DFS_UPCALL
4059 	dfs_cache_put_refsrv_sessions(&cifs_sb->dfs_mount_id);
4060 #endif
4061 	call_rcu(&cifs_sb->rcu, delayed_free);
4062 }
4063 
4064 int
cifs_negotiate_protocol(const unsigned int xid,struct cifs_ses * ses,struct TCP_Server_Info * server)4065 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses,
4066 			struct TCP_Server_Info *server)
4067 {
4068 	int rc = 0;
4069 
4070 	if (!server->ops->need_neg || !server->ops->negotiate)
4071 		return -ENOSYS;
4072 
4073 	/* only send once per connect */
4074 	spin_lock(&server->srv_lock);
4075 	if (!server->ops->need_neg(server) ||
4076 	    server->tcpStatus != CifsNeedNegotiate) {
4077 		spin_unlock(&server->srv_lock);
4078 		return 0;
4079 	}
4080 	server->tcpStatus = CifsInNegotiate;
4081 	spin_unlock(&server->srv_lock);
4082 
4083 	rc = server->ops->negotiate(xid, ses, server);
4084 	if (rc == 0) {
4085 		spin_lock(&server->srv_lock);
4086 		if (server->tcpStatus == CifsInNegotiate)
4087 			server->tcpStatus = CifsGood;
4088 		else
4089 			rc = -EHOSTDOWN;
4090 		spin_unlock(&server->srv_lock);
4091 	} else {
4092 		spin_lock(&server->srv_lock);
4093 		if (server->tcpStatus == CifsInNegotiate)
4094 			server->tcpStatus = CifsNeedNegotiate;
4095 		spin_unlock(&server->srv_lock);
4096 	}
4097 
4098 	return rc;
4099 }
4100 
4101 int
cifs_setup_session(const unsigned int xid,struct cifs_ses * ses,struct TCP_Server_Info * server,struct nls_table * nls_info)4102 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
4103 		   struct TCP_Server_Info *server,
4104 		   struct nls_table *nls_info)
4105 {
4106 	int rc = -ENOSYS;
4107 	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
4108 	struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
4109 	bool is_binding = false;
4110 
4111 	spin_lock(&ses->ses_lock);
4112 	if (server->dstaddr.ss_family == AF_INET6)
4113 		scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI6", &addr6->sin6_addr);
4114 	else
4115 		scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI4", &addr->sin_addr);
4116 
4117 	if (ses->ses_status != SES_GOOD &&
4118 	    ses->ses_status != SES_NEW &&
4119 	    ses->ses_status != SES_NEED_RECON) {
4120 		spin_unlock(&ses->ses_lock);
4121 		return 0;
4122 	}
4123 
4124 	/* only send once per connect */
4125 	spin_lock(&ses->chan_lock);
4126 	if (CIFS_ALL_CHANS_GOOD(ses) ||
4127 	    cifs_chan_in_reconnect(ses, server)) {
4128 		spin_unlock(&ses->chan_lock);
4129 		spin_unlock(&ses->ses_lock);
4130 		return 0;
4131 	}
4132 	is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
4133 	cifs_chan_set_in_reconnect(ses, server);
4134 	spin_unlock(&ses->chan_lock);
4135 
4136 	if (!is_binding)
4137 		ses->ses_status = SES_IN_SETUP;
4138 	spin_unlock(&ses->ses_lock);
4139 
4140 	if (!is_binding) {
4141 		ses->capabilities = server->capabilities;
4142 		if (!linuxExtEnabled)
4143 			ses->capabilities &= (~server->vals->cap_unix);
4144 
4145 		if (ses->auth_key.response) {
4146 			cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
4147 				 ses->auth_key.response);
4148 			kfree_sensitive(ses->auth_key.response);
4149 			ses->auth_key.response = NULL;
4150 			ses->auth_key.len = 0;
4151 		}
4152 	}
4153 
4154 	cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
4155 		 server->sec_mode, server->capabilities, server->timeAdj);
4156 
4157 	if (server->ops->sess_setup)
4158 		rc = server->ops->sess_setup(xid, ses, server, nls_info);
4159 
4160 	if (rc) {
4161 		cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
4162 		spin_lock(&ses->ses_lock);
4163 		if (ses->ses_status == SES_IN_SETUP)
4164 			ses->ses_status = SES_NEED_RECON;
4165 		spin_lock(&ses->chan_lock);
4166 		cifs_chan_clear_in_reconnect(ses, server);
4167 		spin_unlock(&ses->chan_lock);
4168 		spin_unlock(&ses->ses_lock);
4169 	} else {
4170 		spin_lock(&ses->ses_lock);
4171 		if (ses->ses_status == SES_IN_SETUP)
4172 			ses->ses_status = SES_GOOD;
4173 		spin_lock(&ses->chan_lock);
4174 		cifs_chan_clear_in_reconnect(ses, server);
4175 		cifs_chan_clear_need_reconnect(ses, server);
4176 		spin_unlock(&ses->chan_lock);
4177 		spin_unlock(&ses->ses_lock);
4178 	}
4179 
4180 	return rc;
4181 }
4182 
4183 static int
cifs_set_vol_auth(struct smb3_fs_context * ctx,struct cifs_ses * ses)4184 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
4185 {
4186 	ctx->sectype = ses->sectype;
4187 
4188 	/* krb5 is special, since we don't need username or pw */
4189 	if (ctx->sectype == Kerberos)
4190 		return 0;
4191 
4192 	return cifs_set_cifscreds(ctx, ses);
4193 }
4194 
4195 static struct cifs_tcon *
cifs_construct_tcon(struct cifs_sb_info * cifs_sb,kuid_t fsuid)4196 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
4197 {
4198 	int rc;
4199 	struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
4200 	struct cifs_ses *ses;
4201 	struct cifs_tcon *tcon = NULL;
4202 	struct smb3_fs_context *ctx;
4203 
4204 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
4205 	if (ctx == NULL)
4206 		return ERR_PTR(-ENOMEM);
4207 
4208 	ctx->local_nls = cifs_sb->local_nls;
4209 	ctx->linux_uid = fsuid;
4210 	ctx->cred_uid = fsuid;
4211 	ctx->UNC = master_tcon->tree_name;
4212 	ctx->retry = master_tcon->retry;
4213 	ctx->nocase = master_tcon->nocase;
4214 	ctx->nohandlecache = master_tcon->nohandlecache;
4215 	ctx->local_lease = master_tcon->local_lease;
4216 	ctx->no_lease = master_tcon->no_lease;
4217 	ctx->resilient = master_tcon->use_resilient;
4218 	ctx->persistent = master_tcon->use_persistent;
4219 	ctx->handle_timeout = master_tcon->handle_timeout;
4220 	ctx->no_linux_ext = !master_tcon->unix_ext;
4221 	ctx->linux_ext = master_tcon->posix_extensions;
4222 	ctx->sectype = master_tcon->ses->sectype;
4223 	ctx->sign = master_tcon->ses->sign;
4224 	ctx->seal = master_tcon->seal;
4225 	ctx->witness = master_tcon->use_witness;
4226 
4227 	rc = cifs_set_vol_auth(ctx, master_tcon->ses);
4228 	if (rc) {
4229 		tcon = ERR_PTR(rc);
4230 		goto out;
4231 	}
4232 
4233 	/* get a reference for the same TCP session */
4234 	spin_lock(&cifs_tcp_ses_lock);
4235 	++master_tcon->ses->server->srv_count;
4236 	spin_unlock(&cifs_tcp_ses_lock);
4237 
4238 	ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
4239 	if (IS_ERR(ses)) {
4240 		tcon = (struct cifs_tcon *)ses;
4241 		cifs_put_tcp_session(master_tcon->ses->server, 0);
4242 		goto out;
4243 	}
4244 
4245 	tcon = cifs_get_tcon(ses, ctx);
4246 	if (IS_ERR(tcon)) {
4247 		cifs_put_smb_ses(ses);
4248 		goto out;
4249 	}
4250 
4251 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4252 	if (cap_unix(ses))
4253 		reset_cifs_unix_caps(0, tcon, NULL, ctx);
4254 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
4255 
4256 out:
4257 	kfree(ctx->username);
4258 	kfree_sensitive(ctx->password);
4259 	kfree(ctx);
4260 
4261 	return tcon;
4262 }
4263 
4264 struct cifs_tcon *
cifs_sb_master_tcon(struct cifs_sb_info * cifs_sb)4265 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4266 {
4267 	return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4268 }
4269 
4270 /* find and return a tlink with given uid */
4271 static struct tcon_link *
tlink_rb_search(struct rb_root * root,kuid_t uid)4272 tlink_rb_search(struct rb_root *root, kuid_t uid)
4273 {
4274 	struct rb_node *node = root->rb_node;
4275 	struct tcon_link *tlink;
4276 
4277 	while (node) {
4278 		tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4279 
4280 		if (uid_gt(tlink->tl_uid, uid))
4281 			node = node->rb_left;
4282 		else if (uid_lt(tlink->tl_uid, uid))
4283 			node = node->rb_right;
4284 		else
4285 			return tlink;
4286 	}
4287 	return NULL;
4288 }
4289 
4290 /* insert a tcon_link into the tree */
4291 static void
tlink_rb_insert(struct rb_root * root,struct tcon_link * new_tlink)4292 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4293 {
4294 	struct rb_node **new = &(root->rb_node), *parent = NULL;
4295 	struct tcon_link *tlink;
4296 
4297 	while (*new) {
4298 		tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4299 		parent = *new;
4300 
4301 		if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4302 			new = &((*new)->rb_left);
4303 		else
4304 			new = &((*new)->rb_right);
4305 	}
4306 
4307 	rb_link_node(&new_tlink->tl_rbnode, parent, new);
4308 	rb_insert_color(&new_tlink->tl_rbnode, root);
4309 }
4310 
4311 /*
4312  * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4313  * current task.
4314  *
4315  * If the superblock doesn't refer to a multiuser mount, then just return
4316  * the master tcon for the mount.
4317  *
4318  * First, search the rbtree for an existing tcon for this fsuid. If one
4319  * exists, then check to see if it's pending construction. If it is then wait
4320  * for construction to complete. Once it's no longer pending, check to see if
4321  * it failed and either return an error or retry construction, depending on
4322  * the timeout.
4323  *
4324  * If one doesn't exist then insert a new tcon_link struct into the tree and
4325  * try to construct a new one.
4326  */
4327 struct tcon_link *
cifs_sb_tlink(struct cifs_sb_info * cifs_sb)4328 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4329 {
4330 	int ret;
4331 	kuid_t fsuid = current_fsuid();
4332 	struct tcon_link *tlink, *newtlink;
4333 
4334 	if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4335 		return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4336 
4337 	spin_lock(&cifs_sb->tlink_tree_lock);
4338 	tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4339 	if (tlink)
4340 		cifs_get_tlink(tlink);
4341 	spin_unlock(&cifs_sb->tlink_tree_lock);
4342 
4343 	if (tlink == NULL) {
4344 		newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4345 		if (newtlink == NULL)
4346 			return ERR_PTR(-ENOMEM);
4347 		newtlink->tl_uid = fsuid;
4348 		newtlink->tl_tcon = ERR_PTR(-EACCES);
4349 		set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4350 		set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4351 		cifs_get_tlink(newtlink);
4352 
4353 		spin_lock(&cifs_sb->tlink_tree_lock);
4354 		/* was one inserted after previous search? */
4355 		tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4356 		if (tlink) {
4357 			cifs_get_tlink(tlink);
4358 			spin_unlock(&cifs_sb->tlink_tree_lock);
4359 			kfree(newtlink);
4360 			goto wait_for_construction;
4361 		}
4362 		tlink = newtlink;
4363 		tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4364 		spin_unlock(&cifs_sb->tlink_tree_lock);
4365 	} else {
4366 wait_for_construction:
4367 		ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4368 				  TASK_INTERRUPTIBLE);
4369 		if (ret) {
4370 			cifs_put_tlink(tlink);
4371 			return ERR_PTR(-ERESTARTSYS);
4372 		}
4373 
4374 		/* if it's good, return it */
4375 		if (!IS_ERR(tlink->tl_tcon))
4376 			return tlink;
4377 
4378 		/* return error if we tried this already recently */
4379 		if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4380 			cifs_put_tlink(tlink);
4381 			return ERR_PTR(-EACCES);
4382 		}
4383 
4384 		if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4385 			goto wait_for_construction;
4386 	}
4387 
4388 	tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4389 	clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4390 	wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4391 
4392 	if (IS_ERR(tlink->tl_tcon)) {
4393 		cifs_put_tlink(tlink);
4394 		return ERR_PTR(-EACCES);
4395 	}
4396 
4397 	return tlink;
4398 }
4399 
4400 /*
4401  * periodic workqueue job that scans tcon_tree for a superblock and closes
4402  * out tcons.
4403  */
4404 static void
cifs_prune_tlinks(struct work_struct * work)4405 cifs_prune_tlinks(struct work_struct *work)
4406 {
4407 	struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4408 						    prune_tlinks.work);
4409 	struct rb_root *root = &cifs_sb->tlink_tree;
4410 	struct rb_node *node;
4411 	struct rb_node *tmp;
4412 	struct tcon_link *tlink;
4413 
4414 	/*
4415 	 * Because we drop the spinlock in the loop in order to put the tlink
4416 	 * it's not guarded against removal of links from the tree. The only
4417 	 * places that remove entries from the tree are this function and
4418 	 * umounts. Because this function is non-reentrant and is canceled
4419 	 * before umount can proceed, this is safe.
4420 	 */
4421 	spin_lock(&cifs_sb->tlink_tree_lock);
4422 	node = rb_first(root);
4423 	while (node != NULL) {
4424 		tmp = node;
4425 		node = rb_next(tmp);
4426 		tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4427 
4428 		if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4429 		    atomic_read(&tlink->tl_count) != 0 ||
4430 		    time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4431 			continue;
4432 
4433 		cifs_get_tlink(tlink);
4434 		clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4435 		rb_erase(tmp, root);
4436 
4437 		spin_unlock(&cifs_sb->tlink_tree_lock);
4438 		cifs_put_tlink(tlink);
4439 		spin_lock(&cifs_sb->tlink_tree_lock);
4440 	}
4441 	spin_unlock(&cifs_sb->tlink_tree_lock);
4442 
4443 	queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4444 				TLINK_IDLE_EXPIRE);
4445 }
4446 
4447 #ifdef CONFIG_CIFS_DFS_UPCALL
4448 /* Update dfs referral path of superblock */
update_server_fullpath(struct TCP_Server_Info * server,struct cifs_sb_info * cifs_sb,const char * target)4449 static int update_server_fullpath(struct TCP_Server_Info *server, struct cifs_sb_info *cifs_sb,
4450 				  const char *target)
4451 {
4452 	int rc = 0;
4453 	size_t len = strlen(target);
4454 	char *refpath, *npath;
4455 
4456 	if (unlikely(len < 2 || *target != '\\'))
4457 		return -EINVAL;
4458 
4459 	if (target[1] == '\\') {
4460 		len += 1;
4461 		refpath = kmalloc(len, GFP_KERNEL);
4462 		if (!refpath)
4463 			return -ENOMEM;
4464 
4465 		scnprintf(refpath, len, "%s", target);
4466 	} else {
4467 		len += sizeof("\\");
4468 		refpath = kmalloc(len, GFP_KERNEL);
4469 		if (!refpath)
4470 			return -ENOMEM;
4471 
4472 		scnprintf(refpath, len, "\\%s", target);
4473 	}
4474 
4475 	npath = dfs_cache_canonical_path(refpath, cifs_sb->local_nls, cifs_remap(cifs_sb));
4476 	kfree(refpath);
4477 
4478 	if (IS_ERR(npath)) {
4479 		rc = PTR_ERR(npath);
4480 	} else {
4481 		mutex_lock(&server->refpath_lock);
4482 		kfree(server->leaf_fullpath);
4483 		server->leaf_fullpath = npath;
4484 		mutex_unlock(&server->refpath_lock);
4485 		server->current_fullpath = server->leaf_fullpath;
4486 	}
4487 	return rc;
4488 }
4489 
target_share_matches_server(struct TCP_Server_Info * server,const char * tcp_host,size_t tcp_host_len,char * share,bool * target_match)4490 static int target_share_matches_server(struct TCP_Server_Info *server, const char *tcp_host,
4491 				       size_t tcp_host_len, char *share, bool *target_match)
4492 {
4493 	int rc = 0;
4494 	const char *dfs_host;
4495 	size_t dfs_host_len;
4496 
4497 	*target_match = true;
4498 	extract_unc_hostname(share, &dfs_host, &dfs_host_len);
4499 
4500 	/* Check if hostnames or addresses match */
4501 	if (dfs_host_len != tcp_host_len || strncasecmp(dfs_host, tcp_host, dfs_host_len) != 0) {
4502 		cifs_dbg(FYI, "%s: %.*s doesn't match %.*s\n", __func__, (int)dfs_host_len,
4503 			 dfs_host, (int)tcp_host_len, tcp_host);
4504 		rc = match_target_ip(server, dfs_host, dfs_host_len, target_match);
4505 		if (rc)
4506 			cifs_dbg(VFS, "%s: failed to match target ip: %d\n", __func__, rc);
4507 	}
4508 	return rc;
4509 }
4510 
__tree_connect_dfs_target(const unsigned int xid,struct cifs_tcon * tcon,struct cifs_sb_info * cifs_sb,char * tree,bool islink,struct dfs_cache_tgt_list * tl)4511 static int __tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4512 				     struct cifs_sb_info *cifs_sb, char *tree, bool islink,
4513 				     struct dfs_cache_tgt_list *tl)
4514 {
4515 	int rc;
4516 	struct TCP_Server_Info *server = tcon->ses->server;
4517 	const struct smb_version_operations *ops = server->ops;
4518 	struct cifs_tcon *ipc = tcon->ses->tcon_ipc;
4519 	char *share = NULL, *prefix = NULL;
4520 	const char *tcp_host;
4521 	size_t tcp_host_len;
4522 	struct dfs_cache_tgt_iterator *tit;
4523 	bool target_match;
4524 
4525 	extract_unc_hostname(server->hostname, &tcp_host, &tcp_host_len);
4526 
4527 	tit = dfs_cache_get_tgt_iterator(tl);
4528 	if (!tit) {
4529 		rc = -ENOENT;
4530 		goto out;
4531 	}
4532 
4533 	/* Try to tree connect to all dfs targets */
4534 	for (; tit; tit = dfs_cache_get_next_tgt(tl, tit)) {
4535 		const char *target = dfs_cache_get_tgt_name(tit);
4536 		struct dfs_cache_tgt_list ntl = DFS_CACHE_TGT_LIST_INIT(ntl);
4537 
4538 		kfree(share);
4539 		kfree(prefix);
4540 		share = prefix = NULL;
4541 
4542 		/* Check if share matches with tcp ses */
4543 		rc = dfs_cache_get_tgt_share(server->current_fullpath + 1, tit, &share, &prefix);
4544 		if (rc) {
4545 			cifs_dbg(VFS, "%s: failed to parse target share: %d\n", __func__, rc);
4546 			break;
4547 		}
4548 
4549 		rc = target_share_matches_server(server, tcp_host, tcp_host_len, share,
4550 						 &target_match);
4551 		if (rc)
4552 			break;
4553 		if (!target_match) {
4554 			rc = -EHOSTUNREACH;
4555 			continue;
4556 		}
4557 
4558 		if (ipc->need_reconnect) {
4559 			scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4560 			rc = ops->tree_connect(xid, ipc->ses, tree, ipc, cifs_sb->local_nls);
4561 			if (rc)
4562 				break;
4563 		}
4564 
4565 		scnprintf(tree, MAX_TREE_SIZE, "\\%s", share);
4566 		if (!islink) {
4567 			rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4568 			break;
4569 		}
4570 		/*
4571 		 * If no dfs referrals were returned from link target, then just do a TREE_CONNECT
4572 		 * to it.  Otherwise, cache the dfs referral and then mark current tcp ses for
4573 		 * reconnect so either the demultiplex thread or the echo worker will reconnect to
4574 		 * newly resolved target.
4575 		 */
4576 		if (dfs_cache_find(xid, tcon->ses, cifs_sb->local_nls, cifs_remap(cifs_sb), target,
4577 				   NULL, &ntl)) {
4578 			rc = ops->tree_connect(xid, tcon->ses, tree, tcon, cifs_sb->local_nls);
4579 			if (rc)
4580 				continue;
4581 			rc = dfs_cache_noreq_update_tgthint(server->current_fullpath + 1, tit);
4582 			if (!rc)
4583 				rc = cifs_update_super_prepath(cifs_sb, prefix);
4584 		} else {
4585 			/* Target is another dfs share */
4586 			rc = update_server_fullpath(server, cifs_sb, target);
4587 			dfs_cache_free_tgts(tl);
4588 
4589 			if (!rc) {
4590 				rc = -EREMOTE;
4591 				list_replace_init(&ntl.tl_list, &tl->tl_list);
4592 			} else
4593 				dfs_cache_free_tgts(&ntl);
4594 		}
4595 		break;
4596 	}
4597 
4598 out:
4599 	kfree(share);
4600 	kfree(prefix);
4601 
4602 	return rc;
4603 }
4604 
tree_connect_dfs_target(const unsigned int xid,struct cifs_tcon * tcon,struct cifs_sb_info * cifs_sb,char * tree,bool islink,struct dfs_cache_tgt_list * tl)4605 static int tree_connect_dfs_target(const unsigned int xid, struct cifs_tcon *tcon,
4606 				   struct cifs_sb_info *cifs_sb, char *tree, bool islink,
4607 				   struct dfs_cache_tgt_list *tl)
4608 {
4609 	int rc;
4610 	int num_links = 0;
4611 	struct TCP_Server_Info *server = tcon->ses->server;
4612 
4613 	do {
4614 		rc = __tree_connect_dfs_target(xid, tcon, cifs_sb, tree, islink, tl);
4615 		if (!rc || rc != -EREMOTE)
4616 			break;
4617 	} while (rc = -ELOOP, ++num_links < MAX_NESTED_LINKS);
4618 	/*
4619 	 * If we couldn't tree connect to any targets from last referral path, then retry from
4620 	 * original referral path.
4621 	 */
4622 	if (rc && server->current_fullpath != server->origin_fullpath) {
4623 		server->current_fullpath = server->origin_fullpath;
4624 		cifs_signal_cifsd_for_reconnect(server, true);
4625 	}
4626 
4627 	dfs_cache_free_tgts(tl);
4628 	return rc;
4629 }
4630 
cifs_tree_connect(const unsigned int xid,struct cifs_tcon * tcon,const struct nls_table * nlsc)4631 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4632 {
4633 	int rc;
4634 	struct TCP_Server_Info *server = tcon->ses->server;
4635 	const struct smb_version_operations *ops = server->ops;
4636 	struct super_block *sb = NULL;
4637 	struct cifs_sb_info *cifs_sb;
4638 	struct dfs_cache_tgt_list tl = DFS_CACHE_TGT_LIST_INIT(tl);
4639 	char *tree;
4640 	struct dfs_info3_param ref = {0};
4641 
4642 	/* only send once per connect */
4643 	spin_lock(&tcon->tc_lock);
4644 	if (tcon->ses->ses_status != SES_GOOD ||
4645 	    (tcon->status != TID_NEW &&
4646 	    tcon->status != TID_NEED_TCON)) {
4647 		spin_unlock(&tcon->tc_lock);
4648 		return 0;
4649 	}
4650 	tcon->status = TID_IN_TCON;
4651 	spin_unlock(&tcon->tc_lock);
4652 
4653 	tree = kzalloc(MAX_TREE_SIZE, GFP_KERNEL);
4654 	if (!tree) {
4655 		rc = -ENOMEM;
4656 		goto out;
4657 	}
4658 
4659 	if (tcon->ipc) {
4660 		scnprintf(tree, MAX_TREE_SIZE, "\\\\%s\\IPC$", server->hostname);
4661 		rc = ops->tree_connect(xid, tcon->ses, tree, tcon, nlsc);
4662 		goto out;
4663 	}
4664 
4665 	sb = cifs_get_tcp_super(server);
4666 	if (IS_ERR(sb)) {
4667 		rc = PTR_ERR(sb);
4668 		cifs_dbg(VFS, "%s: could not find superblock: %d\n", __func__, rc);
4669 		goto out;
4670 	}
4671 
4672 	cifs_sb = CIFS_SB(sb);
4673 
4674 	/* If it is not dfs or there was no cached dfs referral, then reconnect to same share */
4675 	if (!server->current_fullpath ||
4676 	    dfs_cache_noreq_find(server->current_fullpath + 1, &ref, &tl)) {
4677 		rc = ops->tree_connect(xid, tcon->ses, tcon->tree_name, tcon, cifs_sb->local_nls);
4678 		goto out;
4679 	}
4680 
4681 	rc = tree_connect_dfs_target(xid, tcon, cifs_sb, tree, ref.server_type == DFS_TYPE_LINK,
4682 				     &tl);
4683 	free_dfs_info_param(&ref);
4684 
4685 out:
4686 	kfree(tree);
4687 	cifs_put_tcp_super(sb);
4688 
4689 	if (rc) {
4690 		spin_lock(&tcon->tc_lock);
4691 		if (tcon->status == TID_IN_TCON)
4692 			tcon->status = TID_NEED_TCON;
4693 		spin_unlock(&tcon->tc_lock);
4694 	} else {
4695 		spin_lock(&tcon->tc_lock);
4696 		if (tcon->status == TID_IN_TCON)
4697 			tcon->status = TID_GOOD;
4698 		spin_unlock(&tcon->tc_lock);
4699 		tcon->need_reconnect = false;
4700 	}
4701 
4702 	return rc;
4703 }
4704 #else
cifs_tree_connect(const unsigned int xid,struct cifs_tcon * tcon,const struct nls_table * nlsc)4705 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4706 {
4707 	int rc;
4708 	const struct smb_version_operations *ops = tcon->ses->server->ops;
4709 
4710 	/* only send once per connect */
4711 	spin_lock(&tcon->tc_lock);
4712 	if (tcon->ses->ses_status != SES_GOOD ||
4713 	    (tcon->status != TID_NEW &&
4714 	    tcon->status != TID_NEED_TCON)) {
4715 		spin_unlock(&tcon->tc_lock);
4716 		return 0;
4717 	}
4718 	tcon->status = TID_IN_TCON;
4719 	spin_unlock(&tcon->tc_lock);
4720 
4721 	rc = ops->tree_connect(xid, tcon->ses, tcon->tree_name, tcon, nlsc);
4722 	if (rc) {
4723 		spin_lock(&tcon->tc_lock);
4724 		if (tcon->status == TID_IN_TCON)
4725 			tcon->status = TID_NEED_TCON;
4726 		spin_unlock(&tcon->tc_lock);
4727 	} else {
4728 		spin_lock(&tcon->tc_lock);
4729 		if (tcon->status == TID_IN_TCON)
4730 			tcon->status = TID_GOOD;
4731 		tcon->need_reconnect = false;
4732 		spin_unlock(&tcon->tc_lock);
4733 	}
4734 
4735 	return rc;
4736 }
4737 #endif
4738