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