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