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