xref: /openbmc/linux/fs/smb/client/connect.c (revision 55b7acbd15b15e75c6df468c72177a6b32e648cf)
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_page_from_socket(struct TCP_Server_Info * server,struct page * page,unsigned int page_offset,unsigned int to_read)816 cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
817 	unsigned int page_offset, unsigned int to_read)
818 {
819 	struct msghdr smb_msg = {};
820 	struct bio_vec bv;
821 
822 	bvec_set_page(&bv, page, to_read, page_offset);
823 	iov_iter_bvec(&smb_msg.msg_iter, ITER_DEST, &bv, 1, to_read);
824 	return cifs_readv_from_socket(server, &smb_msg);
825 }
826 
827 int
cifs_read_iter_from_socket(struct TCP_Server_Info * server,struct iov_iter * iter,unsigned int to_read)828 cifs_read_iter_from_socket(struct TCP_Server_Info *server, struct iov_iter *iter,
829 			   unsigned int to_read)
830 {
831 	struct msghdr smb_msg = { .msg_iter = *iter };
832 	int ret;
833 
834 	iov_iter_truncate(&smb_msg.msg_iter, to_read);
835 	ret = cifs_readv_from_socket(server, &smb_msg);
836 	if (ret > 0)
837 		iov_iter_advance(iter, ret);
838 	return ret;
839 }
840 
841 static bool
is_smb_response(struct TCP_Server_Info * server,unsigned char type)842 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
843 {
844 	/*
845 	 * The first byte big endian of the length field,
846 	 * is actually not part of the length but the type
847 	 * with the most common, zero, as regular data.
848 	 */
849 	switch (type) {
850 	case RFC1002_SESSION_MESSAGE:
851 		/* Regular SMB response */
852 		return true;
853 	case RFC1002_SESSION_KEEP_ALIVE:
854 		cifs_dbg(FYI, "RFC 1002 session keep alive\n");
855 		break;
856 	case RFC1002_POSITIVE_SESSION_RESPONSE:
857 		cifs_dbg(FYI, "RFC 1002 positive session response\n");
858 		break;
859 	case RFC1002_NEGATIVE_SESSION_RESPONSE:
860 		/*
861 		 * We get this from Windows 98 instead of an error on
862 		 * SMB negprot response.
863 		 */
864 		cifs_dbg(FYI, "RFC 1002 negative session response\n");
865 		/* give server a second to clean up */
866 		msleep(1000);
867 		/*
868 		 * Always try 445 first on reconnect since we get NACK
869 		 * on some if we ever connected to port 139 (the NACK
870 		 * is since we do not begin with RFC1001 session
871 		 * initialize frame).
872 		 */
873 		cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
874 		cifs_reconnect(server, true);
875 		break;
876 	default:
877 		cifs_server_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
878 		cifs_reconnect(server, true);
879 	}
880 
881 	return false;
882 }
883 
884 void
dequeue_mid(struct mid_q_entry * mid,bool malformed)885 dequeue_mid(struct mid_q_entry *mid, bool malformed)
886 {
887 #ifdef CONFIG_CIFS_STATS2
888 	mid->when_received = jiffies;
889 #endif
890 	spin_lock(&mid->server->mid_lock);
891 	if (!malformed)
892 		mid->mid_state = MID_RESPONSE_RECEIVED;
893 	else
894 		mid->mid_state = MID_RESPONSE_MALFORMED;
895 	/*
896 	 * Trying to handle/dequeue a mid after the send_recv()
897 	 * function has finished processing it is a bug.
898 	 */
899 	if (mid->mid_flags & MID_DELETED) {
900 		spin_unlock(&mid->server->mid_lock);
901 		pr_warn_once("trying to dequeue a deleted mid\n");
902 	} else {
903 		list_del_init(&mid->qhead);
904 		mid->mid_flags |= MID_DELETED;
905 		spin_unlock(&mid->server->mid_lock);
906 	}
907 }
908 
909 static unsigned int
smb2_get_credits_from_hdr(char * buffer,struct TCP_Server_Info * server)910 smb2_get_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
911 {
912 	struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
913 
914 	/*
915 	 * SMB1 does not use credits.
916 	 */
917 	if (is_smb1(server))
918 		return 0;
919 
920 	return le16_to_cpu(shdr->CreditRequest);
921 }
922 
923 static void
handle_mid(struct mid_q_entry * mid,struct TCP_Server_Info * server,char * buf,int malformed)924 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
925 	   char *buf, int malformed)
926 {
927 	if (server->ops->check_trans2 &&
928 	    server->ops->check_trans2(mid, server, buf, malformed))
929 		return;
930 	mid->credits_received = smb2_get_credits_from_hdr(buf, server);
931 	mid->resp_buf = buf;
932 	mid->large_buf = server->large_buf;
933 	/* Was previous buf put in mpx struct for multi-rsp? */
934 	if (!mid->multiRsp) {
935 		/* smb buffer will be freed by user thread */
936 		if (server->large_buf)
937 			server->bigbuf = NULL;
938 		else
939 			server->smallbuf = NULL;
940 	}
941 	dequeue_mid(mid, malformed);
942 }
943 
944 int
cifs_enable_signing(struct TCP_Server_Info * server,bool mnt_sign_required)945 cifs_enable_signing(struct TCP_Server_Info *server, bool mnt_sign_required)
946 {
947 	bool srv_sign_required = server->sec_mode & server->vals->signing_required;
948 	bool srv_sign_enabled = server->sec_mode & server->vals->signing_enabled;
949 	bool mnt_sign_enabled;
950 
951 	/*
952 	 * Is signing required by mnt options? If not then check
953 	 * global_secflags to see if it is there.
954 	 */
955 	if (!mnt_sign_required)
956 		mnt_sign_required = ((global_secflags & CIFSSEC_MUST_SIGN) ==
957 						CIFSSEC_MUST_SIGN);
958 
959 	/*
960 	 * If signing is required then it's automatically enabled too,
961 	 * otherwise, check to see if the secflags allow it.
962 	 */
963 	mnt_sign_enabled = mnt_sign_required ? mnt_sign_required :
964 				(global_secflags & CIFSSEC_MAY_SIGN);
965 
966 	/* If server requires signing, does client allow it? */
967 	if (srv_sign_required) {
968 		if (!mnt_sign_enabled) {
969 			cifs_dbg(VFS, "Server requires signing, but it's disabled in SecurityFlags!\n");
970 			return -EOPNOTSUPP;
971 		}
972 		server->sign = true;
973 	}
974 
975 	/* If client requires signing, does server allow it? */
976 	if (mnt_sign_required) {
977 		if (!srv_sign_enabled) {
978 			cifs_dbg(VFS, "Server does not support signing!\n");
979 			return -EOPNOTSUPP;
980 		}
981 		server->sign = true;
982 	}
983 
984 	if (cifs_rdma_enabled(server) && server->sign)
985 		cifs_dbg(VFS, "Signing is enabled, and RDMA read/write will be disabled\n");
986 
987 	return 0;
988 }
989 
990 static noinline_for_stack void
clean_demultiplex_info(struct TCP_Server_Info * server)991 clean_demultiplex_info(struct TCP_Server_Info *server)
992 {
993 	int length;
994 
995 	/* take it off the list, if it's not already */
996 	spin_lock(&server->srv_lock);
997 	list_del_init(&server->tcp_ses_list);
998 	spin_unlock(&server->srv_lock);
999 
1000 	cancel_delayed_work_sync(&server->echo);
1001 
1002 	spin_lock(&server->srv_lock);
1003 	server->tcpStatus = CifsExiting;
1004 	spin_unlock(&server->srv_lock);
1005 	wake_up_all(&server->response_q);
1006 
1007 	/* check if we have blocked requests that need to free */
1008 	spin_lock(&server->req_lock);
1009 	if (server->credits <= 0)
1010 		server->credits = 1;
1011 	spin_unlock(&server->req_lock);
1012 	/*
1013 	 * Although there should not be any requests blocked on this queue it
1014 	 * can not hurt to be paranoid and try to wake up requests that may
1015 	 * haven been blocked when more than 50 at time were on the wire to the
1016 	 * same server - they now will see the session is in exit state and get
1017 	 * out of SendReceive.
1018 	 */
1019 	wake_up_all(&server->request_q);
1020 	/* give those requests time to exit */
1021 	msleep(125);
1022 	if (cifs_rdma_enabled(server))
1023 		smbd_destroy(server);
1024 	if (server->ssocket) {
1025 		sock_release(server->ssocket);
1026 		server->ssocket = NULL;
1027 	}
1028 
1029 	if (!list_empty(&server->pending_mid_q)) {
1030 		struct list_head dispose_list;
1031 		struct mid_q_entry *mid_entry;
1032 		struct list_head *tmp, *tmp2;
1033 
1034 		INIT_LIST_HEAD(&dispose_list);
1035 		spin_lock(&server->mid_lock);
1036 		list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
1037 			mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
1038 			cifs_dbg(FYI, "Clearing mid %llu\n", mid_entry->mid);
1039 			kref_get(&mid_entry->refcount);
1040 			mid_entry->mid_state = MID_SHUTDOWN;
1041 			list_move(&mid_entry->qhead, &dispose_list);
1042 			mid_entry->mid_flags |= MID_DELETED;
1043 		}
1044 		spin_unlock(&server->mid_lock);
1045 
1046 		/* now walk dispose list and issue callbacks */
1047 		list_for_each_safe(tmp, tmp2, &dispose_list) {
1048 			mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
1049 			cifs_dbg(FYI, "Callback mid %llu\n", mid_entry->mid);
1050 			list_del_init(&mid_entry->qhead);
1051 			mid_entry->callback(mid_entry);
1052 			release_mid(mid_entry);
1053 		}
1054 		/* 1/8th of sec is more than enough time for them to exit */
1055 		msleep(125);
1056 	}
1057 
1058 	if (!list_empty(&server->pending_mid_q)) {
1059 		/*
1060 		 * mpx threads have not exited yet give them at least the smb
1061 		 * send timeout time for long ops.
1062 		 *
1063 		 * Due to delays on oplock break requests, we need to wait at
1064 		 * least 45 seconds before giving up on a request getting a
1065 		 * response and going ahead and killing cifsd.
1066 		 */
1067 		cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
1068 		msleep(46000);
1069 		/*
1070 		 * If threads still have not exited they are probably never
1071 		 * coming home not much else we can do but free the memory.
1072 		 */
1073 	}
1074 
1075 	put_net(cifs_net_ns(server));
1076 	kfree(server->leaf_fullpath);
1077 	kfree(server->hostname);
1078 	kfree(server);
1079 
1080 	length = atomic_dec_return(&tcpSesAllocCount);
1081 	if (length > 0)
1082 		mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1083 }
1084 
1085 static int
standard_receive3(struct TCP_Server_Info * server,struct mid_q_entry * mid)1086 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1087 {
1088 	int length;
1089 	char *buf = server->smallbuf;
1090 	unsigned int pdu_length = server->pdu_size;
1091 
1092 	/* make sure this will fit in a large buffer */
1093 	if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) -
1094 	    HEADER_PREAMBLE_SIZE(server)) {
1095 		cifs_server_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
1096 		cifs_reconnect(server, true);
1097 		return -ECONNABORTED;
1098 	}
1099 
1100 	/* switch to large buffer if too big for a small one */
1101 	if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
1102 		server->large_buf = true;
1103 		memcpy(server->bigbuf, buf, server->total_read);
1104 		buf = server->bigbuf;
1105 	}
1106 
1107 	/* now read the rest */
1108 	length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
1109 				       pdu_length - MID_HEADER_SIZE(server));
1110 
1111 	if (length < 0)
1112 		return length;
1113 	server->total_read += length;
1114 
1115 	dump_smb(buf, server->total_read);
1116 
1117 	return cifs_handle_standard(server, mid);
1118 }
1119 
1120 int
cifs_handle_standard(struct TCP_Server_Info * server,struct mid_q_entry * mid)1121 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
1122 {
1123 	char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
1124 	int rc;
1125 
1126 	/*
1127 	 * We know that we received enough to get to the MID as we
1128 	 * checked the pdu_length earlier. Now check to see
1129 	 * if the rest of the header is OK.
1130 	 *
1131 	 * 48 bytes is enough to display the header and a little bit
1132 	 * into the payload for debugging purposes.
1133 	 */
1134 	rc = server->ops->check_message(buf, server->total_read, server);
1135 	if (rc)
1136 		cifs_dump_mem("Bad SMB: ", buf,
1137 			min_t(unsigned int, server->total_read, 48));
1138 
1139 	if (server->ops->is_session_expired &&
1140 	    server->ops->is_session_expired(buf)) {
1141 		cifs_reconnect(server, true);
1142 		return -1;
1143 	}
1144 
1145 	if (server->ops->is_status_pending &&
1146 	    server->ops->is_status_pending(buf, server))
1147 		return -1;
1148 
1149 	if (!mid)
1150 		return rc;
1151 
1152 	handle_mid(mid, server, buf, rc);
1153 	return 0;
1154 }
1155 
1156 static void
smb2_add_credits_from_hdr(char * buffer,struct TCP_Server_Info * server)1157 smb2_add_credits_from_hdr(char *buffer, struct TCP_Server_Info *server)
1158 {
1159 	struct smb2_hdr *shdr = (struct smb2_hdr *)buffer;
1160 	int scredits, in_flight;
1161 
1162 	/*
1163 	 * SMB1 does not use credits.
1164 	 */
1165 	if (is_smb1(server))
1166 		return;
1167 
1168 	if (shdr->CreditRequest) {
1169 		spin_lock(&server->req_lock);
1170 		server->credits += le16_to_cpu(shdr->CreditRequest);
1171 		scredits = server->credits;
1172 		in_flight = server->in_flight;
1173 		spin_unlock(&server->req_lock);
1174 		wake_up(&server->request_q);
1175 
1176 		trace_smb3_hdr_credits(server->CurrentMid,
1177 				server->conn_id, server->hostname, scredits,
1178 				le16_to_cpu(shdr->CreditRequest), in_flight);
1179 		cifs_server_dbg(FYI, "%s: added %u credits total=%d\n",
1180 				__func__, le16_to_cpu(shdr->CreditRequest),
1181 				scredits);
1182 	}
1183 }
1184 
1185 
1186 static int
cifs_demultiplex_thread(void * p)1187 cifs_demultiplex_thread(void *p)
1188 {
1189 	int i, num_mids, length;
1190 	struct TCP_Server_Info *server = p;
1191 	unsigned int pdu_length;
1192 	unsigned int next_offset;
1193 	char *buf = NULL;
1194 	struct task_struct *task_to_wake = NULL;
1195 	struct mid_q_entry *mids[MAX_COMPOUND];
1196 	char *bufs[MAX_COMPOUND];
1197 	unsigned int noreclaim_flag, num_io_timeout = 0;
1198 	bool pending_reconnect = false;
1199 
1200 	noreclaim_flag = memalloc_noreclaim_save();
1201 	cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
1202 
1203 	length = atomic_inc_return(&tcpSesAllocCount);
1204 	if (length > 1)
1205 		mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
1206 
1207 	set_freezable();
1208 	allow_kernel_signal(SIGKILL);
1209 	while (server->tcpStatus != CifsExiting) {
1210 		if (try_to_freeze())
1211 			continue;
1212 
1213 		if (!allocate_buffers(server))
1214 			continue;
1215 
1216 		server->large_buf = false;
1217 		buf = server->smallbuf;
1218 		pdu_length = 4; /* enough to get RFC1001 header */
1219 
1220 		length = cifs_read_from_socket(server, buf, pdu_length);
1221 		if (length < 0)
1222 			continue;
1223 
1224 		if (is_smb1(server))
1225 			server->total_read = length;
1226 		else
1227 			server->total_read = 0;
1228 
1229 		/*
1230 		 * The right amount was read from socket - 4 bytes,
1231 		 * so we can now interpret the length field.
1232 		 */
1233 		pdu_length = get_rfc1002_length(buf);
1234 
1235 		cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
1236 		if (!is_smb_response(server, buf[0]))
1237 			continue;
1238 
1239 		pending_reconnect = false;
1240 next_pdu:
1241 		server->pdu_size = pdu_length;
1242 
1243 		/* make sure we have enough to get to the MID */
1244 		if (server->pdu_size < MID_HEADER_SIZE(server)) {
1245 			cifs_server_dbg(VFS, "SMB response too short (%u bytes)\n",
1246 				 server->pdu_size);
1247 			cifs_reconnect(server, true);
1248 			continue;
1249 		}
1250 
1251 		/* read down to the MID */
1252 		length = cifs_read_from_socket(server,
1253 			     buf + HEADER_PREAMBLE_SIZE(server),
1254 			     MID_HEADER_SIZE(server));
1255 		if (length < 0)
1256 			continue;
1257 		server->total_read += length;
1258 
1259 		if (server->ops->next_header) {
1260 			if (server->ops->next_header(server, buf, &next_offset)) {
1261 				cifs_dbg(VFS, "%s: malformed response (next_offset=%u)\n",
1262 					 __func__, next_offset);
1263 				cifs_reconnect(server, true);
1264 				continue;
1265 			}
1266 			if (next_offset)
1267 				server->pdu_size = next_offset;
1268 		}
1269 
1270 		memset(mids, 0, sizeof(mids));
1271 		memset(bufs, 0, sizeof(bufs));
1272 		num_mids = 0;
1273 
1274 		if (server->ops->is_transform_hdr &&
1275 		    server->ops->receive_transform &&
1276 		    server->ops->is_transform_hdr(buf)) {
1277 			length = server->ops->receive_transform(server,
1278 								mids,
1279 								bufs,
1280 								&num_mids);
1281 		} else {
1282 			mids[0] = server->ops->find_mid(server, buf);
1283 			bufs[0] = buf;
1284 			num_mids = 1;
1285 
1286 			if (!mids[0] || !mids[0]->receive)
1287 				length = standard_receive3(server, mids[0]);
1288 			else
1289 				length = mids[0]->receive(server, mids[0]);
1290 		}
1291 
1292 		if (length < 0) {
1293 			for (i = 0; i < num_mids; i++)
1294 				if (mids[i])
1295 					release_mid(mids[i]);
1296 			continue;
1297 		}
1298 
1299 		if (server->ops->is_status_io_timeout &&
1300 		    server->ops->is_status_io_timeout(buf)) {
1301 			num_io_timeout++;
1302 			if (num_io_timeout > MAX_STATUS_IO_TIMEOUT) {
1303 				cifs_server_dbg(VFS,
1304 						"Number of request timeouts exceeded %d. Reconnecting",
1305 						MAX_STATUS_IO_TIMEOUT);
1306 
1307 				pending_reconnect = true;
1308 				num_io_timeout = 0;
1309 			}
1310 		}
1311 
1312 		server->lstrp = jiffies;
1313 
1314 		for (i = 0; i < num_mids; i++) {
1315 			if (mids[i] != NULL) {
1316 				mids[i]->resp_buf_size = server->pdu_size;
1317 
1318 				if (bufs[i] != NULL) {
1319 					if (server->ops->is_network_name_deleted &&
1320 					    server->ops->is_network_name_deleted(bufs[i],
1321 										 server)) {
1322 						cifs_server_dbg(FYI,
1323 								"Share deleted. Reconnect needed");
1324 					}
1325 				}
1326 
1327 				if (!mids[i]->multiRsp || mids[i]->multiEnd)
1328 					mids[i]->callback(mids[i]);
1329 
1330 				release_mid(mids[i]);
1331 			} else if (server->ops->is_oplock_break &&
1332 				   server->ops->is_oplock_break(bufs[i],
1333 								server)) {
1334 				smb2_add_credits_from_hdr(bufs[i], server);
1335 				cifs_dbg(FYI, "Received oplock break\n");
1336 			} else {
1337 				cifs_server_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1338 						atomic_read(&mid_count));
1339 				cifs_dump_mem("Received Data is: ", bufs[i],
1340 					      HEADER_SIZE(server));
1341 				smb2_add_credits_from_hdr(bufs[i], server);
1342 #ifdef CONFIG_CIFS_DEBUG2
1343 				if (server->ops->dump_detail)
1344 					server->ops->dump_detail(bufs[i],
1345 								 server);
1346 				cifs_dump_mids(server);
1347 #endif /* CIFS_DEBUG2 */
1348 			}
1349 		}
1350 
1351 		if (pdu_length > server->pdu_size) {
1352 			if (!allocate_buffers(server))
1353 				continue;
1354 			pdu_length -= server->pdu_size;
1355 			server->total_read = 0;
1356 			server->large_buf = false;
1357 			buf = server->smallbuf;
1358 			goto next_pdu;
1359 		}
1360 
1361 		/* do this reconnect at the very end after processing all MIDs */
1362 		if (pending_reconnect)
1363 			cifs_reconnect(server, true);
1364 
1365 	} /* end while !EXITING */
1366 
1367 	/* buffer usually freed in free_mid - need to free it here on exit */
1368 	cifs_buf_release(server->bigbuf);
1369 	if (server->smallbuf) /* no sense logging a debug message if NULL */
1370 		cifs_small_buf_release(server->smallbuf);
1371 
1372 	task_to_wake = xchg(&server->tsk, NULL);
1373 	clean_demultiplex_info(server);
1374 
1375 	/* if server->tsk was NULL then wait for a signal before exiting */
1376 	if (!task_to_wake) {
1377 		set_current_state(TASK_INTERRUPTIBLE);
1378 		while (!signal_pending(current)) {
1379 			schedule();
1380 			set_current_state(TASK_INTERRUPTIBLE);
1381 		}
1382 		set_current_state(TASK_RUNNING);
1383 	}
1384 
1385 	memalloc_noreclaim_restore(noreclaim_flag);
1386 	module_put_and_kthread_exit(0);
1387 }
1388 
1389 int
cifs_ipaddr_cmp(struct sockaddr * srcaddr,struct sockaddr * rhs)1390 cifs_ipaddr_cmp(struct sockaddr *srcaddr, struct sockaddr *rhs)
1391 {
1392 	struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1393 	struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1394 	struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1395 	struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1396 
1397 	switch (srcaddr->sa_family) {
1398 	case AF_UNSPEC:
1399 		switch (rhs->sa_family) {
1400 		case AF_UNSPEC:
1401 			return 0;
1402 		case AF_INET:
1403 		case AF_INET6:
1404 			return 1;
1405 		default:
1406 			return -1;
1407 		}
1408 	case AF_INET: {
1409 		switch (rhs->sa_family) {
1410 		case AF_UNSPEC:
1411 			return -1;
1412 		case AF_INET:
1413 			return memcmp(saddr4, vaddr4,
1414 				      sizeof(struct sockaddr_in));
1415 		case AF_INET6:
1416 			return 1;
1417 		default:
1418 			return -1;
1419 		}
1420 	}
1421 	case AF_INET6: {
1422 		switch (rhs->sa_family) {
1423 		case AF_UNSPEC:
1424 		case AF_INET:
1425 			return -1;
1426 		case AF_INET6:
1427 			return memcmp(saddr6,
1428 				      vaddr6,
1429 				      sizeof(struct sockaddr_in6));
1430 		default:
1431 			return -1;
1432 		}
1433 	}
1434 	default:
1435 		return -1; /* don't expect to be here */
1436 	}
1437 }
1438 
1439 /*
1440  * Returns true if srcaddr isn't specified and rhs isn't specified, or
1441  * if srcaddr is specified and matches the IP address of the rhs argument
1442  */
1443 bool
cifs_match_ipaddr(struct sockaddr * srcaddr,struct sockaddr * rhs)1444 cifs_match_ipaddr(struct sockaddr *srcaddr, struct sockaddr *rhs)
1445 {
1446 	switch (srcaddr->sa_family) {
1447 	case AF_UNSPEC:
1448 		return (rhs->sa_family == AF_UNSPEC);
1449 	case AF_INET: {
1450 		struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
1451 		struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
1452 
1453 		return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
1454 	}
1455 	case AF_INET6: {
1456 		struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
1457 		struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
1458 
1459 		return (ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr)
1460 			&& saddr6->sin6_scope_id == vaddr6->sin6_scope_id);
1461 	}
1462 	default:
1463 		WARN_ON(1);
1464 		return false; /* don't expect to be here */
1465 	}
1466 }
1467 
1468 /*
1469  * If no port is specified in addr structure, we try to match with 445 port
1470  * and if it fails - with 139 ports. It should be called only if address
1471  * families of server and addr are equal.
1472  */
1473 static bool
match_port(struct TCP_Server_Info * server,struct sockaddr * addr)1474 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
1475 {
1476 	__be16 port, *sport;
1477 
1478 	/* SMBDirect manages its own ports, don't match it here */
1479 	if (server->rdma)
1480 		return true;
1481 
1482 	switch (addr->sa_family) {
1483 	case AF_INET:
1484 		sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
1485 		port = ((struct sockaddr_in *) addr)->sin_port;
1486 		break;
1487 	case AF_INET6:
1488 		sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
1489 		port = ((struct sockaddr_in6 *) addr)->sin6_port;
1490 		break;
1491 	default:
1492 		WARN_ON(1);
1493 		return false;
1494 	}
1495 
1496 	if (!port) {
1497 		port = htons(CIFS_PORT);
1498 		if (port == *sport)
1499 			return true;
1500 
1501 		port = htons(RFC1001_PORT);
1502 	}
1503 
1504 	return port == *sport;
1505 }
1506 
match_server_address(struct TCP_Server_Info * server,struct sockaddr * addr)1507 static bool match_server_address(struct TCP_Server_Info *server, struct sockaddr *addr)
1508 {
1509 	if (!cifs_match_ipaddr(addr, (struct sockaddr *)&server->dstaddr))
1510 		return false;
1511 
1512 	return true;
1513 }
1514 
1515 static bool
match_security(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)1516 match_security(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
1517 {
1518 	/*
1519 	 * The select_sectype function should either return the ctx->sectype
1520 	 * that was specified, or "Unspecified" if that sectype was not
1521 	 * compatible with the given NEGOTIATE request.
1522 	 */
1523 	if (server->ops->select_sectype(server, ctx->sectype)
1524 	     == Unspecified)
1525 		return false;
1526 
1527 	/*
1528 	 * Now check if signing mode is acceptable. No need to check
1529 	 * global_secflags at this point since if MUST_SIGN is set then
1530 	 * the server->sign had better be too.
1531 	 */
1532 	if (ctx->sign && !server->sign)
1533 		return false;
1534 
1535 	return true;
1536 }
1537 
1538 /* this function must be called with srv_lock held */
match_server(struct TCP_Server_Info * server,struct smb3_fs_context * ctx,bool match_super)1539 static int match_server(struct TCP_Server_Info *server,
1540 			struct smb3_fs_context *ctx,
1541 			bool match_super)
1542 {
1543 	struct sockaddr *addr = (struct sockaddr *)&ctx->dstaddr;
1544 
1545 	lockdep_assert_held(&server->srv_lock);
1546 
1547 	if (ctx->nosharesock)
1548 		return 0;
1549 
1550 	/* this server does not share socket */
1551 	if (server->nosharesock)
1552 		return 0;
1553 
1554 	if (!match_super && (ctx->dfs_conn || server->dfs_conn))
1555 		return 0;
1556 
1557 	/* If multidialect negotiation see if existing sessions match one */
1558 	if (strcmp(ctx->vals->version_string, SMB3ANY_VERSION_STRING) == 0) {
1559 		if (server->vals->protocol_id < SMB30_PROT_ID)
1560 			return 0;
1561 	} else if (strcmp(ctx->vals->version_string,
1562 		   SMBDEFAULT_VERSION_STRING) == 0) {
1563 		if (server->vals->protocol_id < SMB21_PROT_ID)
1564 			return 0;
1565 	} else if ((server->vals != ctx->vals) || (server->ops != ctx->ops))
1566 		return 0;
1567 
1568 	if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
1569 		return 0;
1570 
1571 	if (!cifs_match_ipaddr((struct sockaddr *)&ctx->srcaddr,
1572 			       (struct sockaddr *)&server->srcaddr))
1573 		return 0;
1574 	/*
1575 	 * When matching cifs.ko superblocks (@match_super == true), we can't
1576 	 * really match either @server->leaf_fullpath or @server->dstaddr
1577 	 * directly since this @server might belong to a completely different
1578 	 * server -- in case of domain-based DFS referrals or DFS links -- as
1579 	 * provided earlier by mount(2) through 'source' and 'ip' options.
1580 	 *
1581 	 * Otherwise, match the DFS referral in @server->leaf_fullpath or the
1582 	 * destination address in @server->dstaddr.
1583 	 *
1584 	 * When using 'nodfs' mount option, we avoid sharing it with DFS
1585 	 * connections as they might failover.
1586 	 */
1587 	if (!match_super) {
1588 		if (!ctx->nodfs) {
1589 			if (server->leaf_fullpath) {
1590 				if (!ctx->leaf_fullpath ||
1591 				    strcasecmp(server->leaf_fullpath,
1592 					       ctx->leaf_fullpath))
1593 					return 0;
1594 			} else if (ctx->leaf_fullpath) {
1595 				return 0;
1596 			}
1597 		} else if (server->leaf_fullpath) {
1598 			return 0;
1599 		}
1600 	}
1601 
1602 	/*
1603 	 * Match for a regular connection (address/hostname/port) which has no
1604 	 * DFS referrals set.
1605 	 */
1606 	if (!server->leaf_fullpath &&
1607 	    (strcasecmp(server->hostname, ctx->server_hostname) ||
1608 	     !match_server_address(server, addr) ||
1609 	     !match_port(server, addr)))
1610 		return 0;
1611 
1612 	if (!match_security(server, ctx))
1613 		return 0;
1614 
1615 	if (server->echo_interval != ctx->echo_interval * HZ)
1616 		return 0;
1617 
1618 	if (server->rdma != ctx->rdma)
1619 		return 0;
1620 
1621 	if (server->ignore_signature != ctx->ignore_signature)
1622 		return 0;
1623 
1624 	if (server->min_offload != ctx->min_offload)
1625 		return 0;
1626 
1627 	if (server->retrans != ctx->retrans)
1628 		return 0;
1629 
1630 	return 1;
1631 }
1632 
1633 struct TCP_Server_Info *
cifs_find_tcp_session(struct smb3_fs_context * ctx)1634 cifs_find_tcp_session(struct smb3_fs_context *ctx)
1635 {
1636 	struct TCP_Server_Info *server;
1637 
1638 	spin_lock(&cifs_tcp_ses_lock);
1639 	list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
1640 		spin_lock(&server->srv_lock);
1641 		/*
1642 		 * Skip ses channels since they're only handled in lower layers
1643 		 * (e.g. cifs_send_recv).
1644 		 */
1645 		if (SERVER_IS_CHAN(server) ||
1646 		    !match_server(server, ctx, false)) {
1647 			spin_unlock(&server->srv_lock);
1648 			continue;
1649 		}
1650 		spin_unlock(&server->srv_lock);
1651 
1652 		++server->srv_count;
1653 		spin_unlock(&cifs_tcp_ses_lock);
1654 		cifs_dbg(FYI, "Existing tcp session with server found\n");
1655 		return server;
1656 	}
1657 	spin_unlock(&cifs_tcp_ses_lock);
1658 	return NULL;
1659 }
1660 
1661 void
cifs_put_tcp_session(struct TCP_Server_Info * server,int from_reconnect)1662 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
1663 {
1664 	struct task_struct *task;
1665 
1666 	spin_lock(&cifs_tcp_ses_lock);
1667 	if (--server->srv_count > 0) {
1668 		spin_unlock(&cifs_tcp_ses_lock);
1669 		return;
1670 	}
1671 
1672 	/* srv_count can never go negative */
1673 	WARN_ON(server->srv_count < 0);
1674 
1675 	list_del_init(&server->tcp_ses_list);
1676 	spin_unlock(&cifs_tcp_ses_lock);
1677 
1678 	cancel_delayed_work_sync(&server->echo);
1679 
1680 	if (from_reconnect)
1681 		/*
1682 		 * Avoid deadlock here: reconnect work calls
1683 		 * cifs_put_tcp_session() at its end. Need to be sure
1684 		 * that reconnect work does nothing with server pointer after
1685 		 * that step.
1686 		 */
1687 		cancel_delayed_work(&server->reconnect);
1688 	else
1689 		cancel_delayed_work_sync(&server->reconnect);
1690 
1691 	/* For secondary channels, we pick up ref-count on the primary server */
1692 	if (SERVER_IS_CHAN(server))
1693 		cifs_put_tcp_session(server->primary_server, from_reconnect);
1694 
1695 	spin_lock(&server->srv_lock);
1696 	server->tcpStatus = CifsExiting;
1697 	spin_unlock(&server->srv_lock);
1698 
1699 	cifs_crypto_secmech_release(server);
1700 
1701 	kfree_sensitive(server->session_key.response);
1702 	server->session_key.response = NULL;
1703 	server->session_key.len = 0;
1704 
1705 	task = xchg(&server->tsk, NULL);
1706 	if (task)
1707 		send_sig(SIGKILL, task, 1);
1708 }
1709 
1710 struct TCP_Server_Info *
cifs_get_tcp_session(struct smb3_fs_context * ctx,struct TCP_Server_Info * primary_server)1711 cifs_get_tcp_session(struct smb3_fs_context *ctx,
1712 		     struct TCP_Server_Info *primary_server)
1713 {
1714 	struct TCP_Server_Info *tcp_ses = NULL;
1715 	int rc;
1716 
1717 	cifs_dbg(FYI, "UNC: %s\n", ctx->UNC);
1718 
1719 	/* see if we already have a matching tcp_ses */
1720 	tcp_ses = cifs_find_tcp_session(ctx);
1721 	if (tcp_ses)
1722 		return tcp_ses;
1723 
1724 	tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
1725 	if (!tcp_ses) {
1726 		rc = -ENOMEM;
1727 		goto out_err;
1728 	}
1729 
1730 	tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
1731 	if (!tcp_ses->hostname) {
1732 		rc = -ENOMEM;
1733 		goto out_err;
1734 	}
1735 
1736 	if (ctx->leaf_fullpath) {
1737 		tcp_ses->leaf_fullpath = kstrdup(ctx->leaf_fullpath, GFP_KERNEL);
1738 		if (!tcp_ses->leaf_fullpath) {
1739 			rc = -ENOMEM;
1740 			goto out_err;
1741 		}
1742 	}
1743 
1744 	if (ctx->nosharesock)
1745 		tcp_ses->nosharesock = true;
1746 	tcp_ses->dfs_conn = ctx->dfs_conn;
1747 
1748 	tcp_ses->ops = ctx->ops;
1749 	tcp_ses->vals = ctx->vals;
1750 	cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
1751 
1752 	tcp_ses->conn_id = atomic_inc_return(&tcpSesNextId);
1753 	tcp_ses->noblockcnt = ctx->rootfs;
1754 	tcp_ses->noblocksnd = ctx->noblocksnd || ctx->rootfs;
1755 	tcp_ses->noautotune = ctx->noautotune;
1756 	tcp_ses->tcp_nodelay = ctx->sockopt_tcp_nodelay;
1757 	tcp_ses->rdma = ctx->rdma;
1758 	tcp_ses->in_flight = 0;
1759 	tcp_ses->max_in_flight = 0;
1760 	tcp_ses->credits = 1;
1761 	if (primary_server) {
1762 		spin_lock(&cifs_tcp_ses_lock);
1763 		++primary_server->srv_count;
1764 		spin_unlock(&cifs_tcp_ses_lock);
1765 		tcp_ses->primary_server = primary_server;
1766 	}
1767 	init_waitqueue_head(&tcp_ses->response_q);
1768 	init_waitqueue_head(&tcp_ses->request_q);
1769 	INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
1770 	mutex_init(&tcp_ses->_srv_mutex);
1771 	memcpy(tcp_ses->workstation_RFC1001_name,
1772 		ctx->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1773 	memcpy(tcp_ses->server_RFC1001_name,
1774 		ctx->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
1775 	tcp_ses->session_estab = false;
1776 	tcp_ses->sequence_number = 0;
1777 	tcp_ses->channel_sequence_num = 0; /* only tracked for primary channel */
1778 	tcp_ses->reconnect_instance = 1;
1779 	tcp_ses->lstrp = jiffies;
1780 	tcp_ses->compression.requested = ctx->compress;
1781 	spin_lock_init(&tcp_ses->req_lock);
1782 	spin_lock_init(&tcp_ses->srv_lock);
1783 	spin_lock_init(&tcp_ses->mid_lock);
1784 	INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
1785 	INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
1786 	INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
1787 	INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
1788 	mutex_init(&tcp_ses->reconnect_mutex);
1789 #ifdef CONFIG_CIFS_DFS_UPCALL
1790 	mutex_init(&tcp_ses->refpath_lock);
1791 #endif
1792 	memcpy(&tcp_ses->srcaddr, &ctx->srcaddr,
1793 	       sizeof(tcp_ses->srcaddr));
1794 	memcpy(&tcp_ses->dstaddr, &ctx->dstaddr,
1795 		sizeof(tcp_ses->dstaddr));
1796 	if (ctx->use_client_guid)
1797 		memcpy(tcp_ses->client_guid, ctx->client_guid,
1798 		       SMB2_CLIENT_GUID_SIZE);
1799 	else
1800 		generate_random_uuid(tcp_ses->client_guid);
1801 	/*
1802 	 * at this point we are the only ones with the pointer
1803 	 * to the struct since the kernel thread not created yet
1804 	 * no need to spinlock this init of tcpStatus or srv_count
1805 	 */
1806 	tcp_ses->tcpStatus = CifsNew;
1807 	++tcp_ses->srv_count;
1808 
1809 	if (ctx->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
1810 		ctx->echo_interval <= SMB_ECHO_INTERVAL_MAX)
1811 		tcp_ses->echo_interval = ctx->echo_interval * HZ;
1812 	else
1813 		tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
1814 	if (tcp_ses->rdma) {
1815 #ifndef CONFIG_CIFS_SMB_DIRECT
1816 		cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
1817 		rc = -ENOENT;
1818 		goto out_err_crypto_release;
1819 #endif
1820 		tcp_ses->smbd_conn = smbd_get_connection(
1821 			tcp_ses, (struct sockaddr *)&ctx->dstaddr);
1822 		if (tcp_ses->smbd_conn) {
1823 			cifs_dbg(VFS, "RDMA transport established\n");
1824 			rc = 0;
1825 			goto smbd_connected;
1826 		} else {
1827 			rc = -ENOENT;
1828 			goto out_err_crypto_release;
1829 		}
1830 	}
1831 	rc = ip_connect(tcp_ses);
1832 	if (rc < 0) {
1833 		cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
1834 		goto out_err_crypto_release;
1835 	}
1836 smbd_connected:
1837 	/*
1838 	 * since we're in a cifs function already, we know that
1839 	 * this will succeed. No need for try_module_get().
1840 	 */
1841 	__module_get(THIS_MODULE);
1842 	tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
1843 				  tcp_ses, "cifsd");
1844 	if (IS_ERR(tcp_ses->tsk)) {
1845 		rc = PTR_ERR(tcp_ses->tsk);
1846 		cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
1847 		module_put(THIS_MODULE);
1848 		goto out_err_crypto_release;
1849 	}
1850 	tcp_ses->min_offload = ctx->min_offload;
1851 	tcp_ses->retrans = ctx->retrans;
1852 	/*
1853 	 * at this point we are the only ones with the pointer
1854 	 * to the struct since the kernel thread not created yet
1855 	 * no need to spinlock this update of tcpStatus
1856 	 */
1857 	spin_lock(&tcp_ses->srv_lock);
1858 	tcp_ses->tcpStatus = CifsNeedNegotiate;
1859 	spin_unlock(&tcp_ses->srv_lock);
1860 
1861 	if ((ctx->max_credits < 20) || (ctx->max_credits > 60000))
1862 		tcp_ses->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
1863 	else
1864 		tcp_ses->max_credits = ctx->max_credits;
1865 
1866 	tcp_ses->nr_targets = 1;
1867 	tcp_ses->ignore_signature = ctx->ignore_signature;
1868 	/* thread spawned, put it on the list */
1869 	spin_lock(&cifs_tcp_ses_lock);
1870 	list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
1871 	spin_unlock(&cifs_tcp_ses_lock);
1872 
1873 	/* queue echo request delayed work */
1874 	queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
1875 
1876 	return tcp_ses;
1877 
1878 out_err_crypto_release:
1879 	cifs_crypto_secmech_release(tcp_ses);
1880 
1881 	put_net(cifs_net_ns(tcp_ses));
1882 
1883 out_err:
1884 	if (tcp_ses) {
1885 		if (SERVER_IS_CHAN(tcp_ses))
1886 			cifs_put_tcp_session(tcp_ses->primary_server, false);
1887 		kfree(tcp_ses->hostname);
1888 		kfree(tcp_ses->leaf_fullpath);
1889 		if (tcp_ses->ssocket)
1890 			sock_release(tcp_ses->ssocket);
1891 		kfree(tcp_ses);
1892 	}
1893 	return ERR_PTR(rc);
1894 }
1895 
1896 /* 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)1897 static int match_session(struct cifs_ses *ses,
1898 			 struct smb3_fs_context *ctx,
1899 			 bool match_super)
1900 {
1901 	struct TCP_Server_Info *server = ses->server;
1902 	enum securityEnum ctx_sec, ses_sec;
1903 
1904 	if (!match_super && ctx->dfs_root_ses != ses->dfs_root_ses)
1905 		return 0;
1906 
1907 	/*
1908 	 * If an existing session is limited to less channels than
1909 	 * requested, it should not be reused
1910 	 */
1911 	if (ses->chan_max < ctx->max_channels)
1912 		return 0;
1913 
1914 	ctx_sec = server->ops->select_sectype(server, ctx->sectype);
1915 	ses_sec = server->ops->select_sectype(server, ses->sectype);
1916 
1917 	if (ctx_sec != ses_sec)
1918 		return 0;
1919 
1920 	switch (ctx_sec) {
1921 	case IAKerb:
1922 	case Kerberos:
1923 		if (!uid_eq(ctx->cred_uid, ses->cred_uid))
1924 			return 0;
1925 		break;
1926 	case NTLMv2:
1927 	case RawNTLMSSP:
1928 	default:
1929 		/* NULL username means anonymous session */
1930 		if (ses->user_name == NULL) {
1931 			if (!ctx->nullauth)
1932 				return 0;
1933 			break;
1934 		}
1935 
1936 		/* anything else takes username/password */
1937 		if (strncmp(ses->user_name,
1938 			    ctx->username ? ctx->username : "",
1939 			    CIFS_MAX_USERNAME_LEN))
1940 			return 0;
1941 		if ((ctx->username && strlen(ctx->username) != 0) &&
1942 		    ses->password != NULL) {
1943 
1944 			/* New mount can only share sessions with an existing mount if:
1945 			 * 1. Both password and password2 match, or
1946 			 * 2. password2 of the old mount matches password of the new mount
1947 			 *    and password of the old mount matches password2 of the new
1948 			 *	  mount
1949 			 */
1950 			if (ses->password2 != NULL && ctx->password2 != NULL) {
1951 				if (!((strncmp(ses->password, ctx->password ?
1952 					ctx->password : "", CIFS_MAX_PASSWORD_LEN) == 0 &&
1953 					strncmp(ses->password2, ctx->password2,
1954 					CIFS_MAX_PASSWORD_LEN) == 0) ||
1955 					(strncmp(ses->password, ctx->password2,
1956 					CIFS_MAX_PASSWORD_LEN) == 0 &&
1957 					strncmp(ses->password2, ctx->password ?
1958 					ctx->password : "", CIFS_MAX_PASSWORD_LEN) == 0)))
1959 					return 0;
1960 
1961 			} else if ((ses->password2 == NULL && ctx->password2 != NULL) ||
1962 				(ses->password2 != NULL && ctx->password2 == NULL)) {
1963 				return 0;
1964 
1965 			} else {
1966 				if (strncmp(ses->password, ctx->password ?
1967 					ctx->password : "", CIFS_MAX_PASSWORD_LEN))
1968 					return 0;
1969 			}
1970 		}
1971 	}
1972 
1973 	if (strcmp(ctx->local_nls->charset, ses->local_nls->charset))
1974 		return 0;
1975 
1976 	return 1;
1977 }
1978 
1979 /**
1980  * cifs_setup_ipc - helper to setup the IPC tcon for the session
1981  * @ses: smb session to issue the request on
1982  * @ctx: the superblock configuration context to use for building the
1983  *       new tree connection for the IPC (interprocess communication RPC)
1984  *
1985  * A new IPC connection is made and stored in the session
1986  * tcon_ipc. The IPC tcon has the same lifetime as the session.
1987  */
1988 static int
cifs_setup_ipc(struct cifs_ses * ses,struct smb3_fs_context * ctx)1989 cifs_setup_ipc(struct cifs_ses *ses, struct smb3_fs_context *ctx)
1990 {
1991 	int rc = 0, xid;
1992 	struct cifs_tcon *tcon;
1993 	char unc[SERVER_NAME_LENGTH + sizeof("//x/IPC$")] = {0};
1994 	bool seal = false;
1995 	struct TCP_Server_Info *server = ses->server;
1996 
1997 	/*
1998 	 * If the mount request that resulted in the creation of the
1999 	 * session requires encryption, force IPC to be encrypted too.
2000 	 */
2001 	if (ctx->seal) {
2002 		if (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION)
2003 			seal = true;
2004 		else {
2005 			cifs_server_dbg(VFS,
2006 				 "IPC: server doesn't support encryption\n");
2007 			return -EOPNOTSUPP;
2008 		}
2009 	}
2010 
2011 	/* no need to setup directory caching on IPC share, so pass in false */
2012 	tcon = tcon_info_alloc(false, netfs_trace_tcon_ref_new_ipc);
2013 	if (tcon == NULL)
2014 		return -ENOMEM;
2015 
2016 	spin_lock(&server->srv_lock);
2017 	scnprintf(unc, sizeof(unc), "\\\\%s\\IPC$", server->hostname);
2018 	spin_unlock(&server->srv_lock);
2019 
2020 	xid = get_xid();
2021 	tcon->ses = ses;
2022 	tcon->ipc = true;
2023 	tcon->seal = seal;
2024 	rc = server->ops->tree_connect(xid, ses, unc, tcon, ctx->local_nls);
2025 	free_xid(xid);
2026 
2027 	if (rc) {
2028 		cifs_server_dbg(VFS, "failed to connect to IPC (rc=%d)\n", rc);
2029 		tconInfoFree(tcon, netfs_trace_tcon_ref_free_ipc_fail);
2030 		goto out;
2031 	}
2032 
2033 	cifs_dbg(FYI, "IPC tcon rc=%d ipc tid=0x%x\n", rc, tcon->tid);
2034 
2035 	spin_lock(&tcon->tc_lock);
2036 	tcon->status = TID_GOOD;
2037 	spin_unlock(&tcon->tc_lock);
2038 	ses->tcon_ipc = tcon;
2039 out:
2040 	return rc;
2041 }
2042 
2043 static struct cifs_ses *
cifs_find_smb_ses(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)2044 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2045 {
2046 	struct cifs_ses *ses, *ret = NULL;
2047 
2048 	spin_lock(&cifs_tcp_ses_lock);
2049 	list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
2050 		spin_lock(&ses->ses_lock);
2051 		if (ses->ses_status == SES_EXITING) {
2052 			spin_unlock(&ses->ses_lock);
2053 			continue;
2054 		}
2055 		spin_lock(&ses->chan_lock);
2056 		if (match_session(ses, ctx, false)) {
2057 			spin_unlock(&ses->chan_lock);
2058 			spin_unlock(&ses->ses_lock);
2059 			ret = ses;
2060 			break;
2061 		}
2062 		spin_unlock(&ses->chan_lock);
2063 		spin_unlock(&ses->ses_lock);
2064 	}
2065 	if (ret)
2066 		cifs_smb_ses_inc_refcount(ret);
2067 	spin_unlock(&cifs_tcp_ses_lock);
2068 	return ret;
2069 }
2070 
__cifs_put_smb_ses(struct cifs_ses * ses)2071 void __cifs_put_smb_ses(struct cifs_ses *ses)
2072 {
2073 	struct TCP_Server_Info *server = ses->server;
2074 	struct cifs_tcon *tcon;
2075 	unsigned int xid;
2076 	size_t i;
2077 	bool do_logoff;
2078 	int rc;
2079 
2080 	spin_lock(&cifs_tcp_ses_lock);
2081 	spin_lock(&ses->ses_lock);
2082 	cifs_dbg(FYI, "%s: id=0x%llx ses_count=%d ses_status=%u ipc=%s\n",
2083 		 __func__, ses->Suid, ses->ses_count, ses->ses_status,
2084 		 ses->tcon_ipc ? ses->tcon_ipc->tree_name : "none");
2085 	if (ses->ses_status == SES_EXITING || --ses->ses_count > 0) {
2086 		spin_unlock(&ses->ses_lock);
2087 		spin_unlock(&cifs_tcp_ses_lock);
2088 		return;
2089 	}
2090 	/* ses_count can never go negative */
2091 	WARN_ON(ses->ses_count < 0);
2092 
2093 	spin_lock(&ses->chan_lock);
2094 	cifs_chan_clear_need_reconnect(ses, server);
2095 	spin_unlock(&ses->chan_lock);
2096 
2097 	do_logoff = ses->ses_status == SES_GOOD && server->ops->logoff;
2098 	ses->ses_status = SES_EXITING;
2099 	tcon = ses->tcon_ipc;
2100 	ses->tcon_ipc = NULL;
2101 	spin_unlock(&ses->ses_lock);
2102 	spin_unlock(&cifs_tcp_ses_lock);
2103 
2104 	/*
2105 	 * On session close, the IPC is closed and the server must release all
2106 	 * tcons of the session.  No need to send a tree disconnect here.
2107 	 *
2108 	 * Besides, it will make the server to not close durable and resilient
2109 	 * files on session close, as specified in MS-SMB2 3.3.5.6 Receiving an
2110 	 * SMB2 LOGOFF Request.
2111 	 */
2112 	tconInfoFree(tcon, netfs_trace_tcon_ref_free_ipc);
2113 	if (do_logoff) {
2114 		xid = get_xid();
2115 		rc = server->ops->logoff(xid, ses);
2116 		if (rc)
2117 			cifs_server_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
2118 				__func__, rc);
2119 		_free_xid(xid);
2120 	}
2121 
2122 	spin_lock(&cifs_tcp_ses_lock);
2123 	list_del_init(&ses->smb_ses_list);
2124 	spin_unlock(&cifs_tcp_ses_lock);
2125 
2126 	/* close any extra channels */
2127 	for (i = 1; i < ses->chan_count; i++) {
2128 		if (ses->chans[i].iface) {
2129 			kref_put(&ses->chans[i].iface->refcount, release_iface);
2130 			ses->chans[i].iface = NULL;
2131 		}
2132 		cifs_put_tcp_session(ses->chans[i].server, 0);
2133 		ses->chans[i].server = NULL;
2134 	}
2135 
2136 	/* we now account for primary channel in iface->refcount */
2137 	if (ses->chans[0].iface) {
2138 		kref_put(&ses->chans[0].iface->refcount, release_iface);
2139 		ses->chans[0].server = NULL;
2140 	}
2141 
2142 	sesInfoFree(ses);
2143 	cifs_put_tcp_session(server, 0);
2144 }
2145 
2146 #ifdef CONFIG_KEYS
2147 
2148 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
2149 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
2150 
2151 /* Populate username and pw fields from keyring if possible */
2152 static int
cifs_set_cifscreds(struct smb3_fs_context * ctx,struct cifs_ses * ses)2153 cifs_set_cifscreds(struct smb3_fs_context *ctx, struct cifs_ses *ses)
2154 {
2155 	int rc = 0;
2156 	int is_domain = 0;
2157 	const char *delim, *payload;
2158 	char *desc;
2159 	ssize_t len;
2160 	struct key *key;
2161 	struct TCP_Server_Info *server = ses->server;
2162 	struct sockaddr_in *sa;
2163 	struct sockaddr_in6 *sa6;
2164 	const struct user_key_payload *upayload;
2165 
2166 	desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
2167 	if (!desc)
2168 		return -ENOMEM;
2169 
2170 	/* try to find an address key first */
2171 	switch (server->dstaddr.ss_family) {
2172 	case AF_INET:
2173 		sa = (struct sockaddr_in *)&server->dstaddr;
2174 		sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
2175 		break;
2176 	case AF_INET6:
2177 		sa6 = (struct sockaddr_in6 *)&server->dstaddr;
2178 		sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
2179 		break;
2180 	default:
2181 		cifs_dbg(FYI, "Bad ss_family (%hu)\n",
2182 			 server->dstaddr.ss_family);
2183 		rc = -EINVAL;
2184 		goto out_err;
2185 	}
2186 
2187 	cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2188 	key = request_key(&key_type_logon, desc, "");
2189 	if (IS_ERR(key)) {
2190 		if (!ses->domainName) {
2191 			cifs_dbg(FYI, "domainName is NULL\n");
2192 			rc = PTR_ERR(key);
2193 			goto out_err;
2194 		}
2195 
2196 		/* didn't work, try to find a domain key */
2197 		sprintf(desc, "cifs:d:%s", ses->domainName);
2198 		cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2199 		key = request_key(&key_type_logon, desc, "");
2200 		if (IS_ERR(key)) {
2201 			rc = PTR_ERR(key);
2202 			goto out_err;
2203 		}
2204 		is_domain = 1;
2205 	}
2206 
2207 	down_read(&key->sem);
2208 	upayload = user_key_payload_locked(key);
2209 	if (IS_ERR_OR_NULL(upayload)) {
2210 		rc = upayload ? PTR_ERR(upayload) : -EINVAL;
2211 		goto out_key_put;
2212 	}
2213 
2214 	/* find first : in payload */
2215 	payload = upayload->data;
2216 	delim = strnchr(payload, upayload->datalen, ':');
2217 	cifs_dbg(FYI, "payload=%s\n", payload);
2218 	if (!delim) {
2219 		cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
2220 			 upayload->datalen);
2221 		rc = -EINVAL;
2222 		goto out_key_put;
2223 	}
2224 
2225 	len = delim - payload;
2226 	if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
2227 		cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
2228 			 len);
2229 		rc = -EINVAL;
2230 		goto out_key_put;
2231 	}
2232 
2233 	ctx->username = kstrndup(payload, len, GFP_KERNEL);
2234 	if (!ctx->username) {
2235 		cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
2236 			 len);
2237 		rc = -ENOMEM;
2238 		goto out_key_put;
2239 	}
2240 	cifs_dbg(FYI, "%s: username=%s\n", __func__, ctx->username);
2241 
2242 	len = key->datalen - (len + 1);
2243 	if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
2244 		cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
2245 		rc = -EINVAL;
2246 		kfree(ctx->username);
2247 		ctx->username = NULL;
2248 		goto out_key_put;
2249 	}
2250 
2251 	++delim;
2252 	/* BB consider adding support for password2 (Key Rotation) for multiuser in future */
2253 	ctx->password = kstrndup(delim, len, GFP_KERNEL);
2254 	if (!ctx->password) {
2255 		cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
2256 			 len);
2257 		rc = -ENOMEM;
2258 		kfree(ctx->username);
2259 		ctx->username = NULL;
2260 		goto out_key_put;
2261 	}
2262 
2263 	/*
2264 	 * If we have a domain key then we must set the domainName in the
2265 	 * for the request.
2266 	 */
2267 	if (is_domain && ses->domainName) {
2268 		ctx->domainname = kstrdup(ses->domainName, GFP_KERNEL);
2269 		if (!ctx->domainname) {
2270 			cifs_dbg(FYI, "Unable to allocate %zd bytes for domain\n",
2271 				 len);
2272 			rc = -ENOMEM;
2273 			kfree(ctx->username);
2274 			ctx->username = NULL;
2275 			kfree_sensitive(ctx->password);
2276 			/* no need to free ctx->password2 since not allocated in this path */
2277 			ctx->password = NULL;
2278 			goto out_key_put;
2279 		}
2280 	}
2281 
2282 	strscpy(ctx->workstation_name, ses->workstation_name, sizeof(ctx->workstation_name));
2283 
2284 out_key_put:
2285 	up_read(&key->sem);
2286 	key_put(key);
2287 out_err:
2288 	kfree(desc);
2289 	cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2290 	return rc;
2291 }
2292 #else /* ! CONFIG_KEYS */
2293 static inline int
cifs_set_cifscreds(struct smb3_fs_context * ctx,struct cifs_ses * ses)2294 cifs_set_cifscreds(struct smb3_fs_context *ctx __attribute__((unused)),
2295 		   struct cifs_ses *ses __attribute__((unused)))
2296 {
2297 	return -ENOSYS;
2298 }
2299 #endif /* CONFIG_KEYS */
2300 
2301 /**
2302  * cifs_get_smb_ses - get a session matching @ctx data from @server
2303  * @server: server to setup the session to
2304  * @ctx: superblock configuration context to use to setup the session
2305  *
2306  * This function assumes it is being called from cifs_mount() where we
2307  * already got a server reference (server refcount +1). See
2308  * cifs_get_tcon() for refcount explanations.
2309  */
2310 struct cifs_ses *
cifs_get_smb_ses(struct TCP_Server_Info * server,struct smb3_fs_context * ctx)2311 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb3_fs_context *ctx)
2312 {
2313 	int rc = 0;
2314 	int retries = 0;
2315 	unsigned int xid;
2316 	struct cifs_ses *ses;
2317 	struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2318 	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2319 
2320 	xid = get_xid();
2321 
2322 	ses = cifs_find_smb_ses(server, ctx);
2323 	if (ses) {
2324 		cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2325 			 ses->ses_status);
2326 
2327 		spin_lock(&ses->chan_lock);
2328 		if (cifs_chan_needs_reconnect(ses, server)) {
2329 			spin_unlock(&ses->chan_lock);
2330 			cifs_dbg(FYI, "Session needs reconnect\n");
2331 
2332 			mutex_lock(&ses->session_mutex);
2333 
2334 retry_old_session:
2335 			rc = cifs_negotiate_protocol(xid, ses, server);
2336 			if (rc) {
2337 				mutex_unlock(&ses->session_mutex);
2338 				/* problem -- put our ses reference */
2339 				cifs_put_smb_ses(ses);
2340 				free_xid(xid);
2341 				return ERR_PTR(rc);
2342 			}
2343 
2344 			rc = cifs_setup_session(xid, ses, server,
2345 						ctx->local_nls);
2346 			if (rc) {
2347 				if (((rc == -EACCES) || (rc == -EKEYEXPIRED) ||
2348 					(rc == -EKEYREVOKED)) && !retries && ses->password2) {
2349 					retries++;
2350 					cifs_dbg(FYI, "Session reconnect failed, retrying with alternate password\n");
2351 					swap(ses->password, ses->password2);
2352 					goto retry_old_session;
2353 				}
2354 				mutex_unlock(&ses->session_mutex);
2355 				/* problem -- put our reference */
2356 				cifs_put_smb_ses(ses);
2357 				free_xid(xid);
2358 				return ERR_PTR(rc);
2359 			}
2360 			mutex_unlock(&ses->session_mutex);
2361 
2362 			spin_lock(&ses->chan_lock);
2363 		}
2364 		spin_unlock(&ses->chan_lock);
2365 
2366 		/* existing SMB ses has a server reference already */
2367 		cifs_put_tcp_session(server, 0);
2368 		free_xid(xid);
2369 		return ses;
2370 	}
2371 
2372 	rc = -ENOMEM;
2373 
2374 	cifs_dbg(FYI, "Existing smb sess not found\n");
2375 	ses = sesInfoAlloc();
2376 	if (ses == NULL)
2377 		goto get_ses_fail;
2378 
2379 	/* new SMB session uses our server ref */
2380 	ses->server = server;
2381 	if (server->dstaddr.ss_family == AF_INET6)
2382 		sprintf(ses->ip_addr, "%pI6", &addr6->sin6_addr);
2383 	else
2384 		sprintf(ses->ip_addr, "%pI4", &addr->sin_addr);
2385 
2386 	if (ctx->username) {
2387 		ses->user_name = kstrdup(ctx->username, GFP_KERNEL);
2388 		if (!ses->user_name)
2389 			goto get_ses_fail;
2390 	}
2391 
2392 	/* ctx->password freed at unmount */
2393 	if (ctx->password) {
2394 		ses->password = kstrdup(ctx->password, GFP_KERNEL);
2395 		if (!ses->password)
2396 			goto get_ses_fail;
2397 	}
2398 	/* ctx->password freed at unmount */
2399 	if (ctx->password2) {
2400 		ses->password2 = kstrdup(ctx->password2, GFP_KERNEL);
2401 		if (!ses->password2)
2402 			goto get_ses_fail;
2403 	}
2404 	if (ctx->domainname) {
2405 		ses->domainName = kstrdup(ctx->domainname, GFP_KERNEL);
2406 		if (!ses->domainName)
2407 			goto get_ses_fail;
2408 	}
2409 
2410 	strscpy(ses->workstation_name, ctx->workstation_name, sizeof(ses->workstation_name));
2411 
2412 	if (ctx->domainauto)
2413 		ses->domainAuto = ctx->domainauto;
2414 	ses->cred_uid = ctx->cred_uid;
2415 	ses->linux_uid = ctx->linux_uid;
2416 
2417 	ses->sectype = ctx->sectype;
2418 	ses->sign = ctx->sign;
2419 	ses->local_nls = load_nls(ctx->local_nls->charset);
2420 
2421 	/* add server as first channel */
2422 	spin_lock(&ses->chan_lock);
2423 	ses->chans[0].server = server;
2424 	ses->chan_count = 1;
2425 	ses->chan_max = ctx->multichannel ? ctx->max_channels:1;
2426 	ses->chans_need_reconnect = 1;
2427 	spin_unlock(&ses->chan_lock);
2428 
2429 retry_new_session:
2430 	mutex_lock(&ses->session_mutex);
2431 	rc = cifs_negotiate_protocol(xid, ses, server);
2432 	if (!rc)
2433 		rc = cifs_setup_session(xid, ses, server, ctx->local_nls);
2434 	mutex_unlock(&ses->session_mutex);
2435 
2436 	/* each channel uses a different signing key */
2437 	spin_lock(&ses->chan_lock);
2438 	memcpy(ses->chans[0].signkey, ses->smb3signingkey,
2439 	       sizeof(ses->smb3signingkey));
2440 	spin_unlock(&ses->chan_lock);
2441 
2442 	if (rc) {
2443 		if (((rc == -EACCES) || (rc == -EKEYEXPIRED) ||
2444 			(rc == -EKEYREVOKED)) && !retries && ses->password2) {
2445 			retries++;
2446 			cifs_dbg(FYI, "Session setup failed, retrying with alternate password\n");
2447 			swap(ses->password, ses->password2);
2448 			goto retry_new_session;
2449 		} else
2450 			goto get_ses_fail;
2451 	}
2452 
2453 	/*
2454 	 * success, put it on the list and add it as first channel
2455 	 * note: the session becomes active soon after this. So you'll
2456 	 * need to lock before changing something in the session.
2457 	 */
2458 	spin_lock(&cifs_tcp_ses_lock);
2459 	ses->dfs_root_ses = ctx->dfs_root_ses;
2460 	list_add(&ses->smb_ses_list, &server->smb_ses_list);
2461 	spin_unlock(&cifs_tcp_ses_lock);
2462 
2463 	cifs_setup_ipc(ses, ctx);
2464 
2465 	free_xid(xid);
2466 
2467 	return ses;
2468 
2469 get_ses_fail:
2470 	sesInfoFree(ses);
2471 	free_xid(xid);
2472 	return ERR_PTR(rc);
2473 }
2474 
2475 /* this function must be called with tc_lock held */
match_tcon(struct cifs_tcon * tcon,struct smb3_fs_context * ctx)2476 static int match_tcon(struct cifs_tcon *tcon, struct smb3_fs_context *ctx)
2477 {
2478 	struct TCP_Server_Info *server = tcon->ses->server;
2479 
2480 	if (tcon->status == TID_EXITING)
2481 		return 0;
2482 
2483 	if (tcon->origin_fullpath) {
2484 		if (!ctx->source ||
2485 		    !dfs_src_pathname_equal(ctx->source,
2486 					    tcon->origin_fullpath))
2487 			return 0;
2488 	} else if (!server->leaf_fullpath &&
2489 		   strncmp(tcon->tree_name, ctx->UNC, MAX_TREE_SIZE)) {
2490 		return 0;
2491 	}
2492 	if (tcon->seal != ctx->seal)
2493 		return 0;
2494 	if (tcon->snapshot_time != ctx->snapshot_time)
2495 		return 0;
2496 	if (tcon->handle_timeout != ctx->handle_timeout)
2497 		return 0;
2498 	if (tcon->no_lease != ctx->no_lease)
2499 		return 0;
2500 	if (tcon->nodelete != ctx->nodelete)
2501 		return 0;
2502 	if (tcon->posix_extensions != ctx->linux_ext)
2503 		return 0;
2504 	return 1;
2505 }
2506 
2507 static struct cifs_tcon *
cifs_find_tcon(struct cifs_ses * ses,struct smb3_fs_context * ctx)2508 cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2509 {
2510 	struct cifs_tcon *tcon;
2511 
2512 	spin_lock(&cifs_tcp_ses_lock);
2513 	list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2514 		spin_lock(&tcon->tc_lock);
2515 		if (!match_tcon(tcon, ctx)) {
2516 			spin_unlock(&tcon->tc_lock);
2517 			continue;
2518 		}
2519 		++tcon->tc_count;
2520 		trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count,
2521 				    netfs_trace_tcon_ref_get_find);
2522 		spin_unlock(&tcon->tc_lock);
2523 		spin_unlock(&cifs_tcp_ses_lock);
2524 		return tcon;
2525 	}
2526 	spin_unlock(&cifs_tcp_ses_lock);
2527 	return NULL;
2528 }
2529 
2530 void
cifs_put_tcon(struct cifs_tcon * tcon,enum smb3_tcon_ref_trace trace)2531 cifs_put_tcon(struct cifs_tcon *tcon, enum smb3_tcon_ref_trace trace)
2532 {
2533 	unsigned int xid;
2534 	struct cifs_ses *ses;
2535 	LIST_HEAD(ses_list);
2536 
2537 	/*
2538 	 * IPC tcon share the lifetime of their session and are
2539 	 * destroyed in the session put function
2540 	 */
2541 	if (tcon == NULL || tcon->ipc)
2542 		return;
2543 
2544 	ses = tcon->ses;
2545 	cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2546 	spin_lock(&cifs_tcp_ses_lock);
2547 	spin_lock(&tcon->tc_lock);
2548 	trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count - 1, trace);
2549 	if (--tcon->tc_count > 0) {
2550 		spin_unlock(&tcon->tc_lock);
2551 		spin_unlock(&cifs_tcp_ses_lock);
2552 		return;
2553 	}
2554 
2555 	/* tc_count can never go negative */
2556 	WARN_ON(tcon->tc_count < 0);
2557 
2558 	list_del_init(&tcon->tcon_list);
2559 	tcon->status = TID_EXITING;
2560 	spin_unlock(&tcon->tc_lock);
2561 	spin_unlock(&cifs_tcp_ses_lock);
2562 
2563 	/* cancel polling of interfaces */
2564 	cancel_delayed_work_sync(&tcon->query_interfaces);
2565 #ifdef CONFIG_CIFS_DFS_UPCALL
2566 	cancel_delayed_work_sync(&tcon->dfs_cache_work);
2567 	list_replace_init(&tcon->dfs_ses_list, &ses_list);
2568 #endif
2569 
2570 	if (tcon->use_witness) {
2571 		int rc;
2572 
2573 		rc = cifs_swn_unregister(tcon);
2574 		if (rc < 0) {
2575 			cifs_dbg(VFS, "%s: Failed to unregister for witness notifications: %d\n",
2576 					__func__, rc);
2577 		}
2578 	}
2579 
2580 	xid = get_xid();
2581 	if (ses->server->ops->tree_disconnect)
2582 		ses->server->ops->tree_disconnect(xid, tcon);
2583 	_free_xid(xid);
2584 
2585 	cifs_fscache_release_super_cookie(tcon);
2586 	tconInfoFree(tcon, netfs_trace_tcon_ref_free);
2587 	cifs_put_smb_ses(ses);
2588 #ifdef CONFIG_CIFS_DFS_UPCALL
2589 	dfs_put_root_smb_sessions(&ses_list);
2590 #endif
2591 }
2592 
2593 /**
2594  * cifs_get_tcon - get a tcon matching @ctx data from @ses
2595  * @ses: smb session to issue the request on
2596  * @ctx: the superblock configuration context to use for building the
2597  *
2598  * - tcon refcount is the number of mount points using the tcon.
2599  * - ses refcount is the number of tcon using the session.
2600  *
2601  * 1. This function assumes it is being called from cifs_mount() where
2602  *    we already got a session reference (ses refcount +1).
2603  *
2604  * 2. Since we're in the context of adding a mount point, the end
2605  *    result should be either:
2606  *
2607  * a) a new tcon already allocated with refcount=1 (1 mount point) and
2608  *    its session refcount incremented (1 new tcon). This +1 was
2609  *    already done in (1).
2610  *
2611  * b) an existing tcon with refcount+1 (add a mount point to it) and
2612  *    identical ses refcount (no new tcon). Because of (1) we need to
2613  *    decrement the ses refcount.
2614  */
2615 static struct cifs_tcon *
cifs_get_tcon(struct cifs_ses * ses,struct smb3_fs_context * ctx)2616 cifs_get_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx)
2617 {
2618 	struct cifs_tcon *tcon;
2619 	bool nohandlecache;
2620 	int rc, xid;
2621 
2622 	tcon = cifs_find_tcon(ses, ctx);
2623 	if (tcon) {
2624 		/*
2625 		 * tcon has refcount already incremented but we need to
2626 		 * decrement extra ses reference gotten by caller (case b)
2627 		 */
2628 		cifs_dbg(FYI, "Found match on UNC path\n");
2629 		cifs_put_smb_ses(ses);
2630 		return tcon;
2631 	}
2632 
2633 	if (!ses->server->ops->tree_connect) {
2634 		rc = -ENOSYS;
2635 		goto out_fail;
2636 	}
2637 
2638 	if (ses->server->dialect >= SMB20_PROT_ID &&
2639 	    (ses->server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING))
2640 		nohandlecache = ctx->nohandlecache || !dir_cache_timeout;
2641 	else
2642 		nohandlecache = true;
2643 	tcon = tcon_info_alloc(!nohandlecache, netfs_trace_tcon_ref_new);
2644 	if (tcon == NULL) {
2645 		rc = -ENOMEM;
2646 		goto out_fail;
2647 	}
2648 	tcon->nohandlecache = nohandlecache;
2649 
2650 	if (ctx->snapshot_time) {
2651 		if (ses->server->vals->protocol_id == 0) {
2652 			cifs_dbg(VFS,
2653 			     "Use SMB2 or later for snapshot mount option\n");
2654 			rc = -EOPNOTSUPP;
2655 			goto out_fail;
2656 		} else
2657 			tcon->snapshot_time = ctx->snapshot_time;
2658 	}
2659 
2660 	if (ctx->handle_timeout) {
2661 		if (ses->server->vals->protocol_id == 0) {
2662 			cifs_dbg(VFS,
2663 			     "Use SMB2.1 or later for handle timeout option\n");
2664 			rc = -EOPNOTSUPP;
2665 			goto out_fail;
2666 		} else
2667 			tcon->handle_timeout = ctx->handle_timeout;
2668 	}
2669 
2670 	tcon->ses = ses;
2671 	if (ctx->password) {
2672 		tcon->password = kstrdup(ctx->password, GFP_KERNEL);
2673 		if (!tcon->password) {
2674 			rc = -ENOMEM;
2675 			goto out_fail;
2676 		}
2677 	}
2678 
2679 	if (ctx->seal) {
2680 		if (ses->server->vals->protocol_id == 0) {
2681 			cifs_dbg(VFS,
2682 				 "SMB3 or later required for encryption\n");
2683 			rc = -EOPNOTSUPP;
2684 			goto out_fail;
2685 		} else if (tcon->ses->server->capabilities &
2686 					SMB2_GLOBAL_CAP_ENCRYPTION)
2687 			tcon->seal = true;
2688 		else {
2689 			cifs_dbg(VFS, "Encryption is not supported on share\n");
2690 			rc = -EOPNOTSUPP;
2691 			goto out_fail;
2692 		}
2693 	}
2694 
2695 	if (ctx->linux_ext) {
2696 		if (ses->server->posix_ext_supported) {
2697 			tcon->posix_extensions = true;
2698 			pr_warn_once("SMB3.11 POSIX Extensions are experimental\n");
2699 		} else if ((ses->server->vals->protocol_id == SMB311_PROT_ID) ||
2700 		    (strcmp(ses->server->vals->version_string,
2701 		     SMB3ANY_VERSION_STRING) == 0) ||
2702 		    (strcmp(ses->server->vals->version_string,
2703 		     SMBDEFAULT_VERSION_STRING) == 0)) {
2704 			cifs_dbg(VFS, "Server does not support mounting with posix SMB3.11 extensions\n");
2705 			rc = -EOPNOTSUPP;
2706 			goto out_fail;
2707 		} else if (ses->server->vals->protocol_id == SMB10_PROT_ID)
2708 			if (cap_unix(ses))
2709 				cifs_dbg(FYI, "Unix Extensions requested on SMB1 mount\n");
2710 			else {
2711 				cifs_dbg(VFS, "SMB1 Unix Extensions not supported by server\n");
2712 				rc = -EOPNOTSUPP;
2713 				goto out_fail;
2714 		} else {
2715 			cifs_dbg(VFS,
2716 				"Check vers= mount option. SMB3.11 disabled but required for POSIX extensions\n");
2717 			rc = -EOPNOTSUPP;
2718 			goto out_fail;
2719 		}
2720 	}
2721 
2722 	xid = get_xid();
2723 	rc = ses->server->ops->tree_connect(xid, ses, ctx->UNC, tcon,
2724 					    ctx->local_nls);
2725 	free_xid(xid);
2726 	cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2727 	if (rc)
2728 		goto out_fail;
2729 
2730 	tcon->use_persistent = false;
2731 	/* check if SMB2 or later, CIFS does not support persistent handles */
2732 	if (ctx->persistent) {
2733 		if (ses->server->vals->protocol_id == 0) {
2734 			cifs_dbg(VFS,
2735 			     "SMB3 or later required for persistent handles\n");
2736 			rc = -EOPNOTSUPP;
2737 			goto out_fail;
2738 		} else if (ses->server->capabilities &
2739 			   SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2740 			tcon->use_persistent = true;
2741 		else /* persistent handles requested but not supported */ {
2742 			cifs_dbg(VFS,
2743 				"Persistent handles not supported on share\n");
2744 			rc = -EOPNOTSUPP;
2745 			goto out_fail;
2746 		}
2747 	} else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2748 	     && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2749 	     && (ctx->nopersistent == false)) {
2750 		cifs_dbg(FYI, "enabling persistent handles\n");
2751 		tcon->use_persistent = true;
2752 	} else if (ctx->resilient) {
2753 		if (ses->server->vals->protocol_id == 0) {
2754 			cifs_dbg(VFS,
2755 			     "SMB2.1 or later required for resilient handles\n");
2756 			rc = -EOPNOTSUPP;
2757 			goto out_fail;
2758 		}
2759 		tcon->use_resilient = true;
2760 	}
2761 
2762 	tcon->use_witness = false;
2763 	if (IS_ENABLED(CONFIG_CIFS_SWN_UPCALL) && ctx->witness) {
2764 		if (ses->server->vals->protocol_id >= SMB30_PROT_ID) {
2765 			if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER) {
2766 				/*
2767 				 * Set witness in use flag in first place
2768 				 * to retry registration in the echo task
2769 				 */
2770 				tcon->use_witness = true;
2771 				/* And try to register immediately */
2772 				rc = cifs_swn_register(tcon);
2773 				if (rc < 0) {
2774 					cifs_dbg(VFS, "Failed to register for witness notifications: %d\n", rc);
2775 					goto out_fail;
2776 				}
2777 			} else {
2778 				/* TODO: try to extend for non-cluster uses (eg multichannel) */
2779 				cifs_dbg(VFS, "witness requested on mount but no CLUSTER capability on share\n");
2780 				rc = -EOPNOTSUPP;
2781 				goto out_fail;
2782 			}
2783 		} else {
2784 			cifs_dbg(VFS, "SMB3 or later required for witness option\n");
2785 			rc = -EOPNOTSUPP;
2786 			goto out_fail;
2787 		}
2788 	}
2789 
2790 	/* If the user really knows what they are doing they can override */
2791 	if (tcon->share_flags & SMB2_SHAREFLAG_NO_CACHING) {
2792 		if (ctx->cache_ro)
2793 			cifs_dbg(VFS, "cache=ro requested on mount but NO_CACHING flag set on share\n");
2794 		else if (ctx->cache_rw)
2795 			cifs_dbg(VFS, "cache=singleclient requested on mount but NO_CACHING flag set on share\n");
2796 	}
2797 
2798 	if (ctx->no_lease) {
2799 		if (ses->server->vals->protocol_id == 0) {
2800 			cifs_dbg(VFS,
2801 				"SMB2 or later required for nolease option\n");
2802 			rc = -EOPNOTSUPP;
2803 			goto out_fail;
2804 		} else
2805 			tcon->no_lease = ctx->no_lease;
2806 	}
2807 
2808 	/*
2809 	 * We can have only one retry value for a connection to a share so for
2810 	 * resources mounted more than once to the same server share the last
2811 	 * value passed in for the retry flag is used.
2812 	 */
2813 	tcon->retry = ctx->retry;
2814 	tcon->nocase = ctx->nocase;
2815 	tcon->broken_sparse_sup = ctx->no_sparse;
2816 	tcon->max_cached_dirs = ctx->max_cached_dirs;
2817 	tcon->nodelete = ctx->nodelete;
2818 	tcon->local_lease = ctx->local_lease;
2819 	tcon->status = TID_GOOD;
2820 
2821 	if (ses->server->dialect >= SMB30_PROT_ID &&
2822 	    (ses->server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
2823 		/* schedule query interfaces poll */
2824 		queue_delayed_work(cifsiod_wq, &tcon->query_interfaces,
2825 				   (SMB_INTERFACE_POLL_INTERVAL * HZ));
2826 	}
2827 	spin_lock(&cifs_tcp_ses_lock);
2828 	list_add(&tcon->tcon_list, &ses->tcon_list);
2829 	spin_unlock(&cifs_tcp_ses_lock);
2830 
2831 	return tcon;
2832 
2833 out_fail:
2834 	tconInfoFree(tcon, netfs_trace_tcon_ref_free_fail);
2835 	return ERR_PTR(rc);
2836 }
2837 
2838 void
cifs_put_tlink(struct tcon_link * tlink)2839 cifs_put_tlink(struct tcon_link *tlink)
2840 {
2841 	if (!tlink || IS_ERR(tlink))
2842 		return;
2843 
2844 	if (!atomic_dec_and_test(&tlink->tl_count) ||
2845 	    test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2846 		tlink->tl_time = jiffies;
2847 		return;
2848 	}
2849 
2850 	if (!IS_ERR(tlink_tcon(tlink)))
2851 		cifs_put_tcon(tlink_tcon(tlink), netfs_trace_tcon_ref_put_tlink);
2852 	kfree(tlink);
2853 }
2854 
2855 static int
compare_mount_options(struct super_block * sb,struct cifs_mnt_data * mnt_data)2856 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
2857 {
2858 	struct cifs_sb_info *old = CIFS_SB(sb);
2859 	struct cifs_sb_info *new = mnt_data->cifs_sb;
2860 	unsigned int oldflags = old->mnt_cifs_flags & CIFS_MOUNT_MASK;
2861 	unsigned int newflags = new->mnt_cifs_flags & CIFS_MOUNT_MASK;
2862 
2863 	if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
2864 		return 0;
2865 
2866 	if (old->mnt_cifs_serverino_autodisabled)
2867 		newflags &= ~CIFS_MOUNT_SERVER_INUM;
2868 
2869 	if (oldflags != newflags)
2870 		return 0;
2871 
2872 	/*
2873 	 * We want to share sb only if we don't specify an r/wsize or
2874 	 * specified r/wsize is greater than or equal to existing one.
2875 	 */
2876 	if (new->ctx->wsize && new->ctx->wsize < old->ctx->wsize)
2877 		return 0;
2878 
2879 	if (new->ctx->rsize && new->ctx->rsize < old->ctx->rsize)
2880 		return 0;
2881 
2882 	if (!uid_eq(old->ctx->linux_uid, new->ctx->linux_uid) ||
2883 	    !gid_eq(old->ctx->linux_gid, new->ctx->linux_gid))
2884 		return 0;
2885 
2886 	if (old->ctx->file_mode != new->ctx->file_mode ||
2887 	    old->ctx->dir_mode != new->ctx->dir_mode)
2888 		return 0;
2889 
2890 	if (strcmp(old->local_nls->charset, new->local_nls->charset))
2891 		return 0;
2892 
2893 	if (old->ctx->acregmax != new->ctx->acregmax)
2894 		return 0;
2895 	if (old->ctx->acdirmax != new->ctx->acdirmax)
2896 		return 0;
2897 	if (old->ctx->closetimeo != new->ctx->closetimeo)
2898 		return 0;
2899 	if (old->ctx->reparse_type != new->ctx->reparse_type)
2900 		return 0;
2901 
2902 	return 1;
2903 }
2904 
match_prepath(struct super_block * sb,struct cifs_tcon * tcon,struct cifs_mnt_data * mnt_data)2905 static int match_prepath(struct super_block *sb,
2906 			 struct cifs_tcon *tcon,
2907 			 struct cifs_mnt_data *mnt_data)
2908 {
2909 	struct smb3_fs_context *ctx = mnt_data->ctx;
2910 	struct cifs_sb_info *old = CIFS_SB(sb);
2911 	struct cifs_sb_info *new = mnt_data->cifs_sb;
2912 	bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2913 		old->prepath;
2914 	bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
2915 		new->prepath;
2916 
2917 	if (tcon->origin_fullpath &&
2918 	    dfs_src_pathname_equal(tcon->origin_fullpath, ctx->source))
2919 		return 1;
2920 
2921 	if (old_set && new_set && !strcmp(new->prepath, old->prepath))
2922 		return 1;
2923 	else if (!old_set && !new_set)
2924 		return 1;
2925 
2926 	return 0;
2927 }
2928 
2929 int
cifs_match_super(struct super_block * sb,void * data)2930 cifs_match_super(struct super_block *sb, void *data)
2931 {
2932 	struct cifs_mnt_data *mnt_data = data;
2933 	struct smb3_fs_context *ctx;
2934 	struct cifs_sb_info *cifs_sb;
2935 	struct TCP_Server_Info *tcp_srv;
2936 	struct cifs_ses *ses;
2937 	struct cifs_tcon *tcon;
2938 	struct tcon_link *tlink;
2939 	int rc = 0;
2940 
2941 	spin_lock(&cifs_tcp_ses_lock);
2942 	cifs_sb = CIFS_SB(sb);
2943 
2944 	/* We do not want to use a superblock that has been shutdown */
2945 	if (CIFS_MOUNT_SHUTDOWN & cifs_sb->mnt_cifs_flags) {
2946 		spin_unlock(&cifs_tcp_ses_lock);
2947 		return 0;
2948 	}
2949 
2950 	tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
2951 	if (IS_ERR_OR_NULL(tlink)) {
2952 		pr_warn_once("%s: skip super matching due to bad tlink(%p)\n",
2953 			     __func__, tlink);
2954 		spin_unlock(&cifs_tcp_ses_lock);
2955 		return 0;
2956 	}
2957 	tcon = tlink_tcon(tlink);
2958 	ses = tcon->ses;
2959 	tcp_srv = ses->server;
2960 
2961 	ctx = mnt_data->ctx;
2962 
2963 	spin_lock(&tcp_srv->srv_lock);
2964 	spin_lock(&ses->ses_lock);
2965 	spin_lock(&ses->chan_lock);
2966 	spin_lock(&tcon->tc_lock);
2967 	if (!match_server(tcp_srv, ctx, true) ||
2968 	    !match_session(ses, ctx, true) ||
2969 	    !match_tcon(tcon, ctx) ||
2970 	    !match_prepath(sb, tcon, mnt_data)) {
2971 		rc = 0;
2972 		goto out;
2973 	}
2974 
2975 	rc = compare_mount_options(sb, mnt_data);
2976 out:
2977 	spin_unlock(&tcon->tc_lock);
2978 	spin_unlock(&ses->chan_lock);
2979 	spin_unlock(&ses->ses_lock);
2980 	spin_unlock(&tcp_srv->srv_lock);
2981 
2982 	spin_unlock(&cifs_tcp_ses_lock);
2983 	cifs_put_tlink(tlink);
2984 	return rc;
2985 }
2986 
2987 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2988 static struct lock_class_key cifs_key[2];
2989 static struct lock_class_key cifs_slock_key[2];
2990 
2991 static inline void
cifs_reclassify_socket4(struct socket * sock)2992 cifs_reclassify_socket4(struct socket *sock)
2993 {
2994 	struct sock *sk = sock->sk;
2995 
2996 	BUG_ON(!sock_allow_reclassification(sk));
2997 	sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
2998 		&cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
2999 }
3000 
3001 static inline void
cifs_reclassify_socket6(struct socket * sock)3002 cifs_reclassify_socket6(struct socket *sock)
3003 {
3004 	struct sock *sk = sock->sk;
3005 
3006 	BUG_ON(!sock_allow_reclassification(sk));
3007 	sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
3008 		&cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
3009 }
3010 #else
3011 static inline void
cifs_reclassify_socket4(struct socket * sock)3012 cifs_reclassify_socket4(struct socket *sock)
3013 {
3014 }
3015 
3016 static inline void
cifs_reclassify_socket6(struct socket * sock)3017 cifs_reclassify_socket6(struct socket *sock)
3018 {
3019 }
3020 #endif
3021 
3022 /* See RFC1001 section 14 on representation of Netbios names */
rfc1002mangle(char * target,char * source,unsigned int length)3023 static void rfc1002mangle(char *target, char *source, unsigned int length)
3024 {
3025 	unsigned int i, j;
3026 
3027 	for (i = 0, j = 0; i < (length); i++) {
3028 		/* mask a nibble at a time and encode */
3029 		target[j] = 'A' + (0x0F & (source[i] >> 4));
3030 		target[j+1] = 'A' + (0x0F & source[i]);
3031 		j += 2;
3032 	}
3033 
3034 }
3035 
3036 static int
bind_socket(struct TCP_Server_Info * server)3037 bind_socket(struct TCP_Server_Info *server)
3038 {
3039 	int rc = 0;
3040 
3041 	if (server->srcaddr.ss_family != AF_UNSPEC) {
3042 		/* Bind to the specified local IP address */
3043 		struct socket *socket = server->ssocket;
3044 
3045 		rc = kernel_bind(socket,
3046 				 (struct sockaddr *) &server->srcaddr,
3047 				 sizeof(server->srcaddr));
3048 		if (rc < 0) {
3049 			struct sockaddr_in *saddr4;
3050 			struct sockaddr_in6 *saddr6;
3051 
3052 			saddr4 = (struct sockaddr_in *)&server->srcaddr;
3053 			saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
3054 			if (saddr6->sin6_family == AF_INET6)
3055 				cifs_server_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
3056 					 &saddr6->sin6_addr, rc);
3057 			else
3058 				cifs_server_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
3059 					 &saddr4->sin_addr.s_addr, rc);
3060 		}
3061 	}
3062 	return rc;
3063 }
3064 
3065 static int
ip_rfc1001_connect(struct TCP_Server_Info * server)3066 ip_rfc1001_connect(struct TCP_Server_Info *server)
3067 {
3068 	int rc = 0;
3069 	/*
3070 	 * some servers require RFC1001 sessinit before sending
3071 	 * negprot - BB check reconnection in case where second
3072 	 * sessinit is sent but no second negprot
3073 	 */
3074 	struct rfc1002_session_packet req = {};
3075 	struct msghdr msg = {};
3076 	struct kvec iov = {};
3077 	unsigned int len;
3078 	size_t sent;
3079 
3080 	req.trailer.session_req.called_len = sizeof(req.trailer.session_req.called_name);
3081 
3082 	if (server->server_RFC1001_name[0] != 0)
3083 		rfc1002mangle(req.trailer.session_req.called_name,
3084 			      server->server_RFC1001_name,
3085 			      RFC1001_NAME_LEN_WITH_NULL);
3086 	else
3087 		rfc1002mangle(req.trailer.session_req.called_name,
3088 			      DEFAULT_CIFS_CALLED_NAME,
3089 			      RFC1001_NAME_LEN_WITH_NULL);
3090 
3091 	req.trailer.session_req.calling_len = sizeof(req.trailer.session_req.calling_name);
3092 
3093 	/* calling name ends in null (byte 16) from old smb convention */
3094 	if (server->workstation_RFC1001_name[0] != 0)
3095 		rfc1002mangle(req.trailer.session_req.calling_name,
3096 			      server->workstation_RFC1001_name,
3097 			      RFC1001_NAME_LEN_WITH_NULL);
3098 	else
3099 		rfc1002mangle(req.trailer.session_req.calling_name,
3100 			      "LINUX_CIFS_CLNT",
3101 			      RFC1001_NAME_LEN_WITH_NULL);
3102 
3103 	/*
3104 	 * As per rfc1002, @len must be the number of bytes that follows the
3105 	 * length field of a rfc1002 session request payload.
3106 	 */
3107 	len = sizeof(req.trailer.session_req);
3108 	req.type = RFC1002_SESSION_REQUEST;
3109 	req.flags = 0;
3110 	req.length = cpu_to_be16(len);
3111 	len += offsetof(typeof(req), trailer.session_req);
3112 	iov.iov_base = &req;
3113 	iov.iov_len = len;
3114 	iov_iter_kvec(&msg.msg_iter, ITER_SOURCE, &iov, 1, len);
3115 	rc = smb_send_kvec(server, &msg, &sent);
3116 	if (rc < 0 || len != sent)
3117 		return (rc == -EINTR || rc == -EAGAIN) ? rc : -ECONNABORTED;
3118 
3119 	/*
3120 	 * RFC1001 layer in at least one server requires very short break before
3121 	 * negprot presumably because not expecting negprot to follow so fast.
3122 	 * This is a simple solution that works without complicating the code
3123 	 * and causes no significant slowing down on mount for everyone else
3124 	 */
3125 	usleep_range(1000, 2000);
3126 
3127 	return 0;
3128 }
3129 
3130 static int
generic_ip_connect(struct TCP_Server_Info * server)3131 generic_ip_connect(struct TCP_Server_Info *server)
3132 {
3133 	struct sockaddr *saddr;
3134 	struct socket *socket;
3135 	int slen, sfamily;
3136 	__be16 sport;
3137 	int rc = 0;
3138 
3139 	saddr = (struct sockaddr *) &server->dstaddr;
3140 
3141 	if (server->dstaddr.ss_family == AF_INET6) {
3142 		struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&server->dstaddr;
3143 
3144 		sport = ipv6->sin6_port;
3145 		slen = sizeof(struct sockaddr_in6);
3146 		sfamily = AF_INET6;
3147 		cifs_dbg(FYI, "%s: connecting to [%pI6]:%d\n", __func__, &ipv6->sin6_addr,
3148 				ntohs(sport));
3149 	} else {
3150 		struct sockaddr_in *ipv4 = (struct sockaddr_in *)&server->dstaddr;
3151 
3152 		sport = ipv4->sin_port;
3153 		slen = sizeof(struct sockaddr_in);
3154 		sfamily = AF_INET;
3155 		cifs_dbg(FYI, "%s: connecting to %pI4:%d\n", __func__, &ipv4->sin_addr,
3156 				ntohs(sport));
3157 	}
3158 
3159 	if (server->ssocket) {
3160 		socket = server->ssocket;
3161 	} else {
3162 		struct net *net = cifs_net_ns(server);
3163 		struct sock *sk;
3164 
3165 		rc = __sock_create(net, sfamily, SOCK_STREAM,
3166 				   IPPROTO_TCP, &server->ssocket, 1);
3167 		if (rc < 0) {
3168 			cifs_server_dbg(VFS, "Error %d creating socket\n", rc);
3169 			return rc;
3170 		}
3171 
3172 		sk = server->ssocket->sk;
3173 		__netns_tracker_free(net, &sk->ns_tracker, false);
3174 		sk->sk_net_refcnt = 1;
3175 		get_net_track(net, &sk->ns_tracker, GFP_KERNEL);
3176 		sock_inuse_add(net, 1);
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->lstrp = jiffies;
4002 	server->tcpStatus = CifsInNegotiate;
4003 	server->neg_start = jiffies;
4004 	spin_unlock(&server->srv_lock);
4005 
4006 	rc = server->ops->negotiate(xid, ses, server);
4007 	if (rc == -EAGAIN) {
4008 		/* Allow one retry attempt */
4009 		if (!in_retry) {
4010 			in_retry = true;
4011 			goto retry;
4012 		}
4013 		rc = -EHOSTDOWN;
4014 	}
4015 	if (rc == 0) {
4016 		spin_lock(&server->srv_lock);
4017 		if (server->tcpStatus == CifsInNegotiate)
4018 			server->tcpStatus = CifsGood;
4019 		else
4020 			rc = -EHOSTDOWN;
4021 		spin_unlock(&server->srv_lock);
4022 	} else {
4023 		spin_lock(&server->srv_lock);
4024 		if (server->tcpStatus == CifsInNegotiate)
4025 			server->tcpStatus = CifsNeedNegotiate;
4026 		spin_unlock(&server->srv_lock);
4027 	}
4028 
4029 	return rc;
4030 }
4031 
4032 int
cifs_setup_session(const unsigned int xid,struct cifs_ses * ses,struct TCP_Server_Info * server,struct nls_table * nls_info)4033 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
4034 		   struct TCP_Server_Info *server,
4035 		   struct nls_table *nls_info)
4036 {
4037 	int rc = -ENOSYS;
4038 	struct TCP_Server_Info *pserver = SERVER_IS_CHAN(server) ? server->primary_server : server;
4039 	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&pserver->dstaddr;
4040 	struct sockaddr_in *addr = (struct sockaddr_in *)&pserver->dstaddr;
4041 	bool is_binding = false;
4042 
4043 	spin_lock(&ses->ses_lock);
4044 	cifs_dbg(FYI, "%s: channel connect bitmap: 0x%lx\n",
4045 		 __func__, ses->chans_need_reconnect);
4046 
4047 	if (ses->ses_status != SES_GOOD &&
4048 	    ses->ses_status != SES_NEW &&
4049 	    ses->ses_status != SES_NEED_RECON) {
4050 		spin_unlock(&ses->ses_lock);
4051 		return -EHOSTDOWN;
4052 	}
4053 
4054 	/* only send once per connect */
4055 	spin_lock(&ses->chan_lock);
4056 	if (CIFS_ALL_CHANS_GOOD(ses)) {
4057 		if (ses->ses_status == SES_NEED_RECON)
4058 			ses->ses_status = SES_GOOD;
4059 		spin_unlock(&ses->chan_lock);
4060 		spin_unlock(&ses->ses_lock);
4061 		return 0;
4062 	}
4063 
4064 	cifs_chan_set_in_reconnect(ses, server);
4065 	is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
4066 	spin_unlock(&ses->chan_lock);
4067 
4068 	if (!is_binding) {
4069 		ses->ses_status = SES_IN_SETUP;
4070 
4071 		/* force iface_list refresh */
4072 		ses->iface_last_update = 0;
4073 	}
4074 	spin_unlock(&ses->ses_lock);
4075 
4076 	/* update ses ip_addr only for primary chan */
4077 	if (server == pserver) {
4078 		if (server->dstaddr.ss_family == AF_INET6)
4079 			scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI6", &addr6->sin6_addr);
4080 		else
4081 			scnprintf(ses->ip_addr, sizeof(ses->ip_addr), "%pI4", &addr->sin_addr);
4082 	}
4083 
4084 	if (!is_binding) {
4085 		ses->capabilities = server->capabilities;
4086 		if (!linuxExtEnabled)
4087 			ses->capabilities &= (~server->vals->cap_unix);
4088 
4089 		if (ses->auth_key.response) {
4090 			cifs_dbg(FYI, "Free previous auth_key.response = %p\n",
4091 				 ses->auth_key.response);
4092 			kfree_sensitive(ses->auth_key.response);
4093 			ses->auth_key.response = NULL;
4094 			ses->auth_key.len = 0;
4095 		}
4096 	}
4097 
4098 	cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
4099 		 server->sec_mode, server->capabilities, server->timeAdj);
4100 
4101 	if (server->ops->sess_setup)
4102 		rc = server->ops->sess_setup(xid, ses, server, nls_info);
4103 
4104 	if (rc) {
4105 		cifs_server_dbg(VFS, "Send error in SessSetup = %d\n", rc);
4106 		spin_lock(&ses->ses_lock);
4107 		if (ses->ses_status == SES_IN_SETUP)
4108 			ses->ses_status = SES_NEED_RECON;
4109 		spin_lock(&ses->chan_lock);
4110 		cifs_chan_clear_in_reconnect(ses, server);
4111 		spin_unlock(&ses->chan_lock);
4112 		spin_unlock(&ses->ses_lock);
4113 	} else {
4114 		spin_lock(&ses->ses_lock);
4115 		if (ses->ses_status == SES_IN_SETUP)
4116 			ses->ses_status = SES_GOOD;
4117 		spin_lock(&ses->chan_lock);
4118 		cifs_chan_clear_in_reconnect(ses, server);
4119 		cifs_chan_clear_need_reconnect(ses, server);
4120 		spin_unlock(&ses->chan_lock);
4121 		spin_unlock(&ses->ses_lock);
4122 	}
4123 
4124 	return rc;
4125 }
4126 
4127 static int
cifs_set_vol_auth(struct smb3_fs_context * ctx,struct cifs_ses * ses)4128 cifs_set_vol_auth(struct smb3_fs_context *ctx, struct cifs_ses *ses)
4129 {
4130 	ctx->sectype = ses->sectype;
4131 
4132 	/* krb5 is special, since we don't need username or pw */
4133 	if (ctx->sectype == Kerberos)
4134 		return 0;
4135 
4136 	return cifs_set_cifscreds(ctx, ses);
4137 }
4138 
4139 static struct cifs_tcon *
cifs_construct_tcon(struct cifs_sb_info * cifs_sb,kuid_t fsuid)4140 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
4141 {
4142 	int rc;
4143 	struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
4144 	struct cifs_ses *ses;
4145 	struct cifs_tcon *tcon = NULL;
4146 	struct smb3_fs_context *ctx;
4147 	char *origin_fullpath = NULL;
4148 
4149 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
4150 	if (ctx == NULL)
4151 		return ERR_PTR(-ENOMEM);
4152 
4153 	ctx->local_nls = cifs_sb->local_nls;
4154 	ctx->linux_uid = fsuid;
4155 	ctx->cred_uid = fsuid;
4156 	ctx->UNC = master_tcon->tree_name;
4157 	ctx->retry = master_tcon->retry;
4158 	ctx->nocase = master_tcon->nocase;
4159 	ctx->nohandlecache = master_tcon->nohandlecache;
4160 	ctx->local_lease = master_tcon->local_lease;
4161 	ctx->no_lease = master_tcon->no_lease;
4162 	ctx->resilient = master_tcon->use_resilient;
4163 	ctx->persistent = master_tcon->use_persistent;
4164 	ctx->handle_timeout = master_tcon->handle_timeout;
4165 	ctx->no_linux_ext = !master_tcon->unix_ext;
4166 	ctx->linux_ext = master_tcon->posix_extensions;
4167 	ctx->sectype = master_tcon->ses->sectype;
4168 	ctx->sign = master_tcon->ses->sign;
4169 	ctx->seal = master_tcon->seal;
4170 	ctx->witness = master_tcon->use_witness;
4171 	ctx->dfs_root_ses = master_tcon->ses->dfs_root_ses;
4172 
4173 	rc = cifs_set_vol_auth(ctx, master_tcon->ses);
4174 	if (rc) {
4175 		tcon = ERR_PTR(rc);
4176 		goto out;
4177 	}
4178 
4179 	/* get a reference for the same TCP session */
4180 	spin_lock(&cifs_tcp_ses_lock);
4181 	++master_tcon->ses->server->srv_count;
4182 	spin_unlock(&cifs_tcp_ses_lock);
4183 
4184 	ses = cifs_get_smb_ses(master_tcon->ses->server, ctx);
4185 	if (IS_ERR(ses)) {
4186 		tcon = (struct cifs_tcon *)ses;
4187 		cifs_put_tcp_session(master_tcon->ses->server, 0);
4188 		goto out;
4189 	}
4190 
4191 #ifdef CONFIG_CIFS_DFS_UPCALL
4192 	spin_lock(&master_tcon->tc_lock);
4193 	if (master_tcon->origin_fullpath) {
4194 		spin_unlock(&master_tcon->tc_lock);
4195 		origin_fullpath = dfs_get_path(cifs_sb, cifs_sb->ctx->source);
4196 		if (IS_ERR(origin_fullpath)) {
4197 			tcon = ERR_CAST(origin_fullpath);
4198 			origin_fullpath = NULL;
4199 			cifs_put_smb_ses(ses);
4200 			goto out;
4201 		}
4202 	} else {
4203 		spin_unlock(&master_tcon->tc_lock);
4204 	}
4205 #endif
4206 
4207 	tcon = cifs_get_tcon(ses, ctx);
4208 	if (IS_ERR(tcon)) {
4209 		cifs_put_smb_ses(ses);
4210 		goto out;
4211 	}
4212 
4213 #ifdef CONFIG_CIFS_DFS_UPCALL
4214 	if (origin_fullpath) {
4215 		spin_lock(&tcon->tc_lock);
4216 		tcon->origin_fullpath = origin_fullpath;
4217 		spin_unlock(&tcon->tc_lock);
4218 		origin_fullpath = NULL;
4219 		queue_delayed_work(dfscache_wq, &tcon->dfs_cache_work,
4220 				   dfs_cache_get_ttl() * HZ);
4221 	}
4222 #endif
4223 
4224 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
4225 	if (cap_unix(ses))
4226 		reset_cifs_unix_caps(0, tcon, NULL, ctx);
4227 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
4228 
4229 out:
4230 	kfree(ctx->username);
4231 	kfree_sensitive(ctx->password);
4232 	kfree(origin_fullpath);
4233 	kfree(ctx);
4234 
4235 	return tcon;
4236 }
4237 
4238 struct cifs_tcon *
cifs_sb_master_tcon(struct cifs_sb_info * cifs_sb)4239 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4240 {
4241 	return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4242 }
4243 
4244 /* find and return a tlink with given uid */
4245 static struct tcon_link *
tlink_rb_search(struct rb_root * root,kuid_t uid)4246 tlink_rb_search(struct rb_root *root, kuid_t uid)
4247 {
4248 	struct rb_node *node = root->rb_node;
4249 	struct tcon_link *tlink;
4250 
4251 	while (node) {
4252 		tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4253 
4254 		if (uid_gt(tlink->tl_uid, uid))
4255 			node = node->rb_left;
4256 		else if (uid_lt(tlink->tl_uid, uid))
4257 			node = node->rb_right;
4258 		else
4259 			return tlink;
4260 	}
4261 	return NULL;
4262 }
4263 
4264 /* insert a tcon_link into the tree */
4265 static void
tlink_rb_insert(struct rb_root * root,struct tcon_link * new_tlink)4266 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4267 {
4268 	struct rb_node **new = &(root->rb_node), *parent = NULL;
4269 	struct tcon_link *tlink;
4270 
4271 	while (*new) {
4272 		tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4273 		parent = *new;
4274 
4275 		if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4276 			new = &((*new)->rb_left);
4277 		else
4278 			new = &((*new)->rb_right);
4279 	}
4280 
4281 	rb_link_node(&new_tlink->tl_rbnode, parent, new);
4282 	rb_insert_color(&new_tlink->tl_rbnode, root);
4283 }
4284 
4285 /*
4286  * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4287  * current task.
4288  *
4289  * If the superblock doesn't refer to a multiuser mount, then just return
4290  * the master tcon for the mount.
4291  *
4292  * First, search the rbtree for an existing tcon for this fsuid. If one
4293  * exists, then check to see if it's pending construction. If it is then wait
4294  * for construction to complete. Once it's no longer pending, check to see if
4295  * it failed and either return an error or retry construction, depending on
4296  * the timeout.
4297  *
4298  * If one doesn't exist then insert a new tcon_link struct into the tree and
4299  * try to construct a new one.
4300  */
4301 struct tcon_link *
cifs_sb_tlink(struct cifs_sb_info * cifs_sb)4302 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4303 {
4304 	int ret;
4305 	kuid_t fsuid = current_fsuid();
4306 	struct tcon_link *tlink, *newtlink;
4307 
4308 	if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4309 		return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4310 
4311 	spin_lock(&cifs_sb->tlink_tree_lock);
4312 	tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4313 	if (tlink)
4314 		cifs_get_tlink(tlink);
4315 	spin_unlock(&cifs_sb->tlink_tree_lock);
4316 
4317 	if (tlink == NULL) {
4318 		newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4319 		if (newtlink == NULL)
4320 			return ERR_PTR(-ENOMEM);
4321 		newtlink->tl_uid = fsuid;
4322 		newtlink->tl_tcon = ERR_PTR(-EACCES);
4323 		set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4324 		set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4325 		cifs_get_tlink(newtlink);
4326 
4327 		spin_lock(&cifs_sb->tlink_tree_lock);
4328 		/* was one inserted after previous search? */
4329 		tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4330 		if (tlink) {
4331 			cifs_get_tlink(tlink);
4332 			spin_unlock(&cifs_sb->tlink_tree_lock);
4333 			kfree(newtlink);
4334 			goto wait_for_construction;
4335 		}
4336 		tlink = newtlink;
4337 		tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4338 		spin_unlock(&cifs_sb->tlink_tree_lock);
4339 	} else {
4340 wait_for_construction:
4341 		ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4342 				  TASK_INTERRUPTIBLE);
4343 		if (ret) {
4344 			cifs_put_tlink(tlink);
4345 			return ERR_PTR(-ERESTARTSYS);
4346 		}
4347 
4348 		/* if it's good, return it */
4349 		if (!IS_ERR(tlink->tl_tcon))
4350 			return tlink;
4351 
4352 		/* return error if we tried this already recently */
4353 		if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4354 			cifs_put_tlink(tlink);
4355 			return ERR_PTR(-EACCES);
4356 		}
4357 
4358 		if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4359 			goto wait_for_construction;
4360 	}
4361 
4362 	tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4363 	clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4364 	wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4365 
4366 	if (IS_ERR(tlink->tl_tcon)) {
4367 		cifs_put_tlink(tlink);
4368 		return ERR_PTR(-EACCES);
4369 	}
4370 
4371 	return tlink;
4372 }
4373 
4374 /*
4375  * periodic workqueue job that scans tcon_tree for a superblock and closes
4376  * out tcons.
4377  */
4378 static void
cifs_prune_tlinks(struct work_struct * work)4379 cifs_prune_tlinks(struct work_struct *work)
4380 {
4381 	struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4382 						    prune_tlinks.work);
4383 	struct rb_root *root = &cifs_sb->tlink_tree;
4384 	struct rb_node *node;
4385 	struct rb_node *tmp;
4386 	struct tcon_link *tlink;
4387 
4388 	/*
4389 	 * Because we drop the spinlock in the loop in order to put the tlink
4390 	 * it's not guarded against removal of links from the tree. The only
4391 	 * places that remove entries from the tree are this function and
4392 	 * umounts. Because this function is non-reentrant and is canceled
4393 	 * before umount can proceed, this is safe.
4394 	 */
4395 	spin_lock(&cifs_sb->tlink_tree_lock);
4396 	node = rb_first(root);
4397 	while (node != NULL) {
4398 		tmp = node;
4399 		node = rb_next(tmp);
4400 		tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4401 
4402 		if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4403 		    atomic_read(&tlink->tl_count) != 0 ||
4404 		    time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4405 			continue;
4406 
4407 		cifs_get_tlink(tlink);
4408 		clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4409 		rb_erase(tmp, root);
4410 
4411 		spin_unlock(&cifs_sb->tlink_tree_lock);
4412 		cifs_put_tlink(tlink);
4413 		spin_lock(&cifs_sb->tlink_tree_lock);
4414 	}
4415 	spin_unlock(&cifs_sb->tlink_tree_lock);
4416 
4417 	queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4418 				TLINK_IDLE_EXPIRE);
4419 }
4420 
4421 #ifndef CONFIG_CIFS_DFS_UPCALL
cifs_tree_connect(const unsigned int xid,struct cifs_tcon * tcon,const struct nls_table * nlsc)4422 int cifs_tree_connect(const unsigned int xid, struct cifs_tcon *tcon, const struct nls_table *nlsc)
4423 {
4424 	int rc;
4425 	const struct smb_version_operations *ops = tcon->ses->server->ops;
4426 
4427 	/* only send once per connect */
4428 	spin_lock(&tcon->tc_lock);
4429 
4430 	/* if tcon is marked for needing reconnect, update state */
4431 	if (tcon->need_reconnect)
4432 		tcon->status = TID_NEED_TCON;
4433 
4434 	if (tcon->status == TID_GOOD) {
4435 		spin_unlock(&tcon->tc_lock);
4436 		return 0;
4437 	}
4438 
4439 	if (tcon->status != TID_NEW &&
4440 	    tcon->status != TID_NEED_TCON) {
4441 		spin_unlock(&tcon->tc_lock);
4442 		return -EHOSTDOWN;
4443 	}
4444 
4445 	tcon->status = TID_IN_TCON;
4446 	spin_unlock(&tcon->tc_lock);
4447 
4448 	rc = ops->tree_connect(xid, tcon->ses, tcon->tree_name, tcon, nlsc);
4449 	if (rc) {
4450 		spin_lock(&tcon->tc_lock);
4451 		if (tcon->status == TID_IN_TCON)
4452 			tcon->status = TID_NEED_TCON;
4453 		spin_unlock(&tcon->tc_lock);
4454 	} else {
4455 		spin_lock(&tcon->tc_lock);
4456 		if (tcon->status == TID_IN_TCON)
4457 			tcon->status = TID_GOOD;
4458 		tcon->need_reconnect = false;
4459 		spin_unlock(&tcon->tc_lock);
4460 	}
4461 
4462 	return rc;
4463 }
4464 #endif
4465