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