• 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 
52 /*
53  *  The following table defines the expected "StructureSize" of SMB2 requests
54  *  in order by SMB2 command.  This is similar to "wct" in SMB/CIFS requests.
55  *
56  *  Note that commands are defined in smb2pdu.h in le16 but the array below is
57  *  indexed by command in host byte order.
58  */
59 static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
60 	/* SMB2_NEGOTIATE */ 36,
61 	/* SMB2_SESSION_SETUP */ 25,
62 	/* SMB2_LOGOFF */ 4,
63 	/* SMB2_TREE_CONNECT */	9,
64 	/* SMB2_TREE_DISCONNECT */ 4,
65 	/* SMB2_CREATE */ 57,
66 	/* SMB2_CLOSE */ 24,
67 	/* SMB2_FLUSH */ 24,
68 	/* SMB2_READ */	49,
69 	/* SMB2_WRITE */ 49,
70 	/* SMB2_LOCK */	48,
71 	/* SMB2_IOCTL */ 57,
72 	/* SMB2_CANCEL */ 4,
73 	/* SMB2_ECHO */ 4,
74 	/* SMB2_QUERY_DIRECTORY */ 33,
75 	/* SMB2_CHANGE_NOTIFY */ 32,
76 	/* SMB2_QUERY_INFO */ 41,
77 	/* SMB2_SET_INFO */ 33,
78 	/* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
79 };
80 
encryption_required(const struct cifs_tcon * tcon)81 static int encryption_required(const struct cifs_tcon *tcon)
82 {
83 	if (!tcon)
84 		return 0;
85 	if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) ||
86 	    (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA))
87 		return 1;
88 	if (tcon->seal &&
89 	    (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
90 		return 1;
91 	return 0;
92 }
93 
94 static void
smb2_hdr_assemble(struct smb2_sync_hdr * shdr,__le16 smb2_cmd,const struct cifs_tcon * tcon)95 smb2_hdr_assemble(struct smb2_sync_hdr *shdr, __le16 smb2_cmd,
96 		  const struct cifs_tcon *tcon)
97 {
98 	shdr->ProtocolId = SMB2_PROTO_NUMBER;
99 	shdr->StructureSize = cpu_to_le16(64);
100 	shdr->Command = smb2_cmd;
101 	if (tcon && tcon->ses && tcon->ses->server) {
102 		struct TCP_Server_Info *server = tcon->ses->server;
103 
104 		spin_lock(&server->req_lock);
105 		/* Request up to 2 credits but don't go over the limit. */
106 		if (server->credits >= server->max_credits)
107 			shdr->CreditRequest = cpu_to_le16(0);
108 		else
109 			shdr->CreditRequest = cpu_to_le16(
110 				min_t(int, server->max_credits -
111 						server->credits, 2));
112 		spin_unlock(&server->req_lock);
113 	} else {
114 		shdr->CreditRequest = cpu_to_le16(2);
115 	}
116 	shdr->ProcessId = cpu_to_le32((__u16)current->tgid);
117 
118 	if (!tcon)
119 		goto out;
120 
121 	/* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
122 	/* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
123 	if ((tcon->ses) && (tcon->ses->server) &&
124 	    (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
125 		shdr->CreditCharge = cpu_to_le16(1);
126 	/* else CreditCharge MBZ */
127 
128 	shdr->TreeId = tcon->tid;
129 	/* Uid is not converted */
130 	if (tcon->ses)
131 		shdr->SessionId = tcon->ses->Suid;
132 
133 	/*
134 	 * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
135 	 * to pass the path on the Open SMB prefixed by \\server\share.
136 	 * Not sure when we would need to do the augmented path (if ever) and
137 	 * setting this flag breaks the SMB2 open operation since it is
138 	 * illegal to send an empty path name (without \\server\share prefix)
139 	 * when the DFS flag is set in the SMB open header. We could
140 	 * consider setting the flag on all operations other than open
141 	 * but it is safer to net set it for now.
142 	 */
143 /*	if (tcon->share_flags & SHI1005_FLAGS_DFS)
144 		shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
145 
146 	if (tcon->ses && tcon->ses->server && tcon->ses->server->sign &&
147 	    !encryption_required(tcon))
148 		shdr->Flags |= SMB2_FLAGS_SIGNED;
149 out:
150 	return;
151 }
152 
153 static int
smb2_reconnect(__le16 smb2_command,struct cifs_tcon * tcon)154 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon)
155 {
156 	int rc;
157 	struct nls_table *nls_codepage;
158 	struct cifs_ses *ses;
159 	struct TCP_Server_Info *server;
160 
161 	/*
162 	 * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
163 	 * check for tcp and smb session status done differently
164 	 * for those three - in the calling routine.
165 	 */
166 	if (tcon == NULL)
167 		return 0;
168 
169 	if (smb2_command == SMB2_TREE_CONNECT || smb2_command == SMB2_IOCTL)
170 		return 0;
171 
172 	if (tcon->tidStatus == CifsExiting) {
173 		/*
174 		 * only tree disconnect, open, and write,
175 		 * (and ulogoff which does not have tcon)
176 		 * are allowed as we start force umount.
177 		 */
178 		if ((smb2_command != SMB2_WRITE) &&
179 		   (smb2_command != SMB2_CREATE) &&
180 		   (smb2_command != SMB2_TREE_DISCONNECT)) {
181 			cifs_dbg(FYI, "can not send cmd %d while umounting\n",
182 				 smb2_command);
183 			return -ENODEV;
184 		}
185 	}
186 	if ((!tcon->ses) || (tcon->ses->status == CifsExiting) ||
187 	    (!tcon->ses->server))
188 		return -EIO;
189 
190 	ses = tcon->ses;
191 	server = ses->server;
192 
193 	/*
194 	 * Give demultiplex thread up to 10 seconds to reconnect, should be
195 	 * greater than cifs socket timeout which is 7 seconds
196 	 */
197 	while (server->tcpStatus == CifsNeedReconnect) {
198 		/*
199 		 * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
200 		 * here since they are implicitly done when session drops.
201 		 */
202 		switch (smb2_command) {
203 		/*
204 		 * BB Should we keep oplock break and add flush to exceptions?
205 		 */
206 		case SMB2_TREE_DISCONNECT:
207 		case SMB2_CANCEL:
208 		case SMB2_CLOSE:
209 		case SMB2_OPLOCK_BREAK:
210 			return -EAGAIN;
211 		}
212 
213 		rc = wait_event_interruptible_timeout(server->response_q,
214 						      (server->tcpStatus != CifsNeedReconnect),
215 						      10 * HZ);
216 		if (rc < 0) {
217 			cifs_dbg(FYI, "%s: aborting reconnect due to a received"
218 				 " signal by the process\n", __func__);
219 			return -ERESTARTSYS;
220 		}
221 
222 		/* are we still trying to reconnect? */
223 		if (server->tcpStatus != CifsNeedReconnect)
224 			break;
225 
226 		/*
227 		 * on "soft" mounts we wait once. Hard mounts keep
228 		 * retrying until process is killed or server comes
229 		 * back on-line
230 		 */
231 		if (!tcon->retry) {
232 			cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n");
233 			return -EHOSTDOWN;
234 		}
235 	}
236 
237 	if (!tcon->ses->need_reconnect && !tcon->need_reconnect)
238 		return 0;
239 
240 	nls_codepage = load_nls_default();
241 
242 	/*
243 	 * need to prevent multiple threads trying to simultaneously reconnect
244 	 * the same SMB session
245 	 */
246 	mutex_lock(&tcon->ses->session_mutex);
247 
248 	/*
249 	 * Recheck after acquire mutex. If another thread is negotiating
250 	 * and the server never sends an answer the socket will be closed
251 	 * and tcpStatus set to reconnect.
252 	 */
253 	if (server->tcpStatus == CifsNeedReconnect) {
254 		rc = -EHOSTDOWN;
255 		mutex_unlock(&tcon->ses->session_mutex);
256 		goto out;
257 	}
258 
259 	rc = cifs_negotiate_protocol(0, tcon->ses);
260 	if (!rc && tcon->ses->need_reconnect) {
261 		rc = cifs_setup_session(0, tcon->ses, nls_codepage);
262 		if ((rc == -EACCES) && !tcon->retry) {
263 			rc = -EHOSTDOWN;
264 			mutex_unlock(&tcon->ses->session_mutex);
265 			goto failed;
266 		}
267 	}
268 	if (rc || !tcon->need_reconnect) {
269 		mutex_unlock(&tcon->ses->session_mutex);
270 		goto out;
271 	}
272 
273 	cifs_mark_open_files_invalid(tcon);
274 	if (tcon->use_persistent)
275 		tcon->need_reopen_files = true;
276 
277 	rc = SMB2_tcon(0, tcon->ses, tcon->treeName, tcon, nls_codepage);
278 	mutex_unlock(&tcon->ses->session_mutex);
279 
280 	cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
281 	if (rc)
282 		goto out;
283 
284 	if (smb2_command != SMB2_INTERNAL_CMD)
285 		queue_delayed_work(cifsiod_wq, &server->reconnect, 0);
286 
287 	atomic_inc(&tconInfoReconnectCount);
288 out:
289 	/*
290 	 * Check if handle based operation so we know whether we can continue
291 	 * or not without returning to caller to reset file handle.
292 	 */
293 	/*
294 	 * BB Is flush done by server on drop of tcp session? Should we special
295 	 * case it and skip above?
296 	 */
297 	switch (smb2_command) {
298 	case SMB2_FLUSH:
299 	case SMB2_READ:
300 	case SMB2_WRITE:
301 	case SMB2_LOCK:
302 	case SMB2_IOCTL:
303 	case SMB2_QUERY_DIRECTORY:
304 	case SMB2_CHANGE_NOTIFY:
305 	case SMB2_QUERY_INFO:
306 	case SMB2_SET_INFO:
307 		rc = -EAGAIN;
308 	}
309 failed:
310 	unload_nls(nls_codepage);
311 	return rc;
312 }
313 
314 static void
fill_small_buf(__le16 smb2_command,struct cifs_tcon * tcon,void * buf,unsigned int * total_len)315 fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon, void *buf,
316 	       unsigned int *total_len)
317 {
318 	struct smb2_sync_pdu *spdu = (struct smb2_sync_pdu *)buf;
319 	/* lookup word count ie StructureSize from table */
320 	__u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)];
321 
322 	/*
323 	 * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
324 	 * largest operations (Create)
325 	 */
326 	memset(buf, 0, 256);
327 
328 	smb2_hdr_assemble(&spdu->sync_hdr, smb2_command, tcon);
329 	spdu->StructureSize2 = cpu_to_le16(parmsize);
330 
331 	*total_len = parmsize + sizeof(struct smb2_sync_hdr);
332 }
333 
334 /* init request without RFC1001 length at the beginning */
335 static int
smb2_plain_req_init(__le16 smb2_command,struct cifs_tcon * tcon,void ** request_buf,unsigned int * total_len)336 smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
337 		    void **request_buf, unsigned int *total_len)
338 {
339 	int rc;
340 	struct smb2_sync_hdr *shdr;
341 
342 	rc = smb2_reconnect(smb2_command, tcon);
343 	if (rc)
344 		return rc;
345 
346 	/* BB eventually switch this to SMB2 specific small buf size */
347 	*request_buf = cifs_small_buf_get();
348 	if (*request_buf == NULL) {
349 		/* BB should we add a retry in here if not a writepage? */
350 		return -ENOMEM;
351 	}
352 
353 	shdr = (struct smb2_sync_hdr *)(*request_buf);
354 
355 	fill_small_buf(smb2_command, tcon, shdr, total_len);
356 
357 	if (tcon != NULL) {
358 #ifdef CONFIG_CIFS_STATS2
359 		uint16_t com_code = le16_to_cpu(smb2_command);
360 
361 		cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
362 #endif
363 		cifs_stats_inc(&tcon->num_smbs_sent);
364 	}
365 
366 	return rc;
367 }
368 
369 /*
370  * Allocate and return pointer to an SMB request hdr, and set basic
371  * SMB information in the SMB header. If the return code is zero, this
372  * function must have filled in request_buf pointer. The returned buffer
373  * has RFC1001 length at the beginning.
374  */
375 static int
small_smb2_init(__le16 smb2_command,struct cifs_tcon * tcon,void ** request_buf)376 small_smb2_init(__le16 smb2_command, struct cifs_tcon *tcon,
377 		void **request_buf)
378 {
379 	int rc;
380 	unsigned int total_len;
381 	struct smb2_pdu *pdu;
382 
383 	rc = smb2_reconnect(smb2_command, tcon);
384 	if (rc)
385 		return rc;
386 
387 	/* BB eventually switch this to SMB2 specific small buf size */
388 	*request_buf = cifs_small_buf_get();
389 	if (*request_buf == NULL) {
390 		/* BB should we add a retry in here if not a writepage? */
391 		return -ENOMEM;
392 	}
393 
394 	pdu = (struct smb2_pdu *)(*request_buf);
395 
396 	fill_small_buf(smb2_command, tcon, get_sync_hdr(pdu), &total_len);
397 
398 	/* Note this is only network field converted to big endian */
399 	pdu->hdr.smb2_buf_length = cpu_to_be32(total_len);
400 
401 	if (tcon != NULL) {
402 #ifdef CONFIG_CIFS_STATS
403 		uint16_t com_code = le16_to_cpu(smb2_command);
404 		cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
405 #endif
406 		cifs_stats_inc(&tcon->num_smbs_sent);
407 	}
408 
409 	return rc;
410 }
411 
412 #ifdef CONFIG_CIFS_SMB311
413 /* offset is sizeof smb2_negotiate_req - 4 but rounded up to 8 bytes */
414 #define OFFSET_OF_NEG_CONTEXT 0x68  /* sizeof(struct smb2_negotiate_req) - 4 */
415 
416 
417 #define SMB2_PREAUTH_INTEGRITY_CAPABILITIES	cpu_to_le16(1)
418 #define SMB2_ENCRYPTION_CAPABILITIES		cpu_to_le16(2)
419 
420 static void
build_preauth_ctxt(struct smb2_preauth_neg_context * pneg_ctxt)421 build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
422 {
423 	pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
424 	pneg_ctxt->DataLength = cpu_to_le16(38);
425 	pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
426 	pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
427 	get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
428 	pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
429 }
430 
431 static void
build_encrypt_ctxt(struct smb2_encryption_neg_context * pneg_ctxt)432 build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
433 {
434 	pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
435 	pneg_ctxt->DataLength = cpu_to_le16(6);
436 	pneg_ctxt->CipherCount = cpu_to_le16(2);
437 	pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
438 	pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM;
439 }
440 
441 static void
assemble_neg_contexts(struct smb2_negotiate_req * req)442 assemble_neg_contexts(struct smb2_negotiate_req *req)
443 {
444 
445 	/* +4 is to account for the RFC1001 len field */
446 	char *pneg_ctxt = (char *)req + OFFSET_OF_NEG_CONTEXT + 4;
447 
448 	build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
449 	/* Add 2 to size to round to 8 byte boundary */
450 	pneg_ctxt += 2 + sizeof(struct smb2_preauth_neg_context);
451 	build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
452 	req->NegotiateContextOffset = cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
453 	req->NegotiateContextCount = cpu_to_le16(2);
454 	inc_rfc1001_len(req, 4 + sizeof(struct smb2_preauth_neg_context)
455 			+ sizeof(struct smb2_encryption_neg_context)); /* calculate hash */
456 }
457 #else
assemble_neg_contexts(struct smb2_negotiate_req * req)458 static void assemble_neg_contexts(struct smb2_negotiate_req *req)
459 {
460 	return;
461 }
462 #endif /* SMB311 */
463 
464 /*
465  *
466  *	SMB2 Worker functions follow:
467  *
468  *	The general structure of the worker functions is:
469  *	1) Call smb2_init (assembles SMB2 header)
470  *	2) Initialize SMB2 command specific fields in fixed length area of SMB
471  *	3) Call smb_sendrcv2 (sends request on socket and waits for response)
472  *	4) Decode SMB2 command specific fields in the fixed length area
473  *	5) Decode variable length data area (if any for this SMB2 command type)
474  *	6) Call free smb buffer
475  *	7) return
476  *
477  */
478 
479 int
SMB2_negotiate(const unsigned int xid,struct cifs_ses * ses)480 SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)
481 {
482 	struct smb2_negotiate_req *req;
483 	struct smb2_negotiate_rsp *rsp;
484 	struct kvec iov[1];
485 	struct kvec rsp_iov;
486 	int rc = 0;
487 	int resp_buftype;
488 	struct TCP_Server_Info *server = ses->server;
489 	int blob_offset, blob_length;
490 	char *security_blob;
491 	int flags = CIFS_NEG_OP;
492 
493 	cifs_dbg(FYI, "Negotiate protocol\n");
494 
495 	if (!server) {
496 		WARN(1, "%s: server is NULL!\n", __func__);
497 		return -EIO;
498 	}
499 
500 	rc = small_smb2_init(SMB2_NEGOTIATE, NULL, (void **) &req);
501 	if (rc)
502 		return rc;
503 
504 	req->hdr.sync_hdr.SessionId = 0;
505 
506 	if (strcmp(ses->server->vals->version_string,
507 		   SMB3ANY_VERSION_STRING) == 0) {
508 		req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
509 		req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
510 		req->DialectCount = cpu_to_le16(2);
511 		inc_rfc1001_len(req, 4);
512 	} else if (strcmp(ses->server->vals->version_string,
513 		   SMBDEFAULT_VERSION_STRING) == 0) {
514 		req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
515 		req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
516 		req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
517 		req->DialectCount = cpu_to_le16(3);
518 		inc_rfc1001_len(req, 6);
519 	} else {
520 		/* otherwise send specific dialect */
521 		req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id);
522 		req->DialectCount = cpu_to_le16(1);
523 		inc_rfc1001_len(req, 2);
524 	}
525 
526 	/* only one of SMB2 signing flags may be set in SMB2 request */
527 	if (ses->sign)
528 		req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
529 	else if (global_secflags & CIFSSEC_MAY_SIGN)
530 		req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
531 	else
532 		req->SecurityMode = 0;
533 
534 	req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities);
535 
536 	/* ClientGUID must be zero for SMB2.02 dialect */
537 	if (ses->server->vals->protocol_id == SMB20_PROT_ID)
538 		memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
539 	else {
540 		memcpy(req->ClientGUID, server->client_guid,
541 			SMB2_CLIENT_GUID_SIZE);
542 		if (ses->server->vals->protocol_id == SMB311_PROT_ID)
543 			assemble_neg_contexts(req);
544 	}
545 	iov[0].iov_base = (char *)req;
546 	/* 4 for rfc1002 length field */
547 	iov[0].iov_len = get_rfc1002_length(req) + 4;
548 
549 	rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
550 	cifs_small_buf_release(req);
551 	rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
552 	/*
553 	 * No tcon so can't do
554 	 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
555 	 */
556 	if (rc == -EOPNOTSUPP) {
557 		cifs_dbg(VFS, "Dialect not supported by server. Consider "
558 			"specifying vers=1.0 or vers=2.0 on mount for accessing"
559 			" older servers\n");
560 		goto neg_exit;
561 	} else if (rc != 0)
562 		goto neg_exit;
563 
564 	if (strcmp(ses->server->vals->version_string,
565 		   SMB3ANY_VERSION_STRING) == 0) {
566 		if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
567 			cifs_dbg(VFS,
568 				"SMB2 dialect returned but not requested\n");
569 			return -EIO;
570 		} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
571 			cifs_dbg(VFS,
572 				"SMB2.1 dialect returned but not requested\n");
573 			return -EIO;
574 		}
575 	} else if (strcmp(ses->server->vals->version_string,
576 		   SMBDEFAULT_VERSION_STRING) == 0) {
577 		if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
578 			cifs_dbg(VFS,
579 				"SMB2 dialect returned but not requested\n");
580 			return -EIO;
581 		} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
582 			/* ops set to 3.0 by default for default so update */
583 			ses->server->ops = &smb21_operations;
584 			ses->server->vals = &smb21_values;
585 		}
586 	} else if (le16_to_cpu(rsp->DialectRevision) !=
587 				ses->server->vals->protocol_id) {
588 		/* if requested single dialect ensure returned dialect matched */
589 		cifs_dbg(VFS, "Illegal 0x%x dialect returned: not requested\n",
590 			le16_to_cpu(rsp->DialectRevision));
591 		return -EIO;
592 	}
593 
594 	cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
595 
596 	if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
597 		cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
598 	else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
599 		cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
600 	else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
601 		cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
602 	else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
603 		cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
604 #ifdef CONFIG_CIFS_SMB311
605 	else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
606 		cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
607 #endif /* SMB311 */
608 	else {
609 		cifs_dbg(VFS, "Illegal dialect returned by server 0x%x\n",
610 			 le16_to_cpu(rsp->DialectRevision));
611 		rc = -EIO;
612 		goto neg_exit;
613 	}
614 	server->dialect = le16_to_cpu(rsp->DialectRevision);
615 
616 	/* BB: add check that dialect was valid given dialect(s) we asked for */
617 
618 	/* SMB2 only has an extended negflavor */
619 	server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
620 	/* set it to the maximum buffer size value we can send with 1 credit */
621 	server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
622 			       SMB2_MAX_BUFFER_SIZE);
623 	server->max_read = le32_to_cpu(rsp->MaxReadSize);
624 	server->max_write = le32_to_cpu(rsp->MaxWriteSize);
625 	/* BB Do we need to validate the SecurityMode? */
626 	server->sec_mode = le16_to_cpu(rsp->SecurityMode);
627 	server->capabilities = le32_to_cpu(rsp->Capabilities);
628 	/* Internal types */
629 	server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
630 
631 	security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
632 					       &rsp->hdr);
633 	/*
634 	 * See MS-SMB2 section 2.2.4: if no blob, client picks default which
635 	 * for us will be
636 	 *	ses->sectype = RawNTLMSSP;
637 	 * but for time being this is our only auth choice so doesn't matter.
638 	 * We just found a server which sets blob length to zero expecting raw.
639 	 */
640 	if (blob_length == 0) {
641 		cifs_dbg(FYI, "missing security blob on negprot\n");
642 		server->sec_ntlmssp = true;
643 	}
644 
645 	rc = cifs_enable_signing(server, ses->sign);
646 	if (rc)
647 		goto neg_exit;
648 	if (blob_length) {
649 		rc = decode_negTokenInit(security_blob, blob_length, server);
650 		if (rc == 1)
651 			rc = 0;
652 		else if (rc == 0)
653 			rc = -EIO;
654 	}
655 neg_exit:
656 	free_rsp_buf(resp_buftype, rsp);
657 	return rc;
658 }
659 
smb3_validate_negotiate(const unsigned int xid,struct cifs_tcon * tcon)660 int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
661 {
662 	int rc = 0;
663 	struct validate_negotiate_info_req vneg_inbuf;
664 	struct validate_negotiate_info_rsp *pneg_rsp = NULL;
665 	u32 rsplen;
666 	u32 inbuflen; /* max of 4 dialects */
667 
668 	cifs_dbg(FYI, "validate negotiate\n");
669 
670 	/*
671 	 * validation ioctl must be signed, so no point sending this if we
672 	 * can not sign it (ie are not known user).  Even if signing is not
673 	 * required (enabled but not negotiated), in those cases we selectively
674 	 * sign just this, the first and only signed request on a connection.
675 	 * Having validation of negotiate info  helps reduce attack vectors.
676 	 */
677 	if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST)
678 		return 0; /* validation requires signing */
679 
680 	if (tcon->ses->user_name == NULL) {
681 		cifs_dbg(FYI, "Can't validate negotiate: null user mount\n");
682 		return 0; /* validation requires signing */
683 	}
684 
685 	if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL)
686 		cifs_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n");
687 
688 	vneg_inbuf.Capabilities =
689 			cpu_to_le32(tcon->ses->server->vals->req_capabilities);
690 	memcpy(vneg_inbuf.Guid, tcon->ses->server->client_guid,
691 					SMB2_CLIENT_GUID_SIZE);
692 
693 	if (tcon->ses->sign)
694 		vneg_inbuf.SecurityMode =
695 			cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
696 	else if (global_secflags & CIFSSEC_MAY_SIGN)
697 		vneg_inbuf.SecurityMode =
698 			cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
699 	else
700 		vneg_inbuf.SecurityMode = 0;
701 
702 
703 	if (strcmp(tcon->ses->server->vals->version_string,
704 		SMB3ANY_VERSION_STRING) == 0) {
705 		vneg_inbuf.Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
706 		vneg_inbuf.Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
707 		vneg_inbuf.DialectCount = cpu_to_le16(2);
708 		/* structure is big enough for 3 dialects, sending only 2 */
709 		inbuflen = sizeof(struct validate_negotiate_info_req) - 2;
710 	} else if (strcmp(tcon->ses->server->vals->version_string,
711 		SMBDEFAULT_VERSION_STRING) == 0) {
712 		vneg_inbuf.Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
713 		vneg_inbuf.Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
714 		vneg_inbuf.Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
715 		vneg_inbuf.DialectCount = cpu_to_le16(3);
716 		/* structure is big enough for 3 dialects */
717 		inbuflen = sizeof(struct validate_negotiate_info_req);
718 	} else {
719 		/* otherwise specific dialect was requested */
720 		vneg_inbuf.Dialects[0] =
721 			cpu_to_le16(tcon->ses->server->vals->protocol_id);
722 		vneg_inbuf.DialectCount = cpu_to_le16(1);
723 		/* structure is big enough for 3 dialects, sending only 1 */
724 		inbuflen = sizeof(struct validate_negotiate_info_req) - 4;
725 	}
726 
727 	rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
728 		FSCTL_VALIDATE_NEGOTIATE_INFO, true /* is_fsctl */,
729 		false /* use_ipc */,
730 		(char *)&vneg_inbuf, sizeof(struct validate_negotiate_info_req),
731 		(char **)&pneg_rsp, &rsplen);
732 
733 	if (rc != 0) {
734 		cifs_dbg(VFS, "validate protocol negotiate failed: %d\n", rc);
735 		return -EIO;
736 	}
737 
738 	if (rsplen != sizeof(struct validate_negotiate_info_rsp)) {
739 		cifs_dbg(VFS, "invalid protocol negotiate response size: %d\n",
740 			 rsplen);
741 
742 		/* relax check since Mac returns max bufsize allowed on ioctl */
743 		if ((rsplen > CIFSMaxBufSize)
744 		     || (rsplen < sizeof(struct validate_negotiate_info_rsp)))
745 			goto err_rsp_free;
746 	}
747 
748 	/* check validate negotiate info response matches what we got earlier */
749 	if (pneg_rsp->Dialect != cpu_to_le16(tcon->ses->server->dialect))
750 		goto vneg_out;
751 
752 	if (pneg_rsp->SecurityMode != cpu_to_le16(tcon->ses->server->sec_mode))
753 		goto vneg_out;
754 
755 	/* do not validate server guid because not saved at negprot time yet */
756 
757 	if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND |
758 	      SMB2_LARGE_FILES) != tcon->ses->server->capabilities)
759 		goto vneg_out;
760 
761 	/* validate negotiate successful */
762 	cifs_dbg(FYI, "validate negotiate info successful\n");
763 	kfree(pneg_rsp);
764 	return 0;
765 
766 vneg_out:
767 	cifs_dbg(VFS, "protocol revalidation - security settings mismatch\n");
768 err_rsp_free:
769 	kfree(pneg_rsp);
770 	return -EIO;
771 }
772 
773 enum securityEnum
smb2_select_sectype(struct TCP_Server_Info * server,enum securityEnum requested)774 smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
775 {
776 	switch (requested) {
777 	case Kerberos:
778 	case RawNTLMSSP:
779 		return requested;
780 	case NTLMv2:
781 		return RawNTLMSSP;
782 	case Unspecified:
783 		if (server->sec_ntlmssp &&
784 			(global_secflags & CIFSSEC_MAY_NTLMSSP))
785 			return RawNTLMSSP;
786 		if ((server->sec_kerberos || server->sec_mskerberos) &&
787 			(global_secflags & CIFSSEC_MAY_KRB5))
788 			return Kerberos;
789 		/* Fallthrough */
790 	default:
791 		return Unspecified;
792 	}
793 }
794 
795 struct SMB2_sess_data {
796 	unsigned int xid;
797 	struct cifs_ses *ses;
798 	struct nls_table *nls_cp;
799 	void (*func)(struct SMB2_sess_data *);
800 	int result;
801 	u64 previous_session;
802 
803 	/* we will send the SMB in three pieces:
804 	 * a fixed length beginning part, an optional
805 	 * SPNEGO blob (which can be zero length), and a
806 	 * last part which will include the strings
807 	 * and rest of bcc area. This allows us to avoid
808 	 * a large buffer 17K allocation
809 	 */
810 	int buf0_type;
811 	struct kvec iov[2];
812 };
813 
814 static int
SMB2_sess_alloc_buffer(struct SMB2_sess_data * sess_data)815 SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
816 {
817 	int rc;
818 	struct cifs_ses *ses = sess_data->ses;
819 	struct smb2_sess_setup_req *req;
820 	struct TCP_Server_Info *server = ses->server;
821 
822 	rc = small_smb2_init(SMB2_SESSION_SETUP, NULL, (void **) &req);
823 	if (rc)
824 		return rc;
825 
826 	/* First session, not a reauthenticate */
827 	req->hdr.sync_hdr.SessionId = 0;
828 
829 	/* if reconnect, we need to send previous sess id, otherwise it is 0 */
830 	req->PreviousSessionId = sess_data->previous_session;
831 
832 	req->Flags = 0; /* MBZ */
833 	/* to enable echos and oplocks */
834 	req->hdr.sync_hdr.CreditRequest = cpu_to_le16(3);
835 
836 	/* only one of SMB2 signing flags may be set in SMB2 request */
837 	if (server->sign)
838 		req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
839 	else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
840 		req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
841 	else
842 		req->SecurityMode = 0;
843 
844 #ifdef CONFIG_CIFS_DFS_UPCALL
845 	req->Capabilities = cpu_to_le32(SMB2_GLOBAL_CAP_DFS);
846 #else
847 	req->Capabilities = 0;
848 #endif /* DFS_UPCALL */
849 
850 	req->Channel = 0; /* MBZ */
851 
852 	sess_data->iov[0].iov_base = (char *)req;
853 	/* 4 for rfc1002 length field and 1 for pad */
854 	sess_data->iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
855 	/*
856 	 * This variable will be used to clear the buffer
857 	 * allocated above in case of any error in the calling function.
858 	 */
859 	sess_data->buf0_type = CIFS_SMALL_BUFFER;
860 
861 	return 0;
862 }
863 
864 static void
SMB2_sess_free_buffer(struct SMB2_sess_data * sess_data)865 SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data)
866 {
867 	free_rsp_buf(sess_data->buf0_type, sess_data->iov[0].iov_base);
868 	sess_data->buf0_type = CIFS_NO_BUFFER;
869 }
870 
871 static int
SMB2_sess_sendreceive(struct SMB2_sess_data * sess_data)872 SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
873 {
874 	int rc;
875 	struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
876 	struct kvec rsp_iov = { NULL, 0 };
877 
878 	/* Testing shows that buffer offset must be at location of Buffer[0] */
879 	req->SecurityBufferOffset =
880 		cpu_to_le16(sizeof(struct smb2_sess_setup_req) -
881 			1 /* pad */ - 4 /* rfc1001 len */);
882 	req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len);
883 
884 	inc_rfc1001_len(req, sess_data->iov[1].iov_len - 1 /* pad */);
885 
886 	/* BB add code to build os and lm fields */
887 
888 	rc = SendReceive2(sess_data->xid, sess_data->ses,
889 				sess_data->iov, 2,
890 				&sess_data->buf0_type,
891 				CIFS_LOG_ERROR | CIFS_NEG_OP, &rsp_iov);
892 	cifs_small_buf_release(sess_data->iov[0].iov_base);
893 	memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
894 
895 	return rc;
896 }
897 
898 static int
SMB2_sess_establish_session(struct SMB2_sess_data * sess_data)899 SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)
900 {
901 	int rc = 0;
902 	struct cifs_ses *ses = sess_data->ses;
903 
904 	mutex_lock(&ses->server->srv_mutex);
905 	if (ses->server->ops->generate_signingkey) {
906 		rc = ses->server->ops->generate_signingkey(ses);
907 		if (rc) {
908 			cifs_dbg(FYI,
909 				"SMB3 session key generation failed\n");
910 			mutex_unlock(&ses->server->srv_mutex);
911 			return rc;
912 		}
913 	}
914 	if (!ses->server->session_estab) {
915 		ses->server->sequence_number = 0x2;
916 		ses->server->session_estab = true;
917 	}
918 	mutex_unlock(&ses->server->srv_mutex);
919 
920 	cifs_dbg(FYI, "SMB2/3 session established successfully\n");
921 	spin_lock(&GlobalMid_Lock);
922 	ses->status = CifsGood;
923 	ses->need_reconnect = false;
924 	spin_unlock(&GlobalMid_Lock);
925 	return rc;
926 }
927 
928 #ifdef CONFIG_CIFS_UPCALL
929 static void
SMB2_auth_kerberos(struct SMB2_sess_data * sess_data)930 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
931 {
932 	int rc;
933 	struct cifs_ses *ses = sess_data->ses;
934 	struct cifs_spnego_msg *msg;
935 	struct key *spnego_key = NULL;
936 	struct smb2_sess_setup_rsp *rsp = NULL;
937 
938 	rc = SMB2_sess_alloc_buffer(sess_data);
939 	if (rc)
940 		goto out;
941 
942 	spnego_key = cifs_get_spnego_key(ses);
943 	if (IS_ERR(spnego_key)) {
944 		rc = PTR_ERR(spnego_key);
945 		spnego_key = NULL;
946 		goto out;
947 	}
948 
949 	msg = spnego_key->payload.data[0];
950 	/*
951 	 * check version field to make sure that cifs.upcall is
952 	 * sending us a response in an expected form
953 	 */
954 	if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
955 		cifs_dbg(VFS,
956 			  "bad cifs.upcall version. Expected %d got %d",
957 			  CIFS_SPNEGO_UPCALL_VERSION, msg->version);
958 		rc = -EKEYREJECTED;
959 		goto out_put_spnego_key;
960 	}
961 
962 	ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
963 					 GFP_KERNEL);
964 	if (!ses->auth_key.response) {
965 		cifs_dbg(VFS,
966 			"Kerberos can't allocate (%u bytes) memory",
967 			msg->sesskey_len);
968 		rc = -ENOMEM;
969 		goto out_put_spnego_key;
970 	}
971 	ses->auth_key.len = msg->sesskey_len;
972 
973 	sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
974 	sess_data->iov[1].iov_len = msg->secblob_len;
975 
976 	rc = SMB2_sess_sendreceive(sess_data);
977 	if (rc)
978 		goto out_put_spnego_key;
979 
980 	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
981 	ses->Suid = rsp->hdr.sync_hdr.SessionId;
982 
983 	ses->session_flags = le16_to_cpu(rsp->SessionFlags);
984 
985 	rc = SMB2_sess_establish_session(sess_data);
986 out_put_spnego_key:
987 	key_invalidate(spnego_key);
988 	key_put(spnego_key);
989 out:
990 	sess_data->result = rc;
991 	sess_data->func = NULL;
992 	SMB2_sess_free_buffer(sess_data);
993 }
994 #else
995 static void
SMB2_auth_kerberos(struct SMB2_sess_data * sess_data)996 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
997 {
998 	cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
999 	sess_data->result = -EOPNOTSUPP;
1000 	sess_data->func = NULL;
1001 }
1002 #endif
1003 
1004 static void
1005 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data);
1006 
1007 static void
SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data * sess_data)1008 SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data)
1009 {
1010 	int rc;
1011 	struct cifs_ses *ses = sess_data->ses;
1012 	struct smb2_sess_setup_rsp *rsp = NULL;
1013 	char *ntlmssp_blob = NULL;
1014 	bool use_spnego = false; /* else use raw ntlmssp */
1015 	u16 blob_length = 0;
1016 
1017 	/*
1018 	 * If memory allocation is successful, caller of this function
1019 	 * frees it.
1020 	 */
1021 	ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
1022 	if (!ses->ntlmssp) {
1023 		rc = -ENOMEM;
1024 		goto out_err;
1025 	}
1026 	ses->ntlmssp->sesskey_per_smbsess = true;
1027 
1028 	rc = SMB2_sess_alloc_buffer(sess_data);
1029 	if (rc)
1030 		goto out_err;
1031 
1032 	ntlmssp_blob = kmalloc(sizeof(struct _NEGOTIATE_MESSAGE),
1033 			       GFP_KERNEL);
1034 	if (ntlmssp_blob == NULL) {
1035 		rc = -ENOMEM;
1036 		goto out;
1037 	}
1038 
1039 	build_ntlmssp_negotiate_blob(ntlmssp_blob, ses);
1040 	if (use_spnego) {
1041 		/* BB eventually need to add this */
1042 		cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1043 		rc = -EOPNOTSUPP;
1044 		goto out;
1045 	} else {
1046 		blob_length = sizeof(struct _NEGOTIATE_MESSAGE);
1047 		/* with raw NTLMSSP we don't encapsulate in SPNEGO */
1048 	}
1049 	sess_data->iov[1].iov_base = ntlmssp_blob;
1050 	sess_data->iov[1].iov_len = blob_length;
1051 
1052 	rc = SMB2_sess_sendreceive(sess_data);
1053 	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1054 
1055 	/* If true, rc here is expected and not an error */
1056 	if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1057 		rsp->hdr.sync_hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
1058 		rc = 0;
1059 
1060 	if (rc)
1061 		goto out;
1062 
1063 	if (offsetof(struct smb2_sess_setup_rsp, Buffer) - 4 !=
1064 			le16_to_cpu(rsp->SecurityBufferOffset)) {
1065 		cifs_dbg(VFS, "Invalid security buffer offset %d\n",
1066 			le16_to_cpu(rsp->SecurityBufferOffset));
1067 		rc = -EIO;
1068 		goto out;
1069 	}
1070 	rc = decode_ntlmssp_challenge(rsp->Buffer,
1071 			le16_to_cpu(rsp->SecurityBufferLength), ses);
1072 	if (rc)
1073 		goto out;
1074 
1075 	cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1076 
1077 
1078 	ses->Suid = rsp->hdr.sync_hdr.SessionId;
1079 	ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1080 
1081 out:
1082 	kfree(ntlmssp_blob);
1083 	SMB2_sess_free_buffer(sess_data);
1084 	if (!rc) {
1085 		sess_data->result = 0;
1086 		sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
1087 		return;
1088 	}
1089 out_err:
1090 	kfree(ses->ntlmssp);
1091 	ses->ntlmssp = NULL;
1092 	sess_data->result = rc;
1093 	sess_data->func = NULL;
1094 }
1095 
1096 static void
SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data * sess_data)1097 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
1098 {
1099 	int rc;
1100 	struct cifs_ses *ses = sess_data->ses;
1101 	struct smb2_sess_setup_req *req;
1102 	struct smb2_sess_setup_rsp *rsp = NULL;
1103 	unsigned char *ntlmssp_blob = NULL;
1104 	bool use_spnego = false; /* else use raw ntlmssp */
1105 	u16 blob_length = 0;
1106 
1107 	rc = SMB2_sess_alloc_buffer(sess_data);
1108 	if (rc)
1109 		goto out;
1110 
1111 	req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
1112 	req->hdr.sync_hdr.SessionId = ses->Suid;
1113 
1114 	rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses,
1115 					sess_data->nls_cp);
1116 	if (rc) {
1117 		cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
1118 		goto out;
1119 	}
1120 
1121 	if (use_spnego) {
1122 		/* BB eventually need to add this */
1123 		cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1124 		rc = -EOPNOTSUPP;
1125 		goto out;
1126 	}
1127 	sess_data->iov[1].iov_base = ntlmssp_blob;
1128 	sess_data->iov[1].iov_len = blob_length;
1129 
1130 	rc = SMB2_sess_sendreceive(sess_data);
1131 	if (rc)
1132 		goto out;
1133 
1134 	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1135 
1136 	ses->Suid = rsp->hdr.sync_hdr.SessionId;
1137 	ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1138 
1139 	rc = SMB2_sess_establish_session(sess_data);
1140 out:
1141 	kfree(ntlmssp_blob);
1142 	SMB2_sess_free_buffer(sess_data);
1143 	kfree(ses->ntlmssp);
1144 	ses->ntlmssp = NULL;
1145 	sess_data->result = rc;
1146 	sess_data->func = NULL;
1147 }
1148 
1149 static int
SMB2_select_sec(struct cifs_ses * ses,struct SMB2_sess_data * sess_data)1150 SMB2_select_sec(struct cifs_ses *ses, struct SMB2_sess_data *sess_data)
1151 {
1152 	int type;
1153 
1154 	type = smb2_select_sectype(ses->server, ses->sectype);
1155 	cifs_dbg(FYI, "sess setup type %d\n", type);
1156 	if (type == Unspecified) {
1157 		cifs_dbg(VFS,
1158 			"Unable to select appropriate authentication method!");
1159 		return -EINVAL;
1160 	}
1161 
1162 	switch (type) {
1163 	case Kerberos:
1164 		sess_data->func = SMB2_auth_kerberos;
1165 		break;
1166 	case RawNTLMSSP:
1167 		sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
1168 		break;
1169 	default:
1170 		cifs_dbg(VFS, "secType %d not supported!\n", type);
1171 		return -EOPNOTSUPP;
1172 	}
1173 
1174 	return 0;
1175 }
1176 
1177 int
SMB2_sess_setup(const unsigned int xid,struct cifs_ses * ses,const struct nls_table * nls_cp)1178 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
1179 		const struct nls_table *nls_cp)
1180 {
1181 	int rc = 0;
1182 	struct TCP_Server_Info *server = ses->server;
1183 	struct SMB2_sess_data *sess_data;
1184 
1185 	cifs_dbg(FYI, "Session Setup\n");
1186 
1187 	if (!server) {
1188 		WARN(1, "%s: server is NULL!\n", __func__);
1189 		return -EIO;
1190 	}
1191 
1192 	sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL);
1193 	if (!sess_data)
1194 		return -ENOMEM;
1195 
1196 	rc = SMB2_select_sec(ses, sess_data);
1197 	if (rc)
1198 		goto out;
1199 	sess_data->xid = xid;
1200 	sess_data->ses = ses;
1201 	sess_data->buf0_type = CIFS_NO_BUFFER;
1202 	sess_data->nls_cp = (struct nls_table *) nls_cp;
1203 	sess_data->previous_session = ses->Suid;
1204 
1205 	while (sess_data->func)
1206 		sess_data->func(sess_data);
1207 
1208 	if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign))
1209 		cifs_dbg(VFS, "signing requested but authenticated as guest\n");
1210 	rc = sess_data->result;
1211 out:
1212 	kfree(sess_data);
1213 	return rc;
1214 }
1215 
1216 int
SMB2_logoff(const unsigned int xid,struct cifs_ses * ses)1217 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
1218 {
1219 	struct smb2_logoff_req *req; /* response is also trivial struct */
1220 	int rc = 0;
1221 	struct TCP_Server_Info *server;
1222 	int flags = 0;
1223 
1224 	cifs_dbg(FYI, "disconnect session %p\n", ses);
1225 
1226 	if (ses && (ses->server))
1227 		server = ses->server;
1228 	else
1229 		return -EIO;
1230 
1231 	/* no need to send SMB logoff if uid already closed due to reconnect */
1232 	if (ses->need_reconnect)
1233 		goto smb2_session_already_dead;
1234 
1235 	rc = small_smb2_init(SMB2_LOGOFF, NULL, (void **) &req);
1236 	if (rc)
1237 		return rc;
1238 
1239 	 /* since no tcon, smb2_init can not do this, so do here */
1240 	req->hdr.sync_hdr.SessionId = ses->Suid;
1241 
1242 	if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
1243 		flags |= CIFS_TRANSFORM_REQ;
1244 	else if (server->sign)
1245 		req->hdr.sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1246 
1247 	rc = SendReceiveNoRsp(xid, ses, (char *) req, flags);
1248 	cifs_small_buf_release(req);
1249 	/*
1250 	 * No tcon so can't do
1251 	 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
1252 	 */
1253 
1254 smb2_session_already_dead:
1255 	return rc;
1256 }
1257 
cifs_stats_fail_inc(struct cifs_tcon * tcon,uint16_t code)1258 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
1259 {
1260 	cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
1261 }
1262 
1263 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
1264 
1265 /* These are similar values to what Windows uses */
init_copy_chunk_defaults(struct cifs_tcon * tcon)1266 static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
1267 {
1268 	tcon->max_chunks = 256;
1269 	tcon->max_bytes_chunk = 1048576;
1270 	tcon->max_bytes_copy = 16777216;
1271 }
1272 
1273 int
SMB2_tcon(const unsigned int xid,struct cifs_ses * ses,const char * tree,struct cifs_tcon * tcon,const struct nls_table * cp)1274 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
1275 	  struct cifs_tcon *tcon, const struct nls_table *cp)
1276 {
1277 	struct smb2_tree_connect_req *req;
1278 	struct smb2_tree_connect_rsp *rsp = NULL;
1279 	struct kvec iov[2];
1280 	struct kvec rsp_iov = { NULL, 0 };
1281 	int rc = 0;
1282 	int resp_buftype;
1283 	int unc_path_len;
1284 	__le16 *unc_path = NULL;
1285 	int flags = 0;
1286 
1287 	cifs_dbg(FYI, "TCON\n");
1288 
1289 	if (!(ses->server) || !tree)
1290 		return -EIO;
1291 
1292 	unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
1293 	if (unc_path == NULL)
1294 		return -ENOMEM;
1295 
1296 	unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
1297 	unc_path_len *= 2;
1298 	if (unc_path_len < 2) {
1299 		kfree(unc_path);
1300 		return -EINVAL;
1301 	}
1302 
1303 	/* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
1304 	if (tcon)
1305 		tcon->tid = 0;
1306 
1307 	rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req);
1308 	if (rc) {
1309 		kfree(unc_path);
1310 		return rc;
1311 	}
1312 
1313 	if (tcon == NULL) {
1314 		if ((ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA))
1315 			flags |= CIFS_TRANSFORM_REQ;
1316 
1317 		/* since no tcon, smb2_init can not do this, so do here */
1318 		req->hdr.sync_hdr.SessionId = ses->Suid;
1319 		if (ses->server->sign)
1320 			req->hdr.sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
1321 	} else if (encryption_required(tcon))
1322 		flags |= CIFS_TRANSFORM_REQ;
1323 
1324 	iov[0].iov_base = (char *)req;
1325 	/* 4 for rfc1002 length field and 1 for pad */
1326 	iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
1327 
1328 	/* Testing shows that buffer offset must be at location of Buffer[0] */
1329 	req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
1330 			- 1 /* pad */ - 4 /* do not count rfc1001 len field */);
1331 	req->PathLength = cpu_to_le16(unc_path_len - 2);
1332 	iov[1].iov_base = unc_path;
1333 	iov[1].iov_len = unc_path_len;
1334 
1335 	inc_rfc1001_len(req, unc_path_len - 1 /* pad */);
1336 
1337 	rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, flags, &rsp_iov);
1338 	cifs_small_buf_release(req);
1339 	rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
1340 
1341 	if (rc != 0) {
1342 		if (tcon) {
1343 			cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
1344 			tcon->need_reconnect = true;
1345 		}
1346 		goto tcon_error_exit;
1347 	}
1348 
1349 	if (tcon == NULL) {
1350 		ses->ipc_tid = rsp->hdr.sync_hdr.TreeId;
1351 		goto tcon_exit;
1352 	}
1353 
1354 	switch (rsp->ShareType) {
1355 	case SMB2_SHARE_TYPE_DISK:
1356 		cifs_dbg(FYI, "connection to disk share\n");
1357 		break;
1358 	case SMB2_SHARE_TYPE_PIPE:
1359 		tcon->ipc = true;
1360 		cifs_dbg(FYI, "connection to pipe share\n");
1361 		break;
1362 	case SMB2_SHARE_TYPE_PRINT:
1363 		tcon->ipc = true;
1364 		cifs_dbg(FYI, "connection to printer\n");
1365 		break;
1366 	default:
1367 		cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
1368 		rc = -EOPNOTSUPP;
1369 		goto tcon_error_exit;
1370 	}
1371 
1372 	tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
1373 	tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
1374 	tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1375 	tcon->tidStatus = CifsGood;
1376 	tcon->need_reconnect = false;
1377 	tcon->tid = rsp->hdr.sync_hdr.TreeId;
1378 	strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
1379 
1380 	if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
1381 	    ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
1382 		cifs_dbg(VFS, "DFS capability contradicts DFS flag\n");
1383 
1384 	if (tcon->seal &&
1385 	    !(tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1386 		cifs_dbg(VFS, "Encryption is requested but not supported\n");
1387 
1388 	init_copy_chunk_defaults(tcon);
1389 	if (tcon->ses->server->ops->validate_negotiate)
1390 		rc = tcon->ses->server->ops->validate_negotiate(xid, tcon);
1391 tcon_exit:
1392 	free_rsp_buf(resp_buftype, rsp);
1393 	kfree(unc_path);
1394 	return rc;
1395 
1396 tcon_error_exit:
1397 	if (rsp && rsp->hdr.sync_hdr.Status == STATUS_BAD_NETWORK_NAME) {
1398 		cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
1399 	}
1400 	goto tcon_exit;
1401 }
1402 
1403 int
SMB2_tdis(const unsigned int xid,struct cifs_tcon * tcon)1404 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
1405 {
1406 	struct smb2_tree_disconnect_req *req; /* response is trivial */
1407 	int rc = 0;
1408 	struct cifs_ses *ses = tcon->ses;
1409 	int flags = 0;
1410 
1411 	cifs_dbg(FYI, "Tree Disconnect\n");
1412 
1413 	if (!ses || !(ses->server))
1414 		return -EIO;
1415 
1416 	if ((tcon->need_reconnect) || (tcon->ses->need_reconnect))
1417 		return 0;
1418 
1419 	rc = small_smb2_init(SMB2_TREE_DISCONNECT, tcon, (void **) &req);
1420 	if (rc)
1421 		return rc;
1422 
1423 	if (encryption_required(tcon))
1424 		flags |= CIFS_TRANSFORM_REQ;
1425 
1426 	rc = SendReceiveNoRsp(xid, ses, (char *)req, flags);
1427 	cifs_small_buf_release(req);
1428 	if (rc)
1429 		cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
1430 
1431 	return rc;
1432 }
1433 
1434 
1435 static struct create_durable *
create_durable_buf(void)1436 create_durable_buf(void)
1437 {
1438 	struct create_durable *buf;
1439 
1440 	buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1441 	if (!buf)
1442 		return NULL;
1443 
1444 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
1445 					(struct create_durable, Data));
1446 	buf->ccontext.DataLength = cpu_to_le32(16);
1447 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
1448 				(struct create_durable, Name));
1449 	buf->ccontext.NameLength = cpu_to_le16(4);
1450 	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
1451 	buf->Name[0] = 'D';
1452 	buf->Name[1] = 'H';
1453 	buf->Name[2] = 'n';
1454 	buf->Name[3] = 'Q';
1455 	return buf;
1456 }
1457 
1458 static struct create_durable *
create_reconnect_durable_buf(struct cifs_fid * fid)1459 create_reconnect_durable_buf(struct cifs_fid *fid)
1460 {
1461 	struct create_durable *buf;
1462 
1463 	buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
1464 	if (!buf)
1465 		return NULL;
1466 
1467 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
1468 					(struct create_durable, Data));
1469 	buf->ccontext.DataLength = cpu_to_le32(16);
1470 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
1471 				(struct create_durable, Name));
1472 	buf->ccontext.NameLength = cpu_to_le16(4);
1473 	buf->Data.Fid.PersistentFileId = fid->persistent_fid;
1474 	buf->Data.Fid.VolatileFileId = fid->volatile_fid;
1475 	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
1476 	buf->Name[0] = 'D';
1477 	buf->Name[1] = 'H';
1478 	buf->Name[2] = 'n';
1479 	buf->Name[3] = 'C';
1480 	return buf;
1481 }
1482 
1483 static __u8
parse_lease_state(struct TCP_Server_Info * server,struct smb2_create_rsp * rsp,unsigned int * epoch)1484 parse_lease_state(struct TCP_Server_Info *server, struct smb2_create_rsp *rsp,
1485 		  unsigned int *epoch)
1486 {
1487 	char *data_offset;
1488 	struct create_context *cc;
1489 	unsigned int next;
1490 	unsigned int remaining;
1491 	char *name;
1492 
1493 	data_offset = (char *)rsp + 4 + le32_to_cpu(rsp->CreateContextsOffset);
1494 	remaining = le32_to_cpu(rsp->CreateContextsLength);
1495 	cc = (struct create_context *)data_offset;
1496 	while (remaining >= sizeof(struct create_context)) {
1497 		name = le16_to_cpu(cc->NameOffset) + (char *)cc;
1498 		if (le16_to_cpu(cc->NameLength) == 4 &&
1499 		    strncmp(name, "RqLs", 4) == 0)
1500 			return server->ops->parse_lease_buf(cc, epoch);
1501 
1502 		next = le32_to_cpu(cc->Next);
1503 		if (!next)
1504 			break;
1505 		remaining -= next;
1506 		cc = (struct create_context *)((char *)cc + next);
1507 	}
1508 
1509 	return 0;
1510 }
1511 
1512 static int
add_lease_context(struct TCP_Server_Info * server,struct kvec * iov,unsigned int * num_iovec,__u8 * oplock)1513 add_lease_context(struct TCP_Server_Info *server, struct kvec *iov,
1514 		  unsigned int *num_iovec, __u8 *oplock)
1515 {
1516 	struct smb2_create_req *req = iov[0].iov_base;
1517 	unsigned int num = *num_iovec;
1518 
1519 	iov[num].iov_base = server->ops->create_lease_buf(oplock+1, *oplock);
1520 	if (iov[num].iov_base == NULL)
1521 		return -ENOMEM;
1522 	iov[num].iov_len = server->vals->create_lease_size;
1523 	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
1524 	if (!req->CreateContextsOffset)
1525 		req->CreateContextsOffset = cpu_to_le32(
1526 				sizeof(struct smb2_create_req) - 4 +
1527 				iov[num - 1].iov_len);
1528 	le32_add_cpu(&req->CreateContextsLength,
1529 		     server->vals->create_lease_size);
1530 	inc_rfc1001_len(&req->hdr, server->vals->create_lease_size);
1531 	*num_iovec = num + 1;
1532 	return 0;
1533 }
1534 
1535 static struct create_durable_v2 *
create_durable_v2_buf(struct cifs_fid * pfid)1536 create_durable_v2_buf(struct cifs_fid *pfid)
1537 {
1538 	struct create_durable_v2 *buf;
1539 
1540 	buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
1541 	if (!buf)
1542 		return NULL;
1543 
1544 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
1545 					(struct create_durable_v2, dcontext));
1546 	buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
1547 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
1548 				(struct create_durable_v2, Name));
1549 	buf->ccontext.NameLength = cpu_to_le16(4);
1550 
1551 	buf->dcontext.Timeout = 0; /* Should this be configurable by workload */
1552 	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
1553 	generate_random_uuid(buf->dcontext.CreateGuid);
1554 	memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
1555 
1556 	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
1557 	buf->Name[0] = 'D';
1558 	buf->Name[1] = 'H';
1559 	buf->Name[2] = '2';
1560 	buf->Name[3] = 'Q';
1561 	return buf;
1562 }
1563 
1564 static struct create_durable_handle_reconnect_v2 *
create_reconnect_durable_v2_buf(struct cifs_fid * fid)1565 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
1566 {
1567 	struct create_durable_handle_reconnect_v2 *buf;
1568 
1569 	buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
1570 			GFP_KERNEL);
1571 	if (!buf)
1572 		return NULL;
1573 
1574 	buf->ccontext.DataOffset =
1575 		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
1576 				     dcontext));
1577 	buf->ccontext.DataLength =
1578 		cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
1579 	buf->ccontext.NameOffset =
1580 		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
1581 			    Name));
1582 	buf->ccontext.NameLength = cpu_to_le16(4);
1583 
1584 	buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
1585 	buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
1586 	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
1587 	memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
1588 
1589 	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
1590 	buf->Name[0] = 'D';
1591 	buf->Name[1] = 'H';
1592 	buf->Name[2] = '2';
1593 	buf->Name[3] = 'C';
1594 	return buf;
1595 }
1596 
1597 static int
add_durable_v2_context(struct kvec * iov,unsigned int * num_iovec,struct cifs_open_parms * oparms)1598 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
1599 		    struct cifs_open_parms *oparms)
1600 {
1601 	struct smb2_create_req *req = iov[0].iov_base;
1602 	unsigned int num = *num_iovec;
1603 
1604 	iov[num].iov_base = create_durable_v2_buf(oparms->fid);
1605 	if (iov[num].iov_base == NULL)
1606 		return -ENOMEM;
1607 	iov[num].iov_len = sizeof(struct create_durable_v2);
1608 	if (!req->CreateContextsOffset)
1609 		req->CreateContextsOffset =
1610 			cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
1611 								iov[1].iov_len);
1612 	le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2));
1613 	inc_rfc1001_len(&req->hdr, sizeof(struct create_durable_v2));
1614 	*num_iovec = num + 1;
1615 	return 0;
1616 }
1617 
1618 static int
add_durable_reconnect_v2_context(struct kvec * iov,unsigned int * num_iovec,struct cifs_open_parms * oparms)1619 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
1620 		    struct cifs_open_parms *oparms)
1621 {
1622 	struct smb2_create_req *req = iov[0].iov_base;
1623 	unsigned int num = *num_iovec;
1624 
1625 	/* indicate that we don't need to relock the file */
1626 	oparms->reconnect = false;
1627 
1628 	iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
1629 	if (iov[num].iov_base == NULL)
1630 		return -ENOMEM;
1631 	iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
1632 	if (!req->CreateContextsOffset)
1633 		req->CreateContextsOffset =
1634 			cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
1635 								iov[1].iov_len);
1636 	le32_add_cpu(&req->CreateContextsLength,
1637 			sizeof(struct create_durable_handle_reconnect_v2));
1638 	inc_rfc1001_len(&req->hdr,
1639 			sizeof(struct create_durable_handle_reconnect_v2));
1640 	*num_iovec = num + 1;
1641 	return 0;
1642 }
1643 
1644 static int
add_durable_context(struct kvec * iov,unsigned int * num_iovec,struct cifs_open_parms * oparms,bool use_persistent)1645 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
1646 		    struct cifs_open_parms *oparms, bool use_persistent)
1647 {
1648 	struct smb2_create_req *req = iov[0].iov_base;
1649 	unsigned int num = *num_iovec;
1650 
1651 	if (use_persistent) {
1652 		if (oparms->reconnect)
1653 			return add_durable_reconnect_v2_context(iov, num_iovec,
1654 								oparms);
1655 		else
1656 			return add_durable_v2_context(iov, num_iovec, oparms);
1657 	}
1658 
1659 	if (oparms->reconnect) {
1660 		iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
1661 		/* indicate that we don't need to relock the file */
1662 		oparms->reconnect = false;
1663 	} else
1664 		iov[num].iov_base = create_durable_buf();
1665 	if (iov[num].iov_base == NULL)
1666 		return -ENOMEM;
1667 	iov[num].iov_len = sizeof(struct create_durable);
1668 	if (!req->CreateContextsOffset)
1669 		req->CreateContextsOffset =
1670 			cpu_to_le32(sizeof(struct smb2_create_req) - 4 +
1671 								iov[1].iov_len);
1672 	le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable));
1673 	inc_rfc1001_len(&req->hdr, sizeof(struct create_durable));
1674 	*num_iovec = num + 1;
1675 	return 0;
1676 }
1677 
1678 static int
alloc_path_with_tree_prefix(__le16 ** out_path,int * out_size,int * out_len,const char * treename,const __le16 * path)1679 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
1680 			    const char *treename, const __le16 *path)
1681 {
1682 	int treename_len, path_len;
1683 	struct nls_table *cp;
1684 	const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
1685 
1686 	/*
1687 	 * skip leading "\\"
1688 	 */
1689 	treename_len = strlen(treename);
1690 	if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
1691 		return -EINVAL;
1692 
1693 	treename += 2;
1694 	treename_len -= 2;
1695 
1696 	path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
1697 
1698 	/*
1699 	 * make room for one path separator between the treename and
1700 	 * path
1701 	 */
1702 	*out_len = treename_len + 1 + path_len;
1703 
1704 	/*
1705 	 * final path needs to be null-terminated UTF16 with a
1706 	 * size aligned to 8
1707 	 */
1708 
1709 	*out_size = roundup((*out_len+1)*2, 8);
1710 	*out_path = kzalloc(*out_size, GFP_KERNEL);
1711 	if (!*out_path)
1712 		return -ENOMEM;
1713 
1714 	cp = load_nls_default();
1715 	cifs_strtoUTF16(*out_path, treename, treename_len, cp);
1716 	UniStrcat(*out_path, sep);
1717 	UniStrcat(*out_path, path);
1718 	unload_nls(cp);
1719 
1720 	return 0;
1721 }
1722 
1723 int
SMB2_open(const unsigned int xid,struct cifs_open_parms * oparms,__le16 * path,__u8 * oplock,struct smb2_file_all_info * buf,struct smb2_err_rsp ** err_buf)1724 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
1725 	  __u8 *oplock, struct smb2_file_all_info *buf,
1726 	  struct smb2_err_rsp **err_buf)
1727 {
1728 	struct smb2_create_req *req;
1729 	struct smb2_create_rsp *rsp;
1730 	struct TCP_Server_Info *server;
1731 	struct cifs_tcon *tcon = oparms->tcon;
1732 	struct cifs_ses *ses = tcon->ses;
1733 	struct kvec iov[4];
1734 	struct kvec rsp_iov = {NULL, 0};
1735 	int resp_buftype;
1736 	int uni_path_len;
1737 	__le16 *copy_path = NULL;
1738 	int copy_size;
1739 	int rc = 0;
1740 	unsigned int n_iov = 2;
1741 	__u32 file_attributes = 0;
1742 	char *dhc_buf = NULL, *lc_buf = NULL;
1743 	int flags = 0;
1744 
1745 	cifs_dbg(FYI, "create/open\n");
1746 
1747 	if (ses && (ses->server))
1748 		server = ses->server;
1749 	else
1750 		return -EIO;
1751 
1752 	rc = small_smb2_init(SMB2_CREATE, tcon, (void **) &req);
1753 	if (rc)
1754 		return rc;
1755 
1756 	if (encryption_required(tcon))
1757 		flags |= CIFS_TRANSFORM_REQ;
1758 
1759 	if (oparms->create_options & CREATE_OPTION_READONLY)
1760 		file_attributes |= ATTR_READONLY;
1761 	if (oparms->create_options & CREATE_OPTION_SPECIAL)
1762 		file_attributes |= ATTR_SYSTEM;
1763 
1764 	req->ImpersonationLevel = IL_IMPERSONATION;
1765 	req->DesiredAccess = cpu_to_le32(oparms->desired_access);
1766 	/* File attributes ignored on open (used in create though) */
1767 	req->FileAttributes = cpu_to_le32(file_attributes);
1768 	req->ShareAccess = FILE_SHARE_ALL_LE;
1769 	req->CreateDisposition = cpu_to_le32(oparms->disposition);
1770 	req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
1771 
1772 	iov[0].iov_base = (char *)req;
1773 	/* 4 for rfc1002 length field */
1774 	iov[0].iov_len = get_rfc1002_length(req) + 4;
1775 	/* -1 since last byte is buf[0] which is sent below (path) */
1776 	iov[0].iov_len--;
1777 
1778 	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req) - 4);
1779 
1780 	/* [MS-SMB2] 2.2.13 NameOffset:
1781 	 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
1782 	 * the SMB2 header, the file name includes a prefix that will
1783 	 * be processed during DFS name normalization as specified in
1784 	 * section 3.3.5.9. Otherwise, the file name is relative to
1785 	 * the share that is identified by the TreeId in the SMB2
1786 	 * header.
1787 	 */
1788 	if (tcon->share_flags & SHI1005_FLAGS_DFS) {
1789 		int name_len;
1790 
1791 		req->hdr.sync_hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
1792 		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
1793 						 &name_len,
1794 						 tcon->treeName, path);
1795 		if (rc) {
1796 			cifs_small_buf_release(req);
1797 			return rc;
1798 		}
1799 		req->NameLength = cpu_to_le16(name_len * 2);
1800 		uni_path_len = copy_size;
1801 		path = copy_path;
1802 	} else {
1803 		uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
1804 		/* MUST set path len (NameLength) to 0 opening root of share */
1805 		req->NameLength = cpu_to_le16(uni_path_len - 2);
1806 		if (uni_path_len % 8 != 0) {
1807 			copy_size = roundup(uni_path_len, 8);
1808 			copy_path = kzalloc(copy_size, GFP_KERNEL);
1809 			if (!copy_path) {
1810 				cifs_small_buf_release(req);
1811 				return -ENOMEM;
1812 			}
1813 			memcpy((char *)copy_path, (const char *)path,
1814 			       uni_path_len);
1815 			uni_path_len = copy_size;
1816 			path = copy_path;
1817 		}
1818 	}
1819 
1820 	iov[1].iov_len = uni_path_len;
1821 	iov[1].iov_base = path;
1822 	/* -1 since last byte is buf[0] which was counted in smb2_buf_len */
1823 	inc_rfc1001_len(req, uni_path_len - 1);
1824 
1825 	if (!server->oplocks)
1826 		*oplock = SMB2_OPLOCK_LEVEL_NONE;
1827 
1828 	if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
1829 	    *oplock == SMB2_OPLOCK_LEVEL_NONE)
1830 		req->RequestedOplockLevel = *oplock;
1831 	else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
1832 		  (oparms->create_options & CREATE_NOT_FILE))
1833 		req->RequestedOplockLevel = *oplock; /* no srv lease support */
1834 	else {
1835 		rc = add_lease_context(server, iov, &n_iov, oplock);
1836 		if (rc) {
1837 			cifs_small_buf_release(req);
1838 			kfree(copy_path);
1839 			return rc;
1840 		}
1841 		lc_buf = iov[n_iov-1].iov_base;
1842 	}
1843 
1844 	if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
1845 		/* need to set Next field of lease context if we request it */
1846 		if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
1847 			struct create_context *ccontext =
1848 			    (struct create_context *)iov[n_iov-1].iov_base;
1849 			ccontext->Next =
1850 				cpu_to_le32(server->vals->create_lease_size);
1851 		}
1852 
1853 		rc = add_durable_context(iov, &n_iov, oparms,
1854 					tcon->use_persistent);
1855 		if (rc) {
1856 			cifs_small_buf_release(req);
1857 			kfree(copy_path);
1858 			kfree(lc_buf);
1859 			return rc;
1860 		}
1861 		dhc_buf = iov[n_iov-1].iov_base;
1862 	}
1863 
1864 	rc = SendReceive2(xid, ses, iov, n_iov, &resp_buftype, flags, &rsp_iov);
1865 	cifs_small_buf_release(req);
1866 	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
1867 
1868 	if (rc != 0) {
1869 		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
1870 		if (err_buf && rsp)
1871 			*err_buf = kmemdup(rsp, get_rfc1002_length(rsp) + 4,
1872 					   GFP_KERNEL);
1873 		goto creat_exit;
1874 	}
1875 
1876 	oparms->fid->persistent_fid = rsp->PersistentFileId;
1877 	oparms->fid->volatile_fid = rsp->VolatileFileId;
1878 
1879 	if (buf) {
1880 		memcpy(buf, &rsp->CreationTime, 32);
1881 		buf->AllocationSize = rsp->AllocationSize;
1882 		buf->EndOfFile = rsp->EndofFile;
1883 		buf->Attributes = rsp->FileAttributes;
1884 		buf->NumberOfLinks = cpu_to_le32(1);
1885 		buf->DeletePending = 0;
1886 	}
1887 
1888 	if (rsp->OplockLevel == SMB2_OPLOCK_LEVEL_LEASE)
1889 		*oplock = parse_lease_state(server, rsp, &oparms->fid->epoch);
1890 	else
1891 		*oplock = rsp->OplockLevel;
1892 creat_exit:
1893 	kfree(copy_path);
1894 	kfree(lc_buf);
1895 	kfree(dhc_buf);
1896 	free_rsp_buf(resp_buftype, rsp);
1897 	return rc;
1898 }
1899 
1900 /*
1901  *	SMB2 IOCTL is used for both IOCTLs and FSCTLs
1902  */
1903 int
SMB2_ioctl(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u32 opcode,bool is_fsctl,bool use_ipc,char * in_data,u32 indatalen,char ** out_data,u32 * plen)1904 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
1905 	   u64 volatile_fid, u32 opcode, bool is_fsctl, bool use_ipc,
1906 	   char *in_data, u32 indatalen,
1907 	   char **out_data, u32 *plen /* returned data len */)
1908 {
1909 	struct smb2_ioctl_req *req;
1910 	struct smb2_ioctl_rsp *rsp;
1911 	struct smb2_sync_hdr *shdr;
1912 	struct cifs_ses *ses;
1913 	struct kvec iov[2];
1914 	struct kvec rsp_iov;
1915 	int resp_buftype;
1916 	int n_iov;
1917 	int rc = 0;
1918 	int flags = 0;
1919 
1920 	cifs_dbg(FYI, "SMB2 IOCTL\n");
1921 
1922 	if (out_data != NULL)
1923 		*out_data = NULL;
1924 
1925 	/* zero out returned data len, in case of error */
1926 	if (plen)
1927 		*plen = 0;
1928 
1929 	if (tcon)
1930 		ses = tcon->ses;
1931 	else
1932 		return -EIO;
1933 
1934 	if (!ses || !(ses->server))
1935 		return -EIO;
1936 
1937 	rc = small_smb2_init(SMB2_IOCTL, tcon, (void **) &req);
1938 	if (rc)
1939 		return rc;
1940 
1941 	if (use_ipc) {
1942 		if (ses->ipc_tid == 0) {
1943 			cifs_small_buf_release(req);
1944 			return -ENOTCONN;
1945 		}
1946 
1947 		cifs_dbg(FYI, "replacing tid 0x%x with IPC tid 0x%x\n",
1948 			 req->hdr.sync_hdr.TreeId, ses->ipc_tid);
1949 		req->hdr.sync_hdr.TreeId = ses->ipc_tid;
1950 	}
1951 	if (encryption_required(tcon))
1952 		flags |= CIFS_TRANSFORM_REQ;
1953 
1954 	req->CtlCode = cpu_to_le32(opcode);
1955 	req->PersistentFileId = persistent_fid;
1956 	req->VolatileFileId = volatile_fid;
1957 
1958 	if (indatalen) {
1959 		req->InputCount = cpu_to_le32(indatalen);
1960 		/* do not set InputOffset if no input data */
1961 		req->InputOffset =
1962 		       cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer) - 4);
1963 		iov[1].iov_base = in_data;
1964 		iov[1].iov_len = indatalen;
1965 		n_iov = 2;
1966 	} else
1967 		n_iov = 1;
1968 
1969 	req->OutputOffset = 0;
1970 	req->OutputCount = 0; /* MBZ */
1971 
1972 	/*
1973 	 * Could increase MaxOutputResponse, but that would require more
1974 	 * than one credit. Windows typically sets this smaller, but for some
1975 	 * ioctls it may be useful to allow server to send more. No point
1976 	 * limiting what the server can send as long as fits in one credit
1977 	 * Unfortunately - we can not handle more than CIFS_MAX_MSG_SIZE
1978 	 * (by default, note that it can be overridden to make max larger)
1979 	 * in responses (except for read responses which can be bigger.
1980 	 * We may want to bump this limit up
1981 	 */
1982 	req->MaxOutputResponse = cpu_to_le32(CIFSMaxBufSize);
1983 
1984 	if (is_fsctl)
1985 		req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
1986 	else
1987 		req->Flags = 0;
1988 
1989 	iov[0].iov_base = (char *)req;
1990 
1991 	/*
1992 	 * If no input data, the size of ioctl struct in
1993 	 * protocol spec still includes a 1 byte data buffer,
1994 	 * but if input data passed to ioctl, we do not
1995 	 * want to double count this, so we do not send
1996 	 * the dummy one byte of data in iovec[0] if sending
1997 	 * input data (in iovec[1]). We also must add 4 bytes
1998 	 * in first iovec to allow for rfc1002 length field.
1999 	 */
2000 
2001 	if (indatalen) {
2002 		iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
2003 		inc_rfc1001_len(req, indatalen - 1);
2004 	} else
2005 		iov[0].iov_len = get_rfc1002_length(req) + 4;
2006 
2007 	/* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
2008 	if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
2009 		req->hdr.sync_hdr.Flags |= SMB2_FLAGS_SIGNED;
2010 
2011 	rc = SendReceive2(xid, ses, iov, n_iov, &resp_buftype, flags, &rsp_iov);
2012 	cifs_small_buf_release(req);
2013 	rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
2014 
2015 	if ((rc != 0) && (rc != -EINVAL)) {
2016 		cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
2017 		goto ioctl_exit;
2018 	} else if (rc == -EINVAL) {
2019 		if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
2020 		    (opcode != FSCTL_SRV_COPYCHUNK)) {
2021 			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
2022 			goto ioctl_exit;
2023 		}
2024 	}
2025 
2026 	/* check if caller wants to look at return data or just return rc */
2027 	if ((plen == NULL) || (out_data == NULL))
2028 		goto ioctl_exit;
2029 
2030 	*plen = le32_to_cpu(rsp->OutputCount);
2031 
2032 	/* We check for obvious errors in the output buffer length and offset */
2033 	if (*plen == 0)
2034 		goto ioctl_exit; /* server returned no data */
2035 	else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
2036 		cifs_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
2037 		*plen = 0;
2038 		rc = -EIO;
2039 		goto ioctl_exit;
2040 	}
2041 
2042 	if (get_rfc1002_length(rsp) - *plen < le32_to_cpu(rsp->OutputOffset)) {
2043 		cifs_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
2044 			le32_to_cpu(rsp->OutputOffset));
2045 		*plen = 0;
2046 		rc = -EIO;
2047 		goto ioctl_exit;
2048 	}
2049 
2050 	*out_data = kmalloc(*plen, GFP_KERNEL);
2051 	if (*out_data == NULL) {
2052 		rc = -ENOMEM;
2053 		goto ioctl_exit;
2054 	}
2055 
2056 	shdr = get_sync_hdr(rsp);
2057 	memcpy(*out_data, (char *)shdr + le32_to_cpu(rsp->OutputOffset), *plen);
2058 ioctl_exit:
2059 	free_rsp_buf(resp_buftype, rsp);
2060 	return rc;
2061 }
2062 
2063 /*
2064  *   Individual callers to ioctl worker function follow
2065  */
2066 
2067 int
SMB2_set_compression(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)2068 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
2069 		     u64 persistent_fid, u64 volatile_fid)
2070 {
2071 	int rc;
2072 	struct  compress_ioctl fsctl_input;
2073 	char *ret_data = NULL;
2074 
2075 	fsctl_input.CompressionState =
2076 			cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
2077 
2078 	rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
2079 			FSCTL_SET_COMPRESSION, true /* is_fsctl */,
2080 			false /* use_ipc */,
2081 			(char *)&fsctl_input /* data input */,
2082 			2 /* in data len */, &ret_data /* out data */, NULL);
2083 
2084 	cifs_dbg(FYI, "set compression rc %d\n", rc);
2085 
2086 	return rc;
2087 }
2088 
2089 int
SMB2_close(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)2090 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
2091 	   u64 persistent_fid, u64 volatile_fid)
2092 {
2093 	struct smb2_close_req *req;
2094 	struct smb2_close_rsp *rsp;
2095 	struct cifs_ses *ses = tcon->ses;
2096 	struct kvec iov[1];
2097 	struct kvec rsp_iov;
2098 	int resp_buftype;
2099 	int rc = 0;
2100 	int flags = 0;
2101 
2102 	cifs_dbg(FYI, "Close\n");
2103 
2104 	if (!ses || !(ses->server))
2105 		return -EIO;
2106 
2107 	rc = small_smb2_init(SMB2_CLOSE, tcon, (void **) &req);
2108 	if (rc)
2109 		return rc;
2110 
2111 	if (encryption_required(tcon))
2112 		flags |= CIFS_TRANSFORM_REQ;
2113 
2114 	req->PersistentFileId = persistent_fid;
2115 	req->VolatileFileId = volatile_fid;
2116 
2117 	iov[0].iov_base = (char *)req;
2118 	/* 4 for rfc1002 length field */
2119 	iov[0].iov_len = get_rfc1002_length(req) + 4;
2120 
2121 	rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
2122 	cifs_small_buf_release(req);
2123 	rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
2124 
2125 	if (rc != 0) {
2126 		cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
2127 		goto close_exit;
2128 	}
2129 
2130 	/* BB FIXME - decode close response, update inode for caching */
2131 
2132 close_exit:
2133 	free_rsp_buf(resp_buftype, rsp);
2134 	return rc;
2135 }
2136 
2137 static int
validate_buf(unsigned int offset,unsigned int buffer_length,struct smb2_hdr * hdr,unsigned int min_buf_size)2138 validate_buf(unsigned int offset, unsigned int buffer_length,
2139 	     struct smb2_hdr *hdr, unsigned int min_buf_size)
2140 
2141 {
2142 	unsigned int smb_len = be32_to_cpu(hdr->smb2_buf_length);
2143 	char *end_of_smb = smb_len + 4 /* RFC1001 length field */ + (char *)hdr;
2144 	char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
2145 	char *end_of_buf = begin_of_buf + buffer_length;
2146 
2147 
2148 	if (buffer_length < min_buf_size) {
2149 		cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
2150 			 buffer_length, min_buf_size);
2151 		return -EINVAL;
2152 	}
2153 
2154 	/* check if beyond RFC1001 maximum length */
2155 	if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
2156 		cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
2157 			 buffer_length, smb_len);
2158 		return -EINVAL;
2159 	}
2160 
2161 	if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
2162 		cifs_dbg(VFS, "illegal server response, bad offset to data\n");
2163 		return -EINVAL;
2164 	}
2165 
2166 	return 0;
2167 }
2168 
2169 /*
2170  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
2171  * Caller must free buffer.
2172  */
2173 static int
validate_and_copy_buf(unsigned int offset,unsigned int buffer_length,struct smb2_hdr * hdr,unsigned int minbufsize,char * data)2174 validate_and_copy_buf(unsigned int offset, unsigned int buffer_length,
2175 		      struct smb2_hdr *hdr, unsigned int minbufsize,
2176 		      char *data)
2177 
2178 {
2179 	char *begin_of_buf = 4 /* RFC1001 len field */ + offset + (char *)hdr;
2180 	int rc;
2181 
2182 	if (!data)
2183 		return -EINVAL;
2184 
2185 	rc = validate_buf(offset, buffer_length, hdr, minbufsize);
2186 	if (rc)
2187 		return rc;
2188 
2189 	memcpy(data, begin_of_buf, buffer_length);
2190 
2191 	return 0;
2192 }
2193 
2194 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)2195 query_info(const unsigned int xid, struct cifs_tcon *tcon,
2196 	   u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
2197 	   u32 additional_info, size_t output_len, size_t min_len, void **data,
2198 		u32 *dlen)
2199 {
2200 	struct smb2_query_info_req *req;
2201 	struct smb2_query_info_rsp *rsp = NULL;
2202 	struct kvec iov[2];
2203 	struct kvec rsp_iov;
2204 	int rc = 0;
2205 	int resp_buftype;
2206 	struct cifs_ses *ses = tcon->ses;
2207 	int flags = 0;
2208 
2209 	cifs_dbg(FYI, "Query Info\n");
2210 
2211 	if (!ses || !(ses->server))
2212 		return -EIO;
2213 
2214 	rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
2215 	if (rc)
2216 		return rc;
2217 
2218 	if (encryption_required(tcon))
2219 		flags |= CIFS_TRANSFORM_REQ;
2220 
2221 	req->InfoType = info_type;
2222 	req->FileInfoClass = info_class;
2223 	req->PersistentFileId = persistent_fid;
2224 	req->VolatileFileId = volatile_fid;
2225 	req->AdditionalInformation = cpu_to_le32(additional_info);
2226 
2227 	/*
2228 	 * We do not use the input buffer (do not send extra byte)
2229 	 */
2230 	req->InputBufferOffset = 0;
2231 	inc_rfc1001_len(req, -1);
2232 
2233 	req->OutputBufferLength = cpu_to_le32(output_len);
2234 
2235 	iov[0].iov_base = (char *)req;
2236 	/* 4 for rfc1002 length field */
2237 	iov[0].iov_len = get_rfc1002_length(req) + 4;
2238 
2239 	rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
2240 	cifs_small_buf_release(req);
2241 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
2242 
2243 	if (rc) {
2244 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
2245 		goto qinf_exit;
2246 	}
2247 
2248 	if (dlen) {
2249 		*dlen = le32_to_cpu(rsp->OutputBufferLength);
2250 		if (!*data) {
2251 			*data = kmalloc(*dlen, GFP_KERNEL);
2252 			if (!*data) {
2253 				cifs_dbg(VFS,
2254 					"Error %d allocating memory for acl\n",
2255 					rc);
2256 				*dlen = 0;
2257 				goto qinf_exit;
2258 			}
2259 		}
2260 	}
2261 
2262 	rc = validate_and_copy_buf(le16_to_cpu(rsp->OutputBufferOffset),
2263 				   le32_to_cpu(rsp->OutputBufferLength),
2264 				   &rsp->hdr, min_len, *data);
2265 
2266 qinf_exit:
2267 	free_rsp_buf(resp_buftype, rsp);
2268 	return rc;
2269 }
2270 
SMB2_query_eas(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,int ea_buf_size,struct smb2_file_full_ea_info * data)2271 int SMB2_query_eas(const unsigned int xid, struct cifs_tcon *tcon,
2272 		   u64 persistent_fid, u64 volatile_fid,
2273 		   int ea_buf_size, struct smb2_file_full_ea_info *data)
2274 {
2275 	return query_info(xid, tcon, persistent_fid, volatile_fid,
2276 			  FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE, 0,
2277 			  ea_buf_size,
2278 			  sizeof(struct smb2_file_full_ea_info),
2279 			  (void **)&data,
2280 			  NULL);
2281 }
2282 
SMB2_query_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct smb2_file_all_info * data)2283 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
2284 	u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
2285 {
2286 	return query_info(xid, tcon, persistent_fid, volatile_fid,
2287 			  FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
2288 			  sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
2289 			  sizeof(struct smb2_file_all_info), (void **)&data,
2290 			  NULL);
2291 }
2292 
2293 int
SMB2_query_acl(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,void ** data,u32 * plen)2294 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
2295 		u64 persistent_fid, u64 volatile_fid,
2296 		void **data, u32 *plen)
2297 {
2298 	__u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO;
2299 	*plen = 0;
2300 
2301 	return query_info(xid, tcon, persistent_fid, volatile_fid,
2302 			  0, SMB2_O_INFO_SECURITY, additional_info,
2303 			  SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
2304 }
2305 
2306 int
SMB2_get_srv_num(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,__le64 * uniqueid)2307 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
2308 		 u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
2309 {
2310 	return query_info(xid, tcon, persistent_fid, volatile_fid,
2311 			  FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
2312 			  sizeof(struct smb2_file_internal_info),
2313 			  sizeof(struct smb2_file_internal_info),
2314 			  (void **)&uniqueid, NULL);
2315 }
2316 
2317 /*
2318  * This is a no-op for now. We're not really interested in the reply, but
2319  * rather in the fact that the server sent one and that server->lstrp
2320  * gets updated.
2321  *
2322  * FIXME: maybe we should consider checking that the reply matches request?
2323  */
2324 static void
smb2_echo_callback(struct mid_q_entry * mid)2325 smb2_echo_callback(struct mid_q_entry *mid)
2326 {
2327 	struct TCP_Server_Info *server = mid->callback_data;
2328 	struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
2329 	unsigned int credits_received = 1;
2330 
2331 	if (mid->mid_state == MID_RESPONSE_RECEIVED)
2332 		credits_received = le16_to_cpu(rsp->hdr.sync_hdr.CreditRequest);
2333 
2334 	DeleteMidQEntry(mid);
2335 	add_credits(server, credits_received, CIFS_ECHO_OP);
2336 }
2337 
smb2_reconnect_server(struct work_struct * work)2338 void smb2_reconnect_server(struct work_struct *work)
2339 {
2340 	struct TCP_Server_Info *server = container_of(work,
2341 					struct TCP_Server_Info, reconnect.work);
2342 	struct cifs_ses *ses;
2343 	struct cifs_tcon *tcon, *tcon2;
2344 	struct list_head tmp_list;
2345 	int tcon_exist = false;
2346 	int rc;
2347 	int resched = false;
2348 
2349 
2350 	/* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
2351 	mutex_lock(&server->reconnect_mutex);
2352 
2353 	INIT_LIST_HEAD(&tmp_list);
2354 	cifs_dbg(FYI, "Need negotiate, reconnecting tcons\n");
2355 
2356 	spin_lock(&cifs_tcp_ses_lock);
2357 	list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
2358 		list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
2359 			if (tcon->need_reconnect || tcon->need_reopen_files) {
2360 				tcon->tc_count++;
2361 				list_add_tail(&tcon->rlist, &tmp_list);
2362 				tcon_exist = true;
2363 			}
2364 		}
2365 	}
2366 	/*
2367 	 * Get the reference to server struct to be sure that the last call of
2368 	 * cifs_put_tcon() in the loop below won't release the server pointer.
2369 	 */
2370 	if (tcon_exist)
2371 		server->srv_count++;
2372 
2373 	spin_unlock(&cifs_tcp_ses_lock);
2374 
2375 	list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
2376 		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon);
2377 		if (!rc)
2378 			cifs_reopen_persistent_handles(tcon);
2379 		else
2380 			resched = true;
2381 		list_del_init(&tcon->rlist);
2382 		cifs_put_tcon(tcon);
2383 	}
2384 
2385 	cifs_dbg(FYI, "Reconnecting tcons finished\n");
2386 	if (resched)
2387 		queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
2388 	mutex_unlock(&server->reconnect_mutex);
2389 
2390 	/* now we can safely release srv struct */
2391 	if (tcon_exist)
2392 		cifs_put_tcp_session(server, 1);
2393 }
2394 
2395 int
SMB2_echo(struct TCP_Server_Info * server)2396 SMB2_echo(struct TCP_Server_Info *server)
2397 {
2398 	struct smb2_echo_req *req;
2399 	int rc = 0;
2400 	struct kvec iov[2];
2401 	struct smb_rqst rqst = { .rq_iov = iov,
2402 				 .rq_nvec = 2 };
2403 
2404 	cifs_dbg(FYI, "In echo request\n");
2405 
2406 	if (server->tcpStatus == CifsNeedNegotiate) {
2407 		/* No need to send echo on newly established connections */
2408 		queue_delayed_work(cifsiod_wq, &server->reconnect, 0);
2409 		return rc;
2410 	}
2411 
2412 	rc = small_smb2_init(SMB2_ECHO, NULL, (void **)&req);
2413 	if (rc)
2414 		return rc;
2415 
2416 	req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1);
2417 
2418 	/* 4 for rfc1002 length field */
2419 	iov[0].iov_len = 4;
2420 	iov[0].iov_base = (char *)req;
2421 	iov[1].iov_len = get_rfc1002_length(req);
2422 	iov[1].iov_base = (char *)req + 4;
2423 
2424 	rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
2425 			     server, CIFS_ECHO_OP);
2426 	if (rc)
2427 		cifs_dbg(FYI, "Echo request failed: %d\n", rc);
2428 
2429 	cifs_small_buf_release(req);
2430 	return rc;
2431 }
2432 
2433 int
SMB2_flush(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)2434 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
2435 	   u64 volatile_fid)
2436 {
2437 	struct smb2_flush_req *req;
2438 	struct cifs_ses *ses = tcon->ses;
2439 	struct kvec iov[1];
2440 	struct kvec rsp_iov;
2441 	int resp_buftype;
2442 	int rc = 0;
2443 	int flags = 0;
2444 
2445 	cifs_dbg(FYI, "Flush\n");
2446 
2447 	if (!ses || !(ses->server))
2448 		return -EIO;
2449 
2450 	rc = small_smb2_init(SMB2_FLUSH, tcon, (void **) &req);
2451 	if (rc)
2452 		return rc;
2453 
2454 	if (encryption_required(tcon))
2455 		flags |= CIFS_TRANSFORM_REQ;
2456 
2457 	req->PersistentFileId = persistent_fid;
2458 	req->VolatileFileId = volatile_fid;
2459 
2460 	iov[0].iov_base = (char *)req;
2461 	/* 4 for rfc1002 length field */
2462 	iov[0].iov_len = get_rfc1002_length(req) + 4;
2463 
2464 	rc = SendReceive2(xid, ses, iov, 1, &resp_buftype, flags, &rsp_iov);
2465 	cifs_small_buf_release(req);
2466 
2467 	if (rc != 0)
2468 		cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
2469 
2470 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
2471 	return rc;
2472 }
2473 
2474 /*
2475  * To form a chain of read requests, any read requests after the first should
2476  * have the end_of_chain boolean set to true.
2477  */
2478 static int
smb2_new_read_req(void ** buf,unsigned int * total_len,struct cifs_io_parms * io_parms,unsigned int remaining_bytes,int request_type)2479 smb2_new_read_req(void **buf, unsigned int *total_len,
2480 		  struct cifs_io_parms *io_parms, unsigned int remaining_bytes,
2481 		  int request_type)
2482 {
2483 	int rc = -EACCES;
2484 	struct smb2_read_plain_req *req = NULL;
2485 	struct smb2_sync_hdr *shdr;
2486 
2487 	rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, (void **) &req,
2488 				 total_len);
2489 	if (rc)
2490 		return rc;
2491 	if (io_parms->tcon->ses->server == NULL)
2492 		return -ECONNABORTED;
2493 
2494 	shdr = &req->sync_hdr;
2495 	shdr->ProcessId = cpu_to_le32(io_parms->pid);
2496 
2497 	req->PersistentFileId = io_parms->persistent_fid;
2498 	req->VolatileFileId = io_parms->volatile_fid;
2499 	req->ReadChannelInfoOffset = 0; /* reserved */
2500 	req->ReadChannelInfoLength = 0; /* reserved */
2501 	req->Channel = 0; /* reserved */
2502 	req->MinimumCount = 0;
2503 	req->Length = cpu_to_le32(io_parms->length);
2504 	req->Offset = cpu_to_le64(io_parms->offset);
2505 
2506 	if (request_type & CHAINED_REQUEST) {
2507 		if (!(request_type & END_OF_CHAIN)) {
2508 			/* next 8-byte aligned request */
2509 			*total_len = DIV_ROUND_UP(*total_len, 8) * 8;
2510 			shdr->NextCommand = cpu_to_le32(*total_len);
2511 		} else /* END_OF_CHAIN */
2512 			shdr->NextCommand = 0;
2513 		if (request_type & RELATED_REQUEST) {
2514 			shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
2515 			/*
2516 			 * Related requests use info from previous read request
2517 			 * in chain.
2518 			 */
2519 			shdr->SessionId = 0xFFFFFFFF;
2520 			shdr->TreeId = 0xFFFFFFFF;
2521 			req->PersistentFileId = 0xFFFFFFFF;
2522 			req->VolatileFileId = 0xFFFFFFFF;
2523 		}
2524 	}
2525 	if (remaining_bytes > io_parms->length)
2526 		req->RemainingBytes = cpu_to_le32(remaining_bytes);
2527 	else
2528 		req->RemainingBytes = 0;
2529 
2530 	*buf = req;
2531 	return rc;
2532 }
2533 
2534 static void
smb2_readv_callback(struct mid_q_entry * mid)2535 smb2_readv_callback(struct mid_q_entry *mid)
2536 {
2537 	struct cifs_readdata *rdata = mid->callback_data;
2538 	struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
2539 	struct TCP_Server_Info *server = tcon->ses->server;
2540 	struct smb2_sync_hdr *shdr =
2541 				(struct smb2_sync_hdr *)rdata->iov[1].iov_base;
2542 	unsigned int credits_received = 1;
2543 	struct smb_rqst rqst = { .rq_iov = rdata->iov,
2544 				 .rq_nvec = 2,
2545 				 .rq_pages = rdata->pages,
2546 				 .rq_npages = rdata->nr_pages,
2547 				 .rq_pagesz = rdata->pagesz,
2548 				 .rq_tailsz = rdata->tailsz };
2549 
2550 	cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
2551 		 __func__, mid->mid, mid->mid_state, rdata->result,
2552 		 rdata->bytes);
2553 
2554 	switch (mid->mid_state) {
2555 	case MID_RESPONSE_RECEIVED:
2556 		credits_received = le16_to_cpu(shdr->CreditRequest);
2557 		/* result already set, check signature */
2558 		if (server->sign && !mid->decrypted) {
2559 			int rc;
2560 
2561 			rc = smb2_verify_signature(&rqst, server);
2562 			if (rc)
2563 				cifs_dbg(VFS, "SMB signature verification returned error = %d\n",
2564 					 rc);
2565 		}
2566 		/* FIXME: should this be counted toward the initiating task? */
2567 		task_io_account_read(rdata->got_bytes);
2568 		cifs_stats_bytes_read(tcon, rdata->got_bytes);
2569 		break;
2570 	case MID_REQUEST_SUBMITTED:
2571 	case MID_RETRY_NEEDED:
2572 		rdata->result = -EAGAIN;
2573 		if (server->sign && rdata->got_bytes)
2574 			/* reset bytes number since we can not check a sign */
2575 			rdata->got_bytes = 0;
2576 		/* FIXME: should this be counted toward the initiating task? */
2577 		task_io_account_read(rdata->got_bytes);
2578 		cifs_stats_bytes_read(tcon, rdata->got_bytes);
2579 		break;
2580 	default:
2581 		if (rdata->result != -ENODATA)
2582 			rdata->result = -EIO;
2583 	}
2584 
2585 	if (rdata->result)
2586 		cifs_stats_fail_inc(tcon, SMB2_READ_HE);
2587 
2588 	queue_work(cifsiod_wq, &rdata->work);
2589 	DeleteMidQEntry(mid);
2590 	add_credits(server, credits_received, 0);
2591 }
2592 
2593 /* smb2_async_readv - send an async read, and set up mid to handle result */
2594 int
smb2_async_readv(struct cifs_readdata * rdata)2595 smb2_async_readv(struct cifs_readdata *rdata)
2596 {
2597 	int rc, flags = 0;
2598 	char *buf;
2599 	struct smb2_sync_hdr *shdr;
2600 	struct cifs_io_parms io_parms;
2601 	struct smb_rqst rqst = { .rq_iov = rdata->iov,
2602 				 .rq_nvec = 2 };
2603 	struct TCP_Server_Info *server;
2604 	unsigned int total_len;
2605 	__be32 req_len;
2606 
2607 	cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
2608 		 __func__, rdata->offset, rdata->bytes);
2609 
2610 	io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
2611 	io_parms.offset = rdata->offset;
2612 	io_parms.length = rdata->bytes;
2613 	io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
2614 	io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
2615 	io_parms.pid = rdata->pid;
2616 
2617 	server = io_parms.tcon->ses->server;
2618 
2619 	rc = smb2_new_read_req((void **) &buf, &total_len, &io_parms, 0, 0);
2620 	if (rc) {
2621 		if (rc == -EAGAIN && rdata->credits) {
2622 			/* credits was reset by reconnect */
2623 			rdata->credits = 0;
2624 			/* reduce in_flight value since we won't send the req */
2625 			spin_lock(&server->req_lock);
2626 			server->in_flight--;
2627 			spin_unlock(&server->req_lock);
2628 		}
2629 		return rc;
2630 	}
2631 
2632 	if (encryption_required(io_parms.tcon))
2633 		flags |= CIFS_TRANSFORM_REQ;
2634 
2635 	req_len = cpu_to_be32(total_len);
2636 
2637 	rdata->iov[0].iov_base = &req_len;
2638 	rdata->iov[0].iov_len = sizeof(__be32);
2639 	rdata->iov[1].iov_base = buf;
2640 	rdata->iov[1].iov_len = total_len;
2641 
2642 	shdr = (struct smb2_sync_hdr *)buf;
2643 
2644 	if (rdata->credits) {
2645 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
2646 						SMB2_MAX_BUFFER_SIZE));
2647 		shdr->CreditRequest =
2648 			cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 1);
2649 		spin_lock(&server->req_lock);
2650 		server->credits += rdata->credits -
2651 						le16_to_cpu(shdr->CreditCharge);
2652 		spin_unlock(&server->req_lock);
2653 		wake_up(&server->request_q);
2654 		rdata->credits = le16_to_cpu(shdr->CreditCharge);
2655 		flags |= CIFS_HAS_CREDITS;
2656 	}
2657 
2658 	kref_get(&rdata->refcount);
2659 	rc = cifs_call_async(io_parms.tcon->ses->server, &rqst,
2660 			     cifs_readv_receive, smb2_readv_callback,
2661 			     smb3_handle_read_data, rdata, flags);
2662 	if (rc) {
2663 		kref_put(&rdata->refcount, cifs_readdata_release);
2664 		cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
2665 	}
2666 
2667 	cifs_small_buf_release(buf);
2668 	return rc;
2669 }
2670 
2671 int
SMB2_read(const unsigned int xid,struct cifs_io_parms * io_parms,unsigned int * nbytes,char ** buf,int * buf_type)2672 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
2673 	  unsigned int *nbytes, char **buf, int *buf_type)
2674 {
2675 	int resp_buftype, rc = -EACCES;
2676 	struct smb2_read_plain_req *req = NULL;
2677 	struct smb2_read_rsp *rsp = NULL;
2678 	struct smb2_sync_hdr *shdr;
2679 	struct kvec iov[2];
2680 	struct kvec rsp_iov;
2681 	unsigned int total_len;
2682 	__be32 req_len;
2683 	struct smb_rqst rqst = { .rq_iov = iov,
2684 				 .rq_nvec = 2 };
2685 	int flags = CIFS_LOG_ERROR;
2686 	struct cifs_ses *ses = io_parms->tcon->ses;
2687 
2688 	*nbytes = 0;
2689 	rc = smb2_new_read_req((void **)&req, &total_len, io_parms, 0, 0);
2690 	if (rc)
2691 		return rc;
2692 
2693 	if (encryption_required(io_parms->tcon))
2694 		flags |= CIFS_TRANSFORM_REQ;
2695 
2696 	req_len = cpu_to_be32(total_len);
2697 
2698 	iov[0].iov_base = &req_len;
2699 	iov[0].iov_len = sizeof(__be32);
2700 	iov[1].iov_base = req;
2701 	iov[1].iov_len = total_len;
2702 
2703 	rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
2704 	cifs_small_buf_release(req);
2705 
2706 	rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
2707 
2708 	if (rc) {
2709 		if (rc != -ENODATA) {
2710 			cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
2711 			cifs_dbg(VFS, "Send error in read = %d\n", rc);
2712 		}
2713 		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
2714 		return rc == -ENODATA ? 0 : rc;
2715 	}
2716 
2717 	*nbytes = le32_to_cpu(rsp->DataLength);
2718 	if ((*nbytes > CIFS_MAX_MSGSIZE) ||
2719 	    (*nbytes > io_parms->length)) {
2720 		cifs_dbg(FYI, "bad length %d for count %d\n",
2721 			 *nbytes, io_parms->length);
2722 		rc = -EIO;
2723 		*nbytes = 0;
2724 	}
2725 
2726 	shdr = get_sync_hdr(rsp);
2727 
2728 	if (*buf) {
2729 		memcpy(*buf, (char *)shdr + rsp->DataOffset, *nbytes);
2730 		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
2731 	} else if (resp_buftype != CIFS_NO_BUFFER) {
2732 		*buf = rsp_iov.iov_base;
2733 		if (resp_buftype == CIFS_SMALL_BUFFER)
2734 			*buf_type = CIFS_SMALL_BUFFER;
2735 		else if (resp_buftype == CIFS_LARGE_BUFFER)
2736 			*buf_type = CIFS_LARGE_BUFFER;
2737 	}
2738 	return rc;
2739 }
2740 
2741 /*
2742  * Check the mid_state and signature on received buffer (if any), and queue the
2743  * workqueue completion task.
2744  */
2745 static void
smb2_writev_callback(struct mid_q_entry * mid)2746 smb2_writev_callback(struct mid_q_entry *mid)
2747 {
2748 	struct cifs_writedata *wdata = mid->callback_data;
2749 	struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
2750 	unsigned int written;
2751 	struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
2752 	unsigned int credits_received = 1;
2753 
2754 	switch (mid->mid_state) {
2755 	case MID_RESPONSE_RECEIVED:
2756 		credits_received = le16_to_cpu(rsp->hdr.sync_hdr.CreditRequest);
2757 		wdata->result = smb2_check_receive(mid, tcon->ses->server, 0);
2758 		if (wdata->result != 0)
2759 			break;
2760 
2761 		written = le32_to_cpu(rsp->DataLength);
2762 		/*
2763 		 * Mask off high 16 bits when bytes written as returned
2764 		 * by the server is greater than bytes requested by the
2765 		 * client. OS/2 servers are known to set incorrect
2766 		 * CountHigh values.
2767 		 */
2768 		if (written > wdata->bytes)
2769 			written &= 0xFFFF;
2770 
2771 		if (written < wdata->bytes)
2772 			wdata->result = -ENOSPC;
2773 		else
2774 			wdata->bytes = written;
2775 		break;
2776 	case MID_REQUEST_SUBMITTED:
2777 	case MID_RETRY_NEEDED:
2778 		wdata->result = -EAGAIN;
2779 		break;
2780 	default:
2781 		wdata->result = -EIO;
2782 		break;
2783 	}
2784 
2785 	if (wdata->result)
2786 		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
2787 
2788 	queue_work(cifsiod_wq, &wdata->work);
2789 	DeleteMidQEntry(mid);
2790 	add_credits(tcon->ses->server, credits_received, 0);
2791 }
2792 
2793 /* smb2_async_writev - send an async write, and set up mid to handle result */
2794 int
smb2_async_writev(struct cifs_writedata * wdata,void (* release)(struct kref * kref))2795 smb2_async_writev(struct cifs_writedata *wdata,
2796 		  void (*release)(struct kref *kref))
2797 {
2798 	int rc = -EACCES, flags = 0;
2799 	struct smb2_write_req *req = NULL;
2800 	struct smb2_sync_hdr *shdr;
2801 	struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
2802 	struct TCP_Server_Info *server = tcon->ses->server;
2803 	struct kvec iov[2];
2804 	struct smb_rqst rqst = { };
2805 
2806 	rc = small_smb2_init(SMB2_WRITE, tcon, (void **) &req);
2807 	if (rc) {
2808 		if (rc == -EAGAIN && wdata->credits) {
2809 			/* credits was reset by reconnect */
2810 			wdata->credits = 0;
2811 			/* reduce in_flight value since we won't send the req */
2812 			spin_lock(&server->req_lock);
2813 			server->in_flight--;
2814 			spin_unlock(&server->req_lock);
2815 		}
2816 		goto async_writev_out;
2817 	}
2818 
2819 	if (encryption_required(tcon))
2820 		flags |= CIFS_TRANSFORM_REQ;
2821 
2822 	shdr = get_sync_hdr(req);
2823 	shdr->ProcessId = cpu_to_le32(wdata->cfile->pid);
2824 
2825 	req->PersistentFileId = wdata->cfile->fid.persistent_fid;
2826 	req->VolatileFileId = wdata->cfile->fid.volatile_fid;
2827 	req->WriteChannelInfoOffset = 0;
2828 	req->WriteChannelInfoLength = 0;
2829 	req->Channel = 0;
2830 	req->Offset = cpu_to_le64(wdata->offset);
2831 	/* 4 for rfc1002 length field */
2832 	req->DataOffset = cpu_to_le16(
2833 				offsetof(struct smb2_write_req, Buffer) - 4);
2834 	req->RemainingBytes = 0;
2835 
2836 	/* 4 for rfc1002 length field and 1 for Buffer */
2837 	iov[0].iov_len = 4;
2838 	iov[0].iov_base = req;
2839 	iov[1].iov_len = get_rfc1002_length(req) - 1;
2840 	iov[1].iov_base = (char *)req + 4;
2841 
2842 	rqst.rq_iov = iov;
2843 	rqst.rq_nvec = 2;
2844 	rqst.rq_pages = wdata->pages;
2845 	rqst.rq_npages = wdata->nr_pages;
2846 	rqst.rq_pagesz = wdata->pagesz;
2847 	rqst.rq_tailsz = wdata->tailsz;
2848 
2849 	cifs_dbg(FYI, "async write at %llu %u bytes\n",
2850 		 wdata->offset, wdata->bytes);
2851 
2852 	req->Length = cpu_to_le32(wdata->bytes);
2853 
2854 	inc_rfc1001_len(&req->hdr, wdata->bytes - 1 /* Buffer */);
2855 
2856 	if (wdata->credits) {
2857 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
2858 						    SMB2_MAX_BUFFER_SIZE));
2859 		shdr->CreditRequest =
2860 			cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 1);
2861 		spin_lock(&server->req_lock);
2862 		server->credits += wdata->credits -
2863 						le16_to_cpu(shdr->CreditCharge);
2864 		spin_unlock(&server->req_lock);
2865 		wake_up(&server->request_q);
2866 		wdata->credits = le16_to_cpu(shdr->CreditCharge);
2867 		flags |= CIFS_HAS_CREDITS;
2868 	}
2869 
2870 	kref_get(&wdata->refcount);
2871 	rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
2872 			     wdata, flags);
2873 
2874 	if (rc) {
2875 		kref_put(&wdata->refcount, release);
2876 		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
2877 	}
2878 
2879 async_writev_out:
2880 	cifs_small_buf_release(req);
2881 	return rc;
2882 }
2883 
2884 /*
2885  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
2886  * The length field from io_parms must be at least 1 and indicates a number of
2887  * elements with data to write that begins with position 1 in iov array. All
2888  * data length is specified by count.
2889  */
2890 int
SMB2_write(const unsigned int xid,struct cifs_io_parms * io_parms,unsigned int * nbytes,struct kvec * iov,int n_vec)2891 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
2892 	   unsigned int *nbytes, struct kvec *iov, int n_vec)
2893 {
2894 	int rc = 0;
2895 	struct smb2_write_req *req = NULL;
2896 	struct smb2_write_rsp *rsp = NULL;
2897 	int resp_buftype;
2898 	struct kvec rsp_iov;
2899 	int flags = 0;
2900 
2901 	*nbytes = 0;
2902 
2903 	if (n_vec < 1)
2904 		return rc;
2905 
2906 	rc = small_smb2_init(SMB2_WRITE, io_parms->tcon, (void **) &req);
2907 	if (rc)
2908 		return rc;
2909 
2910 	if (io_parms->tcon->ses->server == NULL)
2911 		return -ECONNABORTED;
2912 
2913 	if (encryption_required(io_parms->tcon))
2914 		flags |= CIFS_TRANSFORM_REQ;
2915 
2916 	req->hdr.sync_hdr.ProcessId = cpu_to_le32(io_parms->pid);
2917 
2918 	req->PersistentFileId = io_parms->persistent_fid;
2919 	req->VolatileFileId = io_parms->volatile_fid;
2920 	req->WriteChannelInfoOffset = 0;
2921 	req->WriteChannelInfoLength = 0;
2922 	req->Channel = 0;
2923 	req->Length = cpu_to_le32(io_parms->length);
2924 	req->Offset = cpu_to_le64(io_parms->offset);
2925 	/* 4 for rfc1002 length field */
2926 	req->DataOffset = cpu_to_le16(
2927 				offsetof(struct smb2_write_req, Buffer) - 4);
2928 	req->RemainingBytes = 0;
2929 
2930 	iov[0].iov_base = (char *)req;
2931 	/* 4 for rfc1002 length field and 1 for Buffer */
2932 	iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
2933 
2934 	/* length of entire message including data to be written */
2935 	inc_rfc1001_len(req, io_parms->length - 1 /* Buffer */);
2936 
2937 	rc = SendReceive2(xid, io_parms->tcon->ses, iov, n_vec + 1,
2938 			  &resp_buftype, flags, &rsp_iov);
2939 	cifs_small_buf_release(req);
2940 	rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
2941 
2942 	if (rc) {
2943 		cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
2944 		cifs_dbg(VFS, "Send error in write = %d\n", rc);
2945 	} else
2946 		*nbytes = le32_to_cpu(rsp->DataLength);
2947 
2948 	free_rsp_buf(resp_buftype, rsp);
2949 	return rc;
2950 }
2951 
2952 static unsigned int
num_entries(char * bufstart,char * end_of_buf,char ** lastentry,size_t size)2953 num_entries(char *bufstart, char *end_of_buf, char **lastentry, size_t size)
2954 {
2955 	int len;
2956 	unsigned int entrycount = 0;
2957 	unsigned int next_offset = 0;
2958 	char *entryptr;
2959 	FILE_DIRECTORY_INFO *dir_info;
2960 
2961 	if (bufstart == NULL)
2962 		return 0;
2963 
2964 	entryptr = bufstart;
2965 
2966 	while (1) {
2967 		if (entryptr + next_offset < entryptr ||
2968 		    entryptr + next_offset > end_of_buf ||
2969 		    entryptr + next_offset + size > end_of_buf) {
2970 			cifs_dbg(VFS, "malformed search entry would overflow\n");
2971 			break;
2972 		}
2973 
2974 		entryptr = entryptr + next_offset;
2975 		dir_info = (FILE_DIRECTORY_INFO *)entryptr;
2976 
2977 		len = le32_to_cpu(dir_info->FileNameLength);
2978 		if (entryptr + len < entryptr ||
2979 		    entryptr + len > end_of_buf ||
2980 		    entryptr + len + size > end_of_buf) {
2981 			cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
2982 				 end_of_buf);
2983 			break;
2984 		}
2985 
2986 		*lastentry = entryptr;
2987 		entrycount++;
2988 
2989 		next_offset = le32_to_cpu(dir_info->NextEntryOffset);
2990 		if (!next_offset)
2991 			break;
2992 	}
2993 
2994 	return entrycount;
2995 }
2996 
2997 /*
2998  * Readdir/FindFirst
2999  */
3000 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)3001 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
3002 		     u64 persistent_fid, u64 volatile_fid, int index,
3003 		     struct cifs_search_info *srch_inf)
3004 {
3005 	struct smb2_query_directory_req *req;
3006 	struct smb2_query_directory_rsp *rsp = NULL;
3007 	struct kvec iov[2];
3008 	struct kvec rsp_iov;
3009 	int rc = 0;
3010 	int len;
3011 	int resp_buftype = CIFS_NO_BUFFER;
3012 	unsigned char *bufptr;
3013 	struct TCP_Server_Info *server;
3014 	struct cifs_ses *ses = tcon->ses;
3015 	__le16 asteriks = cpu_to_le16('*');
3016 	char *end_of_smb;
3017 	unsigned int output_size = CIFSMaxBufSize;
3018 	size_t info_buf_size;
3019 	int flags = 0;
3020 
3021 	if (ses && (ses->server))
3022 		server = ses->server;
3023 	else
3024 		return -EIO;
3025 
3026 	rc = small_smb2_init(SMB2_QUERY_DIRECTORY, tcon, (void **) &req);
3027 	if (rc)
3028 		return rc;
3029 
3030 	if (encryption_required(tcon))
3031 		flags |= CIFS_TRANSFORM_REQ;
3032 
3033 	switch (srch_inf->info_level) {
3034 	case SMB_FIND_FILE_DIRECTORY_INFO:
3035 		req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
3036 		info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
3037 		break;
3038 	case SMB_FIND_FILE_ID_FULL_DIR_INFO:
3039 		req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
3040 		info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
3041 		break;
3042 	default:
3043 		cifs_dbg(VFS, "info level %u isn't supported\n",
3044 			 srch_inf->info_level);
3045 		rc = -EINVAL;
3046 		goto qdir_exit;
3047 	}
3048 
3049 	req->FileIndex = cpu_to_le32(index);
3050 	req->PersistentFileId = persistent_fid;
3051 	req->VolatileFileId = volatile_fid;
3052 
3053 	len = 0x2;
3054 	bufptr = req->Buffer;
3055 	memcpy(bufptr, &asteriks, len);
3056 
3057 	req->FileNameOffset =
3058 		cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1 - 4);
3059 	req->FileNameLength = cpu_to_le16(len);
3060 	/*
3061 	 * BB could be 30 bytes or so longer if we used SMB2 specific
3062 	 * buffer lengths, but this is safe and close enough.
3063 	 */
3064 	output_size = min_t(unsigned int, output_size, server->maxBuf);
3065 	output_size = min_t(unsigned int, output_size, 2 << 15);
3066 	req->OutputBufferLength = cpu_to_le32(output_size);
3067 
3068 	iov[0].iov_base = (char *)req;
3069 	/* 4 for RFC1001 length and 1 for Buffer */
3070 	iov[0].iov_len = get_rfc1002_length(req) + 4 - 1;
3071 
3072 	iov[1].iov_base = (char *)(req->Buffer);
3073 	iov[1].iov_len = len;
3074 
3075 	inc_rfc1001_len(req, len - 1 /* Buffer */);
3076 
3077 	rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, flags, &rsp_iov);
3078 	cifs_small_buf_release(req);
3079 	rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
3080 
3081 	if (rc) {
3082 		if (rc == -ENODATA &&
3083 		    rsp->hdr.sync_hdr.Status == STATUS_NO_MORE_FILES) {
3084 			srch_inf->endOfSearch = true;
3085 			rc = 0;
3086 		} else
3087 			cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
3088 		goto qdir_exit;
3089 	}
3090 
3091 	rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
3092 			  le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
3093 			  info_buf_size);
3094 	if (rc)
3095 		goto qdir_exit;
3096 
3097 	srch_inf->unicode = true;
3098 
3099 	if (srch_inf->ntwrk_buf_start) {
3100 		if (srch_inf->smallBuf)
3101 			cifs_small_buf_release(srch_inf->ntwrk_buf_start);
3102 		else
3103 			cifs_buf_release(srch_inf->ntwrk_buf_start);
3104 	}
3105 	srch_inf->ntwrk_buf_start = (char *)rsp;
3106 	srch_inf->srch_entries_start = srch_inf->last_entry = 4 /* rfclen */ +
3107 		(char *)&rsp->hdr + le16_to_cpu(rsp->OutputBufferOffset);
3108 	/* 4 for rfc1002 length field */
3109 	end_of_smb = get_rfc1002_length(rsp) + 4 + (char *)&rsp->hdr;
3110 	srch_inf->entries_in_buffer =
3111 			num_entries(srch_inf->srch_entries_start, end_of_smb,
3112 				    &srch_inf->last_entry, info_buf_size);
3113 	srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
3114 	cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
3115 		 srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
3116 		 srch_inf->srch_entries_start, srch_inf->last_entry);
3117 	if (resp_buftype == CIFS_LARGE_BUFFER)
3118 		srch_inf->smallBuf = false;
3119 	else if (resp_buftype == CIFS_SMALL_BUFFER)
3120 		srch_inf->smallBuf = true;
3121 	else
3122 		cifs_dbg(VFS, "illegal search buffer type\n");
3123 
3124 	return rc;
3125 
3126 qdir_exit:
3127 	free_rsp_buf(resp_buftype, rsp);
3128 	return rc;
3129 }
3130 
3131 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)3132 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
3133 	       u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
3134 	       u8 info_type, u32 additional_info, unsigned int num,
3135 		void **data, unsigned int *size)
3136 {
3137 	struct smb2_set_info_req *req;
3138 	struct smb2_set_info_rsp *rsp = NULL;
3139 	struct kvec *iov;
3140 	struct kvec rsp_iov;
3141 	int rc = 0;
3142 	int resp_buftype;
3143 	unsigned int i;
3144 	struct cifs_ses *ses = tcon->ses;
3145 	int flags = 0;
3146 
3147 	if (!ses || !(ses->server))
3148 		return -EIO;
3149 
3150 	if (!num)
3151 		return -EINVAL;
3152 
3153 	iov = kmalloc(sizeof(struct kvec) * num, GFP_KERNEL);
3154 	if (!iov)
3155 		return -ENOMEM;
3156 
3157 	rc = small_smb2_init(SMB2_SET_INFO, tcon, (void **) &req);
3158 	if (rc) {
3159 		kfree(iov);
3160 		return rc;
3161 	}
3162 
3163 	if (encryption_required(tcon))
3164 		flags |= CIFS_TRANSFORM_REQ;
3165 
3166 	req->hdr.sync_hdr.ProcessId = cpu_to_le32(pid);
3167 
3168 	req->InfoType = info_type;
3169 	req->FileInfoClass = info_class;
3170 	req->PersistentFileId = persistent_fid;
3171 	req->VolatileFileId = volatile_fid;
3172 	req->AdditionalInformation = cpu_to_le32(additional_info);
3173 
3174 	/* 4 for RFC1001 length and 1 for Buffer */
3175 	req->BufferOffset =
3176 			cpu_to_le16(sizeof(struct smb2_set_info_req) - 1 - 4);
3177 	req->BufferLength = cpu_to_le32(*size);
3178 
3179 	inc_rfc1001_len(req, *size - 1 /* Buffer */);
3180 
3181 	memcpy(req->Buffer, *data, *size);
3182 
3183 	iov[0].iov_base = (char *)req;
3184 	/* 4 for RFC1001 length */
3185 	iov[0].iov_len = get_rfc1002_length(req) + 4;
3186 
3187 	for (i = 1; i < num; i++) {
3188 		inc_rfc1001_len(req, size[i]);
3189 		le32_add_cpu(&req->BufferLength, size[i]);
3190 		iov[i].iov_base = (char *)data[i];
3191 		iov[i].iov_len = size[i];
3192 	}
3193 
3194 	rc = SendReceive2(xid, ses, iov, num, &resp_buftype, flags, &rsp_iov);
3195 	cifs_small_buf_release(req);
3196 	rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
3197 
3198 	if (rc != 0)
3199 		cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
3200 
3201 	free_rsp_buf(resp_buftype, rsp);
3202 	kfree(iov);
3203 	return rc;
3204 }
3205 
3206 int
SMB2_rename(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,__le16 * target_file)3207 SMB2_rename(const unsigned int xid, struct cifs_tcon *tcon,
3208 	    u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
3209 {
3210 	struct smb2_file_rename_info info;
3211 	void **data;
3212 	unsigned int size[2];
3213 	int rc;
3214 	int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
3215 
3216 	data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
3217 	if (!data)
3218 		return -ENOMEM;
3219 
3220 	info.ReplaceIfExists = 1; /* 1 = replace existing target with new */
3221 			      /* 0 = fail if target already exists */
3222 	info.RootDirectory = 0;  /* MBZ for network ops (why does spec say?) */
3223 	info.FileNameLength = cpu_to_le32(len);
3224 
3225 	data[0] = &info;
3226 	size[0] = sizeof(struct smb2_file_rename_info);
3227 
3228 	data[1] = target_file;
3229 	size[1] = len + 2 /* null */;
3230 
3231 	rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
3232 		current->tgid, FILE_RENAME_INFORMATION, SMB2_O_INFO_FILE,
3233 		0, 2, data, size);
3234 	kfree(data);
3235 	return rc;
3236 }
3237 
3238 int
SMB2_rmdir(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)3239 SMB2_rmdir(const unsigned int xid, struct cifs_tcon *tcon,
3240 		  u64 persistent_fid, u64 volatile_fid)
3241 {
3242 	__u8 delete_pending = 1;
3243 	void *data;
3244 	unsigned int size;
3245 
3246 	data = &delete_pending;
3247 	size = 1; /* sizeof __u8 */
3248 
3249 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3250 		current->tgid, FILE_DISPOSITION_INFORMATION, SMB2_O_INFO_FILE,
3251 		0, 1, &data, &size);
3252 }
3253 
3254 int
SMB2_set_hardlink(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,__le16 * target_file)3255 SMB2_set_hardlink(const unsigned int xid, struct cifs_tcon *tcon,
3256 		  u64 persistent_fid, u64 volatile_fid, __le16 *target_file)
3257 {
3258 	struct smb2_file_link_info info;
3259 	void **data;
3260 	unsigned int size[2];
3261 	int rc;
3262 	int len = (2 * UniStrnlen((wchar_t *)target_file, PATH_MAX));
3263 
3264 	data = kmalloc(sizeof(void *) * 2, GFP_KERNEL);
3265 	if (!data)
3266 		return -ENOMEM;
3267 
3268 	info.ReplaceIfExists = 0; /* 1 = replace existing link with new */
3269 			      /* 0 = fail if link already exists */
3270 	info.RootDirectory = 0;  /* MBZ for network ops (why does spec say?) */
3271 	info.FileNameLength = cpu_to_le32(len);
3272 
3273 	data[0] = &info;
3274 	size[0] = sizeof(struct smb2_file_link_info);
3275 
3276 	data[1] = target_file;
3277 	size[1] = len + 2 /* null */;
3278 
3279 	rc = send_set_info(xid, tcon, persistent_fid, volatile_fid,
3280 			current->tgid, FILE_LINK_INFORMATION, SMB2_O_INFO_FILE,
3281 			0, 2, data, size);
3282 	kfree(data);
3283 	return rc;
3284 }
3285 
3286 int
SMB2_set_eof(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u32 pid,__le64 * eof,bool is_falloc)3287 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3288 	     u64 volatile_fid, u32 pid, __le64 *eof, bool is_falloc)
3289 {
3290 	struct smb2_file_eof_info info;
3291 	void *data;
3292 	unsigned int size;
3293 
3294 	info.EndOfFile = *eof;
3295 
3296 	data = &info;
3297 	size = sizeof(struct smb2_file_eof_info);
3298 
3299 	if (is_falloc)
3300 		return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3301 			pid, FILE_ALLOCATION_INFORMATION, SMB2_O_INFO_FILE,
3302 			0, 1, &data, &size);
3303 	else
3304 		return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3305 			pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
3306 			0, 1, &data, &size);
3307 }
3308 
3309 int
SMB2_set_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,FILE_BASIC_INFO * buf)3310 SMB2_set_info(const unsigned int xid, struct cifs_tcon *tcon,
3311 	      u64 persistent_fid, u64 volatile_fid, FILE_BASIC_INFO *buf)
3312 {
3313 	unsigned int size;
3314 	size = sizeof(FILE_BASIC_INFO);
3315 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3316 		current->tgid, FILE_BASIC_INFORMATION, SMB2_O_INFO_FILE,
3317 		0, 1, (void **)&buf, &size);
3318 }
3319 
3320 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)3321 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
3322 		u64 persistent_fid, u64 volatile_fid,
3323 		struct cifs_ntsd *pnntsd, int pacllen, int aclflag)
3324 {
3325 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3326 			current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
3327 			1, (void **)&pnntsd, &pacllen);
3328 }
3329 
3330 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)3331 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
3332 	    u64 persistent_fid, u64 volatile_fid,
3333 	    struct smb2_file_full_ea_info *buf, int len)
3334 {
3335 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
3336 		current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
3337 		0, 1, (void **)&buf, &len);
3338 }
3339 
3340 int
SMB2_oplock_break(const unsigned int xid,struct cifs_tcon * tcon,const u64 persistent_fid,const u64 volatile_fid,__u8 oplock_level)3341 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
3342 		  const u64 persistent_fid, const u64 volatile_fid,
3343 		  __u8 oplock_level)
3344 {
3345 	int rc;
3346 	struct smb2_oplock_break *req = NULL;
3347 	int flags = CIFS_OBREAK_OP;
3348 
3349 	cifs_dbg(FYI, "SMB2_oplock_break\n");
3350 	rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req);
3351 	if (rc)
3352 		return rc;
3353 
3354 	if (encryption_required(tcon))
3355 		flags |= CIFS_TRANSFORM_REQ;
3356 
3357 	req->VolatileFid = volatile_fid;
3358 	req->PersistentFid = persistent_fid;
3359 	req->OplockLevel = oplock_level;
3360 	req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1);
3361 
3362 	rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, flags);
3363 	cifs_small_buf_release(req);
3364 
3365 	if (rc) {
3366 		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
3367 		cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
3368 	}
3369 
3370 	return rc;
3371 }
3372 
3373 static void
copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info * pfs_inf,struct kstatfs * kst)3374 copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
3375 			struct kstatfs *kst)
3376 {
3377 	kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
3378 			  le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
3379 	kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
3380 	kst->f_bfree  = kst->f_bavail =
3381 			le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
3382 	return;
3383 }
3384 
3385 static int
build_qfs_info_req(struct kvec * iov,struct cifs_tcon * tcon,int level,int outbuf_len,u64 persistent_fid,u64 volatile_fid)3386 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon, int level,
3387 		   int outbuf_len, u64 persistent_fid, u64 volatile_fid)
3388 {
3389 	int rc;
3390 	struct smb2_query_info_req *req;
3391 
3392 	cifs_dbg(FYI, "Query FSInfo level %d\n", level);
3393 
3394 	if ((tcon->ses == NULL) || (tcon->ses->server == NULL))
3395 		return -EIO;
3396 
3397 	rc = small_smb2_init(SMB2_QUERY_INFO, tcon, (void **) &req);
3398 	if (rc)
3399 		return rc;
3400 
3401 	req->InfoType = SMB2_O_INFO_FILESYSTEM;
3402 	req->FileInfoClass = level;
3403 	req->PersistentFileId = persistent_fid;
3404 	req->VolatileFileId = volatile_fid;
3405 	/* 4 for rfc1002 length field and 1 for pad */
3406 	req->InputBufferOffset =
3407 			cpu_to_le16(sizeof(struct smb2_query_info_req) - 1 - 4);
3408 	req->OutputBufferLength = cpu_to_le32(
3409 		outbuf_len + sizeof(struct smb2_query_info_rsp) - 1 - 4);
3410 
3411 	iov->iov_base = (char *)req;
3412 	/* 4 for rfc1002 length field */
3413 	iov->iov_len = get_rfc1002_length(req) + 4;
3414 	return 0;
3415 }
3416 
3417 int
SMB2_QFS_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct kstatfs * fsdata)3418 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
3419 	      u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
3420 {
3421 	struct smb2_query_info_rsp *rsp = NULL;
3422 	struct kvec iov;
3423 	struct kvec rsp_iov;
3424 	int rc = 0;
3425 	int resp_buftype;
3426 	struct cifs_ses *ses = tcon->ses;
3427 	struct smb2_fs_full_size_info *info = NULL;
3428 	int flags = 0;
3429 
3430 	rc = build_qfs_info_req(&iov, tcon, FS_FULL_SIZE_INFORMATION,
3431 				sizeof(struct smb2_fs_full_size_info),
3432 				persistent_fid, volatile_fid);
3433 	if (rc)
3434 		return rc;
3435 
3436 	if (encryption_required(tcon))
3437 		flags |= CIFS_TRANSFORM_REQ;
3438 
3439 	rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, flags, &rsp_iov);
3440 	cifs_small_buf_release(iov.iov_base);
3441 	if (rc) {
3442 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3443 		goto qfsinf_exit;
3444 	}
3445 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3446 
3447 	info = (struct smb2_fs_full_size_info *)(4 /* RFC1001 len */ +
3448 		le16_to_cpu(rsp->OutputBufferOffset) + (char *)&rsp->hdr);
3449 	rc = validate_buf(le16_to_cpu(rsp->OutputBufferOffset),
3450 			  le32_to_cpu(rsp->OutputBufferLength), &rsp->hdr,
3451 			  sizeof(struct smb2_fs_full_size_info));
3452 	if (!rc)
3453 		copy_fs_info_to_kstatfs(info, fsdata);
3454 
3455 qfsinf_exit:
3456 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3457 	return rc;
3458 }
3459 
3460 int
SMB2_QFS_attr(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,int level)3461 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
3462 	      u64 persistent_fid, u64 volatile_fid, int level)
3463 {
3464 	struct smb2_query_info_rsp *rsp = NULL;
3465 	struct kvec iov;
3466 	struct kvec rsp_iov;
3467 	int rc = 0;
3468 	int resp_buftype, max_len, min_len;
3469 	struct cifs_ses *ses = tcon->ses;
3470 	unsigned int rsp_len, offset;
3471 	int flags = 0;
3472 
3473 	if (level == FS_DEVICE_INFORMATION) {
3474 		max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
3475 		min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
3476 	} else if (level == FS_ATTRIBUTE_INFORMATION) {
3477 		max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
3478 		min_len = MIN_FS_ATTR_INFO_SIZE;
3479 	} else if (level == FS_SECTOR_SIZE_INFORMATION) {
3480 		max_len = sizeof(struct smb3_fs_ss_info);
3481 		min_len = sizeof(struct smb3_fs_ss_info);
3482 	} else if (level == FS_VOLUME_INFORMATION) {
3483 		max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN;
3484 		min_len = sizeof(struct smb3_fs_vol_info);
3485 	} else {
3486 		cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
3487 		return -EINVAL;
3488 	}
3489 
3490 	rc = build_qfs_info_req(&iov, tcon, level, max_len,
3491 				persistent_fid, volatile_fid);
3492 	if (rc)
3493 		return rc;
3494 
3495 	if (encryption_required(tcon))
3496 		flags |= CIFS_TRANSFORM_REQ;
3497 
3498 	rc = SendReceive2(xid, ses, &iov, 1, &resp_buftype, flags, &rsp_iov);
3499 	cifs_small_buf_release(iov.iov_base);
3500 	if (rc) {
3501 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3502 		goto qfsattr_exit;
3503 	}
3504 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3505 
3506 	rsp_len = le32_to_cpu(rsp->OutputBufferLength);
3507 	offset = le16_to_cpu(rsp->OutputBufferOffset);
3508 	rc = validate_buf(offset, rsp_len, &rsp->hdr, min_len);
3509 	if (rc)
3510 		goto qfsattr_exit;
3511 
3512 	if (level == FS_ATTRIBUTE_INFORMATION)
3513 		memcpy(&tcon->fsAttrInfo, 4 /* RFC1001 len */ + offset
3514 			+ (char *)&rsp->hdr, min_t(unsigned int,
3515 			rsp_len, max_len));
3516 	else if (level == FS_DEVICE_INFORMATION)
3517 		memcpy(&tcon->fsDevInfo, 4 /* RFC1001 len */ + offset
3518 			+ (char *)&rsp->hdr, sizeof(FILE_SYSTEM_DEVICE_INFO));
3519 	else if (level == FS_SECTOR_SIZE_INFORMATION) {
3520 		struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
3521 			(4 /* RFC1001 len */ + offset + (char *)&rsp->hdr);
3522 		tcon->ss_flags = le32_to_cpu(ss_info->Flags);
3523 		tcon->perf_sector_size =
3524 			le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
3525 	} else if (level == FS_VOLUME_INFORMATION) {
3526 		struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *)
3527 			(offset + (char *)rsp);
3528 		tcon->vol_serial_number = vol_info->VolumeSerialNumber;
3529 		tcon->vol_create_time = vol_info->VolumeCreationTime;
3530 	}
3531 
3532 qfsattr_exit:
3533 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3534 	return rc;
3535 }
3536 
3537 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)3538 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
3539 	   const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
3540 	   const __u32 num_lock, struct smb2_lock_element *buf)
3541 {
3542 	int rc = 0;
3543 	struct smb2_lock_req *req = NULL;
3544 	struct kvec iov[2];
3545 	struct kvec rsp_iov;
3546 	int resp_buf_type;
3547 	unsigned int count;
3548 	int flags = CIFS_NO_RESP;
3549 
3550 	cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
3551 
3552 	rc = small_smb2_init(SMB2_LOCK, tcon, (void **) &req);
3553 	if (rc)
3554 		return rc;
3555 
3556 	if (encryption_required(tcon))
3557 		flags |= CIFS_TRANSFORM_REQ;
3558 
3559 	req->hdr.sync_hdr.ProcessId = cpu_to_le32(pid);
3560 	req->LockCount = cpu_to_le16(num_lock);
3561 
3562 	req->PersistentFileId = persist_fid;
3563 	req->VolatileFileId = volatile_fid;
3564 
3565 	count = num_lock * sizeof(struct smb2_lock_element);
3566 	inc_rfc1001_len(req, count - sizeof(struct smb2_lock_element));
3567 
3568 	iov[0].iov_base = (char *)req;
3569 	/* 4 for rfc1002 length field and count for all locks */
3570 	iov[0].iov_len = get_rfc1002_length(req) + 4 - count;
3571 	iov[1].iov_base = (char *)buf;
3572 	iov[1].iov_len = count;
3573 
3574 	cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
3575 	rc = SendReceive2(xid, tcon->ses, iov, 2, &resp_buf_type, flags,
3576 			  &rsp_iov);
3577 	cifs_small_buf_release(req);
3578 	if (rc) {
3579 		cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
3580 		cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
3581 	}
3582 
3583 	return rc;
3584 }
3585 
3586 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)3587 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
3588 	  const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
3589 	  const __u64 length, const __u64 offset, const __u32 lock_flags,
3590 	  const bool wait)
3591 {
3592 	struct smb2_lock_element lock;
3593 
3594 	lock.Offset = cpu_to_le64(offset);
3595 	lock.Length = cpu_to_le64(length);
3596 	lock.Flags = cpu_to_le32(lock_flags);
3597 	if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
3598 		lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
3599 
3600 	return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
3601 }
3602 
3603 int
SMB2_lease_break(const unsigned int xid,struct cifs_tcon * tcon,__u8 * lease_key,const __le32 lease_state)3604 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
3605 		 __u8 *lease_key, const __le32 lease_state)
3606 {
3607 	int rc;
3608 	struct smb2_lease_ack *req = NULL;
3609 	int flags = CIFS_OBREAK_OP;
3610 
3611 	cifs_dbg(FYI, "SMB2_lease_break\n");
3612 	rc = small_smb2_init(SMB2_OPLOCK_BREAK, tcon, (void **) &req);
3613 	if (rc)
3614 		return rc;
3615 
3616 	if (encryption_required(tcon))
3617 		flags |= CIFS_TRANSFORM_REQ;
3618 
3619 	req->hdr.sync_hdr.CreditRequest = cpu_to_le16(1);
3620 	req->StructureSize = cpu_to_le16(36);
3621 	inc_rfc1001_len(req, 12);
3622 
3623 	memcpy(req->LeaseKey, lease_key, 16);
3624 	req->LeaseState = lease_state;
3625 
3626 	rc = SendReceiveNoRsp(xid, tcon->ses, (char *) req, flags);
3627 	cifs_small_buf_release(req);
3628 
3629 	if (rc) {
3630 		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
3631 		cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
3632 	}
3633 
3634 	return rc;
3635 }
3636