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