xref: /linux/fs/smb/client/misc.c (revision e0b1f59142746f74476a03040f745329c8355a7e)
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   Copyright (C) International Business Machines  Corp., 2002,2008
5  *   Author(s): Steve French (sfrench@us.ibm.com)
6  *
7  */
8 
9 #include <linux/slab.h>
10 #include <linux/ctype.h>
11 #include <linux/mempool.h>
12 #include <linux/vmalloc.h>
13 #include "cifspdu.h"
14 #include "cifsglob.h"
15 #include "cifsproto.h"
16 #include "cifs_debug.h"
17 #include "smberr.h"
18 #include "nterr.h"
19 #include "cifs_unicode.h"
20 #include "smb2pdu.h"
21 #include "cifsfs.h"
22 #ifdef CONFIG_CIFS_DFS_UPCALL
23 #include "dns_resolve.h"
24 #include "dfs_cache.h"
25 #include "dfs.h"
26 #endif
27 #include "fs_context.h"
28 #include "cached_dir.h"
29 
30 /* The xid serves as a useful identifier for each incoming vfs request,
31    in a similar way to the mid which is useful to track each sent smb,
32    and CurrentXid can also provide a running counter (although it
33    will eventually wrap past zero) of the total vfs operations handled
34    since the cifs fs was mounted */
35 
36 unsigned int
_get_xid(void)37 _get_xid(void)
38 {
39 	unsigned int xid;
40 
41 	spin_lock(&GlobalMid_Lock);
42 	GlobalTotalActiveXid++;
43 
44 	/* keep high water mark for number of simultaneous ops in filesystem */
45 	if (GlobalTotalActiveXid > GlobalMaxActiveXid)
46 		GlobalMaxActiveXid = GlobalTotalActiveXid;
47 	if (GlobalTotalActiveXid > 65000)
48 		cifs_dbg(FYI, "warning: more than 65000 requests active\n");
49 	xid = GlobalCurrentXid++;
50 	spin_unlock(&GlobalMid_Lock);
51 	return xid;
52 }
53 
54 void
_free_xid(unsigned int xid)55 _free_xid(unsigned int xid)
56 {
57 	spin_lock(&GlobalMid_Lock);
58 	/* if (GlobalTotalActiveXid == 0)
59 		BUG(); */
60 	GlobalTotalActiveXid--;
61 	spin_unlock(&GlobalMid_Lock);
62 }
63 
64 struct cifs_ses *
sesInfoAlloc(void)65 sesInfoAlloc(void)
66 {
67 	struct cifs_ses *ret_buf;
68 
69 	ret_buf = kzalloc(sizeof(struct cifs_ses), GFP_KERNEL);
70 	if (ret_buf) {
71 		atomic_inc(&sesInfoAllocCount);
72 		spin_lock_init(&ret_buf->ses_lock);
73 		ret_buf->ses_status = SES_NEW;
74 		++ret_buf->ses_count;
75 		INIT_LIST_HEAD(&ret_buf->smb_ses_list);
76 		INIT_LIST_HEAD(&ret_buf->tcon_list);
77 		mutex_init(&ret_buf->session_mutex);
78 		spin_lock_init(&ret_buf->iface_lock);
79 		INIT_LIST_HEAD(&ret_buf->iface_list);
80 		spin_lock_init(&ret_buf->chan_lock);
81 	}
82 	return ret_buf;
83 }
84 
85 void
sesInfoFree(struct cifs_ses * buf_to_free)86 sesInfoFree(struct cifs_ses *buf_to_free)
87 {
88 	struct cifs_server_iface *iface = NULL, *niface = NULL;
89 
90 	if (buf_to_free == NULL) {
91 		cifs_dbg(FYI, "Null buffer passed to sesInfoFree\n");
92 		return;
93 	}
94 
95 	unload_nls(buf_to_free->local_nls);
96 	atomic_dec(&sesInfoAllocCount);
97 	kfree(buf_to_free->serverOS);
98 	kfree(buf_to_free->serverDomain);
99 	kfree(buf_to_free->serverNOS);
100 	kfree_sensitive(buf_to_free->password);
101 	kfree_sensitive(buf_to_free->password2);
102 	kfree(buf_to_free->user_name);
103 	kfree(buf_to_free->domainName);
104 	kfree(buf_to_free->dns_dom);
105 	kfree_sensitive(buf_to_free->auth_key.response);
106 	spin_lock(&buf_to_free->iface_lock);
107 	list_for_each_entry_safe(iface, niface, &buf_to_free->iface_list,
108 				 iface_head)
109 		kref_put(&iface->refcount, release_iface);
110 	spin_unlock(&buf_to_free->iface_lock);
111 	kfree_sensitive(buf_to_free);
112 }
113 
114 struct cifs_tcon *
tcon_info_alloc(bool dir_leases_enabled,enum smb3_tcon_ref_trace trace)115 tcon_info_alloc(bool dir_leases_enabled, enum smb3_tcon_ref_trace trace)
116 {
117 	struct cifs_tcon *ret_buf;
118 	static atomic_t tcon_debug_id;
119 
120 	ret_buf = kzalloc(sizeof(*ret_buf), GFP_KERNEL);
121 	if (!ret_buf)
122 		return NULL;
123 
124 	if (dir_leases_enabled == true) {
125 		ret_buf->cfids = init_cached_dirs();
126 		if (!ret_buf->cfids) {
127 			kfree(ret_buf);
128 			return NULL;
129 		}
130 	}
131 	/* else ret_buf->cfids is already set to NULL above */
132 
133 	atomic_inc(&tconInfoAllocCount);
134 	ret_buf->status = TID_NEW;
135 	ret_buf->debug_id = atomic_inc_return(&tcon_debug_id);
136 	ret_buf->tc_count = 1;
137 	spin_lock_init(&ret_buf->tc_lock);
138 	INIT_LIST_HEAD(&ret_buf->openFileList);
139 	INIT_LIST_HEAD(&ret_buf->tcon_list);
140 	spin_lock_init(&ret_buf->open_file_lock);
141 	spin_lock_init(&ret_buf->stat_lock);
142 	atomic_set(&ret_buf->num_local_opens, 0);
143 	atomic_set(&ret_buf->num_remote_opens, 0);
144 	ret_buf->stats_from_time = ktime_get_real_seconds();
145 #ifdef CONFIG_CIFS_FSCACHE
146 	mutex_init(&ret_buf->fscache_lock);
147 #endif
148 	trace_smb3_tcon_ref(ret_buf->debug_id, ret_buf->tc_count, trace);
149 #ifdef CONFIG_CIFS_DFS_UPCALL
150 	INIT_LIST_HEAD(&ret_buf->dfs_ses_list);
151 #endif
152 
153 	return ret_buf;
154 }
155 
156 void
tconInfoFree(struct cifs_tcon * tcon,enum smb3_tcon_ref_trace trace)157 tconInfoFree(struct cifs_tcon *tcon, enum smb3_tcon_ref_trace trace)
158 {
159 	if (tcon == NULL) {
160 		cifs_dbg(FYI, "Null buffer passed to tconInfoFree\n");
161 		return;
162 	}
163 	trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count, trace);
164 	free_cached_dirs(tcon->cfids);
165 	atomic_dec(&tconInfoAllocCount);
166 	kfree(tcon->nativeFileSystem);
167 	kfree_sensitive(tcon->password);
168 	kfree(tcon->origin_fullpath);
169 	kfree(tcon);
170 }
171 
172 struct smb_hdr *
cifs_buf_get(void)173 cifs_buf_get(void)
174 {
175 	struct smb_hdr *ret_buf = NULL;
176 	/*
177 	 * SMB2 header is bigger than CIFS one - no problems to clean some
178 	 * more bytes for CIFS.
179 	 */
180 	size_t buf_size = sizeof(struct smb2_hdr);
181 
182 	/*
183 	 * We could use negotiated size instead of max_msgsize -
184 	 * but it may be more efficient to always alloc same size
185 	 * albeit slightly larger than necessary and maxbuffersize
186 	 * defaults to this and can not be bigger.
187 	 */
188 	ret_buf = mempool_alloc(cifs_req_poolp, GFP_NOFS);
189 
190 	/* clear the first few header bytes */
191 	/* for most paths, more is cleared in header_assemble */
192 	memset(ret_buf, 0, buf_size + 3);
193 	atomic_inc(&buf_alloc_count);
194 #ifdef CONFIG_CIFS_STATS2
195 	atomic_inc(&total_buf_alloc_count);
196 #endif /* CONFIG_CIFS_STATS2 */
197 
198 	return ret_buf;
199 }
200 
201 void
cifs_buf_release(void * buf_to_free)202 cifs_buf_release(void *buf_to_free)
203 {
204 	if (buf_to_free == NULL) {
205 		/* cifs_dbg(FYI, "Null buffer passed to cifs_buf_release\n");*/
206 		return;
207 	}
208 	mempool_free(buf_to_free, cifs_req_poolp);
209 
210 	atomic_dec(&buf_alloc_count);
211 	return;
212 }
213 
214 struct smb_hdr *
cifs_small_buf_get(void)215 cifs_small_buf_get(void)
216 {
217 	struct smb_hdr *ret_buf = NULL;
218 
219 /* We could use negotiated size instead of max_msgsize -
220    but it may be more efficient to always alloc same size
221    albeit slightly larger than necessary and maxbuffersize
222    defaults to this and can not be bigger */
223 	ret_buf = mempool_alloc(cifs_sm_req_poolp, GFP_NOFS);
224 	/* No need to clear memory here, cleared in header assemble */
225 	/*	memset(ret_buf, 0, sizeof(struct smb_hdr) + 27);*/
226 	atomic_inc(&small_buf_alloc_count);
227 #ifdef CONFIG_CIFS_STATS2
228 	atomic_inc(&total_small_buf_alloc_count);
229 #endif /* CONFIG_CIFS_STATS2 */
230 
231 	return ret_buf;
232 }
233 
234 void
cifs_small_buf_release(void * buf_to_free)235 cifs_small_buf_release(void *buf_to_free)
236 {
237 
238 	if (buf_to_free == NULL) {
239 		cifs_dbg(FYI, "Null buffer passed to cifs_small_buf_release\n");
240 		return;
241 	}
242 	mempool_free(buf_to_free, cifs_sm_req_poolp);
243 
244 	atomic_dec(&small_buf_alloc_count);
245 	return;
246 }
247 
248 void
free_rsp_buf(int resp_buftype,void * rsp)249 free_rsp_buf(int resp_buftype, void *rsp)
250 {
251 	if (resp_buftype == CIFS_SMALL_BUFFER)
252 		cifs_small_buf_release(rsp);
253 	else if (resp_buftype == CIFS_LARGE_BUFFER)
254 		cifs_buf_release(rsp);
255 }
256 
257 /* NB: MID can not be set if treeCon not passed in, in that
258    case it is responsibility of caller to set the mid */
259 void
header_assemble(struct smb_hdr * buffer,char smb_command,const struct cifs_tcon * treeCon,int word_count)260 header_assemble(struct smb_hdr *buffer, char smb_command /* command */ ,
261 		const struct cifs_tcon *treeCon, int word_count
262 		/* length of fixed section (word count) in two byte units  */)
263 {
264 	char *temp = (char *) buffer;
265 
266 	memset(temp, 0, 256); /* bigger than MAX_CIFS_HDR_SIZE */
267 
268 	buffer->smb_buf_length = cpu_to_be32(
269 	    (2 * word_count) + sizeof(struct smb_hdr) -
270 	    4 /*  RFC 1001 length field does not count */  +
271 	    2 /* for bcc field itself */) ;
272 
273 	buffer->Protocol[0] = 0xFF;
274 	buffer->Protocol[1] = 'S';
275 	buffer->Protocol[2] = 'M';
276 	buffer->Protocol[3] = 'B';
277 	buffer->Command = smb_command;
278 	buffer->Flags = 0x00;	/* case sensitive */
279 	buffer->Flags2 = SMBFLG2_KNOWS_LONG_NAMES;
280 	buffer->Pid = cpu_to_le16((__u16)current->tgid);
281 	buffer->PidHigh = cpu_to_le16((__u16)(current->tgid >> 16));
282 	if (treeCon) {
283 		buffer->Tid = treeCon->tid;
284 		if (treeCon->ses) {
285 			if (treeCon->ses->capabilities & CAP_UNICODE)
286 				buffer->Flags2 |= SMBFLG2_UNICODE;
287 			if (treeCon->ses->capabilities & CAP_STATUS32)
288 				buffer->Flags2 |= SMBFLG2_ERR_STATUS;
289 
290 			/* Uid is not converted */
291 			buffer->Uid = treeCon->ses->Suid;
292 			if (treeCon->ses->server)
293 				buffer->Mid = get_next_mid(treeCon->ses->server);
294 		}
295 		if (treeCon->Flags & SMB_SHARE_IS_IN_DFS)
296 			buffer->Flags2 |= SMBFLG2_DFS;
297 		if (treeCon->nocase)
298 			buffer->Flags  |= SMBFLG_CASELESS;
299 		if ((treeCon->ses) && (treeCon->ses->server))
300 			if (treeCon->ses->server->sign)
301 				buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
302 	}
303 
304 /*  endian conversion of flags is now done just before sending */
305 	buffer->WordCount = (char) word_count;
306 	return;
307 }
308 
309 static int
check_smb_hdr(struct smb_hdr * smb)310 check_smb_hdr(struct smb_hdr *smb)
311 {
312 	/* does it have the right SMB "signature" ? */
313 	if (*(__le32 *) smb->Protocol != cpu_to_le32(0x424d53ff)) {
314 		cifs_dbg(VFS, "Bad protocol string signature header 0x%x\n",
315 			 *(unsigned int *)smb->Protocol);
316 		return 1;
317 	}
318 
319 	/* if it's a response then accept */
320 	if (smb->Flags & SMBFLG_RESPONSE)
321 		return 0;
322 
323 	/* only one valid case where server sends us request */
324 	if (smb->Command == SMB_COM_LOCKING_ANDX)
325 		return 0;
326 
327 	cifs_dbg(VFS, "Server sent request, not response. mid=%u\n",
328 		 get_mid(smb));
329 	return 1;
330 }
331 
332 int
checkSMB(char * buf,unsigned int total_read,struct TCP_Server_Info * server)333 checkSMB(char *buf, unsigned int total_read, struct TCP_Server_Info *server)
334 {
335 	struct smb_hdr *smb = (struct smb_hdr *)buf;
336 	__u32 rfclen = be32_to_cpu(smb->smb_buf_length);
337 	__u32 clc_len;  /* calculated length */
338 	cifs_dbg(FYI, "checkSMB Length: 0x%x, smb_buf_length: 0x%x\n",
339 		 total_read, rfclen);
340 
341 	/* is this frame too small to even get to a BCC? */
342 	if (total_read < 2 + sizeof(struct smb_hdr)) {
343 		if ((total_read >= sizeof(struct smb_hdr) - 1)
344 			    && (smb->Status.CifsError != 0)) {
345 			/* it's an error return */
346 			smb->WordCount = 0;
347 			/* some error cases do not return wct and bcc */
348 			return 0;
349 		} else if ((total_read == sizeof(struct smb_hdr) + 1) &&
350 				(smb->WordCount == 0)) {
351 			char *tmp = (char *)smb;
352 			/* Need to work around a bug in two servers here */
353 			/* First, check if the part of bcc they sent was zero */
354 			if (tmp[sizeof(struct smb_hdr)] == 0) {
355 				/* some servers return only half of bcc
356 				 * on simple responses (wct, bcc both zero)
357 				 * in particular have seen this on
358 				 * ulogoffX and FindClose. This leaves
359 				 * one byte of bcc potentially uninitialized
360 				 */
361 				/* zero rest of bcc */
362 				tmp[sizeof(struct smb_hdr)+1] = 0;
363 				return 0;
364 			}
365 			cifs_dbg(VFS, "rcvd invalid byte count (bcc)\n");
366 		} else {
367 			cifs_dbg(VFS, "Length less than smb header size\n");
368 		}
369 		return -EIO;
370 	} else if (total_read < sizeof(*smb) + 2 * smb->WordCount) {
371 		cifs_dbg(VFS, "%s: can't read BCC due to invalid WordCount(%u)\n",
372 			 __func__, smb->WordCount);
373 		return -EIO;
374 	}
375 
376 	/* otherwise, there is enough to get to the BCC */
377 	if (check_smb_hdr(smb))
378 		return -EIO;
379 	clc_len = smbCalcSize(smb);
380 
381 	if (4 + rfclen != total_read) {
382 		cifs_dbg(VFS, "Length read does not match RFC1001 length %d\n",
383 			 rfclen);
384 		return -EIO;
385 	}
386 
387 	if (4 + rfclen != clc_len) {
388 		__u16 mid = get_mid(smb);
389 		/* check if bcc wrapped around for large read responses */
390 		if ((rfclen > 64 * 1024) && (rfclen > clc_len)) {
391 			/* check if lengths match mod 64K */
392 			if (((4 + rfclen) & 0xFFFF) == (clc_len & 0xFFFF))
393 				return 0; /* bcc wrapped */
394 		}
395 		cifs_dbg(FYI, "Calculated size %u vs length %u mismatch for mid=%u\n",
396 			 clc_len, 4 + rfclen, mid);
397 
398 		if (4 + rfclen < clc_len) {
399 			cifs_dbg(VFS, "RFC1001 size %u smaller than SMB for mid=%u\n",
400 				 rfclen, mid);
401 			return -EIO;
402 		} else if (rfclen > clc_len + 512) {
403 			/*
404 			 * Some servers (Windows XP in particular) send more
405 			 * data than the lengths in the SMB packet would
406 			 * indicate on certain calls (byte range locks and
407 			 * trans2 find first calls in particular). While the
408 			 * client can handle such a frame by ignoring the
409 			 * trailing data, we choose limit the amount of extra
410 			 * data to 512 bytes.
411 			 */
412 			cifs_dbg(VFS, "RFC1001 size %u more than 512 bytes larger than SMB for mid=%u\n",
413 				 rfclen, mid);
414 			return -EIO;
415 		}
416 	}
417 	return 0;
418 }
419 
420 bool
is_valid_oplock_break(char * buffer,struct TCP_Server_Info * srv)421 is_valid_oplock_break(char *buffer, struct TCP_Server_Info *srv)
422 {
423 	struct smb_hdr *buf = (struct smb_hdr *)buffer;
424 	struct smb_com_lock_req *pSMB = (struct smb_com_lock_req *)buf;
425 	struct TCP_Server_Info *pserver;
426 	struct cifs_ses *ses;
427 	struct cifs_tcon *tcon;
428 	struct cifsInodeInfo *pCifsInode;
429 	struct cifsFileInfo *netfile;
430 
431 	cifs_dbg(FYI, "Checking for oplock break or dnotify response\n");
432 	if ((pSMB->hdr.Command == SMB_COM_NT_TRANSACT) &&
433 	   (pSMB->hdr.Flags & SMBFLG_RESPONSE)) {
434 		struct smb_com_transaction_change_notify_rsp *pSMBr =
435 			(struct smb_com_transaction_change_notify_rsp *)buf;
436 		struct file_notify_information *pnotify;
437 		__u32 data_offset = 0;
438 		size_t len = srv->total_read - sizeof(pSMBr->hdr.smb_buf_length);
439 
440 		if (get_bcc(buf) > sizeof(struct file_notify_information)) {
441 			data_offset = le32_to_cpu(pSMBr->DataOffset);
442 
443 			if (data_offset >
444 			    len - sizeof(struct file_notify_information)) {
445 				cifs_dbg(FYI, "Invalid data_offset %u\n",
446 					 data_offset);
447 				return true;
448 			}
449 			pnotify = (struct file_notify_information *)
450 				((char *)&pSMBr->hdr.Protocol + data_offset);
451 			cifs_dbg(FYI, "dnotify on %s Action: 0x%x\n",
452 				 pnotify->FileName, pnotify->Action);
453 			/*   cifs_dump_mem("Rcvd notify Data: ",buf,
454 				sizeof(struct smb_hdr)+60); */
455 			return true;
456 		}
457 		if (pSMBr->hdr.Status.CifsError) {
458 			cifs_dbg(FYI, "notify err 0x%x\n",
459 				 pSMBr->hdr.Status.CifsError);
460 			return true;
461 		}
462 		return false;
463 	}
464 	if (pSMB->hdr.Command != SMB_COM_LOCKING_ANDX)
465 		return false;
466 	if (pSMB->hdr.Flags & SMBFLG_RESPONSE) {
467 		/* no sense logging error on invalid handle on oplock
468 		   break - harmless race between close request and oplock
469 		   break response is expected from time to time writing out
470 		   large dirty files cached on the client */
471 		if ((NT_STATUS_INVALID_HANDLE) ==
472 		   le32_to_cpu(pSMB->hdr.Status.CifsError)) {
473 			cifs_dbg(FYI, "Invalid handle on oplock break\n");
474 			return true;
475 		} else if (ERRbadfid ==
476 		   le16_to_cpu(pSMB->hdr.Status.DosError.Error)) {
477 			return true;
478 		} else {
479 			return false; /* on valid oplock brk we get "request" */
480 		}
481 	}
482 	if (pSMB->hdr.WordCount != 8)
483 		return false;
484 
485 	cifs_dbg(FYI, "oplock type 0x%x level 0x%x\n",
486 		 pSMB->LockType, pSMB->OplockLevel);
487 	if (!(pSMB->LockType & LOCKING_ANDX_OPLOCK_RELEASE))
488 		return false;
489 
490 	/* If server is a channel, select the primary channel */
491 	pserver = SERVER_IS_CHAN(srv) ? srv->primary_server : srv;
492 
493 	/* look up tcon based on tid & uid */
494 	spin_lock(&cifs_tcp_ses_lock);
495 	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
496 		if (cifs_ses_exiting(ses))
497 			continue;
498 		list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
499 			if (tcon->tid != buf->Tid)
500 				continue;
501 
502 			cifs_stats_inc(&tcon->stats.cifs_stats.num_oplock_brks);
503 			spin_lock(&tcon->open_file_lock);
504 			list_for_each_entry(netfile, &tcon->openFileList, tlist) {
505 				if (pSMB->Fid != netfile->fid.netfid)
506 					continue;
507 
508 				cifs_dbg(FYI, "file id match, oplock break\n");
509 				pCifsInode = CIFS_I(d_inode(netfile->dentry));
510 
511 				set_bit(CIFS_INODE_PENDING_OPLOCK_BREAK,
512 					&pCifsInode->flags);
513 
514 				netfile->oplock_epoch = 0;
515 				netfile->oplock_level = pSMB->OplockLevel;
516 				netfile->oplock_break_cancelled = false;
517 				cifs_queue_oplock_break(netfile);
518 
519 				spin_unlock(&tcon->open_file_lock);
520 				spin_unlock(&cifs_tcp_ses_lock);
521 				return true;
522 			}
523 			spin_unlock(&tcon->open_file_lock);
524 			spin_unlock(&cifs_tcp_ses_lock);
525 			cifs_dbg(FYI, "No matching file for oplock break\n");
526 			return true;
527 		}
528 	}
529 	spin_unlock(&cifs_tcp_ses_lock);
530 	cifs_dbg(FYI, "Can not process oplock break for non-existent connection\n");
531 	return true;
532 }
533 
534 void
dump_smb(void * buf,int smb_buf_length)535 dump_smb(void *buf, int smb_buf_length)
536 {
537 	if (traceSMB == 0)
538 		return;
539 
540 	print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_NONE, 8, 2, buf,
541 		       smb_buf_length, true);
542 }
543 
544 void
cifs_autodisable_serverino(struct cifs_sb_info * cifs_sb)545 cifs_autodisable_serverino(struct cifs_sb_info *cifs_sb)
546 {
547 	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) {
548 		struct cifs_tcon *tcon = NULL;
549 
550 		if (cifs_sb->master_tlink)
551 			tcon = cifs_sb_master_tcon(cifs_sb);
552 
553 		cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_SERVER_INUM;
554 		cifs_sb->mnt_cifs_serverino_autodisabled = true;
555 		cifs_dbg(VFS, "Autodisabling the use of server inode numbers on %s\n",
556 			 tcon ? tcon->tree_name : "new server");
557 		cifs_dbg(VFS, "The server doesn't seem to support them properly or the files might be on different servers (DFS)\n");
558 		cifs_dbg(VFS, "Hardlinks will not be recognized on this mount. Consider mounting with the \"noserverino\" option to silence this message.\n");
559 
560 	}
561 }
562 
cifs_set_oplock_level(struct cifsInodeInfo * cinode,__u32 oplock)563 void cifs_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock)
564 {
565 	oplock &= 0xF;
566 
567 	if (oplock == OPLOCK_EXCLUSIVE) {
568 		cinode->oplock = CIFS_CACHE_WRITE_FLG | CIFS_CACHE_READ_FLG;
569 		cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
570 			 &cinode->netfs.inode);
571 	} else if (oplock == OPLOCK_READ) {
572 		cinode->oplock = CIFS_CACHE_READ_FLG;
573 		cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
574 			 &cinode->netfs.inode);
575 	} else
576 		cinode->oplock = 0;
577 }
578 
579 /*
580  * We wait for oplock breaks to be processed before we attempt to perform
581  * writes.
582  */
cifs_get_writer(struct cifsInodeInfo * cinode)583 int cifs_get_writer(struct cifsInodeInfo *cinode)
584 {
585 	int rc;
586 
587 start:
588 	rc = wait_on_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK,
589 			 TASK_KILLABLE);
590 	if (rc)
591 		return rc;
592 
593 	spin_lock(&cinode->writers_lock);
594 	if (!cinode->writers)
595 		set_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
596 	cinode->writers++;
597 	/* Check to see if we have started servicing an oplock break */
598 	if (test_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags)) {
599 		cinode->writers--;
600 		if (cinode->writers == 0) {
601 			clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
602 			wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
603 		}
604 		spin_unlock(&cinode->writers_lock);
605 		goto start;
606 	}
607 	spin_unlock(&cinode->writers_lock);
608 	return 0;
609 }
610 
cifs_put_writer(struct cifsInodeInfo * cinode)611 void cifs_put_writer(struct cifsInodeInfo *cinode)
612 {
613 	spin_lock(&cinode->writers_lock);
614 	cinode->writers--;
615 	if (cinode->writers == 0) {
616 		clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
617 		wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
618 	}
619 	spin_unlock(&cinode->writers_lock);
620 }
621 
622 /**
623  * cifs_queue_oplock_break - queue the oplock break handler for cfile
624  * @cfile: The file to break the oplock on
625  *
626  * This function is called from the demultiplex thread when it
627  * receives an oplock break for @cfile.
628  *
629  * Assumes the tcon->open_file_lock is held.
630  * Assumes cfile->file_info_lock is NOT held.
631  */
cifs_queue_oplock_break(struct cifsFileInfo * cfile)632 void cifs_queue_oplock_break(struct cifsFileInfo *cfile)
633 {
634 	/*
635 	 * Bump the handle refcount now while we hold the
636 	 * open_file_lock to enforce the validity of it for the oplock
637 	 * break handler. The matching put is done at the end of the
638 	 * handler.
639 	 */
640 	cifsFileInfo_get(cfile);
641 
642 	queue_work(cifsoplockd_wq, &cfile->oplock_break);
643 }
644 
cifs_done_oplock_break(struct cifsInodeInfo * cinode)645 void cifs_done_oplock_break(struct cifsInodeInfo *cinode)
646 {
647 	clear_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags);
648 	wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK);
649 }
650 
651 bool
backup_cred(struct cifs_sb_info * cifs_sb)652 backup_cred(struct cifs_sb_info *cifs_sb)
653 {
654 	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPUID) {
655 		if (uid_eq(cifs_sb->ctx->backupuid, current_fsuid()))
656 			return true;
657 	}
658 	if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPGID) {
659 		if (in_group_p(cifs_sb->ctx->backupgid))
660 			return true;
661 	}
662 
663 	return false;
664 }
665 
666 void
cifs_del_pending_open(struct cifs_pending_open * open)667 cifs_del_pending_open(struct cifs_pending_open *open)
668 {
669 	spin_lock(&tlink_tcon(open->tlink)->open_file_lock);
670 	list_del(&open->olist);
671 	spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
672 }
673 
674 void
cifs_add_pending_open_locked(struct cifs_fid * fid,struct tcon_link * tlink,struct cifs_pending_open * open)675 cifs_add_pending_open_locked(struct cifs_fid *fid, struct tcon_link *tlink,
676 			     struct cifs_pending_open *open)
677 {
678 	memcpy(open->lease_key, fid->lease_key, SMB2_LEASE_KEY_SIZE);
679 	open->oplock = CIFS_OPLOCK_NO_CHANGE;
680 	open->tlink = tlink;
681 	fid->pending_open = open;
682 	list_add_tail(&open->olist, &tlink_tcon(tlink)->pending_opens);
683 }
684 
685 void
cifs_add_pending_open(struct cifs_fid * fid,struct tcon_link * tlink,struct cifs_pending_open * open)686 cifs_add_pending_open(struct cifs_fid *fid, struct tcon_link *tlink,
687 		      struct cifs_pending_open *open)
688 {
689 	spin_lock(&tlink_tcon(tlink)->open_file_lock);
690 	cifs_add_pending_open_locked(fid, tlink, open);
691 	spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
692 }
693 
694 /*
695  * Critical section which runs after acquiring deferred_lock.
696  * As there is no reference count on cifs_deferred_close, pdclose
697  * should not be used outside deferred_lock.
698  */
699 bool
cifs_is_deferred_close(struct cifsFileInfo * cfile,struct cifs_deferred_close ** pdclose)700 cifs_is_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close **pdclose)
701 {
702 	struct cifs_deferred_close *dclose;
703 
704 	list_for_each_entry(dclose, &CIFS_I(d_inode(cfile->dentry))->deferred_closes, dlist) {
705 		if ((dclose->netfid == cfile->fid.netfid) &&
706 			(dclose->persistent_fid == cfile->fid.persistent_fid) &&
707 			(dclose->volatile_fid == cfile->fid.volatile_fid)) {
708 			*pdclose = dclose;
709 			return true;
710 		}
711 	}
712 	return false;
713 }
714 
715 /*
716  * Critical section which runs after acquiring deferred_lock.
717  */
718 void
cifs_add_deferred_close(struct cifsFileInfo * cfile,struct cifs_deferred_close * dclose)719 cifs_add_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close *dclose)
720 {
721 	bool is_deferred = false;
722 	struct cifs_deferred_close *pdclose;
723 
724 	is_deferred = cifs_is_deferred_close(cfile, &pdclose);
725 	if (is_deferred) {
726 		kfree(dclose);
727 		return;
728 	}
729 
730 	dclose->tlink = cfile->tlink;
731 	dclose->netfid = cfile->fid.netfid;
732 	dclose->persistent_fid = cfile->fid.persistent_fid;
733 	dclose->volatile_fid = cfile->fid.volatile_fid;
734 	list_add_tail(&dclose->dlist, &CIFS_I(d_inode(cfile->dentry))->deferred_closes);
735 }
736 
737 /*
738  * Critical section which runs after acquiring deferred_lock.
739  */
740 void
cifs_del_deferred_close(struct cifsFileInfo * cfile)741 cifs_del_deferred_close(struct cifsFileInfo *cfile)
742 {
743 	bool is_deferred = false;
744 	struct cifs_deferred_close *dclose;
745 
746 	is_deferred = cifs_is_deferred_close(cfile, &dclose);
747 	if (!is_deferred)
748 		return;
749 	list_del(&dclose->dlist);
750 	kfree(dclose);
751 }
752 
753 void
cifs_close_deferred_file(struct cifsInodeInfo * cifs_inode)754 cifs_close_deferred_file(struct cifsInodeInfo *cifs_inode)
755 {
756 	struct cifsFileInfo *cfile = NULL;
757 	struct file_list *tmp_list, *tmp_next_list;
758 	LIST_HEAD(file_head);
759 
760 	if (cifs_inode == NULL)
761 		return;
762 
763 	spin_lock(&cifs_inode->open_file_lock);
764 	list_for_each_entry(cfile, &cifs_inode->openFileList, flist) {
765 		if (delayed_work_pending(&cfile->deferred)) {
766 			if (cancel_delayed_work(&cfile->deferred)) {
767 				spin_lock(&cifs_inode->deferred_lock);
768 				cifs_del_deferred_close(cfile);
769 				spin_unlock(&cifs_inode->deferred_lock);
770 
771 				tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
772 				if (tmp_list == NULL)
773 					break;
774 				tmp_list->cfile = cfile;
775 				list_add_tail(&tmp_list->list, &file_head);
776 			}
777 		}
778 	}
779 	spin_unlock(&cifs_inode->open_file_lock);
780 
781 	list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
782 		_cifsFileInfo_put(tmp_list->cfile, false, false);
783 		list_del(&tmp_list->list);
784 		kfree(tmp_list);
785 	}
786 }
787 
788 void
cifs_close_all_deferred_files(struct cifs_tcon * tcon)789 cifs_close_all_deferred_files(struct cifs_tcon *tcon)
790 {
791 	struct cifsFileInfo *cfile;
792 	struct file_list *tmp_list, *tmp_next_list;
793 	LIST_HEAD(file_head);
794 
795 	spin_lock(&tcon->open_file_lock);
796 	list_for_each_entry(cfile, &tcon->openFileList, tlist) {
797 		if (delayed_work_pending(&cfile->deferred)) {
798 			if (cancel_delayed_work(&cfile->deferred)) {
799 				spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
800 				cifs_del_deferred_close(cfile);
801 				spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
802 
803 				tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
804 				if (tmp_list == NULL)
805 					break;
806 				tmp_list->cfile = cfile;
807 				list_add_tail(&tmp_list->list, &file_head);
808 			}
809 		}
810 	}
811 	spin_unlock(&tcon->open_file_lock);
812 
813 	list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
814 		_cifsFileInfo_put(tmp_list->cfile, true, false);
815 		list_del(&tmp_list->list);
816 		kfree(tmp_list);
817 	}
818 }
819 void
cifs_close_deferred_file_under_dentry(struct cifs_tcon * tcon,const char * path)820 cifs_close_deferred_file_under_dentry(struct cifs_tcon *tcon, const char *path)
821 {
822 	struct cifsFileInfo *cfile;
823 	struct file_list *tmp_list, *tmp_next_list;
824 	void *page;
825 	const char *full_path;
826 	LIST_HEAD(file_head);
827 
828 	page = alloc_dentry_path();
829 	spin_lock(&tcon->open_file_lock);
830 	list_for_each_entry(cfile, &tcon->openFileList, tlist) {
831 		full_path = build_path_from_dentry(cfile->dentry, page);
832 		if (strstr(full_path, path)) {
833 			if (delayed_work_pending(&cfile->deferred)) {
834 				if (cancel_delayed_work(&cfile->deferred)) {
835 					spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
836 					cifs_del_deferred_close(cfile);
837 					spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
838 
839 					tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
840 					if (tmp_list == NULL)
841 						break;
842 					tmp_list->cfile = cfile;
843 					list_add_tail(&tmp_list->list, &file_head);
844 				}
845 			}
846 		}
847 	}
848 	spin_unlock(&tcon->open_file_lock);
849 
850 	list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
851 		_cifsFileInfo_put(tmp_list->cfile, true, false);
852 		list_del(&tmp_list->list);
853 		kfree(tmp_list);
854 	}
855 	free_dentry_path(page);
856 }
857 
858 /*
859  * If a dentry has been deleted, all corresponding open handles should know that
860  * so that we do not defer close them.
861  */
cifs_mark_open_handles_for_deleted_file(struct inode * inode,const char * path)862 void cifs_mark_open_handles_for_deleted_file(struct inode *inode,
863 					     const char *path)
864 {
865 	struct cifsFileInfo *cfile;
866 	void *page;
867 	const char *full_path;
868 	struct cifsInodeInfo *cinode = CIFS_I(inode);
869 
870 	page = alloc_dentry_path();
871 	spin_lock(&cinode->open_file_lock);
872 
873 	/*
874 	 * note: we need to construct path from dentry and compare only if the
875 	 * inode has any hardlinks. When number of hardlinks is 1, we can just
876 	 * mark all open handles since they are going to be from the same file.
877 	 */
878 	if (inode->i_nlink > 1) {
879 		list_for_each_entry(cfile, &cinode->openFileList, flist) {
880 			full_path = build_path_from_dentry(cfile->dentry, page);
881 			if (!IS_ERR(full_path) && strcmp(full_path, path) == 0)
882 				cfile->status_file_deleted = true;
883 		}
884 	} else {
885 		list_for_each_entry(cfile, &cinode->openFileList, flist)
886 			cfile->status_file_deleted = true;
887 	}
888 	spin_unlock(&cinode->open_file_lock);
889 	free_dentry_path(page);
890 }
891 
892 /* parses DFS referral V3 structure
893  * caller is responsible for freeing target_nodes
894  * returns:
895  * - on success - 0
896  * - on failure - errno
897  */
898 int
parse_dfs_referrals(struct get_dfs_referral_rsp * rsp,u32 rsp_size,unsigned int * num_of_nodes,struct dfs_info3_param ** target_nodes,const struct nls_table * nls_codepage,int remap,const char * searchName,bool is_unicode)899 parse_dfs_referrals(struct get_dfs_referral_rsp *rsp, u32 rsp_size,
900 		    unsigned int *num_of_nodes,
901 		    struct dfs_info3_param **target_nodes,
902 		    const struct nls_table *nls_codepage, int remap,
903 		    const char *searchName, bool is_unicode)
904 {
905 	int i, rc = 0;
906 	char *data_end;
907 	struct dfs_referral_level_3 *ref;
908 
909 	*num_of_nodes = le16_to_cpu(rsp->NumberOfReferrals);
910 
911 	if (*num_of_nodes < 1) {
912 		cifs_dbg(VFS | ONCE, "%s: [path=%s] num_referrals must be at least > 0, but we got %d\n",
913 			 __func__, searchName, *num_of_nodes);
914 		rc = -ENOENT;
915 		goto parse_DFS_referrals_exit;
916 	}
917 
918 	ref = (struct dfs_referral_level_3 *) &(rsp->referrals);
919 	if (ref->VersionNumber != cpu_to_le16(3)) {
920 		cifs_dbg(VFS, "Referrals of V%d version are not supported, should be V3\n",
921 			 le16_to_cpu(ref->VersionNumber));
922 		rc = -EINVAL;
923 		goto parse_DFS_referrals_exit;
924 	}
925 
926 	/* get the upper boundary of the resp buffer */
927 	data_end = (char *)rsp + rsp_size;
928 
929 	cifs_dbg(FYI, "num_referrals: %d dfs flags: 0x%x ...\n",
930 		 *num_of_nodes, le32_to_cpu(rsp->DFSFlags));
931 
932 	*target_nodes = kcalloc(*num_of_nodes, sizeof(struct dfs_info3_param),
933 				GFP_KERNEL);
934 	if (*target_nodes == NULL) {
935 		rc = -ENOMEM;
936 		goto parse_DFS_referrals_exit;
937 	}
938 
939 	/* collect necessary data from referrals */
940 	for (i = 0; i < *num_of_nodes; i++) {
941 		char *temp;
942 		int max_len;
943 		struct dfs_info3_param *node = (*target_nodes)+i;
944 
945 		node->flags = le32_to_cpu(rsp->DFSFlags);
946 		if (is_unicode) {
947 			__le16 *tmp = kmalloc(strlen(searchName)*2 + 2,
948 						GFP_KERNEL);
949 			if (tmp == NULL) {
950 				rc = -ENOMEM;
951 				goto parse_DFS_referrals_exit;
952 			}
953 			cifsConvertToUTF16((__le16 *) tmp, searchName,
954 					   PATH_MAX, nls_codepage, remap);
955 			node->path_consumed = cifs_utf16_bytes(tmp,
956 					le16_to_cpu(rsp->PathConsumed),
957 					nls_codepage);
958 			kfree(tmp);
959 		} else
960 			node->path_consumed = le16_to_cpu(rsp->PathConsumed);
961 
962 		node->server_type = le16_to_cpu(ref->ServerType);
963 		node->ref_flag = le16_to_cpu(ref->ReferralEntryFlags);
964 
965 		/* copy DfsPath */
966 		temp = (char *)ref + le16_to_cpu(ref->DfsPathOffset);
967 		max_len = data_end - temp;
968 		node->path_name = cifs_strndup_from_utf16(temp, max_len,
969 						is_unicode, nls_codepage);
970 		if (!node->path_name) {
971 			rc = -ENOMEM;
972 			goto parse_DFS_referrals_exit;
973 		}
974 
975 		/* copy link target UNC */
976 		temp = (char *)ref + le16_to_cpu(ref->NetworkAddressOffset);
977 		max_len = data_end - temp;
978 		node->node_name = cifs_strndup_from_utf16(temp, max_len,
979 						is_unicode, nls_codepage);
980 		if (!node->node_name) {
981 			rc = -ENOMEM;
982 			goto parse_DFS_referrals_exit;
983 		}
984 
985 		node->ttl = le32_to_cpu(ref->TimeToLive);
986 
987 		ref++;
988 	}
989 
990 parse_DFS_referrals_exit:
991 	if (rc) {
992 		free_dfs_info_array(*target_nodes, *num_of_nodes);
993 		*target_nodes = NULL;
994 		*num_of_nodes = 0;
995 	}
996 	return rc;
997 }
998 
999 /**
1000  * cifs_alloc_hash - allocate hash and hash context together
1001  * @name: The name of the crypto hash algo
1002  * @sdesc: SHASH descriptor where to put the pointer to the hash TFM
1003  *
1004  * The caller has to make sure @sdesc is initialized to either NULL or
1005  * a valid context. It can be freed via cifs_free_hash().
1006  */
1007 int
cifs_alloc_hash(const char * name,struct shash_desc ** sdesc)1008 cifs_alloc_hash(const char *name, struct shash_desc **sdesc)
1009 {
1010 	int rc = 0;
1011 	struct crypto_shash *alg = NULL;
1012 
1013 	if (*sdesc)
1014 		return 0;
1015 
1016 	alg = crypto_alloc_shash(name, 0, 0);
1017 	if (IS_ERR(alg)) {
1018 		cifs_dbg(VFS, "Could not allocate shash TFM '%s'\n", name);
1019 		rc = PTR_ERR(alg);
1020 		*sdesc = NULL;
1021 		return rc;
1022 	}
1023 
1024 	*sdesc = kmalloc(sizeof(struct shash_desc) + crypto_shash_descsize(alg), GFP_KERNEL);
1025 	if (*sdesc == NULL) {
1026 		cifs_dbg(VFS, "no memory left to allocate shash TFM '%s'\n", name);
1027 		crypto_free_shash(alg);
1028 		return -ENOMEM;
1029 	}
1030 
1031 	(*sdesc)->tfm = alg;
1032 	return 0;
1033 }
1034 
1035 /**
1036  * cifs_free_hash - free hash and hash context together
1037  * @sdesc: Where to find the pointer to the hash TFM
1038  *
1039  * Freeing a NULL descriptor is safe.
1040  */
1041 void
cifs_free_hash(struct shash_desc ** sdesc)1042 cifs_free_hash(struct shash_desc **sdesc)
1043 {
1044 	if (unlikely(!sdesc) || !*sdesc)
1045 		return;
1046 
1047 	if ((*sdesc)->tfm) {
1048 		crypto_free_shash((*sdesc)->tfm);
1049 		(*sdesc)->tfm = NULL;
1050 	}
1051 
1052 	kfree_sensitive(*sdesc);
1053 	*sdesc = NULL;
1054 }
1055 
extract_unc_hostname(const char * unc,const char ** h,size_t * len)1056 void extract_unc_hostname(const char *unc, const char **h, size_t *len)
1057 {
1058 	const char *end;
1059 
1060 	/* skip initial slashes */
1061 	while (*unc && (*unc == '\\' || *unc == '/'))
1062 		unc++;
1063 
1064 	end = unc;
1065 
1066 	while (*end && !(*end == '\\' || *end == '/'))
1067 		end++;
1068 
1069 	*h = unc;
1070 	*len = end - unc;
1071 }
1072 
1073 /**
1074  * copy_path_name - copy src path to dst, possibly truncating
1075  * @dst: The destination buffer
1076  * @src: The source name
1077  *
1078  * returns number of bytes written (including trailing nul)
1079  */
copy_path_name(char * dst,const char * src)1080 int copy_path_name(char *dst, const char *src)
1081 {
1082 	int name_len;
1083 
1084 	/*
1085 	 * PATH_MAX includes nul, so if strlen(src) >= PATH_MAX it
1086 	 * will truncate and strlen(dst) will be PATH_MAX-1
1087 	 */
1088 	name_len = strscpy(dst, src, PATH_MAX);
1089 	if (WARN_ON_ONCE(name_len < 0))
1090 		name_len = PATH_MAX-1;
1091 
1092 	/* we count the trailing nul */
1093 	name_len++;
1094 	return name_len;
1095 }
1096 
1097 struct super_cb_data {
1098 	void *data;
1099 	struct super_block *sb;
1100 };
1101 
tcon_super_cb(struct super_block * sb,void * arg)1102 static void tcon_super_cb(struct super_block *sb, void *arg)
1103 {
1104 	struct super_cb_data *sd = arg;
1105 	struct cifs_sb_info *cifs_sb;
1106 	struct cifs_tcon *t1 = sd->data, *t2;
1107 
1108 	if (sd->sb)
1109 		return;
1110 
1111 	cifs_sb = CIFS_SB(sb);
1112 	t2 = cifs_sb_master_tcon(cifs_sb);
1113 
1114 	spin_lock(&t2->tc_lock);
1115 	if ((t1->ses == t2->ses ||
1116 	     t1->ses->dfs_root_ses == t2->ses->dfs_root_ses) &&
1117 	    t1->ses->server == t2->ses->server &&
1118 	    t2->origin_fullpath &&
1119 	    dfs_src_pathname_equal(t2->origin_fullpath, t1->origin_fullpath))
1120 		sd->sb = sb;
1121 	spin_unlock(&t2->tc_lock);
1122 }
1123 
__cifs_get_super(void (* f)(struct super_block *,void *),void * data)1124 static struct super_block *__cifs_get_super(void (*f)(struct super_block *, void *),
1125 					    void *data)
1126 {
1127 	struct super_cb_data sd = {
1128 		.data = data,
1129 		.sb = NULL,
1130 	};
1131 	struct file_system_type **fs_type = (struct file_system_type *[]) {
1132 		&cifs_fs_type, &smb3_fs_type, NULL,
1133 	};
1134 
1135 	for (; *fs_type; fs_type++) {
1136 		iterate_supers_type(*fs_type, f, &sd);
1137 		if (sd.sb) {
1138 			/*
1139 			 * Grab an active reference in order to prevent automounts (DFS links)
1140 			 * of expiring and then freeing up our cifs superblock pointer while
1141 			 * we're doing failover.
1142 			 */
1143 			cifs_sb_active(sd.sb);
1144 			return sd.sb;
1145 		}
1146 	}
1147 	pr_warn_once("%s: could not find dfs superblock\n", __func__);
1148 	return ERR_PTR(-EINVAL);
1149 }
1150 
__cifs_put_super(struct super_block * sb)1151 static void __cifs_put_super(struct super_block *sb)
1152 {
1153 	if (!IS_ERR_OR_NULL(sb))
1154 		cifs_sb_deactive(sb);
1155 }
1156 
cifs_get_dfs_tcon_super(struct cifs_tcon * tcon)1157 struct super_block *cifs_get_dfs_tcon_super(struct cifs_tcon *tcon)
1158 {
1159 	spin_lock(&tcon->tc_lock);
1160 	if (!tcon->origin_fullpath) {
1161 		spin_unlock(&tcon->tc_lock);
1162 		return ERR_PTR(-ENOENT);
1163 	}
1164 	spin_unlock(&tcon->tc_lock);
1165 	return __cifs_get_super(tcon_super_cb, tcon);
1166 }
1167 
cifs_put_tcp_super(struct super_block * sb)1168 void cifs_put_tcp_super(struct super_block *sb)
1169 {
1170 	__cifs_put_super(sb);
1171 }
1172 
1173 #ifdef CONFIG_CIFS_DFS_UPCALL
match_target_ip(struct TCP_Server_Info * server,const char * host,size_t hostlen,bool * result)1174 int match_target_ip(struct TCP_Server_Info *server,
1175 		    const char *host, size_t hostlen,
1176 		    bool *result)
1177 {
1178 	struct sockaddr_storage ss;
1179 	int rc;
1180 
1181 	cifs_dbg(FYI, "%s: hostname=%.*s\n", __func__, (int)hostlen, host);
1182 
1183 	*result = false;
1184 
1185 	rc = dns_resolve_name(server->dns_dom, host, hostlen,
1186 			      (struct sockaddr *)&ss);
1187 	if (rc < 0)
1188 		return rc;
1189 
1190 	spin_lock(&server->srv_lock);
1191 	*result = cifs_match_ipaddr((struct sockaddr *)&server->dstaddr, (struct sockaddr *)&ss);
1192 	spin_unlock(&server->srv_lock);
1193 	cifs_dbg(FYI, "%s: ip addresses matched: %s\n", __func__, str_yes_no(*result));
1194 	return 0;
1195 }
1196 
cifs_update_super_prepath(struct cifs_sb_info * cifs_sb,char * prefix)1197 int cifs_update_super_prepath(struct cifs_sb_info *cifs_sb, char *prefix)
1198 {
1199 	int rc;
1200 
1201 	kfree(cifs_sb->prepath);
1202 	cifs_sb->prepath = NULL;
1203 
1204 	if (prefix && *prefix) {
1205 		cifs_sb->prepath = cifs_sanitize_prepath(prefix, GFP_ATOMIC);
1206 		if (IS_ERR(cifs_sb->prepath)) {
1207 			rc = PTR_ERR(cifs_sb->prepath);
1208 			cifs_sb->prepath = NULL;
1209 			return rc;
1210 		}
1211 		if (cifs_sb->prepath)
1212 			convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb));
1213 	}
1214 
1215 	cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
1216 	return 0;
1217 }
1218 
1219 /*
1220  * Handle weird Windows SMB server behaviour. It responds with
1221  * STATUS_OBJECT_NAME_INVALID code to SMB2 QUERY_INFO request for
1222  * "\<server>\<dfsname>\<linkpath>" DFS reference, where <dfsname> contains
1223  * non-ASCII unicode symbols.
1224  */
cifs_inval_name_dfs_link_error(const unsigned int xid,struct cifs_tcon * tcon,struct cifs_sb_info * cifs_sb,const char * full_path,bool * islink)1225 int cifs_inval_name_dfs_link_error(const unsigned int xid,
1226 				   struct cifs_tcon *tcon,
1227 				   struct cifs_sb_info *cifs_sb,
1228 				   const char *full_path,
1229 				   bool *islink)
1230 {
1231 	struct TCP_Server_Info *server = tcon->ses->server;
1232 	struct cifs_ses *ses = tcon->ses;
1233 	size_t len;
1234 	char *path;
1235 	char *ref_path;
1236 
1237 	*islink = false;
1238 
1239 	/*
1240 	 * Fast path - skip check when @full_path doesn't have a prefix path to
1241 	 * look up or tcon is not DFS.
1242 	 */
1243 	if (strlen(full_path) < 2 || !cifs_sb ||
1244 	    (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
1245 	    !is_tcon_dfs(tcon))
1246 		return 0;
1247 
1248 	spin_lock(&server->srv_lock);
1249 	if (!server->leaf_fullpath) {
1250 		spin_unlock(&server->srv_lock);
1251 		return 0;
1252 	}
1253 	spin_unlock(&server->srv_lock);
1254 
1255 	/*
1256 	 * Slow path - tcon is DFS and @full_path has prefix path, so attempt
1257 	 * to get a referral to figure out whether it is an DFS link.
1258 	 */
1259 	len = strnlen(tcon->tree_name, MAX_TREE_SIZE + 1) + strlen(full_path) + 1;
1260 	path = kmalloc(len, GFP_KERNEL);
1261 	if (!path)
1262 		return -ENOMEM;
1263 
1264 	scnprintf(path, len, "%s%s", tcon->tree_name, full_path);
1265 	ref_path = dfs_cache_canonical_path(path + 1, cifs_sb->local_nls,
1266 					    cifs_remap(cifs_sb));
1267 	kfree(path);
1268 
1269 	if (IS_ERR(ref_path)) {
1270 		if (PTR_ERR(ref_path) != -EINVAL)
1271 			return PTR_ERR(ref_path);
1272 	} else {
1273 		struct dfs_info3_param *refs = NULL;
1274 		int num_refs = 0;
1275 
1276 		/*
1277 		 * XXX: we are not using dfs_cache_find() here because we might
1278 		 * end up filling all the DFS cache and thus potentially
1279 		 * removing cached DFS targets that the client would eventually
1280 		 * need during failover.
1281 		 */
1282 		ses = CIFS_DFS_ROOT_SES(ses);
1283 		if (ses->server->ops->get_dfs_refer &&
1284 		    !ses->server->ops->get_dfs_refer(xid, ses, ref_path, &refs,
1285 						     &num_refs, cifs_sb->local_nls,
1286 						     cifs_remap(cifs_sb)))
1287 			*islink = refs[0].server_type == DFS_TYPE_LINK;
1288 		free_dfs_info_array(refs, num_refs);
1289 		kfree(ref_path);
1290 	}
1291 	return 0;
1292 }
1293 #endif
1294 
cifs_wait_for_server_reconnect(struct TCP_Server_Info * server,bool retry)1295 int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry)
1296 {
1297 	int timeout = 10;
1298 	int rc;
1299 
1300 	spin_lock(&server->srv_lock);
1301 	if (server->tcpStatus != CifsNeedReconnect) {
1302 		spin_unlock(&server->srv_lock);
1303 		return 0;
1304 	}
1305 	timeout *= server->nr_targets;
1306 	spin_unlock(&server->srv_lock);
1307 
1308 	/*
1309 	 * Give demultiplex thread up to 10 seconds to each target available for
1310 	 * reconnect -- should be greater than cifs socket timeout which is 7
1311 	 * seconds.
1312 	 *
1313 	 * On "soft" mounts we wait once. Hard mounts keep retrying until
1314 	 * process is killed or server comes back on-line.
1315 	 */
1316 	do {
1317 		rc = wait_event_interruptible_timeout(server->response_q,
1318 						      (server->tcpStatus != CifsNeedReconnect),
1319 						      timeout * HZ);
1320 		if (rc < 0) {
1321 			cifs_dbg(FYI, "%s: aborting reconnect due to received signal\n",
1322 				 __func__);
1323 			return -ERESTARTSYS;
1324 		}
1325 
1326 		/* are we still trying to reconnect? */
1327 		spin_lock(&server->srv_lock);
1328 		if (server->tcpStatus != CifsNeedReconnect) {
1329 			spin_unlock(&server->srv_lock);
1330 			return 0;
1331 		}
1332 		spin_unlock(&server->srv_lock);
1333 	} while (retry);
1334 
1335 	cifs_dbg(FYI, "%s: gave up waiting on reconnect\n", __func__);
1336 	return -EHOSTDOWN;
1337 }
1338