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