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