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