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