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