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