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