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