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