xref: /openbmc/linux/fs/smb/client/connect.c (revision 4d75f5c664195b970e1cd2fd25b65b5eff257a0a)
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->hostname);
1060 	kfree(server);
1061 
1062 	length = atomic_dec_return(&tcpSesAllocCount);
1063 	if (length > 0)
1064 		mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1065 }
1066 
1067 static int
standard_receive3(struct TCP_Server_Info * server,struct mid_q_entry * mid)1068 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1069 {
1070 	int length;
1071 	char *buf = server->smallbuf;
1072 	unsigned int pdu_length = server->pdu_size;
1073 
1074 	/* make sure this will fit in a large buffer */
1075 	if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
1076 	    HEADER_PREAMBLE_SIZE(server)) {
1077 		cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
1078 		cifs_reconnect(server, true);
1079 		return -ECONNABORTED;
1080 	}
1081 
1082 	/* switch to large buffer if too big for a small one */
1083 	if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
1084 		server->large_buf = true;
1085 		memcpy(server->bigbuf, buf, server->total_read);
1086 		buf = server->bigbuf;
1087 	}
1088 
1089 	/* now read the rest */
1090 	length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
1091 				       pdu_length - MID_HEADER_SIZE(server));
1092 
1093 	if (length < 0)
1094 		return length;
1095 	server->total_read += length;
1096 
1097 	dump_smb(buf, server->total_read);
1098 
1099 	return cifs_handle_standard(server, mid);
1100 }
1101 
1102 int
cifs_handle_standard(struct TCP_Server_Info * server,struct mid_q_entry * mid)1103 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1104 {
1105 	char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
1106 	int rc;
1107 
1108 	/*
1109 	 * We know that we received enough to get to the MID as we
1110 	 * checked the pdu_length earlier. Now check to see
1111 	 * if the rest of the header is OK.
1112 	 *
1113 	 * 48 bytes is enough to display the header and a little bit
1114 	 * into the payload for debugging purposes.
1115 	 */
1116 	rc = server->ops->check_message(buf, server->total_read, server);
1117 	if (rc)
1118 		cifs_dump_mem("Bad SMB: ", buf,
1119 			min_t(unsigned int, server->total_read, 48));
1120 
1121 	if (server->ops->is_session_expired &&
1122 	    server->ops->is_session_expired(buf)) {
1123 		cifs_reconnect(server, true);
1124 		return -1;
1125 	}
1126 
1127 	if (server->ops->is_status_pending &&
1128 	    server->ops->is_status_pending(buf, server))
1129 		return -1;
1130 
1131 	if (!mid)
1132 		return rc;
1133 
1134 	handle_mid(mid, server, buf, rc);
1135 	return 0;
1136 }
1137 
1138 static void
smb2_add_credits_from_hdr(char * buffer,struct TCP_Server_Info * server)1139 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
1140 {
1141 	struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
1142 	int scredits, in_flight;
1143 
1144 	/*
1145 	 * SMB1 does not use credits.
1146 	 */
1147 	if (is_smb1(server))
1148 		return;
1149 
1150 	if (shdr->CreditRequest) {
1151 		spin_lock(&server->req_lock);
1152 		server->credits += le16_to_cpu(shdr->CreditRequest);
1153 		scredits = server->credits;
1154 		in_flight = server->in_flight;
1155 		spin_unlock(&server->req_lock);
1156 		wake_up(&server->request_q);
1157 
1158 		trace_smb3_hdr_credits(server->CurrentMid,
1159 				server->conn_id, server->hostname, scredits,
1160 				le16_to_cpu(shdr->CreditRequest), in_flight);
1161 		cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
1162 				__func__, le16_to_cpu(shdr->CreditRequest),
1163 				scredits);
1164 	}
1165 }
1166 
1167 
1168 static int
cifs_demultiplex_thread(void * p)1169 cifs_demultiplex_thread(void *p)
1170 {
1171 	int i, num_mids, length;
1172 	struct TCP_Server_Info *server = p;
1173 	unsigned int pdu_length;
1174 	unsigned int next_offset;
1175 	char *buf = NULL;
1176 	struct task_struct *task_to_wake = NULL;
1177 	struct mid_q_entry *mids[MAX_COMPOUND];
1178 	char *bufs[MAX_COMPOUND];
1179 	unsigned int noreclaim_flag, num_io_timeout = 0;
1180 	bool pending_reconnect = false;
1181 
1182 	noreclaim_flag = memalloc_noreclaim_save();
1183 	cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1184 
1185 	length = atomic_inc_return(&tcpSesAllocCount);
1186 	if (length > 1)
1187 		mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1188 
1189 	set_freezable();
1190 	allow_kernel_signal(SIGKILL);
1191 	while (server->tcpStatus != CifsExiting) {
1192 		if (try_to_freeze())
1193 			continue;
1194 
1195 		if (!allocate_buffers(server))
1196 			continue;
1197 
1198 		server->large_buf = false;
1199 		buf = server->smallbuf;
1200 		pdu_length = 4; /* enough to get RFC1001 header */
1201 
1202 		length = cifs_read_from_socket(server, buf, pdu_length);
1203 		if (length < 0)
1204 			continue;
1205 
1206 		if (is_smb1(server))
1207 			server->total_read = length;
1208 		else
1209 			server->total_read = 0;
1210 
1211 		/*
1212 		 * The right amount was read from socket - 4 bytes,
1213 		 * so we can now interpret the length field.
1214 		 */
1215 		pdu_length = get_rfc1002_length(buf);
1216 
1217 		cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1218 		if (!is_smb_response(server, buf[0]))
1219 			continue;
1220 
1221 		pending_reconnect = false;
1222 next_pdu:
1223 		server->pdu_size = pdu_length;
1224 
1225 		/* make sure we have enough to get to the MID */
1226 		if (server->pdu_size < MID_HEADER_SIZE(server)) {
1227 			cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1228 				 server->pdu_size);
1229 			cifs_reconnect(server, true);
1230 			continue;
1231 		}
1232 
1233 		/* read down to the MID */
1234 		length = cifs_read_from_socket(server,
1235 			     buf + HEADER_PREAMBLE_SIZE(server),
1236 			     MID_HEADER_SIZE(server));
1237 		if (length < 0)
1238 			continue;
1239 		server->total_read += length;
1240 
1241 		if (server->ops->next_header) {
1242 			if (server->ops->next_header(server, buf, &next_offset)) {
1243 				cifs_dbg(VFS, "%s: malformed response (next_offset=%u)\n",
1244 					 __func__, next_offset);
1245 				cifs_reconnect(server, true);
1246 				continue;
1247 			}
1248 			if (next_offset)
1249 				server->pdu_size = next_offset;
1250 		}
1251 
1252 		memset(mids, 0, sizeof(mids));
1253 		memset(bufs, 0, sizeof(bufs));
1254 		num_mids = 0;
1255 
1256 		if (server->ops->is_transform_hdr &&
1257 		    server->ops->receive_transform &&
1258 		    server->ops->is_transform_hdr(buf)) {
1259 			length = server->ops->receive_transform(server,
1260 								mids,
1261 								bufs,
1262 								&num_mids);
1263 		} else {
1264 			mids[0] = server->ops->find_mid(server, buf);
1265 			bufs[0] = buf;
1266 			num_mids = 1;
1267 
1268 			if (!mids[0] || !mids[0]->receive)
1269 				length = standard_receive3(server, mids[0]);
1270 			else
1271 				length = mids[0]->receive(server, mids[0]);
1272 		}
1273 
1274 		if (length < 0) {
1275 			for (i = 0; i < num_mids; i++)
1276 				if (mids[i])
1277 					release_mid(mids[i]);
1278 			continue;
1279 		}
1280 
1281 		if (server->ops->is_status_io_timeout &&
1282 		    server->ops->is_status_io_timeout(buf)) {
1283 			num_io_timeout++;
1284 			if (num_io_timeout > MAX_STATUS_IO_TIMEOUT) {
1285 				cifs_server_dbg(VFS,
1286 						"Number of request timeouts exceeded %d. Reconnecting",
1287 						MAX_STATUS_IO_TIMEOUT);
1288 
1289 				pending_reconnect = true;
1290 				num_io_timeout = 0;
1291 			}
1292 		}
1293 
1294 		server->lstrp = jiffies;
1295 
1296 		for (i = 0; i < num_mids; i++) {
1297 			if (mids[i] != NULL) {
1298 				mids[i]->resp_buf_size = server->pdu_size;
1299 
1300 				if (bufs[i] != NULL) {
1301 					if (server->ops->is_network_name_deleted &&
1302 					    server->ops->is_network_name_deleted(bufs[i],
1303 										 server)) {
1304 						cifs_server_dbg(FYI,
1305 								"Share deleted. Reconnect needed");
1306 					}
1307 				}
1308 
1309 				if (!mids[i]->multiRsp || mids[i]->multiEnd)
1310 					mids[i]->callback(mids[i]);
1311 
1312 				release_mid(mids[i]);
1313 			} else if (server->ops->is_oplock_break &&
1314 				   server->ops->is_oplock_break(bufs[i],
1315 								server)) {
1316 				smb2_add_credits_from_hdr(bufs[i], server);
1317 				cifs_dbg(FYI, "Received oplock break\n");
1318 			} else {
1319 				cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1320 						atomic_read(&mid_count));
1321 				cifs_dump_mem("Received Data is: ", bufs[i],
1322 					      HEADER_SIZE(server));
1323 				smb2_add_credits_from_hdr(bufs[i], server);
1324 #ifdef CONFIG_CIFS_DEBUG2
1325 				if (server->ops->dump_detail)
1326 					server->ops->dump_detail(bufs[i],
1327 								 server);
1328 				cifs_dump_mids(server);
1329 #endif /* CIFS_DEBUG2 */
1330 			}
1331 		}
1332 
1333 		if (pdu_length > server->pdu_size) {
1334 			if (!allocate_buffers(server))
1335 				continue;
1336 			pdu_length -= server->pdu_size;
1337 			server->total_read = 0;
1338 			server->large_buf = false;
1339 			buf = server->smallbuf;
1340 			goto next_pdu;
1341 		}
1342 
1343 		/* do this reconnect at the very end after processing all MIDs */
1344 		if (pending_reconnect)
1345 			cifs_reconnect(server, true);
1346 
1347 	} /* end while !EXITING */
1348 
1349 	/* buffer usually freed in free_mid - need to free it here on exit */
1350 	cifs_buf_release(server->bigbuf);
1351 	if (server->smallbuf) /* no sense logging a debug message if NULL */
1352 		cifs_small_buf_release(server->smallbuf);
1353 
1354 	task_to_wake = xchg(&server->tsk, NULL);
1355 	clean_demultiplex_info(server);
1356 
1357 	/* if server->tsk was NULL then wait for a signal before exiting */
1358 	if (!task_to_wake) {
1359 		set_current_state(TASK_INTERRUPTIBLE);
1360 		while (!signal_pending(current)) {
1361 			schedule();
1362 			set_current_state(TASK_INTERRUPTIBLE);
1363 		}
1364 		set_current_state(TASK_RUNNING);
1365 	}
1366 
1367 	memalloc_noreclaim_restore(noreclaim_flag);
1368 	module_put_and_kthread_exit(0);
1369 }
1370 
1371 int
cifs_ipaddr_cmp(struct sockaddr * srcaddr,struct sockaddr * rhs)1372 cifs_ipaddr_cmp(struct sockaddr *srcaddr, struct sockaddr *rhs)
1373 {
1374 	struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1375 	struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1376 	struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1377 	struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1378 
1379 	switch (srcaddr->sa_family) {
1380 	case AF_UNSPEC:
1381 		switch (rhs->sa_family) {
1382 		case AF_UNSPEC:
1383 			return 0;
1384 		case AF_INET:
1385 		case AF_INET6:
1386 			return 1;
1387 		default:
1388 			return -1;
1389 		}
1390 	case AF_INET: {
1391 		switch (rhs->sa_family) {
1392 		case AF_UNSPEC:
1393 			return -1;
1394 		case AF_INET:
1395 			return memcmp(saddr4, vaddr4,
1396 				      sizeof(struct sockaddr_in));
1397 		case AF_INET6:
1398 			return 1;
1399 		default:
1400 			return -1;
1401 		}
1402 	}
1403 	case AF_INET6: {
1404 		switch (rhs->sa_family) {
1405 		case AF_UNSPEC:
1406 		case AF_INET:
1407 			return -1;
1408 		case AF_INET6:
1409 			return memcmp(saddr6,
1410 				      vaddr6,
1411 				      sizeof(struct sockaddr_in6));
1412 		default:
1413 			return -1;
1414 		}
1415 	}
1416 	default:
1417 		return -1; /* don't expect to be here */
1418 	}
1419 }
1420 
1421 /*
1422  * Returns true if srcaddr isn't specified and rhs isn't specified, or
1423  * if srcaddr is specified and matches the IP address of the rhs argument
1424  */
1425 bool
cifs_match_ipaddr(struct sockaddr * srcaddr,struct sockaddr * rhs)1426 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1427 {
1428 	switch (srcaddr->sa_family) {
1429 	case AF_UNSPEC:
1430 		return (rhs->sa_family == AF_UNSPEC);
1431 	case AF_INET: {
1432 		struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1433 		struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1434 
1435 		return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1436 	}
1437 	case AF_INET6: {
1438 		struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1439 		struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1440 
1441 		return (ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr)
1442 			&& saddr6->sin6_scope_id == vaddr6->sin6_scope_id);
1443 	}
1444 	default:
1445 		WARN_ON(1);
1446 		return false; /* don't expect to be here */
1447 	}
1448 }
1449 
1450 /*
1451  * If no port is specified in addr structure, we try to match with 445 port
1452  * and if it fails - with 139 ports. It should be called only if address
1453  * families of server and addr are equal.
1454  */
1455 static bool
match_port(struct TCP_Server_Info * server,struct sockaddr * addr)1456 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1457 {
1458 	__be16 port, *sport;
1459 
1460 	/* SMBDirect manages its own ports, don't match it here */
1461 	if (server->rdma)
1462 		return true;
1463 
1464 	switch (addr->sa_family) {
1465 	case AF_INET:
1466 		sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1467 		port = ((struct sockaddr_in *) addr)->sin_port;
1468 		break;
1469 	case AF_INET6:
1470 		sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1471 		port = ((struct sockaddr_in6 *) addr)->sin6_port;
1472 		break;
1473 	default:
1474 		WARN_ON(1);
1475 		return false;
1476 	}
1477 
1478 	if (!port) {
1479 		port = htons(CIFS_PORT);
1480 		if (port == *sport)
1481 			return true;
1482 
1483 		port = htons(RFC1001_PORT);
1484 	}
1485 
1486 	return port == *sport;
1487 }
1488 
match_server_address(struct TCP_Server_Info * server,struct sockaddr * addr)1489 static bool match_server_address(struct TCP_Server_Info *server, struct sockaddr *addr)
1490 {
1491 	if (!cifs_match_ipaddr(addr, (struct sockaddr *)&server->dstaddr))
1492 		return false;
1493 
1494 	return true;
1495 }
1496 
1497 static bool
match_security(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)1498 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1499 {
1500 	/*
1501 	 * The select_sectype function should either return the ctx->sectype
1502 	 * that was specified, or "Unspecified" if that sectype was not
1503 	 * compatible with the given NEGOTIATE request.
1504 	 */
1505 	if (server->ops->select_sectype(server, ctx->sectype)
1506 	     == Unspecified)
1507 		return false;
1508 
1509 	/*
1510 	 * Now check if signing mode is acceptable. No need to check
1511 	 * global_secflags at this point since if MUST_SIGN is set then
1512 	 * the server->sign had better be too.
1513 	 */
1514 	if (ctx->sign && !server->sign)
1515 		return false;
1516 
1517 	return true;
1518 }
1519 
1520 /* this function must be called with srv_lock held */
match_server(struct TCP_Server_Info * server,struct smb3_fs_context * ctx,bool match_super)1521 static int match_server(struct TCP_Server_Info *server,
1522 			struct smb3_fs_context *ctx,
1523 			bool match_super)
1524 {
1525 	struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1526 
1527 	lockdep_assert_held(&server->srv_lock);
1528 
1529 	if (ctx->nosharesock)
1530 		return 0;
1531 
1532 	/* this server does not share socket */
1533 	if (server->nosharesock)
1534 		return 0;
1535 
1536 	/* If multidialect negotiation see if existing sessions match one */
1537 	if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1538 		if (server->vals->protocol_id < SMB30_PROT_ID)
1539 			return 0;
1540 	} else if (strcmp(ctx->vals->version_string,
1541 		   SMBDEFAULT_VERSION_STRING) == 0) {
1542 		if (server->vals->protocol_id < SMB21_PROT_ID)
1543 			return 0;
1544 	} else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1545 		return 0;
1546 
1547 	if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1548 		return 0;
1549 
1550 	if (!cifs_match_ipaddr((struct sockaddr *)&ctx->srcaddr,
1551 			       (struct sockaddr *)&server->srcaddr))
1552 		return 0;
1553 	/*
1554 	 * When matching cifs.ko superblocks (@match_super == true), we can't
1555 	 * really match either @server->leaf_fullpath or @server->dstaddr
1556 	 * directly since this @server might belong to a completely different
1557 	 * server -- in case of domain-based DFS referrals or DFS links -- as
1558 	 * provided earlier by mount(2) through 'source' and 'ip' options.
1559 	 *
1560 	 * Otherwise, match the DFS referral in @server->leaf_fullpath or the
1561 	 * destination address in @server->dstaddr.
1562 	 *
1563 	 * When using 'nodfs' mount option, we avoid sharing it with DFS
1564 	 * connections as they might failover.
1565 	 */
1566 	if (!match_super) {
1567 		if (!ctx->nodfs) {
1568 			if (server->leaf_fullpath) {
1569 				if (!ctx->leaf_fullpath ||
1570 				    strcasecmp(server->leaf_fullpath,
1571 					       ctx->leaf_fullpath))
1572 					return 0;
1573 			} else if (ctx->leaf_fullpath) {
1574 				return 0;
1575 			}
1576 		} else if (server->leaf_fullpath) {
1577 			return 0;
1578 		}
1579 	}
1580 
1581 	/*
1582 	 * Match for a regular connection (address/hostname/port) which has no
1583 	 * DFS referrals set.
1584 	 */
1585 	if (!server->leaf_fullpath &&
1586 	    (strcasecmp(server->hostname, ctx->server_hostname) ||
1587 	     !match_server_address(server, addr) ||
1588 	     !match_port(server, addr)))
1589 		return 0;
1590 
1591 	if (!match_security(server, ctx))
1592 		return 0;
1593 
1594 	if (server->echo_interval != ctx->echo_interval * HZ)
1595 		return 0;
1596 
1597 	if (server->rdma != ctx->rdma)
1598 		return 0;
1599 
1600 	if (server->ignore_signature != ctx->ignore_signature)
1601 		return 0;
1602 
1603 	if (server->min_offload != ctx->min_offload)
1604 		return 0;
1605 
1606 	if (server->retrans != ctx->retrans)
1607 		return 0;
1608 
1609 	return 1;
1610 }
1611 
1612 struct TCP_Server_Info *
cifs_find_tcp_session(struct smb3_fs_context * ctx)1613 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1614 {
1615 	struct TCP_Server_Info *server;
1616 
1617 	spin_lock(&cifs_tcp_ses_lock);
1618 	list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1619 		spin_lock(&server->srv_lock);
1620 		/*
1621 		 * Skip ses channels since they're only handled in lower layers
1622 		 * (e.g. cifs_send_recv).
1623 		 */
1624 		if (SERVER_IS_CHAN(server) ||
1625 		    !match_server(server, ctx, false)) {
1626 			spin_unlock(&server->srv_lock);
1627 			continue;
1628 		}
1629 		spin_unlock(&server->srv_lock);
1630 
1631 		++server->srv_count;
1632 		spin_unlock(&cifs_tcp_ses_lock);
1633 		cifs_dbg(FYI, "Existing tcp session with server found\n");
1634 		return server;
1635 	}
1636 	spin_unlock(&cifs_tcp_ses_lock);
1637 	return NULL;
1638 }
1639 
1640 void
cifs_put_tcp_session(struct TCP_Server_Info * server,int from_reconnect)1641 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1642 {
1643 	struct task_struct *task;
1644 
1645 	spin_lock(&cifs_tcp_ses_lock);
1646 	if (--server->srv_count > 0) {
1647 		spin_unlock(&cifs_tcp_ses_lock);
1648 		return;
1649 	}
1650 
1651 	/* srv_count can never go negative */
1652 	WARN_ON(server->srv_count < 0);
1653 
1654 	list_del_init(&server->tcp_ses_list);
1655 	spin_unlock(&cifs_tcp_ses_lock);
1656 
1657 	cancel_delayed_work_sync(&server->echo);
1658 
1659 	if (from_reconnect)
1660 		/*
1661 		 * Avoid deadlock here: reconnect work calls
1662 		 * cifs_put_tcp_session() at its end. Need to be sure
1663 		 * that reconnect work does nothing with server pointer after
1664 		 * that step.
1665 		 */
1666 		cancel_delayed_work(&server->reconnect);
1667 	else
1668 		cancel_delayed_work_sync(&server->reconnect);
1669 
1670 	/* For secondary channels, we pick up ref-count on the primary server */
1671 	if (SERVER_IS_CHAN(server))
1672 		cifs_put_tcp_session(server->primary_server, from_reconnect);
1673 
1674 	spin_lock(&server->srv_lock);
1675 	server->tcpStatus = CifsExiting;
1676 	spin_unlock(&server->srv_lock);
1677 
1678 	cifs_crypto_secmech_release(server);
1679 
1680 	kfree_sensitive(server->session_key.response);
1681 	server->session_key.response = NULL;
1682 	server->session_key.len = 0;
1683 
1684 	task = xchg(&server->tsk, NULL);
1685 	if (task)
1686 		send_sig(SIGKILL, task, 1);
1687 }
1688 
1689 struct TCP_Server_Info *
cifs_get_tcp_session(struct smb3_fs_context * ctx,struct TCP_Server_Info * primary_server)1690 cifs_get_tcp_session(struct smb3_fs_context *ctx,
1691 		     struct TCP_Server_Info *primary_server)
1692 {
1693 	struct TCP_Server_Info *tcp_ses = NULL;
1694 	int rc;
1695 
1696 	cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1697 
1698 	/* see if we already have a matching tcp_ses */
1699 	tcp_ses = cifs_find_tcp_session(ctx);
1700 	if (tcp_ses)
1701 		return tcp_ses;
1702 
1703 	tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1704 	if (!tcp_ses) {
1705 		rc = -ENOMEM;
1706 		goto out_err;
1707 	}
1708 
1709 	tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1710 	if (!tcp_ses->hostname) {
1711 		rc = -ENOMEM;
1712 		goto out_err;
1713 	}
1714 
1715 	if (ctx->leaf_fullpath) {
1716 		tcp_ses->leaf_fullpath = kstrdup(ctx->leaf_fullpath, GFP_KERNEL);
1717 		if (!tcp_ses->leaf_fullpath) {
1718 			rc = -ENOMEM;
1719 			goto out_err;
1720 		}
1721 	}
1722 
1723 	if (ctx->nosharesock)
1724 		tcp_ses->nosharesock = true;
1725 
1726 	tcp_ses->ops = ctx->ops;
1727 	tcp_ses->vals = ctx->vals;
1728 	cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1729 
1730 	tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1731 	tcp_ses->noblockcnt = ctx->rootfs;
1732 	tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1733 	tcp_ses->noautotune = ctx->noautotune;
1734 	tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1735 	tcp_ses->rdma = ctx->rdma;
1736 	tcp_ses->in_flight = 0;
1737 	tcp_ses->max_in_flight = 0;
1738 	tcp_ses->credits = 1;
1739 	if (primary_server) {
1740 		spin_lock(&cifs_tcp_ses_lock);
1741 		++primary_server->srv_count;
1742 		spin_unlock(&cifs_tcp_ses_lock);
1743 		tcp_ses->primary_server = primary_server;
1744 	}
1745 	init_waitqueue_head(&tcp_ses->response_q);
1746 	init_waitqueue_head(&tcp_ses->request_q);
1747 	INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1748 	mutex_init(&tcp_ses->_srv_mutex);
1749 	memcpy(tcp_ses->workstation_RFC1001_name,
1750 		ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1751 	memcpy(tcp_ses->server_RFC1001_name,
1752 		ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1753 	tcp_ses->session_estab = false;
1754 	tcp_ses->sequence_number = 0;
1755 	tcp_ses->channel_sequence_num = 0; /* only tracked for primary channel */
1756 	tcp_ses->reconnect_instance = 1;
1757 	tcp_ses->lstrp = jiffies;
1758 	tcp_ses->compression.requested = ctx->compress;
1759 	spin_lock_init(&tcp_ses->req_lock);
1760 	spin_lock_init(&tcp_ses->srv_lock);
1761 	spin_lock_init(&tcp_ses->mid_lock);
1762 	INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1763 	INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1764 	INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1765 	INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1766 	mutex_init(&tcp_ses->reconnect_mutex);
1767 #ifdef CONFIG_CIFS_DFS_UPCALL
1768 	mutex_init(&tcp_ses->refpath_lock);
1769 #endif
1770 	memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1771 	       sizeof(tcp_ses->srcaddr));
1772 	memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1773 		sizeof(tcp_ses->dstaddr));
1774 	if (ctx->use_client_guid)
1775 		memcpy(tcp_ses->client_guid, ctx->client_guid,
1776 		       SMB2_CLIENT_GUID_SIZE);
1777 	else
1778 		generate_random_uuid(tcp_ses->client_guid);
1779 	/*
1780 	 * at this point we are the only ones with the pointer
1781 	 * to the struct since the kernel thread not created yet
1782 	 * no need to spinlock this init of tcpStatus or srv_count
1783 	 */
1784 	tcp_ses->tcpStatus = CifsNew;
1785 	++tcp_ses->srv_count;
1786 
1787 	if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1788 		ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1789 		tcp_ses->echo_interval = ctx->echo_interval * HZ;
1790 	else
1791 		tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1792 	if (tcp_ses->rdma) {
1793 #ifndef CONFIG_CIFS_SMB_DIRECT
1794 		cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1795 		rc = -ENOENT;
1796 		goto out_err_crypto_release;
1797 #endif
1798 		tcp_ses->smbd_conn = smbd_get_connection(
1799 			tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1800 		if (tcp_ses->smbd_conn) {
1801 			cifs_dbg(VFS, "RDMA transport established\n");
1802 			rc = 0;
1803 			goto smbd_connected;
1804 		} else {
1805 			rc = -ENOENT;
1806 			goto out_err_crypto_release;
1807 		}
1808 	}
1809 	rc = ip_connect(tcp_ses);
1810 	if (rc < 0) {
1811 		cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1812 		goto out_err_crypto_release;
1813 	}
1814 smbd_connected:
1815 	/*
1816 	 * since we're in a cifs function already, we know that
1817 	 * this will succeed. No need for try_module_get().
1818 	 */
1819 	__module_get(THIS_MODULE);
1820 	tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1821 				  tcp_ses, "cifsd");
1822 	if (IS_ERR(tcp_ses->tsk)) {
1823 		rc = PTR_ERR(tcp_ses->tsk);
1824 		cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1825 		module_put(THIS_MODULE);
1826 		goto out_err_crypto_release;
1827 	}
1828 	tcp_ses->min_offload = ctx->min_offload;
1829 	tcp_ses->retrans = ctx->retrans;
1830 	/*
1831 	 * at this point we are the only ones with the pointer
1832 	 * to the struct since the kernel thread not created yet
1833 	 * no need to spinlock this update of tcpStatus
1834 	 */
1835 	spin_lock(&tcp_ses->srv_lock);
1836 	tcp_ses->tcpStatus = CifsNeedNegotiate;
1837 	spin_unlock(&tcp_ses->srv_lock);
1838 
1839 	if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1840 		tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1841 	else
1842 		tcp_ses->max_credits = ctx->max_credits;
1843 
1844 	tcp_ses->nr_targets = 1;
1845 	tcp_ses->ignore_signature = ctx->ignore_signature;
1846 	/* thread spawned, put it on the list */
1847 	spin_lock(&cifs_tcp_ses_lock);
1848 	list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1849 	spin_unlock(&cifs_tcp_ses_lock);
1850 
1851 	/* queue echo request delayed work */
1852 	queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1853 
1854 	return tcp_ses;
1855 
1856 out_err_crypto_release:
1857 	cifs_crypto_secmech_release(tcp_ses);
1858 
1859 	put_net(cifs_net_ns(tcp_ses));
1860 
1861 out_err:
1862 	if (tcp_ses) {
1863 		if (SERVER_IS_CHAN(tcp_ses))
1864 			cifs_put_tcp_session(tcp_ses->primary_server, false);
1865 		kfree(tcp_ses->hostname);
1866 		kfree(tcp_ses->leaf_fullpath);
1867 		if (tcp_ses->ssocket)
1868 			sock_release(tcp_ses->ssocket);
1869 		kfree(tcp_ses);
1870 	}
1871 	return ERR_PTR(rc);
1872 }
1873 
1874 /* this function must be called with ses_lock and chan_lock held */
match_session(struct cifs_ses * ses,struct smb3_fs_context * ctx)1875 static int match_session(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1876 {
1877 	struct TCP_Server_Info *server = ses->server;
1878 	enum securityEnum ctx_sec, ses_sec;
1879 
1880 	if (ctx->dfs_root_ses != ses->dfs_root_ses)
1881 		return 0;
1882 
1883 	/*
1884 	 * If an existing session is limited to less channels than
1885 	 * requested, it should not be reused
1886 	 */
1887 	if (ses->chan_max < ctx->max_channels)
1888 		return 0;
1889 
1890 	ctx_sec = server->ops->select_sectype(server, ctx->sectype);
1891 	ses_sec = server->ops->select_sectype(server, ses->sectype);
1892 
1893 	if (ctx_sec != ses_sec)
1894 		return 0;
1895 
1896 	switch (ctx_sec) {
1897 	case IAKerb:
1898 	case Kerberos:
1899 		if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1900 			return 0;
1901 		break;
1902 	case NTLMv2:
1903 	case RawNTLMSSP:
1904 	default:
1905 		/* NULL username means anonymous session */
1906 		if (ses->user_name == NULL) {
1907 			if (!ctx->nullauth)
1908 				return 0;
1909 			break;
1910 		}
1911 
1912 		/* anything else takes username/password */
1913 		if (strncmp(ses->user_name,
1914 			    ctx->username ? ctx->username : "",
1915 			    CIFS_MAX_USERNAME_LEN))
1916 			return 0;
1917 		if ((ctx->username && strlen(ctx->username) != 0) &&
1918 		    ses->password != NULL) {
1919 
1920 			/* New mount can only share sessions with an existing mount if:
1921 			 * 1. Both password and password2 match, or
1922 			 * 2. password2 of the old mount matches password of the new mount
1923 			 *    and password of the old mount matches password2 of the new
1924 			 *	  mount
1925 			 */
1926 			if (ses->password2 != NULL && ctx->password2 != NULL) {
1927 				if (!((strncmp(ses->password, ctx->password ?
1928 					ctx->password : "", CIFS_MAX_PASSWORD_LEN) == 0 &&
1929 					strncmp(ses->password2, ctx->password2,
1930 					CIFS_MAX_PASSWORD_LEN) == 0) ||
1931 					(strncmp(ses->password, ctx->password2,
1932 					CIFS_MAX_PASSWORD_LEN) == 0 &&
1933 					strncmp(ses->password2, ctx->password ?
1934 					ctx->password : "", CIFS_MAX_PASSWORD_LEN) == 0)))
1935 					return 0;
1936 
1937 			} else if ((ses->password2 == NULL && ctx->password2 != NULL) ||
1938 				(ses->password2 != NULL && ctx->password2 == NULL)) {
1939 				return 0;
1940 
1941 			} else {
1942 				if (strncmp(ses->password, ctx->password ?
1943 					ctx->password : "", CIFS_MAX_PASSWORD_LEN))
1944 					return 0;
1945 			}
1946 		}
1947 	}
1948 
1949 	if (strcmp(ctx->local_nls->charset, ses->local_nls->charset))
1950 		return 0;
1951 
1952 	return 1;
1953 }
1954 
1955 /**
1956  * cifs_setup_ipc - helper to setup the IPC tcon for the session
1957  * @ses: smb session to issue the request on
1958  * @ctx: the superblock configuration context to use for building the
1959  *       new tree connection for the IPC (interprocess communication RPC)
1960  *
1961  * A new IPC connection is made and stored in the session
1962  * tcon_ipc. The IPC tcon has the same lifetime as the session.
1963  */
1964 static int
cifs_setup_ipc(struct cifs_ses * ses,struct smb3_fs_context * ctx)1965 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1966 {
1967 	int rc = 0, xid;
1968 	struct cifs_tcon *tcon;
1969 	char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1970 	bool seal = false;
1971 	struct TCP_Server_Info *server = ses->server;
1972 
1973 	/*
1974 	 * If the mount request that resulted in the creation of the
1975 	 * session requires encryption, force IPC to be encrypted too.
1976 	 */
1977 	if (ctx->seal) {
1978 		if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
1979 			seal = true;
1980 		else {
1981 			cifs_server_dbg(VFS,
1982 				 "IPC: server doesn't support encryption\n");
1983 			return -EOPNOTSUPP;
1984 		}
1985 	}
1986 
1987 	/* no need to setup directory caching on IPC share, so pass in false */
1988 	tcon = tcon_info_alloc(false, netfs_trace_tcon_ref_new_ipc);
1989 	if (tcon == NULL)
1990 		return -ENOMEM;
1991 
1992 	spin_lock(&server->srv_lock);
1993 	scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
1994 	spin_unlock(&server->srv_lock);
1995 
1996 	xid = get_xid();
1997 	tcon->ses = ses;
1998 	tcon->ipc = true;
1999 	tcon->seal = seal;
2000 	rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
2001 	free_xid(xid);
2002 
2003 	if (rc) {
2004 		cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
2005 		tconInfoFree(tcon, netfs_trace_tcon_ref_free_ipc_fail);
2006 		goto out;
2007 	}
2008 
2009 	cifs_dbg(FYI, "IPC tcon rc=%d ipc tid=0x%x\n", rc, tcon->tid);
2010 
2011 	spin_lock(&tcon->tc_lock);
2012 	tcon->status = TID_GOOD;
2013 	spin_unlock(&tcon->tc_lock);
2014 	ses->tcon_ipc = tcon;
2015 out:
2016 	return rc;
2017 }
2018 
2019 static struct cifs_ses *
cifs_find_smb_ses(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)2020 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2021 {
2022 	struct cifs_ses *ses, *ret = NULL;
2023 
2024 	spin_lock(&cifs_tcp_ses_lock);
2025 	list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
2026 		spin_lock(&ses->ses_lock);
2027 		if (ses->ses_status == SES_EXITING) {
2028 			spin_unlock(&ses->ses_lock);
2029 			continue;
2030 		}
2031 		spin_lock(&ses->chan_lock);
2032 		if (match_session(ses, ctx)) {
2033 			spin_unlock(&ses->chan_lock);
2034 			spin_unlock(&ses->ses_lock);
2035 			ret = ses;
2036 			break;
2037 		}
2038 		spin_unlock(&ses->chan_lock);
2039 		spin_unlock(&ses->ses_lock);
2040 	}
2041 	if (ret)
2042 		cifs_smb_ses_inc_refcount(ret);
2043 	spin_unlock(&cifs_tcp_ses_lock);
2044 	return ret;
2045 }
2046 
__cifs_put_smb_ses(struct cifs_ses * ses)2047 void __cifs_put_smb_ses(struct cifs_ses *ses)
2048 {
2049 	struct TCP_Server_Info *server = ses->server;
2050 	struct cifs_tcon *tcon;
2051 	unsigned int xid;
2052 	size_t i;
2053 	bool do_logoff;
2054 	int rc;
2055 
2056 	spin_lock(&cifs_tcp_ses_lock);
2057 	spin_lock(&ses->ses_lock);
2058 	cifs_dbg(FYI, "%s: id=0x%llx ses_count=%d ses_status=%u ipc=%s\n",
2059 		 __func__, ses->Suid, ses->ses_count, ses->ses_status,
2060 		 ses->tcon_ipc ? ses->tcon_ipc->tree_name : "none");
2061 	if (ses->ses_status == SES_EXITING || --ses->ses_count > 0) {
2062 		spin_unlock(&ses->ses_lock);
2063 		spin_unlock(&cifs_tcp_ses_lock);
2064 		return;
2065 	}
2066 	/* ses_count can never go negative */
2067 	WARN_ON(ses->ses_count < 0);
2068 
2069 	spin_lock(&ses->chan_lock);
2070 	cifs_chan_clear_need_reconnect(ses, server);
2071 	spin_unlock(&ses->chan_lock);
2072 
2073 	do_logoff = ses->ses_status == SES_GOOD && server->ops->logoff;
2074 	ses->ses_status = SES_EXITING;
2075 	tcon = ses->tcon_ipc;
2076 	ses->tcon_ipc = NULL;
2077 	spin_unlock(&ses->ses_lock);
2078 	spin_unlock(&cifs_tcp_ses_lock);
2079 
2080 	/*
2081 	 * On session close, the IPC is closed and the server must release all
2082 	 * tcons of the session.  No need to send a tree disconnect here.
2083 	 *
2084 	 * Besides, it will make the server to not close durable and resilient
2085 	 * files on session close, as specified in MS-SMB2 3.3.5.6 Receiving an
2086 	 * SMB2 LOGOFF Request.
2087 	 */
2088 	tconInfoFree(tcon, netfs_trace_tcon_ref_free_ipc);
2089 	if (do_logoff) {
2090 		xid = get_xid();
2091 		rc = server->ops->logoff(xid, ses);
2092 		if (rc)
2093 			cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
2094 				__func__, rc);
2095 		_free_xid(xid);
2096 	}
2097 
2098 	spin_lock(&cifs_tcp_ses_lock);
2099 	list_del_init(&ses->smb_ses_list);
2100 	spin_unlock(&cifs_tcp_ses_lock);
2101 
2102 	/* close any extra channels */
2103 	for (i = 1; i < ses->chan_count; i++) {
2104 		if (ses->chans[i].iface) {
2105 			kref_put(&ses->chans[i].iface->refcount, release_iface);
2106 			ses->chans[i].iface = NULL;
2107 		}
2108 		cifs_put_tcp_session(ses->chans[i].server, 0);
2109 		ses->chans[i].server = NULL;
2110 	}
2111 
2112 	/* we now account for primary channel in iface->refcount */
2113 	if (ses->chans[0].iface) {
2114 		kref_put(&ses->chans[0].iface->refcount, release_iface);
2115 		ses->chans[0].server = NULL;
2116 	}
2117 
2118 	sesInfoFree(ses);
2119 	cifs_put_tcp_session(server, 0);
2120 }
2121 
2122 #ifdef CONFIG_KEYS
2123 
2124 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
2125 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
2126 
2127 /* Populate username and pw fields from keyring if possible */
2128 static int
cifs_set_cifscreds(struct smb3_fs_context * ctx,struct cifs_ses * ses)2129 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
2130 {
2131 	int rc = 0;
2132 	int is_domain = 0;
2133 	const char *delim, *payload;
2134 	char *desc;
2135 	ssize_t len;
2136 	struct key *key;
2137 	struct TCP_Server_Info *server = ses->server;
2138 	struct sockaddr_in *sa;
2139 	struct sockaddr_in6 *sa6;
2140 	const struct user_key_payload *upayload;
2141 
2142 	desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
2143 	if (!desc)
2144 		return -ENOMEM;
2145 
2146 	/* try to find an address key first */
2147 	switch (server->dstaddr.ss_family) {
2148 	case AF_INET:
2149 		sa = (struct sockaddr_in *)&server->dstaddr;
2150 		sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
2151 		break;
2152 	case AF_INET6:
2153 		sa6 = (struct sockaddr_in6 *)&server->dstaddr;
2154 		sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
2155 		break;
2156 	default:
2157 		cifs_dbg(FYI, "Bad ss_family (%hu)\n",
2158 			 server->dstaddr.ss_family);
2159 		rc = -EINVAL;
2160 		goto out_err;
2161 	}
2162 
2163 	cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2164 	key = request_key(&key_type_logon, desc, "");
2165 	if (IS_ERR(key)) {
2166 		if (!ses->domainName) {
2167 			cifs_dbg(FYI, "domainName is NULL\n");
2168 			rc = PTR_ERR(key);
2169 			goto out_err;
2170 		}
2171 
2172 		/* didn't work, try to find a domain key */
2173 		sprintf(desc, "cifs:d:%s", ses->domainName);
2174 		cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2175 		key = request_key(&key_type_logon, desc, "");
2176 		if (IS_ERR(key)) {
2177 			rc = PTR_ERR(key);
2178 			goto out_err;
2179 		}
2180 		is_domain = 1;
2181 	}
2182 
2183 	down_read(&key->sem);
2184 	upayload = user_key_payload_locked(key);
2185 	if (IS_ERR_OR_NULL(upayload)) {
2186 		rc = upayload ? PTR_ERR(upayload) : -EINVAL;
2187 		goto out_key_put;
2188 	}
2189 
2190 	/* find first : in payload */
2191 	payload = upayload->data;
2192 	delim = strnchr(payload, upayload->datalen, ':');
2193 	cifs_dbg(FYI, "payload=%s\n", payload);
2194 	if (!delim) {
2195 		cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
2196 			 upayload->datalen);
2197 		rc = -EINVAL;
2198 		goto out_key_put;
2199 	}
2200 
2201 	len = delim - payload;
2202 	if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
2203 		cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
2204 			 len);
2205 		rc = -EINVAL;
2206 		goto out_key_put;
2207 	}
2208 
2209 	ctx->username = kstrndup(payload, len, GFP_KERNEL);
2210 	if (!ctx->username) {
2211 		cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
2212 			 len);
2213 		rc = -ENOMEM;
2214 		goto out_key_put;
2215 	}
2216 	cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
2217 
2218 	len = key->datalen - (len + 1);
2219 	if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
2220 		cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
2221 		rc = -EINVAL;
2222 		kfree(ctx->username);
2223 		ctx->username = NULL;
2224 		goto out_key_put;
2225 	}
2226 
2227 	++delim;
2228 	/* BB consider adding support for password2 (Key Rotation) for multiuser in future */
2229 	ctx->password = kstrndup(delim, len, GFP_KERNEL);
2230 	if (!ctx->password) {
2231 		cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
2232 			 len);
2233 		rc = -ENOMEM;
2234 		kfree(ctx->username);
2235 		ctx->username = NULL;
2236 		goto out_key_put;
2237 	}
2238 
2239 	/*
2240 	 * If we have a domain key then we must set the domainName in the
2241 	 * for the request.
2242 	 */
2243 	if (is_domain && ses->domainName) {
2244 		ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
2245 		if (!ctx->domainname) {
2246 			cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
2247 				 len);
2248 			rc = -ENOMEM;
2249 			kfree(ctx->username);
2250 			ctx->username = NULL;
2251 			kfree_sensitive(ctx->password);
2252 			/* no need to free ctx->password2 since not allocated in this path */
2253 			ctx->password = NULL;
2254 			goto out_key_put;
2255 		}
2256 	}
2257 
2258 	strscpy(ctx->workstation_name, ses->workstation_name, sizeof(ctx->workstation_name));
2259 
2260 out_key_put:
2261 	up_read(&key->sem);
2262 	key_put(key);
2263 out_err:
2264 	kfree(desc);
2265 	cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2266 	return rc;
2267 }
2268 #else /* ! CONFIG_KEYS */
2269 static inline int
cifs_set_cifscreds(struct smb3_fs_context * ctx,struct cifs_ses * ses)2270 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
2271 		   struct cifs_ses *ses __attribute__((unused)))
2272 {
2273 	return -ENOSYS;
2274 }
2275 #endif /* CONFIG_KEYS */
2276 
2277 /**
2278  * cifs_get_smb_ses - get a session matching @ctx data from @server
2279  * @server: server to setup the session to
2280  * @ctx: superblock configuration context to use to setup the session
2281  *
2282  * This function assumes it is being called from cifs_mount() where we
2283  * already got a server reference (server refcount +1). See
2284  * cifs_get_tcon() for refcount explanations.
2285  */
2286 struct cifs_ses *
cifs_get_smb_ses(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)2287 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2288 {
2289 	int rc = 0;
2290 	int retries = 0;
2291 	unsigned int xid;
2292 	struct cifs_ses *ses;
2293 	struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2294 	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2295 
2296 	xid = get_xid();
2297 
2298 	ses = cifs_find_smb_ses(server, ctx);
2299 	if (ses) {
2300 		cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2301 			 ses->ses_status);
2302 
2303 		spin_lock(&ses->chan_lock);
2304 		if (cifs_chan_needs_reconnect(ses, server)) {
2305 			spin_unlock(&ses->chan_lock);
2306 			cifs_dbg(FYI, "Session needs reconnect\n");
2307 
2308 			mutex_lock(&ses->session_mutex);
2309 
2310 retry_old_session:
2311 			rc = cifs_negotiate_protocol(xid, ses, server);
2312 			if (rc) {
2313 				mutex_unlock(&ses->session_mutex);
2314 				/* problem -- put our ses reference */
2315 				cifs_put_smb_ses(ses);
2316 				free_xid(xid);
2317 				return ERR_PTR(rc);
2318 			}
2319 
2320 			rc = cifs_setup_session(xid, ses, server,
2321 						ctx->local_nls);
2322 			if (rc) {
2323 				if (((rc == -EACCES) || (rc == -EKEYEXPIRED) ||
2324 					(rc == -EKEYREVOKED)) && !retries && ses->password2) {
2325 					retries++;
2326 					cifs_dbg(FYI, "Session reconnect failed, retrying with alternate password\n");
2327 					swap(ses->password, ses->password2);
2328 					goto retry_old_session;
2329 				}
2330 				mutex_unlock(&ses->session_mutex);
2331 				/* problem -- put our reference */
2332 				cifs_put_smb_ses(ses);
2333 				free_xid(xid);
2334 				return ERR_PTR(rc);
2335 			}
2336 			mutex_unlock(&ses->session_mutex);
2337 
2338 			spin_lock(&ses->chan_lock);
2339 		}
2340 		spin_unlock(&ses->chan_lock);
2341 
2342 		/* existing SMB ses has a server reference already */
2343 		cifs_put_tcp_session(server, 0);
2344 		free_xid(xid);
2345 		return ses;
2346 	}
2347 
2348 	rc = -ENOMEM;
2349 
2350 	cifs_dbg(FYI, "Existing smb sess not found\n");
2351 	ses = sesInfoAlloc();
2352 	if (ses == NULL)
2353 		goto get_ses_fail;
2354 
2355 	/* new SMB session uses our server ref */
2356 	ses->server = server;
2357 	if (server->dstaddr.ss_family == AF_INET6)
2358 		sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2359 	else
2360 		sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2361 
2362 	if (ctx->username) {
2363 		ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2364 		if (!ses->user_name)
2365 			goto get_ses_fail;
2366 	}
2367 
2368 	/* ctx->password freed at unmount */
2369 	if (ctx->password) {
2370 		ses->password = kstrdup(ctx->password, GFP_KERNEL);
2371 		if (!ses->password)
2372 			goto get_ses_fail;
2373 	}
2374 	/* ctx->password freed at unmount */
2375 	if (ctx->password2) {
2376 		ses->password2 = kstrdup(ctx->password2, GFP_KERNEL);
2377 		if (!ses->password2)
2378 			goto get_ses_fail;
2379 	}
2380 	if (ctx->domainname) {
2381 		ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2382 		if (!ses->domainName)
2383 			goto get_ses_fail;
2384 	}
2385 
2386 	strscpy(ses->workstation_name, ctx->workstation_name, sizeof(ses->workstation_name));
2387 
2388 	if (ctx->domainauto)
2389 		ses->domainAuto = ctx->domainauto;
2390 	ses->cred_uid = ctx->cred_uid;
2391 	ses->linux_uid = ctx->linux_uid;
2392 
2393 	ses->sectype = ctx->sectype;
2394 	ses->sign = ctx->sign;
2395 	ses->local_nls = load_nls(ctx->local_nls->charset);
2396 
2397 	/* add server as first channel */
2398 	spin_lock(&ses->chan_lock);
2399 	ses->chans[0].server = server;
2400 	ses->chan_count = 1;
2401 	ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2402 	ses->chans_need_reconnect = 1;
2403 	spin_unlock(&ses->chan_lock);
2404 
2405 retry_new_session:
2406 	mutex_lock(&ses->session_mutex);
2407 	rc = cifs_negotiate_protocol(xid, ses, server);
2408 	if (!rc)
2409 		rc = cifs_setup_session(xid, ses, server, ctx->local_nls);
2410 	mutex_unlock(&ses->session_mutex);
2411 
2412 	/* each channel uses a different signing key */
2413 	spin_lock(&ses->chan_lock);
2414 	memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2415 	       sizeof(ses->smb3signingkey));
2416 	spin_unlock(&ses->chan_lock);
2417 
2418 	if (rc) {
2419 		if (((rc == -EACCES) || (rc == -EKEYEXPIRED) ||
2420 			(rc == -EKEYREVOKED)) && !retries && ses->password2) {
2421 			retries++;
2422 			cifs_dbg(FYI, "Session setup failed, retrying with alternate password\n");
2423 			swap(ses->password, ses->password2);
2424 			goto retry_new_session;
2425 		} else
2426 			goto get_ses_fail;
2427 	}
2428 
2429 	/*
2430 	 * success, put it on the list and add it as first channel
2431 	 * note: the session becomes active soon after this. So you'll
2432 	 * need to lock before changing something in the session.
2433 	 */
2434 	spin_lock(&cifs_tcp_ses_lock);
2435 	if (ctx->dfs_root_ses)
2436 		cifs_smb_ses_inc_refcount(ctx->dfs_root_ses);
2437 	ses->dfs_root_ses = ctx->dfs_root_ses;
2438 	list_add(&ses->smb_ses_list, &server->smb_ses_list);
2439 	spin_unlock(&cifs_tcp_ses_lock);
2440 
2441 	cifs_setup_ipc(ses, ctx);
2442 
2443 	free_xid(xid);
2444 
2445 	return ses;
2446 
2447 get_ses_fail:
2448 	sesInfoFree(ses);
2449 	free_xid(xid);
2450 	return ERR_PTR(rc);
2451 }
2452 
2453 /* this function must be called with tc_lock held */
match_tcon(struct cifs_tcon * tcon,struct smb3_fs_context * ctx)2454 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2455 {
2456 	struct TCP_Server_Info *server = tcon->ses->server;
2457 
2458 	if (tcon->status == TID_EXITING)
2459 		return 0;
2460 
2461 	if (tcon->origin_fullpath) {
2462 		if (!ctx->source ||
2463 		    !dfs_src_pathname_equal(ctx->source,
2464 					    tcon->origin_fullpath))
2465 			return 0;
2466 	} else if (!server->leaf_fullpath &&
2467 		   strncmp(tcon->tree_name, ctx->UNC, MAX_TREE_SIZE)) {
2468 		return 0;
2469 	}
2470 	if (tcon->seal != ctx->seal)
2471 		return 0;
2472 	if (tcon->snapshot_time != ctx->snapshot_time)
2473 		return 0;
2474 	if (tcon->handle_timeout != ctx->handle_timeout)
2475 		return 0;
2476 	if (tcon->no_lease != ctx->no_lease)
2477 		return 0;
2478 	if (tcon->nodelete != ctx->nodelete)
2479 		return 0;
2480 	if (tcon->posix_extensions != ctx->linux_ext)
2481 		return 0;
2482 	return 1;
2483 }
2484 
2485 static struct cifs_tcon *
cifs_find_tcon(struct cifs_ses * ses,struct smb3_fs_context * ctx)2486 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2487 {
2488 	struct cifs_tcon *tcon;
2489 
2490 	spin_lock(&cifs_tcp_ses_lock);
2491 	list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2492 		spin_lock(&tcon->tc_lock);
2493 		if (!match_tcon(tcon, ctx)) {
2494 			spin_unlock(&tcon->tc_lock);
2495 			continue;
2496 		}
2497 		++tcon->tc_count;
2498 		trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count,
2499 				    netfs_trace_tcon_ref_get_find);
2500 		spin_unlock(&tcon->tc_lock);
2501 		spin_unlock(&cifs_tcp_ses_lock);
2502 		return tcon;
2503 	}
2504 	spin_unlock(&cifs_tcp_ses_lock);
2505 	return NULL;
2506 }
2507 
2508 void
cifs_put_tcon(struct cifs_tcon * tcon,enum smb3_tcon_ref_trace trace)2509 cifs_put_tcon(struct cifs_tcon *tcon, enum smb3_tcon_ref_trace trace)
2510 {
2511 	unsigned int xid;
2512 	struct cifs_ses *ses;
2513 
2514 	/*
2515 	 * IPC tcon share the lifetime of their session and are
2516 	 * destroyed in the session put function
2517 	 */
2518 	if (tcon == NULL || tcon->ipc)
2519 		return;
2520 
2521 	ses = tcon->ses;
2522 	cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2523 	spin_lock(&cifs_tcp_ses_lock);
2524 	spin_lock(&tcon->tc_lock);
2525 	trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count - 1, trace);
2526 	if (--tcon->tc_count > 0) {
2527 		spin_unlock(&tcon->tc_lock);
2528 		spin_unlock(&cifs_tcp_ses_lock);
2529 		return;
2530 	}
2531 
2532 	/* tc_count can never go negative */
2533 	WARN_ON(tcon->tc_count < 0);
2534 
2535 	list_del_init(&tcon->tcon_list);
2536 	tcon->status = TID_EXITING;
2537 	spin_unlock(&tcon->tc_lock);
2538 	spin_unlock(&cifs_tcp_ses_lock);
2539 
2540 	/* cancel polling of interfaces */
2541 	cancel_delayed_work_sync(&tcon->query_interfaces);
2542 #ifdef CONFIG_CIFS_DFS_UPCALL
2543 	cancel_delayed_work_sync(&tcon->dfs_cache_work);
2544 #endif
2545 
2546 	if (tcon->use_witness) {
2547 		int rc;
2548 
2549 		rc = cifs_swn_unregister(tcon);
2550 		if (rc < 0) {
2551 			cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2552 					__func__, rc);
2553 		}
2554 	}
2555 
2556 	xid = get_xid();
2557 	if (ses->server->ops->tree_disconnect)
2558 		ses->server->ops->tree_disconnect(xid, tcon);
2559 	_free_xid(xid);
2560 
2561 	cifs_fscache_release_super_cookie(tcon);
2562 	tconInfoFree(tcon, netfs_trace_tcon_ref_free);
2563 	cifs_put_smb_ses(ses);
2564 }
2565 
2566 /**
2567  * cifs_get_tcon - get a tcon matching @ctx data from @ses
2568  * @ses: smb session to issue the request on
2569  * @ctx: the superblock configuration context to use for building the
2570  *
2571  * - tcon refcount is the number of mount points using the tcon.
2572  * - ses refcount is the number of tcon using the session.
2573  *
2574  * 1. This function assumes it is being called from cifs_mount() where
2575  *    we already got a session reference (ses refcount +1).
2576  *
2577  * 2. Since we're in the context of adding a mount point, the end
2578  *    result should be either:
2579  *
2580  * a) a new tcon already allocated with refcount=1 (1 mount point) and
2581  *    its session refcount incremented (1 new tcon). This +1 was
2582  *    already done in (1).
2583  *
2584  * b) an existing tcon with refcount+1 (add a mount point to it) and
2585  *    identical ses refcount (no new tcon). Because of (1) we need to
2586  *    decrement the ses refcount.
2587  */
2588 static struct cifs_tcon *
cifs_get_tcon(struct cifs_ses * ses,struct smb3_fs_context * ctx)2589 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2590 {
2591 	struct cifs_tcon *tcon;
2592 	bool nohandlecache;
2593 	int rc, xid;
2594 
2595 	tcon = cifs_find_tcon(ses, ctx);
2596 	if (tcon) {
2597 		/*
2598 		 * tcon has refcount already incremented but we need to
2599 		 * decrement extra ses reference gotten by caller (case b)
2600 		 */
2601 		cifs_dbg(FYI, "Found match on UNC path\n");
2602 		cifs_put_smb_ses(ses);
2603 		return tcon;
2604 	}
2605 
2606 	if (!ses->server->ops->tree_connect) {
2607 		rc = -ENOSYS;
2608 		goto out_fail;
2609 	}
2610 
2611 	if (ses->server->dialect >= SMB20_PROT_ID &&
2612 	    (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING))
2613 		nohandlecache = ctx->nohandlecache || !dir_cache_timeout;
2614 	else
2615 		nohandlecache = true;
2616 	tcon = tcon_info_alloc(!nohandlecache, netfs_trace_tcon_ref_new);
2617 	if (tcon == NULL) {
2618 		rc = -ENOMEM;
2619 		goto out_fail;
2620 	}
2621 	tcon->nohandlecache = nohandlecache;
2622 
2623 	if (ctx->snapshot_time) {
2624 		if (ses->server->vals->protocol_id == 0) {
2625 			cifs_dbg(VFS,
2626 			     "Use SMB2 or later for snapshot mount option\n");
2627 			rc = -EOPNOTSUPP;
2628 			goto out_fail;
2629 		} else
2630 			tcon->snapshot_time = ctx->snapshot_time;
2631 	}
2632 
2633 	if (ctx->handle_timeout) {
2634 		if (ses->server->vals->protocol_id == 0) {
2635 			cifs_dbg(VFS,
2636 			     "Use SMB2.1 or later for handle timeout option\n");
2637 			rc = -EOPNOTSUPP;
2638 			goto out_fail;
2639 		} else
2640 			tcon->handle_timeout = ctx->handle_timeout;
2641 	}
2642 
2643 	tcon->ses = ses;
2644 	if (ctx->password) {
2645 		tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2646 		if (!tcon->password) {
2647 			rc = -ENOMEM;
2648 			goto out_fail;
2649 		}
2650 	}
2651 
2652 	if (ctx->seal) {
2653 		if (ses->server->vals->protocol_id == 0) {
2654 			cifs_dbg(VFS,
2655 				 "SMB3 or later required for encryption\n");
2656 			rc = -EOPNOTSUPP;
2657 			goto out_fail;
2658 		} else if (tcon->ses->server->capabilities &
2659 					SMB2_GLOBAL_CAP_ENCRYPTION)
2660 			tcon->seal = true;
2661 		else {
2662 			cifs_dbg(VFS, "Encryption is not supported on share\n");
2663 			rc = -EOPNOTSUPP;
2664 			goto out_fail;
2665 		}
2666 	}
2667 
2668 	if (ctx->linux_ext) {
2669 		if (ses->server->posix_ext_supported) {
2670 			tcon->posix_extensions = true;
2671 			pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2672 		} else if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
2673 		    (strcmp(ses->server->vals->version_string,
2674 		     SMB3ANY_VERSION_STRING) == 0) ||
2675 		    (strcmp(ses->server->vals->version_string,
2676 		     SMBDEFAULT_VERSION_STRING) == 0)) {
2677 			cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2678 			rc = -EOPNOTSUPP;
2679 			goto out_fail;
2680 		} else if (ses->server->vals->protocol_id == SMB10_PROT_ID)
2681 			if (cap_unix(ses))
2682 				cifs_dbg(FYI, "Unix Extensions requested on SMB1 mount\n");
2683 			else {
2684 				cifs_dbg(VFS, "SMB1 Unix Extensions not supported by server\n");
2685 				rc = -EOPNOTSUPP;
2686 				goto out_fail;
2687 		} else {
2688 			cifs_dbg(VFS,
2689 				"Check vers= mount option. SMB3.11 disabled but required for POSIX extensions\n");
2690 			rc = -EOPNOTSUPP;
2691 			goto out_fail;
2692 		}
2693 	}
2694 
2695 	xid = get_xid();
2696 	rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2697 					    ctx->local_nls);
2698 	free_xid(xid);
2699 	cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2700 	if (rc)
2701 		goto out_fail;
2702 
2703 	tcon->use_persistent = false;
2704 	/* check if SMB2 or later, CIFS does not support persistent handles */
2705 	if (ctx->persistent) {
2706 		if (ses->server->vals->protocol_id == 0) {
2707 			cifs_dbg(VFS,
2708 			     "SMB3 or later required for persistent handles\n");
2709 			rc = -EOPNOTSUPP;
2710 			goto out_fail;
2711 		} else if (ses->server->capabilities &
2712 			   SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2713 			tcon->use_persistent = true;
2714 		else /* persistent handles requested but not supported */ {
2715 			cifs_dbg(VFS,
2716 				"Persistent handles not supported on share\n");
2717 			rc = -EOPNOTSUPP;
2718 			goto out_fail;
2719 		}
2720 	} else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2721 	     && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2722 	     && (ctx->nopersistent == false)) {
2723 		cifs_dbg(FYI, "enabling persistent handles\n");
2724 		tcon->use_persistent = true;
2725 	} else if (ctx->resilient) {
2726 		if (ses->server->vals->protocol_id == 0) {
2727 			cifs_dbg(VFS,
2728 			     "SMB2.1 or later required for resilient handles\n");
2729 			rc = -EOPNOTSUPP;
2730 			goto out_fail;
2731 		}
2732 		tcon->use_resilient = true;
2733 	}
2734 
2735 	tcon->use_witness = false;
2736 	if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2737 		if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2738 			if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2739 				/*
2740 				 * Set witness in use flag in first place
2741 				 * to retry registration in the echo task
2742 				 */
2743 				tcon->use_witness = true;
2744 				/* And try to register immediately */
2745 				rc = cifs_swn_register(tcon);
2746 				if (rc < 0) {
2747 					cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2748 					goto out_fail;
2749 				}
2750 			} else {
2751 				/* TODO: try to extend for non-cluster uses (eg multichannel) */
2752 				cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2753 				rc = -EOPNOTSUPP;
2754 				goto out_fail;
2755 			}
2756 		} else {
2757 			cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2758 			rc = -EOPNOTSUPP;
2759 			goto out_fail;
2760 		}
2761 	}
2762 
2763 	/* If the user really knows what they are doing they can override */
2764 	if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2765 		if (ctx->cache_ro)
2766 			cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2767 		else if (ctx->cache_rw)
2768 			cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2769 	}
2770 
2771 	if (ctx->no_lease) {
2772 		if (ses->server->vals->protocol_id == 0) {
2773 			cifs_dbg(VFS,
2774 				"SMB2 or later required for nolease option\n");
2775 			rc = -EOPNOTSUPP;
2776 			goto out_fail;
2777 		} else
2778 			tcon->no_lease = ctx->no_lease;
2779 	}
2780 
2781 	/*
2782 	 * We can have only one retry value for a connection to a share so for
2783 	 * resources mounted more than once to the same server share the last
2784 	 * value passed in for the retry flag is used.
2785 	 */
2786 	tcon->retry = ctx->retry;
2787 	tcon->nocase = ctx->nocase;
2788 	tcon->broken_sparse_sup = ctx->no_sparse;
2789 	tcon->max_cached_dirs = ctx->max_cached_dirs;
2790 	tcon->nodelete = ctx->nodelete;
2791 	tcon->local_lease = ctx->local_lease;
2792 	INIT_LIST_HEAD(&tcon->pending_opens);
2793 	tcon->status = TID_GOOD;
2794 
2795 	INIT_DELAYED_WORK(&tcon->query_interfaces,
2796 			  smb2_query_server_interfaces);
2797 	if (ses->server->dialect >= SMB30_PROT_ID &&
2798 	    (ses->server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
2799 		/* schedule query interfaces poll */
2800 		queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
2801 				   (SMB_INTERFACE_POLL_INTERVAL * HZ));
2802 	}
2803 #ifdef CONFIG_CIFS_DFS_UPCALL
2804 	INIT_DELAYED_WORK(&tcon->dfs_cache_work, dfs_cache_refresh);
2805 #endif
2806 	spin_lock(&cifs_tcp_ses_lock);
2807 	list_add(&tcon->tcon_list, &ses->tcon_list);
2808 	spin_unlock(&cifs_tcp_ses_lock);
2809 
2810 	return tcon;
2811 
2812 out_fail:
2813 	tconInfoFree(tcon, netfs_trace_tcon_ref_free_fail);
2814 	return ERR_PTR(rc);
2815 }
2816 
2817 void
cifs_put_tlink(struct tcon_link * tlink)2818 cifs_put_tlink(struct tcon_link *tlink)
2819 {
2820 	if (!tlink || IS_ERR(tlink))
2821 		return;
2822 
2823 	if (!atomic_dec_and_test(&tlink->tl_count) ||
2824 	    test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2825 		tlink->tl_time = jiffies;
2826 		return;
2827 	}
2828 
2829 	if (!IS_ERR(tlink_tcon(tlink)))
2830 		cifs_put_tcon(tlink_tcon(tlink), netfs_trace_tcon_ref_put_tlink);
2831 	kfree(tlink);
2832 }
2833 
2834 static int
compare_mount_options(struct super_block * sb,struct cifs_mnt_data * mnt_data)2835 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2836 {
2837 	struct cifs_sb_info *old = CIFS_SB(sb);
2838 	struct cifs_sb_info *new = mnt_data->cifs_sb;
2839 	unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2840 	unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2841 
2842 	if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2843 		return 0;
2844 
2845 	if (old->mnt_cifs_serverino_autodisabled)
2846 		newflags &= ~CIFS_MOUNT_SERVER_INUM;
2847 
2848 	if (oldflags != newflags)
2849 		return 0;
2850 
2851 	/*
2852 	 * We want to share sb only if we don't specify an r/wsize or
2853 	 * specified r/wsize is greater than or equal to existing one.
2854 	 */
2855 	if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2856 		return 0;
2857 
2858 	if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2859 		return 0;
2860 
2861 	if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2862 	    !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2863 		return 0;
2864 
2865 	if (old->ctx->file_mode != new->ctx->file_mode ||
2866 	    old->ctx->dir_mode != new->ctx->dir_mode)
2867 		return 0;
2868 
2869 	if (strcmp(old->local_nls->charset, new->local_nls->charset))
2870 		return 0;
2871 
2872 	if (old->ctx->acregmax != new->ctx->acregmax)
2873 		return 0;
2874 	if (old->ctx->acdirmax != new->ctx->acdirmax)
2875 		return 0;
2876 	if (old->ctx->closetimeo != new->ctx->closetimeo)
2877 		return 0;
2878 	if (old->ctx->reparse_type != new->ctx->reparse_type)
2879 		return 0;
2880 
2881 	return 1;
2882 }
2883 
match_prepath(struct super_block * sb,struct cifs_tcon * tcon,struct cifs_mnt_data * mnt_data)2884 static int match_prepath(struct super_block *sb,
2885 			 struct cifs_tcon *tcon,
2886 			 struct cifs_mnt_data *mnt_data)
2887 {
2888 	struct smb3_fs_context *ctx = mnt_data->ctx;
2889 	struct cifs_sb_info *old = CIFS_SB(sb);
2890 	struct cifs_sb_info *new = mnt_data->cifs_sb;
2891 	bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2892 		old->prepath;
2893 	bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2894 		new->prepath;
2895 
2896 	if (tcon->origin_fullpath &&
2897 	    dfs_src_pathname_equal(tcon->origin_fullpath, ctx->source))
2898 		return 1;
2899 
2900 	if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2901 		return 1;
2902 	else if (!old_set && !new_set)
2903 		return 1;
2904 
2905 	return 0;
2906 }
2907 
2908 int
cifs_match_super(struct super_block * sb,void * data)2909 cifs_match_super(struct super_block *sb, void *data)
2910 {
2911 	struct cifs_mnt_data *mnt_data = data;
2912 	struct smb3_fs_context *ctx;
2913 	struct cifs_sb_info *cifs_sb;
2914 	struct TCP_Server_Info *tcp_srv;
2915 	struct cifs_ses *ses;
2916 	struct cifs_tcon *tcon;
2917 	struct tcon_link *tlink;
2918 	int rc = 0;
2919 
2920 	spin_lock(&cifs_tcp_ses_lock);
2921 	cifs_sb = CIFS_SB(sb);
2922 
2923 	/* We do not want to use a superblock that has been shutdown */
2924 	if (CIFS_MOUNT_SHUTDOWN & cifs_sb->mnt_cifs_flags) {
2925 		spin_unlock(&cifs_tcp_ses_lock);
2926 		return 0;
2927 	}
2928 
2929 	tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2930 	if (IS_ERR_OR_NULL(tlink)) {
2931 		pr_warn_once("%s: skip super matching due to bad tlink(%p)\n",
2932 			     __func__, tlink);
2933 		spin_unlock(&cifs_tcp_ses_lock);
2934 		return 0;
2935 	}
2936 	tcon = tlink_tcon(tlink);
2937 	ses = tcon->ses;
2938 	tcp_srv = ses->server;
2939 
2940 	ctx = mnt_data->ctx;
2941 
2942 	spin_lock(&tcp_srv->srv_lock);
2943 	spin_lock(&ses->ses_lock);
2944 	spin_lock(&ses->chan_lock);
2945 	spin_lock(&tcon->tc_lock);
2946 	if (!match_server(tcp_srv, ctx, true) ||
2947 	    !match_session(ses, ctx) ||
2948 	    !match_tcon(tcon, ctx) ||
2949 	    !match_prepath(sb, tcon, mnt_data)) {
2950 		rc = 0;
2951 		goto out;
2952 	}
2953 
2954 	rc = compare_mount_options(sb, mnt_data);
2955 out:
2956 	spin_unlock(&tcon->tc_lock);
2957 	spin_unlock(&ses->chan_lock);
2958 	spin_unlock(&ses->ses_lock);
2959 	spin_unlock(&tcp_srv->srv_lock);
2960 
2961 	spin_unlock(&cifs_tcp_ses_lock);
2962 	cifs_put_tlink(tlink);
2963 	return rc;
2964 }
2965 
2966 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2967 static struct lock_class_key cifs_key[2];
2968 static struct lock_class_key cifs_slock_key[2];
2969 
2970 static inline void
cifs_reclassify_socket4(struct socket * sock)2971 cifs_reclassify_socket4(struct socket *sock)
2972 {
2973 	struct sock *sk = sock->sk;
2974 
2975 	BUG_ON(!sock_allow_reclassification(sk));
2976 	sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2977 		&cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2978 }
2979 
2980 static inline void
cifs_reclassify_socket6(struct socket * sock)2981 cifs_reclassify_socket6(struct socket *sock)
2982 {
2983 	struct sock *sk = sock->sk;
2984 
2985 	BUG_ON(!sock_allow_reclassification(sk));
2986 	sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
2987 		&cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
2988 }
2989 #else
2990 static inline void
cifs_reclassify_socket4(struct socket * sock)2991 cifs_reclassify_socket4(struct socket *sock)
2992 {
2993 }
2994 
2995 static inline void
cifs_reclassify_socket6(struct socket * sock)2996 cifs_reclassify_socket6(struct socket *sock)
2997 {
2998 }
2999 #endif
3000 
3001 /* See RFC1001 section 14 on representation of Netbios names */
rfc1002mangle(char * target,char * source,unsigned int length)3002 static void rfc1002mangle(char *target, char *source, unsigned int length)
3003 {
3004 	unsigned int i, j;
3005 
3006 	for (i = 0, j = 0; i < (length); i++) {
3007 		/* mask a nibble at a time and encode */
3008 		target[j] = 'A' + (0x0F & (source[i] >> 4));
3009 		target[j+1] = 'A' + (0x0F & source[i]);
3010 		j += 2;
3011 	}
3012 
3013 }
3014 
3015 static int
bind_socket(struct TCP_Server_Info * server)3016 bind_socket(struct TCP_Server_Info *server)
3017 {
3018 	int rc = 0;
3019 
3020 	if (server->srcaddr.ss_family != AF_UNSPEC) {
3021 		/* Bind to the specified local IP address */
3022 		struct socket *socket = server->ssocket;
3023 
3024 		rc = kernel_bind(socket,
3025 				 (struct sockaddr *) &server->srcaddr,
3026 				 sizeof(server->srcaddr));
3027 		if (rc < 0) {
3028 			struct sockaddr_in *saddr4;
3029 			struct sockaddr_in6 *saddr6;
3030 
3031 			saddr4 = (struct sockaddr_in *)&server->srcaddr;
3032 			saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
3033 			if (saddr6->sin6_family == AF_INET6)
3034 				cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
3035 					 &saddr6->sin6_addr, rc);
3036 			else
3037 				cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
3038 					 &saddr4->sin_addr.s_addr, rc);
3039 		}
3040 	}
3041 	return rc;
3042 }
3043 
3044 static int
ip_rfc1001_connect(struct TCP_Server_Info * server)3045 ip_rfc1001_connect(struct TCP_Server_Info *server)
3046 {
3047 	int rc = 0;
3048 	/*
3049 	 * some servers require RFC1001 sessinit before sending
3050 	 * negprot - BB check reconnection in case where second
3051 	 * sessinit is sent but no second negprot
3052 	 */
3053 	struct rfc1002_session_packet req = {};
3054 	struct msghdr msg = {};
3055 	struct kvec iov = {};
3056 	unsigned int len;
3057 	size_t sent;
3058 
3059 	req.trailer.session_req.called_len = sizeof(req.trailer.session_req.called_name);
3060 
3061 	if (server->server_RFC1001_name[0] != 0)
3062 		rfc1002mangle(req.trailer.session_req.called_name,
3063 			      server->server_RFC1001_name,
3064 			      RFC1001_NAME_LEN_WITH_NULL);
3065 	else
3066 		rfc1002mangle(req.trailer.session_req.called_name,
3067 			      DEFAULT_CIFS_CALLED_NAME,
3068 			      RFC1001_NAME_LEN_WITH_NULL);
3069 
3070 	req.trailer.session_req.calling_len = sizeof(req.trailer.session_req.calling_name);
3071 
3072 	/* calling name ends in null (byte 16) from old smb convention */
3073 	if (server->workstation_RFC1001_name[0] != 0)
3074 		rfc1002mangle(req.trailer.session_req.calling_name,
3075 			      server->workstation_RFC1001_name,
3076 			      RFC1001_NAME_LEN_WITH_NULL);
3077 	else
3078 		rfc1002mangle(req.trailer.session_req.calling_name,
3079 			      "LINUX_CIFS_CLNT",
3080 			      RFC1001_NAME_LEN_WITH_NULL);
3081 
3082 	/*
3083 	 * As per rfc1002, @len must be the number of bytes that follows the
3084 	 * length field of a rfc1002 session request payload.
3085 	 */
3086 	len = sizeof(req.trailer.session_req);
3087 	req.type = RFC1002_SESSION_REQUEST;
3088 	req.flags = 0;
3089 	req.length = cpu_to_be16(len);
3090 	len += offsetof(typeof(req), trailer.session_req);
3091 	iov.iov_base = &req;
3092 	iov.iov_len = len;
3093 	iov_iter_kvec(&msg.msg_iter, ITER_SOURCE, &iov, 1, len);
3094 	rc = smb_send_kvec(server, &msg, &sent);
3095 	if (rc < 0 || len != sent)
3096 		return (rc == -EINTR || rc == -EAGAIN) ? rc : -ECONNABORTED;
3097 
3098 	/*
3099 	 * RFC1001 layer in at least one server requires very short break before
3100 	 * negprot presumably because not expecting negprot to follow so fast.
3101 	 * This is a simple solution that works without complicating the code
3102 	 * and causes no significant slowing down on mount for everyone else
3103 	 */
3104 	usleep_range(1000, 2000);
3105 
3106 	return 0;
3107 }
3108 
3109 static int
generic_ip_connect(struct TCP_Server_Info * server)3110 generic_ip_connect(struct TCP_Server_Info *server)
3111 {
3112 	struct sockaddr *saddr;
3113 	struct socket *socket;
3114 	int slen, sfamily;
3115 	__be16 sport;
3116 	int rc = 0;
3117 
3118 	saddr = (struct sockaddr *) &server->dstaddr;
3119 
3120 	if (server->dstaddr.ss_family == AF_INET6) {
3121 		struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
3122 
3123 		sport = ipv6->sin6_port;
3124 		slen = sizeof(struct sockaddr_in6);
3125 		sfamily = AF_INET6;
3126 		cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
3127 				ntohs(sport));
3128 	} else {
3129 		struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
3130 
3131 		sport = ipv4->sin_port;
3132 		slen = sizeof(struct sockaddr_in);
3133 		sfamily = AF_INET;
3134 		cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
3135 				ntohs(sport));
3136 	}
3137 
3138 	if (server->ssocket) {
3139 		socket = server->ssocket;
3140 	} else {
3141 		struct net *net = cifs_net_ns(server);
3142 		struct sock *sk;
3143 
3144 		rc = __sock_create(net, sfamily, SOCK_STREAM,
3145 				   IPPROTO_TCP, &server->ssocket, 1);
3146 		if (rc < 0) {
3147 			cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
3148 			return rc;
3149 		}
3150 
3151 		sk = server->ssocket->sk;
3152 		__netns_tracker_free(net, &sk->ns_tracker, false);
3153 		sk->sk_net_refcnt = 1;
3154 		get_net_track(net, &sk->ns_tracker, GFP_KERNEL);
3155 		sock_inuse_add(net, 1);
3156 
3157 		/* BB other socket options to set KEEPALIVE, NODELAY? */
3158 		cifs_dbg(FYI, "Socket created\n");
3159 		socket = server->ssocket;
3160 		socket->sk->sk_allocation = GFP_NOFS;
3161 		socket->sk->sk_use_task_frag = false;
3162 		if (sfamily == AF_INET6)
3163 			cifs_reclassify_socket6(socket);
3164 		else
3165 			cifs_reclassify_socket4(socket);
3166 	}
3167 
3168 	rc = bind_socket(server);
3169 	if (rc < 0)
3170 		return rc;
3171 
3172 	/*
3173 	 * Eventually check for other socket options to change from
3174 	 * the default. sock_setsockopt not used because it expects
3175 	 * user space buffer
3176 	 */
3177 	socket->sk->sk_rcvtimeo = 7 * HZ;
3178 	socket->sk->sk_sndtimeo = 5 * HZ;
3179 
3180 	/* make the bufsizes depend on wsize/rsize and max requests */
3181 	if (server->noautotune) {
3182 		if (socket->sk->sk_sndbuf < (200 * 1024))
3183 			socket->sk->sk_sndbuf = 200 * 1024;
3184 		if (socket->sk->sk_rcvbuf < (140 * 1024))
3185 			socket->sk->sk_rcvbuf = 140 * 1024;
3186 	}
3187 
3188 	if (server->tcp_nodelay)
3189 		tcp_sock_set_nodelay(socket->sk);
3190 
3191 	cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
3192 		 socket->sk->sk_sndbuf,
3193 		 socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
3194 
3195 	rc = kernel_connect(socket, saddr, slen,
3196 			    server->noblockcnt ? O_NONBLOCK : 0);
3197 	/*
3198 	 * When mounting SMB root file systems, we do not want to block in
3199 	 * connect. Otherwise bail out and then let cifs_reconnect() perform
3200 	 * reconnect failover - if possible.
3201 	 */
3202 	if (server->noblockcnt && rc == -EINPROGRESS)
3203 		rc = 0;
3204 	if (rc < 0) {
3205 		cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3206 		trace_smb3_connect_err(server->hostname, server->conn_id, &server->dstaddr, rc);
3207 		sock_release(socket);
3208 		server->ssocket = NULL;
3209 		return rc;
3210 	}
3211 	trace_smb3_connect_done(server->hostname, server->conn_id, &server->dstaddr);
3212 	if (sport == htons(RFC1001_PORT))
3213 		rc = ip_rfc1001_connect(server);
3214 
3215 	return rc;
3216 }
3217 
3218 static int
ip_connect(struct TCP_Server_Info * server)3219 ip_connect(struct TCP_Server_Info *server)
3220 {
3221 	__be16 *sport;
3222 	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3223 	struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3224 
3225 	if (server->dstaddr.ss_family == AF_INET6)
3226 		sport = &addr6->sin6_port;
3227 	else
3228 		sport = &addr->sin_port;
3229 
3230 	if (*sport == 0) {
3231 		int rc;
3232 
3233 		/* try with 445 port at first */
3234 		*sport = htons(CIFS_PORT);
3235 
3236 		rc = generic_ip_connect(server);
3237 		if (rc >= 0)
3238 			return rc;
3239 
3240 		/* if it failed, try with 139 port */
3241 		*sport = htons(RFC1001_PORT);
3242 	}
3243 
3244 	return generic_ip_connect(server);
3245 }
3246 
3247 #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)3248 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3249 			  struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3250 {
3251 	/*
3252 	 * If we are reconnecting then should we check to see if
3253 	 * any requested capabilities changed locally e.g. via
3254 	 * remount but we can not do much about it here
3255 	 * if they have (even if we could detect it by the following)
3256 	 * Perhaps we could add a backpointer to array of sb from tcon
3257 	 * or if we change to make all sb to same share the same
3258 	 * sb as NFS - then we only have one backpointer to sb.
3259 	 * What if we wanted to mount the server share twice once with
3260 	 * and once without posixacls or posix paths?
3261 	 */
3262 	__u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3263 
3264 	if (ctx && ctx->no_linux_ext) {
3265 		tcon->fsUnixInfo.Capability = 0;
3266 		tcon->unix_ext = 0; /* Unix Extensions disabled */
3267 		cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3268 		return;
3269 	} else if (ctx)
3270 		tcon->unix_ext = 1; /* Unix Extensions supported */
3271 
3272 	if (!tcon->unix_ext) {
3273 		cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3274 		return;
3275 	}
3276 
3277 	if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3278 		__u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3279 
3280 		cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3281 		/*
3282 		 * check for reconnect case in which we do not
3283 		 * want to change the mount behavior if we can avoid it
3284 		 */
3285 		if (ctx == NULL) {
3286 			/*
3287 			 * turn off POSIX ACL and PATHNAMES if not set
3288 			 * originally at mount time
3289 			 */
3290 			if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3291 				cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3292 			if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3293 				if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3294 					cifs_dbg(VFS, "POSIXPATH support change\n");
3295 				cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3296 			} else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3297 				cifs_dbg(VFS, "possible reconnect error\n");
3298 				cifs_dbg(VFS, "server disabled POSIX path support\n");
3299 			}
3300 		}
3301 
3302 		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3303 			cifs_dbg(VFS, "per-share encryption not supported yet\n");
3304 
3305 		cap &= CIFS_UNIX_CAP_MASK;
3306 		if (ctx && ctx->no_psx_acl)
3307 			cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3308 		else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3309 			cifs_dbg(FYI, "negotiated posix acl support\n");
3310 			if (cifs_sb)
3311 				cifs_sb->mnt_cifs_flags |=
3312 					CIFS_MOUNT_POSIXACL;
3313 		}
3314 
3315 		if (ctx && ctx->posix_paths == 0)
3316 			cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3317 		else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3318 			cifs_dbg(FYI, "negotiate posix pathnames\n");
3319 			if (cifs_sb)
3320 				cifs_sb->mnt_cifs_flags |=
3321 					CIFS_MOUNT_POSIX_PATHS;
3322 		}
3323 
3324 		cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3325 #ifdef CONFIG_CIFS_DEBUG2
3326 		if (cap & CIFS_UNIX_FCNTL_CAP)
3327 			cifs_dbg(FYI, "FCNTL cap\n");
3328 		if (cap & CIFS_UNIX_EXTATTR_CAP)
3329 			cifs_dbg(FYI, "EXTATTR cap\n");
3330 		if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3331 			cifs_dbg(FYI, "POSIX path cap\n");
3332 		if (cap & CIFS_UNIX_XATTR_CAP)
3333 			cifs_dbg(FYI, "XATTR cap\n");
3334 		if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3335 			cifs_dbg(FYI, "POSIX ACL cap\n");
3336 		if (cap & CIFS_UNIX_LARGE_READ_CAP)
3337 			cifs_dbg(FYI, "very large read cap\n");
3338 		if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3339 			cifs_dbg(FYI, "very large write cap\n");
3340 		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3341 			cifs_dbg(FYI, "transport encryption cap\n");
3342 		if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3343 			cifs_dbg(FYI, "mandatory transport encryption cap\n");
3344 #endif /* CIFS_DEBUG2 */
3345 		if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3346 			if (ctx == NULL)
3347 				cifs_dbg(FYI, "resetting capabilities failed\n");
3348 			else
3349 				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");
3350 
3351 		}
3352 	}
3353 }
3354 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3355 
cifs_setup_cifs_sb(struct cifs_sb_info * cifs_sb)3356 int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)
3357 {
3358 	struct smb3_fs_context *ctx = cifs_sb->ctx;
3359 
3360 	INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3361 
3362 	spin_lock_init(&cifs_sb->tlink_tree_lock);
3363 	cifs_sb->tlink_tree = RB_ROOT;
3364 
3365 	cifs_dbg(FYI, "file mode: %04ho  dir mode: %04ho\n",
3366 		 ctx->file_mode, ctx->dir_mode);
3367 
3368 	/* this is needed for ASCII cp to Unicode converts */
3369 	if (ctx->iocharset == NULL) {
3370 		/* load_nls_default cannot return null */
3371 		cifs_sb->local_nls = load_nls_default();
3372 	} else {
3373 		cifs_sb->local_nls = load_nls(ctx->iocharset);
3374 		if (cifs_sb->local_nls == NULL) {
3375 			cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3376 				 ctx->iocharset);
3377 			return -ELIBACC;
3378 		}
3379 	}
3380 	ctx->local_nls = cifs_sb->local_nls;
3381 
3382 	smb3_update_mnt_flags(cifs_sb);
3383 
3384 	if (ctx->direct_io)
3385 		cifs_dbg(FYI, "mounting share using direct i/o\n");
3386 	if (ctx->cache_ro) {
3387 		cifs_dbg(VFS, "mounting share with read only caching. Ensure that the share will not be modified while in use.\n");
3388 		cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RO_CACHE;
3389 	} else if (ctx->cache_rw) {
3390 		cifs_dbg(VFS, "mounting share in single client RW caching mode. Ensure that no other systems will be accessing the share.\n");
3391 		cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_RO_CACHE |
3392 					    CIFS_MOUNT_RW_CACHE);
3393 	}
3394 
3395 	if ((ctx->cifs_acl) && (ctx->dynperm))
3396 		cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3397 
3398 	if (ctx->prepath) {
3399 		cifs_sb->prepath = kstrdup(ctx->prepath, GFP_KERNEL);
3400 		if (cifs_sb->prepath == NULL)
3401 			return -ENOMEM;
3402 		cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3403 	}
3404 
3405 	return 0;
3406 }
3407 
3408 /* Release all succeed connections */
cifs_mount_put_conns(struct cifs_mount_ctx * mnt_ctx)3409 void cifs_mount_put_conns(struct cifs_mount_ctx *mnt_ctx)
3410 {
3411 	int rc = 0;
3412 
3413 	if (mnt_ctx->tcon)
3414 		cifs_put_tcon(mnt_ctx->tcon, netfs_trace_tcon_ref_put_mnt_ctx);
3415 	else if (mnt_ctx->ses)
3416 		cifs_put_smb_ses(mnt_ctx->ses);
3417 	else if (mnt_ctx->server)
3418 		cifs_put_tcp_session(mnt_ctx->server, 0);
3419 	mnt_ctx->ses = NULL;
3420 	mnt_ctx->tcon = NULL;
3421 	mnt_ctx->server = NULL;
3422 	mnt_ctx->cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3423 	free_xid(mnt_ctx->xid);
3424 }
3425 
cifs_mount_get_session(struct cifs_mount_ctx * mnt_ctx)3426 int cifs_mount_get_session(struct cifs_mount_ctx *mnt_ctx)
3427 {
3428 	struct TCP_Server_Info *server = NULL;
3429 	struct smb3_fs_context *ctx;
3430 	struct cifs_ses *ses = NULL;
3431 	unsigned int xid;
3432 	int rc = 0;
3433 
3434 	xid = get_xid();
3435 
3436 	if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->fs_ctx)) {
3437 		rc = -EINVAL;
3438 		goto out;
3439 	}
3440 	ctx = mnt_ctx->fs_ctx;
3441 
3442 	/* get a reference to a tcp session */
3443 	server = cifs_get_tcp_session(ctx, NULL);
3444 	if (IS_ERR(server)) {
3445 		rc = PTR_ERR(server);
3446 		server = NULL;
3447 		goto out;
3448 	}
3449 
3450 	/* get a reference to a SMB session */
3451 	ses = cifs_get_smb_ses(server, ctx);
3452 	if (IS_ERR(ses)) {
3453 		rc = PTR_ERR(ses);
3454 		ses = NULL;
3455 		goto out;
3456 	}
3457 
3458 	if ((ctx->persistent == true) && (!(ses->server->capabilities &
3459 					    SMB2_GLOBAL_CAP_PERSISTENT_HANDLES))) {
3460 		cifs_server_dbg(VFS, "persistent handles not supported by server\n");
3461 		rc = -EOPNOTSUPP;
3462 	}
3463 
3464 out:
3465 	mnt_ctx->xid = xid;
3466 	mnt_ctx->server = server;
3467 	mnt_ctx->ses = ses;
3468 	mnt_ctx->tcon = NULL;
3469 
3470 	return rc;
3471 }
3472 
cifs_mount_get_tcon(struct cifs_mount_ctx * mnt_ctx)3473 int cifs_mount_get_tcon(struct cifs_mount_ctx *mnt_ctx)
3474 {
3475 	struct TCP_Server_Info *server;
3476 	struct cifs_sb_info *cifs_sb;
3477 	struct smb3_fs_context *ctx;
3478 	struct cifs_tcon *tcon = NULL;
3479 	int rc = 0;
3480 
3481 	if (WARN_ON_ONCE(!mnt_ctx || !mnt_ctx->server || !mnt_ctx->ses || !mnt_ctx->fs_ctx ||
3482 			 !mnt_ctx->cifs_sb)) {
3483 		rc = -EINVAL;
3484 		goto out;
3485 	}
3486 	server = mnt_ctx->server;
3487 	ctx = mnt_ctx->fs_ctx;
3488 	cifs_sb = mnt_ctx->cifs_sb;
3489 
3490 	/* search for existing tcon to this server share */
3491 	tcon = cifs_get_tcon(mnt_ctx->ses, ctx);
3492 	if (IS_ERR(tcon)) {
3493 		rc = PTR_ERR(tcon);
3494 		tcon = NULL;
3495 		goto out;
3496 	}
3497 
3498 	/* if new SMB3.11 POSIX extensions are supported do not remap / and \ */
3499 	if (tcon->posix_extensions)
3500 		cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_POSIX_PATHS;
3501 
3502 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3503 	/* tell server which Unix caps we support */
3504 	if (cap_unix(tcon->ses)) {
3505 		/*
3506 		 * reset of caps checks mount to see if unix extensions disabled
3507 		 * for just this mount.
3508 		 */
3509 		reset_cifs_unix_caps(mnt_ctx->xid, tcon, cifs_sb, ctx);
3510 		spin_lock(&tcon->ses->server->srv_lock);
3511 		if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3512 		    (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3513 		     CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3514 			spin_unlock(&tcon->ses->server->srv_lock);
3515 			rc = -EACCES;
3516 			goto out;
3517 		}
3518 		spin_unlock(&tcon->ses->server->srv_lock);
3519 	} else
3520 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3521 		tcon->unix_ext = 0; /* server does not support them */
3522 
3523 	/* do not care if a following call succeed - informational */
3524 	if (!tcon->pipe && server->ops->qfs_tcon) {
3525 		server->ops->qfs_tcon(mnt_ctx->xid, tcon, cifs_sb);
3526 		if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE) {
3527 			if (tcon->fsDevInfo.DeviceCharacteristics &
3528 			    cpu_to_le32(FILE_READ_ONLY_DEVICE))
3529 				cifs_dbg(VFS, "mounted to read only share\n");
3530 			else if ((cifs_sb->mnt_cifs_flags &
3531 				  CIFS_MOUNT_RW_CACHE) == 0)
3532 				cifs_dbg(VFS, "read only mount of RW share\n");
3533 			/* no need to log a RW mount of a typical RW share */
3534 		}
3535 	}
3536 
3537 	/*
3538 	 * Clamp the rsize/wsize mount arguments if they are too big for the server
3539 	 * and set the rsize/wsize to the negotiated values if not passed in by
3540 	 * the user on mount
3541 	 */
3542 	if ((cifs_sb->ctx->wsize == 0) ||
3543 	    (cifs_sb->ctx->wsize > server->ops->negotiate_wsize(tcon, ctx))) {
3544 		cifs_sb->ctx->wsize =
3545 			round_down(server->ops->negotiate_wsize(tcon, ctx), PAGE_SIZE);
3546 		/*
3547 		 * in the very unlikely event that the server sent a max write size under PAGE_SIZE,
3548 		 * (which would get rounded down to 0) then reset wsize to absolute minimum eg 4096
3549 		 */
3550 		if (cifs_sb->ctx->wsize == 0) {
3551 			cifs_sb->ctx->wsize = PAGE_SIZE;
3552 			cifs_dbg(VFS, "wsize too small, reset to minimum ie PAGE_SIZE, usually 4096\n");
3553 		}
3554 	}
3555 	if ((cifs_sb->ctx->rsize == 0) ||
3556 	    (cifs_sb->ctx->rsize > server->ops->negotiate_rsize(tcon, ctx)))
3557 		cifs_sb->ctx->rsize = server->ops->negotiate_rsize(tcon, ctx);
3558 
3559 	/*
3560 	 * The cookie is initialized from volume info returned above.
3561 	 * Inside cifs_fscache_get_super_cookie it checks
3562 	 * that we do not get super cookie twice.
3563 	 */
3564 	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE)
3565 		cifs_fscache_get_super_cookie(tcon);
3566 
3567 out:
3568 	mnt_ctx->tcon = tcon;
3569 	return rc;
3570 }
3571 
mount_setup_tlink(struct cifs_sb_info * cifs_sb,struct cifs_ses * ses,struct cifs_tcon * tcon)3572 static int mount_setup_tlink(struct cifs_sb_info *cifs_sb, struct cifs_ses *ses,
3573 			     struct cifs_tcon *tcon)
3574 {
3575 	struct tcon_link *tlink;
3576 
3577 	/* hang the tcon off of the superblock */
3578 	tlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
3579 	if (tlink == NULL)
3580 		return -ENOMEM;
3581 
3582 	tlink->tl_uid = ses->linux_uid;
3583 	tlink->tl_tcon = tcon;
3584 	tlink->tl_time = jiffies;
3585 	set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
3586 	set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3587 
3588 	cifs_sb->master_tlink = tlink;
3589 	spin_lock(&cifs_sb->tlink_tree_lock);
3590 	tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
3591 	spin_unlock(&cifs_sb->tlink_tree_lock);
3592 
3593 	queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
3594 				TLINK_IDLE_EXPIRE);
3595 	return 0;
3596 }
3597 
3598 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)3599 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3600 					unsigned int xid,
3601 					struct cifs_tcon *tcon,
3602 					struct cifs_sb_info *cifs_sb,
3603 					char *full_path,
3604 					int added_treename)
3605 {
3606 	int rc;
3607 	char *s;
3608 	char sep, tmp;
3609 	int skip = added_treename ? 1 : 0;
3610 
3611 	sep = CIFS_DIR_SEP(cifs_sb);
3612 	s = full_path;
3613 
3614 	rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3615 	while (rc == 0) {
3616 		/* skip separators */
3617 		while (*s == sep)
3618 			s++;
3619 		if (!*s)
3620 			break;
3621 		/* next separator */
3622 		while (*s && *s != sep)
3623 			s++;
3624 		/*
3625 		 * if the treename is added, we then have to skip the first
3626 		 * part within the separators
3627 		 */
3628 		if (skip) {
3629 			skip = 0;
3630 			continue;
3631 		}
3632 		/*
3633 		 * temporarily null-terminate the path at the end of
3634 		 * the current component
3635 		 */
3636 		tmp = *s;
3637 		*s = 0;
3638 		rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3639 						     full_path);
3640 		*s = tmp;
3641 	}
3642 	return rc;
3643 }
3644 
3645 /*
3646  * Check if path is remote (i.e. a DFS share).
3647  *
3648  * Return -EREMOTE if it is, otherwise 0 or -errno.
3649  */
cifs_is_path_remote(struct cifs_mount_ctx * mnt_ctx)3650 int cifs_is_path_remote(struct cifs_mount_ctx *mnt_ctx)
3651 {
3652 	int rc;
3653 	struct cifs_sb_info *cifs_sb = mnt_ctx->cifs_sb;
3654 	struct TCP_Server_Info *server = mnt_ctx->server;
3655 	unsigned int xid = mnt_ctx->xid;
3656 	struct cifs_tcon *tcon = mnt_ctx->tcon;
3657 	struct smb3_fs_context *ctx = mnt_ctx->fs_ctx;
3658 	char *full_path;
3659 
3660 	if (!server->ops->is_path_accessible)
3661 		return -EOPNOTSUPP;
3662 
3663 	/*
3664 	 * cifs_build_path_to_root works only when we have a valid tcon
3665 	 */
3666 	full_path = cifs_build_path_to_root(ctx, cifs_sb, tcon,
3667 					    tcon->Flags & SMB_SHARE_IS_IN_DFS);
3668 	if (full_path == NULL)
3669 		return -ENOMEM;
3670 
3671 	cifs_dbg(FYI, "%s: full_path: %s\n", __func__, full_path);
3672 
3673 	rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3674 					     full_path);
3675 	if (rc != 0 && rc != -EREMOTE)
3676 		goto out;
3677 
3678 	if (rc != -EREMOTE) {
3679 		rc = cifs_are_all_path_components_accessible(server, xid, tcon,
3680 			cifs_sb, full_path, tcon->Flags & SMB_SHARE_IS_IN_DFS);
3681 		if (rc != 0) {
3682 			cifs_server_dbg(VFS, "cannot query dirs between root and final path, enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3683 			cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3684 			rc = 0;
3685 		}
3686 	}
3687 
3688 out:
3689 	kfree(full_path);
3690 	return rc;
3691 }
3692 
3693 #ifdef CONFIG_CIFS_DFS_UPCALL
cifs_mount(struct cifs_sb_info * cifs_sb,struct smb3_fs_context * ctx)3694 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3695 {
3696 	struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3697 	bool isdfs;
3698 	int rc;
3699 
3700 	rc = dfs_mount_share(&mnt_ctx, &isdfs);
3701 	if (rc)
3702 		goto error;
3703 	if (!isdfs)
3704 		goto out;
3705 
3706 	/*
3707 	 * After reconnecting to a different server, unique ids won't match anymore, so we disable
3708 	 * serverino. This prevents dentry revalidation to think the dentry are stale (ESTALE).
3709 	 */
3710 	cifs_autodisable_serverino(cifs_sb);
3711 	/*
3712 	 * Force the use of prefix path to support failover on DFS paths that resolve to targets
3713 	 * that have different prefix paths.
3714 	 */
3715 	cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3716 	kfree(cifs_sb->prepath);
3717 	cifs_sb->prepath = ctx->prepath;
3718 	ctx->prepath = NULL;
3719 
3720 out:
3721 	cifs_try_adding_channels(mnt_ctx.ses);
3722 	rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3723 	if (rc)
3724 		goto error;
3725 
3726 	free_xid(mnt_ctx.xid);
3727 	return rc;
3728 
3729 error:
3730 	cifs_mount_put_conns(&mnt_ctx);
3731 	return rc;
3732 }
3733 #else
cifs_mount(struct cifs_sb_info * cifs_sb,struct smb3_fs_context * ctx)3734 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx)
3735 {
3736 	int rc = 0;
3737 	struct cifs_mount_ctx mnt_ctx = { .cifs_sb = cifs_sb, .fs_ctx = ctx, };
3738 
3739 	rc = cifs_mount_get_session(&mnt_ctx);
3740 	if (rc)
3741 		goto error;
3742 
3743 	rc = cifs_mount_get_tcon(&mnt_ctx);
3744 	if (!rc) {
3745 		/*
3746 		 * Prevent superblock from being created with any missing
3747 		 * connections.
3748 		 */
3749 		if (WARN_ON(!mnt_ctx.server))
3750 			rc = -EHOSTDOWN;
3751 		else if (WARN_ON(!mnt_ctx.ses))
3752 			rc = -EACCES;
3753 		else if (WARN_ON(!mnt_ctx.tcon))
3754 			rc = -ENOENT;
3755 	}
3756 	if (rc)
3757 		goto error;
3758 
3759 	rc = cifs_is_path_remote(&mnt_ctx);
3760 	if (rc == -EREMOTE)
3761 		rc = -EOPNOTSUPP;
3762 	if (rc)
3763 		goto error;
3764 
3765 	rc = mount_setup_tlink(cifs_sb, mnt_ctx.ses, mnt_ctx.tcon);
3766 	if (rc)
3767 		goto error;
3768 
3769 	free_xid(mnt_ctx.xid);
3770 	return rc;
3771 
3772 error:
3773 	cifs_mount_put_conns(&mnt_ctx);
3774 	return rc;
3775 }
3776 #endif
3777 
3778 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
3779 /*
3780  * Issue a TREE_CONNECT request.
3781  */
3782 int
CIFSTCon(const unsigned int xid,struct cifs_ses * ses,const char * tree,struct cifs_tcon * tcon,const struct nls_table * nls_codepage)3783 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
3784 	 const char *tree, struct cifs_tcon *tcon,
3785 	 const struct nls_table *nls_codepage)
3786 {
3787 	struct smb_hdr *smb_buffer;
3788 	struct smb_hdr *smb_buffer_response;
3789 	TCONX_REQ *pSMB;
3790 	TCONX_RSP *pSMBr;
3791 	unsigned char *bcc_ptr;
3792 	int rc = 0;
3793 	int length;
3794 	__u16 bytes_left, count;
3795 
3796 	if (ses == NULL)
3797 		return -EIO;
3798 
3799 	smb_buffer = cifs_buf_get();
3800 	if (smb_buffer == NULL)
3801 		return -ENOMEM;
3802 
3803 	smb_buffer_response = smb_buffer;
3804 
3805 	header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
3806 			NULL /*no tid */, 4 /*wct */);
3807 
3808 	smb_buffer->Mid = get_next_mid(ses->server);
3809 	smb_buffer->Uid = ses->Suid;
3810 	pSMB = (TCONX_REQ *) smb_buffer;
3811 	pSMBr = (TCONX_RSP *) smb_buffer_response;
3812 
3813 	pSMB->AndXCommand = 0xFF;
3814 	pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
3815 	bcc_ptr = &pSMB->Password[0];
3816 
3817 	pSMB->PasswordLength = cpu_to_le16(1);	/* minimum */
3818 	*bcc_ptr = 0; /* password is null byte */
3819 	bcc_ptr++;              /* skip password */
3820 	/* already aligned so no need to do it below */
3821 
3822 	if (ses->server->sign)
3823 		smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
3824 
3825 	if (ses->capabilities & CAP_STATUS32)
3826 		smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
3827 
3828 	if (ses->capabilities & CAP_DFS)
3829 		smb_buffer->Flags2 |= SMBFLG2_DFS;
3830 
3831 	if (ses->capabilities & CAP_UNICODE) {
3832 		smb_buffer->Flags2 |= SMBFLG2_UNICODE;
3833 		length =
3834 		    cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
3835 			6 /* max utf8 char length in bytes */ *
3836 			(/* server len*/ + 256 /* share len */), nls_codepage);
3837 		bcc_ptr += 2 * length;	/* convert num 16 bit words to bytes */
3838 		bcc_ptr += 2;	/* skip trailing null */
3839 	} else {		/* ASCII */
3840 		strcpy(bcc_ptr, tree);
3841 		bcc_ptr += strlen(tree) + 1;
3842 	}
3843 	strcpy(bcc_ptr, "?????");
3844 	bcc_ptr += strlen("?????");
3845 	bcc_ptr += 1;
3846 	count = bcc_ptr - &pSMB->Password[0];
3847 	be32_add_cpu(&pSMB->hdr.smb_buf_length, count);
3848 	pSMB->ByteCount = cpu_to_le16(count);
3849 
3850 	rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
3851 			 0);
3852 
3853 	/* above now done in SendReceive */
3854 	if (rc == 0) {
3855 		bool is_unicode;
3856 
3857 		tcon->tid = smb_buffer_response->Tid;
3858 		bcc_ptr = pByteArea(smb_buffer_response);
3859 		bytes_left = get_bcc(smb_buffer_response);
3860 		length = strnlen(bcc_ptr, bytes_left - 2);
3861 		if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
3862 			is_unicode = true;
3863 		else
3864 			is_unicode = false;
3865 
3866 
3867 		/* skip service field (NB: this field is always ASCII) */
3868 		if (length == 3) {
3869 			if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
3870 			    (bcc_ptr[2] == 'C')) {
3871 				cifs_dbg(FYI, "IPC connection\n");
3872 				tcon->ipc = true;
3873 				tcon->pipe = true;
3874 			}
3875 		} else if (length == 2) {
3876 			if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
3877 				/* the most common case */
3878 				cifs_dbg(FYI, "disk share connection\n");
3879 			}
3880 		}
3881 		bcc_ptr += length + 1;
3882 		bytes_left -= (length + 1);
3883 		strscpy(tcon->tree_name, tree, sizeof(tcon->tree_name));
3884 
3885 		/* mostly informational -- no need to fail on error here */
3886 		kfree(tcon->nativeFileSystem);
3887 		tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
3888 						      bytes_left, is_unicode,
3889 						      nls_codepage);
3890 
3891 		cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
3892 
3893 		if ((smb_buffer_response->WordCount == 3) ||
3894 			 (smb_buffer_response->WordCount == 7))
3895 			/* field is in same location */
3896 			tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
3897 		else
3898 			tcon->Flags = 0;
3899 		cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
3900 
3901 		/*
3902 		 * reset_cifs_unix_caps calls QFSInfo which requires
3903 		 * need_reconnect to be false, but we would not need to call
3904 		 * reset_caps if this were not a reconnect case so must check
3905 		 * need_reconnect flag here.  The caller will also clear
3906 		 * need_reconnect when tcon was successful but needed to be
3907 		 * cleared earlier in the case of unix extensions reconnect
3908 		 */
3909 		if (tcon->need_reconnect && tcon->unix_ext) {
3910 			cifs_dbg(FYI, "resetting caps for %s\n", tcon->tree_name);
3911 			tcon->need_reconnect = false;
3912 			reset_cifs_unix_caps(xid, tcon, NULL, NULL);
3913 		}
3914 	}
3915 	cifs_buf_release(smb_buffer);
3916 	return rc;
3917 }
3918 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
3919 
delayed_free(struct rcu_head * p)3920 static void delayed_free(struct rcu_head *p)
3921 {
3922 	struct cifs_sb_info *cifs_sb = container_of(p, struct cifs_sb_info, rcu);
3923 
3924 	unload_nls(cifs_sb->local_nls);
3925 	smb3_cleanup_fs_context(cifs_sb->ctx);
3926 	kfree(cifs_sb);
3927 }
3928 
3929 void
cifs_umount(struct cifs_sb_info * cifs_sb)3930 cifs_umount(struct cifs_sb_info *cifs_sb)
3931 {
3932 	struct rb_root *root = &cifs_sb->tlink_tree;
3933 	struct rb_node *node;
3934 	struct tcon_link *tlink;
3935 
3936 	cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
3937 
3938 	spin_lock(&cifs_sb->tlink_tree_lock);
3939 	while ((node = rb_first(root))) {
3940 		tlink = rb_entry(node, struct tcon_link, tl_rbnode);
3941 		cifs_get_tlink(tlink);
3942 		clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
3943 		rb_erase(node, root);
3944 
3945 		spin_unlock(&cifs_sb->tlink_tree_lock);
3946 		cifs_put_tlink(tlink);
3947 		spin_lock(&cifs_sb->tlink_tree_lock);
3948 	}
3949 	spin_unlock(&cifs_sb->tlink_tree_lock);
3950 
3951 	kfree(cifs_sb->prepath);
3952 	call_rcu(&cifs_sb->rcu, delayed_free);
3953 }
3954 
3955 int
cifs_negotiate_protocol(const unsigned int xid,struct cifs_ses * ses,struct TCP_Server_Info * server)3956 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses,
3957 			struct TCP_Server_Info *server)
3958 {
3959 	bool in_retry = false;
3960 	int rc = 0;
3961 
3962 	if (!server->ops->need_neg || !server->ops->negotiate)
3963 		return -ENOSYS;
3964 
3965 retry:
3966 	/* only send once per connect */
3967 	spin_lock(&server->srv_lock);
3968 	if (server->tcpStatus != CifsGood &&
3969 	    server->tcpStatus != CifsNew &&
3970 	    server->tcpStatus != CifsNeedNegotiate) {
3971 		spin_unlock(&server->srv_lock);
3972 		return -EHOSTDOWN;
3973 	}
3974 
3975 	if (!server->ops->need_neg(server) &&
3976 	    server->tcpStatus == CifsGood) {
3977 		spin_unlock(&server->srv_lock);
3978 		return 0;
3979 	}
3980 
3981 	server->tcpStatus = CifsInNegotiate;
3982 	spin_unlock(&server->srv_lock);
3983 
3984 	rc = server->ops->negotiate(xid, ses, server);
3985 	if (rc == -EAGAIN) {
3986 		/* Allow one retry attempt */
3987 		if (!in_retry) {
3988 			in_retry = true;
3989 			goto retry;
3990 		}
3991 		rc = -EHOSTDOWN;
3992 	}
3993 	if (rc == 0) {
3994 		spin_lock(&server->srv_lock);
3995 		if (server->tcpStatus == CifsInNegotiate)
3996 			server->tcpStatus = CifsGood;
3997 		else
3998 			rc = -EHOSTDOWN;
3999 		spin_unlock(&server->srv_lock);
4000 	} else {
4001 		spin_lock(&server->srv_lock);
4002 		if (server->tcpStatus == CifsInNegotiate)
4003 			server->tcpStatus = CifsNeedNegotiate;
4004 		spin_unlock(&server->srv_lock);
4005 	}
4006 
4007 	return rc;
4008 }
4009 
4010 int
cifs_setup_session(const unsigned int xid,struct cifs_ses * ses,struct TCP_Server_Info * server,struct nls_table * nls_info)4011 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
4012 		   struct TCP_Server_Info *server,
4013 		   struct nls_table *nls_info)
4014 {
4015 	int rc = -ENOSYS;
4016 	struct TCP_Server_Info *pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
4017 	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&pserver->dstaddr;
4018 	struct sockaddr_in *addr = (struct sockaddr_in *)&pserver->dstaddr;
4019 	bool is_binding = false;
4020 
4021 	spin_lock(&ses->ses_lock);
4022 	cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
4023 		 __func__, ses->chans_need_reconnect);
4024 
4025 	if (ses->ses_status != SES_GOOD &&
4026 	    ses->ses_status != SES_NEW &&
4027 	    ses->ses_status != SES_NEED_RECON) {
4028 		spin_unlock(&ses->ses_lock);
4029 		return -EHOSTDOWN;
4030 	}
4031 
4032 	/* only send once per connect */
4033 	spin_lock(&ses->chan_lock);
4034 	if (CIFS_ALL_CHANS_GOOD(ses)) {
4035 		if (ses->ses_status == SES_NEED_RECON)
4036 			ses->ses_status = SES_GOOD;
4037 		spin_unlock(&ses->chan_lock);
4038 		spin_unlock(&ses->ses_lock);
4039 		return 0;
4040 	}
4041 
4042 	cifs_chan_set_in_reconnect(ses, server);
4043 	is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
4044 	spin_unlock(&ses->chan_lock);
4045 
4046 	if (!is_binding) {
4047 		ses->ses_status = SES_IN_SETUP;
4048 
4049 		/* force iface_list refresh */
4050 		ses->iface_last_update = 0;
4051 	}
4052 	spin_unlock(&ses->ses_lock);
4053 
4054 	/* update ses ip_addr only for primary chan */
4055 	if (server == pserver) {
4056 		if (server->dstaddr.ss_family == AF_INET6)
4057 			scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI6", &addr6->sin6_addr);
4058 		else
4059 			scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI4", &addr->sin_addr);
4060 	}
4061 
4062 	if (!is_binding) {
4063 		ses->capabilities = server->capabilities;
4064 		if (!linuxExtEnabled)
4065 			ses->capabilities &= (~server->vals->cap_unix);
4066 
4067 		if (ses->auth_key.response) {
4068 			cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
4069 				 ses->auth_key.response);
4070 			kfree_sensitive(ses->auth_key.response);
4071 			ses->auth_key.response = NULL;
4072 			ses->auth_key.len = 0;
4073 		}
4074 	}
4075 
4076 	cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
4077 		 server->sec_mode, server->capabilities, server->timeAdj);
4078 
4079 	if (server->ops->sess_setup)
4080 		rc = server->ops->sess_setup(xid, ses, server, nls_info);
4081 
4082 	if (rc) {
4083 		cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
4084 		spin_lock(&ses->ses_lock);
4085 		if (ses->ses_status == SES_IN_SETUP)
4086 			ses->ses_status = SES_NEED_RECON;
4087 		spin_lock(&ses->chan_lock);
4088 		cifs_chan_clear_in_reconnect(ses, server);
4089 		spin_unlock(&ses->chan_lock);
4090 		spin_unlock(&ses->ses_lock);
4091 	} else {
4092 		spin_lock(&ses->ses_lock);
4093 		if (ses->ses_status == SES_IN_SETUP)
4094 			ses->ses_status = SES_GOOD;
4095 		spin_lock(&ses->chan_lock);
4096 		cifs_chan_clear_in_reconnect(ses, server);
4097 		cifs_chan_clear_need_reconnect(ses, server);
4098 		spin_unlock(&ses->chan_lock);
4099 		spin_unlock(&ses->ses_lock);
4100 	}
4101 
4102 	return rc;
4103 }
4104 
4105 static int
cifs_set_vol_auth(struct smb3_fs_context * ctx,struct cifs_ses * ses)4106 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
4107 {
4108 	ctx->sectype = ses->sectype;
4109 
4110 	/* krb5 is special, since we don't need username or pw */
4111 	if (ctx->sectype == Kerberos)
4112 		return 0;
4113 
4114 	return cifs_set_cifscreds(ctx, ses);
4115 }
4116 
4117 static struct cifs_tcon *
__cifs_construct_tcon(struct cifs_sb_info * cifs_sb,kuid_t fsuid)4118 __cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
4119 {
4120 	int rc;
4121 	struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
4122 	struct cifs_ses *ses;
4123 	struct cifs_tcon *tcon = NULL;
4124 	struct smb3_fs_context *ctx;
4125 	char *origin_fullpath = NULL;
4126 
4127 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
4128 	if (ctx == NULL)
4129 		return ERR_PTR(-ENOMEM);
4130 
4131 	ctx->local_nls = cifs_sb->local_nls;
4132 	ctx->linux_uid = fsuid;
4133 	ctx->cred_uid = fsuid;
4134 	ctx->UNC = master_tcon->tree_name;
4135 	ctx->retry = master_tcon->retry;
4136 	ctx->nocase = master_tcon->nocase;
4137 	ctx->nohandlecache = master_tcon->nohandlecache;
4138 	ctx->local_lease = master_tcon->local_lease;
4139 	ctx->no_lease = master_tcon->no_lease;
4140 	ctx->resilient = master_tcon->use_resilient;
4141 	ctx->persistent = master_tcon->use_persistent;
4142 	ctx->handle_timeout = master_tcon->handle_timeout;
4143 	ctx->no_linux_ext = !master_tcon->unix_ext;
4144 	ctx->linux_ext = master_tcon->posix_extensions;
4145 	ctx->sectype = master_tcon->ses->sectype;
4146 	ctx->sign = master_tcon->ses->sign;
4147 	ctx->seal = master_tcon->seal;
4148 	ctx->witness = master_tcon->use_witness;
4149 	ctx->dfs_root_ses = master_tcon->ses->dfs_root_ses;
4150 
4151 	rc = cifs_set_vol_auth(ctx, master_tcon->ses);
4152 	if (rc) {
4153 		tcon = ERR_PTR(rc);
4154 		goto out;
4155 	}
4156 
4157 	/* get a reference for the same TCP session */
4158 	spin_lock(&cifs_tcp_ses_lock);
4159 	++master_tcon->ses->server->srv_count;
4160 	spin_unlock(&cifs_tcp_ses_lock);
4161 
4162 	ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
4163 	if (IS_ERR(ses)) {
4164 		tcon = (struct cifs_tcon *)ses;
4165 		cifs_put_tcp_session(master_tcon->ses->server, 0);
4166 		goto out;
4167 	}
4168 
4169 #ifdef CONFIG_CIFS_DFS_UPCALL
4170 	spin_lock(&master_tcon->tc_lock);
4171 	if (master_tcon->origin_fullpath) {
4172 		spin_unlock(&master_tcon->tc_lock);
4173 		origin_fullpath = dfs_get_path(cifs_sb, cifs_sb->ctx->source);
4174 		if (IS_ERR(origin_fullpath)) {
4175 			tcon = ERR_CAST(origin_fullpath);
4176 			origin_fullpath = NULL;
4177 			cifs_put_smb_ses(ses);
4178 			goto out;
4179 		}
4180 	} else {
4181 		spin_unlock(&master_tcon->tc_lock);
4182 	}
4183 #endif
4184 
4185 	tcon = cifs_get_tcon(ses, ctx);
4186 	if (IS_ERR(tcon)) {
4187 		cifs_put_smb_ses(ses);
4188 		goto out;
4189 	}
4190 
4191 #ifdef CONFIG_CIFS_DFS_UPCALL
4192 	if (origin_fullpath) {
4193 		spin_lock(&tcon->tc_lock);
4194 		tcon->origin_fullpath = origin_fullpath;
4195 		spin_unlock(&tcon->tc_lock);
4196 		origin_fullpath = NULL;
4197 		queue_delayed_work(dfscache_wq, &tcon->dfs_cache_work,
4198 				   dfs_cache_get_ttl() * HZ);
4199 	}
4200 #endif
4201 
4202 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4203 	if (cap_unix(ses))
4204 		reset_cifs_unix_caps(0, tcon, NULL, ctx);
4205 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
4206 
4207 out:
4208 	kfree(ctx->username);
4209 	kfree_sensitive(ctx->password);
4210 	kfree(origin_fullpath);
4211 	kfree(ctx);
4212 
4213 	return tcon;
4214 }
4215 
4216 static struct cifs_tcon *
cifs_construct_tcon(struct cifs_sb_info * cifs_sb,kuid_t fsuid)4217 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
4218 {
4219 	struct cifs_tcon *ret;
4220 
4221 	cifs_mount_lock();
4222 	ret = __cifs_construct_tcon(cifs_sb, fsuid);
4223 	cifs_mount_unlock();
4224 	return ret;
4225 }
4226 
4227 struct cifs_tcon *
cifs_sb_master_tcon(struct cifs_sb_info * cifs_sb)4228 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4229 {
4230 	return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4231 }
4232 
4233 /* find and return a tlink with given uid */
4234 static struct tcon_link *
tlink_rb_search(struct rb_root * root,kuid_t uid)4235 tlink_rb_search(struct rb_root *root, kuid_t uid)
4236 {
4237 	struct rb_node *node = root->rb_node;
4238 	struct tcon_link *tlink;
4239 
4240 	while (node) {
4241 		tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4242 
4243 		if (uid_gt(tlink->tl_uid, uid))
4244 			node = node->rb_left;
4245 		else if (uid_lt(tlink->tl_uid, uid))
4246 			node = node->rb_right;
4247 		else
4248 			return tlink;
4249 	}
4250 	return NULL;
4251 }
4252 
4253 /* insert a tcon_link into the tree */
4254 static void
tlink_rb_insert(struct rb_root * root,struct tcon_link * new_tlink)4255 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4256 {
4257 	struct rb_node **new = &(root->rb_node), *parent = NULL;
4258 	struct tcon_link *tlink;
4259 
4260 	while (*new) {
4261 		tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4262 		parent = *new;
4263 
4264 		if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4265 			new = &((*new)->rb_left);
4266 		else
4267 			new = &((*new)->rb_right);
4268 	}
4269 
4270 	rb_link_node(&new_tlink->tl_rbnode, parent, new);
4271 	rb_insert_color(&new_tlink->tl_rbnode, root);
4272 }
4273 
4274 /*
4275  * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4276  * current task.
4277  *
4278  * If the superblock doesn't refer to a multiuser mount, then just return
4279  * the master tcon for the mount.
4280  *
4281  * First, search the rbtree for an existing tcon for this fsuid. If one
4282  * exists, then check to see if it's pending construction. If it is then wait
4283  * for construction to complete. Once it's no longer pending, check to see if
4284  * it failed and either return an error or retry construction, depending on
4285  * the timeout.
4286  *
4287  * If one doesn't exist then insert a new tcon_link struct into the tree and
4288  * try to construct a new one.
4289  */
4290 struct tcon_link *
cifs_sb_tlink(struct cifs_sb_info * cifs_sb)4291 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4292 {
4293 	int ret;
4294 	kuid_t fsuid = current_fsuid();
4295 	struct tcon_link *tlink, *newtlink;
4296 
4297 	if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4298 		return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4299 
4300 	spin_lock(&cifs_sb->tlink_tree_lock);
4301 	tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4302 	if (tlink)
4303 		cifs_get_tlink(tlink);
4304 	spin_unlock(&cifs_sb->tlink_tree_lock);
4305 
4306 	if (tlink == NULL) {
4307 		newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4308 		if (newtlink == NULL)
4309 			return ERR_PTR(-ENOMEM);
4310 		newtlink->tl_uid = fsuid;
4311 		newtlink->tl_tcon = ERR_PTR(-EACCES);
4312 		set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4313 		set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4314 		cifs_get_tlink(newtlink);
4315 
4316 		spin_lock(&cifs_sb->tlink_tree_lock);
4317 		/* was one inserted after previous search? */
4318 		tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4319 		if (tlink) {
4320 			cifs_get_tlink(tlink);
4321 			spin_unlock(&cifs_sb->tlink_tree_lock);
4322 			kfree(newtlink);
4323 			goto wait_for_construction;
4324 		}
4325 		tlink = newtlink;
4326 		tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4327 		spin_unlock(&cifs_sb->tlink_tree_lock);
4328 	} else {
4329 wait_for_construction:
4330 		ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4331 				  TASK_INTERRUPTIBLE);
4332 		if (ret) {
4333 			cifs_put_tlink(tlink);
4334 			return ERR_PTR(-ERESTARTSYS);
4335 		}
4336 
4337 		/* if it's good, return it */
4338 		if (!IS_ERR(tlink->tl_tcon))
4339 			return tlink;
4340 
4341 		/* return error if we tried this already recently */
4342 		if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4343 			cifs_put_tlink(tlink);
4344 			return ERR_PTR(-EACCES);
4345 		}
4346 
4347 		if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4348 			goto wait_for_construction;
4349 	}
4350 
4351 	tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4352 	clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4353 	wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4354 
4355 	if (IS_ERR(tlink->tl_tcon)) {
4356 		cifs_put_tlink(tlink);
4357 		return ERR_PTR(-EACCES);
4358 	}
4359 
4360 	return tlink;
4361 }
4362 
4363 /*
4364  * periodic workqueue job that scans tcon_tree for a superblock and closes
4365  * out tcons.
4366  */
4367 static void
cifs_prune_tlinks(struct work_struct * work)4368 cifs_prune_tlinks(struct work_struct *work)
4369 {
4370 	struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4371 						    prune_tlinks.work);
4372 	struct rb_root *root = &cifs_sb->tlink_tree;
4373 	struct rb_node *node;
4374 	struct rb_node *tmp;
4375 	struct tcon_link *tlink;
4376 
4377 	/*
4378 	 * Because we drop the spinlock in the loop in order to put the tlink
4379 	 * it's not guarded against removal of links from the tree. The only
4380 	 * places that remove entries from the tree are this function and
4381 	 * umounts. Because this function is non-reentrant and is canceled
4382 	 * before umount can proceed, this is safe.
4383 	 */
4384 	spin_lock(&cifs_sb->tlink_tree_lock);
4385 	node = rb_first(root);
4386 	while (node != NULL) {
4387 		tmp = node;
4388 		node = rb_next(tmp);
4389 		tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4390 
4391 		if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4392 		    atomic_read(&tlink->tl_count) != 0 ||
4393 		    time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4394 			continue;
4395 
4396 		cifs_get_tlink(tlink);
4397 		clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4398 		rb_erase(tmp, root);
4399 
4400 		spin_unlock(&cifs_sb->tlink_tree_lock);
4401 		cifs_put_tlink(tlink);
4402 		spin_lock(&cifs_sb->tlink_tree_lock);
4403 	}
4404 	spin_unlock(&cifs_sb->tlink_tree_lock);
4405 
4406 	queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4407 				TLINK_IDLE_EXPIRE);
4408 }
4409 
4410 #ifndef CONFIG_CIFS_DFS_UPCALL
cifs_tree_connect(const unsigned int xid,struct cifs_tcon * tcon,const struct nls_table * nlsc)4411 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4412 {
4413 	int rc;
4414 	const struct smb_version_operations *ops = tcon->ses->server->ops;
4415 
4416 	/* only send once per connect */
4417 	spin_lock(&tcon->tc_lock);
4418 
4419 	/* if tcon is marked for needing reconnect, update state */
4420 	if (tcon->need_reconnect)
4421 		tcon->status = TID_NEED_TCON;
4422 
4423 	if (tcon->status == TID_GOOD) {
4424 		spin_unlock(&tcon->tc_lock);
4425 		return 0;
4426 	}
4427 
4428 	if (tcon->status != TID_NEW &&
4429 	    tcon->status != TID_NEED_TCON) {
4430 		spin_unlock(&tcon->tc_lock);
4431 		return -EHOSTDOWN;
4432 	}
4433 
4434 	tcon->status = TID_IN_TCON;
4435 	spin_unlock(&tcon->tc_lock);
4436 
4437 	rc = ops->tree_connect(xid, tcon->ses, tcon->tree_name, tcon, nlsc);
4438 	if (rc) {
4439 		spin_lock(&tcon->tc_lock);
4440 		if (tcon->status == TID_IN_TCON)
4441 			tcon->status = TID_NEED_TCON;
4442 		spin_unlock(&tcon->tc_lock);
4443 	} else {
4444 		spin_lock(&tcon->tc_lock);
4445 		if (tcon->status == TID_IN_TCON)
4446 			tcon->status = TID_GOOD;
4447 		tcon->need_reconnect = false;
4448 		spin_unlock(&tcon->tc_lock);
4449 	}
4450 
4451 	return rc;
4452 }
4453 #endif
4454