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