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