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