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