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