1 /*
2  *   fs/cifs/smb2pdu.c
3  *
4  *   Copyright (C) International Business Machines  Corp., 2009, 2013
5  *                 Etersoft, 2012
6  *   Author(s): Steve French (sfrench@us.ibm.com)
7  *              Pavel Shilovsky (pshilovsky@samba.org) 2012
8  *
9  *   Contains the routines for constructing the SMB2 PDUs themselves
10  *
11  *   This library is free software; you can redistribute it and/or modify
12  *   it under the terms of the GNU Lesser General Public License as published
13  *   by the Free Software Foundation; either version 2.1 of the License, or
14  *   (at your option) any later version.
15  *
16  *   This library is distributed in the hope that it will be useful,
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
19  *   the GNU Lesser General Public License for more details.
20  *
21  *   You should have received a copy of the GNU Lesser General Public License
22  *   along with this library; if not, write to the Free Software
23  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24  */
25 
26  /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */
27  /* Note that there are handle based routines which must be		      */
28  /* treated slightly differently for reconnection purposes since we never     */
29  /* want to reuse a stale file handle and only the caller knows the file info */
30 
31 #include <linux/fs.h>
32 #include <linux/kernel.h>
33 #include <linux/vfs.h>
34 #include <linux/task_io_accounting_ops.h>
35 #include <linux/uaccess.h>
36 #include <linux/uuid.h>
37 #include <linux/pagemap.h>
38 #include <linux/xattr.h>
39 #include "smb2pdu.h"
40 #include "cifsglob.h"
41 #include "cifsacl.h"
42 #include "cifsproto.h"
43 #include "smb2proto.h"
44 #include "cifs_unicode.h"
45 #include "cifs_debug.h"
46 #include "ntlmssp.h"
47 #include "smb2status.h"
48 #include "smb2glob.h"
49 #include "cifspdu.h"
50 #include "cifs_spnego.h"
51 #include "smbdirect.h"
52 #include "trace.h"
53 
54 /*
55  *  The following table defines the expected "StructureSize" of SMB2 requests
56  *  in order by SMB2 command.  This is similar to "wct" in SMB/CIFS requests.
57  *
58  *  Note that commands are defined in smb2pdu.h in le16 but the array below is
59  *  indexed by command in host byte order.
60  */
61 static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
62 	/* SMB2_NEGOTIATE */ 36,
63 	/* SMB2_SESSION_SETUP */ 25,
64 	/* SMB2_LOGOFF */ 4,
65 	/* SMB2_TREE_CONNECT */	9,
66 	/* SMB2_TREE_DISCONNECT */ 4,
67 	/* SMB2_CREATE */ 57,
68 	/* SMB2_CLOSE */ 24,
69 	/* SMB2_FLUSH */ 24,
70 	/* SMB2_READ */	49,
71 	/* SMB2_WRITE */ 49,
72 	/* SMB2_LOCK */	48,
73 	/* SMB2_IOCTL */ 57,
74 	/* SMB2_CANCEL */ 4,
75 	/* SMB2_ECHO */ 4,
76 	/* SMB2_QUERY_DIRECTORY */ 33,
77 	/* SMB2_CHANGE_NOTIFY */ 32,
78 	/* SMB2_QUERY_INFO */ 41,
79 	/* SMB2_SET_INFO */ 33,
80 	/* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
81 };
82 
smb3_encryption_required(const struct cifs_tcon * tcon)83 int smb3_encryption_required(const struct cifs_tcon *tcon)
84 {
85 	if (!tcon)
86 		return 0;
87 	if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) ||
88 	    (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA))
89 		return 1;
90 	if (tcon->seal &&
91 	    (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
92 		return 1;
93 	return 0;
94 }
95 
96 static void
smb2_hdr_assemble(struct smb2_sync_hdr * shdr,__le16 smb2_cmd,const struct cifs_tcon * tcon)97 smb2_hdr_assemble(struct smb2_sync_hdr *shdr, __le16 smb2_cmd,
98 		  const struct cifs_tcon *tcon)
99 {
100 	shdr->ProtocolId = SMB2_PROTO_NUMBER;
101 	shdr->StructureSize = cpu_to_le16(64);
102 	shdr->Command = smb2_cmd;
103 	if (tcon && tcon->ses && tcon->ses->server) {
104 		struct TCP_Server_Info *server = tcon->ses->server;
105 
106 		spin_lock(&server->req_lock);
107 		/* Request up to 2 credits but don't go over the limit. */
108 		if (server->credits >= server->max_credits)
109 			shdr->CreditRequest = cpu_to_le16(0);
110 		else
111 			shdr->CreditRequest = cpu_to_le16(
112 				min_t(int, server->max_credits -
113 						server->credits, 2));
114 		spin_unlock(&server->req_lock);
115 	} else {
116 		shdr->CreditRequest = cpu_to_le16(2);
117 	}
118 	shdr->ProcessId = cpu_to_le32((__u16)current->tgid);
119 
120 	if (!tcon)
121 		goto out;
122 
123 	/* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
124 	/* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
125 	if ((tcon->ses) && (tcon->ses->server) &&
126 	    (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
127 		shdr->CreditCharge = cpu_to_le16(1);
128 	/* else CreditCharge MBZ */
129 
130 	shdr->TreeId = tcon->tid;
131 	/* Uid is not converted */
132 	if (tcon->ses)
133 		shdr->SessionId = tcon->ses->Suid;
134 
135 	/*
136 	 * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
137 	 * to pass the path on the Open SMB prefixed by \\server\share.
138 	 * Not sure when we would need to do the augmented path (if ever) and
139 	 * setting this flag breaks the SMB2 open operation since it is
140 	 * illegal to send an empty path name (without \\server\share prefix)
141 	 * when the DFS flag is set in the SMB open header. We could
142 	 * consider setting the flag on all operations other than open
143 	 * but it is safer to net set it for now.
144 	 */
145 /*	if (tcon->share_flags & SHI1005_FLAGS_DFS)
146 		shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
147 
148 	if (tcon->ses && tcon->ses->server && tcon->ses->server->sign &&
149 	    !smb3_encryption_required(tcon))
150 		shdr->Flags |= SMB2_FLAGS_SIGNED;
151 out:
152 	return;
153 }
154 
155 static int
smb2_reconnect(__le16 smb2_command,struct cifs_tcon * tcon)156 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon)
157 {
158 	int rc;
159 	struct nls_table *nls_codepage;
160 	struct cifs_ses *ses;
161 	struct TCP_Server_Info *server;
162 
163 	/*
164 	 * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
165 	 * check for tcp and smb session status done differently
166 	 * for those three - in the calling routine.
167 	 */
168 	if (tcon == NULL)
169 		return 0;
170 
171 	if (smb2_command == SMB2_TREE_CONNECT)
172 		return 0;
173 
174 	if (tcon->tidStatus == CifsExiting) {
175 		/*
176 		 * only tree disconnect, open, and write,
177 		 * (and ulogoff which does not have tcon)
178 		 * are allowed as we start force umount.
179 		 */
180 		if ((smb2_command != SMB2_WRITE) &&
181 		   (smb2_command != SMB2_CREATE) &&
182 		   (smb2_command != SMB2_TREE_DISCONNECT)) {
183 			cifs_dbg(FYI, "can not send cmd %d while umounting\n",
184 				 smb2_command);
185 			return -ENODEV;
186 		}
187 	}
188 	if ((!tcon->ses) || (tcon->ses->status == CifsExiting) ||
189 	    (!tcon->ses->server))
190 		return -EIO;
191 
192 	ses = tcon->ses;
193 	server = ses->server;
194 
195 	/*
196 	 * Give demultiplex thread up to 10 seconds to reconnect, should be
197 	 * greater than cifs socket timeout which is 7 seconds
198 	 */
199 	while (server->tcpStatus == CifsNeedReconnect) {
200 		/*
201 		 * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
202 		 * here since they are implicitly done when session drops.
203 		 */
204 		switch (smb2_command) {
205 		/*
206 		 * BB Should we keep oplock break and add flush to exceptions?
207 		 */
208 		case SMB2_TREE_DISCONNECT:
209 		case SMB2_CANCEL:
210 		case SMB2_CLOSE:
211 		case SMB2_OPLOCK_BREAK:
212 			return -EAGAIN;
213 		}
214 
215 		rc = wait_event_interruptible_timeout(server->response_q,
216 						      (server->tcpStatus != CifsNeedReconnect),
217 						      10 * HZ);
218 		if (rc < 0) {
219 			cifs_dbg(FYI, "%s: aborting reconnect due to a received"
220 				 " signal by the process\n", __func__);
221 			return -ERESTARTSYS;
222 		}
223 
224 		/* are we still trying to reconnect? */
225 		if (server->tcpStatus != CifsNeedReconnect)
226 			break;
227 
228 		/*
229 		 * on "soft" mounts we wait once. Hard mounts keep
230 		 * retrying until process is killed or server comes
231 		 * back on-line
232 		 */
233 		if (!tcon->retry) {
234 			cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n");
235 			return -EHOSTDOWN;
236 		}
237 	}
238 
239 	if (!tcon->ses->need_reconnect && !tcon->need_reconnect)
240 		return 0;
241 
242 	nls_codepage = load_nls_default();
243 
244 	/*
245 	 * need to prevent multiple threads trying to simultaneously reconnect
246 	 * the same SMB session
247 	 */
248 	mutex_lock(&tcon->ses->session_mutex);
249 
250 	/*
251 	 * Recheck after acquire mutex. If another thread is negotiating
252 	 * and the server never sends an answer the socket will be closed
253 	 * and tcpStatus set to reconnect.
254 	 */
255 	if (server->tcpStatus == CifsNeedReconnect) {
256 		rc = -EHOSTDOWN;
257 		mutex_unlock(&tcon->ses->session_mutex);
258 		goto out;
259 	}
260 
261 	rc = cifs_negotiate_protocol(0, tcon->ses);
262 	if (!rc && tcon->ses->need_reconnect) {
263 		rc = cifs_setup_session(0, tcon->ses, nls_codepage);
264 		if ((rc == -EACCES) && !tcon->retry) {
265 			rc = -EHOSTDOWN;
266 			mutex_unlock(&tcon->ses->session_mutex);
267 			goto failed;
268 		} else if (rc) {
269 			mutex_unlock(&ses->session_mutex);
270 			goto out;
271 		}
272 	}
273 	if (rc || !tcon->need_reconnect) {
274 		mutex_unlock(&tcon->ses->session_mutex);
275 		goto out;
276 	}
277 
278 	cifs_mark_open_files_invalid(tcon);
279 	if (tcon->use_persistent)
280 		tcon->need_reopen_files = true;
281 
282 	rc = SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nls_codepage);
283 	mutex_unlock(&tcon->ses->session_mutex);
284 
285 	cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
286 	if (rc) {
287 		/* If sess reconnected but tcon didn't, something strange ... */
288 		printk_once(KERN_WARNING "reconnect tcon failed rc = %d\n", rc);
289 		goto out;
290 	}
291 
292 	if (smb2_command != SMB2_INTERNAL_CMD)
293 		queue_delayed_work(cifsiod_wq, &server->reconnect, 0);
294 
295 	atomic_inc(&tconInfoReconnectCount);
296 out:
297 	/*
298 	 * Check if handle based operation so we know whether we can continue
299 	 * or not without returning to caller to reset file handle.
300 	 */
301 	/*
302 	 * BB Is flush done by server on drop of tcp session? Should we special
303 	 * case it and skip above?
304 	 */
305 	switch (smb2_command) {
306 	case SMB2_FLUSH:
307 	case SMB2_READ:
308 	case SMB2_WRITE:
309 	case SMB2_LOCK:
310 	case SMB2_IOCTL:
311 	case SMB2_QUERY_DIRECTORY:
312 	case SMB2_CHANGE_NOTIFY:
313 	case SMB2_QUERY_INFO:
314 	case SMB2_SET_INFO:
315 		rc = -EAGAIN;
316 	}
317 failed:
318 	unload_nls(nls_codepage);
319 	return rc;
320 }
321 
322 static void
fill_small_buf(__le16 smb2_command,struct cifs_tcon * tcon,void * buf,unsigned int * total_len)323 fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon, void *buf,
324 	       unsigned int *total_len)
325 {
326 	struct smb2_sync_pdu *spdu = (struct smb2_sync_pdu *)buf;
327 	/* lookup word count ie StructureSize from table */
328 	__u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)];
329 
330 	/*
331 	 * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
332 	 * largest operations (Create)
333 	 */
334 	memset(buf, 0, 256);
335 
336 	smb2_hdr_assemble(&spdu->sync_hdr, smb2_command, tcon);
337 	spdu->StructureSize2 = cpu_to_le16(parmsize);
338 
339 	*total_len = parmsize + sizeof(struct smb2_sync_hdr);
340 }
341 
342 /*
343  * Allocate and return pointer to an SMB request hdr, and set basic
344  * SMB information in the SMB header. If the return code is zero, this
345  * function must have filled in request_buf pointer.
346  */
__smb2_plain_req_init(__le16 smb2_command,struct cifs_tcon * tcon,void ** request_buf,unsigned int * total_len)347 static int __smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
348 				  void **request_buf, unsigned int *total_len)
349 {
350 	/* BB eventually switch this to SMB2 specific small buf size */
351 	if (smb2_command == SMB2_SET_INFO)
352 		*request_buf = cifs_buf_get();
353 	else
354 		*request_buf = cifs_small_buf_get();
355 	if (*request_buf == NULL) {
356 		/* BB should we add a retry in here if not a writepage? */
357 		return -ENOMEM;
358 	}
359 
360 	fill_small_buf(smb2_command, tcon,
361 		       (struct smb2_sync_hdr *)(*request_buf),
362 		       total_len);
363 
364 	if (tcon != NULL) {
365 		uint16_t com_code = le16_to_cpu(smb2_command);
366 		cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
367 		cifs_stats_inc(&tcon->num_smbs_sent);
368 	}
369 
370 	return 0;
371 }
372 
smb2_plain_req_init(__le16 smb2_command,struct cifs_tcon * tcon,void ** request_buf,unsigned int * total_len)373 static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
374 			       void **request_buf, unsigned int *total_len)
375 {
376 	int rc;
377 
378 	rc = smb2_reconnect(smb2_command, tcon);
379 	if (rc)
380 		return rc;
381 
382 	return __smb2_plain_req_init(smb2_command, tcon, request_buf,
383 				     total_len);
384 }
385 
smb2_ioctl_req_init(u32 opcode,struct cifs_tcon * tcon,void ** request_buf,unsigned int * total_len)386 static int smb2_ioctl_req_init(u32 opcode, struct cifs_tcon *tcon,
387 			       void **request_buf, unsigned int *total_len)
388 {
389 	/* Skip reconnect only for FSCTL_VALIDATE_NEGOTIATE_INFO IOCTLs */
390 	if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO) {
391 		return __smb2_plain_req_init(SMB2_IOCTL, tcon, request_buf,
392 					     total_len);
393 	}
394 	return smb2_plain_req_init(SMB2_IOCTL, tcon, request_buf, total_len);
395 }
396 
397 
398 /* offset is sizeof smb2_negotiate_req but rounded up to 8 bytes */
399 #define OFFSET_OF_NEG_CONTEXT 0x68  /* sizeof(struct smb2_negotiate_req) */
400 
401 
402 #define SMB2_PREAUTH_INTEGRITY_CAPABILITIES	cpu_to_le16(1)
403 #define SMB2_ENCRYPTION_CAPABILITIES		cpu_to_le16(2)
404 #define SMB2_POSIX_EXTENSIONS_AVAILABLE		cpu_to_le16(0x100)
405 
406 static void
build_preauth_ctxt(struct smb2_preauth_neg_context * pneg_ctxt)407 build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
408 {
409 	pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
410 	pneg_ctxt->DataLength = cpu_to_le16(38);
411 	pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
412 	pneg_ctxt->SaltLength = cpu_to_le16(SMB311_LINUX_CLIENT_SALT_SIZE);
413 	get_random_bytes(pneg_ctxt->Salt, SMB311_LINUX_CLIENT_SALT_SIZE);
414 	pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
415 }
416 
417 static void
build_encrypt_ctxt(struct smb2_encryption_neg_context * pneg_ctxt)418 build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
419 {
420 	pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
421 	pneg_ctxt->DataLength = cpu_to_le16(4); /* Cipher Count + le16 cipher */
422 	pneg_ctxt->CipherCount = cpu_to_le16(1);
423 /* pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;*/ /* not supported yet */
424 	pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_CCM;
425 }
426 
427 static void
build_posix_ctxt(struct smb2_posix_neg_context * pneg_ctxt)428 build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
429 {
430 	pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
431 	pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
432 }
433 
434 static void
assemble_neg_contexts(struct smb2_negotiate_req * req,unsigned int * total_len)435 assemble_neg_contexts(struct smb2_negotiate_req *req,
436 		      unsigned int *total_len)
437 {
438 	char *pneg_ctxt = (char *)req + OFFSET_OF_NEG_CONTEXT;
439 	unsigned int ctxt_len;
440 
441 	*total_len += 2; /* Add 2 due to round to 8 byte boundary for 1st ctxt */
442 	build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
443 	ctxt_len = DIV_ROUND_UP(sizeof(struct smb2_preauth_neg_context), 8) * 8;
444 	*total_len += ctxt_len;
445 	pneg_ctxt += ctxt_len;
446 
447 	build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
448 	ctxt_len = DIV_ROUND_UP(sizeof(struct smb2_encryption_neg_context), 8) * 8;
449 	*total_len += ctxt_len;
450 	pneg_ctxt += ctxt_len;
451 
452 	build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
453 	*total_len += sizeof(struct smb2_posix_neg_context);
454 
455 	req->NegotiateContextOffset = cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
456 	req->NegotiateContextCount = cpu_to_le16(3);
457 }
458 
decode_preauth_context(struct smb2_preauth_neg_context * ctxt)459 static void decode_preauth_context(struct smb2_preauth_neg_context *ctxt)
460 {
461 	unsigned int len = le16_to_cpu(ctxt->DataLength);
462 
463 	/* If invalid preauth context warn but use what we requested, SHA-512 */
464 	if (len < MIN_PREAUTH_CTXT_DATA_LEN) {
465 		printk_once(KERN_WARNING "server sent bad preauth context\n");
466 		return;
467 	} else if (len < MIN_PREAUTH_CTXT_DATA_LEN + le16_to_cpu(ctxt->SaltLength)) {
468 		pr_warn_once("server sent invalid SaltLength\n");
469 		return;
470 	}
471 	if (le16_to_cpu(ctxt->HashAlgorithmCount) != 1)
472 		printk_once(KERN_WARNING "illegal SMB3 hash algorithm count\n");
473 	if (ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
474 		printk_once(KERN_WARNING "unknown SMB3 hash algorithm\n");
475 }
476 
decode_encrypt_ctx(struct TCP_Server_Info * server,struct smb2_encryption_neg_context * ctxt)477 static int decode_encrypt_ctx(struct TCP_Server_Info *server,
478 			      struct smb2_encryption_neg_context *ctxt)
479 {
480 	unsigned int len = le16_to_cpu(ctxt->DataLength);
481 
482 	cifs_dbg(FYI, "decode SMB3.11 encryption neg context of len %d\n", len);
483 	if (len < MIN_ENCRYPT_CTXT_DATA_LEN) {
484 		printk_once(KERN_WARNING "server sent bad crypto ctxt len\n");
485 		return -EINVAL;
486 	}
487 
488 	if (le16_to_cpu(ctxt->CipherCount) != 1) {
489 		printk_once(KERN_WARNING "illegal SMB3.11 cipher count\n");
490 		return -EINVAL;
491 	}
492 	cifs_dbg(FYI, "SMB311 cipher type:%d\n", le16_to_cpu(ctxt->Ciphers[0]));
493 	if ((ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_CCM) &&
494 	    (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_GCM)) {
495 		printk_once(KERN_WARNING "invalid SMB3.11 cipher returned\n");
496 		return -EINVAL;
497 	}
498 	server->cipher_type = ctxt->Ciphers[0];
499 	server->capabilities |= SMB2_GLOBAL_CAP_ENCRYPTION;
500 	return 0;
501 }
502 
smb311_decode_neg_context(struct smb2_negotiate_rsp * rsp,struct TCP_Server_Info * server,unsigned int len_of_smb)503 static int smb311_decode_neg_context(struct smb2_negotiate_rsp *rsp,
504 				     struct TCP_Server_Info *server,
505 				     unsigned int len_of_smb)
506 {
507 	struct smb2_neg_context *pctx;
508 	unsigned int offset = le32_to_cpu(rsp->NegotiateContextOffset);
509 	unsigned int ctxt_cnt = le16_to_cpu(rsp->NegotiateContextCount);
510 	unsigned int len_of_ctxts, i;
511 	int rc = 0;
512 
513 	cifs_dbg(FYI, "decoding %d negotiate contexts\n", ctxt_cnt);
514 	if (len_of_smb <= offset) {
515 		cifs_dbg(VFS, "Invalid response: negotiate context offset\n");
516 		return -EINVAL;
517 	}
518 
519 	len_of_ctxts = len_of_smb - offset;
520 
521 	for (i = 0; i < ctxt_cnt; i++) {
522 		int clen;
523 		/* check that offset is not beyond end of SMB */
524 		if (len_of_ctxts == 0)
525 			break;
526 
527 		if (len_of_ctxts < sizeof(struct smb2_neg_context))
528 			break;
529 
530 		pctx = (struct smb2_neg_context *)(offset + (char *)rsp);
531 		clen = le16_to_cpu(pctx->DataLength);
532 		if (clen > len_of_ctxts)
533 			break;
534 
535 		if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES)
536 			decode_preauth_context(
537 				(struct smb2_preauth_neg_context *)pctx);
538 		else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES)
539 			rc = decode_encrypt_ctx(server,
540 				(struct smb2_encryption_neg_context *)pctx);
541 		else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE)
542 			server->posix_ext_supported = true;
543 		else
544 			cifs_dbg(VFS, "unknown negcontext of type %d ignored\n",
545 				le16_to_cpu(pctx->ContextType));
546 
547 		if (rc)
548 			break;
549 		/* offsets must be 8 byte aligned */
550 		clen = (clen + 7) & ~0x7;
551 		offset += clen + sizeof(struct smb2_neg_context);
552 		len_of_ctxts -= clen;
553 	}
554 	return rc;
555 }
556 
557 static struct create_posix *
create_posix_buf(umode_t mode)558 create_posix_buf(umode_t mode)
559 {
560 	struct create_posix *buf;
561 
562 	buf = kzalloc(sizeof(struct create_posix),
563 			GFP_KERNEL);
564 	if (!buf)
565 		return NULL;
566 
567 	buf->ccontext.DataOffset =
568 		cpu_to_le16(offsetof(struct create_posix, Mode));
569 	buf->ccontext.DataLength = cpu_to_le32(4);
570 	buf->ccontext.NameOffset =
571 		cpu_to_le16(offsetof(struct create_posix, Name));
572 	buf->ccontext.NameLength = cpu_to_le16(16);
573 
574 	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
575 	buf->Name[0] = 0x93;
576 	buf->Name[1] = 0xAD;
577 	buf->Name[2] = 0x25;
578 	buf->Name[3] = 0x50;
579 	buf->Name[4] = 0x9C;
580 	buf->Name[5] = 0xB4;
581 	buf->Name[6] = 0x11;
582 	buf->Name[7] = 0xE7;
583 	buf->Name[8] = 0xB4;
584 	buf->Name[9] = 0x23;
585 	buf->Name[10] = 0x83;
586 	buf->Name[11] = 0xDE;
587 	buf->Name[12] = 0x96;
588 	buf->Name[13] = 0x8B;
589 	buf->Name[14] = 0xCD;
590 	buf->Name[15] = 0x7C;
591 	buf->Mode = cpu_to_le32(mode);
592 	cifs_dbg(FYI, "mode on posix create 0%o", mode);
593 	return buf;
594 }
595 
596 static int
add_posix_context(struct kvec * iov,unsigned int * num_iovec,umode_t mode)597 add_posix_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode)
598 {
599 	struct smb2_create_req *req = iov[0].iov_base;
600 	unsigned int num = *num_iovec;
601 
602 	iov[num].iov_base = create_posix_buf(mode);
603 	if (iov[num].iov_base == NULL)
604 		return -ENOMEM;
605 	iov[num].iov_len = sizeof(struct create_posix);
606 	if (!req->CreateContextsOffset)
607 		req->CreateContextsOffset = cpu_to_le32(
608 				sizeof(struct smb2_create_req) +
609 				iov[num - 1].iov_len);
610 	le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_posix));
611 	*num_iovec = num + 1;
612 	return 0;
613 }
614 
615 
616 /*
617  *
618  *	SMB2 Worker functions follow:
619  *
620  *	The general structure of the worker functions is:
621  *	1) Call smb2_init (assembles SMB2 header)
622  *	2) Initialize SMB2 command specific fields in fixed length area of SMB
623  *	3) Call smb_sendrcv2 (sends request on socket and waits for response)
624  *	4) Decode SMB2 command specific fields in the fixed length area
625  *	5) Decode variable length data area (if any for this SMB2 command type)
626  *	6) Call free smb buffer
627  *	7) return
628  *
629  */
630 
631 int
SMB2_negotiate(const unsigned int xid,struct cifs_ses * ses)632 SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)
633 {
634 	struct smb_rqst rqst;
635 	struct smb2_negotiate_req *req;
636 	struct smb2_negotiate_rsp *rsp;
637 	struct kvec iov[1];
638 	struct kvec rsp_iov;
639 	int rc = 0;
640 	int resp_buftype;
641 	struct TCP_Server_Info *server = ses->server;
642 	int blob_offset, blob_length;
643 	char *security_blob;
644 	int flags = CIFS_NEG_OP;
645 	unsigned int total_len;
646 
647 	cifs_dbg(FYI, "Negotiate protocol\n");
648 
649 	if (!server) {
650 		WARN(1, "%s: server is NULL!\n", __func__);
651 		return -EIO;
652 	}
653 
654 	rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, (void **) &req, &total_len);
655 	if (rc)
656 		return rc;
657 
658 	req->sync_hdr.SessionId = 0;
659 
660 	memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
661 	memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
662 
663 	if (strcmp(ses->server->vals->version_string,
664 		   SMB3ANY_VERSION_STRING) == 0) {
665 		req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
666 		req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
667 		req->DialectCount = cpu_to_le16(2);
668 		total_len += 4;
669 	} else if (strcmp(ses->server->vals->version_string,
670 		   SMBDEFAULT_VERSION_STRING) == 0) {
671 		req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
672 		req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
673 		req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
674 		req->DialectCount = cpu_to_le16(3);
675 		total_len += 6;
676 	} else {
677 		/* otherwise send specific dialect */
678 		req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id);
679 		req->DialectCount = cpu_to_le16(1);
680 		total_len += 2;
681 	}
682 
683 	/* only one of SMB2 signing flags may be set in SMB2 request */
684 	if (ses->sign)
685 		req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
686 	else if (global_secflags & CIFSSEC_MAY_SIGN)
687 		req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
688 	else
689 		req->SecurityMode = 0;
690 
691 	req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities);
692 
693 	/* ClientGUID must be zero for SMB2.02 dialect */
694 	if (ses->server->vals->protocol_id == SMB20_PROT_ID)
695 		memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
696 	else {
697 		memcpy(req->ClientGUID, server->client_guid,
698 			SMB2_CLIENT_GUID_SIZE);
699 		if (ses->server->vals->protocol_id == SMB311_PROT_ID)
700 			assemble_neg_contexts(req, &total_len);
701 	}
702 	iov[0].iov_base = (char *)req;
703 	iov[0].iov_len = total_len;
704 
705 	memset(&rqst, 0, sizeof(struct smb_rqst));
706 	rqst.rq_iov = iov;
707 	rqst.rq_nvec = 1;
708 
709 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
710 	cifs_small_buf_release(req);
711 	rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
712 	/*
713 	 * No tcon so can't do
714 	 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
715 	 */
716 	if (rc == -EOPNOTSUPP) {
717 		cifs_dbg(VFS, "Dialect not supported by server. Consider "
718 			"specifying vers=1.0 or vers=2.0 on mount for accessing"
719 			" older servers\n");
720 		goto neg_exit;
721 	} else if (rc != 0)
722 		goto neg_exit;
723 
724 	if (strcmp(ses->server->vals->version_string,
725 		   SMB3ANY_VERSION_STRING) == 0) {
726 		if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
727 			cifs_dbg(VFS,
728 				"SMB2 dialect returned but not requested\n");
729 			return -EIO;
730 		} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
731 			cifs_dbg(VFS,
732 				"SMB2.1 dialect returned but not requested\n");
733 			return -EIO;
734 		}
735 	} else if (strcmp(ses->server->vals->version_string,
736 		   SMBDEFAULT_VERSION_STRING) == 0) {
737 		if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
738 			cifs_dbg(VFS,
739 				"SMB2 dialect returned but not requested\n");
740 			return -EIO;
741 		} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
742 			/* ops set to 3.0 by default for default so update */
743 			ses->server->ops = &smb21_operations;
744 			ses->server->vals = &smb21_values;
745 		}
746 	} else if (le16_to_cpu(rsp->DialectRevision) !=
747 				ses->server->vals->protocol_id) {
748 		/* if requested single dialect ensure returned dialect matched */
749 		cifs_dbg(VFS, "Illegal 0x%x dialect returned: not requested\n",
750 			le16_to_cpu(rsp->DialectRevision));
751 		return -EIO;
752 	}
753 
754 	cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
755 
756 	if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
757 		cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
758 	else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
759 		cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
760 	else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
761 		cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
762 	else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
763 		cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
764 	else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
765 		cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
766 	else {
767 		cifs_dbg(VFS, "Illegal dialect returned by server 0x%x\n",
768 			 le16_to_cpu(rsp->DialectRevision));
769 		rc = -EIO;
770 		goto neg_exit;
771 	}
772 	server->dialect = le16_to_cpu(rsp->DialectRevision);
773 
774 	/*
775 	 * Keep a copy of the hash after negprot. This hash will be
776 	 * the starting hash value for all sessions made from this
777 	 * server.
778 	 */
779 	memcpy(server->preauth_sha_hash, ses->preauth_sha_hash,
780 	       SMB2_PREAUTH_HASH_SIZE);
781 
782 	/* SMB2 only has an extended negflavor */
783 	server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
784 	/* set it to the maximum buffer size value we can send with 1 credit */
785 	server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
786 			       SMB2_MAX_BUFFER_SIZE);
787 	server->max_read = le32_to_cpu(rsp->MaxReadSize);
788 	server->max_write = le32_to_cpu(rsp->MaxWriteSize);
789 	server->sec_mode = le16_to_cpu(rsp->SecurityMode);
790 	if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode)
791 		cifs_dbg(FYI, "Server returned unexpected security mode 0x%x\n",
792 				server->sec_mode);
793 	server->capabilities = le32_to_cpu(rsp->Capabilities);
794 	/* Internal types */
795 	server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
796 
797 	/*
798 	 * SMB3.0 supports only 1 cipher and doesn't have a encryption neg context
799 	 * Set the cipher type manually.
800 	 */
801 	if (server->dialect == SMB30_PROT_ID && (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
802 		server->cipher_type = SMB2_ENCRYPTION_AES128_CCM;
803 
804 	security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
805 					       (struct smb2_sync_hdr *)rsp);
806 	/*
807 	 * See MS-SMB2 section 2.2.4: if no blob, client picks default which
808 	 * for us will be
809 	 *	ses->sectype = RawNTLMSSP;
810 	 * but for time being this is our only auth choice so doesn't matter.
811 	 * We just found a server which sets blob length to zero expecting raw.
812 	 */
813 	if (blob_length == 0) {
814 		cifs_dbg(FYI, "missing security blob on negprot\n");
815 		server->sec_ntlmssp = true;
816 	}
817 
818 	rc = cifs_enable_signing(server, ses->sign);
819 	if (rc)
820 		goto neg_exit;
821 	if (blob_length) {
822 		rc = decode_negTokenInit(security_blob, blob_length, server);
823 		if (rc == 1)
824 			rc = 0;
825 		else if (rc == 0)
826 			rc = -EIO;
827 	}
828 
829 	if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
830 		if (rsp->NegotiateContextCount)
831 			rc = smb311_decode_neg_context(rsp, server,
832 						       rsp_iov.iov_len);
833 		else
834 			cifs_dbg(VFS, "Missing expected negotiate contexts\n");
835 	}
836 neg_exit:
837 	free_rsp_buf(resp_buftype, rsp);
838 	return rc;
839 }
840 
smb3_validate_negotiate(const unsigned int xid,struct cifs_tcon * tcon)841 int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
842 {
843 	int rc;
844 	struct validate_negotiate_info_req *pneg_inbuf;
845 	struct validate_negotiate_info_rsp *pneg_rsp = NULL;
846 	u32 rsplen;
847 	u32 inbuflen; /* max of 4 dialects */
848 
849 	cifs_dbg(FYI, "validate negotiate\n");
850 
851 	/* In SMB3.11 preauth integrity supersedes validate negotiate */
852 	if (tcon->ses->server->dialect == SMB311_PROT_ID)
853 		return 0;
854 
855 	/*
856 	 * validation ioctl must be signed, so no point sending this if we
857 	 * can not sign it (ie are not known user).  Even if signing is not
858 	 * required (enabled but not negotiated), in those cases we selectively
859 	 * sign just this, the first and only signed request on a connection.
860 	 * Having validation of negotiate info  helps reduce attack vectors.
861 	 */
862 	if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST)
863 		return 0; /* validation requires signing */
864 
865 	if (tcon->ses->user_name == NULL) {
866 		cifs_dbg(FYI, "Can't validate negotiate: null user mount\n");
867 		return 0; /* validation requires signing */
868 	}
869 
870 	if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL)
871 		cifs_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n");
872 
873 	pneg_inbuf = kmalloc(sizeof(*pneg_inbuf), GFP_NOFS);
874 	if (!pneg_inbuf)
875 		return -ENOMEM;
876 
877 	pneg_inbuf->Capabilities =
878 			cpu_to_le32(tcon->ses->server->vals->req_capabilities);
879 	memcpy(pneg_inbuf->Guid, tcon->ses->server->client_guid,
880 					SMB2_CLIENT_GUID_SIZE);
881 
882 	if (tcon->ses->sign)
883 		pneg_inbuf->SecurityMode =
884 			cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
885 	else if (global_secflags & CIFSSEC_MAY_SIGN)
886 		pneg_inbuf->SecurityMode =
887 			cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
888 	else
889 		pneg_inbuf->SecurityMode = 0;
890 
891 
892 	if (strcmp(tcon->ses->server->vals->version_string,
893 		SMB3ANY_VERSION_STRING) == 0) {
894 		pneg_inbuf->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
895 		pneg_inbuf->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
896 		pneg_inbuf->DialectCount = cpu_to_le16(2);
897 		/* structure is big enough for 3 dialects, sending only 2 */
898 		inbuflen = sizeof(*pneg_inbuf) -
899 				sizeof(pneg_inbuf->Dialects[0]);
900 	} else if (strcmp(tcon->ses->server->vals->version_string,
901 		SMBDEFAULT_VERSION_STRING) == 0) {
902 		pneg_inbuf->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
903 		pneg_inbuf->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
904 		pneg_inbuf->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
905 		pneg_inbuf->DialectCount = cpu_to_le16(3);
906 		/* structure is big enough for 3 dialects */
907 		inbuflen = sizeof(*pneg_inbuf);
908 	} else {
909 		/* otherwise specific dialect was requested */
910 		pneg_inbuf->Dialects[0] =
911 			cpu_to_le16(tcon->ses->server->vals->protocol_id);
912 		pneg_inbuf->DialectCount = cpu_to_le16(1);
913 		/* structure is big enough for 3 dialects, sending only 1 */
914 		inbuflen = sizeof(*pneg_inbuf) -
915 				sizeof(pneg_inbuf->Dialects[0]) * 2;
916 	}
917 
918 	rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
919 		FSCTL_VALIDATE_NEGOTIATE_INFO, true /* is_fsctl */,
920 		(char *)pneg_inbuf, inbuflen, (char **)&pneg_rsp, &rsplen);
921 	if (rc == -EOPNOTSUPP) {
922 		/*
923 		 * Old Windows versions or Netapp SMB server can return
924 		 * not supported error. Client should accept it.
925 		 */
926 		cifs_dbg(VFS, "Server does not support validate negotiate\n");
927 		rc = 0;
928 		goto out_free_inbuf;
929 	} else if (rc != 0) {
930 		cifs_dbg(VFS, "validate protocol negotiate failed: %d\n", rc);
931 		rc = -EIO;
932 		goto out_free_inbuf;
933 	}
934 
935 	rc = -EIO;
936 	if (rsplen != sizeof(*pneg_rsp)) {
937 		cifs_dbg(VFS, "invalid protocol negotiate response size: %d\n",
938 			 rsplen);
939 
940 		/* relax check since Mac returns max bufsize allowed on ioctl */
941 		if (rsplen > CIFSMaxBufSize || rsplen < sizeof(*pneg_rsp))
942 			goto out_free_rsp;
943 	}
944 
945 	/* check validate negotiate info response matches what we got earlier */
946 	if (pneg_rsp->Dialect != cpu_to_le16(tcon->ses->server->dialect))
947 		goto vneg_out;
948 
949 	if (pneg_rsp->SecurityMode != cpu_to_le16(tcon->ses->server->sec_mode))
950 		goto vneg_out;
951 
952 	/* do not validate server guid because not saved at negprot time yet */
953 
954 	if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND |
955 	      SMB2_LARGE_FILES) != tcon->ses->server->capabilities)
956 		goto vneg_out;
957 
958 	/* validate negotiate successful */
959 	rc = 0;
960 	cifs_dbg(FYI, "validate negotiate info successful\n");
961 	goto out_free_rsp;
962 
963 vneg_out:
964 	cifs_dbg(VFS, "protocol revalidation - security settings mismatch\n");
965 out_free_rsp:
966 	kfree(pneg_rsp);
967 out_free_inbuf:
968 	kfree(pneg_inbuf);
969 	return rc;
970 }
971 
972 enum securityEnum
smb2_select_sectype(struct TCP_Server_Info * server,enum securityEnum requested)973 smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
974 {
975 	switch (requested) {
976 	case Kerberos:
977 	case RawNTLMSSP:
978 		return requested;
979 	case NTLMv2:
980 		return RawNTLMSSP;
981 	case Unspecified:
982 		if (server->sec_ntlmssp &&
983 			(global_secflags & CIFSSEC_MAY_NTLMSSP))
984 			return RawNTLMSSP;
985 		if ((server->sec_kerberos || server->sec_mskerberos) &&
986 			(global_secflags & CIFSSEC_MAY_KRB5))
987 			return Kerberos;
988 		/* Fallthrough */
989 	default:
990 		return Unspecified;
991 	}
992 }
993 
994 struct SMB2_sess_data {
995 	unsigned int xid;
996 	struct cifs_ses *ses;
997 	struct nls_table *nls_cp;
998 	void (*func)(struct SMB2_sess_data *);
999 	int result;
1000 	u64 previous_session;
1001 
1002 	/* we will send the SMB in three pieces:
1003 	 * a fixed length beginning part, an optional
1004 	 * SPNEGO blob (which can be zero length), and a
1005 	 * last part which will include the strings
1006 	 * and rest of bcc area. This allows us to avoid
1007 	 * a large buffer 17K allocation
1008 	 */
1009 	int buf0_type;
1010 	struct kvec iov[2];
1011 };
1012 
1013 static int
SMB2_sess_alloc_buffer(struct SMB2_sess_data * sess_data)1014 SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
1015 {
1016 	int rc;
1017 	struct cifs_ses *ses = sess_data->ses;
1018 	struct smb2_sess_setup_req *req;
1019 	struct TCP_Server_Info *server = ses->server;
1020 	unsigned int total_len;
1021 
1022 	rc = smb2_plain_req_init(SMB2_SESSION_SETUP, NULL, (void **) &req,
1023 			     &total_len);
1024 	if (rc)
1025 		return rc;
1026 
1027 	/* First session, not a reauthenticate */
1028 	req->sync_hdr.SessionId = 0;
1029 
1030 	/* if reconnect, we need to send previous sess id, otherwise it is 0 */
1031 	req->PreviousSessionId = sess_data->previous_session;
1032 
1033 	req->Flags = 0; /* MBZ */
1034 
1035 	/* enough to enable echos and oplocks and one max size write */
1036 	req->sync_hdr.CreditRequest = cpu_to_le16(130);
1037 
1038 	/* only one of SMB2 signing flags may be set in SMB2 request */
1039 	if (server->sign)
1040 		req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
1041 	else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
1042 		req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
1043 	else
1044 		req->SecurityMode = 0;
1045 
1046 #ifdef CONFIG_CIFS_DFS_UPCALL
1047 	req->Capabilities = cpu_to_le32(SMB2_GLOBAL_CAP_DFS);
1048 #else
1049 	req->Capabilities = 0;
1050 #endif /* DFS_UPCALL */
1051 
1052 	req->Channel = 0; /* MBZ */
1053 
1054 	sess_data->iov[0].iov_base = (char *)req;
1055 	/* 1 for pad */
1056 	sess_data->iov[0].iov_len = total_len - 1;
1057 	/*
1058 	 * This variable will be used to clear the buffer
1059 	 * allocated above in case of any error in the calling function.
1060 	 */
1061 	sess_data->buf0_type = CIFS_SMALL_BUFFER;
1062 
1063 	return 0;
1064 }
1065 
1066 static void
SMB2_sess_free_buffer(struct SMB2_sess_data * sess_data)1067 SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data)
1068 {
1069 	free_rsp_buf(sess_data->buf0_type, sess_data->iov[0].iov_base);
1070 	sess_data->buf0_type = CIFS_NO_BUFFER;
1071 }
1072 
1073 static int
SMB2_sess_sendreceive(struct SMB2_sess_data * sess_data)1074 SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
1075 {
1076 	int rc;
1077 	struct smb_rqst rqst;
1078 	struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
1079 	struct kvec rsp_iov = { NULL, 0 };
1080 
1081 	/* Testing shows that buffer offset must be at location of Buffer[0] */
1082 	req->SecurityBufferOffset =
1083 		cpu_to_le16(sizeof(struct smb2_sess_setup_req) - 1 /* pad */);
1084 	req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len);
1085 
1086 	memset(&rqst, 0, sizeof(struct smb_rqst));
1087 	rqst.rq_iov = sess_data->iov;
1088 	rqst.rq_nvec = 2;
1089 
1090 	/* BB add code to build os and lm fields */
1091 	rc = cifs_send_recv(sess_data->xid, sess_data->ses,
1092 			    &rqst,
1093 			    &sess_data->buf0_type,
1094 			    CIFS_LOG_ERROR | CIFS_NEG_OP, &rsp_iov);
1095 	cifs_small_buf_release(sess_data->iov[0].iov_base);
1096 	memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
1097 
1098 	return rc;
1099 }
1100 
1101 static int
SMB2_sess_establish_session(struct SMB2_sess_data * sess_data)1102 SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)
1103 {
1104 	int rc = 0;
1105 	struct cifs_ses *ses = sess_data->ses;
1106 
1107 	mutex_lock(&ses->server->srv_mutex);
1108 	if (ses->server->ops->generate_signingkey) {
1109 		rc = ses->server->ops->generate_signingkey(ses);
1110 		if (rc) {
1111 			cifs_dbg(FYI,
1112 				"SMB3 session key generation failed\n");
1113 			mutex_unlock(&ses->server->srv_mutex);
1114 			return rc;
1115 		}
1116 	}
1117 	if (!ses->server->session_estab) {
1118 		ses->server->sequence_number = 0x2;
1119 		ses->server->session_estab = true;
1120 	}
1121 	mutex_unlock(&ses->server->srv_mutex);
1122 
1123 	cifs_dbg(FYI, "SMB2/3 session established successfully\n");
1124 	spin_lock(&GlobalMid_Lock);
1125 	ses->status = CifsGood;
1126 	ses->need_reconnect = false;
1127 	spin_unlock(&GlobalMid_Lock);
1128 	return rc;
1129 }
1130 
1131 #ifdef CONFIG_CIFS_UPCALL
1132 static void
SMB2_auth_kerberos(struct SMB2_sess_data * sess_data)1133 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1134 {
1135 	int rc;
1136 	struct cifs_ses *ses = sess_data->ses;
1137 	struct cifs_spnego_msg *msg;
1138 	struct key *spnego_key = NULL;
1139 	struct smb2_sess_setup_rsp *rsp = NULL;
1140 
1141 	rc = SMB2_sess_alloc_buffer(sess_data);
1142 	if (rc)
1143 		goto out;
1144 
1145 	spnego_key = cifs_get_spnego_key(ses);
1146 	if (IS_ERR(spnego_key)) {
1147 		rc = PTR_ERR(spnego_key);
1148 		if (rc == -ENOKEY)
1149 			cifs_dbg(VFS, "Verify user has a krb5 ticket and keyutils is installed\n");
1150 		spnego_key = NULL;
1151 		goto out;
1152 	}
1153 
1154 	msg = spnego_key->payload.data[0];
1155 	/*
1156 	 * check version field to make sure that cifs.upcall is
1157 	 * sending us a response in an expected form
1158 	 */
1159 	if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
1160 		cifs_dbg(VFS,
1161 			  "bad cifs.upcall version. Expected %d got %d",
1162 			  CIFS_SPNEGO_UPCALL_VERSION, msg->version);
1163 		rc = -EKEYREJECTED;
1164 		goto out_put_spnego_key;
1165 	}
1166 
1167 	ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
1168 					 GFP_KERNEL);
1169 	if (!ses->auth_key.response) {
1170 		cifs_dbg(VFS,
1171 			"Kerberos can't allocate (%u bytes) memory",
1172 			msg->sesskey_len);
1173 		rc = -ENOMEM;
1174 		goto out_put_spnego_key;
1175 	}
1176 	ses->auth_key.len = msg->sesskey_len;
1177 
1178 	sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
1179 	sess_data->iov[1].iov_len = msg->secblob_len;
1180 
1181 	rc = SMB2_sess_sendreceive(sess_data);
1182 	if (rc)
1183 		goto out_put_spnego_key;
1184 
1185 	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1186 	ses->Suid = rsp->sync_hdr.SessionId;
1187 
1188 	ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1189 
1190 	rc = SMB2_sess_establish_session(sess_data);
1191 out_put_spnego_key:
1192 	key_invalidate(spnego_key);
1193 	key_put(spnego_key);
1194 out:
1195 	sess_data->result = rc;
1196 	sess_data->func = NULL;
1197 	SMB2_sess_free_buffer(sess_data);
1198 }
1199 #else
1200 static void
SMB2_auth_kerberos(struct SMB2_sess_data * sess_data)1201 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1202 {
1203 	cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
1204 	sess_data->result = -EOPNOTSUPP;
1205 	sess_data->func = NULL;
1206 }
1207 #endif
1208 
1209 static void
1210 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data);
1211 
1212 static void
SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data * sess_data)1213 SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data)
1214 {
1215 	int rc;
1216 	struct cifs_ses *ses = sess_data->ses;
1217 	struct smb2_sess_setup_rsp *rsp = NULL;
1218 	char *ntlmssp_blob = NULL;
1219 	bool use_spnego = false; /* else use raw ntlmssp */
1220 	u16 blob_length = 0;
1221 
1222 	/*
1223 	 * If memory allocation is successful, caller of this function
1224 	 * frees it.
1225 	 */
1226 	ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
1227 	if (!ses->ntlmssp) {
1228 		rc = -ENOMEM;
1229 		goto out_err;
1230 	}
1231 	ses->ntlmssp->sesskey_per_smbsess = true;
1232 
1233 	rc = SMB2_sess_alloc_buffer(sess_data);
1234 	if (rc)
1235 		goto out_err;
1236 
1237 	ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE),
1238 			       GFP_KERNEL);
1239 	if (ntlmssp_blob == NULL) {
1240 		rc = -ENOMEM;
1241 		goto out;
1242 	}
1243 
1244 	build_ntlmssp_negotiate_blob(ntlmssp_blob, ses);
1245 	if (use_spnego) {
1246 		/* BB eventually need to add this */
1247 		cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1248 		rc = -EOPNOTSUPP;
1249 		goto out;
1250 	} else {
1251 		blob_length = sizeof(struct _NEGOTIATE_MESSAGE);
1252 		/* with raw NTLMSSP we don't encapsulate in SPNEGO */
1253 	}
1254 	sess_data->iov[1].iov_base = ntlmssp_blob;
1255 	sess_data->iov[1].iov_len = blob_length;
1256 
1257 	rc = SMB2_sess_sendreceive(sess_data);
1258 	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1259 
1260 	/* If true, rc here is expected and not an error */
1261 	if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1262 		rsp->sync_hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
1263 		rc = 0;
1264 
1265 	if (rc)
1266 		goto out;
1267 
1268 	if (offsetof(struct smb2_sess_setup_rsp, Buffer) !=
1269 			le16_to_cpu(rsp->SecurityBufferOffset)) {
1270 		cifs_dbg(VFS, "Invalid security buffer offset %d\n",
1271 			le16_to_cpu(rsp->SecurityBufferOffset));
1272 		rc = -EIO;
1273 		goto out;
1274 	}
1275 	rc = decode_ntlmssp_challenge(rsp->Buffer,
1276 			le16_to_cpu(rsp->SecurityBufferLength), ses);
1277 	if (rc)
1278 		goto out;
1279 
1280 	cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1281 
1282 
1283 	ses->Suid = rsp->sync_hdr.SessionId;
1284 	ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1285 
1286 out:
1287 	kfree(ntlmssp_blob);
1288 	SMB2_sess_free_buffer(sess_data);
1289 	if (!rc) {
1290 		sess_data->result = 0;
1291 		sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
1292 		return;
1293 	}
1294 out_err:
1295 	kfree(ses->ntlmssp);
1296 	ses->ntlmssp = NULL;
1297 	sess_data->result = rc;
1298 	sess_data->func = NULL;
1299 }
1300 
1301 static void
SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data * sess_data)1302 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
1303 {
1304 	int rc;
1305 	struct cifs_ses *ses = sess_data->ses;
1306 	struct smb2_sess_setup_req *req;
1307 	struct smb2_sess_setup_rsp *rsp = NULL;
1308 	unsigned char *ntlmssp_blob = NULL;
1309 	bool use_spnego = false; /* else use raw ntlmssp */
1310 	u16 blob_length = 0;
1311 
1312 	rc = SMB2_sess_alloc_buffer(sess_data);
1313 	if (rc)
1314 		goto out;
1315 
1316 	req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
1317 	req->sync_hdr.SessionId = ses->Suid;
1318 
1319 	rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses,
1320 					sess_data->nls_cp);
1321 	if (rc) {
1322 		cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
1323 		goto out;
1324 	}
1325 
1326 	if (use_spnego) {
1327 		/* BB eventually need to add this */
1328 		cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1329 		rc = -EOPNOTSUPP;
1330 		goto out;
1331 	}
1332 	sess_data->iov[1].iov_base = ntlmssp_blob;
1333 	sess_data->iov[1].iov_len = blob_length;
1334 
1335 	rc = SMB2_sess_sendreceive(sess_data);
1336 	if (rc)
1337 		goto out;
1338 
1339 	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1340 
1341 	ses->Suid = rsp->sync_hdr.SessionId;
1342 	ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1343 
1344 	rc = SMB2_sess_establish_session(sess_data);
1345 out:
1346 	kfree(ntlmssp_blob);
1347 	SMB2_sess_free_buffer(sess_data);
1348 	kfree(ses->ntlmssp);
1349 	ses->ntlmssp = NULL;
1350 	sess_data->result = rc;
1351 	sess_data->func = NULL;
1352 }
1353 
1354 static int
SMB2_select_sec(struct cifs_ses * ses,struct SMB2_sess_data * sess_data)1355 SMB2_select_sec(struct cifs_ses *ses, struct SMB2_sess_data *sess_data)
1356 {
1357 	int type;
1358 
1359 	type = smb2_select_sectype(ses->server, ses->sectype);
1360 	cifs_dbg(FYI, "sess setup type %d\n", type);
1361 	if (type == Unspecified) {
1362 		cifs_dbg(VFS,
1363 			"Unable to select appropriate authentication method!");
1364 		return -EINVAL;
1365 	}
1366 
1367 	switch (type) {
1368 	case Kerberos:
1369 		sess_data->func = SMB2_auth_kerberos;
1370 		break;
1371 	case RawNTLMSSP:
1372 		sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
1373 		break;
1374 	default:
1375 		cifs_dbg(VFS, "secType %d not supported!\n", type);
1376 		return -EOPNOTSUPP;
1377 	}
1378 
1379 	return 0;
1380 }
1381 
1382 int
SMB2_sess_setup(const unsigned int xid,struct cifs_ses * ses,const struct nls_table * nls_cp)1383 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
1384 		const struct nls_table *nls_cp)
1385 {
1386 	int rc = 0;
1387 	struct TCP_Server_Info *server = ses->server;
1388 	struct SMB2_sess_data *sess_data;
1389 
1390 	cifs_dbg(FYI, "Session Setup\n");
1391 
1392 	if (!server) {
1393 		WARN(1, "%s: server is NULL!\n", __func__);
1394 		return -EIO;
1395 	}
1396 
1397 	sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL);
1398 	if (!sess_data)
1399 		return -ENOMEM;
1400 
1401 	rc = SMB2_select_sec(ses, sess_data);
1402 	if (rc)
1403 		goto out;
1404 	sess_data->xid = xid;
1405 	sess_data->ses = ses;
1406 	sess_data->buf0_type = CIFS_NO_BUFFER;
1407 	sess_data->nls_cp = (struct nls_table *) nls_cp;
1408 	sess_data->previous_session = ses->Suid;
1409 
1410 	/*
1411 	 * Initialize the session hash with the server one.
1412 	 */
1413 	memcpy(ses->preauth_sha_hash, ses->server->preauth_sha_hash,
1414 	       SMB2_PREAUTH_HASH_SIZE);
1415 
1416 	while (sess_data->func)
1417 		sess_data->func(sess_data);
1418 
1419 	if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign))
1420 		cifs_dbg(VFS, "signing requested but authenticated as guest\n");
1421 	rc = sess_data->result;
1422 out:
1423 	kfree(sess_data);
1424 	return rc;
1425 }
1426 
1427 int
SMB2_logoff(const unsigned int xid,struct cifs_ses * ses)1428 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
1429 {
1430 	struct smb_rqst rqst;
1431 	struct smb2_logoff_req *req; /* response is also trivial struct */
1432 	int rc = 0;
1433 	struct TCP_Server_Info *server;
1434 	int flags = 0;
1435 	unsigned int total_len;
1436 	struct kvec iov[1];
1437 	struct kvec rsp_iov;
1438 	int resp_buf_type;
1439 
1440 	cifs_dbg(FYI, "disconnect session %p\n", ses);
1441 
1442 	if (ses && (ses->server))
1443 		server = ses->server;
1444 	else
1445 		return -EIO;
1446 
1447 	/* no need to send SMB logoff if uid already closed due to reconnect */
1448 	if (ses->need_reconnect)
1449 		goto smb2_session_already_dead;
1450 
1451 	rc = smb2_plain_req_init(SMB2_LOGOFF, NULL, (void **) &req, &total_len);
1452 	if (rc)
1453 		return rc;
1454 
1455 	 /* since no tcon, smb2_init can not do this, so do here */
1456 	req->sync_hdr.SessionId = ses->Suid;
1457 
1458 	if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
1459 		flags |= CIFS_TRANSFORM_REQ;
1460 	else if (server->sign)
1461 		req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1462 
1463 	flags |= CIFS_NO_RESP;
1464 
1465 	iov[0].iov_base = (char *)req;
1466 	iov[0].iov_len = total_len;
1467 
1468 	memset(&rqst, 0, sizeof(struct smb_rqst));
1469 	rqst.rq_iov = iov;
1470 	rqst.rq_nvec = 1;
1471 
1472 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buf_type, flags, &rsp_iov);
1473 	cifs_small_buf_release(req);
1474 	/*
1475 	 * No tcon so can't do
1476 	 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
1477 	 */
1478 
1479 smb2_session_already_dead:
1480 	return rc;
1481 }
1482 
cifs_stats_fail_inc(struct cifs_tcon * tcon,uint16_t code)1483 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
1484 {
1485 	cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
1486 }
1487 
1488 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
1489 
1490 /* These are similar values to what Windows uses */
init_copy_chunk_defaults(struct cifs_tcon * tcon)1491 static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
1492 {
1493 	tcon->max_chunks = 256;
1494 	tcon->max_bytes_chunk = 1048576;
1495 	tcon->max_bytes_copy = 16777216;
1496 }
1497 
1498 int
SMB2_tcon(const unsigned int xid,struct cifs_ses * ses,const char * tree,struct cifs_tcon * tcon,const struct nls_table * cp)1499 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
1500 	  struct cifs_tcon *tcon, const struct nls_table *cp)
1501 {
1502 	struct smb_rqst rqst;
1503 	struct smb2_tree_connect_req *req;
1504 	struct smb2_tree_connect_rsp *rsp = NULL;
1505 	struct kvec iov[2];
1506 	struct kvec rsp_iov = { NULL, 0 };
1507 	int rc = 0;
1508 	int resp_buftype;
1509 	int unc_path_len;
1510 	__le16 *unc_path = NULL;
1511 	int flags = 0;
1512 	unsigned int total_len;
1513 
1514 	cifs_dbg(FYI, "TCON\n");
1515 
1516 	if (!(ses->server) || !tree)
1517 		return -EIO;
1518 
1519 	unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
1520 	if (unc_path == NULL)
1521 		return -ENOMEM;
1522 
1523 	unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
1524 	unc_path_len *= 2;
1525 	if (unc_path_len < 2) {
1526 		kfree(unc_path);
1527 		return -EINVAL;
1528 	}
1529 
1530 	/* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
1531 	tcon->tid = 0;
1532 
1533 	rc = smb2_plain_req_init(SMB2_TREE_CONNECT, tcon, (void **) &req,
1534 			     &total_len);
1535 	if (rc) {
1536 		kfree(unc_path);
1537 		return rc;
1538 	}
1539 
1540 	if (smb3_encryption_required(tcon))
1541 		flags |= CIFS_TRANSFORM_REQ;
1542 
1543 	iov[0].iov_base = (char *)req;
1544 	/* 1 for pad */
1545 	iov[0].iov_len = total_len - 1;
1546 
1547 	/* Testing shows that buffer offset must be at location of Buffer[0] */
1548 	req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
1549 			- 1 /* pad */);
1550 	req->PathLength = cpu_to_le16(unc_path_len - 2);
1551 	iov[1].iov_base = unc_path;
1552 	iov[1].iov_len = unc_path_len;
1553 
1554 	/*
1555 	 * 3.11 tcon req must be signed if not encrypted. See MS-SMB2 3.2.4.1.1
1556 	 * unless it is guest or anonymous user. See MS-SMB2 3.2.5.3.1
1557 	 * (Samba servers don't always set the flag so also check if null user)
1558 	 */
1559 	if ((ses->server->dialect == SMB311_PROT_ID) &&
1560 	    !smb3_encryption_required(tcon) &&
1561 	    !(ses->session_flags &
1562 		    (SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL)) &&
1563 	    ((ses->user_name != NULL) || (ses->sectype == Kerberos)))
1564 		req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1565 
1566 	memset(&rqst, 0, sizeof(struct smb_rqst));
1567 	rqst.rq_iov = iov;
1568 	rqst.rq_nvec = 2;
1569 
1570 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
1571 	cifs_small_buf_release(req);
1572 	rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
1573 
1574 	if (rc != 0) {
1575 		if (tcon) {
1576 			cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
1577 			tcon->need_reconnect = true;
1578 		}
1579 		goto tcon_error_exit;
1580 	}
1581 
1582 	switch (rsp->ShareType) {
1583 	case SMB2_SHARE_TYPE_DISK:
1584 		cifs_dbg(FYI, "connection to disk share\n");
1585 		break;
1586 	case SMB2_SHARE_TYPE_PIPE:
1587 		tcon->pipe = true;
1588 		cifs_dbg(FYI, "connection to pipe share\n");
1589 		break;
1590 	case SMB2_SHARE_TYPE_PRINT:
1591 		tcon->print = true;
1592 		cifs_dbg(FYI, "connection to printer\n");
1593 		break;
1594 	default:
1595 		cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
1596 		rc = -EOPNOTSUPP;
1597 		goto tcon_error_exit;
1598 	}
1599 
1600 	tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
1601 	tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
1602 	tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1603 	tcon->tidStatus = CifsGood;
1604 	tcon->need_reconnect = false;
1605 	tcon->tid = rsp->sync_hdr.TreeId;
1606 	strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
1607 
1608 	if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
1609 	    ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
1610 		cifs_dbg(VFS, "DFS capability contradicts DFS flag\n");
1611 
1612 	if (tcon->seal &&
1613 	    !(tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1614 		cifs_dbg(VFS, "Encryption is requested but not supported\n");
1615 
1616 	init_copy_chunk_defaults(tcon);
1617 	if (tcon->ses->server->ops->validate_negotiate)
1618 		rc = tcon->ses->server->ops->validate_negotiate(xid, tcon);
1619 tcon_exit:
1620 	free_rsp_buf(resp_buftype, rsp);
1621 	kfree(unc_path);
1622 	return rc;
1623 
1624 tcon_error_exit:
1625 	if (rsp && rsp->sync_hdr.Status == STATUS_BAD_NETWORK_NAME) {
1626 		cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
1627 	}
1628 	goto tcon_exit;
1629 }
1630 
1631 int
SMB2_tdis(const unsigned int xid,struct cifs_tcon * tcon)1632 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
1633 {
1634 	struct smb_rqst rqst;
1635 	struct smb2_tree_disconnect_req *req; /* response is trivial */
1636 	int rc = 0;
1637 	struct cifs_ses *ses = tcon->ses;
1638 	int flags = 0;
1639 	unsigned int total_len;
1640 	struct kvec iov[1];
1641 	struct kvec rsp_iov;
1642 	int resp_buf_type;
1643 
1644 	cifs_dbg(FYI, "Tree Disconnect\n");
1645 
1646 	if (!ses || !(ses->server))
1647 		return -EIO;
1648 
1649 	if ((tcon->need_reconnect) || (tcon->ses->need_reconnect))
1650 		return 0;
1651 
1652 	rc = smb2_plain_req_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req,
1653 			     &total_len);
1654 	if (rc)
1655 		return rc;
1656 
1657 	if (smb3_encryption_required(tcon))
1658 		flags |= CIFS_TRANSFORM_REQ;
1659 
1660 	flags |= CIFS_NO_RESP;
1661 
1662 	iov[0].iov_base = (char *)req;
1663 	iov[0].iov_len = total_len;
1664 
1665 	memset(&rqst, 0, sizeof(struct smb_rqst));
1666 	rqst.rq_iov = iov;
1667 	rqst.rq_nvec = 1;
1668 
1669 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buf_type, flags, &rsp_iov);
1670 	cifs_small_buf_release(req);
1671 	if (rc)
1672 		cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
1673 
1674 	return rc;
1675 }
1676 
1677 
1678 static struct create_durable *
create_durable_buf(void)1679 create_durable_buf(void)
1680 {
1681 	struct create_durable *buf;
1682 
1683 	buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1684 	if (!buf)
1685 		return NULL;
1686 
1687 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
1688 					(struct create_durable, Data));
1689 	buf->ccontext.DataLength = cpu_to_le32(16);
1690 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
1691 				(struct create_durable, Name));
1692 	buf->ccontext.NameLength = cpu_to_le16(4);
1693 	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
1694 	buf->Name[0] = 'D';
1695 	buf->Name[1] = 'H';
1696 	buf->Name[2] = 'n';
1697 	buf->Name[3] = 'Q';
1698 	return buf;
1699 }
1700 
1701 static struct create_durable *
create_reconnect_durable_buf(struct cifs_fid * fid)1702 create_reconnect_durable_buf(struct cifs_fid *fid)
1703 {
1704 	struct create_durable *buf;
1705 
1706 	buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1707 	if (!buf)
1708 		return NULL;
1709 
1710 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
1711 					(struct create_durable, Data));
1712 	buf->ccontext.DataLength = cpu_to_le32(16);
1713 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
1714 				(struct create_durable, Name));
1715 	buf->ccontext.NameLength = cpu_to_le16(4);
1716 	buf->Data.Fid.PersistentFileId = fid->persistent_fid;
1717 	buf->Data.Fid.VolatileFileId = fid->volatile_fid;
1718 	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
1719 	buf->Name[0] = 'D';
1720 	buf->Name[1] = 'H';
1721 	buf->Name[2] = 'n';
1722 	buf->Name[3] = 'C';
1723 	return buf;
1724 }
1725 
1726 static __u8
parse_lease_state(struct TCP_Server_Info * server,struct smb2_create_rsp * rsp,unsigned int * epoch,char * lease_key)1727 parse_lease_state(struct TCP_Server_Info *server, struct smb2_create_rsp *rsp,
1728 		  unsigned int *epoch, char *lease_key)
1729 {
1730 	char *data_offset;
1731 	struct create_context *cc;
1732 	unsigned int next;
1733 	unsigned int remaining;
1734 	char *name;
1735 
1736 	data_offset = (char *)rsp + le32_to_cpu(rsp->CreateContextsOffset);
1737 	remaining = le32_to_cpu(rsp->CreateContextsLength);
1738 	cc = (struct create_context *)data_offset;
1739 	while (remaining >= sizeof(struct create_context)) {
1740 		name = le16_to_cpu(cc->NameOffset) + (char *)cc;
1741 		if (le16_to_cpu(cc->NameLength) == 4 &&
1742 		    strncmp(name, "RqLs", 4) == 0)
1743 			return server->ops->parse_lease_buf(cc, epoch,
1744 							    lease_key);
1745 
1746 		next = le32_to_cpu(cc->Next);
1747 		if (!next)
1748 			break;
1749 		remaining -= next;
1750 		cc = (struct create_context *)((char *)cc + next);
1751 	}
1752 
1753 	return 0;
1754 }
1755 
1756 static int
add_lease_context(struct TCP_Server_Info * server,struct kvec * iov,unsigned int * num_iovec,u8 * lease_key,__u8 * oplock)1757 add_lease_context(struct TCP_Server_Info *server, struct kvec *iov,
1758 		  unsigned int *num_iovec, u8 *lease_key, __u8 *oplock)
1759 {
1760 	struct smb2_create_req *req = iov[0].iov_base;
1761 	unsigned int num = *num_iovec;
1762 
1763 	iov[num].iov_base = server->ops->create_lease_buf(lease_key, *oplock);
1764 	if (iov[num].iov_base == NULL)
1765 		return -ENOMEM;
1766 	iov[num].iov_len = server->vals->create_lease_size;
1767 	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
1768 	if (!req->CreateContextsOffset)
1769 		req->CreateContextsOffset = cpu_to_le32(
1770 				sizeof(struct smb2_create_req) +
1771 				iov[num - 1].iov_len);
1772 	le32_add_cpu(&req->CreateContextsLength,
1773 		     server->vals->create_lease_size);
1774 	*num_iovec = num + 1;
1775 	return 0;
1776 }
1777 
1778 static struct create_durable_v2 *
create_durable_v2_buf(struct cifs_fid * pfid)1779 create_durable_v2_buf(struct cifs_fid *pfid)
1780 {
1781 	struct create_durable_v2 *buf;
1782 
1783 	buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
1784 	if (!buf)
1785 		return NULL;
1786 
1787 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
1788 					(struct create_durable_v2, dcontext));
1789 	buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
1790 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
1791 				(struct create_durable_v2, Name));
1792 	buf->ccontext.NameLength = cpu_to_le16(4);
1793 
1794 	buf->dcontext.Timeout = 0; /* Should this be configurable by workload */
1795 	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
1796 	generate_random_uuid(buf->dcontext.CreateGuid);
1797 	memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
1798 
1799 	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
1800 	buf->Name[0] = 'D';
1801 	buf->Name[1] = 'H';
1802 	buf->Name[2] = '2';
1803 	buf->Name[3] = 'Q';
1804 	return buf;
1805 }
1806 
1807 static struct create_durable_handle_reconnect_v2 *
create_reconnect_durable_v2_buf(struct cifs_fid * fid)1808 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
1809 {
1810 	struct create_durable_handle_reconnect_v2 *buf;
1811 
1812 	buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
1813 			GFP_KERNEL);
1814 	if (!buf)
1815 		return NULL;
1816 
1817 	buf->ccontext.DataOffset =
1818 		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
1819 				     dcontext));
1820 	buf->ccontext.DataLength =
1821 		cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
1822 	buf->ccontext.NameOffset =
1823 		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
1824 			    Name));
1825 	buf->ccontext.NameLength = cpu_to_le16(4);
1826 
1827 	buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
1828 	buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
1829 	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
1830 	memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
1831 
1832 	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
1833 	buf->Name[0] = 'D';
1834 	buf->Name[1] = 'H';
1835 	buf->Name[2] = '2';
1836 	buf->Name[3] = 'C';
1837 	return buf;
1838 }
1839 
1840 static int
add_durable_v2_context(struct kvec * iov,unsigned int * num_iovec,struct cifs_open_parms * oparms)1841 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
1842 		    struct cifs_open_parms *oparms)
1843 {
1844 	struct smb2_create_req *req = iov[0].iov_base;
1845 	unsigned int num = *num_iovec;
1846 
1847 	iov[num].iov_base = create_durable_v2_buf(oparms->fid);
1848 	if (iov[num].iov_base == NULL)
1849 		return -ENOMEM;
1850 	iov[num].iov_len = sizeof(struct create_durable_v2);
1851 	if (!req->CreateContextsOffset)
1852 		req->CreateContextsOffset =
1853 			cpu_to_le32(sizeof(struct smb2_create_req) +
1854 								iov[1].iov_len);
1855 	le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2));
1856 	*num_iovec = num + 1;
1857 	return 0;
1858 }
1859 
1860 static int
add_durable_reconnect_v2_context(struct kvec * iov,unsigned int * num_iovec,struct cifs_open_parms * oparms)1861 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
1862 		    struct cifs_open_parms *oparms)
1863 {
1864 	struct smb2_create_req *req = iov[0].iov_base;
1865 	unsigned int num = *num_iovec;
1866 
1867 	/* indicate that we don't need to relock the file */
1868 	oparms->reconnect = false;
1869 
1870 	iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
1871 	if (iov[num].iov_base == NULL)
1872 		return -ENOMEM;
1873 	iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
1874 	if (!req->CreateContextsOffset)
1875 		req->CreateContextsOffset =
1876 			cpu_to_le32(sizeof(struct smb2_create_req) +
1877 								iov[1].iov_len);
1878 	le32_add_cpu(&req->CreateContextsLength,
1879 			sizeof(struct create_durable_handle_reconnect_v2));
1880 	*num_iovec = num + 1;
1881 	return 0;
1882 }
1883 
1884 static int
add_durable_context(struct kvec * iov,unsigned int * num_iovec,struct cifs_open_parms * oparms,bool use_persistent)1885 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
1886 		    struct cifs_open_parms *oparms, bool use_persistent)
1887 {
1888 	struct smb2_create_req *req = iov[0].iov_base;
1889 	unsigned int num = *num_iovec;
1890 
1891 	if (use_persistent) {
1892 		if (oparms->reconnect)
1893 			return add_durable_reconnect_v2_context(iov, num_iovec,
1894 								oparms);
1895 		else
1896 			return add_durable_v2_context(iov, num_iovec, oparms);
1897 	}
1898 
1899 	if (oparms->reconnect) {
1900 		iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
1901 		/* indicate that we don't need to relock the file */
1902 		oparms->reconnect = false;
1903 	} else
1904 		iov[num].iov_base = create_durable_buf();
1905 	if (iov[num].iov_base == NULL)
1906 		return -ENOMEM;
1907 	iov[num].iov_len = sizeof(struct create_durable);
1908 	if (!req->CreateContextsOffset)
1909 		req->CreateContextsOffset =
1910 			cpu_to_le32(sizeof(struct smb2_create_req) +
1911 								iov[1].iov_len);
1912 	le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable));
1913 	*num_iovec = num + 1;
1914 	return 0;
1915 }
1916 
1917 /* See MS-SMB2 2.2.13.2.7 */
1918 static struct crt_twarp_ctxt *
create_twarp_buf(__u64 timewarp)1919 create_twarp_buf(__u64 timewarp)
1920 {
1921 	struct crt_twarp_ctxt *buf;
1922 
1923 	buf = kzalloc(sizeof(struct crt_twarp_ctxt), GFP_KERNEL);
1924 	if (!buf)
1925 		return NULL;
1926 
1927 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
1928 					(struct crt_twarp_ctxt, Timestamp));
1929 	buf->ccontext.DataLength = cpu_to_le32(8);
1930 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
1931 				(struct crt_twarp_ctxt, Name));
1932 	buf->ccontext.NameLength = cpu_to_le16(4);
1933 	/* SMB2_CREATE_TIMEWARP_TOKEN is "TWrp" */
1934 	buf->Name[0] = 'T';
1935 	buf->Name[1] = 'W';
1936 	buf->Name[2] = 'r';
1937 	buf->Name[3] = 'p';
1938 	buf->Timestamp = cpu_to_le64(timewarp);
1939 	return buf;
1940 }
1941 
1942 /* See MS-SMB2 2.2.13.2.7 */
1943 static int
add_twarp_context(struct kvec * iov,unsigned int * num_iovec,__u64 timewarp)1944 add_twarp_context(struct kvec *iov, unsigned int *num_iovec, __u64 timewarp)
1945 {
1946 	struct smb2_create_req *req = iov[0].iov_base;
1947 	unsigned int num = *num_iovec;
1948 
1949 	iov[num].iov_base = create_twarp_buf(timewarp);
1950 	if (iov[num].iov_base == NULL)
1951 		return -ENOMEM;
1952 	iov[num].iov_len = sizeof(struct crt_twarp_ctxt);
1953 	if (!req->CreateContextsOffset)
1954 		req->CreateContextsOffset = cpu_to_le32(
1955 				sizeof(struct smb2_create_req) +
1956 				iov[num - 1].iov_len);
1957 	le32_add_cpu(&req->CreateContextsLength, sizeof(struct crt_twarp_ctxt));
1958 	*num_iovec = num + 1;
1959 	return 0;
1960 }
1961 
1962 static int
alloc_path_with_tree_prefix(__le16 ** out_path,int * out_size,int * out_len,const char * treename,const __le16 * path)1963 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
1964 			    const char *treename, const __le16 *path)
1965 {
1966 	int treename_len, path_len;
1967 	struct nls_table *cp;
1968 	const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
1969 
1970 	/*
1971 	 * skip leading "\\"
1972 	 */
1973 	treename_len = strlen(treename);
1974 	if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
1975 		return -EINVAL;
1976 
1977 	treename += 2;
1978 	treename_len -= 2;
1979 
1980 	path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
1981 
1982 	/*
1983 	 * make room for one path separator between the treename and
1984 	 * path
1985 	 */
1986 	*out_len = treename_len + 1 + path_len;
1987 
1988 	/*
1989 	 * final path needs to be null-terminated UTF16 with a
1990 	 * size aligned to 8
1991 	 */
1992 
1993 	*out_size = roundup((*out_len+1)*2, 8);
1994 	*out_path = kzalloc(*out_size, GFP_KERNEL);
1995 	if (!*out_path)
1996 		return -ENOMEM;
1997 
1998 	cp = load_nls_default();
1999 	cifs_strtoUTF16(*out_path, treename, treename_len, cp);
2000 	UniStrcat(*out_path, sep);
2001 	UniStrcat(*out_path, path);
2002 	unload_nls(cp);
2003 
2004 	return 0;
2005 }
2006 
smb311_posix_mkdir(const unsigned int xid,struct inode * inode,umode_t mode,struct cifs_tcon * tcon,const char * full_path,struct cifs_sb_info * cifs_sb)2007 int smb311_posix_mkdir(const unsigned int xid, struct inode *inode,
2008 			       umode_t mode, struct cifs_tcon *tcon,
2009 			       const char *full_path,
2010 			       struct cifs_sb_info *cifs_sb)
2011 {
2012 	struct smb_rqst rqst;
2013 	struct smb2_create_req *req;
2014 	struct smb2_create_rsp *rsp = NULL;
2015 	struct TCP_Server_Info *server;
2016 	struct cifs_ses *ses = tcon->ses;
2017 	struct kvec iov[3]; /* make sure at least one for each open context */
2018 	struct kvec rsp_iov = {NULL, 0};
2019 	int resp_buftype;
2020 	int uni_path_len;
2021 	__le16 *copy_path = NULL;
2022 	int copy_size;
2023 	int rc = 0;
2024 	unsigned int n_iov = 2;
2025 	__u32 file_attributes = 0;
2026 	char *pc_buf = NULL;
2027 	int flags = 0;
2028 	unsigned int total_len;
2029 	__le16 *utf16_path = NULL;
2030 
2031 	cifs_dbg(FYI, "mkdir\n");
2032 
2033 	/* resource #1: path allocation */
2034 	utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
2035 	if (!utf16_path)
2036 		return -ENOMEM;
2037 
2038 	if (ses && (ses->server))
2039 		server = ses->server;
2040 	else {
2041 		rc = -EIO;
2042 		goto err_free_path;
2043 	}
2044 
2045 	/* resource #2: request */
2046 	rc = smb2_plain_req_init(SMB2_CREATE, tcon, (void **) &req, &total_len);
2047 	if (rc)
2048 		goto err_free_path;
2049 
2050 
2051 	if (smb3_encryption_required(tcon))
2052 		flags |= CIFS_TRANSFORM_REQ;
2053 
2054 	req->ImpersonationLevel = IL_IMPERSONATION;
2055 	req->DesiredAccess = cpu_to_le32(FILE_WRITE_ATTRIBUTES);
2056 	/* File attributes ignored on open (used in create though) */
2057 	req->FileAttributes = cpu_to_le32(file_attributes);
2058 	req->ShareAccess = FILE_SHARE_ALL_LE;
2059 	req->CreateDisposition = cpu_to_le32(FILE_CREATE);
2060 	req->CreateOptions = cpu_to_le32(CREATE_NOT_FILE);
2061 
2062 	iov[0].iov_base = (char *)req;
2063 	/* -1 since last byte is buf[0] which is sent below (path) */
2064 	iov[0].iov_len = total_len - 1;
2065 
2066 	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2067 
2068 	/* [MS-SMB2] 2.2.13 NameOffset:
2069 	 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2070 	 * the SMB2 header, the file name includes a prefix that will
2071 	 * be processed during DFS name normalization as specified in
2072 	 * section 3.3.5.9. Otherwise, the file name is relative to
2073 	 * the share that is identified by the TreeId in the SMB2
2074 	 * header.
2075 	 */
2076 	if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2077 		int name_len;
2078 
2079 		req->sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2080 		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2081 						 &name_len,
2082 						 tcon->treeName, utf16_path);
2083 		if (rc)
2084 			goto err_free_req;
2085 
2086 		req->NameLength = cpu_to_le16(name_len * 2);
2087 		uni_path_len = copy_size;
2088 		/* free before overwriting resource */
2089 		kfree(utf16_path);
2090 		utf16_path = copy_path;
2091 	} else {
2092 		uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2;
2093 		/* MUST set path len (NameLength) to 0 opening root of share */
2094 		req->NameLength = cpu_to_le16(uni_path_len - 2);
2095 		if (uni_path_len % 8 != 0) {
2096 			copy_size = roundup(uni_path_len, 8);
2097 			copy_path = kzalloc(copy_size, GFP_KERNEL);
2098 			if (!copy_path) {
2099 				rc = -ENOMEM;
2100 				goto err_free_req;
2101 			}
2102 			memcpy((char *)copy_path, (const char *)utf16_path,
2103 			       uni_path_len);
2104 			uni_path_len = copy_size;
2105 			/* free before overwriting resource */
2106 			kfree(utf16_path);
2107 			utf16_path = copy_path;
2108 		}
2109 	}
2110 
2111 	iov[1].iov_len = uni_path_len;
2112 	iov[1].iov_base = utf16_path;
2113 	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2114 
2115 	if (tcon->posix_extensions) {
2116 		/* resource #3: posix buf */
2117 		rc = add_posix_context(iov, &n_iov, mode);
2118 		if (rc)
2119 			goto err_free_req;
2120 		pc_buf = iov[n_iov-1].iov_base;
2121 	}
2122 
2123 
2124 	memset(&rqst, 0, sizeof(struct smb_rqst));
2125 	rqst.rq_iov = iov;
2126 	rqst.rq_nvec = n_iov;
2127 
2128 	/* resource #4: response buffer */
2129 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
2130 	if (rc) {
2131 		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2132 		trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid,
2133 					   CREATE_NOT_FILE,
2134 					   FILE_WRITE_ATTRIBUTES, rc);
2135 		goto err_free_rsp_buf;
2136 	}
2137 
2138 	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2139 	trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid,
2140 				    ses->Suid, CREATE_NOT_FILE,
2141 				    FILE_WRITE_ATTRIBUTES);
2142 
2143 	SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
2144 
2145 	/* Eventually save off posix specific response info and timestaps */
2146 
2147 err_free_rsp_buf:
2148 	free_rsp_buf(resp_buftype, rsp);
2149 	kfree(pc_buf);
2150 err_free_req:
2151 	cifs_small_buf_release(req);
2152 err_free_path:
2153 	kfree(utf16_path);
2154 	return rc;
2155 }
2156 
2157 int
SMB2_open_init(struct cifs_tcon * tcon,struct smb_rqst * rqst,__u8 * oplock,struct cifs_open_parms * oparms,__le16 * path)2158 SMB2_open_init(struct cifs_tcon *tcon, struct smb_rqst *rqst, __u8 *oplock,
2159 	       struct cifs_open_parms *oparms, __le16 *path)
2160 {
2161 	struct TCP_Server_Info *server = tcon->ses->server;
2162 	struct smb2_create_req *req;
2163 	unsigned int n_iov = 2;
2164 	__u32 file_attributes = 0;
2165 	int copy_size;
2166 	int uni_path_len;
2167 	unsigned int total_len;
2168 	struct kvec *iov = rqst->rq_iov;
2169 	__le16 *copy_path;
2170 	int rc;
2171 
2172 	rc = smb2_plain_req_init(SMB2_CREATE, tcon, (void **) &req, &total_len);
2173 	if (rc)
2174 		return rc;
2175 
2176 	iov[0].iov_base = (char *)req;
2177 	/* -1 since last byte is buf[0] which is sent below (path) */
2178 	iov[0].iov_len = total_len - 1;
2179 
2180 	if (oparms->create_options & CREATE_OPTION_READONLY)
2181 		file_attributes |= ATTR_READONLY;
2182 	if (oparms->create_options & CREATE_OPTION_SPECIAL)
2183 		file_attributes |= ATTR_SYSTEM;
2184 
2185 	req->ImpersonationLevel = IL_IMPERSONATION;
2186 	req->DesiredAccess = cpu_to_le32(oparms->desired_access);
2187 	/* File attributes ignored on open (used in create though) */
2188 	req->FileAttributes = cpu_to_le32(file_attributes);
2189 	req->ShareAccess = FILE_SHARE_ALL_LE;
2190 	req->CreateDisposition = cpu_to_le32(oparms->disposition);
2191 	req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
2192 	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2193 
2194 	/* [MS-SMB2] 2.2.13 NameOffset:
2195 	 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2196 	 * the SMB2 header, the file name includes a prefix that will
2197 	 * be processed during DFS name normalization as specified in
2198 	 * section 3.3.5.9. Otherwise, the file name is relative to
2199 	 * the share that is identified by the TreeId in the SMB2
2200 	 * header.
2201 	 */
2202 	if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2203 		int name_len;
2204 
2205 		req->sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2206 		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2207 						 &name_len,
2208 						 tcon->treeName, path);
2209 		if (rc)
2210 			return rc;
2211 		req->NameLength = cpu_to_le16(name_len * 2);
2212 		uni_path_len = copy_size;
2213 		path = copy_path;
2214 	} else {
2215 		uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
2216 		/* MUST set path len (NameLength) to 0 opening root of share */
2217 		req->NameLength = cpu_to_le16(uni_path_len - 2);
2218 		copy_size = uni_path_len;
2219 		if (copy_size % 8 != 0)
2220 			copy_size = roundup(copy_size, 8);
2221 		copy_path = kzalloc(copy_size, GFP_KERNEL);
2222 		if (!copy_path)
2223 			return -ENOMEM;
2224 		memcpy((char *)copy_path, (const char *)path,
2225 		       uni_path_len);
2226 		uni_path_len = copy_size;
2227 		path = copy_path;
2228 	}
2229 
2230 	iov[1].iov_len = uni_path_len;
2231 	iov[1].iov_base = path;
2232 
2233 	if ((!server->oplocks) || (tcon->no_lease))
2234 		*oplock = SMB2_OPLOCK_LEVEL_NONE;
2235 
2236 	if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
2237 	    *oplock == SMB2_OPLOCK_LEVEL_NONE)
2238 		req->RequestedOplockLevel = *oplock;
2239 	else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
2240 		  (oparms->create_options & CREATE_NOT_FILE))
2241 		req->RequestedOplockLevel = *oplock; /* no srv lease support */
2242 	else {
2243 		rc = add_lease_context(server, iov, &n_iov,
2244 				       oparms->fid->lease_key, oplock);
2245 		if (rc)
2246 			return rc;
2247 	}
2248 
2249 	if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
2250 		/* need to set Next field of lease context if we request it */
2251 		if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
2252 			struct create_context *ccontext =
2253 			    (struct create_context *)iov[n_iov-1].iov_base;
2254 			ccontext->Next =
2255 				cpu_to_le32(server->vals->create_lease_size);
2256 		}
2257 
2258 		rc = add_durable_context(iov, &n_iov, oparms,
2259 					tcon->use_persistent);
2260 		if (rc)
2261 			return rc;
2262 	}
2263 
2264 	if (tcon->posix_extensions) {
2265 		if (n_iov > 2) {
2266 			struct create_context *ccontext =
2267 			    (struct create_context *)iov[n_iov-1].iov_base;
2268 			ccontext->Next =
2269 				cpu_to_le32(iov[n_iov-1].iov_len);
2270 		}
2271 
2272 		rc = add_posix_context(iov, &n_iov, oparms->mode);
2273 		if (rc)
2274 			return rc;
2275 	}
2276 
2277 	if (tcon->snapshot_time) {
2278 		cifs_dbg(FYI, "adding snapshot context\n");
2279 		if (n_iov > 2) {
2280 			struct create_context *ccontext =
2281 			    (struct create_context *)iov[n_iov-1].iov_base;
2282 			ccontext->Next =
2283 				cpu_to_le32(iov[n_iov-1].iov_len);
2284 		}
2285 
2286 		rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time);
2287 		if (rc)
2288 			return rc;
2289 	}
2290 
2291 
2292 	rqst->rq_nvec = n_iov;
2293 	return 0;
2294 }
2295 
2296 /* rq_iov[0] is the request and is released by cifs_small_buf_release().
2297  * All other vectors are freed by kfree().
2298  */
2299 void
SMB2_open_free(struct smb_rqst * rqst)2300 SMB2_open_free(struct smb_rqst *rqst)
2301 {
2302 	int i;
2303 
2304 	if (rqst && rqst->rq_iov) {
2305 		cifs_small_buf_release(rqst->rq_iov[0].iov_base);
2306 		for (i = 1; i < rqst->rq_nvec; i++)
2307 			if (rqst->rq_iov[i].iov_base != smb2_padding)
2308 				kfree(rqst->rq_iov[i].iov_base);
2309 	}
2310 }
2311 
2312 int
SMB2_open(const unsigned int xid,struct cifs_open_parms * oparms,__le16 * path,__u8 * oplock,struct smb2_file_all_info * buf,struct kvec * err_iov,int * buftype)2313 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
2314 	  __u8 *oplock, struct smb2_file_all_info *buf,
2315 	  struct kvec *err_iov, int *buftype)
2316 {
2317 	struct smb_rqst rqst;
2318 	struct smb2_create_rsp *rsp = NULL;
2319 	struct TCP_Server_Info *server;
2320 	struct cifs_tcon *tcon = oparms->tcon;
2321 	struct cifs_ses *ses = tcon->ses;
2322 	struct kvec iov[SMB2_CREATE_IOV_SIZE];
2323 	struct kvec rsp_iov = {NULL, 0};
2324 	int resp_buftype = CIFS_NO_BUFFER;
2325 	int rc = 0;
2326 	int flags = 0;
2327 
2328 	cifs_dbg(FYI, "create/open\n");
2329 	if (ses && (ses->server))
2330 		server = ses->server;
2331 	else
2332 		return -EIO;
2333 
2334 	if (smb3_encryption_required(tcon))
2335 		flags |= CIFS_TRANSFORM_REQ;
2336 
2337 	memset(&rqst, 0, sizeof(struct smb_rqst));
2338 	memset(&iov, 0, sizeof(iov));
2339 	rqst.rq_iov = iov;
2340 	rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
2341 
2342 	rc = SMB2_open_init(tcon, &rqst, oplock, oparms, path);
2343 	if (rc)
2344 		goto creat_exit;
2345 
2346 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags,
2347 			    &rsp_iov);
2348 	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2349 
2350 	if (rc != 0) {
2351 		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2352 		if (err_iov && rsp) {
2353 			*err_iov = rsp_iov;
2354 			*buftype = resp_buftype;
2355 			resp_buftype = CIFS_NO_BUFFER;
2356 			rsp = NULL;
2357 		}
2358 		trace_smb3_open_err(xid, tcon->tid, ses->Suid,
2359 				    oparms->create_options, oparms->desired_access, rc);
2360 		goto creat_exit;
2361 	} else
2362 		trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid,
2363 				     ses->Suid, oparms->create_options,
2364 				     oparms->desired_access);
2365 
2366 	oparms->fid->persistent_fid = rsp->PersistentFileId;
2367 	oparms->fid->volatile_fid = rsp->VolatileFileId;
2368 
2369 	if (buf) {
2370 		memcpy(buf, &rsp->CreationTime, 32);
2371 		buf->AllocationSize = rsp->AllocationSize;
2372 		buf->EndOfFile = rsp->EndofFile;
2373 		buf->Attributes = rsp->FileAttributes;
2374 		buf->NumberOfLinks = cpu_to_le32(1);
2375 		buf->DeletePending = 0;
2376 	}
2377 
2378 	if (rsp->OplockLevel == SMB2_OPLOCK_LEVEL_LEASE)
2379 		*oplock = parse_lease_state(server, rsp, &oparms->fid->epoch,
2380 					    oparms->fid->lease_key);
2381 	else
2382 		*oplock = rsp->OplockLevel;
2383 creat_exit:
2384 	SMB2_open_free(&rqst);
2385 	free_rsp_buf(resp_buftype, rsp);
2386 	return rc;
2387 }
2388 
2389 /*
2390  *	SMB2 IOCTL is used for both IOCTLs and FSCTLs
2391  */
2392 int
SMB2_ioctl(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u32 opcode,bool is_fsctl,char * in_data,u32 indatalen,char ** out_data,u32 * plen)2393 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
2394 	   u64 volatile_fid, u32 opcode, bool is_fsctl,
2395 	   char *in_data, u32 indatalen,
2396 	   char **out_data, u32 *plen /* returned data len */)
2397 {
2398 	struct smb_rqst rqst;
2399 	struct smb2_ioctl_req *req;
2400 	struct smb2_ioctl_rsp *rsp;
2401 	struct cifs_ses *ses;
2402 	struct kvec iov[2];
2403 	struct kvec rsp_iov;
2404 	int resp_buftype;
2405 	int n_iov;
2406 	int rc = 0;
2407 	int flags = 0;
2408 	unsigned int total_len;
2409 
2410 	cifs_dbg(FYI, "SMB2 IOCTL\n");
2411 
2412 	if (out_data != NULL)
2413 		*out_data = NULL;
2414 
2415 	/* zero out returned data len, in case of error */
2416 	if (plen)
2417 		*plen = 0;
2418 
2419 	if (tcon)
2420 		ses = tcon->ses;
2421 	else
2422 		return -EIO;
2423 
2424 	if (!ses || !(ses->server))
2425 		return -EIO;
2426 
2427 	rc = smb2_ioctl_req_init(opcode, tcon, (void **) &req, &total_len);
2428 	if (rc)
2429 		return rc;
2430 
2431 	if (smb3_encryption_required(tcon))
2432 		flags |= CIFS_TRANSFORM_REQ;
2433 
2434 	req->CtlCode = cpu_to_le32(opcode);
2435 	req->PersistentFileId = persistent_fid;
2436 	req->VolatileFileId = volatile_fid;
2437 
2438 	if (indatalen) {
2439 		req->InputCount = cpu_to_le32(indatalen);
2440 		/* do not set InputOffset if no input data */
2441 		req->InputOffset =
2442 		       cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
2443 		iov[1].iov_base = in_data;
2444 		iov[1].iov_len = indatalen;
2445 		n_iov = 2;
2446 	} else
2447 		n_iov = 1;
2448 
2449 	req->OutputOffset = 0;
2450 	req->OutputCount = 0; /* MBZ */
2451 
2452 	/*
2453 	 * Could increase MaxOutputResponse, but that would require more
2454 	 * than one credit. Windows typically sets this smaller, but for some
2455 	 * ioctls it may be useful to allow server to send more. No point
2456 	 * limiting what the server can send as long as fits in one credit
2457 	 * Unfortunately - we can not handle more than CIFS_MAX_MSG_SIZE
2458 	 * (by default, note that it can be overridden to make max larger)
2459 	 * in responses (except for read responses which can be bigger.
2460 	 * We may want to bump this limit up
2461 	 */
2462 	req->MaxOutputResponse = cpu_to_le32(CIFSMaxBufSize);
2463 
2464 	if (is_fsctl)
2465 		req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
2466 	else
2467 		req->Flags = 0;
2468 
2469 	iov[0].iov_base = (char *)req;
2470 
2471 	/*
2472 	 * If no input data, the size of ioctl struct in
2473 	 * protocol spec still includes a 1 byte data buffer,
2474 	 * but if input data passed to ioctl, we do not
2475 	 * want to double count this, so we do not send
2476 	 * the dummy one byte of data in iovec[0] if sending
2477 	 * input data (in iovec[1]).
2478 	 */
2479 
2480 	if (indatalen) {
2481 		iov[0].iov_len = total_len - 1;
2482 	} else
2483 		iov[0].iov_len = total_len;
2484 
2485 	/* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
2486 	if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
2487 		req->sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
2488 
2489 	memset(&rqst, 0, sizeof(struct smb_rqst));
2490 	rqst.rq_iov = iov;
2491 	rqst.rq_nvec = n_iov;
2492 
2493 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags,
2494 			    &rsp_iov);
2495 	cifs_small_buf_release(req);
2496 	rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
2497 
2498 	if (rc != 0)
2499 		trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
2500 				ses->Suid, 0, opcode, rc);
2501 
2502 	if ((rc != 0) && (rc != -EINVAL)) {
2503 		cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
2504 		goto ioctl_exit;
2505 	} else if (rc == -EINVAL) {
2506 		if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
2507 		    (opcode != FSCTL_SRV_COPYCHUNK)) {
2508 			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
2509 			goto ioctl_exit;
2510 		}
2511 	}
2512 
2513 	/* check if caller wants to look at return data or just return rc */
2514 	if ((plen == NULL) || (out_data == NULL))
2515 		goto ioctl_exit;
2516 
2517 	*plen = le32_to_cpu(rsp->OutputCount);
2518 
2519 	/* We check for obvious errors in the output buffer length and offset */
2520 	if (*plen == 0)
2521 		goto ioctl_exit; /* server returned no data */
2522 	else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
2523 		cifs_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
2524 		*plen = 0;
2525 		rc = -EIO;
2526 		goto ioctl_exit;
2527 	}
2528 
2529 	if (rsp_iov.iov_len - *plen < le32_to_cpu(rsp->OutputOffset)) {
2530 		cifs_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
2531 			le32_to_cpu(rsp->OutputOffset));
2532 		*plen = 0;
2533 		rc = -EIO;
2534 		goto ioctl_exit;
2535 	}
2536 
2537 	*out_data = kmalloc(*plen, GFP_KERNEL);
2538 	if (*out_data == NULL) {
2539 		rc = -ENOMEM;
2540 		goto ioctl_exit;
2541 	}
2542 
2543 	memcpy(*out_data, (char *)rsp + le32_to_cpu(rsp->OutputOffset), *plen);
2544 ioctl_exit:
2545 	free_rsp_buf(resp_buftype, rsp);
2546 	return rc;
2547 }
2548 
2549 /*
2550  *   Individual callers to ioctl worker function follow
2551  */
2552 
2553 int
SMB2_set_compression(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)2554 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
2555 		     u64 persistent_fid, u64 volatile_fid)
2556 {
2557 	int rc;
2558 	struct  compress_ioctl fsctl_input;
2559 	char *ret_data = NULL;
2560 
2561 	fsctl_input.CompressionState =
2562 			cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
2563 
2564 	rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
2565 			FSCTL_SET_COMPRESSION, true /* is_fsctl */,
2566 			(char *)&fsctl_input /* data input */,
2567 			2 /* in data len */, &ret_data /* out data */, NULL);
2568 
2569 	cifs_dbg(FYI, "set compression rc %d\n", rc);
2570 
2571 	return rc;
2572 }
2573 
2574 int
SMB2_close_init(struct cifs_tcon * tcon,struct smb_rqst * rqst,u64 persistent_fid,u64 volatile_fid)2575 SMB2_close_init(struct cifs_tcon *tcon, struct smb_rqst *rqst,
2576 		u64 persistent_fid, u64 volatile_fid)
2577 {
2578 	struct smb2_close_req *req;
2579 	struct kvec *iov = rqst->rq_iov;
2580 	unsigned int total_len;
2581 	int rc;
2582 
2583 	rc = smb2_plain_req_init(SMB2_CLOSE, tcon, (void **) &req, &total_len);
2584 	if (rc)
2585 		return rc;
2586 
2587 	req->PersistentFileId = persistent_fid;
2588 	req->VolatileFileId = volatile_fid;
2589 	iov[0].iov_base = (char *)req;
2590 	iov[0].iov_len = total_len;
2591 
2592 	return 0;
2593 }
2594 
2595 void
SMB2_close_free(struct smb_rqst * rqst)2596 SMB2_close_free(struct smb_rqst *rqst)
2597 {
2598 	if (rqst && rqst->rq_iov)
2599 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
2600 }
2601 
2602 int
SMB2_close_flags(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,int flags)2603 SMB2_close_flags(const unsigned int xid, struct cifs_tcon *tcon,
2604 		 u64 persistent_fid, u64 volatile_fid, int flags)
2605 {
2606 	struct smb_rqst rqst;
2607 	struct smb2_close_rsp *rsp = NULL;
2608 	struct cifs_ses *ses = tcon->ses;
2609 	struct kvec iov[1];
2610 	struct kvec rsp_iov;
2611 	int resp_buftype = CIFS_NO_BUFFER;
2612 	int rc = 0;
2613 
2614 	cifs_dbg(FYI, "Close\n");
2615 
2616 	if (!ses || !(ses->server))
2617 		return -EIO;
2618 
2619 	if (smb3_encryption_required(tcon))
2620 		flags |= CIFS_TRANSFORM_REQ;
2621 
2622 	memset(&rqst, 0, sizeof(struct smb_rqst));
2623 	memset(&iov, 0, sizeof(iov));
2624 	rqst.rq_iov = iov;
2625 	rqst.rq_nvec = 1;
2626 
2627 	rc = SMB2_close_init(tcon, &rqst, persistent_fid, volatile_fid);
2628 	if (rc)
2629 		goto close_exit;
2630 
2631 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
2632 	rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
2633 
2634 	if (rc != 0) {
2635 		cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
2636 		trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
2637 				     rc);
2638 		goto close_exit;
2639 	}
2640 
2641 	/* BB FIXME - decode close response, update inode for caching */
2642 
2643 close_exit:
2644 	SMB2_close_free(&rqst);
2645 	free_rsp_buf(resp_buftype, rsp);
2646 	return rc;
2647 }
2648 
2649 int
SMB2_close(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)2650 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
2651 	   u64 persistent_fid, u64 volatile_fid)
2652 {
2653 	int rc;
2654 	int tmp_rc;
2655 
2656 	rc = SMB2_close_flags(xid, tcon, persistent_fid, volatile_fid, 0);
2657 
2658 	/* retry close in a worker thread if this one is interrupted */
2659 	if (rc == -EINTR) {
2660 		tmp_rc = smb2_handle_cancelled_close(tcon, persistent_fid,
2661 						     volatile_fid);
2662 		if (tmp_rc)
2663 			cifs_dbg(VFS, "handle cancelled close fid 0x%llx returned error %d\n",
2664 				 persistent_fid, tmp_rc);
2665 	}
2666 
2667 	return rc;
2668 }
2669 
2670 int
smb2_validate_iov(unsigned int offset,unsigned int buffer_length,struct kvec * iov,unsigned int min_buf_size)2671 smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
2672 		  struct kvec *iov, unsigned int min_buf_size)
2673 {
2674 	unsigned int smb_len = iov->iov_len;
2675 	char *end_of_smb = smb_len + (char *)iov->iov_base;
2676 	char *begin_of_buf = offset + (char *)iov->iov_base;
2677 	char *end_of_buf = begin_of_buf + buffer_length;
2678 
2679 
2680 	if (buffer_length < min_buf_size) {
2681 		cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
2682 			 buffer_length, min_buf_size);
2683 		return -EINVAL;
2684 	}
2685 
2686 	/* check if beyond RFC1001 maximum length */
2687 	if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
2688 		cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
2689 			 buffer_length, smb_len);
2690 		return -EINVAL;
2691 	}
2692 
2693 	if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
2694 		cifs_dbg(VFS, "illegal server response, bad offset to data\n");
2695 		return -EINVAL;
2696 	}
2697 
2698 	return 0;
2699 }
2700 
2701 /*
2702  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
2703  * Caller must free buffer.
2704  */
2705 static int
validate_and_copy_iov(unsigned int offset,unsigned int buffer_length,struct kvec * iov,unsigned int minbufsize,char * data)2706 validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
2707 		      struct kvec *iov, unsigned int minbufsize,
2708 		      char *data)
2709 {
2710 	char *begin_of_buf = offset + (char *)iov->iov_base;
2711 	int rc;
2712 
2713 	if (!data)
2714 		return -EINVAL;
2715 
2716 	rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
2717 	if (rc)
2718 		return rc;
2719 
2720 	memcpy(data, begin_of_buf, buffer_length);
2721 
2722 	return 0;
2723 }
2724 
2725 int
SMB2_query_info_init(struct cifs_tcon * tcon,struct smb_rqst * rqst,u64 persistent_fid,u64 volatile_fid,u8 info_class,u8 info_type,u32 additional_info,size_t output_len)2726 SMB2_query_info_init(struct cifs_tcon *tcon, struct smb_rqst *rqst,
2727 		     u64 persistent_fid, u64 volatile_fid,
2728 		     u8 info_class, u8 info_type, u32 additional_info,
2729 		     size_t output_len)
2730 {
2731 	struct smb2_query_info_req *req;
2732 	struct kvec *iov = rqst->rq_iov;
2733 	unsigned int total_len;
2734 	int rc;
2735 
2736 	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, (void **) &req,
2737 			     &total_len);
2738 	if (rc)
2739 		return rc;
2740 
2741 	req->InfoType = info_type;
2742 	req->FileInfoClass = info_class;
2743 	req->PersistentFileId = persistent_fid;
2744 	req->VolatileFileId = volatile_fid;
2745 	req->AdditionalInformation = cpu_to_le32(additional_info);
2746 
2747 	/*
2748 	 * We do not use the input buffer (do not send extra byte)
2749 	 */
2750 	req->InputBufferOffset = 0;
2751 
2752 	req->OutputBufferLength = cpu_to_le32(output_len);
2753 
2754 	iov[0].iov_base = (char *)req;
2755 	/* 1 for Buffer */
2756 	iov[0].iov_len = total_len - 1;
2757 	return 0;
2758 }
2759 
2760 void
SMB2_query_info_free(struct smb_rqst * rqst)2761 SMB2_query_info_free(struct smb_rqst *rqst)
2762 {
2763 	if (rqst && rqst->rq_iov)
2764 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
2765 }
2766 
2767 static int
query_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u8 info_class,u8 info_type,u32 additional_info,size_t output_len,size_t min_len,void ** data,u32 * dlen)2768 query_info(const unsigned int xid, struct cifs_tcon *tcon,
2769 	   u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
2770 	   u32 additional_info, size_t output_len, size_t min_len, void **data,
2771 		u32 *dlen)
2772 {
2773 	struct smb_rqst rqst;
2774 	struct smb2_query_info_rsp *rsp = NULL;
2775 	struct kvec iov[1];
2776 	struct kvec rsp_iov;
2777 	int rc = 0;
2778 	int resp_buftype = CIFS_NO_BUFFER;
2779 	struct cifs_ses *ses = tcon->ses;
2780 	int flags = 0;
2781 
2782 	cifs_dbg(FYI, "Query Info\n");
2783 
2784 	if (!ses || !(ses->server))
2785 		return -EIO;
2786 
2787 	if (smb3_encryption_required(tcon))
2788 		flags |= CIFS_TRANSFORM_REQ;
2789 
2790 	memset(&rqst, 0, sizeof(struct smb_rqst));
2791 	memset(&iov, 0, sizeof(iov));
2792 	rqst.rq_iov = iov;
2793 	rqst.rq_nvec = 1;
2794 
2795 	rc = SMB2_query_info_init(tcon, &rqst, persistent_fid, volatile_fid,
2796 				  info_class, info_type, additional_info,
2797 				  output_len);
2798 	if (rc)
2799 		goto qinf_exit;
2800 
2801 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
2802 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
2803 
2804 	if (rc) {
2805 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
2806 		trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
2807 				ses->Suid, info_class, (__u32)info_type, rc);
2808 		goto qinf_exit;
2809 	}
2810 
2811 	if (dlen) {
2812 		*dlen = le32_to_cpu(rsp->OutputBufferLength);
2813 		if (!*data) {
2814 			*data = kmalloc(*dlen, GFP_KERNEL);
2815 			if (!*data) {
2816 				cifs_dbg(VFS,
2817 					"Error %d allocating memory for acl\n",
2818 					rc);
2819 				*dlen = 0;
2820 				goto qinf_exit;
2821 			}
2822 		}
2823 	}
2824 
2825 	rc = validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
2826 				   le32_to_cpu(rsp->OutputBufferLength),
2827 				   &rsp_iov, min_len, *data);
2828 
2829 qinf_exit:
2830 	SMB2_query_info_free(&rqst);
2831 	free_rsp_buf(resp_buftype, rsp);
2832 	return rc;
2833 }
2834 
SMB2_query_eas(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,int ea_buf_size,struct smb2_file_full_ea_info * data)2835 int SMB2_query_eas(const unsigned int xid, struct cifs_tcon *tcon,
2836 		   u64 persistent_fid, u64 volatile_fid,
2837 		   int ea_buf_size, struct smb2_file_full_ea_info *data)
2838 {
2839 	return query_info(xid, tcon, persistent_fid, volatile_fid,
2840 			  FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE, 0,
2841 			  ea_buf_size,
2842 			  sizeof(struct smb2_file_full_ea_info),
2843 			  (void **)&data,
2844 			  NULL);
2845 }
2846 
SMB2_query_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct smb2_file_all_info * data)2847 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
2848 	u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
2849 {
2850 	return query_info(xid, tcon, persistent_fid, volatile_fid,
2851 			  FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
2852 			  sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
2853 			  sizeof(struct smb2_file_all_info), (void **)&data,
2854 			  NULL);
2855 }
2856 
2857 int
SMB2_query_acl(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,void ** data,u32 * plen)2858 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
2859 		u64 persistent_fid, u64 volatile_fid,
2860 		void **data, u32 *plen)
2861 {
2862 	__u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO;
2863 	*plen = 0;
2864 
2865 	return query_info(xid, tcon, persistent_fid, volatile_fid,
2866 			  0, SMB2_O_INFO_SECURITY, additional_info,
2867 			  SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
2868 }
2869 
2870 int
SMB2_get_srv_num(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,__le64 * uniqueid)2871 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
2872 		 u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
2873 {
2874 	return query_info(xid, tcon, persistent_fid, volatile_fid,
2875 			  FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
2876 			  sizeof(struct smb2_file_internal_info),
2877 			  sizeof(struct smb2_file_internal_info),
2878 			  (void **)&uniqueid, NULL);
2879 }
2880 
2881 /*
2882  * This is a no-op for now. We're not really interested in the reply, but
2883  * rather in the fact that the server sent one and that server->lstrp
2884  * gets updated.
2885  *
2886  * FIXME: maybe we should consider checking that the reply matches request?
2887  */
2888 static void
smb2_echo_callback(struct mid_q_entry * mid)2889 smb2_echo_callback(struct mid_q_entry *mid)
2890 {
2891 	struct TCP_Server_Info *server = mid->callback_data;
2892 	struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
2893 	unsigned int credits_received = 0;
2894 
2895 	if (mid->mid_state == MID_RESPONSE_RECEIVED
2896 	    || mid->mid_state == MID_RESPONSE_MALFORMED)
2897 		credits_received = le16_to_cpu(rsp->sync_hdr.CreditRequest);
2898 
2899 	DeleteMidQEntry(mid);
2900 	add_credits(server, credits_received, CIFS_ECHO_OP);
2901 }
2902 
smb2_reconnect_server(struct work_struct * work)2903 void smb2_reconnect_server(struct work_struct *work)
2904 {
2905 	struct TCP_Server_Info *server = container_of(work,
2906 					struct TCP_Server_Info, reconnect.work);
2907 	struct cifs_ses *ses;
2908 	struct cifs_tcon *tcon, *tcon2;
2909 	struct list_head tmp_list;
2910 	int tcon_exist = false;
2911 	int rc;
2912 	int resched = false;
2913 
2914 
2915 	/* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
2916 	mutex_lock(&server->reconnect_mutex);
2917 
2918 	INIT_LIST_HEAD(&tmp_list);
2919 	cifs_dbg(FYI, "Need negotiate, reconnecting tcons\n");
2920 
2921 	spin_lock(&cifs_tcp_ses_lock);
2922 	list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
2923 		list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2924 			if (tcon->need_reconnect || tcon->need_reopen_files) {
2925 				tcon->tc_count++;
2926 				list_add_tail(&tcon->rlist, &tmp_list);
2927 				tcon_exist = true;
2928 			}
2929 		}
2930 		if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
2931 			list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
2932 			tcon_exist = true;
2933 		}
2934 	}
2935 	/*
2936 	 * Get the reference to server struct to be sure that the last call of
2937 	 * cifs_put_tcon() in the loop below won't release the server pointer.
2938 	 */
2939 	if (tcon_exist)
2940 		server->srv_count++;
2941 
2942 	spin_unlock(&cifs_tcp_ses_lock);
2943 
2944 	list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
2945 		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon);
2946 		if (!rc)
2947 			cifs_reopen_persistent_handles(tcon);
2948 		else
2949 			resched = true;
2950 		list_del_init(&tcon->rlist);
2951 		cifs_put_tcon(tcon);
2952 	}
2953 
2954 	cifs_dbg(FYI, "Reconnecting tcons finished\n");
2955 	if (resched)
2956 		queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
2957 	mutex_unlock(&server->reconnect_mutex);
2958 
2959 	/* now we can safely release srv struct */
2960 	if (tcon_exist)
2961 		cifs_put_tcp_session(server, 1);
2962 }
2963 
2964 int
SMB2_echo(struct TCP_Server_Info * server)2965 SMB2_echo(struct TCP_Server_Info *server)
2966 {
2967 	struct smb2_echo_req *req;
2968 	int rc = 0;
2969 	struct kvec iov[1];
2970 	struct smb_rqst rqst = { .rq_iov = iov,
2971 				 .rq_nvec = 1 };
2972 	unsigned int total_len;
2973 
2974 	cifs_dbg(FYI, "In echo request\n");
2975 
2976 	if (server->tcpStatus == CifsNeedNegotiate) {
2977 		/* No need to send echo on newly established connections */
2978 		queue_delayed_work(cifsiod_wq, &server->reconnect, 0);
2979 		return rc;
2980 	}
2981 
2982 	rc = smb2_plain_req_init(SMB2_ECHO, NULL, (void **)&req, &total_len);
2983 	if (rc)
2984 		return rc;
2985 
2986 	req->sync_hdr.CreditRequest = cpu_to_le16(1);
2987 
2988 	iov[0].iov_len = total_len;
2989 	iov[0].iov_base = (char *)req;
2990 
2991 	rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
2992 			     server, CIFS_ECHO_OP);
2993 	if (rc)
2994 		cifs_dbg(FYI, "Echo request failed: %d\n", rc);
2995 
2996 	cifs_small_buf_release(req);
2997 	return rc;
2998 }
2999 
3000 int
SMB2_flush(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)3001 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3002 	   u64 volatile_fid)
3003 {
3004 	struct smb_rqst rqst;
3005 	struct smb2_flush_req *req;
3006 	struct cifs_ses *ses = tcon->ses;
3007 	struct kvec iov[1];
3008 	struct kvec rsp_iov;
3009 	int resp_buftype;
3010 	int rc = 0;
3011 	int flags = 0;
3012 	unsigned int total_len;
3013 
3014 	cifs_dbg(FYI, "Flush\n");
3015 
3016 	if (!ses || !(ses->server))
3017 		return -EIO;
3018 
3019 	rc = smb2_plain_req_init(SMB2_FLUSH, tcon, (void **) &req, &total_len);
3020 	if (rc)
3021 		return rc;
3022 
3023 	if (smb3_encryption_required(tcon))
3024 		flags |= CIFS_TRANSFORM_REQ;
3025 
3026 	req->PersistentFileId = persistent_fid;
3027 	req->VolatileFileId = volatile_fid;
3028 
3029 	iov[0].iov_base = (char *)req;
3030 	iov[0].iov_len = total_len;
3031 
3032 	memset(&rqst, 0, sizeof(struct smb_rqst));
3033 	rqst.rq_iov = iov;
3034 	rqst.rq_nvec = 1;
3035 
3036 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
3037 	cifs_small_buf_release(req);
3038 
3039 	if (rc != 0) {
3040 		cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
3041 		trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
3042 				     rc);
3043 	}
3044 
3045 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3046 	return rc;
3047 }
3048 
3049 /*
3050  * To form a chain of read requests, any read requests after the first should
3051  * have the end_of_chain boolean set to true.
3052  */
3053 static int
smb2_new_read_req(void ** buf,unsigned int * total_len,struct cifs_io_parms * io_parms,struct cifs_readdata * rdata,unsigned int remaining_bytes,int request_type)3054 smb2_new_read_req(void **buf, unsigned int *total_len,
3055 	struct cifs_io_parms *io_parms, struct cifs_readdata *rdata,
3056 	unsigned int remaining_bytes, int request_type)
3057 {
3058 	int rc = -EACCES;
3059 	struct smb2_read_plain_req *req = NULL;
3060 	struct smb2_sync_hdr *shdr;
3061 	struct TCP_Server_Info *server;
3062 
3063 	rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, (void **) &req,
3064 				 total_len);
3065 	if (rc)
3066 		return rc;
3067 
3068 	server = io_parms->tcon->ses->server;
3069 	if (server == NULL)
3070 		return -ECONNABORTED;
3071 
3072 	shdr = &req->sync_hdr;
3073 	shdr->ProcessId = cpu_to_le32(io_parms->pid);
3074 
3075 	req->PersistentFileId = io_parms->persistent_fid;
3076 	req->VolatileFileId = io_parms->volatile_fid;
3077 	req->ReadChannelInfoOffset = 0; /* reserved */
3078 	req->ReadChannelInfoLength = 0; /* reserved */
3079 	req->Channel = 0; /* reserved */
3080 	req->MinimumCount = 0;
3081 	req->Length = cpu_to_le32(io_parms->length);
3082 	req->Offset = cpu_to_le64(io_parms->offset);
3083 #ifdef CONFIG_CIFS_SMB_DIRECT
3084 	/*
3085 	 * If we want to do a RDMA write, fill in and append
3086 	 * smbd_buffer_descriptor_v1 to the end of read request
3087 	 */
3088 	if (server->rdma && rdata && !server->sign &&
3089 		rdata->bytes >= server->smbd_conn->rdma_readwrite_threshold) {
3090 
3091 		struct smbd_buffer_descriptor_v1 *v1;
3092 		bool need_invalidate =
3093 			io_parms->tcon->ses->server->dialect == SMB30_PROT_ID;
3094 
3095 		rdata->mr = smbd_register_mr(
3096 				server->smbd_conn, rdata->pages,
3097 				rdata->nr_pages, rdata->page_offset,
3098 				rdata->tailsz, true, need_invalidate);
3099 		if (!rdata->mr)
3100 			return -ENOBUFS;
3101 
3102 		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
3103 		if (need_invalidate)
3104 			req->Channel = SMB2_CHANNEL_RDMA_V1;
3105 		req->ReadChannelInfoOffset =
3106 			cpu_to_le16(offsetof(struct smb2_read_plain_req, Buffer));
3107 		req->ReadChannelInfoLength =
3108 			cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
3109 		v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
3110 		v1->offset = cpu_to_le64(rdata->mr->mr->iova);
3111 		v1->token = cpu_to_le32(rdata->mr->mr->rkey);
3112 		v1->length = cpu_to_le32(rdata->mr->mr->length);
3113 
3114 		*total_len += sizeof(*v1) - 1;
3115 	}
3116 #endif
3117 	if (request_type & CHAINED_REQUEST) {
3118 		if (!(request_type & END_OF_CHAIN)) {
3119 			/* next 8-byte aligned request */
3120 			*total_len = DIV_ROUND_UP(*total_len, 8) * 8;
3121 			shdr->NextCommand = cpu_to_le32(*total_len);
3122 		} else /* END_OF_CHAIN */
3123 			shdr->NextCommand = 0;
3124 		if (request_type & RELATED_REQUEST) {
3125 			shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
3126 			/*
3127 			 * Related requests use info from previous read request
3128 			 * in chain.
3129 			 */
3130 			shdr->SessionId = 0xFFFFFFFFFFFFFFFF;
3131 			shdr->TreeId = 0xFFFFFFFF;
3132 			req->PersistentFileId = 0xFFFFFFFFFFFFFFFF;
3133 			req->VolatileFileId = 0xFFFFFFFFFFFFFFFF;
3134 		}
3135 	}
3136 	if (remaining_bytes > io_parms->length)
3137 		req->RemainingBytes = cpu_to_le32(remaining_bytes);
3138 	else
3139 		req->RemainingBytes = 0;
3140 
3141 	*buf = req;
3142 	return rc;
3143 }
3144 
3145 static void
smb2_readv_callback(struct mid_q_entry * mid)3146 smb2_readv_callback(struct mid_q_entry *mid)
3147 {
3148 	struct cifs_readdata *rdata = mid->callback_data;
3149 	struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
3150 	struct TCP_Server_Info *server = tcon->ses->server;
3151 	struct smb2_sync_hdr *shdr =
3152 				(struct smb2_sync_hdr *)rdata->iov[0].iov_base;
3153 	unsigned int credits_received = 0;
3154 	struct smb_rqst rqst = { .rq_iov = &rdata->iov[1],
3155 				 .rq_nvec = 1, };
3156 
3157 	if (rdata->got_bytes) {
3158 		rqst.rq_pages = rdata->pages;
3159 		rqst.rq_offset = rdata->page_offset;
3160 		rqst.rq_npages = rdata->nr_pages;
3161 		rqst.rq_pagesz = rdata->pagesz;
3162 		rqst.rq_tailsz = rdata->tailsz;
3163 	}
3164 
3165 	cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
3166 		 __func__, mid->mid, mid->mid_state, rdata->result,
3167 		 rdata->bytes);
3168 
3169 	switch (mid->mid_state) {
3170 	case MID_RESPONSE_RECEIVED:
3171 		credits_received = le16_to_cpu(shdr->CreditRequest);
3172 		/* result already set, check signature */
3173 		if (server->sign && !mid->decrypted) {
3174 			int rc;
3175 
3176 			rc = smb2_verify_signature(&rqst, server);
3177 			if (rc)
3178 				cifs_dbg(VFS, "SMB signature verification returned error = %d\n",
3179 					 rc);
3180 		}
3181 		/* FIXME: should this be counted toward the initiating task? */
3182 		task_io_account_read(rdata->got_bytes);
3183 		cifs_stats_bytes_read(tcon, rdata->got_bytes);
3184 		break;
3185 	case MID_REQUEST_SUBMITTED:
3186 	case MID_RETRY_NEEDED:
3187 		rdata->result = -EAGAIN;
3188 		if (server->sign && rdata->got_bytes)
3189 			/* reset bytes number since we can not check a sign */
3190 			rdata->got_bytes = 0;
3191 		/* FIXME: should this be counted toward the initiating task? */
3192 		task_io_account_read(rdata->got_bytes);
3193 		cifs_stats_bytes_read(tcon, rdata->got_bytes);
3194 		break;
3195 	case MID_RESPONSE_MALFORMED:
3196 		credits_received = le16_to_cpu(shdr->CreditRequest);
3197 		/* fall through */
3198 	default:
3199 		if (rdata->result != -ENODATA)
3200 			rdata->result = -EIO;
3201 	}
3202 #ifdef CONFIG_CIFS_SMB_DIRECT
3203 	/*
3204 	 * If this rdata has a memmory registered, the MR can be freed
3205 	 * MR needs to be freed as soon as I/O finishes to prevent deadlock
3206 	 * because they have limited number and are used for future I/Os
3207 	 */
3208 	if (rdata->mr) {
3209 		smbd_deregister_mr(rdata->mr);
3210 		rdata->mr = NULL;
3211 	}
3212 #endif
3213 	if (rdata->result && rdata->result != -ENODATA) {
3214 		cifs_stats_fail_inc(tcon, SMB2_READ_HE);
3215 		trace_smb3_read_err(0 /* xid */,
3216 				    rdata->cfile->fid.persistent_fid,
3217 				    tcon->tid, tcon->ses->Suid, rdata->offset,
3218 				    rdata->bytes, rdata->result);
3219 	} else
3220 		trace_smb3_read_done(0 /* xid */,
3221 				     rdata->cfile->fid.persistent_fid,
3222 				     tcon->tid, tcon->ses->Suid,
3223 				     rdata->offset, rdata->got_bytes);
3224 
3225 	queue_work(cifsiod_wq, &rdata->work);
3226 	DeleteMidQEntry(mid);
3227 	add_credits(server, credits_received, 0);
3228 }
3229 
3230 /* smb2_async_readv - send an async read, and set up mid to handle result */
3231 int
smb2_async_readv(struct cifs_readdata * rdata)3232 smb2_async_readv(struct cifs_readdata *rdata)
3233 {
3234 	int rc, flags = 0;
3235 	char *buf;
3236 	struct smb2_sync_hdr *shdr;
3237 	struct cifs_io_parms io_parms;
3238 	struct smb_rqst rqst = { .rq_iov = rdata->iov,
3239 				 .rq_nvec = 1 };
3240 	struct TCP_Server_Info *server;
3241 	unsigned int total_len;
3242 
3243 	cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
3244 		 __func__, rdata->offset, rdata->bytes);
3245 
3246 	io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
3247 	io_parms.offset = rdata->offset;
3248 	io_parms.length = rdata->bytes;
3249 	io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
3250 	io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
3251 	io_parms.pid = rdata->pid;
3252 
3253 	server = io_parms.tcon->ses->server;
3254 
3255 	rc = smb2_new_read_req(
3256 		(void **) &buf, &total_len, &io_parms, rdata, 0, 0);
3257 	if (rc) {
3258 		if (rc == -EAGAIN && rdata->credits) {
3259 			/* credits was reset by reconnect */
3260 			rdata->credits = 0;
3261 			/* reduce in_flight value since we won't send the req */
3262 			spin_lock(&server->req_lock);
3263 			server->in_flight--;
3264 			spin_unlock(&server->req_lock);
3265 		}
3266 		return rc;
3267 	}
3268 
3269 	if (smb3_encryption_required(io_parms.tcon))
3270 		flags |= CIFS_TRANSFORM_REQ;
3271 
3272 	rdata->iov[0].iov_base = buf;
3273 	rdata->iov[0].iov_len = total_len;
3274 
3275 	shdr = (struct smb2_sync_hdr *)buf;
3276 
3277 	if (rdata->credits) {
3278 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
3279 						SMB2_MAX_BUFFER_SIZE));
3280 		shdr->CreditRequest =
3281 			cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 1);
3282 		spin_lock(&server->req_lock);
3283 		server->credits += rdata->credits -
3284 						le16_to_cpu(shdr->CreditCharge);
3285 		spin_unlock(&server->req_lock);
3286 		wake_up(&server->request_q);
3287 		rdata->credits = le16_to_cpu(shdr->CreditCharge);
3288 		flags |= CIFS_HAS_CREDITS;
3289 	}
3290 
3291 	kref_get(&rdata->refcount);
3292 	rc = cifs_call_async(io_parms.tcon->ses->server, &rqst,
3293 			     cifs_readv_receive, smb2_readv_callback,
3294 			     smb3_handle_read_data, rdata, flags);
3295 	if (rc) {
3296 		kref_put(&rdata->refcount, cifs_readdata_release);
3297 		cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
3298 		trace_smb3_read_err(0 /* xid */, io_parms.persistent_fid,
3299 				    io_parms.tcon->tid,
3300 				    io_parms.tcon->ses->Suid,
3301 				    io_parms.offset, io_parms.length, rc);
3302 	}
3303 
3304 	cifs_small_buf_release(buf);
3305 	return rc;
3306 }
3307 
3308 int
SMB2_read(const unsigned int xid,struct cifs_io_parms * io_parms,unsigned int * nbytes,char ** buf,int * buf_type)3309 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
3310 	  unsigned int *nbytes, char **buf, int *buf_type)
3311 {
3312 	struct smb_rqst rqst;
3313 	int resp_buftype, rc = -EACCES;
3314 	struct smb2_read_plain_req *req = NULL;
3315 	struct smb2_read_rsp *rsp = NULL;
3316 	struct kvec iov[1];
3317 	struct kvec rsp_iov;
3318 	unsigned int total_len;
3319 	int flags = CIFS_LOG_ERROR;
3320 	struct cifs_ses *ses = io_parms->tcon->ses;
3321 
3322 	*nbytes = 0;
3323 	rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
3324 	if (rc)
3325 		return rc;
3326 
3327 	if (smb3_encryption_required(io_parms->tcon))
3328 		flags |= CIFS_TRANSFORM_REQ;
3329 
3330 	iov[0].iov_base = (char *)req;
3331 	iov[0].iov_len = total_len;
3332 
3333 	memset(&rqst, 0, sizeof(struct smb_rqst));
3334 	rqst.rq_iov = iov;
3335 	rqst.rq_nvec = 1;
3336 
3337 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
3338 	rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
3339 
3340 	if (rc) {
3341 		if (rc != -ENODATA) {
3342 			cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
3343 			cifs_dbg(VFS, "Send error in read = %d\n", rc);
3344 			trace_smb3_read_err(xid, req->PersistentFileId,
3345 					    io_parms->tcon->tid, ses->Suid,
3346 					    io_parms->offset, io_parms->length,
3347 					    rc);
3348 		}
3349 		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3350 		cifs_small_buf_release(req);
3351 		return rc == -ENODATA ? 0 : rc;
3352 	} else
3353 		trace_smb3_read_done(xid, req->PersistentFileId,
3354 				    io_parms->tcon->tid, ses->Suid,
3355 				    io_parms->offset, io_parms->length);
3356 
3357 	cifs_small_buf_release(req);
3358 
3359 	*nbytes = le32_to_cpu(rsp->DataLength);
3360 	if ((*nbytes > CIFS_MAX_MSGSIZE) ||
3361 	    (*nbytes > io_parms->length)) {
3362 		cifs_dbg(FYI, "bad length %d for count %d\n",
3363 			 *nbytes, io_parms->length);
3364 		rc = -EIO;
3365 		*nbytes = 0;
3366 	}
3367 
3368 	if (*buf) {
3369 		memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
3370 		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3371 	} else if (resp_buftype != CIFS_NO_BUFFER) {
3372 		*buf = rsp_iov.iov_base;
3373 		if (resp_buftype == CIFS_SMALL_BUFFER)
3374 			*buf_type = CIFS_SMALL_BUFFER;
3375 		else if (resp_buftype == CIFS_LARGE_BUFFER)
3376 			*buf_type = CIFS_LARGE_BUFFER;
3377 	}
3378 	return rc;
3379 }
3380 
3381 /*
3382  * Check the mid_state and signature on received buffer (if any), and queue the
3383  * workqueue completion task.
3384  */
3385 static void
smb2_writev_callback(struct mid_q_entry * mid)3386 smb2_writev_callback(struct mid_q_entry *mid)
3387 {
3388 	struct cifs_writedata *wdata = mid->callback_data;
3389 	struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
3390 	unsigned int written;
3391 	struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
3392 	unsigned int credits_received = 0;
3393 
3394 	switch (mid->mid_state) {
3395 	case MID_RESPONSE_RECEIVED:
3396 		credits_received = le16_to_cpu(rsp->sync_hdr.CreditRequest);
3397 		wdata->result = smb2_check_receive(mid, tcon->ses->server, 0);
3398 		if (wdata->result != 0)
3399 			break;
3400 
3401 		written = le32_to_cpu(rsp->DataLength);
3402 		/*
3403 		 * Mask off high 16 bits when bytes written as returned
3404 		 * by the server is greater than bytes requested by the
3405 		 * client. OS/2 servers are known to set incorrect
3406 		 * CountHigh values.
3407 		 */
3408 		if (written > wdata->bytes)
3409 			written &= 0xFFFF;
3410 
3411 		if (written < wdata->bytes)
3412 			wdata->result = -ENOSPC;
3413 		else
3414 			wdata->bytes = written;
3415 		break;
3416 	case MID_REQUEST_SUBMITTED:
3417 	case MID_RETRY_NEEDED:
3418 		wdata->result = -EAGAIN;
3419 		break;
3420 	case MID_RESPONSE_MALFORMED:
3421 		credits_received = le16_to_cpu(rsp->sync_hdr.CreditRequest);
3422 		/* fall through */
3423 	default:
3424 		wdata->result = -EIO;
3425 		break;
3426 	}
3427 #ifdef CONFIG_CIFS_SMB_DIRECT
3428 	/*
3429 	 * If this wdata has a memory registered, the MR can be freed
3430 	 * The number of MRs available is limited, it's important to recover
3431 	 * used MR as soon as I/O is finished. Hold MR longer in the later
3432 	 * I/O process can possibly result in I/O deadlock due to lack of MR
3433 	 * to send request on I/O retry
3434 	 */
3435 	if (wdata->mr) {
3436 		smbd_deregister_mr(wdata->mr);
3437 		wdata->mr = NULL;
3438 	}
3439 #endif
3440 	if (wdata->result) {
3441 		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
3442 		trace_smb3_write_err(0 /* no xid */,
3443 				     wdata->cfile->fid.persistent_fid,
3444 				     tcon->tid, tcon->ses->Suid, wdata->offset,
3445 				     wdata->bytes, wdata->result);
3446 		if (wdata->result == -ENOSPC)
3447 			printk_once(KERN_WARNING "Out of space writing to %s\n",
3448 				    tcon->treeName);
3449 	} else
3450 		trace_smb3_write_done(0 /* no xid */,
3451 				      wdata->cfile->fid.persistent_fid,
3452 				      tcon->tid, tcon->ses->Suid,
3453 				      wdata->offset, wdata->bytes);
3454 
3455 	queue_work(cifsiod_wq, &wdata->work);
3456 	DeleteMidQEntry(mid);
3457 	add_credits(tcon->ses->server, credits_received, 0);
3458 }
3459 
3460 /* smb2_async_writev - send an async write, and set up mid to handle result */
3461 int
smb2_async_writev(struct cifs_writedata * wdata,void (* release)(struct kref * kref))3462 smb2_async_writev(struct cifs_writedata *wdata,
3463 		  void (*release)(struct kref *kref))
3464 {
3465 	int rc = -EACCES, flags = 0;
3466 	struct smb2_write_req *req = NULL;
3467 	struct smb2_sync_hdr *shdr;
3468 	struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
3469 	struct TCP_Server_Info *server = tcon->ses->server;
3470 	struct kvec iov[1];
3471 	struct smb_rqst rqst = { };
3472 	unsigned int total_len;
3473 
3474 	rc = smb2_plain_req_init(SMB2_WRITE, tcon, (void **) &req, &total_len);
3475 	if (rc) {
3476 		if (rc == -EAGAIN && wdata->credits) {
3477 			/* credits was reset by reconnect */
3478 			wdata->credits = 0;
3479 			/* reduce in_flight value since we won't send the req */
3480 			spin_lock(&server->req_lock);
3481 			server->in_flight--;
3482 			spin_unlock(&server->req_lock);
3483 		}
3484 		goto async_writev_out;
3485 	}
3486 
3487 	if (smb3_encryption_required(tcon))
3488 		flags |= CIFS_TRANSFORM_REQ;
3489 
3490 	shdr = (struct smb2_sync_hdr *)req;
3491 	shdr->ProcessId = cpu_to_le32(wdata->cfile->pid);
3492 
3493 	req->PersistentFileId = wdata->cfile->fid.persistent_fid;
3494 	req->VolatileFileId = wdata->cfile->fid.volatile_fid;
3495 	req->WriteChannelInfoOffset = 0;
3496 	req->WriteChannelInfoLength = 0;
3497 	req->Channel = 0;
3498 	req->Offset = cpu_to_le64(wdata->offset);
3499 	req->DataOffset = cpu_to_le16(
3500 				offsetof(struct smb2_write_req, Buffer));
3501 	req->RemainingBytes = 0;
3502 #ifdef CONFIG_CIFS_SMB_DIRECT
3503 	/*
3504 	 * If we want to do a server RDMA read, fill in and append
3505 	 * smbd_buffer_descriptor_v1 to the end of write request
3506 	 */
3507 	if (server->rdma && !server->sign && wdata->bytes >=
3508 		server->smbd_conn->rdma_readwrite_threshold) {
3509 
3510 		struct smbd_buffer_descriptor_v1 *v1;
3511 		bool need_invalidate = server->dialect == SMB30_PROT_ID;
3512 
3513 		wdata->mr = smbd_register_mr(
3514 				server->smbd_conn, wdata->pages,
3515 				wdata->nr_pages, wdata->page_offset,
3516 				wdata->tailsz, false, need_invalidate);
3517 		if (!wdata->mr) {
3518 			rc = -ENOBUFS;
3519 			goto async_writev_out;
3520 		}
3521 		req->Length = 0;
3522 		req->DataOffset = 0;
3523 		if (wdata->nr_pages > 1)
3524 			req->RemainingBytes =
3525 				cpu_to_le32(
3526 					(wdata->nr_pages - 1) * wdata->pagesz -
3527 					wdata->page_offset + wdata->tailsz
3528 				);
3529 		else
3530 			req->RemainingBytes = cpu_to_le32(wdata->tailsz);
3531 		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
3532 		if (need_invalidate)
3533 			req->Channel = SMB2_CHANNEL_RDMA_V1;
3534 		req->WriteChannelInfoOffset =
3535 			cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
3536 		req->WriteChannelInfoLength =
3537 			cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
3538 		v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
3539 		v1->offset = cpu_to_le64(wdata->mr->mr->iova);
3540 		v1->token = cpu_to_le32(wdata->mr->mr->rkey);
3541 		v1->length = cpu_to_le32(wdata->mr->mr->length);
3542 	}
3543 #endif
3544 	iov[0].iov_len = total_len - 1;
3545 	iov[0].iov_base = (char *)req;
3546 
3547 	rqst.rq_iov = iov;
3548 	rqst.rq_nvec = 1;
3549 	rqst.rq_pages = wdata->pages;
3550 	rqst.rq_offset = wdata->page_offset;
3551 	rqst.rq_npages = wdata->nr_pages;
3552 	rqst.rq_pagesz = wdata->pagesz;
3553 	rqst.rq_tailsz = wdata->tailsz;
3554 #ifdef CONFIG_CIFS_SMB_DIRECT
3555 	if (wdata->mr) {
3556 		iov[0].iov_len += sizeof(struct smbd_buffer_descriptor_v1);
3557 		rqst.rq_npages = 0;
3558 	}
3559 #endif
3560 	cifs_dbg(FYI, "async write at %llu %u bytes\n",
3561 		 wdata->offset, wdata->bytes);
3562 
3563 #ifdef CONFIG_CIFS_SMB_DIRECT
3564 	/* For RDMA read, I/O size is in RemainingBytes not in Length */
3565 	if (!wdata->mr)
3566 		req->Length = cpu_to_le32(wdata->bytes);
3567 #else
3568 	req->Length = cpu_to_le32(wdata->bytes);
3569 #endif
3570 
3571 	if (wdata->credits) {
3572 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
3573 						    SMB2_MAX_BUFFER_SIZE));
3574 		shdr->CreditRequest =
3575 			cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 1);
3576 		spin_lock(&server->req_lock);
3577 		server->credits += wdata->credits -
3578 						le16_to_cpu(shdr->CreditCharge);
3579 		spin_unlock(&server->req_lock);
3580 		wake_up(&server->request_q);
3581 		wdata->credits = le16_to_cpu(shdr->CreditCharge);
3582 		flags |= CIFS_HAS_CREDITS;
3583 	}
3584 
3585 	kref_get(&wdata->refcount);
3586 	rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
3587 			     wdata, flags);
3588 
3589 	if (rc) {
3590 		trace_smb3_write_err(0 /* no xid */, req->PersistentFileId,
3591 				     tcon->tid, tcon->ses->Suid, wdata->offset,
3592 				     wdata->bytes, rc);
3593 		kref_put(&wdata->refcount, release);
3594 		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
3595 	}
3596 
3597 async_writev_out:
3598 	cifs_small_buf_release(req);
3599 	return rc;
3600 }
3601 
3602 /*
3603  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
3604  * The length field from io_parms must be at least 1 and indicates a number of
3605  * elements with data to write that begins with position 1 in iov array. All
3606  * data length is specified by count.
3607  */
3608 int
SMB2_write(const unsigned int xid,struct cifs_io_parms * io_parms,unsigned int * nbytes,struct kvec * iov,int n_vec)3609 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
3610 	   unsigned int *nbytes, struct kvec *iov, int n_vec)
3611 {
3612 	struct smb_rqst rqst;
3613 	int rc = 0;
3614 	struct smb2_write_req *req = NULL;
3615 	struct smb2_write_rsp *rsp = NULL;
3616 	int resp_buftype;
3617 	struct kvec rsp_iov;
3618 	int flags = 0;
3619 	unsigned int total_len;
3620 
3621 	*nbytes = 0;
3622 
3623 	if (n_vec < 1)
3624 		return rc;
3625 
3626 	rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, (void **) &req,
3627 			     &total_len);
3628 	if (rc)
3629 		return rc;
3630 
3631 	if (io_parms->tcon->ses->server == NULL)
3632 		return -ECONNABORTED;
3633 
3634 	if (smb3_encryption_required(io_parms->tcon))
3635 		flags |= CIFS_TRANSFORM_REQ;
3636 
3637 	req->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid);
3638 
3639 	req->PersistentFileId = io_parms->persistent_fid;
3640 	req->VolatileFileId = io_parms->volatile_fid;
3641 	req->WriteChannelInfoOffset = 0;
3642 	req->WriteChannelInfoLength = 0;
3643 	req->Channel = 0;
3644 	req->Length = cpu_to_le32(io_parms->length);
3645 	req->Offset = cpu_to_le64(io_parms->offset);
3646 	req->DataOffset = cpu_to_le16(
3647 				offsetof(struct smb2_write_req, Buffer));
3648 	req->RemainingBytes = 0;
3649 
3650 	iov[0].iov_base = (char *)req;
3651 	/* 1 for Buffer */
3652 	iov[0].iov_len = total_len - 1;
3653 
3654 	memset(&rqst, 0, sizeof(struct smb_rqst));
3655 	rqst.rq_iov = iov;
3656 	rqst.rq_nvec = n_vec + 1;
3657 
3658 	rc = cifs_send_recv(xid, io_parms->tcon->ses, &rqst,
3659 			    &resp_buftype, flags, &rsp_iov);
3660 	rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
3661 
3662 	if (rc) {
3663 		trace_smb3_write_err(xid, req->PersistentFileId,
3664 				     io_parms->tcon->tid,
3665 				     io_parms->tcon->ses->Suid,
3666 				     io_parms->offset, io_parms->length, rc);
3667 		cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
3668 		cifs_dbg(VFS, "Send error in write = %d\n", rc);
3669 	} else {
3670 		*nbytes = le32_to_cpu(rsp->DataLength);
3671 		trace_smb3_write_done(xid, req->PersistentFileId,
3672 				     io_parms->tcon->tid,
3673 				     io_parms->tcon->ses->Suid,
3674 				     io_parms->offset, *nbytes);
3675 	}
3676 
3677 	cifs_small_buf_release(req);
3678 	free_rsp_buf(resp_buftype, rsp);
3679 	return rc;
3680 }
3681 
3682 static unsigned int
num_entries(char * bufstart,char * end_of_buf,char ** lastentry,size_t size)3683 num_entries(char *bufstart, char *end_of_buf, char **lastentry, size_t size)
3684 {
3685 	int len;
3686 	unsigned int entrycount = 0;
3687 	unsigned int next_offset = 0;
3688 	char *entryptr;
3689 	FILE_DIRECTORY_INFO *dir_info;
3690 
3691 	if (bufstart == NULL)
3692 		return 0;
3693 
3694 	entryptr = bufstart;
3695 
3696 	while (1) {
3697 		if (entryptr + next_offset < entryptr ||
3698 		    entryptr + next_offset > end_of_buf ||
3699 		    entryptr + next_offset + size > end_of_buf) {
3700 			cifs_dbg(VFS, "malformed search entry would overflow\n");
3701 			break;
3702 		}
3703 
3704 		entryptr = entryptr + next_offset;
3705 		dir_info = (FILE_DIRECTORY_INFO *)entryptr;
3706 
3707 		len = le32_to_cpu(dir_info->FileNameLength);
3708 		if (entryptr + len < entryptr ||
3709 		    entryptr + len > end_of_buf ||
3710 		    entryptr + len + size > end_of_buf) {
3711 			cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
3712 				 end_of_buf);
3713 			break;
3714 		}
3715 
3716 		*lastentry = entryptr;
3717 		entrycount++;
3718 
3719 		next_offset = le32_to_cpu(dir_info->NextEntryOffset);
3720 		if (!next_offset)
3721 			break;
3722 	}
3723 
3724 	return entrycount;
3725 }
3726 
3727 /*
3728  * Readdir/FindFirst
3729  */
3730 int
SMB2_query_directory(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,int index,struct cifs_search_info * srch_inf)3731 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
3732 		     u64 persistent_fid, u64 volatile_fid, int index,
3733 		     struct cifs_search_info *srch_inf)
3734 {
3735 	struct smb_rqst rqst;
3736 	struct smb2_query_directory_req *req;
3737 	struct smb2_query_directory_rsp *rsp = NULL;
3738 	struct kvec iov[2];
3739 	struct kvec rsp_iov;
3740 	int rc = 0;
3741 	int len;
3742 	int resp_buftype = CIFS_NO_BUFFER;
3743 	unsigned char *bufptr;
3744 	struct TCP_Server_Info *server;
3745 	struct cifs_ses *ses = tcon->ses;
3746 	__le16 asteriks = cpu_to_le16('*');
3747 	char *end_of_smb;
3748 	unsigned int output_size = CIFSMaxBufSize;
3749 	size_t info_buf_size;
3750 	int flags = 0;
3751 	unsigned int total_len;
3752 
3753 	if (ses && (ses->server))
3754 		server = ses->server;
3755 	else
3756 		return -EIO;
3757 
3758 	rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, (void **) &req,
3759 			     &total_len);
3760 	if (rc)
3761 		return rc;
3762 
3763 	if (smb3_encryption_required(tcon))
3764 		flags |= CIFS_TRANSFORM_REQ;
3765 
3766 	switch (srch_inf->info_level) {
3767 	case SMB_FIND_FILE_DIRECTORY_INFO:
3768 		req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
3769 		info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
3770 		break;
3771 	case SMB_FIND_FILE_ID_FULL_DIR_INFO:
3772 		req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
3773 		info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
3774 		break;
3775 	default:
3776 		cifs_dbg(VFS, "info level %u isn't supported\n",
3777 			 srch_inf->info_level);
3778 		rc = -EINVAL;
3779 		goto qdir_exit;
3780 	}
3781 
3782 	req->FileIndex = cpu_to_le32(index);
3783 	req->PersistentFileId = persistent_fid;
3784 	req->VolatileFileId = volatile_fid;
3785 
3786 	len = 0x2;
3787 	bufptr = req->Buffer;
3788 	memcpy(bufptr, &asteriks, len);
3789 
3790 	req->FileNameOffset =
3791 		cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1);
3792 	req->FileNameLength = cpu_to_le16(len);
3793 	/*
3794 	 * BB could be 30 bytes or so longer if we used SMB2 specific
3795 	 * buffer lengths, but this is safe and close enough.
3796 	 */
3797 	output_size = min_t(unsigned int, output_size, server->maxBuf);
3798 	output_size = min_t(unsigned int, output_size, 2 << 15);
3799 	req->OutputBufferLength = cpu_to_le32(output_size);
3800 
3801 	iov[0].iov_base = (char *)req;
3802 	/* 1 for Buffer */
3803 	iov[0].iov_len = total_len - 1;
3804 
3805 	iov[1].iov_base = (char *)(req->Buffer);
3806 	iov[1].iov_len = len;
3807 
3808 	memset(&rqst, 0, sizeof(struct smb_rqst));
3809 	rqst.rq_iov = iov;
3810 	rqst.rq_nvec = 2;
3811 
3812 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
3813 	cifs_small_buf_release(req);
3814 	rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
3815 
3816 	if (rc) {
3817 		if (rc == -ENODATA &&
3818 		    rsp->sync_hdr.Status == STATUS_NO_MORE_FILES) {
3819 			srch_inf->endOfSearch = true;
3820 			rc = 0;
3821 		} else
3822 			cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
3823 		goto qdir_exit;
3824 	}
3825 
3826 	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
3827 			       le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
3828 			       info_buf_size);
3829 	if (rc)
3830 		goto qdir_exit;
3831 
3832 	srch_inf->unicode = true;
3833 
3834 	if (srch_inf->ntwrk_buf_start) {
3835 		if (srch_inf->smallBuf)
3836 			cifs_small_buf_release(srch_inf->ntwrk_buf_start);
3837 		else
3838 			cifs_buf_release(srch_inf->ntwrk_buf_start);
3839 	}
3840 	srch_inf->ntwrk_buf_start = (char *)rsp;
3841 	srch_inf->srch_entries_start = srch_inf->last_entry =
3842 		(char *)rsp + le16_to_cpu(rsp->OutputBufferOffset);
3843 	end_of_smb = rsp_iov.iov_len + (char *)rsp;
3844 	srch_inf->entries_in_buffer =
3845 			num_entries(srch_inf->srch_entries_start, end_of_smb,
3846 				    &srch_inf->last_entry, info_buf_size);
3847 	srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
3848 	cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
3849 		 srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
3850 		 srch_inf->srch_entries_start, srch_inf->last_entry);
3851 	if (resp_buftype == CIFS_LARGE_BUFFER)
3852 		srch_inf->smallBuf = false;
3853 	else if (resp_buftype == CIFS_SMALL_BUFFER)
3854 		srch_inf->smallBuf = true;
3855 	else
3856 		cifs_dbg(VFS, "illegal search buffer type\n");
3857 
3858 	return rc;
3859 
3860 qdir_exit:
3861 	free_rsp_buf(resp_buftype, rsp);
3862 	return rc;
3863 }
3864 
3865 static int
send_set_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u32 pid,u8 info_class,u8 info_type,u32 additional_info,unsigned int num,void ** data,unsigned int * size)3866 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
3867 	       u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
3868 	       u8 info_type, u32 additional_info, unsigned int num,
3869 		void **data, unsigned int *size)
3870 {
3871 	struct smb_rqst rqst;
3872 	struct smb2_set_info_req *req;
3873 	struct smb2_set_info_rsp *rsp = NULL;
3874 	struct kvec *iov;
3875 	struct kvec rsp_iov;
3876 	int rc = 0;
3877 	int resp_buftype;
3878 	unsigned int i;
3879 	struct cifs_ses *ses = tcon->ses;
3880 	int flags = 0;
3881 	unsigned int total_len;
3882 
3883 	if (!ses || !(ses->server))
3884 		return -EIO;
3885 
3886 	if (!num)
3887 		return -EINVAL;
3888 
3889 	iov = kmalloc_array(num, sizeof(struct kvec), GFP_KERNEL);
3890 	if (!iov)
3891 		return -ENOMEM;
3892 
3893 	rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, (void **) &req, &total_len);
3894 	if (rc) {
3895 		kfree(iov);
3896 		return rc;
3897 	}
3898 
3899 	if (smb3_encryption_required(tcon))
3900 		flags |= CIFS_TRANSFORM_REQ;
3901 
3902 	req->sync_hdr.ProcessId = cpu_to_le32(pid);
3903 
3904 	req->InfoType = info_type;
3905 	req->FileInfoClass = info_class;
3906 	req->PersistentFileId = persistent_fid;
3907 	req->VolatileFileId = volatile_fid;
3908 	req->AdditionalInformation = cpu_to_le32(additional_info);
3909 
3910 	req->BufferOffset =
3911 			cpu_to_le16(sizeof(struct smb2_set_info_req) - 1);
3912 	req->BufferLength = cpu_to_le32(*size);
3913 
3914 	memcpy(req->Buffer, *data, *size);
3915 	total_len += *size;
3916 
3917 	iov[0].iov_base = (char *)req;
3918 	/* 1 for Buffer */
3919 	iov[0].iov_len = total_len - 1;
3920 
3921 	for (i = 1; i < num; i++) {
3922 		le32_add_cpu(&req->BufferLength, size[i]);
3923 		iov[i].iov_base = (char *)data[i];
3924 		iov[i].iov_len = size[i];
3925 	}
3926 
3927 	memset(&rqst, 0, sizeof(struct smb_rqst));
3928 	rqst.rq_iov = iov;
3929 	rqst.rq_nvec = num;
3930 
3931 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags,
3932 			    &rsp_iov);
3933 	cifs_buf_release(req);
3934 	rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
3935 
3936 	if (rc != 0) {
3937 		cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
3938 		trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
3939 				ses->Suid, info_class, (__u32)info_type, rc);
3940 	}
3941 
3942 	free_rsp_buf(resp_buftype, rsp);
3943 	kfree(iov);
3944 	return rc;
3945 }
3946 
3947 int
SMB2_rename(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,__le16 * target_file)3948 SMB2_rename(const unsigned int xid, struct cifs_tcon *tcon,
3949 	    u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
3950 {
3951 	struct smb2_file_rename_info info;
3952 	void **data;
3953 	unsigned int size[2];
3954 	int rc;
3955 	int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
3956 
3957 	data = kmalloc_array(2, sizeof(void *), GFP_KERNEL);
3958 	if (!data)
3959 		return -ENOMEM;
3960 
3961 	info.ReplaceIfExists = 1; /* 1 = replace existing target with new */
3962 			      /* 0 = fail if target already exists */
3963 	info.RootDirectory = 0;  /* MBZ for network ops (why does spec say?) */
3964 	info.FileNameLength = cpu_to_le32(len);
3965 
3966 	data[0] = &info;
3967 	size[0] = sizeof(struct smb2_file_rename_info);
3968 
3969 	data[1] = target_file;
3970 	size[1] = len + 2 /* null */;
3971 
3972 	rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
3973 		current->tgid, FILE_RENAME_INFORMATION, SMB2_O_INFO_FILE,
3974 		0, 2, data, size);
3975 	kfree(data);
3976 	return rc;
3977 }
3978 
3979 int
SMB2_rmdir(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)3980 SMB2_rmdir(const unsigned int xid, struct cifs_tcon *tcon,
3981 		  u64 persistent_fid, u64 volatile_fid)
3982 {
3983 	__u8 delete_pending = 1;
3984 	void *data;
3985 	unsigned int size;
3986 
3987 	data = &delete_pending;
3988 	size = 1; /* sizeof __u8 */
3989 
3990 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3991 		current->tgid, FILE_DISPOSITION_INFORMATION, SMB2_O_INFO_FILE,
3992 		0, 1, &data, &size);
3993 }
3994 
3995 int
SMB2_set_hardlink(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,__le16 * target_file)3996 SMB2_set_hardlink(const unsigned int xid, struct cifs_tcon *tcon,
3997 		  u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
3998 {
3999 	struct smb2_file_link_info info;
4000 	void **data;
4001 	unsigned int size[2];
4002 	int rc;
4003 	int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
4004 
4005 	data = kmalloc_array(2, sizeof(void *), GFP_KERNEL);
4006 	if (!data)
4007 		return -ENOMEM;
4008 
4009 	info.ReplaceIfExists = 0; /* 1 = replace existing link with new */
4010 			      /* 0 = fail if link already exists */
4011 	info.RootDirectory = 0;  /* MBZ for network ops (why does spec say?) */
4012 	info.FileNameLength = cpu_to_le32(len);
4013 
4014 	data[0] = &info;
4015 	size[0] = sizeof(struct smb2_file_link_info);
4016 
4017 	data[1] = target_file;
4018 	size[1] = len + 2 /* null */;
4019 
4020 	rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
4021 			current->tgid, FILE_LINK_INFORMATION, SMB2_O_INFO_FILE,
4022 			0, 2, data, size);
4023 	kfree(data);
4024 	return rc;
4025 }
4026 
4027 int
SMB2_set_eof(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u32 pid,__le64 * eof,bool is_falloc)4028 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
4029 	     u64 volatile_fid, u32 pid, __le64 *eof, bool is_falloc)
4030 {
4031 	struct smb2_file_eof_info info;
4032 	void *data;
4033 	unsigned int size;
4034 
4035 	info.EndOfFile = *eof;
4036 
4037 	data = &info;
4038 	size = sizeof(struct smb2_file_eof_info);
4039 
4040 	if (is_falloc)
4041 		return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4042 			pid, FILE_ALLOCATION_INFORMATION, SMB2_O_INFO_FILE,
4043 			0, 1, &data, &size);
4044 	else
4045 		return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4046 			pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
4047 			0, 1, &data, &size);
4048 }
4049 
4050 int
SMB2_set_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,FILE_BASIC_INFO * buf)4051 SMB2_set_info(const unsigned int xid, struct cifs_tcon *tcon,
4052 	      u64 persistent_fid, u64 volatile_fid, FILE_BASIC_INFO *buf)
4053 {
4054 	unsigned int size;
4055 	size = sizeof(FILE_BASIC_INFO);
4056 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4057 		current->tgid, FILE_BASIC_INFORMATION, SMB2_O_INFO_FILE,
4058 		0, 1, (void **)&buf, &size);
4059 }
4060 
4061 int
SMB2_set_acl(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct cifs_ntsd * pnntsd,int pacllen,int aclflag)4062 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
4063 		u64 persistent_fid, u64 volatile_fid,
4064 		struct cifs_ntsd *pnntsd, int pacllen, int aclflag)
4065 {
4066 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4067 			current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
4068 			1, (void **)&pnntsd, &pacllen);
4069 }
4070 
4071 int
SMB2_set_ea(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct smb2_file_full_ea_info * buf,int len)4072 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
4073 	    u64 persistent_fid, u64 volatile_fid,
4074 	    struct smb2_file_full_ea_info *buf, int len)
4075 {
4076 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
4077 		current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
4078 		0, 1, (void **)&buf, &len);
4079 }
4080 
4081 int
SMB2_oplock_break(const unsigned int xid,struct cifs_tcon * tcon,const u64 persistent_fid,const u64 volatile_fid,__u8 oplock_level)4082 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
4083 		  const u64 persistent_fid, const u64 volatile_fid,
4084 		  __u8 oplock_level)
4085 {
4086 	struct smb_rqst rqst;
4087 	int rc;
4088 	struct smb2_oplock_break *req = NULL;
4089 	struct cifs_ses *ses = tcon->ses;
4090 	int flags = CIFS_OBREAK_OP;
4091 	unsigned int total_len;
4092 	struct kvec iov[1];
4093 	struct kvec rsp_iov;
4094 	int resp_buf_type;
4095 
4096 	cifs_dbg(FYI, "SMB2_oplock_break\n");
4097 	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req,
4098 			     &total_len);
4099 	if (rc)
4100 		return rc;
4101 
4102 	if (smb3_encryption_required(tcon))
4103 		flags |= CIFS_TRANSFORM_REQ;
4104 
4105 	req->VolatileFid = volatile_fid;
4106 	req->PersistentFid = persistent_fid;
4107 	req->OplockLevel = oplock_level;
4108 	req->sync_hdr.CreditRequest = cpu_to_le16(1);
4109 
4110 	flags |= CIFS_NO_RESP;
4111 
4112 	iov[0].iov_base = (char *)req;
4113 	iov[0].iov_len = total_len;
4114 
4115 	memset(&rqst, 0, sizeof(struct smb_rqst));
4116 	rqst.rq_iov = iov;
4117 	rqst.rq_nvec = 1;
4118 
4119 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buf_type, flags, &rsp_iov);
4120 	cifs_small_buf_release(req);
4121 
4122 	if (rc) {
4123 		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
4124 		cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
4125 	}
4126 
4127 	return rc;
4128 }
4129 
4130 void
smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info * pfs_inf,struct kstatfs * kst)4131 smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
4132 			     struct kstatfs *kst)
4133 {
4134 	kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
4135 			  le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
4136 	kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
4137 	kst->f_bfree  = kst->f_bavail =
4138 			le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
4139 	return;
4140 }
4141 
4142 static void
copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO * response_data,struct kstatfs * kst)4143 copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data,
4144 			struct kstatfs *kst)
4145 {
4146 	kst->f_bsize = le32_to_cpu(response_data->BlockSize);
4147 	kst->f_blocks = le64_to_cpu(response_data->TotalBlocks);
4148 	kst->f_bfree =  le64_to_cpu(response_data->BlocksAvail);
4149 	if (response_data->UserBlocksAvail == cpu_to_le64(-1))
4150 		kst->f_bavail = kst->f_bfree;
4151 	else
4152 		kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail);
4153 	if (response_data->TotalFileNodes != cpu_to_le64(-1))
4154 		kst->f_files = le64_to_cpu(response_data->TotalFileNodes);
4155 	if (response_data->FreeFileNodes != cpu_to_le64(-1))
4156 		kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes);
4157 
4158 	return;
4159 }
4160 
4161 static int
build_qfs_info_req(struct kvec * iov,struct cifs_tcon * tcon,int level,int outbuf_len,u64 persistent_fid,u64 volatile_fid)4162 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon, int level,
4163 		   int outbuf_len, u64 persistent_fid, u64 volatile_fid)
4164 {
4165 	struct TCP_Server_Info *server;
4166 	int rc;
4167 	struct smb2_query_info_req *req;
4168 	unsigned int total_len;
4169 
4170 	cifs_dbg(FYI, "Query FSInfo level %d\n", level);
4171 
4172 	if ((tcon->ses == NULL) || (tcon->ses->server == NULL))
4173 		return -EIO;
4174 
4175 	server = tcon->ses->server;
4176 
4177 	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, (void **) &req,
4178 			     &total_len);
4179 	if (rc)
4180 		return rc;
4181 
4182 	req->InfoType = SMB2_O_INFO_FILESYSTEM;
4183 	req->FileInfoClass = level;
4184 	req->PersistentFileId = persistent_fid;
4185 	req->VolatileFileId = volatile_fid;
4186 	/* 1 for pad */
4187 	req->InputBufferOffset =
4188 			cpu_to_le16(sizeof(struct smb2_query_info_req) - 1);
4189 	req->OutputBufferLength = cpu_to_le32(
4190 		outbuf_len + sizeof(struct smb2_query_info_rsp) - 1);
4191 
4192 	iov->iov_base = (char *)req;
4193 	iov->iov_len = total_len;
4194 	return 0;
4195 }
4196 
4197 int
SMB311_posix_qfs_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct kstatfs * fsdata)4198 SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon,
4199 	      u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
4200 {
4201 	struct smb_rqst rqst;
4202 	struct smb2_query_info_rsp *rsp = NULL;
4203 	struct kvec iov;
4204 	struct kvec rsp_iov;
4205 	int rc = 0;
4206 	int resp_buftype;
4207 	struct cifs_ses *ses = tcon->ses;
4208 	FILE_SYSTEM_POSIX_INFO *info = NULL;
4209 	int flags = 0;
4210 
4211 	rc = build_qfs_info_req(&iov, tcon, FS_POSIX_INFORMATION,
4212 				sizeof(FILE_SYSTEM_POSIX_INFO),
4213 				persistent_fid, volatile_fid);
4214 	if (rc)
4215 		return rc;
4216 
4217 	if (smb3_encryption_required(tcon))
4218 		flags |= CIFS_TRANSFORM_REQ;
4219 
4220 	memset(&rqst, 0, sizeof(struct smb_rqst));
4221 	rqst.rq_iov = &iov;
4222 	rqst.rq_nvec = 1;
4223 
4224 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
4225 	cifs_small_buf_release(iov.iov_base);
4226 	if (rc) {
4227 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
4228 		goto posix_qfsinf_exit;
4229 	}
4230 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
4231 
4232 	info = (FILE_SYSTEM_POSIX_INFO *)(
4233 		le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
4234 	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
4235 			       le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
4236 			       sizeof(FILE_SYSTEM_POSIX_INFO));
4237 	if (!rc)
4238 		copy_posix_fs_info_to_kstatfs(info, fsdata);
4239 
4240 posix_qfsinf_exit:
4241 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4242 	return rc;
4243 }
4244 
4245 int
SMB2_QFS_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct kstatfs * fsdata)4246 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
4247 	      u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
4248 {
4249 	struct smb_rqst rqst;
4250 	struct smb2_query_info_rsp *rsp = NULL;
4251 	struct kvec iov;
4252 	struct kvec rsp_iov;
4253 	int rc = 0;
4254 	int resp_buftype;
4255 	struct cifs_ses *ses = tcon->ses;
4256 	struct smb2_fs_full_size_info *info = NULL;
4257 	int flags = 0;
4258 
4259 	rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION,
4260 				sizeof(struct smb2_fs_full_size_info),
4261 				persistent_fid, volatile_fid);
4262 	if (rc)
4263 		return rc;
4264 
4265 	if (smb3_encryption_required(tcon))
4266 		flags |= CIFS_TRANSFORM_REQ;
4267 
4268 	memset(&rqst, 0, sizeof(struct smb_rqst));
4269 	rqst.rq_iov = &iov;
4270 	rqst.rq_nvec = 1;
4271 
4272 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
4273 	cifs_small_buf_release(iov.iov_base);
4274 	if (rc) {
4275 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
4276 		goto qfsinf_exit;
4277 	}
4278 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
4279 
4280 	info = (struct smb2_fs_full_size_info *)(
4281 		le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
4282 	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
4283 			       le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
4284 			       sizeof(struct smb2_fs_full_size_info));
4285 	if (!rc)
4286 		smb2_copy_fs_info_to_kstatfs(info, fsdata);
4287 
4288 qfsinf_exit:
4289 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4290 	return rc;
4291 }
4292 
4293 int
SMB2_QFS_attr(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,int level)4294 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
4295 	      u64 persistent_fid, u64 volatile_fid, int level)
4296 {
4297 	struct smb_rqst rqst;
4298 	struct smb2_query_info_rsp *rsp = NULL;
4299 	struct kvec iov;
4300 	struct kvec rsp_iov;
4301 	int rc = 0;
4302 	int resp_buftype, max_len, min_len;
4303 	struct cifs_ses *ses = tcon->ses;
4304 	unsigned int rsp_len, offset;
4305 	int flags = 0;
4306 
4307 	if (level == FS_DEVICE_INFORMATION) {
4308 		max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
4309 		min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
4310 	} else if (level == FS_ATTRIBUTE_INFORMATION) {
4311 		max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
4312 		min_len = MIN_FS_ATTR_INFO_SIZE;
4313 	} else if (level == FS_SECTOR_SIZE_INFORMATION) {
4314 		max_len = sizeof(struct smb3_fs_ss_info);
4315 		min_len = sizeof(struct smb3_fs_ss_info);
4316 	} else if (level == FS_VOLUME_INFORMATION) {
4317 		max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN;
4318 		min_len = sizeof(struct smb3_fs_vol_info);
4319 	} else {
4320 		cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
4321 		return -EINVAL;
4322 	}
4323 
4324 	rc = build_qfs_info_req(&iov, tcon, level, max_len,
4325 				persistent_fid, volatile_fid);
4326 	if (rc)
4327 		return rc;
4328 
4329 	if (smb3_encryption_required(tcon))
4330 		flags |= CIFS_TRANSFORM_REQ;
4331 
4332 	memset(&rqst, 0, sizeof(struct smb_rqst));
4333 	rqst.rq_iov = &iov;
4334 	rqst.rq_nvec = 1;
4335 
4336 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
4337 	cifs_small_buf_release(iov.iov_base);
4338 	if (rc) {
4339 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
4340 		goto qfsattr_exit;
4341 	}
4342 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
4343 
4344 	rsp_len = le32_to_cpu(rsp->OutputBufferLength);
4345 	offset = le16_to_cpu(rsp->OutputBufferOffset);
4346 	rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
4347 	if (rc)
4348 		goto qfsattr_exit;
4349 
4350 	if (level == FS_ATTRIBUTE_INFORMATION)
4351 		memcpy(&tcon->fsAttrInfo, offset
4352 			+ (char *)rsp, min_t(unsigned int,
4353 			rsp_len, max_len));
4354 	else if (level == FS_DEVICE_INFORMATION)
4355 		memcpy(&tcon->fsDevInfo, offset
4356 			+ (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
4357 	else if (level == FS_SECTOR_SIZE_INFORMATION) {
4358 		struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
4359 			(offset + (char *)rsp);
4360 		tcon->ss_flags = le32_to_cpu(ss_info->Flags);
4361 		tcon->perf_sector_size =
4362 			le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
4363 	} else if (level == FS_VOLUME_INFORMATION) {
4364 		struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *)
4365 			(offset + (char *)rsp);
4366 		tcon->vol_serial_number = vol_info->VolumeSerialNumber;
4367 		tcon->vol_create_time = vol_info->VolumeCreationTime;
4368 	}
4369 
4370 qfsattr_exit:
4371 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4372 	return rc;
4373 }
4374 
4375 int
smb2_lockv(const unsigned int xid,struct cifs_tcon * tcon,const __u64 persist_fid,const __u64 volatile_fid,const __u32 pid,const __u32 num_lock,struct smb2_lock_element * buf)4376 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
4377 	   const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
4378 	   const __u32 num_lock, struct smb2_lock_element *buf)
4379 {
4380 	struct smb_rqst rqst;
4381 	int rc = 0;
4382 	struct smb2_lock_req *req = NULL;
4383 	struct kvec iov[2];
4384 	struct kvec rsp_iov;
4385 	int resp_buf_type;
4386 	unsigned int count;
4387 	int flags = CIFS_NO_RESP;
4388 	unsigned int total_len;
4389 
4390 	cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
4391 
4392 	rc = smb2_plain_req_init(SMB2_LOCK, tcon, (void **) &req, &total_len);
4393 	if (rc)
4394 		return rc;
4395 
4396 	if (smb3_encryption_required(tcon))
4397 		flags |= CIFS_TRANSFORM_REQ;
4398 
4399 	req->sync_hdr.ProcessId = cpu_to_le32(pid);
4400 	req->LockCount = cpu_to_le16(num_lock);
4401 
4402 	req->PersistentFileId = persist_fid;
4403 	req->VolatileFileId = volatile_fid;
4404 
4405 	count = num_lock * sizeof(struct smb2_lock_element);
4406 
4407 	iov[0].iov_base = (char *)req;
4408 	iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
4409 	iov[1].iov_base = (char *)buf;
4410 	iov[1].iov_len = count;
4411 
4412 	cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
4413 
4414 	memset(&rqst, 0, sizeof(struct smb_rqst));
4415 	rqst.rq_iov = iov;
4416 	rqst.rq_nvec = 2;
4417 
4418 	rc = cifs_send_recv(xid, tcon->ses, &rqst, &resp_buf_type, flags,
4419 			    &rsp_iov);
4420 	cifs_small_buf_release(req);
4421 	if (rc) {
4422 		cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
4423 		cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
4424 		trace_smb3_lock_err(xid, persist_fid, tcon->tid,
4425 				    tcon->ses->Suid, rc);
4426 	}
4427 
4428 	return rc;
4429 }
4430 
4431 int
SMB2_lock(const unsigned int xid,struct cifs_tcon * tcon,const __u64 persist_fid,const __u64 volatile_fid,const __u32 pid,const __u64 length,const __u64 offset,const __u32 lock_flags,const bool wait)4432 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
4433 	  const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
4434 	  const __u64 length, const __u64 offset, const __u32 lock_flags,
4435 	  const bool wait)
4436 {
4437 	struct smb2_lock_element lock;
4438 
4439 	lock.Offset = cpu_to_le64(offset);
4440 	lock.Length = cpu_to_le64(length);
4441 	lock.Flags = cpu_to_le32(lock_flags);
4442 	if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
4443 		lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
4444 
4445 	return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
4446 }
4447 
4448 int
SMB2_lease_break(const unsigned int xid,struct cifs_tcon * tcon,__u8 * lease_key,const __le32 lease_state)4449 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
4450 		 __u8 *lease_key, const __le32 lease_state)
4451 {
4452 	struct smb_rqst rqst;
4453 	int rc;
4454 	struct smb2_lease_ack *req = NULL;
4455 	struct cifs_ses *ses = tcon->ses;
4456 	int flags = CIFS_OBREAK_OP;
4457 	unsigned int total_len;
4458 	struct kvec iov[1];
4459 	struct kvec rsp_iov;
4460 	int resp_buf_type;
4461 
4462 	cifs_dbg(FYI, "SMB2_lease_break\n");
4463 	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req,
4464 			     &total_len);
4465 	if (rc)
4466 		return rc;
4467 
4468 	if (smb3_encryption_required(tcon))
4469 		flags |= CIFS_TRANSFORM_REQ;
4470 
4471 	req->sync_hdr.CreditRequest = cpu_to_le16(1);
4472 	req->StructureSize = cpu_to_le16(36);
4473 	total_len += 12;
4474 
4475 	memcpy(req->LeaseKey, lease_key, 16);
4476 	req->LeaseState = lease_state;
4477 
4478 	flags |= CIFS_NO_RESP;
4479 
4480 	iov[0].iov_base = (char *)req;
4481 	iov[0].iov_len = total_len;
4482 
4483 	memset(&rqst, 0, sizeof(struct smb_rqst));
4484 	rqst.rq_iov = iov;
4485 	rqst.rq_nvec = 1;
4486 
4487 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buf_type, flags, &rsp_iov);
4488 	cifs_small_buf_release(req);
4489 
4490 	if (rc) {
4491 		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
4492 		cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
4493 	}
4494 
4495 	return rc;
4496 }
4497