1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 *   Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
4 *   Copyright (C) 2018 Samsung Electronics Co., Ltd.
5 */
6
7#include <linux/inetdevice.h>
8#include <net/addrconf.h>
9#include <linux/syscalls.h>
10#include <linux/namei.h>
11#include <linux/statfs.h>
12#include <linux/ethtool.h>
13#include <linux/falloc.h>
14#include <linux/mount.h>
15#include <linux/filelock.h>
16
17#include "glob.h"
18#include "smbfsctl.h"
19#include "oplock.h"
20#include "smbacl.h"
21
22#include "auth.h"
23#include "asn1.h"
24#include "connection.h"
25#include "transport_ipc.h"
26#include "transport_rdma.h"
27#include "vfs.h"
28#include "vfs_cache.h"
29#include "misc.h"
30
31#include "server.h"
32#include "smb_common.h"
33#include "smbstatus.h"
34#include "ksmbd_work.h"
35#include "mgmt/user_config.h"
36#include "mgmt/share_config.h"
37#include "mgmt/tree_connect.h"
38#include "mgmt/user_session.h"
39#include "mgmt/ksmbd_ida.h"
40#include "ndr.h"
41
42static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
43{
44	if (work->next_smb2_rcv_hdr_off) {
45		*req = ksmbd_req_buf_next(work);
46		*rsp = ksmbd_resp_buf_next(work);
47	} else {
48		*req = smb2_get_msg(work->request_buf);
49		*rsp = smb2_get_msg(work->response_buf);
50	}
51}
52
53#define WORK_BUFFERS(w, rq, rs)	__wbuf((w), (void **)&(rq), (void **)&(rs))
54
55/**
56 * check_session_id() - check for valid session id in smb header
57 * @conn:	connection instance
58 * @id:		session id from smb header
59 *
60 * Return:      1 if valid session id, otherwise 0
61 */
62static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
63{
64	struct ksmbd_session *sess;
65
66	if (id == 0 || id == -1)
67		return false;
68
69	sess = ksmbd_session_lookup_all(conn, id);
70	if (sess)
71		return true;
72	pr_err("Invalid user session id: %llu\n", id);
73	return false;
74}
75
76struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
77{
78	return xa_load(&sess->ksmbd_chann_list, (long)conn);
79}
80
81/**
82 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
83 * @work:	smb work
84 *
85 * Return:	0 if there is a tree connection matched or these are
86 *		skipable commands, otherwise error
87 */
88int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
89{
90	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
91	unsigned int cmd = le16_to_cpu(req_hdr->Command);
92	unsigned int tree_id;
93
94	if (cmd == SMB2_TREE_CONNECT_HE ||
95	    cmd ==  SMB2_CANCEL_HE ||
96	    cmd ==  SMB2_LOGOFF_HE) {
97		ksmbd_debug(SMB, "skip to check tree connect request\n");
98		return 0;
99	}
100
101	if (xa_empty(&work->sess->tree_conns)) {
102		ksmbd_debug(SMB, "NO tree connected\n");
103		return -ENOENT;
104	}
105
106	tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
107
108	/*
109	 * If request is not the first in Compound request,
110	 * Just validate tree id in header with work->tcon->id.
111	 */
112	if (work->next_smb2_rcv_hdr_off) {
113		if (!work->tcon) {
114			pr_err("The first operation in the compound does not have tcon\n");
115			return -EINVAL;
116		}
117		if (tree_id != UINT_MAX && work->tcon->id != tree_id) {
118			pr_err("tree id(%u) is different with id(%u) in first operation\n",
119					tree_id, work->tcon->id);
120			return -EINVAL;
121		}
122		return 1;
123	}
124
125	work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
126	if (!work->tcon) {
127		pr_err("Invalid tid %d\n", tree_id);
128		return -ENOENT;
129	}
130
131	return 1;
132}
133
134/**
135 * smb2_set_err_rsp() - set error response code on smb response
136 * @work:	smb work containing response buffer
137 */
138void smb2_set_err_rsp(struct ksmbd_work *work)
139{
140	struct smb2_err_rsp *err_rsp;
141
142	if (work->next_smb2_rcv_hdr_off)
143		err_rsp = ksmbd_resp_buf_next(work);
144	else
145		err_rsp = smb2_get_msg(work->response_buf);
146
147	if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
148		int err;
149
150		err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
151		err_rsp->ErrorContextCount = 0;
152		err_rsp->Reserved = 0;
153		err_rsp->ByteCount = 0;
154		err_rsp->ErrorData[0] = 0;
155		err = ksmbd_iov_pin_rsp(work, (void *)err_rsp,
156					__SMB2_HEADER_STRUCTURE_SIZE +
157						SMB2_ERROR_STRUCTURE_SIZE2);
158		if (err)
159			work->send_no_response = 1;
160	}
161}
162
163/**
164 * is_smb2_neg_cmd() - is it smb2 negotiation command
165 * @work:	smb work containing smb header
166 *
167 * Return:      true if smb2 negotiation command, otherwise false
168 */
169bool is_smb2_neg_cmd(struct ksmbd_work *work)
170{
171	struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
172
173	/* is it SMB2 header ? */
174	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
175		return false;
176
177	/* make sure it is request not response message */
178	if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
179		return false;
180
181	if (hdr->Command != SMB2_NEGOTIATE)
182		return false;
183
184	return true;
185}
186
187/**
188 * is_smb2_rsp() - is it smb2 response
189 * @work:	smb work containing smb response buffer
190 *
191 * Return:      true if smb2 response, otherwise false
192 */
193bool is_smb2_rsp(struct ksmbd_work *work)
194{
195	struct smb2_hdr *hdr = smb2_get_msg(work->response_buf);
196
197	/* is it SMB2 header ? */
198	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
199		return false;
200
201	/* make sure it is response not request message */
202	if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
203		return false;
204
205	return true;
206}
207
208/**
209 * get_smb2_cmd_val() - get smb command code from smb header
210 * @work:	smb work containing smb request buffer
211 *
212 * Return:      smb2 request command value
213 */
214u16 get_smb2_cmd_val(struct ksmbd_work *work)
215{
216	struct smb2_hdr *rcv_hdr;
217
218	if (work->next_smb2_rcv_hdr_off)
219		rcv_hdr = ksmbd_req_buf_next(work);
220	else
221		rcv_hdr = smb2_get_msg(work->request_buf);
222	return le16_to_cpu(rcv_hdr->Command);
223}
224
225/**
226 * set_smb2_rsp_status() - set error response code on smb2 header
227 * @work:	smb work containing response buffer
228 * @err:	error response code
229 */
230void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
231{
232	struct smb2_hdr *rsp_hdr;
233
234	rsp_hdr = smb2_get_msg(work->response_buf);
235	rsp_hdr->Status = err;
236
237	work->iov_idx = 0;
238	work->iov_cnt = 0;
239	work->next_smb2_rcv_hdr_off = 0;
240	smb2_set_err_rsp(work);
241}
242
243/**
244 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
245 * @work:	smb work containing smb request buffer
246 *
247 * smb2 negotiate response is sent in reply of smb1 negotiate command for
248 * dialect auto-negotiation.
249 */
250int init_smb2_neg_rsp(struct ksmbd_work *work)
251{
252	struct smb2_hdr *rsp_hdr;
253	struct smb2_negotiate_rsp *rsp;
254	struct ksmbd_conn *conn = work->conn;
255	int err;
256
257	rsp_hdr = smb2_get_msg(work->response_buf);
258	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
259	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
260	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
261	rsp_hdr->CreditRequest = cpu_to_le16(2);
262	rsp_hdr->Command = SMB2_NEGOTIATE;
263	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
264	rsp_hdr->NextCommand = 0;
265	rsp_hdr->MessageId = 0;
266	rsp_hdr->Id.SyncId.ProcessId = 0;
267	rsp_hdr->Id.SyncId.TreeId = 0;
268	rsp_hdr->SessionId = 0;
269	memset(rsp_hdr->Signature, 0, 16);
270
271	rsp = smb2_get_msg(work->response_buf);
272
273	WARN_ON(ksmbd_conn_good(conn));
274
275	rsp->StructureSize = cpu_to_le16(65);
276	ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
277	rsp->DialectRevision = cpu_to_le16(conn->dialect);
278	/* Not setting conn guid rsp->ServerGUID, as it
279	 * not used by client for identifying connection
280	 */
281	rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
282	/* Default Max Message Size till SMB2.0, 64K*/
283	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
284	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
285	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
286
287	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
288	rsp->ServerStartTime = 0;
289
290	rsp->SecurityBufferOffset = cpu_to_le16(128);
291	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
292	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
293		le16_to_cpu(rsp->SecurityBufferOffset));
294	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
295	if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
296		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
297	err = ksmbd_iov_pin_rsp(work, rsp,
298				sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH);
299	if (err)
300		return err;
301	conn->use_spnego = true;
302
303	ksmbd_conn_set_need_negotiate(conn);
304	return 0;
305}
306
307/**
308 * smb2_set_rsp_credits() - set number of credits in response buffer
309 * @work:	smb work containing smb response buffer
310 */
311int smb2_set_rsp_credits(struct ksmbd_work *work)
312{
313	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
314	struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
315	struct ksmbd_conn *conn = work->conn;
316	unsigned short credits_requested, aux_max;
317	unsigned short credit_charge, credits_granted = 0;
318
319	if (work->send_no_response)
320		return 0;
321
322	hdr->CreditCharge = req_hdr->CreditCharge;
323
324	if (conn->total_credits > conn->vals->max_credits) {
325		hdr->CreditRequest = 0;
326		pr_err("Total credits overflow: %d\n", conn->total_credits);
327		return -EINVAL;
328	}
329
330	credit_charge = max_t(unsigned short,
331			      le16_to_cpu(req_hdr->CreditCharge), 1);
332	if (credit_charge > conn->total_credits) {
333		ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
334			    credit_charge, conn->total_credits);
335		return -EINVAL;
336	}
337
338	conn->total_credits -= credit_charge;
339	conn->outstanding_credits -= credit_charge;
340	credits_requested = max_t(unsigned short,
341				  le16_to_cpu(req_hdr->CreditRequest), 1);
342
343	/* according to smb2.credits smbtorture, Windows server
344	 * 2016 or later grant up to 8192 credits at once.
345	 *
346	 * TODO: Need to adjuct CreditRequest value according to
347	 * current cpu load
348	 */
349	if (hdr->Command == SMB2_NEGOTIATE)
350		aux_max = 1;
351	else
352		aux_max = conn->vals->max_credits - conn->total_credits;
353	credits_granted = min_t(unsigned short, credits_requested, aux_max);
354
355	conn->total_credits += credits_granted;
356	work->credits_granted += credits_granted;
357
358	if (!req_hdr->NextCommand) {
359		/* Update CreditRequest in last request */
360		hdr->CreditRequest = cpu_to_le16(work->credits_granted);
361	}
362	ksmbd_debug(SMB,
363		    "credits: requested[%d] granted[%d] total_granted[%d]\n",
364		    credits_requested, credits_granted,
365		    conn->total_credits);
366	return 0;
367}
368
369/**
370 * init_chained_smb2_rsp() - initialize smb2 chained response
371 * @work:	smb work containing smb response buffer
372 */
373static void init_chained_smb2_rsp(struct ksmbd_work *work)
374{
375	struct smb2_hdr *req = ksmbd_req_buf_next(work);
376	struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
377	struct smb2_hdr *rsp_hdr;
378	struct smb2_hdr *rcv_hdr;
379	int next_hdr_offset = 0;
380	int len, new_len;
381
382	/* Len of this response = updated RFC len - offset of previous cmd
383	 * in the compound rsp
384	 */
385
386	/* Storing the current local FID which may be needed by subsequent
387	 * command in the compound request
388	 */
389	if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
390		work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
391		work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
392		work->compound_sid = le64_to_cpu(rsp->SessionId);
393	}
394
395	len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
396	next_hdr_offset = le32_to_cpu(req->NextCommand);
397
398	new_len = ALIGN(len, 8);
399	work->iov[work->iov_idx].iov_len += (new_len - len);
400	inc_rfc1001_len(work->response_buf, new_len - len);
401	rsp->NextCommand = cpu_to_le32(new_len);
402
403	work->next_smb2_rcv_hdr_off += next_hdr_offset;
404	work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
405	work->next_smb2_rsp_hdr_off += new_len;
406	ksmbd_debug(SMB,
407		    "Compound req new_len = %d rcv off = %d rsp off = %d\n",
408		    new_len, work->next_smb2_rcv_hdr_off,
409		    work->next_smb2_rsp_hdr_off);
410
411	rsp_hdr = ksmbd_resp_buf_next(work);
412	rcv_hdr = ksmbd_req_buf_next(work);
413
414	if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
415		ksmbd_debug(SMB, "related flag should be set\n");
416		work->compound_fid = KSMBD_NO_FID;
417		work->compound_pfid = KSMBD_NO_FID;
418	}
419	memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
420	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
421	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
422	rsp_hdr->Command = rcv_hdr->Command;
423
424	/*
425	 * Message is response. We don't grant oplock yet.
426	 */
427	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
428				SMB2_FLAGS_RELATED_OPERATIONS);
429	rsp_hdr->NextCommand = 0;
430	rsp_hdr->MessageId = rcv_hdr->MessageId;
431	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
432	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
433	rsp_hdr->SessionId = rcv_hdr->SessionId;
434	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
435}
436
437/**
438 * is_chained_smb2_message() - check for chained command
439 * @work:	smb work containing smb request buffer
440 *
441 * Return:      true if chained request, otherwise false
442 */
443bool is_chained_smb2_message(struct ksmbd_work *work)
444{
445	struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
446	unsigned int len, next_cmd;
447
448	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
449		return false;
450
451	hdr = ksmbd_req_buf_next(work);
452	next_cmd = le32_to_cpu(hdr->NextCommand);
453	if (next_cmd > 0) {
454		if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
455			__SMB2_HEADER_STRUCTURE_SIZE >
456		    get_rfc1002_len(work->request_buf)) {
457			pr_err("next command(%u) offset exceeds smb msg size\n",
458			       next_cmd);
459			return false;
460		}
461
462		if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
463		    work->response_sz) {
464			pr_err("next response offset exceeds response buffer size\n");
465			return false;
466		}
467
468		ksmbd_debug(SMB, "got SMB2 chained command\n");
469		init_chained_smb2_rsp(work);
470		return true;
471	} else if (work->next_smb2_rcv_hdr_off) {
472		/*
473		 * This is last request in chained command,
474		 * align response to 8 byte
475		 */
476		len = ALIGN(get_rfc1002_len(work->response_buf), 8);
477		len = len - get_rfc1002_len(work->response_buf);
478		if (len) {
479			ksmbd_debug(SMB, "padding len %u\n", len);
480			work->iov[work->iov_idx].iov_len += len;
481			inc_rfc1001_len(work->response_buf, len);
482		}
483		work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
484	}
485	return false;
486}
487
488/**
489 * init_smb2_rsp_hdr() - initialize smb2 response
490 * @work:	smb work containing smb request buffer
491 *
492 * Return:      0
493 */
494int init_smb2_rsp_hdr(struct ksmbd_work *work)
495{
496	struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
497	struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
498
499	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
500	rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
501	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
502	rsp_hdr->Command = rcv_hdr->Command;
503
504	/*
505	 * Message is response. We don't grant oplock yet.
506	 */
507	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
508	rsp_hdr->NextCommand = 0;
509	rsp_hdr->MessageId = rcv_hdr->MessageId;
510	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
511	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
512	rsp_hdr->SessionId = rcv_hdr->SessionId;
513	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
514
515	return 0;
516}
517
518/**
519 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
520 * @work:	smb work containing smb request buffer
521 *
522 * Return:      0 on success, otherwise -ENOMEM
523 */
524int smb2_allocate_rsp_buf(struct ksmbd_work *work)
525{
526	struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
527	size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
528	size_t large_sz = small_sz + work->conn->vals->max_trans_size;
529	size_t sz = small_sz;
530	int cmd = le16_to_cpu(hdr->Command);
531
532	if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
533		sz = large_sz;
534
535	if (cmd == SMB2_QUERY_INFO_HE) {
536		struct smb2_query_info_req *req;
537
538		if (get_rfc1002_len(work->request_buf) <
539		    offsetof(struct smb2_query_info_req, OutputBufferLength))
540			return -EINVAL;
541
542		req = smb2_get_msg(work->request_buf);
543		if ((req->InfoType == SMB2_O_INFO_FILE &&
544		     (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
545		     req->FileInfoClass == FILE_ALL_INFORMATION)) ||
546		    req->InfoType == SMB2_O_INFO_SECURITY)
547			sz = large_sz;
548	}
549
550	/* allocate large response buf for chained commands */
551	if (le32_to_cpu(hdr->NextCommand) > 0)
552		sz = large_sz;
553
554	work->response_buf = kvzalloc(sz, GFP_KERNEL);
555	if (!work->response_buf)
556		return -ENOMEM;
557
558	work->response_sz = sz;
559	return 0;
560}
561
562/**
563 * smb2_check_user_session() - check for valid session for a user
564 * @work:	smb work containing smb request buffer
565 *
566 * Return:      0 on success, otherwise error
567 */
568int smb2_check_user_session(struct ksmbd_work *work)
569{
570	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
571	struct ksmbd_conn *conn = work->conn;
572	unsigned int cmd = le16_to_cpu(req_hdr->Command);
573	unsigned long long sess_id;
574
575	/*
576	 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
577	 * require a session id, so no need to validate user session's for
578	 * these commands.
579	 */
580	if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
581	    cmd == SMB2_SESSION_SETUP_HE)
582		return 0;
583
584	if (!ksmbd_conn_good(conn))
585		return -EIO;
586
587	sess_id = le64_to_cpu(req_hdr->SessionId);
588
589	/*
590	 * If request is not the first in Compound request,
591	 * Just validate session id in header with work->sess->id.
592	 */
593	if (work->next_smb2_rcv_hdr_off) {
594		if (!work->sess) {
595			pr_err("The first operation in the compound does not have sess\n");
596			return -EINVAL;
597		}
598		if (sess_id != ULLONG_MAX && work->sess->id != sess_id) {
599			pr_err("session id(%llu) is different with the first operation(%lld)\n",
600					sess_id, work->sess->id);
601			return -EINVAL;
602		}
603		return 1;
604	}
605
606	/* Check for validity of user session */
607	work->sess = ksmbd_session_lookup_all(conn, sess_id);
608	if (work->sess)
609		return 1;
610	ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
611	return -ENOENT;
612}
613
614/**
615 * smb2_get_name() - get filename string from on the wire smb format
616 * @src:	source buffer
617 * @maxlen:	maxlen of source string
618 * @local_nls:	nls_table pointer
619 *
620 * Return:      matching converted filename on success, otherwise error ptr
621 */
622static char *
623smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
624{
625	char *name;
626
627	name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
628	if (IS_ERR(name)) {
629		pr_err("failed to get name %ld\n", PTR_ERR(name));
630		return name;
631	}
632
633	ksmbd_conv_path_to_unix(name);
634	ksmbd_strip_last_slash(name);
635	return name;
636}
637
638int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
639{
640	struct ksmbd_conn *conn = work->conn;
641	int id;
642
643	id = ksmbd_acquire_async_msg_id(&conn->async_ida);
644	if (id < 0) {
645		pr_err("Failed to alloc async message id\n");
646		return id;
647	}
648	work->asynchronous = true;
649	work->async_id = id;
650
651	ksmbd_debug(SMB,
652		    "Send interim Response to inform async request id : %d\n",
653		    work->async_id);
654
655	work->cancel_fn = fn;
656	work->cancel_argv = arg;
657
658	if (list_empty(&work->async_request_entry)) {
659		spin_lock(&conn->request_lock);
660		list_add_tail(&work->async_request_entry, &conn->async_requests);
661		spin_unlock(&conn->request_lock);
662	}
663
664	return 0;
665}
666
667void release_async_work(struct ksmbd_work *work)
668{
669	struct ksmbd_conn *conn = work->conn;
670
671	spin_lock(&conn->request_lock);
672	list_del_init(&work->async_request_entry);
673	spin_unlock(&conn->request_lock);
674
675	work->asynchronous = 0;
676	work->cancel_fn = NULL;
677	kfree(work->cancel_argv);
678	work->cancel_argv = NULL;
679	if (work->async_id) {
680		ksmbd_release_id(&conn->async_ida, work->async_id);
681		work->async_id = 0;
682	}
683}
684
685void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
686{
687	struct smb2_hdr *rsp_hdr;
688	struct ksmbd_work *in_work = ksmbd_alloc_work_struct();
689
690	if (allocate_interim_rsp_buf(in_work)) {
691		pr_err("smb_allocate_rsp_buf failed!\n");
692		ksmbd_free_work_struct(in_work);
693		return;
694	}
695
696	in_work->conn = work->conn;
697	memcpy(smb2_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work),
698	       __SMB2_HEADER_STRUCTURE_SIZE);
699
700	rsp_hdr = smb2_get_msg(in_work->response_buf);
701	rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
702	rsp_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
703	smb2_set_err_rsp(in_work);
704	rsp_hdr->Status = status;
705
706	ksmbd_conn_write(in_work);
707	ksmbd_free_work_struct(in_work);
708}
709
710static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
711{
712	if (S_ISDIR(mode) || S_ISREG(mode))
713		return 0;
714
715	if (S_ISLNK(mode))
716		return IO_REPARSE_TAG_LX_SYMLINK_LE;
717	else if (S_ISFIFO(mode))
718		return IO_REPARSE_TAG_LX_FIFO_LE;
719	else if (S_ISSOCK(mode))
720		return IO_REPARSE_TAG_AF_UNIX_LE;
721	else if (S_ISCHR(mode))
722		return IO_REPARSE_TAG_LX_CHR_LE;
723	else if (S_ISBLK(mode))
724		return IO_REPARSE_TAG_LX_BLK_LE;
725
726	return 0;
727}
728
729/**
730 * smb2_get_dos_mode() - get file mode in dos format from unix mode
731 * @stat:	kstat containing file mode
732 * @attribute:	attribute flags
733 *
734 * Return:      converted dos mode
735 */
736static int smb2_get_dos_mode(struct kstat *stat, int attribute)
737{
738	int attr = 0;
739
740	if (S_ISDIR(stat->mode)) {
741		attr = FILE_ATTRIBUTE_DIRECTORY |
742			(attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
743	} else {
744		attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
745		attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
746		if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
747				FILE_SUPPORTS_SPARSE_FILES))
748			attr |= FILE_ATTRIBUTE_SPARSE_FILE;
749
750		if (smb2_get_reparse_tag_special_file(stat->mode))
751			attr |= FILE_ATTRIBUTE_REPARSE_POINT;
752	}
753
754	return attr;
755}
756
757static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
758			       __le16 hash_id)
759{
760	pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
761	pneg_ctxt->DataLength = cpu_to_le16(38);
762	pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
763	pneg_ctxt->Reserved = cpu_to_le32(0);
764	pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
765	get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
766	pneg_ctxt->HashAlgorithms = hash_id;
767}
768
769static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
770			       __le16 cipher_type)
771{
772	pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
773	pneg_ctxt->DataLength = cpu_to_le16(4);
774	pneg_ctxt->Reserved = cpu_to_le32(0);
775	pneg_ctxt->CipherCount = cpu_to_le16(1);
776	pneg_ctxt->Ciphers[0] = cipher_type;
777}
778
779static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
780				__le16 sign_algo)
781{
782	pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
783	pneg_ctxt->DataLength =
784		cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
785			- sizeof(struct smb2_neg_context));
786	pneg_ctxt->Reserved = cpu_to_le32(0);
787	pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
788	pneg_ctxt->SigningAlgorithms[0] = sign_algo;
789}
790
791static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
792{
793	pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
794	pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
795	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
796	pneg_ctxt->Name[0] = 0x93;
797	pneg_ctxt->Name[1] = 0xAD;
798	pneg_ctxt->Name[2] = 0x25;
799	pneg_ctxt->Name[3] = 0x50;
800	pneg_ctxt->Name[4] = 0x9C;
801	pneg_ctxt->Name[5] = 0xB4;
802	pneg_ctxt->Name[6] = 0x11;
803	pneg_ctxt->Name[7] = 0xE7;
804	pneg_ctxt->Name[8] = 0xB4;
805	pneg_ctxt->Name[9] = 0x23;
806	pneg_ctxt->Name[10] = 0x83;
807	pneg_ctxt->Name[11] = 0xDE;
808	pneg_ctxt->Name[12] = 0x96;
809	pneg_ctxt->Name[13] = 0x8B;
810	pneg_ctxt->Name[14] = 0xCD;
811	pneg_ctxt->Name[15] = 0x7C;
812}
813
814static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
815				  struct smb2_negotiate_rsp *rsp)
816{
817	char * const pneg_ctxt = (char *)rsp +
818			le32_to_cpu(rsp->NegotiateContextOffset);
819	int neg_ctxt_cnt = 1;
820	int ctxt_size;
821
822	ksmbd_debug(SMB,
823		    "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
824	build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
825			   conn->preauth_info->Preauth_HashId);
826	ctxt_size = sizeof(struct smb2_preauth_neg_context);
827
828	if (conn->cipher_type) {
829		/* Round to 8 byte boundary */
830		ctxt_size = round_up(ctxt_size, 8);
831		ksmbd_debug(SMB,
832			    "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
833		build_encrypt_ctxt((struct smb2_encryption_neg_context *)
834				   (pneg_ctxt + ctxt_size),
835				   conn->cipher_type);
836		neg_ctxt_cnt++;
837		ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
838	}
839
840	/* compression context not yet supported */
841	WARN_ON(conn->compress_algorithm != SMB3_COMPRESS_NONE);
842
843	if (conn->posix_ext_supported) {
844		ctxt_size = round_up(ctxt_size, 8);
845		ksmbd_debug(SMB,
846			    "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
847		build_posix_ctxt((struct smb2_posix_neg_context *)
848				 (pneg_ctxt + ctxt_size));
849		neg_ctxt_cnt++;
850		ctxt_size += sizeof(struct smb2_posix_neg_context);
851	}
852
853	if (conn->signing_negotiated) {
854		ctxt_size = round_up(ctxt_size, 8);
855		ksmbd_debug(SMB,
856			    "assemble SMB2_SIGNING_CAPABILITIES context\n");
857		build_sign_cap_ctxt((struct smb2_signing_capabilities *)
858				    (pneg_ctxt + ctxt_size),
859				    conn->signing_algorithm);
860		neg_ctxt_cnt++;
861		ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
862	}
863
864	rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
865	return ctxt_size + AUTH_GSS_PADDING;
866}
867
868static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
869				  struct smb2_preauth_neg_context *pneg_ctxt,
870				  int ctxt_len)
871{
872	/*
873	 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
874	 * which may not be present. Only check for used HashAlgorithms[1].
875	 */
876	if (ctxt_len <
877	    sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
878		return STATUS_INVALID_PARAMETER;
879
880	if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
881		return STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
882
883	conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
884	return STATUS_SUCCESS;
885}
886
887static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
888				struct smb2_encryption_neg_context *pneg_ctxt,
889				int ctxt_len)
890{
891	int cph_cnt;
892	int i, cphs_size;
893
894	if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
895		pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
896		return;
897	}
898
899	conn->cipher_type = 0;
900
901	cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
902	cphs_size = cph_cnt * sizeof(__le16);
903
904	if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
905	    ctxt_len) {
906		pr_err("Invalid cipher count(%d)\n", cph_cnt);
907		return;
908	}
909
910	if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
911		return;
912
913	for (i = 0; i < cph_cnt; i++) {
914		if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
915		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
916		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
917		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
918			ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
919				    pneg_ctxt->Ciphers[i]);
920			conn->cipher_type = pneg_ctxt->Ciphers[i];
921			break;
922		}
923	}
924}
925
926/**
927 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
928 * @conn:	smb connection
929 *
930 * Return:	true if connection should be encrypted, else false
931 */
932bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
933{
934	if (!conn->ops->generate_encryptionkey)
935		return false;
936
937	/*
938	 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
939	 * SMB 3.1.1 uses the cipher_type field.
940	 */
941	return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
942	    conn->cipher_type;
943}
944
945static void decode_compress_ctxt(struct ksmbd_conn *conn,
946				 struct smb2_compression_capabilities_context *pneg_ctxt)
947{
948	conn->compress_algorithm = SMB3_COMPRESS_NONE;
949}
950
951static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
952				 struct smb2_signing_capabilities *pneg_ctxt,
953				 int ctxt_len)
954{
955	int sign_algo_cnt;
956	int i, sign_alos_size;
957
958	if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
959		pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
960		return;
961	}
962
963	conn->signing_negotiated = false;
964	sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
965	sign_alos_size = sign_algo_cnt * sizeof(__le16);
966
967	if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
968	    ctxt_len) {
969		pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
970		return;
971	}
972
973	for (i = 0; i < sign_algo_cnt; i++) {
974		if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
975		    pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
976			ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
977				    pneg_ctxt->SigningAlgorithms[i]);
978			conn->signing_negotiated = true;
979			conn->signing_algorithm =
980				pneg_ctxt->SigningAlgorithms[i];
981			break;
982		}
983	}
984}
985
986static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
987				      struct smb2_negotiate_req *req,
988				      unsigned int len_of_smb)
989{
990	/* +4 is to account for the RFC1001 len field */
991	struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
992	int i = 0, len_of_ctxts;
993	unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
994	unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
995	__le32 status = STATUS_INVALID_PARAMETER;
996
997	ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
998	if (len_of_smb <= offset) {
999		ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
1000		return status;
1001	}
1002
1003	len_of_ctxts = len_of_smb - offset;
1004
1005	while (i++ < neg_ctxt_cnt) {
1006		int clen, ctxt_len;
1007
1008		if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
1009			break;
1010
1011		pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1012		clen = le16_to_cpu(pctx->DataLength);
1013		ctxt_len = clen + sizeof(struct smb2_neg_context);
1014
1015		if (ctxt_len > len_of_ctxts)
1016			break;
1017
1018		if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1019			ksmbd_debug(SMB,
1020				    "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1021			if (conn->preauth_info->Preauth_HashId)
1022				break;
1023
1024			status = decode_preauth_ctxt(conn,
1025						     (struct smb2_preauth_neg_context *)pctx,
1026						     ctxt_len);
1027			if (status != STATUS_SUCCESS)
1028				break;
1029		} else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1030			ksmbd_debug(SMB,
1031				    "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1032			if (conn->cipher_type)
1033				break;
1034
1035			decode_encrypt_ctxt(conn,
1036					    (struct smb2_encryption_neg_context *)pctx,
1037					    ctxt_len);
1038		} else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1039			ksmbd_debug(SMB,
1040				    "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1041			if (conn->compress_algorithm)
1042				break;
1043
1044			decode_compress_ctxt(conn,
1045					     (struct smb2_compression_capabilities_context *)pctx);
1046		} else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1047			ksmbd_debug(SMB,
1048				    "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1049		} else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1050			ksmbd_debug(SMB,
1051				    "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1052			conn->posix_ext_supported = true;
1053		} else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1054			ksmbd_debug(SMB,
1055				    "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1056
1057			decode_sign_cap_ctxt(conn,
1058					     (struct smb2_signing_capabilities *)pctx,
1059					     ctxt_len);
1060		}
1061
1062		/* offsets must be 8 byte aligned */
1063		offset = (ctxt_len + 7) & ~0x7;
1064		len_of_ctxts -= offset;
1065	}
1066	return status;
1067}
1068
1069/**
1070 * smb2_handle_negotiate() - handler for smb2 negotiate command
1071 * @work:	smb work containing smb request buffer
1072 *
1073 * Return:      0
1074 */
1075int smb2_handle_negotiate(struct ksmbd_work *work)
1076{
1077	struct ksmbd_conn *conn = work->conn;
1078	struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1079	struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1080	int rc = 0;
1081	unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0;
1082	__le32 status;
1083
1084	ksmbd_debug(SMB, "Received negotiate request\n");
1085	conn->need_neg = false;
1086	if (ksmbd_conn_good(conn)) {
1087		pr_err("conn->tcp_status is already in CifsGood State\n");
1088		work->send_no_response = 1;
1089		return rc;
1090	}
1091
1092	smb2_buf_len = get_rfc1002_len(work->request_buf);
1093	smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1094	if (smb2_neg_size > smb2_buf_len) {
1095		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1096		rc = -EINVAL;
1097		goto err_out;
1098	}
1099
1100	if (req->DialectCount == 0) {
1101		pr_err("malformed packet\n");
1102		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1103		rc = -EINVAL;
1104		goto err_out;
1105	}
1106
1107	if (conn->dialect == SMB311_PROT_ID) {
1108		unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1109
1110		if (smb2_buf_len < nego_ctxt_off) {
1111			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1112			rc = -EINVAL;
1113			goto err_out;
1114		}
1115
1116		if (smb2_neg_size > nego_ctxt_off) {
1117			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1118			rc = -EINVAL;
1119			goto err_out;
1120		}
1121
1122		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1123		    nego_ctxt_off) {
1124			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1125			rc = -EINVAL;
1126			goto err_out;
1127		}
1128	} else {
1129		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1130		    smb2_buf_len) {
1131			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1132			rc = -EINVAL;
1133			goto err_out;
1134		}
1135	}
1136
1137	conn->cli_cap = le32_to_cpu(req->Capabilities);
1138	switch (conn->dialect) {
1139	case SMB311_PROT_ID:
1140		conn->preauth_info =
1141			kzalloc(sizeof(struct preauth_integrity_info),
1142				GFP_KERNEL);
1143		if (!conn->preauth_info) {
1144			rc = -ENOMEM;
1145			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1146			goto err_out;
1147		}
1148
1149		status = deassemble_neg_contexts(conn, req,
1150						 get_rfc1002_len(work->request_buf));
1151		if (status != STATUS_SUCCESS) {
1152			pr_err("deassemble_neg_contexts error(0x%x)\n",
1153			       status);
1154			rsp->hdr.Status = status;
1155			rc = -EINVAL;
1156			kfree(conn->preauth_info);
1157			conn->preauth_info = NULL;
1158			goto err_out;
1159		}
1160
1161		rc = init_smb3_11_server(conn);
1162		if (rc < 0) {
1163			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1164			kfree(conn->preauth_info);
1165			conn->preauth_info = NULL;
1166			goto err_out;
1167		}
1168
1169		ksmbd_gen_preauth_integrity_hash(conn,
1170						 work->request_buf,
1171						 conn->preauth_info->Preauth_HashValue);
1172		rsp->NegotiateContextOffset =
1173				cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1174		neg_ctxt_len = assemble_neg_contexts(conn, rsp);
1175		break;
1176	case SMB302_PROT_ID:
1177		init_smb3_02_server(conn);
1178		break;
1179	case SMB30_PROT_ID:
1180		init_smb3_0_server(conn);
1181		break;
1182	case SMB21_PROT_ID:
1183		init_smb2_1_server(conn);
1184		break;
1185	case SMB2X_PROT_ID:
1186	case BAD_PROT_ID:
1187	default:
1188		ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1189			    conn->dialect);
1190		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1191		rc = -EINVAL;
1192		goto err_out;
1193	}
1194	rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1195
1196	/* For stats */
1197	conn->connection_type = conn->dialect;
1198
1199	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1200	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1201	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1202
1203	memcpy(conn->ClientGUID, req->ClientGUID,
1204			SMB2_CLIENT_GUID_SIZE);
1205	conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1206
1207	rsp->StructureSize = cpu_to_le16(65);
1208	rsp->DialectRevision = cpu_to_le16(conn->dialect);
1209	/* Not setting conn guid rsp->ServerGUID, as it
1210	 * not used by client for identifying server
1211	 */
1212	memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1213
1214	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1215	rsp->ServerStartTime = 0;
1216	ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1217		    le32_to_cpu(rsp->NegotiateContextOffset),
1218		    le16_to_cpu(rsp->NegotiateContextCount));
1219
1220	rsp->SecurityBufferOffset = cpu_to_le16(128);
1221	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1222	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1223				  le16_to_cpu(rsp->SecurityBufferOffset));
1224
1225	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1226	conn->use_spnego = true;
1227
1228	if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1229	     server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1230	    req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1231		conn->sign = true;
1232	else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1233		server_conf.enforced_signing = true;
1234		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1235		conn->sign = true;
1236	}
1237
1238	conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1239	ksmbd_conn_set_need_negotiate(conn);
1240
1241err_out:
1242	if (rc)
1243		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1244
1245	if (!rc)
1246		rc = ksmbd_iov_pin_rsp(work, rsp,
1247				       sizeof(struct smb2_negotiate_rsp) +
1248					AUTH_GSS_LENGTH + neg_ctxt_len);
1249	if (rc < 0)
1250		smb2_set_err_rsp(work);
1251	return rc;
1252}
1253
1254static int alloc_preauth_hash(struct ksmbd_session *sess,
1255			      struct ksmbd_conn *conn)
1256{
1257	if (sess->Preauth_HashValue)
1258		return 0;
1259
1260	sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1261					  PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1262	if (!sess->Preauth_HashValue)
1263		return -ENOMEM;
1264
1265	return 0;
1266}
1267
1268static int generate_preauth_hash(struct ksmbd_work *work)
1269{
1270	struct ksmbd_conn *conn = work->conn;
1271	struct ksmbd_session *sess = work->sess;
1272	u8 *preauth_hash;
1273
1274	if (conn->dialect != SMB311_PROT_ID)
1275		return 0;
1276
1277	if (conn->binding) {
1278		struct preauth_session *preauth_sess;
1279
1280		preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1281		if (!preauth_sess) {
1282			preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1283			if (!preauth_sess)
1284				return -ENOMEM;
1285		}
1286
1287		preauth_hash = preauth_sess->Preauth_HashValue;
1288	} else {
1289		if (!sess->Preauth_HashValue)
1290			if (alloc_preauth_hash(sess, conn))
1291				return -ENOMEM;
1292		preauth_hash = sess->Preauth_HashValue;
1293	}
1294
1295	ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1296	return 0;
1297}
1298
1299static int decode_negotiation_token(struct ksmbd_conn *conn,
1300				    struct negotiate_message *negblob,
1301				    size_t sz)
1302{
1303	if (!conn->use_spnego)
1304		return -EINVAL;
1305
1306	if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1307		if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1308			conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1309			conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1310			conn->use_spnego = false;
1311		}
1312	}
1313	return 0;
1314}
1315
1316static int ntlm_negotiate(struct ksmbd_work *work,
1317			  struct negotiate_message *negblob,
1318			  size_t negblob_len, struct smb2_sess_setup_rsp *rsp)
1319{
1320	struct challenge_message *chgblob;
1321	unsigned char *spnego_blob = NULL;
1322	u16 spnego_blob_len;
1323	char *neg_blob;
1324	int sz, rc;
1325
1326	ksmbd_debug(SMB, "negotiate phase\n");
1327	rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1328	if (rc)
1329		return rc;
1330
1331	sz = le16_to_cpu(rsp->SecurityBufferOffset);
1332	chgblob =
1333		(struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1334	memset(chgblob, 0, sizeof(struct challenge_message));
1335
1336	if (!work->conn->use_spnego) {
1337		sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1338		if (sz < 0)
1339			return -ENOMEM;
1340
1341		rsp->SecurityBufferLength = cpu_to_le16(sz);
1342		return 0;
1343	}
1344
1345	sz = sizeof(struct challenge_message);
1346	sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1347
1348	neg_blob = kzalloc(sz, GFP_KERNEL);
1349	if (!neg_blob)
1350		return -ENOMEM;
1351
1352	chgblob = (struct challenge_message *)neg_blob;
1353	sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1354	if (sz < 0) {
1355		rc = -ENOMEM;
1356		goto out;
1357	}
1358
1359	rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1360					   neg_blob, sz);
1361	if (rc) {
1362		rc = -ENOMEM;
1363		goto out;
1364	}
1365
1366	sz = le16_to_cpu(rsp->SecurityBufferOffset);
1367	memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1368	rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1369
1370out:
1371	kfree(spnego_blob);
1372	kfree(neg_blob);
1373	return rc;
1374}
1375
1376static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1377						  struct smb2_sess_setup_req *req)
1378{
1379	int sz;
1380
1381	if (conn->use_spnego && conn->mechToken)
1382		return (struct authenticate_message *)conn->mechToken;
1383
1384	sz = le16_to_cpu(req->SecurityBufferOffset);
1385	return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1386					       + sz);
1387}
1388
1389static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1390				       struct smb2_sess_setup_req *req)
1391{
1392	struct authenticate_message *authblob;
1393	struct ksmbd_user *user;
1394	char *name;
1395	unsigned int name_off, name_len, secbuf_len;
1396
1397	if (conn->use_spnego && conn->mechToken)
1398		secbuf_len = conn->mechTokenLen;
1399	else
1400		secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1401	if (secbuf_len < sizeof(struct authenticate_message)) {
1402		ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1403		return NULL;
1404	}
1405	authblob = user_authblob(conn, req);
1406	name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1407	name_len = le16_to_cpu(authblob->UserName.Length);
1408
1409	if (secbuf_len < (u64)name_off + name_len)
1410		return NULL;
1411
1412	name = smb_strndup_from_utf16((const char *)authblob + name_off,
1413				      name_len,
1414				      true,
1415				      conn->local_nls);
1416	if (IS_ERR(name)) {
1417		pr_err("cannot allocate memory\n");
1418		return NULL;
1419	}
1420
1421	ksmbd_debug(SMB, "session setup request for user %s\n", name);
1422	user = ksmbd_login_user(name);
1423	kfree(name);
1424	return user;
1425}
1426
1427static int ntlm_authenticate(struct ksmbd_work *work,
1428			     struct smb2_sess_setup_req *req,
1429			     struct smb2_sess_setup_rsp *rsp)
1430{
1431	struct ksmbd_conn *conn = work->conn;
1432	struct ksmbd_session *sess = work->sess;
1433	struct channel *chann = NULL;
1434	struct ksmbd_user *user;
1435	u64 prev_id;
1436	int sz, rc;
1437
1438	ksmbd_debug(SMB, "authenticate phase\n");
1439	if (conn->use_spnego) {
1440		unsigned char *spnego_blob;
1441		u16 spnego_blob_len;
1442
1443		rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1444						    &spnego_blob_len,
1445						    0);
1446		if (rc)
1447			return -ENOMEM;
1448
1449		sz = le16_to_cpu(rsp->SecurityBufferOffset);
1450		memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1451		rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1452		kfree(spnego_blob);
1453	}
1454
1455	user = session_user(conn, req);
1456	if (!user) {
1457		ksmbd_debug(SMB, "Unknown user name or an error\n");
1458		return -EPERM;
1459	}
1460
1461	/* Check for previous session */
1462	prev_id = le64_to_cpu(req->PreviousSessionId);
1463	if (prev_id && prev_id != sess->id)
1464		destroy_previous_session(conn, user, prev_id);
1465
1466	if (sess->state == SMB2_SESSION_VALID) {
1467		/*
1468		 * Reuse session if anonymous try to connect
1469		 * on reauthetication.
1470		 */
1471		if (conn->binding == false && ksmbd_anonymous_user(user)) {
1472			ksmbd_free_user(user);
1473			return 0;
1474		}
1475
1476		if (!ksmbd_compare_user(sess->user, user)) {
1477			ksmbd_free_user(user);
1478			return -EPERM;
1479		}
1480		ksmbd_free_user(user);
1481	} else {
1482		sess->user = user;
1483	}
1484
1485	if (conn->binding == false && user_guest(sess->user)) {
1486		rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1487	} else {
1488		struct authenticate_message *authblob;
1489
1490		authblob = user_authblob(conn, req);
1491		if (conn->use_spnego && conn->mechToken)
1492			sz = conn->mechTokenLen;
1493		else
1494			sz = le16_to_cpu(req->SecurityBufferLength);
1495		rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1496		if (rc) {
1497			set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1498			ksmbd_debug(SMB, "authentication failed\n");
1499			return -EPERM;
1500		}
1501	}
1502
1503	/*
1504	 * If session state is SMB2_SESSION_VALID, We can assume
1505	 * that it is reauthentication. And the user/password
1506	 * has been verified, so return it here.
1507	 */
1508	if (sess->state == SMB2_SESSION_VALID) {
1509		if (conn->binding)
1510			goto binding_session;
1511		return 0;
1512	}
1513
1514	if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1515	     (conn->sign || server_conf.enforced_signing)) ||
1516	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1517		sess->sign = true;
1518
1519	if (smb3_encryption_negotiated(conn) &&
1520			!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1521		rc = conn->ops->generate_encryptionkey(conn, sess);
1522		if (rc) {
1523			ksmbd_debug(SMB,
1524					"SMB3 encryption key generation failed\n");
1525			return -EINVAL;
1526		}
1527		sess->enc = true;
1528		if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1529			rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1530		/*
1531		 * signing is disable if encryption is enable
1532		 * on this session
1533		 */
1534		sess->sign = false;
1535	}
1536
1537binding_session:
1538	if (conn->dialect >= SMB30_PROT_ID) {
1539		chann = lookup_chann_list(sess, conn);
1540		if (!chann) {
1541			chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1542			if (!chann)
1543				return -ENOMEM;
1544
1545			chann->conn = conn;
1546			xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1547		}
1548	}
1549
1550	if (conn->ops->generate_signingkey) {
1551		rc = conn->ops->generate_signingkey(sess, conn);
1552		if (rc) {
1553			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1554			return -EINVAL;
1555		}
1556	}
1557
1558	if (!ksmbd_conn_lookup_dialect(conn)) {
1559		pr_err("fail to verify the dialect\n");
1560		return -ENOENT;
1561	}
1562	return 0;
1563}
1564
1565#ifdef CONFIG_SMB_SERVER_KERBEROS5
1566static int krb5_authenticate(struct ksmbd_work *work,
1567			     struct smb2_sess_setup_req *req,
1568			     struct smb2_sess_setup_rsp *rsp)
1569{
1570	struct ksmbd_conn *conn = work->conn;
1571	struct ksmbd_session *sess = work->sess;
1572	char *in_blob, *out_blob;
1573	struct channel *chann = NULL;
1574	u64 prev_sess_id;
1575	int in_len, out_len;
1576	int retval;
1577
1578	in_blob = (char *)&req->hdr.ProtocolId +
1579		le16_to_cpu(req->SecurityBufferOffset);
1580	in_len = le16_to_cpu(req->SecurityBufferLength);
1581	out_blob = (char *)&rsp->hdr.ProtocolId +
1582		le16_to_cpu(rsp->SecurityBufferOffset);
1583	out_len = work->response_sz -
1584		(le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1585
1586	/* Check previous session */
1587	prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1588	if (prev_sess_id && prev_sess_id != sess->id)
1589		destroy_previous_session(conn, sess->user, prev_sess_id);
1590
1591	if (sess->state == SMB2_SESSION_VALID)
1592		ksmbd_free_user(sess->user);
1593
1594	retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1595					 out_blob, &out_len);
1596	if (retval) {
1597		ksmbd_debug(SMB, "krb5 authentication failed\n");
1598		return -EINVAL;
1599	}
1600	rsp->SecurityBufferLength = cpu_to_le16(out_len);
1601
1602	if ((conn->sign || server_conf.enforced_signing) ||
1603	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1604		sess->sign = true;
1605
1606	if (smb3_encryption_negotiated(conn)) {
1607		retval = conn->ops->generate_encryptionkey(conn, sess);
1608		if (retval) {
1609			ksmbd_debug(SMB,
1610				    "SMB3 encryption key generation failed\n");
1611			return -EINVAL;
1612		}
1613		sess->enc = true;
1614		if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1615			rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1616		sess->sign = false;
1617	}
1618
1619	if (conn->dialect >= SMB30_PROT_ID) {
1620		chann = lookup_chann_list(sess, conn);
1621		if (!chann) {
1622			chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1623			if (!chann)
1624				return -ENOMEM;
1625
1626			chann->conn = conn;
1627			xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1628		}
1629	}
1630
1631	if (conn->ops->generate_signingkey) {
1632		retval = conn->ops->generate_signingkey(sess, conn);
1633		if (retval) {
1634			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1635			return -EINVAL;
1636		}
1637	}
1638
1639	if (!ksmbd_conn_lookup_dialect(conn)) {
1640		pr_err("fail to verify the dialect\n");
1641		return -ENOENT;
1642	}
1643	return 0;
1644}
1645#else
1646static int krb5_authenticate(struct ksmbd_work *work,
1647			     struct smb2_sess_setup_req *req,
1648			     struct smb2_sess_setup_rsp *rsp)
1649{
1650	return -EOPNOTSUPP;
1651}
1652#endif
1653
1654int smb2_sess_setup(struct ksmbd_work *work)
1655{
1656	struct ksmbd_conn *conn = work->conn;
1657	struct smb2_sess_setup_req *req;
1658	struct smb2_sess_setup_rsp *rsp;
1659	struct ksmbd_session *sess;
1660	struct negotiate_message *negblob;
1661	unsigned int negblob_len, negblob_off;
1662	int rc = 0;
1663
1664	ksmbd_debug(SMB, "Received request for session setup\n");
1665
1666	WORK_BUFFERS(work, req, rsp);
1667
1668	rsp->StructureSize = cpu_to_le16(9);
1669	rsp->SessionFlags = 0;
1670	rsp->SecurityBufferOffset = cpu_to_le16(72);
1671	rsp->SecurityBufferLength = 0;
1672
1673	ksmbd_conn_lock(conn);
1674	if (!req->hdr.SessionId) {
1675		sess = ksmbd_smb2_session_create();
1676		if (!sess) {
1677			rc = -ENOMEM;
1678			goto out_err;
1679		}
1680		rsp->hdr.SessionId = cpu_to_le64(sess->id);
1681		rc = ksmbd_session_register(conn, sess);
1682		if (rc)
1683			goto out_err;
1684	} else if (conn->dialect >= SMB30_PROT_ID &&
1685		   (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1686		   req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1687		u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1688
1689		sess = ksmbd_session_lookup_slowpath(sess_id);
1690		if (!sess) {
1691			rc = -ENOENT;
1692			goto out_err;
1693		}
1694
1695		if (conn->dialect != sess->dialect) {
1696			rc = -EINVAL;
1697			goto out_err;
1698		}
1699
1700		if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1701			rc = -EINVAL;
1702			goto out_err;
1703		}
1704
1705		if (strncmp(conn->ClientGUID, sess->ClientGUID,
1706			    SMB2_CLIENT_GUID_SIZE)) {
1707			rc = -ENOENT;
1708			goto out_err;
1709		}
1710
1711		if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1712			rc = -EACCES;
1713			goto out_err;
1714		}
1715
1716		if (sess->state == SMB2_SESSION_EXPIRED) {
1717			rc = -EFAULT;
1718			goto out_err;
1719		}
1720
1721		if (ksmbd_conn_need_reconnect(conn)) {
1722			rc = -EFAULT;
1723			sess = NULL;
1724			goto out_err;
1725		}
1726
1727		if (ksmbd_session_lookup(conn, sess_id)) {
1728			rc = -EACCES;
1729			goto out_err;
1730		}
1731
1732		if (user_guest(sess->user)) {
1733			rc = -EOPNOTSUPP;
1734			goto out_err;
1735		}
1736
1737		conn->binding = true;
1738	} else if ((conn->dialect < SMB30_PROT_ID ||
1739		    server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1740		   (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1741		sess = NULL;
1742		rc = -EACCES;
1743		goto out_err;
1744	} else {
1745		sess = ksmbd_session_lookup(conn,
1746					    le64_to_cpu(req->hdr.SessionId));
1747		if (!sess) {
1748			rc = -ENOENT;
1749			goto out_err;
1750		}
1751
1752		if (sess->state == SMB2_SESSION_EXPIRED) {
1753			rc = -EFAULT;
1754			goto out_err;
1755		}
1756
1757		if (ksmbd_conn_need_reconnect(conn)) {
1758			rc = -EFAULT;
1759			sess = NULL;
1760			goto out_err;
1761		}
1762	}
1763	work->sess = sess;
1764
1765	negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1766	negblob_len = le16_to_cpu(req->SecurityBufferLength);
1767	if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer)) {
1768		rc = -EINVAL;
1769		goto out_err;
1770	}
1771
1772	negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1773			negblob_off);
1774
1775	if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1776		if (conn->mechToken) {
1777			negblob = (struct negotiate_message *)conn->mechToken;
1778			negblob_len = conn->mechTokenLen;
1779		}
1780	}
1781
1782	if (negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1783		rc = -EINVAL;
1784		goto out_err;
1785	}
1786
1787	if (server_conf.auth_mechs & conn->auth_mechs) {
1788		rc = generate_preauth_hash(work);
1789		if (rc)
1790			goto out_err;
1791
1792		if (conn->preferred_auth_mech &
1793				(KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1794			rc = krb5_authenticate(work, req, rsp);
1795			if (rc) {
1796				rc = -EINVAL;
1797				goto out_err;
1798			}
1799
1800			if (!ksmbd_conn_need_reconnect(conn)) {
1801				ksmbd_conn_set_good(conn);
1802				sess->state = SMB2_SESSION_VALID;
1803			}
1804			kfree(sess->Preauth_HashValue);
1805			sess->Preauth_HashValue = NULL;
1806		} else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1807			if (negblob->MessageType == NtLmNegotiate) {
1808				rc = ntlm_negotiate(work, negblob, negblob_len, rsp);
1809				if (rc)
1810					goto out_err;
1811				rsp->hdr.Status =
1812					STATUS_MORE_PROCESSING_REQUIRED;
1813			} else if (negblob->MessageType == NtLmAuthenticate) {
1814				rc = ntlm_authenticate(work, req, rsp);
1815				if (rc)
1816					goto out_err;
1817
1818				if (!ksmbd_conn_need_reconnect(conn)) {
1819					ksmbd_conn_set_good(conn);
1820					sess->state = SMB2_SESSION_VALID;
1821				}
1822				if (conn->binding) {
1823					struct preauth_session *preauth_sess;
1824
1825					preauth_sess =
1826						ksmbd_preauth_session_lookup(conn, sess->id);
1827					if (preauth_sess) {
1828						list_del(&preauth_sess->preauth_entry);
1829						kfree(preauth_sess);
1830					}
1831				}
1832				kfree(sess->Preauth_HashValue);
1833				sess->Preauth_HashValue = NULL;
1834			} else {
1835				pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
1836						le32_to_cpu(negblob->MessageType));
1837				rc = -EINVAL;
1838			}
1839		} else {
1840			/* TODO: need one more negotiation */
1841			pr_err("Not support the preferred authentication\n");
1842			rc = -EINVAL;
1843		}
1844	} else {
1845		pr_err("Not support authentication\n");
1846		rc = -EINVAL;
1847	}
1848
1849out_err:
1850	if (rc == -EINVAL)
1851		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1852	else if (rc == -ENOENT)
1853		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1854	else if (rc == -EACCES)
1855		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1856	else if (rc == -EFAULT)
1857		rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1858	else if (rc == -ENOMEM)
1859		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1860	else if (rc == -EOPNOTSUPP)
1861		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1862	else if (rc)
1863		rsp->hdr.Status = STATUS_LOGON_FAILURE;
1864
1865	if (conn->use_spnego && conn->mechToken) {
1866		kfree(conn->mechToken);
1867		conn->mechToken = NULL;
1868	}
1869
1870	if (rc < 0) {
1871		/*
1872		 * SecurityBufferOffset should be set to zero
1873		 * in session setup error response.
1874		 */
1875		rsp->SecurityBufferOffset = 0;
1876
1877		if (sess) {
1878			bool try_delay = false;
1879
1880			/*
1881			 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1882			 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1883			 * failure to make it harder to send enough random connection requests
1884			 * to break into a server.
1885			 */
1886			if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1887				try_delay = true;
1888
1889			sess->last_active = jiffies;
1890			sess->state = SMB2_SESSION_EXPIRED;
1891			if (try_delay) {
1892				ksmbd_conn_set_need_reconnect(conn);
1893				ssleep(5);
1894				ksmbd_conn_set_need_negotiate(conn);
1895			}
1896		}
1897		smb2_set_err_rsp(work);
1898	} else {
1899		unsigned int iov_len;
1900
1901		if (rsp->SecurityBufferLength)
1902			iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) +
1903				le16_to_cpu(rsp->SecurityBufferLength);
1904		else
1905			iov_len = sizeof(struct smb2_sess_setup_rsp);
1906		rc = ksmbd_iov_pin_rsp(work, rsp, iov_len);
1907		if (rc)
1908			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1909	}
1910
1911	ksmbd_conn_unlock(conn);
1912	return rc;
1913}
1914
1915/**
1916 * smb2_tree_connect() - handler for smb2 tree connect command
1917 * @work:	smb work containing smb request buffer
1918 *
1919 * Return:      0 on success, otherwise error
1920 */
1921int smb2_tree_connect(struct ksmbd_work *work)
1922{
1923	struct ksmbd_conn *conn = work->conn;
1924	struct smb2_tree_connect_req *req;
1925	struct smb2_tree_connect_rsp *rsp;
1926	struct ksmbd_session *sess = work->sess;
1927	char *treename = NULL, *name = NULL;
1928	struct ksmbd_tree_conn_status status;
1929	struct ksmbd_share_config *share;
1930	int rc = -EINVAL;
1931
1932	WORK_BUFFERS(work, req, rsp);
1933
1934	treename = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->PathOffset),
1935					  le16_to_cpu(req->PathLength), true,
1936					  conn->local_nls);
1937	if (IS_ERR(treename)) {
1938		pr_err("treename is NULL\n");
1939		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1940		goto out_err1;
1941	}
1942
1943	name = ksmbd_extract_sharename(conn->um, treename);
1944	if (IS_ERR(name)) {
1945		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1946		goto out_err1;
1947	}
1948
1949	ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1950		    name, treename);
1951
1952	status = ksmbd_tree_conn_connect(conn, sess, name);
1953	if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1954		rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1955	else
1956		goto out_err1;
1957
1958	share = status.tree_conn->share_conf;
1959	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1960		ksmbd_debug(SMB, "IPC share path request\n");
1961		rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1962		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1963			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1964			FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1965			FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1966			FILE_SYNCHRONIZE_LE;
1967	} else {
1968		rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1969		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1970			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1971		if (test_tree_conn_flag(status.tree_conn,
1972					KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1973			rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1974				FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1975				FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1976				FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1977				FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1978				FILE_SYNCHRONIZE_LE;
1979		}
1980	}
1981
1982	status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1983	if (conn->posix_ext_supported)
1984		status.tree_conn->posix_extensions = true;
1985
1986	write_lock(&sess->tree_conns_lock);
1987	status.tree_conn->t_state = TREE_CONNECTED;
1988	write_unlock(&sess->tree_conns_lock);
1989	rsp->StructureSize = cpu_to_le16(16);
1990out_err1:
1991	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE &&
1992	    test_share_config_flag(share,
1993				   KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY))
1994		rsp->Capabilities = SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY;
1995	else
1996		rsp->Capabilities = 0;
1997	rsp->Reserved = 0;
1998	/* default manual caching */
1999	rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
2000
2001	rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
2002	if (rc)
2003		status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
2004
2005	if (!IS_ERR(treename))
2006		kfree(treename);
2007	if (!IS_ERR(name))
2008		kfree(name);
2009
2010	switch (status.ret) {
2011	case KSMBD_TREE_CONN_STATUS_OK:
2012		rsp->hdr.Status = STATUS_SUCCESS;
2013		rc = 0;
2014		break;
2015	case -ESTALE:
2016	case -ENOENT:
2017	case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2018		rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2019		break;
2020	case -ENOMEM:
2021	case KSMBD_TREE_CONN_STATUS_NOMEM:
2022		rsp->hdr.Status = STATUS_NO_MEMORY;
2023		break;
2024	case KSMBD_TREE_CONN_STATUS_ERROR:
2025	case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2026	case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2027		rsp->hdr.Status = STATUS_ACCESS_DENIED;
2028		break;
2029	case -EINVAL:
2030		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2031		break;
2032	default:
2033		rsp->hdr.Status = STATUS_ACCESS_DENIED;
2034	}
2035
2036	if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2037		smb2_set_err_rsp(work);
2038
2039	return rc;
2040}
2041
2042/**
2043 * smb2_create_open_flags() - convert smb open flags to unix open flags
2044 * @file_present:	is file already present
2045 * @access:		file access flags
2046 * @disposition:	file disposition flags
2047 * @may_flags:		set with MAY_ flags
2048 *
2049 * Return:      file open flags
2050 */
2051static int smb2_create_open_flags(bool file_present, __le32 access,
2052				  __le32 disposition,
2053				  int *may_flags)
2054{
2055	int oflags = O_NONBLOCK | O_LARGEFILE;
2056
2057	if (access & FILE_READ_DESIRED_ACCESS_LE &&
2058	    access & FILE_WRITE_DESIRE_ACCESS_LE) {
2059		oflags |= O_RDWR;
2060		*may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2061	} else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2062		oflags |= O_WRONLY;
2063		*may_flags = MAY_OPEN | MAY_WRITE;
2064	} else {
2065		oflags |= O_RDONLY;
2066		*may_flags = MAY_OPEN | MAY_READ;
2067	}
2068
2069	if (access == FILE_READ_ATTRIBUTES_LE)
2070		oflags |= O_PATH;
2071
2072	if (file_present) {
2073		switch (disposition & FILE_CREATE_MASK_LE) {
2074		case FILE_OPEN_LE:
2075		case FILE_CREATE_LE:
2076			break;
2077		case FILE_SUPERSEDE_LE:
2078		case FILE_OVERWRITE_LE:
2079		case FILE_OVERWRITE_IF_LE:
2080			oflags |= O_TRUNC;
2081			break;
2082		default:
2083			break;
2084		}
2085	} else {
2086		switch (disposition & FILE_CREATE_MASK_LE) {
2087		case FILE_SUPERSEDE_LE:
2088		case FILE_CREATE_LE:
2089		case FILE_OPEN_IF_LE:
2090		case FILE_OVERWRITE_IF_LE:
2091			oflags |= O_CREAT;
2092			break;
2093		case FILE_OPEN_LE:
2094		case FILE_OVERWRITE_LE:
2095			oflags &= ~O_CREAT;
2096			break;
2097		default:
2098			break;
2099		}
2100	}
2101
2102	return oflags;
2103}
2104
2105/**
2106 * smb2_tree_disconnect() - handler for smb tree connect request
2107 * @work:	smb work containing request buffer
2108 *
2109 * Return:      0
2110 */
2111int smb2_tree_disconnect(struct ksmbd_work *work)
2112{
2113	struct smb2_tree_disconnect_rsp *rsp;
2114	struct smb2_tree_disconnect_req *req;
2115	struct ksmbd_session *sess = work->sess;
2116	struct ksmbd_tree_connect *tcon = work->tcon;
2117	int err;
2118
2119	WORK_BUFFERS(work, req, rsp);
2120
2121	ksmbd_debug(SMB, "request\n");
2122
2123	if (!tcon) {
2124		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2125
2126		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2127		err = -ENOENT;
2128		goto err_out;
2129	}
2130
2131	ksmbd_close_tree_conn_fds(work);
2132
2133	write_lock(&sess->tree_conns_lock);
2134	if (tcon->t_state == TREE_DISCONNECTED) {
2135		write_unlock(&sess->tree_conns_lock);
2136		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2137		err = -ENOENT;
2138		goto err_out;
2139	}
2140
2141	WARN_ON_ONCE(atomic_dec_and_test(&tcon->refcount));
2142	tcon->t_state = TREE_DISCONNECTED;
2143	write_unlock(&sess->tree_conns_lock);
2144
2145	err = ksmbd_tree_conn_disconnect(sess, tcon);
2146	if (err) {
2147		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2148		goto err_out;
2149	}
2150
2151	work->tcon = NULL;
2152
2153	rsp->StructureSize = cpu_to_le16(4);
2154	err = ksmbd_iov_pin_rsp(work, rsp,
2155				sizeof(struct smb2_tree_disconnect_rsp));
2156	if (err) {
2157		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2158		goto err_out;
2159	}
2160
2161	return 0;
2162
2163err_out:
2164	smb2_set_err_rsp(work);
2165	return err;
2166
2167}
2168
2169/**
2170 * smb2_session_logoff() - handler for session log off request
2171 * @work:	smb work containing request buffer
2172 *
2173 * Return:      0
2174 */
2175int smb2_session_logoff(struct ksmbd_work *work)
2176{
2177	struct ksmbd_conn *conn = work->conn;
2178	struct smb2_logoff_req *req;
2179	struct smb2_logoff_rsp *rsp;
2180	struct ksmbd_session *sess;
2181	u64 sess_id;
2182	int err;
2183
2184	WORK_BUFFERS(work, req, rsp);
2185
2186	ksmbd_debug(SMB, "request\n");
2187
2188	ksmbd_conn_lock(conn);
2189	if (!ksmbd_conn_good(conn)) {
2190		ksmbd_conn_unlock(conn);
2191		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2192		smb2_set_err_rsp(work);
2193		return -ENOENT;
2194	}
2195	sess_id = le64_to_cpu(req->hdr.SessionId);
2196	ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
2197	ksmbd_conn_unlock(conn);
2198
2199	ksmbd_close_session_fds(work);
2200	ksmbd_conn_wait_idle(conn, sess_id);
2201
2202	/*
2203	 * Re-lookup session to validate if session is deleted
2204	 * while waiting request complete
2205	 */
2206	sess = ksmbd_session_lookup_all(conn, sess_id);
2207	if (ksmbd_tree_conn_session_logoff(sess)) {
2208		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2209		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2210		smb2_set_err_rsp(work);
2211		return -ENOENT;
2212	}
2213
2214	ksmbd_destroy_file_table(&sess->file_table);
2215	sess->state = SMB2_SESSION_EXPIRED;
2216
2217	ksmbd_free_user(sess->user);
2218	sess->user = NULL;
2219	ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_NEGOTIATE);
2220
2221	rsp->StructureSize = cpu_to_le16(4);
2222	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
2223	if (err) {
2224		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2225		smb2_set_err_rsp(work);
2226		return err;
2227	}
2228	return 0;
2229}
2230
2231/**
2232 * create_smb2_pipe() - create IPC pipe
2233 * @work:	smb work containing request buffer
2234 *
2235 * Return:      0 on success, otherwise error
2236 */
2237static noinline int create_smb2_pipe(struct ksmbd_work *work)
2238{
2239	struct smb2_create_rsp *rsp;
2240	struct smb2_create_req *req;
2241	int id;
2242	int err;
2243	char *name;
2244
2245	WORK_BUFFERS(work, req, rsp);
2246
2247	name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2248				      1, work->conn->local_nls);
2249	if (IS_ERR(name)) {
2250		rsp->hdr.Status = STATUS_NO_MEMORY;
2251		err = PTR_ERR(name);
2252		goto out;
2253	}
2254
2255	id = ksmbd_session_rpc_open(work->sess, name);
2256	if (id < 0) {
2257		pr_err("Unable to open RPC pipe: %d\n", id);
2258		err = id;
2259		goto out;
2260	}
2261
2262	rsp->hdr.Status = STATUS_SUCCESS;
2263	rsp->StructureSize = cpu_to_le16(89);
2264	rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2265	rsp->Flags = 0;
2266	rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2267
2268	rsp->CreationTime = cpu_to_le64(0);
2269	rsp->LastAccessTime = cpu_to_le64(0);
2270	rsp->ChangeTime = cpu_to_le64(0);
2271	rsp->AllocationSize = cpu_to_le64(0);
2272	rsp->EndofFile = cpu_to_le64(0);
2273	rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2274	rsp->Reserved2 = 0;
2275	rsp->VolatileFileId = id;
2276	rsp->PersistentFileId = 0;
2277	rsp->CreateContextsOffset = 0;
2278	rsp->CreateContextsLength = 0;
2279
2280	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
2281	if (err)
2282		goto out;
2283
2284	kfree(name);
2285	return 0;
2286
2287out:
2288	switch (err) {
2289	case -EINVAL:
2290		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2291		break;
2292	case -ENOSPC:
2293	case -ENOMEM:
2294		rsp->hdr.Status = STATUS_NO_MEMORY;
2295		break;
2296	}
2297
2298	if (!IS_ERR(name))
2299		kfree(name);
2300
2301	smb2_set_err_rsp(work);
2302	return err;
2303}
2304
2305/**
2306 * smb2_set_ea() - handler for setting extended attributes using set
2307 *		info command
2308 * @eabuf:	set info command buffer
2309 * @buf_len:	set info command buffer length
2310 * @path:	dentry path for get ea
2311 * @get_write:	get write access to a mount
2312 *
2313 * Return:	0 on success, otherwise error
2314 */
2315static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2316		       const struct path *path, bool get_write)
2317{
2318	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2319	char *attr_name = NULL, *value;
2320	int rc = 0;
2321	unsigned int next = 0;
2322
2323	if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2324			le16_to_cpu(eabuf->EaValueLength))
2325		return -EINVAL;
2326
2327	attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2328	if (!attr_name)
2329		return -ENOMEM;
2330
2331	do {
2332		if (!eabuf->EaNameLength)
2333			goto next;
2334
2335		ksmbd_debug(SMB,
2336			    "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2337			    eabuf->name, eabuf->EaNameLength,
2338			    le16_to_cpu(eabuf->EaValueLength),
2339			    le32_to_cpu(eabuf->NextEntryOffset));
2340
2341		if (eabuf->EaNameLength >
2342		    (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2343			rc = -EINVAL;
2344			break;
2345		}
2346
2347		memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2348		memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2349		       eabuf->EaNameLength);
2350		attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2351		value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2352
2353		if (!eabuf->EaValueLength) {
2354			rc = ksmbd_vfs_casexattr_len(idmap,
2355						     path->dentry,
2356						     attr_name,
2357						     XATTR_USER_PREFIX_LEN +
2358						     eabuf->EaNameLength);
2359
2360			/* delete the EA only when it exits */
2361			if (rc > 0) {
2362				rc = ksmbd_vfs_remove_xattr(idmap,
2363							    path,
2364							    attr_name);
2365
2366				if (rc < 0) {
2367					ksmbd_debug(SMB,
2368						    "remove xattr failed(%d)\n",
2369						    rc);
2370					break;
2371				}
2372			}
2373
2374			/* if the EA doesn't exist, just do nothing. */
2375			rc = 0;
2376		} else {
2377			rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
2378						le16_to_cpu(eabuf->EaValueLength),
2379						0, true);
2380			if (rc < 0) {
2381				ksmbd_debug(SMB,
2382					    "ksmbd_vfs_setxattr is failed(%d)\n",
2383					    rc);
2384				break;
2385			}
2386		}
2387
2388next:
2389		next = le32_to_cpu(eabuf->NextEntryOffset);
2390		if (next == 0 || buf_len < next)
2391			break;
2392		buf_len -= next;
2393		eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2394		if (buf_len < sizeof(struct smb2_ea_info)) {
2395			rc = -EINVAL;
2396			break;
2397		}
2398
2399		if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2400				le16_to_cpu(eabuf->EaValueLength)) {
2401			rc = -EINVAL;
2402			break;
2403		}
2404	} while (next != 0);
2405
2406	kfree(attr_name);
2407	return rc;
2408}
2409
2410static noinline int smb2_set_stream_name_xattr(const struct path *path,
2411					       struct ksmbd_file *fp,
2412					       char *stream_name, int s_type)
2413{
2414	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2415	size_t xattr_stream_size;
2416	char *xattr_stream_name;
2417	int rc;
2418
2419	rc = ksmbd_vfs_xattr_stream_name(stream_name,
2420					 &xattr_stream_name,
2421					 &xattr_stream_size,
2422					 s_type);
2423	if (rc)
2424		return rc;
2425
2426	fp->stream.name = xattr_stream_name;
2427	fp->stream.size = xattr_stream_size;
2428
2429	/* Check if there is stream prefix in xattr space */
2430	rc = ksmbd_vfs_casexattr_len(idmap,
2431				     path->dentry,
2432				     xattr_stream_name,
2433				     xattr_stream_size);
2434	if (rc >= 0)
2435		return 0;
2436
2437	if (fp->cdoption == FILE_OPEN_LE) {
2438		ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2439		return -EBADF;
2440	}
2441
2442	rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0, false);
2443	if (rc < 0)
2444		pr_err("Failed to store XATTR stream name :%d\n", rc);
2445	return 0;
2446}
2447
2448static int smb2_remove_smb_xattrs(const struct path *path)
2449{
2450	struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2451	char *name, *xattr_list = NULL;
2452	ssize_t xattr_list_len;
2453	int err = 0;
2454
2455	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2456	if (xattr_list_len < 0) {
2457		goto out;
2458	} else if (!xattr_list_len) {
2459		ksmbd_debug(SMB, "empty xattr in the file\n");
2460		goto out;
2461	}
2462
2463	for (name = xattr_list; name - xattr_list < xattr_list_len;
2464			name += strlen(name) + 1) {
2465		ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2466
2467		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2468		    !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2469			     STREAM_PREFIX_LEN)) {
2470			err = ksmbd_vfs_remove_xattr(idmap, path,
2471						     name);
2472			if (err)
2473				ksmbd_debug(SMB, "remove xattr failed : %s\n",
2474					    name);
2475		}
2476	}
2477out:
2478	kvfree(xattr_list);
2479	return err;
2480}
2481
2482static int smb2_create_truncate(const struct path *path)
2483{
2484	int rc = vfs_truncate(path, 0);
2485
2486	if (rc) {
2487		pr_err("vfs_truncate failed, rc %d\n", rc);
2488		return rc;
2489	}
2490
2491	rc = smb2_remove_smb_xattrs(path);
2492	if (rc == -EOPNOTSUPP)
2493		rc = 0;
2494	if (rc)
2495		ksmbd_debug(SMB,
2496			    "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2497			    rc);
2498	return rc;
2499}
2500
2501static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2502			    struct ksmbd_file *fp)
2503{
2504	struct xattr_dos_attrib da = {0};
2505	int rc;
2506
2507	if (!test_share_config_flag(tcon->share_conf,
2508				    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2509		return;
2510
2511	da.version = 4;
2512	da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2513	da.itime = da.create_time = fp->create_time;
2514	da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2515		XATTR_DOSINFO_ITIME;
2516
2517	rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da, true);
2518	if (rc)
2519		ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2520}
2521
2522static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2523			       const struct path *path, struct ksmbd_file *fp)
2524{
2525	struct xattr_dos_attrib da;
2526	int rc;
2527
2528	fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2529
2530	/* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2531	if (!test_share_config_flag(tcon->share_conf,
2532				    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2533		return;
2534
2535	rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
2536					    path->dentry, &da);
2537	if (rc > 0) {
2538		fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2539		fp->create_time = da.create_time;
2540		fp->itime = da.itime;
2541	}
2542}
2543
2544static int smb2_creat(struct ksmbd_work *work, struct path *parent_path,
2545		      struct path *path, char *name, int open_flags,
2546		      umode_t posix_mode, bool is_dir)
2547{
2548	struct ksmbd_tree_connect *tcon = work->tcon;
2549	struct ksmbd_share_config *share = tcon->share_conf;
2550	umode_t mode;
2551	int rc;
2552
2553	if (!(open_flags & O_CREAT))
2554		return -EBADF;
2555
2556	ksmbd_debug(SMB, "file does not exist, so creating\n");
2557	if (is_dir == true) {
2558		ksmbd_debug(SMB, "creating directory\n");
2559
2560		mode = share_config_directory_mode(share, posix_mode);
2561		rc = ksmbd_vfs_mkdir(work, name, mode);
2562		if (rc)
2563			return rc;
2564	} else {
2565		ksmbd_debug(SMB, "creating regular file\n");
2566
2567		mode = share_config_create_mode(share, posix_mode);
2568		rc = ksmbd_vfs_create(work, name, mode);
2569		if (rc)
2570			return rc;
2571	}
2572
2573	rc = ksmbd_vfs_kern_path_locked(work, name, 0, parent_path, path, 0);
2574	if (rc) {
2575		pr_err("cannot get linux path (%s), err = %d\n",
2576		       name, rc);
2577		return rc;
2578	}
2579	return 0;
2580}
2581
2582static int smb2_create_sd_buffer(struct ksmbd_work *work,
2583				 struct smb2_create_req *req,
2584				 const struct path *path)
2585{
2586	struct create_context *context;
2587	struct create_sd_buf_req *sd_buf;
2588
2589	if (!req->CreateContextsOffset)
2590		return -ENOENT;
2591
2592	/* Parse SD BUFFER create contexts */
2593	context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2594	if (!context)
2595		return -ENOENT;
2596	else if (IS_ERR(context))
2597		return PTR_ERR(context);
2598
2599	ksmbd_debug(SMB,
2600		    "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2601	sd_buf = (struct create_sd_buf_req *)context;
2602	if (le16_to_cpu(context->DataOffset) +
2603	    le32_to_cpu(context->DataLength) <
2604	    sizeof(struct create_sd_buf_req))
2605		return -EINVAL;
2606	return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2607			    le32_to_cpu(sd_buf->ccontext.DataLength), true, false);
2608}
2609
2610static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2611			     struct mnt_idmap *idmap,
2612			     struct inode *inode)
2613{
2614	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2615	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2616
2617	fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2618	fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2619	fattr->cf_mode = inode->i_mode;
2620	fattr->cf_acls = NULL;
2621	fattr->cf_dacls = NULL;
2622
2623	if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2624		fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
2625		if (S_ISDIR(inode->i_mode))
2626			fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
2627	}
2628}
2629
2630enum {
2631	DURABLE_RECONN_V2 = 1,
2632	DURABLE_RECONN,
2633	DURABLE_REQ_V2,
2634	DURABLE_REQ,
2635};
2636
2637struct durable_info {
2638	struct ksmbd_file *fp;
2639	unsigned short int type;
2640	bool persistent;
2641	bool reconnected;
2642	unsigned int timeout;
2643	char *CreateGuid;
2644};
2645
2646static int parse_durable_handle_context(struct ksmbd_work *work,
2647					struct smb2_create_req *req,
2648					struct lease_ctx_info *lc,
2649					struct durable_info *dh_info)
2650{
2651	struct ksmbd_conn *conn = work->conn;
2652	struct create_context *context;
2653	int dh_idx, err = 0;
2654	u64 persistent_id = 0;
2655	int req_op_level;
2656	static const char * const durable_arr[] = {"DH2C", "DHnC", "DH2Q", "DHnQ"};
2657
2658	req_op_level = req->RequestedOplockLevel;
2659	for (dh_idx = DURABLE_RECONN_V2; dh_idx <= ARRAY_SIZE(durable_arr);
2660	     dh_idx++) {
2661		context = smb2_find_context_vals(req, durable_arr[dh_idx - 1], 4);
2662		if (IS_ERR(context)) {
2663			err = PTR_ERR(context);
2664			goto out;
2665		}
2666		if (!context)
2667			continue;
2668
2669		switch (dh_idx) {
2670		case DURABLE_RECONN_V2:
2671		{
2672			struct create_durable_reconn_v2_req *recon_v2;
2673
2674			if (dh_info->type == DURABLE_RECONN ||
2675			    dh_info->type == DURABLE_REQ_V2) {
2676				err = -EINVAL;
2677				goto out;
2678			}
2679
2680			recon_v2 = (struct create_durable_reconn_v2_req *)context;
2681			persistent_id = recon_v2->Fid.PersistentFileId;
2682			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
2683			if (!dh_info->fp) {
2684				ksmbd_debug(SMB, "Failed to get durable handle state\n");
2685				err = -EBADF;
2686				goto out;
2687			}
2688
2689			if (memcmp(dh_info->fp->create_guid, recon_v2->CreateGuid,
2690				   SMB2_CREATE_GUID_SIZE)) {
2691				err = -EBADF;
2692				ksmbd_put_durable_fd(dh_info->fp);
2693				goto out;
2694			}
2695
2696			dh_info->type = dh_idx;
2697			dh_info->reconnected = true;
2698			ksmbd_debug(SMB,
2699				"reconnect v2 Persistent-id from reconnect = %llu\n",
2700					persistent_id);
2701			break;
2702		}
2703		case DURABLE_RECONN:
2704		{
2705			struct create_durable_reconn_req *recon;
2706
2707			if (dh_info->type == DURABLE_RECONN_V2 ||
2708			    dh_info->type == DURABLE_REQ_V2) {
2709				err = -EINVAL;
2710				goto out;
2711			}
2712
2713			recon = (struct create_durable_reconn_req *)context;
2714			persistent_id = recon->Data.Fid.PersistentFileId;
2715			dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
2716			if (!dh_info->fp) {
2717				ksmbd_debug(SMB, "Failed to get durable handle state\n");
2718				err = -EBADF;
2719				goto out;
2720			}
2721
2722			dh_info->type = dh_idx;
2723			dh_info->reconnected = true;
2724			ksmbd_debug(SMB, "reconnect Persistent-id from reconnect = %llu\n",
2725				    persistent_id);
2726			break;
2727		}
2728		case DURABLE_REQ_V2:
2729		{
2730			struct create_durable_req_v2 *durable_v2_blob;
2731
2732			if (dh_info->type == DURABLE_RECONN ||
2733			    dh_info->type == DURABLE_RECONN_V2) {
2734				err = -EINVAL;
2735				goto out;
2736			}
2737
2738			durable_v2_blob =
2739				(struct create_durable_req_v2 *)context;
2740			ksmbd_debug(SMB, "Request for durable v2 open\n");
2741			dh_info->fp = ksmbd_lookup_fd_cguid(durable_v2_blob->CreateGuid);
2742			if (dh_info->fp) {
2743				if (!memcmp(conn->ClientGUID, dh_info->fp->client_guid,
2744					    SMB2_CLIENT_GUID_SIZE)) {
2745					if (!(req->hdr.Flags & SMB2_FLAGS_REPLAY_OPERATION)) {
2746						err = -ENOEXEC;
2747						goto out;
2748					}
2749
2750					dh_info->fp->conn = conn;
2751					dh_info->reconnected = true;
2752					goto out;
2753				}
2754			}
2755
2756			if (((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
2757			     req_op_level == SMB2_OPLOCK_LEVEL_BATCH)) {
2758				dh_info->CreateGuid =
2759					durable_v2_blob->CreateGuid;
2760				dh_info->persistent =
2761					le32_to_cpu(durable_v2_blob->Flags);
2762				dh_info->timeout =
2763					le32_to_cpu(durable_v2_blob->Timeout);
2764				dh_info->type = dh_idx;
2765			}
2766			break;
2767		}
2768		case DURABLE_REQ:
2769			if (dh_info->type == DURABLE_RECONN)
2770				goto out;
2771			if (dh_info->type == DURABLE_RECONN_V2 ||
2772			    dh_info->type == DURABLE_REQ_V2) {
2773				err = -EINVAL;
2774				goto out;
2775			}
2776
2777			if (((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
2778			     req_op_level == SMB2_OPLOCK_LEVEL_BATCH)) {
2779				ksmbd_debug(SMB, "Request for durable open\n");
2780				dh_info->type = dh_idx;
2781			}
2782		}
2783	}
2784
2785out:
2786	return err;
2787}
2788
2789/**
2790 * smb2_open() - handler for smb file open request
2791 * @work:	smb work containing request buffer
2792 *
2793 * Return:      0 on success, otherwise error
2794 */
2795int smb2_open(struct ksmbd_work *work)
2796{
2797	struct ksmbd_conn *conn = work->conn;
2798	struct ksmbd_session *sess = work->sess;
2799	struct ksmbd_tree_connect *tcon = work->tcon;
2800	struct smb2_create_req *req;
2801	struct smb2_create_rsp *rsp;
2802	struct path path, parent_path;
2803	struct ksmbd_share_config *share = tcon->share_conf;
2804	struct ksmbd_file *fp = NULL;
2805	struct file *filp = NULL;
2806	struct mnt_idmap *idmap = NULL;
2807	struct kstat stat;
2808	struct create_context *context;
2809	struct lease_ctx_info *lc = NULL;
2810	struct create_ea_buf_req *ea_buf = NULL;
2811	struct oplock_info *opinfo;
2812	struct durable_info dh_info = {0};
2813	__le32 *next_ptr = NULL;
2814	int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2815	int rc = 0;
2816	int contxt_cnt = 0, query_disk_id = 0;
2817	int maximal_access_ctxt = 0, posix_ctxt = 0;
2818	int s_type = 0;
2819	int next_off = 0;
2820	char *name = NULL;
2821	char *stream_name = NULL;
2822	bool file_present = false, created = false, already_permitted = false;
2823	int share_ret, need_truncate = 0;
2824	u64 time;
2825	umode_t posix_mode = 0;
2826	__le32 daccess, maximal_access = 0;
2827	int iov_len = 0;
2828
2829	WORK_BUFFERS(work, req, rsp);
2830
2831	if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2832	    (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2833		ksmbd_debug(SMB, "invalid flag in chained command\n");
2834		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2835		smb2_set_err_rsp(work);
2836		return -EINVAL;
2837	}
2838
2839	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2840		ksmbd_debug(SMB, "IPC pipe create request\n");
2841		return create_smb2_pipe(work);
2842	}
2843
2844	if (req->NameLength) {
2845		if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2846		    *(char *)req->Buffer == '\\') {
2847			pr_err("not allow directory name included leading slash\n");
2848			rc = -EINVAL;
2849			goto err_out2;
2850		}
2851
2852		name = smb2_get_name((char *)req + le16_to_cpu(req->NameOffset),
2853				     le16_to_cpu(req->NameLength),
2854				     work->conn->local_nls);
2855		if (IS_ERR(name)) {
2856			rc = PTR_ERR(name);
2857			if (rc != -ENOMEM)
2858				rc = -ENOENT;
2859			name = NULL;
2860			goto err_out2;
2861		}
2862
2863		ksmbd_debug(SMB, "converted name = %s\n", name);
2864		if (strchr(name, ':')) {
2865			if (!test_share_config_flag(work->tcon->share_conf,
2866						    KSMBD_SHARE_FLAG_STREAMS)) {
2867				rc = -EBADF;
2868				goto err_out2;
2869			}
2870			rc = parse_stream_name(name, &stream_name, &s_type);
2871			if (rc < 0)
2872				goto err_out2;
2873		}
2874
2875		rc = ksmbd_validate_filename(name);
2876		if (rc < 0)
2877			goto err_out2;
2878
2879		if (ksmbd_share_veto_filename(share, name)) {
2880			rc = -ENOENT;
2881			ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2882				    name);
2883			goto err_out2;
2884		}
2885	} else {
2886		name = kstrdup("", GFP_KERNEL);
2887		if (!name) {
2888			rc = -ENOMEM;
2889			goto err_out2;
2890		}
2891	}
2892
2893	req_op_level = req->RequestedOplockLevel;
2894
2895	if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE &&
2896	    req->CreateContextsOffset) {
2897		lc = parse_lease_state(req);
2898		rc = parse_durable_handle_context(work, req, lc, &dh_info);
2899		if (rc) {
2900			ksmbd_debug(SMB, "error parsing durable handle context\n");
2901			goto err_out2;
2902		}
2903
2904		if (dh_info.reconnected == true) {
2905			rc = smb2_check_durable_oplock(conn, share, dh_info.fp, lc, name);
2906			if (rc) {
2907				ksmbd_put_durable_fd(dh_info.fp);
2908				goto err_out2;
2909			}
2910
2911			rc = ksmbd_reopen_durable_fd(work, dh_info.fp);
2912			if (rc) {
2913				ksmbd_put_durable_fd(dh_info.fp);
2914				goto err_out2;
2915			}
2916
2917			if (ksmbd_override_fsids(work)) {
2918				rc = -ENOMEM;
2919				ksmbd_put_durable_fd(dh_info.fp);
2920				goto err_out2;
2921			}
2922
2923			fp = dh_info.fp;
2924			file_info = FILE_OPENED;
2925
2926			rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
2927			if (rc)
2928				goto err_out2;
2929
2930			ksmbd_put_durable_fd(fp);
2931			goto reconnected_fp;
2932		}
2933	} else if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2934		lc = parse_lease_state(req);
2935
2936	if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2937		pr_err("Invalid impersonationlevel : 0x%x\n",
2938		       le32_to_cpu(req->ImpersonationLevel));
2939		rc = -EIO;
2940		rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2941		goto err_out2;
2942	}
2943
2944	if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2945		pr_err("Invalid create options : 0x%x\n",
2946		       le32_to_cpu(req->CreateOptions));
2947		rc = -EINVAL;
2948		goto err_out2;
2949	} else {
2950		if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2951		    req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2952			req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2953
2954		if (req->CreateOptions &
2955		    (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2956		     FILE_RESERVE_OPFILTER_LE)) {
2957			rc = -EOPNOTSUPP;
2958			goto err_out2;
2959		}
2960
2961		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2962			if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2963				rc = -EINVAL;
2964				goto err_out2;
2965			} else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2966				req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2967			}
2968		}
2969	}
2970
2971	if (le32_to_cpu(req->CreateDisposition) >
2972	    le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2973		pr_err("Invalid create disposition : 0x%x\n",
2974		       le32_to_cpu(req->CreateDisposition));
2975		rc = -EINVAL;
2976		goto err_out2;
2977	}
2978
2979	if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2980		pr_err("Invalid desired access : 0x%x\n",
2981		       le32_to_cpu(req->DesiredAccess));
2982		rc = -EACCES;
2983		goto err_out2;
2984	}
2985
2986	if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2987		pr_err("Invalid file attribute : 0x%x\n",
2988		       le32_to_cpu(req->FileAttributes));
2989		rc = -EINVAL;
2990		goto err_out2;
2991	}
2992
2993	if (req->CreateContextsOffset) {
2994		/* Parse non-durable handle create contexts */
2995		context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
2996		if (IS_ERR(context)) {
2997			rc = PTR_ERR(context);
2998			goto err_out2;
2999		} else if (context) {
3000			ea_buf = (struct create_ea_buf_req *)context;
3001			if (le16_to_cpu(context->DataOffset) +
3002			    le32_to_cpu(context->DataLength) <
3003			    sizeof(struct create_ea_buf_req)) {
3004				rc = -EINVAL;
3005				goto err_out2;
3006			}
3007			if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
3008				rsp->hdr.Status = STATUS_ACCESS_DENIED;
3009				rc = -EACCES;
3010				goto err_out2;
3011			}
3012		}
3013
3014		context = smb2_find_context_vals(req,
3015						 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
3016		if (IS_ERR(context)) {
3017			rc = PTR_ERR(context);
3018			goto err_out2;
3019		} else if (context) {
3020			ksmbd_debug(SMB,
3021				    "get query maximal access context\n");
3022			maximal_access_ctxt = 1;
3023		}
3024
3025		context = smb2_find_context_vals(req,
3026						 SMB2_CREATE_TIMEWARP_REQUEST, 4);
3027		if (IS_ERR(context)) {
3028			rc = PTR_ERR(context);
3029			goto err_out2;
3030		} else if (context) {
3031			ksmbd_debug(SMB, "get timewarp context\n");
3032			rc = -EBADF;
3033			goto err_out2;
3034		}
3035
3036		if (tcon->posix_extensions) {
3037			context = smb2_find_context_vals(req,
3038							 SMB2_CREATE_TAG_POSIX, 16);
3039			if (IS_ERR(context)) {
3040				rc = PTR_ERR(context);
3041				goto err_out2;
3042			} else if (context) {
3043				struct create_posix *posix =
3044					(struct create_posix *)context;
3045				if (le16_to_cpu(context->DataOffset) +
3046				    le32_to_cpu(context->DataLength) <
3047				    sizeof(struct create_posix) - 4) {
3048					rc = -EINVAL;
3049					goto err_out2;
3050				}
3051				ksmbd_debug(SMB, "get posix context\n");
3052
3053				posix_mode = le32_to_cpu(posix->Mode);
3054				posix_ctxt = 1;
3055			}
3056		}
3057	}
3058
3059	if (ksmbd_override_fsids(work)) {
3060		rc = -ENOMEM;
3061		goto err_out2;
3062	}
3063
3064	rc = ksmbd_vfs_kern_path_locked(work, name, LOOKUP_NO_SYMLINKS,
3065					&parent_path, &path, 1);
3066	if (!rc) {
3067		file_present = true;
3068
3069		if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
3070			/*
3071			 * If file exists with under flags, return access
3072			 * denied error.
3073			 */
3074			if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
3075			    req->CreateDisposition == FILE_OPEN_IF_LE) {
3076				rc = -EACCES;
3077				goto err_out;
3078			}
3079
3080			if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3081				ksmbd_debug(SMB,
3082					    "User does not have write permission\n");
3083				rc = -EACCES;
3084				goto err_out;
3085			}
3086		} else if (d_is_symlink(path.dentry)) {
3087			rc = -EACCES;
3088			goto err_out;
3089		}
3090
3091		file_present = true;
3092		idmap = mnt_idmap(path.mnt);
3093	} else {
3094		if (rc != -ENOENT)
3095			goto err_out;
3096		ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
3097			    name, rc);
3098		rc = 0;
3099	}
3100
3101	if (stream_name) {
3102		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3103			if (s_type == DATA_STREAM) {
3104				rc = -EIO;
3105				rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3106			}
3107		} else {
3108			if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
3109			    s_type == DATA_STREAM) {
3110				rc = -EIO;
3111				rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3112			}
3113		}
3114
3115		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
3116		    req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
3117			rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3118			rc = -EIO;
3119		}
3120
3121		if (rc < 0)
3122			goto err_out;
3123	}
3124
3125	if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
3126	    S_ISDIR(d_inode(path.dentry)->i_mode) &&
3127	    !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3128		ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
3129			    name, req->CreateOptions);
3130		rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3131		rc = -EIO;
3132		goto err_out;
3133	}
3134
3135	if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
3136	    !(req->CreateDisposition == FILE_CREATE_LE) &&
3137	    !S_ISDIR(d_inode(path.dentry)->i_mode)) {
3138		rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3139		rc = -EIO;
3140		goto err_out;
3141	}
3142
3143	if (!stream_name && file_present &&
3144	    req->CreateDisposition == FILE_CREATE_LE) {
3145		rc = -EEXIST;
3146		goto err_out;
3147	}
3148
3149	daccess = smb_map_generic_desired_access(req->DesiredAccess);
3150
3151	if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3152		rc = smb_check_perm_dacl(conn, &path, &daccess,
3153					 sess->user->uid);
3154		if (rc)
3155			goto err_out;
3156	}
3157
3158	if (daccess & FILE_MAXIMAL_ACCESS_LE) {
3159		if (!file_present) {
3160			daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
3161		} else {
3162			ksmbd_vfs_query_maximal_access(idmap,
3163							    path.dentry,
3164							    &daccess);
3165			already_permitted = true;
3166		}
3167		maximal_access = daccess;
3168	}
3169
3170	open_flags = smb2_create_open_flags(file_present, daccess,
3171					    req->CreateDisposition,
3172					    &may_flags);
3173
3174	if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3175		if (open_flags & (O_CREAT | O_TRUNC)) {
3176			ksmbd_debug(SMB,
3177				    "User does not have write permission\n");
3178			rc = -EACCES;
3179			goto err_out;
3180		}
3181	}
3182
3183	/*create file if not present */
3184	if (!file_present) {
3185		rc = smb2_creat(work, &parent_path, &path, name, open_flags,
3186				posix_mode,
3187				req->CreateOptions & FILE_DIRECTORY_FILE_LE);
3188		if (rc) {
3189			if (rc == -ENOENT) {
3190				rc = -EIO;
3191				rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
3192			}
3193			goto err_out;
3194		}
3195
3196		created = true;
3197		idmap = mnt_idmap(path.mnt);
3198		if (ea_buf) {
3199			if (le32_to_cpu(ea_buf->ccontext.DataLength) <
3200			    sizeof(struct smb2_ea_info)) {
3201				rc = -EINVAL;
3202				goto err_out;
3203			}
3204
3205			rc = smb2_set_ea(&ea_buf->ea,
3206					 le32_to_cpu(ea_buf->ccontext.DataLength),
3207					 &path, false);
3208			if (rc == -EOPNOTSUPP)
3209				rc = 0;
3210			else if (rc)
3211				goto err_out;
3212		}
3213	} else if (!already_permitted) {
3214		/* FILE_READ_ATTRIBUTE is allowed without inode_permission,
3215		 * because execute(search) permission on a parent directory,
3216		 * is already granted.
3217		 */
3218		if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
3219			rc = inode_permission(idmap,
3220					      d_inode(path.dentry),
3221					      may_flags);
3222			if (rc)
3223				goto err_out;
3224
3225			if ((daccess & FILE_DELETE_LE) ||
3226			    (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3227				rc = inode_permission(idmap,
3228						      d_inode(path.dentry->d_parent),
3229						      MAY_EXEC | MAY_WRITE);
3230				if (rc)
3231					goto err_out;
3232			}
3233		}
3234	}
3235
3236	rc = ksmbd_query_inode_status(path.dentry->d_parent);
3237	if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
3238		rc = -EBUSY;
3239		goto err_out;
3240	}
3241
3242	rc = 0;
3243	filp = dentry_open(&path, open_flags, current_cred());
3244	if (IS_ERR(filp)) {
3245		rc = PTR_ERR(filp);
3246		pr_err("dentry open for dir failed, rc %d\n", rc);
3247		goto err_out;
3248	}
3249
3250	if (file_present) {
3251		if (!(open_flags & O_TRUNC))
3252			file_info = FILE_OPENED;
3253		else
3254			file_info = FILE_OVERWRITTEN;
3255
3256		if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
3257		    FILE_SUPERSEDE_LE)
3258			file_info = FILE_SUPERSEDED;
3259	} else if (open_flags & O_CREAT) {
3260		file_info = FILE_CREATED;
3261	}
3262
3263	ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
3264
3265	/* Obtain Volatile-ID */
3266	fp = ksmbd_open_fd(work, filp);
3267	if (IS_ERR(fp)) {
3268		fput(filp);
3269		rc = PTR_ERR(fp);
3270		fp = NULL;
3271		goto err_out;
3272	}
3273
3274	/* Get Persistent-ID */
3275	ksmbd_open_durable_fd(fp);
3276	if (!has_file_id(fp->persistent_id)) {
3277		rc = -ENOMEM;
3278		goto err_out;
3279	}
3280
3281	fp->cdoption = req->CreateDisposition;
3282	fp->daccess = daccess;
3283	fp->saccess = req->ShareAccess;
3284	fp->coption = req->CreateOptions;
3285
3286	/* Set default windows and posix acls if creating new file */
3287	if (created) {
3288		int posix_acl_rc;
3289		struct inode *inode = d_inode(path.dentry);
3290
3291		posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
3292							   &path,
3293							   d_inode(path.dentry->d_parent));
3294		if (posix_acl_rc)
3295			ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3296
3297		if (test_share_config_flag(work->tcon->share_conf,
3298					   KSMBD_SHARE_FLAG_ACL_XATTR)) {
3299			rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3300					      sess->user->gid);
3301		}
3302
3303		if (rc) {
3304			rc = smb2_create_sd_buffer(work, req, &path);
3305			if (rc) {
3306				if (posix_acl_rc)
3307					ksmbd_vfs_set_init_posix_acl(idmap,
3308								     &path);
3309
3310				if (test_share_config_flag(work->tcon->share_conf,
3311							   KSMBD_SHARE_FLAG_ACL_XATTR)) {
3312					struct smb_fattr fattr;
3313					struct smb_ntsd *pntsd;
3314					int pntsd_size, ace_num = 0;
3315
3316					ksmbd_acls_fattr(&fattr, idmap, inode);
3317					if (fattr.cf_acls)
3318						ace_num = fattr.cf_acls->a_count;
3319					if (fattr.cf_dacls)
3320						ace_num += fattr.cf_dacls->a_count;
3321
3322					pntsd = kmalloc(sizeof(struct smb_ntsd) +
3323							sizeof(struct smb_sid) * 3 +
3324							sizeof(struct smb_acl) +
3325							sizeof(struct smb_ace) * ace_num * 2,
3326							GFP_KERNEL);
3327					if (!pntsd) {
3328						posix_acl_release(fattr.cf_acls);
3329						posix_acl_release(fattr.cf_dacls);
3330						goto err_out;
3331					}
3332
3333					rc = build_sec_desc(idmap,
3334							    pntsd, NULL, 0,
3335							    OWNER_SECINFO |
3336							    GROUP_SECINFO |
3337							    DACL_SECINFO,
3338							    &pntsd_size, &fattr);
3339					posix_acl_release(fattr.cf_acls);
3340					posix_acl_release(fattr.cf_dacls);
3341					if (rc) {
3342						kfree(pntsd);
3343						goto err_out;
3344					}
3345
3346					rc = ksmbd_vfs_set_sd_xattr(conn,
3347								    idmap,
3348								    &path,
3349								    pntsd,
3350								    pntsd_size,
3351								    false);
3352					kfree(pntsd);
3353					if (rc)
3354						pr_err("failed to store ntacl in xattr : %d\n",
3355						       rc);
3356				}
3357			}
3358		}
3359		rc = 0;
3360	}
3361
3362	if (stream_name) {
3363		rc = smb2_set_stream_name_xattr(&path,
3364						fp,
3365						stream_name,
3366						s_type);
3367		if (rc)
3368			goto err_out;
3369		file_info = FILE_CREATED;
3370	}
3371
3372	fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3373			FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3374
3375	/* fp should be searchable through ksmbd_inode.m_fp_list
3376	 * after daccess, saccess, attrib_only, and stream are
3377	 * initialized.
3378	 */
3379	write_lock(&fp->f_ci->m_lock);
3380	list_add(&fp->node, &fp->f_ci->m_fp_list);
3381	write_unlock(&fp->f_ci->m_lock);
3382
3383	/* Check delete pending among previous fp before oplock break */
3384	if (ksmbd_inode_pending_delete(fp)) {
3385		rc = -EBUSY;
3386		goto err_out;
3387	}
3388
3389	if (file_present || created)
3390		ksmbd_vfs_kern_path_unlock(&parent_path, &path);
3391
3392	if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3393	    !fp->attrib_only && !stream_name) {
3394		smb_break_all_oplock(work, fp);
3395		need_truncate = 1;
3396	}
3397
3398	share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3399	if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3400	    (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3401	     !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3402		if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3403			rc = share_ret;
3404			goto err_out1;
3405		}
3406	} else {
3407		if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3408			if (S_ISDIR(file_inode(filp)->i_mode)) {
3409				lc->req_state &= ~SMB2_LEASE_WRITE_CACHING_LE;
3410				lc->is_dir = true;
3411			}
3412
3413			/*
3414			 * Compare parent lease using parent key. If there is no
3415			 * a lease that has same parent key, Send lease break
3416			 * notification.
3417			 */
3418			smb_send_parent_lease_break_noti(fp, lc);
3419
3420			req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3421			ksmbd_debug(SMB,
3422				    "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3423				    name, req_op_level, lc->req_state);
3424			rc = find_same_lease_key(sess, fp->f_ci, lc);
3425			if (rc)
3426				goto err_out1;
3427		} else if (open_flags == O_RDONLY &&
3428			   (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3429			    req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3430			req_op_level = SMB2_OPLOCK_LEVEL_II;
3431
3432		rc = smb_grant_oplock(work, req_op_level,
3433				      fp->persistent_id, fp,
3434				      le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3435				      lc, share_ret);
3436		if (rc < 0)
3437			goto err_out1;
3438	}
3439
3440	if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3441		ksmbd_fd_set_delete_on_close(fp, file_info);
3442
3443	if (need_truncate) {
3444		rc = smb2_create_truncate(&fp->filp->f_path);
3445		if (rc)
3446			goto err_out1;
3447	}
3448
3449	if (req->CreateContextsOffset) {
3450		struct create_alloc_size_req *az_req;
3451
3452		az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3453					SMB2_CREATE_ALLOCATION_SIZE, 4);
3454		if (IS_ERR(az_req)) {
3455			rc = PTR_ERR(az_req);
3456			goto err_out1;
3457		} else if (az_req) {
3458			loff_t alloc_size;
3459			int err;
3460
3461			if (le16_to_cpu(az_req->ccontext.DataOffset) +
3462			    le32_to_cpu(az_req->ccontext.DataLength) <
3463			    sizeof(struct create_alloc_size_req)) {
3464				rc = -EINVAL;
3465				goto err_out1;
3466			}
3467			alloc_size = le64_to_cpu(az_req->AllocationSize);
3468			ksmbd_debug(SMB,
3469				    "request smb2 create allocate size : %llu\n",
3470				    alloc_size);
3471			smb_break_all_levII_oplock(work, fp, 1);
3472			err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3473					    alloc_size);
3474			if (err < 0)
3475				ksmbd_debug(SMB,
3476					    "vfs_fallocate is failed : %d\n",
3477					    err);
3478		}
3479
3480		context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3481		if (IS_ERR(context)) {
3482			rc = PTR_ERR(context);
3483			goto err_out1;
3484		} else if (context) {
3485			ksmbd_debug(SMB, "get query on disk id context\n");
3486			query_disk_id = 1;
3487		}
3488	}
3489
3490	rc = ksmbd_vfs_getattr(&path, &stat);
3491	if (rc)
3492		goto err_out1;
3493
3494	if (stat.result_mask & STATX_BTIME)
3495		fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3496	else
3497		fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3498	if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3499		fp->f_ci->m_fattr =
3500			cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3501
3502	if (!created)
3503		smb2_update_xattrs(tcon, &path, fp);
3504	else
3505		smb2_new_xattrs(tcon, &path, fp);
3506
3507	memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3508
3509	if (dh_info.type == DURABLE_REQ_V2 || dh_info.type == DURABLE_REQ) {
3510		if (dh_info.type == DURABLE_REQ_V2 && dh_info.persistent &&
3511		    test_share_config_flag(work->tcon->share_conf,
3512					   KSMBD_SHARE_FLAG_CONTINUOUS_AVAILABILITY))
3513			fp->is_persistent = true;
3514		else
3515			fp->is_durable = true;
3516
3517		if (dh_info.type == DURABLE_REQ_V2) {
3518			memcpy(fp->create_guid, dh_info.CreateGuid,
3519					SMB2_CREATE_GUID_SIZE);
3520			if (dh_info.timeout)
3521				fp->durable_timeout = min(dh_info.timeout,
3522						300000);
3523			else
3524				fp->durable_timeout = 60;
3525		}
3526	}
3527
3528reconnected_fp:
3529	rsp->StructureSize = cpu_to_le16(89);
3530	rcu_read_lock();
3531	opinfo = rcu_dereference(fp->f_opinfo);
3532	rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3533	rcu_read_unlock();
3534	rsp->Flags = 0;
3535	rsp->CreateAction = cpu_to_le32(file_info);
3536	rsp->CreationTime = cpu_to_le64(fp->create_time);
3537	time = ksmbd_UnixTimeToNT(stat.atime);
3538	rsp->LastAccessTime = cpu_to_le64(time);
3539	time = ksmbd_UnixTimeToNT(stat.mtime);
3540	rsp->LastWriteTime = cpu_to_le64(time);
3541	time = ksmbd_UnixTimeToNT(stat.ctime);
3542	rsp->ChangeTime = cpu_to_le64(time);
3543	rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3544		cpu_to_le64(stat.blocks << 9);
3545	rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3546	rsp->FileAttributes = fp->f_ci->m_fattr;
3547
3548	rsp->Reserved2 = 0;
3549
3550	rsp->PersistentFileId = fp->persistent_id;
3551	rsp->VolatileFileId = fp->volatile_id;
3552
3553	rsp->CreateContextsOffset = 0;
3554	rsp->CreateContextsLength = 0;
3555	iov_len = offsetof(struct smb2_create_rsp, Buffer);
3556
3557	/* If lease is request send lease context response */
3558	if (opinfo && opinfo->is_lease) {
3559		struct create_context *lease_ccontext;
3560
3561		ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3562			    name, opinfo->o_lease->state);
3563		rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3564
3565		lease_ccontext = (struct create_context *)rsp->Buffer;
3566		contxt_cnt++;
3567		create_lease_buf(rsp->Buffer, opinfo->o_lease);
3568		le32_add_cpu(&rsp->CreateContextsLength,
3569			     conn->vals->create_lease_size);
3570		iov_len += conn->vals->create_lease_size;
3571		next_ptr = &lease_ccontext->Next;
3572		next_off = conn->vals->create_lease_size;
3573	}
3574
3575	if (maximal_access_ctxt) {
3576		struct create_context *mxac_ccontext;
3577
3578		if (maximal_access == 0)
3579			ksmbd_vfs_query_maximal_access(idmap,
3580						       path.dentry,
3581						       &maximal_access);
3582		mxac_ccontext = (struct create_context *)(rsp->Buffer +
3583				le32_to_cpu(rsp->CreateContextsLength));
3584		contxt_cnt++;
3585		create_mxac_rsp_buf(rsp->Buffer +
3586				le32_to_cpu(rsp->CreateContextsLength),
3587				le32_to_cpu(maximal_access));
3588		le32_add_cpu(&rsp->CreateContextsLength,
3589			     conn->vals->create_mxac_size);
3590		iov_len += conn->vals->create_mxac_size;
3591		if (next_ptr)
3592			*next_ptr = cpu_to_le32(next_off);
3593		next_ptr = &mxac_ccontext->Next;
3594		next_off = conn->vals->create_mxac_size;
3595	}
3596
3597	if (query_disk_id) {
3598		struct create_context *disk_id_ccontext;
3599
3600		disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3601				le32_to_cpu(rsp->CreateContextsLength));
3602		contxt_cnt++;
3603		create_disk_id_rsp_buf(rsp->Buffer +
3604				le32_to_cpu(rsp->CreateContextsLength),
3605				stat.ino, tcon->id);
3606		le32_add_cpu(&rsp->CreateContextsLength,
3607			     conn->vals->create_disk_id_size);
3608		iov_len += conn->vals->create_disk_id_size;
3609		if (next_ptr)
3610			*next_ptr = cpu_to_le32(next_off);
3611		next_ptr = &disk_id_ccontext->Next;
3612		next_off = conn->vals->create_disk_id_size;
3613	}
3614
3615	if (dh_info.type == DURABLE_REQ || dh_info.type == DURABLE_REQ_V2) {
3616		struct create_context *durable_ccontext;
3617
3618		durable_ccontext = (struct create_context *)(rsp->Buffer +
3619				le32_to_cpu(rsp->CreateContextsLength));
3620		contxt_cnt++;
3621		if (dh_info.type == DURABLE_REQ) {
3622			create_durable_rsp_buf(rsp->Buffer +
3623					le32_to_cpu(rsp->CreateContextsLength));
3624			le32_add_cpu(&rsp->CreateContextsLength,
3625					conn->vals->create_durable_size);
3626			iov_len += conn->vals->create_durable_size;
3627		} else {
3628			create_durable_v2_rsp_buf(rsp->Buffer +
3629					le32_to_cpu(rsp->CreateContextsLength),
3630					fp);
3631			le32_add_cpu(&rsp->CreateContextsLength,
3632					conn->vals->create_durable_v2_size);
3633			iov_len += conn->vals->create_durable_v2_size;
3634		}
3635
3636		if (next_ptr)
3637			*next_ptr = cpu_to_le32(next_off);
3638		next_ptr = &durable_ccontext->Next;
3639		next_off = conn->vals->create_durable_size;
3640	}
3641
3642	if (posix_ctxt) {
3643		contxt_cnt++;
3644		create_posix_rsp_buf(rsp->Buffer +
3645				le32_to_cpu(rsp->CreateContextsLength),
3646				fp);
3647		le32_add_cpu(&rsp->CreateContextsLength,
3648			     conn->vals->create_posix_size);
3649		iov_len += conn->vals->create_posix_size;
3650		if (next_ptr)
3651			*next_ptr = cpu_to_le32(next_off);
3652	}
3653
3654	if (contxt_cnt > 0) {
3655		rsp->CreateContextsOffset =
3656			cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3657	}
3658
3659err_out:
3660	if (rc && (file_present || created))
3661		ksmbd_vfs_kern_path_unlock(&parent_path, &path);
3662
3663err_out1:
3664	ksmbd_revert_fsids(work);
3665
3666err_out2:
3667	if (!rc) {
3668		ksmbd_update_fstate(&work->sess->file_table, fp, FP_INITED);
3669		rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
3670	}
3671	if (rc) {
3672		if (rc == -EINVAL)
3673			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3674		else if (rc == -EOPNOTSUPP)
3675			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3676		else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3677			rsp->hdr.Status = STATUS_ACCESS_DENIED;
3678		else if (rc == -ENOENT)
3679			rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3680		else if (rc == -EPERM)
3681			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3682		else if (rc == -EBUSY)
3683			rsp->hdr.Status = STATUS_DELETE_PENDING;
3684		else if (rc == -EBADF)
3685			rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3686		else if (rc == -ENOEXEC)
3687			rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3688		else if (rc == -ENXIO)
3689			rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3690		else if (rc == -EEXIST)
3691			rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3692		else if (rc == -EMFILE)
3693			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3694		if (!rsp->hdr.Status)
3695			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3696
3697		if (fp)
3698			ksmbd_fd_put(work, fp);
3699		smb2_set_err_rsp(work);
3700		ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3701	}
3702
3703	kfree(name);
3704	kfree(lc);
3705
3706	return 0;
3707}
3708
3709static int readdir_info_level_struct_sz(int info_level)
3710{
3711	switch (info_level) {
3712	case FILE_FULL_DIRECTORY_INFORMATION:
3713		return sizeof(struct file_full_directory_info);
3714	case FILE_BOTH_DIRECTORY_INFORMATION:
3715		return sizeof(struct file_both_directory_info);
3716	case FILE_DIRECTORY_INFORMATION:
3717		return sizeof(struct file_directory_info);
3718	case FILE_NAMES_INFORMATION:
3719		return sizeof(struct file_names_info);
3720	case FILEID_FULL_DIRECTORY_INFORMATION:
3721		return sizeof(struct file_id_full_dir_info);
3722	case FILEID_BOTH_DIRECTORY_INFORMATION:
3723		return sizeof(struct file_id_both_directory_info);
3724	case SMB_FIND_FILE_POSIX_INFO:
3725		return sizeof(struct smb2_posix_info);
3726	default:
3727		return -EOPNOTSUPP;
3728	}
3729}
3730
3731static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3732{
3733	switch (info_level) {
3734	case FILE_FULL_DIRECTORY_INFORMATION:
3735	{
3736		struct file_full_directory_info *ffdinfo;
3737
3738		ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3739		d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3740		d_info->name = ffdinfo->FileName;
3741		d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3742		return 0;
3743	}
3744	case FILE_BOTH_DIRECTORY_INFORMATION:
3745	{
3746		struct file_both_directory_info *fbdinfo;
3747
3748		fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3749		d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3750		d_info->name = fbdinfo->FileName;
3751		d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3752		return 0;
3753	}
3754	case FILE_DIRECTORY_INFORMATION:
3755	{
3756		struct file_directory_info *fdinfo;
3757
3758		fdinfo = (struct file_directory_info *)d_info->rptr;
3759		d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3760		d_info->name = fdinfo->FileName;
3761		d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3762		return 0;
3763	}
3764	case FILE_NAMES_INFORMATION:
3765	{
3766		struct file_names_info *fninfo;
3767
3768		fninfo = (struct file_names_info *)d_info->rptr;
3769		d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3770		d_info->name = fninfo->FileName;
3771		d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3772		return 0;
3773	}
3774	case FILEID_FULL_DIRECTORY_INFORMATION:
3775	{
3776		struct file_id_full_dir_info *dinfo;
3777
3778		dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3779		d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3780		d_info->name = dinfo->FileName;
3781		d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3782		return 0;
3783	}
3784	case FILEID_BOTH_DIRECTORY_INFORMATION:
3785	{
3786		struct file_id_both_directory_info *fibdinfo;
3787
3788		fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3789		d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3790		d_info->name = fibdinfo->FileName;
3791		d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3792		return 0;
3793	}
3794	case SMB_FIND_FILE_POSIX_INFO:
3795	{
3796		struct smb2_posix_info *posix_info;
3797
3798		posix_info = (struct smb2_posix_info *)d_info->rptr;
3799		d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3800		d_info->name = posix_info->name;
3801		d_info->name_len = le32_to_cpu(posix_info->name_len);
3802		return 0;
3803	}
3804	default:
3805		return -EINVAL;
3806	}
3807}
3808
3809/**
3810 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3811 * buffer
3812 * @conn:	connection instance
3813 * @info_level:	smb information level
3814 * @d_info:	structure included variables for query dir
3815 * @ksmbd_kstat:	ksmbd wrapper of dirent stat information
3816 *
3817 * if directory has many entries, find first can't read it fully.
3818 * find next might be called multiple times to read remaining dir entries
3819 *
3820 * Return:	0 on success, otherwise error
3821 */
3822static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3823				       struct ksmbd_dir_info *d_info,
3824				       struct ksmbd_kstat *ksmbd_kstat)
3825{
3826	int next_entry_offset = 0;
3827	char *conv_name;
3828	int conv_len;
3829	void *kstat;
3830	int struct_sz, rc = 0;
3831
3832	conv_name = ksmbd_convert_dir_info_name(d_info,
3833						conn->local_nls,
3834						&conv_len);
3835	if (!conv_name)
3836		return -ENOMEM;
3837
3838	/* Somehow the name has only terminating NULL bytes */
3839	if (conv_len < 0) {
3840		rc = -EINVAL;
3841		goto free_conv_name;
3842	}
3843
3844	struct_sz = readdir_info_level_struct_sz(info_level) + conv_len;
3845	next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3846	d_info->last_entry_off_align = next_entry_offset - struct_sz;
3847
3848	if (next_entry_offset > d_info->out_buf_len) {
3849		d_info->out_buf_len = 0;
3850		rc = -ENOSPC;
3851		goto free_conv_name;
3852	}
3853
3854	kstat = d_info->wptr;
3855	if (info_level != FILE_NAMES_INFORMATION)
3856		kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3857
3858	switch (info_level) {
3859	case FILE_FULL_DIRECTORY_INFORMATION:
3860	{
3861		struct file_full_directory_info *ffdinfo;
3862
3863		ffdinfo = (struct file_full_directory_info *)kstat;
3864		ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3865		ffdinfo->EaSize =
3866			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3867		if (ffdinfo->EaSize)
3868			ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3869		if (d_info->hide_dot_file && d_info->name[0] == '.')
3870			ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3871		memcpy(ffdinfo->FileName, conv_name, conv_len);
3872		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3873		break;
3874	}
3875	case FILE_BOTH_DIRECTORY_INFORMATION:
3876	{
3877		struct file_both_directory_info *fbdinfo;
3878
3879		fbdinfo = (struct file_both_directory_info *)kstat;
3880		fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3881		fbdinfo->EaSize =
3882			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3883		if (fbdinfo->EaSize)
3884			fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3885		fbdinfo->ShortNameLength = 0;
3886		fbdinfo->Reserved = 0;
3887		if (d_info->hide_dot_file && d_info->name[0] == '.')
3888			fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3889		memcpy(fbdinfo->FileName, conv_name, conv_len);
3890		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3891		break;
3892	}
3893	case FILE_DIRECTORY_INFORMATION:
3894	{
3895		struct file_directory_info *fdinfo;
3896
3897		fdinfo = (struct file_directory_info *)kstat;
3898		fdinfo->FileNameLength = cpu_to_le32(conv_len);
3899		if (d_info->hide_dot_file && d_info->name[0] == '.')
3900			fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3901		memcpy(fdinfo->FileName, conv_name, conv_len);
3902		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3903		break;
3904	}
3905	case FILE_NAMES_INFORMATION:
3906	{
3907		struct file_names_info *fninfo;
3908
3909		fninfo = (struct file_names_info *)kstat;
3910		fninfo->FileNameLength = cpu_to_le32(conv_len);
3911		memcpy(fninfo->FileName, conv_name, conv_len);
3912		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3913		break;
3914	}
3915	case FILEID_FULL_DIRECTORY_INFORMATION:
3916	{
3917		struct file_id_full_dir_info *dinfo;
3918
3919		dinfo = (struct file_id_full_dir_info *)kstat;
3920		dinfo->FileNameLength = cpu_to_le32(conv_len);
3921		dinfo->EaSize =
3922			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3923		if (dinfo->EaSize)
3924			dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3925		dinfo->Reserved = 0;
3926		dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3927		if (d_info->hide_dot_file && d_info->name[0] == '.')
3928			dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3929		memcpy(dinfo->FileName, conv_name, conv_len);
3930		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3931		break;
3932	}
3933	case FILEID_BOTH_DIRECTORY_INFORMATION:
3934	{
3935		struct file_id_both_directory_info *fibdinfo;
3936
3937		fibdinfo = (struct file_id_both_directory_info *)kstat;
3938		fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3939		fibdinfo->EaSize =
3940			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3941		if (fibdinfo->EaSize)
3942			fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3943		fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3944		fibdinfo->ShortNameLength = 0;
3945		fibdinfo->Reserved = 0;
3946		fibdinfo->Reserved2 = cpu_to_le16(0);
3947		if (d_info->hide_dot_file && d_info->name[0] == '.')
3948			fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3949		memcpy(fibdinfo->FileName, conv_name, conv_len);
3950		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3951		break;
3952	}
3953	case SMB_FIND_FILE_POSIX_INFO:
3954	{
3955		struct smb2_posix_info *posix_info;
3956		u64 time;
3957
3958		posix_info = (struct smb2_posix_info *)kstat;
3959		posix_info->Ignored = 0;
3960		posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3961		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3962		posix_info->ChangeTime = cpu_to_le64(time);
3963		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3964		posix_info->LastAccessTime = cpu_to_le64(time);
3965		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3966		posix_info->LastWriteTime = cpu_to_le64(time);
3967		posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3968		posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3969		posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3970		posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3971		posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
3972		posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3973		posix_info->DosAttributes =
3974			S_ISDIR(ksmbd_kstat->kstat->mode) ?
3975				FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3976		if (d_info->hide_dot_file && d_info->name[0] == '.')
3977			posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3978		/*
3979		 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
3980		 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
3981		 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
3982		 */
3983		id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3984			  SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3985		id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3986			  SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
3987		memcpy(posix_info->name, conv_name, conv_len);
3988		posix_info->name_len = cpu_to_le32(conv_len);
3989		posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3990		break;
3991	}
3992
3993	} /* switch (info_level) */
3994
3995	d_info->last_entry_offset = d_info->data_count;
3996	d_info->data_count += next_entry_offset;
3997	d_info->out_buf_len -= next_entry_offset;
3998	d_info->wptr += next_entry_offset;
3999
4000	ksmbd_debug(SMB,
4001		    "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
4002		    info_level, d_info->out_buf_len,
4003		    next_entry_offset, d_info->data_count);
4004
4005free_conv_name:
4006	kfree(conv_name);
4007	return rc;
4008}
4009
4010struct smb2_query_dir_private {
4011	struct ksmbd_work	*work;
4012	char			*search_pattern;
4013	struct ksmbd_file	*dir_fp;
4014
4015	struct ksmbd_dir_info	*d_info;
4016	int			info_level;
4017};
4018
4019static void lock_dir(struct ksmbd_file *dir_fp)
4020{
4021	struct dentry *dir = dir_fp->filp->f_path.dentry;
4022
4023	inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
4024}
4025
4026static void unlock_dir(struct ksmbd_file *dir_fp)
4027{
4028	struct dentry *dir = dir_fp->filp->f_path.dentry;
4029
4030	inode_unlock(d_inode(dir));
4031}
4032
4033static int process_query_dir_entries(struct smb2_query_dir_private *priv)
4034{
4035	struct mnt_idmap	*idmap = file_mnt_idmap(priv->dir_fp->filp);
4036	struct kstat		kstat;
4037	struct ksmbd_kstat	ksmbd_kstat;
4038	int			rc;
4039	int			i;
4040
4041	for (i = 0; i < priv->d_info->num_entry; i++) {
4042		struct dentry *dent;
4043
4044		if (dentry_name(priv->d_info, priv->info_level))
4045			return -EINVAL;
4046
4047		lock_dir(priv->dir_fp);
4048		dent = lookup_one(idmap, priv->d_info->name,
4049				  priv->dir_fp->filp->f_path.dentry,
4050				  priv->d_info->name_len);
4051		unlock_dir(priv->dir_fp);
4052
4053		if (IS_ERR(dent)) {
4054			ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
4055				    priv->d_info->name,
4056				    PTR_ERR(dent));
4057			continue;
4058		}
4059		if (unlikely(d_is_negative(dent))) {
4060			dput(dent);
4061			ksmbd_debug(SMB, "Negative dentry `%s'\n",
4062				    priv->d_info->name);
4063			continue;
4064		}
4065
4066		ksmbd_kstat.kstat = &kstat;
4067		if (priv->info_level != FILE_NAMES_INFORMATION) {
4068			rc = ksmbd_vfs_fill_dentry_attrs(priv->work,
4069							 idmap,
4070							 dent,
4071							 &ksmbd_kstat);
4072			if (rc) {
4073				dput(dent);
4074				continue;
4075			}
4076		}
4077
4078		rc = smb2_populate_readdir_entry(priv->work->conn,
4079						 priv->info_level,
4080						 priv->d_info,
4081						 &ksmbd_kstat);
4082		dput(dent);
4083		if (rc)
4084			return rc;
4085	}
4086	return 0;
4087}
4088
4089static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
4090				   int info_level)
4091{
4092	int struct_sz;
4093	int conv_len;
4094	int next_entry_offset;
4095
4096	struct_sz = readdir_info_level_struct_sz(info_level);
4097	if (struct_sz == -EOPNOTSUPP)
4098		return -EOPNOTSUPP;
4099
4100	conv_len = (d_info->name_len + 1) * 2;
4101	next_entry_offset = ALIGN(struct_sz + conv_len,
4102				  KSMBD_DIR_INFO_ALIGNMENT);
4103
4104	if (next_entry_offset > d_info->out_buf_len) {
4105		d_info->out_buf_len = 0;
4106		return -ENOSPC;
4107	}
4108
4109	switch (info_level) {
4110	case FILE_FULL_DIRECTORY_INFORMATION:
4111	{
4112		struct file_full_directory_info *ffdinfo;
4113
4114		ffdinfo = (struct file_full_directory_info *)d_info->wptr;
4115		memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
4116		ffdinfo->FileName[d_info->name_len] = 0x00;
4117		ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4118		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4119		break;
4120	}
4121	case FILE_BOTH_DIRECTORY_INFORMATION:
4122	{
4123		struct file_both_directory_info *fbdinfo;
4124
4125		fbdinfo = (struct file_both_directory_info *)d_info->wptr;
4126		memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
4127		fbdinfo->FileName[d_info->name_len] = 0x00;
4128		fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4129		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4130		break;
4131	}
4132	case FILE_DIRECTORY_INFORMATION:
4133	{
4134		struct file_directory_info *fdinfo;
4135
4136		fdinfo = (struct file_directory_info *)d_info->wptr;
4137		memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
4138		fdinfo->FileName[d_info->name_len] = 0x00;
4139		fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4140		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4141		break;
4142	}
4143	case FILE_NAMES_INFORMATION:
4144	{
4145		struct file_names_info *fninfo;
4146
4147		fninfo = (struct file_names_info *)d_info->wptr;
4148		memcpy(fninfo->FileName, d_info->name, d_info->name_len);
4149		fninfo->FileName[d_info->name_len] = 0x00;
4150		fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
4151		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4152		break;
4153	}
4154	case FILEID_FULL_DIRECTORY_INFORMATION:
4155	{
4156		struct file_id_full_dir_info *dinfo;
4157
4158		dinfo = (struct file_id_full_dir_info *)d_info->wptr;
4159		memcpy(dinfo->FileName, d_info->name, d_info->name_len);
4160		dinfo->FileName[d_info->name_len] = 0x00;
4161		dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4162		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4163		break;
4164	}
4165	case FILEID_BOTH_DIRECTORY_INFORMATION:
4166	{
4167		struct file_id_both_directory_info *fibdinfo;
4168
4169		fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
4170		memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
4171		fibdinfo->FileName[d_info->name_len] = 0x00;
4172		fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4173		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4174		break;
4175	}
4176	case SMB_FIND_FILE_POSIX_INFO:
4177	{
4178		struct smb2_posix_info *posix_info;
4179
4180		posix_info = (struct smb2_posix_info *)d_info->wptr;
4181		memcpy(posix_info->name, d_info->name, d_info->name_len);
4182		posix_info->name[d_info->name_len] = 0x00;
4183		posix_info->name_len = cpu_to_le32(d_info->name_len);
4184		posix_info->NextEntryOffset =
4185			cpu_to_le32(next_entry_offset);
4186		break;
4187	}
4188	} /* switch (info_level) */
4189
4190	d_info->num_entry++;
4191	d_info->out_buf_len -= next_entry_offset;
4192	d_info->wptr += next_entry_offset;
4193	return 0;
4194}
4195
4196static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
4197		       loff_t offset, u64 ino, unsigned int d_type)
4198{
4199	struct ksmbd_readdir_data	*buf;
4200	struct smb2_query_dir_private	*priv;
4201	struct ksmbd_dir_info		*d_info;
4202	int				rc;
4203
4204	buf	= container_of(ctx, struct ksmbd_readdir_data, ctx);
4205	priv	= buf->private;
4206	d_info	= priv->d_info;
4207
4208	/* dot and dotdot entries are already reserved */
4209	if (!strcmp(".", name) || !strcmp("..", name))
4210		return true;
4211	if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
4212		return true;
4213	if (!match_pattern(name, namlen, priv->search_pattern))
4214		return true;
4215
4216	d_info->name		= name;
4217	d_info->name_len	= namlen;
4218	rc = reserve_populate_dentry(d_info, priv->info_level);
4219	if (rc)
4220		return false;
4221	if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
4222		d_info->out_buf_len = 0;
4223	return true;
4224}
4225
4226static int verify_info_level(int info_level)
4227{
4228	switch (info_level) {
4229	case FILE_FULL_DIRECTORY_INFORMATION:
4230	case FILE_BOTH_DIRECTORY_INFORMATION:
4231	case FILE_DIRECTORY_INFORMATION:
4232	case FILE_NAMES_INFORMATION:
4233	case FILEID_FULL_DIRECTORY_INFORMATION:
4234	case FILEID_BOTH_DIRECTORY_INFORMATION:
4235	case SMB_FIND_FILE_POSIX_INFO:
4236		break;
4237	default:
4238		return -EOPNOTSUPP;
4239	}
4240
4241	return 0;
4242}
4243
4244static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
4245{
4246	int free_len;
4247
4248	free_len = (int)(work->response_sz -
4249		(get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
4250	return free_len;
4251}
4252
4253static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
4254				     unsigned short hdr2_len,
4255				     unsigned int out_buf_len)
4256{
4257	int free_len;
4258
4259	if (out_buf_len > work->conn->vals->max_trans_size)
4260		return -EINVAL;
4261
4262	free_len = smb2_resp_buf_len(work, hdr2_len);
4263	if (free_len < 0)
4264		return -EINVAL;
4265
4266	return min_t(int, out_buf_len, free_len);
4267}
4268
4269int smb2_query_dir(struct ksmbd_work *work)
4270{
4271	struct ksmbd_conn *conn = work->conn;
4272	struct smb2_query_directory_req *req;
4273	struct smb2_query_directory_rsp *rsp;
4274	struct ksmbd_share_config *share = work->tcon->share_conf;
4275	struct ksmbd_file *dir_fp = NULL;
4276	struct ksmbd_dir_info d_info;
4277	int rc = 0;
4278	char *srch_ptr = NULL;
4279	unsigned char srch_flag;
4280	int buffer_sz;
4281	struct smb2_query_dir_private query_dir_private = {NULL, };
4282
4283	WORK_BUFFERS(work, req, rsp);
4284
4285	if (ksmbd_override_fsids(work)) {
4286		rsp->hdr.Status = STATUS_NO_MEMORY;
4287		smb2_set_err_rsp(work);
4288		return -ENOMEM;
4289	}
4290
4291	rc = verify_info_level(req->FileInformationClass);
4292	if (rc) {
4293		rc = -EFAULT;
4294		goto err_out2;
4295	}
4296
4297	dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
4298	if (!dir_fp) {
4299		rc = -EBADF;
4300		goto err_out2;
4301	}
4302
4303	if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
4304	    inode_permission(file_mnt_idmap(dir_fp->filp),
4305			     file_inode(dir_fp->filp),
4306			     MAY_READ | MAY_EXEC)) {
4307		pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
4308		rc = -EACCES;
4309		goto err_out2;
4310	}
4311
4312	if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
4313		pr_err("can't do query dir for a file\n");
4314		rc = -EINVAL;
4315		goto err_out2;
4316	}
4317
4318	srch_flag = req->Flags;
4319	srch_ptr = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->FileNameOffset),
4320					  le16_to_cpu(req->FileNameLength), 1,
4321					  conn->local_nls);
4322	if (IS_ERR(srch_ptr)) {
4323		ksmbd_debug(SMB, "Search Pattern not found\n");
4324		rc = -EINVAL;
4325		goto err_out2;
4326	} else {
4327		ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
4328	}
4329
4330	if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
4331		ksmbd_debug(SMB, "Restart directory scan\n");
4332		generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
4333	}
4334
4335	memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
4336	d_info.wptr = (char *)rsp->Buffer;
4337	d_info.rptr = (char *)rsp->Buffer;
4338	d_info.out_buf_len =
4339		smb2_calc_max_out_buf_len(work, 8,
4340					  le32_to_cpu(req->OutputBufferLength));
4341	if (d_info.out_buf_len < 0) {
4342		rc = -EINVAL;
4343		goto err_out;
4344	}
4345	d_info.flags = srch_flag;
4346
4347	/*
4348	 * reserve dot and dotdot entries in head of buffer
4349	 * in first response
4350	 */
4351	rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4352					       dir_fp, &d_info, srch_ptr,
4353					       smb2_populate_readdir_entry);
4354	if (rc == -ENOSPC)
4355		rc = 0;
4356	else if (rc)
4357		goto err_out;
4358
4359	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4360		d_info.hide_dot_file = true;
4361
4362	buffer_sz				= d_info.out_buf_len;
4363	d_info.rptr				= d_info.wptr;
4364	query_dir_private.work			= work;
4365	query_dir_private.search_pattern	= srch_ptr;
4366	query_dir_private.dir_fp		= dir_fp;
4367	query_dir_private.d_info		= &d_info;
4368	query_dir_private.info_level		= req->FileInformationClass;
4369	dir_fp->readdir_data.private		= &query_dir_private;
4370	set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4371
4372	rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4373	/*
4374	 * req->OutputBufferLength is too small to contain even one entry.
4375	 * In this case, it immediately returns OutputBufferLength 0 to client.
4376	 */
4377	if (!d_info.out_buf_len && !d_info.num_entry)
4378		goto no_buf_len;
4379	if (rc > 0 || rc == -ENOSPC)
4380		rc = 0;
4381	else if (rc)
4382		goto err_out;
4383
4384	d_info.wptr = d_info.rptr;
4385	d_info.out_buf_len = buffer_sz;
4386	rc = process_query_dir_entries(&query_dir_private);
4387	if (rc)
4388		goto err_out;
4389
4390	if (!d_info.data_count && d_info.out_buf_len >= 0) {
4391		if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4392			rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4393		} else {
4394			dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4395			rsp->hdr.Status = STATUS_NO_MORE_FILES;
4396		}
4397		rsp->StructureSize = cpu_to_le16(9);
4398		rsp->OutputBufferOffset = cpu_to_le16(0);
4399		rsp->OutputBufferLength = cpu_to_le32(0);
4400		rsp->Buffer[0] = 0;
4401		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4402				       sizeof(struct smb2_query_directory_rsp));
4403		if (rc)
4404			goto err_out;
4405	} else {
4406no_buf_len:
4407		((struct file_directory_info *)
4408		((char *)rsp->Buffer + d_info.last_entry_offset))
4409		->NextEntryOffset = 0;
4410		if (d_info.data_count >= d_info.last_entry_off_align)
4411			d_info.data_count -= d_info.last_entry_off_align;
4412
4413		rsp->StructureSize = cpu_to_le16(9);
4414		rsp->OutputBufferOffset = cpu_to_le16(72);
4415		rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4416		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4417				       offsetof(struct smb2_query_directory_rsp, Buffer) +
4418				       d_info.data_count);
4419		if (rc)
4420			goto err_out;
4421	}
4422
4423	kfree(srch_ptr);
4424	ksmbd_fd_put(work, dir_fp);
4425	ksmbd_revert_fsids(work);
4426	return 0;
4427
4428err_out:
4429	pr_err("error while processing smb2 query dir rc = %d\n", rc);
4430	kfree(srch_ptr);
4431
4432err_out2:
4433	if (rc == -EINVAL)
4434		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4435	else if (rc == -EACCES)
4436		rsp->hdr.Status = STATUS_ACCESS_DENIED;
4437	else if (rc == -ENOENT)
4438		rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4439	else if (rc == -EBADF)
4440		rsp->hdr.Status = STATUS_FILE_CLOSED;
4441	else if (rc == -ENOMEM)
4442		rsp->hdr.Status = STATUS_NO_MEMORY;
4443	else if (rc == -EFAULT)
4444		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4445	else if (rc == -EIO)
4446		rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4447	if (!rsp->hdr.Status)
4448		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4449
4450	smb2_set_err_rsp(work);
4451	ksmbd_fd_put(work, dir_fp);
4452	ksmbd_revert_fsids(work);
4453	return 0;
4454}
4455
4456/**
4457 * buffer_check_err() - helper function to check buffer errors
4458 * @reqOutputBufferLength:	max buffer length expected in command response
4459 * @rsp:		query info response buffer contains output buffer length
4460 * @rsp_org:		base response buffer pointer in case of chained response
4461 *
4462 * Return:	0 on success, otherwise error
4463 */
4464static int buffer_check_err(int reqOutputBufferLength,
4465			    struct smb2_query_info_rsp *rsp,
4466			    void *rsp_org)
4467{
4468	if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4469		pr_err("Invalid Buffer Size Requested\n");
4470		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4471		*(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4472		return -EINVAL;
4473	}
4474	return 0;
4475}
4476
4477static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4478				   void *rsp_org)
4479{
4480	struct smb2_file_standard_info *sinfo;
4481
4482	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4483
4484	sinfo->AllocationSize = cpu_to_le64(4096);
4485	sinfo->EndOfFile = cpu_to_le64(0);
4486	sinfo->NumberOfLinks = cpu_to_le32(1);
4487	sinfo->DeletePending = 1;
4488	sinfo->Directory = 0;
4489	rsp->OutputBufferLength =
4490		cpu_to_le32(sizeof(struct smb2_file_standard_info));
4491}
4492
4493static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4494				   void *rsp_org)
4495{
4496	struct smb2_file_internal_info *file_info;
4497
4498	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4499
4500	/* any unique number */
4501	file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4502	rsp->OutputBufferLength =
4503		cpu_to_le32(sizeof(struct smb2_file_internal_info));
4504}
4505
4506static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4507				   struct smb2_query_info_req *req,
4508				   struct smb2_query_info_rsp *rsp,
4509				   void *rsp_org)
4510{
4511	u64 id;
4512	int rc;
4513
4514	/*
4515	 * Windows can sometime send query file info request on
4516	 * pipe without opening it, checking error condition here
4517	 */
4518	id = req->VolatileFileId;
4519	if (!ksmbd_session_rpc_method(sess, id))
4520		return -ENOENT;
4521
4522	ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4523		    req->FileInfoClass, req->VolatileFileId);
4524
4525	switch (req->FileInfoClass) {
4526	case FILE_STANDARD_INFORMATION:
4527		get_standard_info_pipe(rsp, rsp_org);
4528		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4529				      rsp, rsp_org);
4530		break;
4531	case FILE_INTERNAL_INFORMATION:
4532		get_internal_info_pipe(rsp, id, rsp_org);
4533		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4534				      rsp, rsp_org);
4535		break;
4536	default:
4537		ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4538			    req->FileInfoClass);
4539		rc = -EOPNOTSUPP;
4540	}
4541	return rc;
4542}
4543
4544/**
4545 * smb2_get_ea() - handler for smb2 get extended attribute command
4546 * @work:	smb work containing query info command buffer
4547 * @fp:		ksmbd_file pointer
4548 * @req:	get extended attribute request
4549 * @rsp:	response buffer pointer
4550 * @rsp_org:	base response buffer pointer in case of chained response
4551 *
4552 * Return:	0 on success, otherwise error
4553 */
4554static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4555		       struct smb2_query_info_req *req,
4556		       struct smb2_query_info_rsp *rsp, void *rsp_org)
4557{
4558	struct smb2_ea_info *eainfo, *prev_eainfo;
4559	char *name, *ptr, *xattr_list = NULL, *buf;
4560	int rc, name_len, value_len, xattr_list_len, idx;
4561	ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4562	struct smb2_ea_info_req *ea_req = NULL;
4563	const struct path *path;
4564	struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4565
4566	if (!(fp->daccess & FILE_READ_EA_LE)) {
4567		pr_err("Not permitted to read ext attr : 0x%x\n",
4568		       fp->daccess);
4569		return -EACCES;
4570	}
4571
4572	path = &fp->filp->f_path;
4573	/* single EA entry is requested with given user.* name */
4574	if (req->InputBufferLength) {
4575		if (le32_to_cpu(req->InputBufferLength) <
4576		    sizeof(struct smb2_ea_info_req))
4577			return -EINVAL;
4578
4579		ea_req = (struct smb2_ea_info_req *)((char *)req +
4580						     le16_to_cpu(req->InputBufferOffset));
4581	} else {
4582		/* need to send all EAs, if no specific EA is requested*/
4583		if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4584			ksmbd_debug(SMB,
4585				    "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4586				    le32_to_cpu(req->Flags));
4587	}
4588
4589	buf_free_len =
4590		smb2_calc_max_out_buf_len(work, 8,
4591					  le32_to_cpu(req->OutputBufferLength));
4592	if (buf_free_len < 0)
4593		return -EINVAL;
4594
4595	rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4596	if (rc < 0) {
4597		rsp->hdr.Status = STATUS_INVALID_HANDLE;
4598		goto out;
4599	} else if (!rc) { /* there is no EA in the file */
4600		ksmbd_debug(SMB, "no ea data in the file\n");
4601		goto done;
4602	}
4603	xattr_list_len = rc;
4604
4605	ptr = (char *)rsp->Buffer;
4606	eainfo = (struct smb2_ea_info *)ptr;
4607	prev_eainfo = eainfo;
4608	idx = 0;
4609
4610	while (idx < xattr_list_len) {
4611		name = xattr_list + idx;
4612		name_len = strlen(name);
4613
4614		ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4615		idx += name_len + 1;
4616
4617		/*
4618		 * CIFS does not support EA other than user.* namespace,
4619		 * still keep the framework generic, to list other attrs
4620		 * in future.
4621		 */
4622		if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4623			continue;
4624
4625		if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4626			     STREAM_PREFIX_LEN))
4627			continue;
4628
4629		if (req->InputBufferLength &&
4630		    strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4631			    ea_req->EaNameLength))
4632			continue;
4633
4634		if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4635			     DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4636			continue;
4637
4638		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4639			name_len -= XATTR_USER_PREFIX_LEN;
4640
4641		ptr = eainfo->name + name_len + 1;
4642		buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4643				name_len + 1);
4644		/* bailout if xattr can't fit in buf_free_len */
4645		value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
4646					       name, &buf);
4647		if (value_len <= 0) {
4648			rc = -ENOENT;
4649			rsp->hdr.Status = STATUS_INVALID_HANDLE;
4650			goto out;
4651		}
4652
4653		buf_free_len -= value_len;
4654		if (buf_free_len < 0) {
4655			kfree(buf);
4656			break;
4657		}
4658
4659		memcpy(ptr, buf, value_len);
4660		kfree(buf);
4661
4662		ptr += value_len;
4663		eainfo->Flags = 0;
4664		eainfo->EaNameLength = name_len;
4665
4666		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4667			memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4668			       name_len);
4669		else
4670			memcpy(eainfo->name, name, name_len);
4671
4672		eainfo->name[name_len] = '\0';
4673		eainfo->EaValueLength = cpu_to_le16(value_len);
4674		next_offset = offsetof(struct smb2_ea_info, name) +
4675			name_len + 1 + value_len;
4676
4677		/* align next xattr entry at 4 byte bundary */
4678		alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4679		if (alignment_bytes) {
4680			memset(ptr, '\0', alignment_bytes);
4681			ptr += alignment_bytes;
4682			next_offset += alignment_bytes;
4683			buf_free_len -= alignment_bytes;
4684		}
4685		eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4686		prev_eainfo = eainfo;
4687		eainfo = (struct smb2_ea_info *)ptr;
4688		rsp_data_cnt += next_offset;
4689
4690		if (req->InputBufferLength) {
4691			ksmbd_debug(SMB, "single entry requested\n");
4692			break;
4693		}
4694	}
4695
4696	/* no more ea entries */
4697	prev_eainfo->NextEntryOffset = 0;
4698done:
4699	rc = 0;
4700	if (rsp_data_cnt == 0)
4701		rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4702	rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4703out:
4704	kvfree(xattr_list);
4705	return rc;
4706}
4707
4708static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4709				 struct ksmbd_file *fp, void *rsp_org)
4710{
4711	struct smb2_file_access_info *file_info;
4712
4713	file_info = (struct smb2_file_access_info *)rsp->Buffer;
4714	file_info->AccessFlags = fp->daccess;
4715	rsp->OutputBufferLength =
4716		cpu_to_le32(sizeof(struct smb2_file_access_info));
4717}
4718
4719static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4720			       struct ksmbd_file *fp, void *rsp_org)
4721{
4722	struct smb2_file_basic_info *basic_info;
4723	struct kstat stat;
4724	u64 time;
4725	int ret;
4726
4727	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4728		pr_err("no right to read the attributes : 0x%x\n",
4729		       fp->daccess);
4730		return -EACCES;
4731	}
4732
4733	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4734			  AT_STATX_SYNC_AS_STAT);
4735	if (ret)
4736		return ret;
4737
4738	basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4739	basic_info->CreationTime = cpu_to_le64(fp->create_time);
4740	time = ksmbd_UnixTimeToNT(stat.atime);
4741	basic_info->LastAccessTime = cpu_to_le64(time);
4742	time = ksmbd_UnixTimeToNT(stat.mtime);
4743	basic_info->LastWriteTime = cpu_to_le64(time);
4744	time = ksmbd_UnixTimeToNT(stat.ctime);
4745	basic_info->ChangeTime = cpu_to_le64(time);
4746	basic_info->Attributes = fp->f_ci->m_fattr;
4747	basic_info->Pad1 = 0;
4748	rsp->OutputBufferLength =
4749		cpu_to_le32(sizeof(struct smb2_file_basic_info));
4750	return 0;
4751}
4752
4753static int get_file_standard_info(struct smb2_query_info_rsp *rsp,
4754				  struct ksmbd_file *fp, void *rsp_org)
4755{
4756	struct smb2_file_standard_info *sinfo;
4757	unsigned int delete_pending;
4758	struct kstat stat;
4759	int ret;
4760
4761	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4762			  AT_STATX_SYNC_AS_STAT);
4763	if (ret)
4764		return ret;
4765
4766	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4767	delete_pending = ksmbd_inode_pending_delete(fp);
4768
4769	sinfo->AllocationSize = cpu_to_le64(stat.blocks << 9);
4770	sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4771	sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4772	sinfo->DeletePending = delete_pending;
4773	sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4774	rsp->OutputBufferLength =
4775		cpu_to_le32(sizeof(struct smb2_file_standard_info));
4776
4777	return 0;
4778}
4779
4780static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4781				    void *rsp_org)
4782{
4783	struct smb2_file_alignment_info *file_info;
4784
4785	file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4786	file_info->AlignmentRequirement = 0;
4787	rsp->OutputBufferLength =
4788		cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4789}
4790
4791static int get_file_all_info(struct ksmbd_work *work,
4792			     struct smb2_query_info_rsp *rsp,
4793			     struct ksmbd_file *fp,
4794			     void *rsp_org)
4795{
4796	struct ksmbd_conn *conn = work->conn;
4797	struct smb2_file_all_info *file_info;
4798	unsigned int delete_pending;
4799	struct kstat stat;
4800	int conv_len;
4801	char *filename;
4802	u64 time;
4803	int ret;
4804
4805	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4806		ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4807			    fp->daccess);
4808		return -EACCES;
4809	}
4810
4811	filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4812	if (IS_ERR(filename))
4813		return PTR_ERR(filename);
4814
4815	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4816			  AT_STATX_SYNC_AS_STAT);
4817	if (ret)
4818		return ret;
4819
4820	ksmbd_debug(SMB, "filename = %s\n", filename);
4821	delete_pending = ksmbd_inode_pending_delete(fp);
4822	file_info = (struct smb2_file_all_info *)rsp->Buffer;
4823
4824	file_info->CreationTime = cpu_to_le64(fp->create_time);
4825	time = ksmbd_UnixTimeToNT(stat.atime);
4826	file_info->LastAccessTime = cpu_to_le64(time);
4827	time = ksmbd_UnixTimeToNT(stat.mtime);
4828	file_info->LastWriteTime = cpu_to_le64(time);
4829	time = ksmbd_UnixTimeToNT(stat.ctime);
4830	file_info->ChangeTime = cpu_to_le64(time);
4831	file_info->Attributes = fp->f_ci->m_fattr;
4832	file_info->Pad1 = 0;
4833	file_info->AllocationSize =
4834		cpu_to_le64(stat.blocks << 9);
4835	file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4836	file_info->NumberOfLinks =
4837			cpu_to_le32(get_nlink(&stat) - delete_pending);
4838	file_info->DeletePending = delete_pending;
4839	file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4840	file_info->Pad2 = 0;
4841	file_info->IndexNumber = cpu_to_le64(stat.ino);
4842	file_info->EASize = 0;
4843	file_info->AccessFlags = fp->daccess;
4844	file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4845	file_info->Mode = fp->coption;
4846	file_info->AlignmentRequirement = 0;
4847	conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4848				     PATH_MAX, conn->local_nls, 0);
4849	conv_len *= 2;
4850	file_info->FileNameLength = cpu_to_le32(conv_len);
4851	rsp->OutputBufferLength =
4852		cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4853	kfree(filename);
4854	return 0;
4855}
4856
4857static void get_file_alternate_info(struct ksmbd_work *work,
4858				    struct smb2_query_info_rsp *rsp,
4859				    struct ksmbd_file *fp,
4860				    void *rsp_org)
4861{
4862	struct ksmbd_conn *conn = work->conn;
4863	struct smb2_file_alt_name_info *file_info;
4864	struct dentry *dentry = fp->filp->f_path.dentry;
4865	int conv_len;
4866
4867	spin_lock(&dentry->d_lock);
4868	file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4869	conv_len = ksmbd_extract_shortname(conn,
4870					   dentry->d_name.name,
4871					   file_info->FileName);
4872	spin_unlock(&dentry->d_lock);
4873	file_info->FileNameLength = cpu_to_le32(conv_len);
4874	rsp->OutputBufferLength =
4875		cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4876}
4877
4878static int get_file_stream_info(struct ksmbd_work *work,
4879				struct smb2_query_info_rsp *rsp,
4880				struct ksmbd_file *fp,
4881				void *rsp_org)
4882{
4883	struct ksmbd_conn *conn = work->conn;
4884	struct smb2_file_stream_info *file_info;
4885	char *stream_name, *xattr_list = NULL, *stream_buf;
4886	struct kstat stat;
4887	const struct path *path = &fp->filp->f_path;
4888	ssize_t xattr_list_len;
4889	int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4890	int buf_free_len;
4891	struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4892	int ret;
4893
4894	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4895			  AT_STATX_SYNC_AS_STAT);
4896	if (ret)
4897		return ret;
4898
4899	file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4900
4901	buf_free_len =
4902		smb2_calc_max_out_buf_len(work, 8,
4903					  le32_to_cpu(req->OutputBufferLength));
4904	if (buf_free_len < 0)
4905		goto out;
4906
4907	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4908	if (xattr_list_len < 0) {
4909		goto out;
4910	} else if (!xattr_list_len) {
4911		ksmbd_debug(SMB, "empty xattr in the file\n");
4912		goto out;
4913	}
4914
4915	while (idx < xattr_list_len) {
4916		stream_name = xattr_list + idx;
4917		streamlen = strlen(stream_name);
4918		idx += streamlen + 1;
4919
4920		ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4921
4922		if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4923			    STREAM_PREFIX, STREAM_PREFIX_LEN))
4924			continue;
4925
4926		stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4927				STREAM_PREFIX_LEN);
4928		streamlen = stream_name_len;
4929
4930		/* plus : size */
4931		streamlen += 1;
4932		stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4933		if (!stream_buf)
4934			break;
4935
4936		streamlen = snprintf(stream_buf, streamlen + 1,
4937				     ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4938
4939		next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4940		if (next > buf_free_len) {
4941			kfree(stream_buf);
4942			break;
4943		}
4944
4945		file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4946		streamlen  = smbConvertToUTF16((__le16 *)file_info->StreamName,
4947					       stream_buf, streamlen,
4948					       conn->local_nls, 0);
4949		streamlen *= 2;
4950		kfree(stream_buf);
4951		file_info->StreamNameLength = cpu_to_le32(streamlen);
4952		file_info->StreamSize = cpu_to_le64(stream_name_len);
4953		file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4954
4955		nbytes += next;
4956		buf_free_len -= next;
4957		file_info->NextEntryOffset = cpu_to_le32(next);
4958	}
4959
4960out:
4961	if (!S_ISDIR(stat.mode) &&
4962	    buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4963		file_info = (struct smb2_file_stream_info *)
4964			&rsp->Buffer[nbytes];
4965		streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4966					      "::$DATA", 7, conn->local_nls, 0);
4967		streamlen *= 2;
4968		file_info->StreamNameLength = cpu_to_le32(streamlen);
4969		file_info->StreamSize = cpu_to_le64(stat.size);
4970		file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4971		nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4972	}
4973
4974	/* last entry offset should be 0 */
4975	file_info->NextEntryOffset = 0;
4976	kvfree(xattr_list);
4977
4978	rsp->OutputBufferLength = cpu_to_le32(nbytes);
4979
4980	return 0;
4981}
4982
4983static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
4984				  struct ksmbd_file *fp, void *rsp_org)
4985{
4986	struct smb2_file_internal_info *file_info;
4987	struct kstat stat;
4988	int ret;
4989
4990	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4991			  AT_STATX_SYNC_AS_STAT);
4992	if (ret)
4993		return ret;
4994
4995	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4996	file_info->IndexNumber = cpu_to_le64(stat.ino);
4997	rsp->OutputBufferLength =
4998		cpu_to_le32(sizeof(struct smb2_file_internal_info));
4999
5000	return 0;
5001}
5002
5003static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
5004				      struct ksmbd_file *fp, void *rsp_org)
5005{
5006	struct smb2_file_ntwrk_info *file_info;
5007	struct kstat stat;
5008	u64 time;
5009	int ret;
5010
5011	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5012		pr_err("no right to read the attributes : 0x%x\n",
5013		       fp->daccess);
5014		return -EACCES;
5015	}
5016
5017	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5018			  AT_STATX_SYNC_AS_STAT);
5019	if (ret)
5020		return ret;
5021
5022	file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
5023
5024	file_info->CreationTime = cpu_to_le64(fp->create_time);
5025	time = ksmbd_UnixTimeToNT(stat.atime);
5026	file_info->LastAccessTime = cpu_to_le64(time);
5027	time = ksmbd_UnixTimeToNT(stat.mtime);
5028	file_info->LastWriteTime = cpu_to_le64(time);
5029	time = ksmbd_UnixTimeToNT(stat.ctime);
5030	file_info->ChangeTime = cpu_to_le64(time);
5031	file_info->Attributes = fp->f_ci->m_fattr;
5032	file_info->AllocationSize = cpu_to_le64(stat.blocks << 9);
5033	file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5034	file_info->Reserved = cpu_to_le32(0);
5035	rsp->OutputBufferLength =
5036		cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
5037	return 0;
5038}
5039
5040static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
5041{
5042	struct smb2_file_ea_info *file_info;
5043
5044	file_info = (struct smb2_file_ea_info *)rsp->Buffer;
5045	file_info->EASize = 0;
5046	rsp->OutputBufferLength =
5047		cpu_to_le32(sizeof(struct smb2_file_ea_info));
5048}
5049
5050static void get_file_position_info(struct smb2_query_info_rsp *rsp,
5051				   struct ksmbd_file *fp, void *rsp_org)
5052{
5053	struct smb2_file_pos_info *file_info;
5054
5055	file_info = (struct smb2_file_pos_info *)rsp->Buffer;
5056	file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
5057	rsp->OutputBufferLength =
5058		cpu_to_le32(sizeof(struct smb2_file_pos_info));
5059}
5060
5061static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
5062			       struct ksmbd_file *fp, void *rsp_org)
5063{
5064	struct smb2_file_mode_info *file_info;
5065
5066	file_info = (struct smb2_file_mode_info *)rsp->Buffer;
5067	file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
5068	rsp->OutputBufferLength =
5069		cpu_to_le32(sizeof(struct smb2_file_mode_info));
5070}
5071
5072static int get_file_compression_info(struct smb2_query_info_rsp *rsp,
5073				     struct ksmbd_file *fp, void *rsp_org)
5074{
5075	struct smb2_file_comp_info *file_info;
5076	struct kstat stat;
5077	int ret;
5078
5079	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5080			  AT_STATX_SYNC_AS_STAT);
5081	if (ret)
5082		return ret;
5083
5084	file_info = (struct smb2_file_comp_info *)rsp->Buffer;
5085	file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
5086	file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
5087	file_info->CompressionUnitShift = 0;
5088	file_info->ChunkShift = 0;
5089	file_info->ClusterShift = 0;
5090	memset(&file_info->Reserved[0], 0, 3);
5091
5092	rsp->OutputBufferLength =
5093		cpu_to_le32(sizeof(struct smb2_file_comp_info));
5094
5095	return 0;
5096}
5097
5098static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
5099				       struct ksmbd_file *fp, void *rsp_org)
5100{
5101	struct smb2_file_attr_tag_info *file_info;
5102
5103	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5104		pr_err("no right to read the attributes : 0x%x\n",
5105		       fp->daccess);
5106		return -EACCES;
5107	}
5108
5109	file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
5110	file_info->FileAttributes = fp->f_ci->m_fattr;
5111	file_info->ReparseTag = 0;
5112	rsp->OutputBufferLength =
5113		cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
5114	return 0;
5115}
5116
5117static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
5118				struct ksmbd_file *fp, void *rsp_org)
5119{
5120	struct smb311_posix_qinfo *file_info;
5121	struct inode *inode = file_inode(fp->filp);
5122	struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
5123	vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
5124	vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
5125	struct kstat stat;
5126	u64 time;
5127	int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
5128	int ret;
5129
5130	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5131			  AT_STATX_SYNC_AS_STAT);
5132	if (ret)
5133		return ret;
5134
5135	file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
5136	file_info->CreationTime = cpu_to_le64(fp->create_time);
5137	time = ksmbd_UnixTimeToNT(stat.atime);
5138	file_info->LastAccessTime = cpu_to_le64(time);
5139	time = ksmbd_UnixTimeToNT(stat.mtime);
5140	file_info->LastWriteTime = cpu_to_le64(time);
5141	time = ksmbd_UnixTimeToNT(stat.ctime);
5142	file_info->ChangeTime = cpu_to_le64(time);
5143	file_info->DosAttributes = fp->f_ci->m_fattr;
5144	file_info->Inode = cpu_to_le64(stat.ino);
5145	file_info->EndOfFile = cpu_to_le64(stat.size);
5146	file_info->AllocationSize = cpu_to_le64(stat.blocks << 9);
5147	file_info->HardLinks = cpu_to_le32(stat.nlink);
5148	file_info->Mode = cpu_to_le32(stat.mode & 0777);
5149	file_info->DeviceId = cpu_to_le32(stat.rdev);
5150
5151	/*
5152	 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
5153	 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
5154	 *		  sub_auth(4 * 1(num_subauth)) + RID(4).
5155	 */
5156	id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
5157		  SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
5158	id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
5159		  SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
5160
5161	rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
5162
5163	return 0;
5164}
5165
5166static int smb2_get_info_file(struct ksmbd_work *work,
5167			      struct smb2_query_info_req *req,
5168			      struct smb2_query_info_rsp *rsp)
5169{
5170	struct ksmbd_file *fp;
5171	int fileinfoclass = 0;
5172	int rc = 0;
5173	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5174
5175	if (test_share_config_flag(work->tcon->share_conf,
5176				   KSMBD_SHARE_FLAG_PIPE)) {
5177		/* smb2 info file called for pipe */
5178		return smb2_get_info_file_pipe(work->sess, req, rsp,
5179					       work->response_buf);
5180	}
5181
5182	if (work->next_smb2_rcv_hdr_off) {
5183		if (!has_file_id(req->VolatileFileId)) {
5184			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5185				    work->compound_fid);
5186			id = work->compound_fid;
5187			pid = work->compound_pfid;
5188		}
5189	}
5190
5191	if (!has_file_id(id)) {
5192		id = req->VolatileFileId;
5193		pid = req->PersistentFileId;
5194	}
5195
5196	fp = ksmbd_lookup_fd_slow(work, id, pid);
5197	if (!fp)
5198		return -ENOENT;
5199
5200	fileinfoclass = req->FileInfoClass;
5201
5202	switch (fileinfoclass) {
5203	case FILE_ACCESS_INFORMATION:
5204		get_file_access_info(rsp, fp, work->response_buf);
5205		break;
5206
5207	case FILE_BASIC_INFORMATION:
5208		rc = get_file_basic_info(rsp, fp, work->response_buf);
5209		break;
5210
5211	case FILE_STANDARD_INFORMATION:
5212		rc = get_file_standard_info(rsp, fp, work->response_buf);
5213		break;
5214
5215	case FILE_ALIGNMENT_INFORMATION:
5216		get_file_alignment_info(rsp, work->response_buf);
5217		break;
5218
5219	case FILE_ALL_INFORMATION:
5220		rc = get_file_all_info(work, rsp, fp, work->response_buf);
5221		break;
5222
5223	case FILE_ALTERNATE_NAME_INFORMATION:
5224		get_file_alternate_info(work, rsp, fp, work->response_buf);
5225		break;
5226
5227	case FILE_STREAM_INFORMATION:
5228		rc = get_file_stream_info(work, rsp, fp, work->response_buf);
5229		break;
5230
5231	case FILE_INTERNAL_INFORMATION:
5232		rc = get_file_internal_info(rsp, fp, work->response_buf);
5233		break;
5234
5235	case FILE_NETWORK_OPEN_INFORMATION:
5236		rc = get_file_network_open_info(rsp, fp, work->response_buf);
5237		break;
5238
5239	case FILE_EA_INFORMATION:
5240		get_file_ea_info(rsp, work->response_buf);
5241		break;
5242
5243	case FILE_FULL_EA_INFORMATION:
5244		rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
5245		break;
5246
5247	case FILE_POSITION_INFORMATION:
5248		get_file_position_info(rsp, fp, work->response_buf);
5249		break;
5250
5251	case FILE_MODE_INFORMATION:
5252		get_file_mode_info(rsp, fp, work->response_buf);
5253		break;
5254
5255	case FILE_COMPRESSION_INFORMATION:
5256		rc = get_file_compression_info(rsp, fp, work->response_buf);
5257		break;
5258
5259	case FILE_ATTRIBUTE_TAG_INFORMATION:
5260		rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
5261		break;
5262	case SMB_FIND_FILE_POSIX_INFO:
5263		if (!work->tcon->posix_extensions) {
5264			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5265			rc = -EOPNOTSUPP;
5266		} else {
5267			rc = find_file_posix_info(rsp, fp, work->response_buf);
5268		}
5269		break;
5270	default:
5271		ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
5272			    fileinfoclass);
5273		rc = -EOPNOTSUPP;
5274	}
5275	if (!rc)
5276		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5277				      rsp, work->response_buf);
5278	ksmbd_fd_put(work, fp);
5279	return rc;
5280}
5281
5282static int smb2_get_info_filesystem(struct ksmbd_work *work,
5283				    struct smb2_query_info_req *req,
5284				    struct smb2_query_info_rsp *rsp)
5285{
5286	struct ksmbd_session *sess = work->sess;
5287	struct ksmbd_conn *conn = work->conn;
5288	struct ksmbd_share_config *share = work->tcon->share_conf;
5289	int fsinfoclass = 0;
5290	struct kstatfs stfs;
5291	struct path path;
5292	int rc = 0, len;
5293
5294	if (!share->path)
5295		return -EIO;
5296
5297	rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
5298	if (rc) {
5299		pr_err("cannot create vfs path\n");
5300		return -EIO;
5301	}
5302
5303	rc = vfs_statfs(&path, &stfs);
5304	if (rc) {
5305		pr_err("cannot do stat of path %s\n", share->path);
5306		path_put(&path);
5307		return -EIO;
5308	}
5309
5310	fsinfoclass = req->FileInfoClass;
5311
5312	switch (fsinfoclass) {
5313	case FS_DEVICE_INFORMATION:
5314	{
5315		struct filesystem_device_info *info;
5316
5317		info = (struct filesystem_device_info *)rsp->Buffer;
5318
5319		info->DeviceType = cpu_to_le32(stfs.f_type);
5320		info->DeviceCharacteristics = cpu_to_le32(0x00000020);
5321		rsp->OutputBufferLength = cpu_to_le32(8);
5322		break;
5323	}
5324	case FS_ATTRIBUTE_INFORMATION:
5325	{
5326		struct filesystem_attribute_info *info;
5327		size_t sz;
5328
5329		info = (struct filesystem_attribute_info *)rsp->Buffer;
5330		info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
5331					       FILE_PERSISTENT_ACLS |
5332					       FILE_UNICODE_ON_DISK |
5333					       FILE_CASE_PRESERVED_NAMES |
5334					       FILE_CASE_SENSITIVE_SEARCH |
5335					       FILE_SUPPORTS_BLOCK_REFCOUNTING);
5336
5337		info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
5338
5339		if (test_share_config_flag(work->tcon->share_conf,
5340		    KSMBD_SHARE_FLAG_STREAMS))
5341			info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
5342
5343		info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
5344		len = smbConvertToUTF16((__le16 *)info->FileSystemName,
5345					"NTFS", PATH_MAX, conn->local_nls, 0);
5346		len = len * 2;
5347		info->FileSystemNameLen = cpu_to_le32(len);
5348		sz = sizeof(struct filesystem_attribute_info) - 2 + len;
5349		rsp->OutputBufferLength = cpu_to_le32(sz);
5350		break;
5351	}
5352	case FS_VOLUME_INFORMATION:
5353	{
5354		struct filesystem_vol_info *info;
5355		size_t sz;
5356		unsigned int serial_crc = 0;
5357
5358		info = (struct filesystem_vol_info *)(rsp->Buffer);
5359		info->VolumeCreationTime = 0;
5360		serial_crc = crc32_le(serial_crc, share->name,
5361				      strlen(share->name));
5362		serial_crc = crc32_le(serial_crc, share->path,
5363				      strlen(share->path));
5364		serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
5365				      strlen(ksmbd_netbios_name()));
5366		/* Taking dummy value of serial number*/
5367		info->SerialNumber = cpu_to_le32(serial_crc);
5368		len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
5369					share->name, PATH_MAX,
5370					conn->local_nls, 0);
5371		len = len * 2;
5372		info->VolumeLabelSize = cpu_to_le32(len);
5373		info->Reserved = 0;
5374		sz = sizeof(struct filesystem_vol_info) - 2 + len;
5375		rsp->OutputBufferLength = cpu_to_le32(sz);
5376		break;
5377	}
5378	case FS_SIZE_INFORMATION:
5379	{
5380		struct filesystem_info *info;
5381
5382		info = (struct filesystem_info *)(rsp->Buffer);
5383		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5384		info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
5385		info->SectorsPerAllocationUnit = cpu_to_le32(1);
5386		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5387		rsp->OutputBufferLength = cpu_to_le32(24);
5388		break;
5389	}
5390	case FS_FULL_SIZE_INFORMATION:
5391	{
5392		struct smb2_fs_full_size_info *info;
5393
5394		info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5395		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5396		info->CallerAvailableAllocationUnits =
5397					cpu_to_le64(stfs.f_bavail);
5398		info->ActualAvailableAllocationUnits =
5399					cpu_to_le64(stfs.f_bfree);
5400		info->SectorsPerAllocationUnit = cpu_to_le32(1);
5401		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5402		rsp->OutputBufferLength = cpu_to_le32(32);
5403		break;
5404	}
5405	case FS_OBJECT_ID_INFORMATION:
5406	{
5407		struct object_id_info *info;
5408
5409		info = (struct object_id_info *)(rsp->Buffer);
5410
5411		if (!user_guest(sess->user))
5412			memcpy(info->objid, user_passkey(sess->user), 16);
5413		else
5414			memset(info->objid, 0, 16);
5415
5416		info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5417		info->extended_info.version = cpu_to_le32(1);
5418		info->extended_info.release = cpu_to_le32(1);
5419		info->extended_info.rel_date = 0;
5420		memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5421		rsp->OutputBufferLength = cpu_to_le32(64);
5422		break;
5423	}
5424	case FS_SECTOR_SIZE_INFORMATION:
5425	{
5426		struct smb3_fs_ss_info *info;
5427		unsigned int sector_size =
5428			min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5429
5430		info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5431
5432		info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5433		info->PhysicalBytesPerSectorForAtomicity =
5434				cpu_to_le32(sector_size);
5435		info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5436		info->FSEffPhysicalBytesPerSectorForAtomicity =
5437				cpu_to_le32(sector_size);
5438		info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5439				    SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5440		info->ByteOffsetForSectorAlignment = 0;
5441		info->ByteOffsetForPartitionAlignment = 0;
5442		rsp->OutputBufferLength = cpu_to_le32(28);
5443		break;
5444	}
5445	case FS_CONTROL_INFORMATION:
5446	{
5447		/*
5448		 * TODO : The current implementation is based on
5449		 * test result with win7(NTFS) server. It's need to
5450		 * modify this to get valid Quota values
5451		 * from Linux kernel
5452		 */
5453		struct smb2_fs_control_info *info;
5454
5455		info = (struct smb2_fs_control_info *)(rsp->Buffer);
5456		info->FreeSpaceStartFiltering = 0;
5457		info->FreeSpaceThreshold = 0;
5458		info->FreeSpaceStopFiltering = 0;
5459		info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5460		info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5461		info->Padding = 0;
5462		rsp->OutputBufferLength = cpu_to_le32(48);
5463		break;
5464	}
5465	case FS_POSIX_INFORMATION:
5466	{
5467		struct filesystem_posix_info *info;
5468
5469		if (!work->tcon->posix_extensions) {
5470			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5471			rc = -EOPNOTSUPP;
5472		} else {
5473			info = (struct filesystem_posix_info *)(rsp->Buffer);
5474			info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5475			info->BlockSize = cpu_to_le32(stfs.f_bsize);
5476			info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5477			info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5478			info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5479			info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5480			info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5481			rsp->OutputBufferLength = cpu_to_le32(56);
5482		}
5483		break;
5484	}
5485	default:
5486		path_put(&path);
5487		return -EOPNOTSUPP;
5488	}
5489	rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5490			      rsp, work->response_buf);
5491	path_put(&path);
5492	return rc;
5493}
5494
5495static int smb2_get_info_sec(struct ksmbd_work *work,
5496			     struct smb2_query_info_req *req,
5497			     struct smb2_query_info_rsp *rsp)
5498{
5499	struct ksmbd_file *fp;
5500	struct mnt_idmap *idmap;
5501	struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5502	struct smb_fattr fattr = {{0}};
5503	struct inode *inode;
5504	__u32 secdesclen = 0;
5505	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5506	int addition_info = le32_to_cpu(req->AdditionalInformation);
5507	int rc = 0, ppntsd_size = 0;
5508
5509	if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5510			      PROTECTED_DACL_SECINFO |
5511			      UNPROTECTED_DACL_SECINFO)) {
5512		ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5513		       addition_info);
5514
5515		pntsd->revision = cpu_to_le16(1);
5516		pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5517		pntsd->osidoffset = 0;
5518		pntsd->gsidoffset = 0;
5519		pntsd->sacloffset = 0;
5520		pntsd->dacloffset = 0;
5521
5522		secdesclen = sizeof(struct smb_ntsd);
5523		rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5524
5525		return 0;
5526	}
5527
5528	if (work->next_smb2_rcv_hdr_off) {
5529		if (!has_file_id(req->VolatileFileId)) {
5530			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5531				    work->compound_fid);
5532			id = work->compound_fid;
5533			pid = work->compound_pfid;
5534		}
5535	}
5536
5537	if (!has_file_id(id)) {
5538		id = req->VolatileFileId;
5539		pid = req->PersistentFileId;
5540	}
5541
5542	fp = ksmbd_lookup_fd_slow(work, id, pid);
5543	if (!fp)
5544		return -ENOENT;
5545
5546	idmap = file_mnt_idmap(fp->filp);
5547	inode = file_inode(fp->filp);
5548	ksmbd_acls_fattr(&fattr, idmap, inode);
5549
5550	if (test_share_config_flag(work->tcon->share_conf,
5551				   KSMBD_SHARE_FLAG_ACL_XATTR))
5552		ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
5553						     fp->filp->f_path.dentry,
5554						     &ppntsd);
5555
5556	/* Check if sd buffer size exceeds response buffer size */
5557	if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5558		rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
5559				    addition_info, &secdesclen, &fattr);
5560	posix_acl_release(fattr.cf_acls);
5561	posix_acl_release(fattr.cf_dacls);
5562	kfree(ppntsd);
5563	ksmbd_fd_put(work, fp);
5564	if (rc)
5565		return rc;
5566
5567	rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5568	return 0;
5569}
5570
5571/**
5572 * smb2_query_info() - handler for smb2 query info command
5573 * @work:	smb work containing query info request buffer
5574 *
5575 * Return:	0 on success, otherwise error
5576 */
5577int smb2_query_info(struct ksmbd_work *work)
5578{
5579	struct smb2_query_info_req *req;
5580	struct smb2_query_info_rsp *rsp;
5581	int rc = 0;
5582
5583	WORK_BUFFERS(work, req, rsp);
5584
5585	ksmbd_debug(SMB, "GOT query info request\n");
5586
5587	switch (req->InfoType) {
5588	case SMB2_O_INFO_FILE:
5589		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5590		rc = smb2_get_info_file(work, req, rsp);
5591		break;
5592	case SMB2_O_INFO_FILESYSTEM:
5593		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5594		rc = smb2_get_info_filesystem(work, req, rsp);
5595		break;
5596	case SMB2_O_INFO_SECURITY:
5597		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5598		rc = smb2_get_info_sec(work, req, rsp);
5599		break;
5600	default:
5601		ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5602			    req->InfoType);
5603		rc = -EOPNOTSUPP;
5604	}
5605
5606	if (!rc) {
5607		rsp->StructureSize = cpu_to_le16(9);
5608		rsp->OutputBufferOffset = cpu_to_le16(72);
5609		rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5610				       offsetof(struct smb2_query_info_rsp, Buffer) +
5611					le32_to_cpu(rsp->OutputBufferLength));
5612	}
5613
5614	if (rc < 0) {
5615		if (rc == -EACCES)
5616			rsp->hdr.Status = STATUS_ACCESS_DENIED;
5617		else if (rc == -ENOENT)
5618			rsp->hdr.Status = STATUS_FILE_CLOSED;
5619		else if (rc == -EIO)
5620			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5621		else if (rc == -ENOMEM)
5622			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5623		else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5624			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5625		smb2_set_err_rsp(work);
5626
5627		ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5628			    rc);
5629		return rc;
5630	}
5631	return 0;
5632}
5633
5634/**
5635 * smb2_close_pipe() - handler for closing IPC pipe
5636 * @work:	smb work containing close request buffer
5637 *
5638 * Return:	0
5639 */
5640static noinline int smb2_close_pipe(struct ksmbd_work *work)
5641{
5642	u64 id;
5643	struct smb2_close_req *req;
5644	struct smb2_close_rsp *rsp;
5645
5646	WORK_BUFFERS(work, req, rsp);
5647
5648	id = req->VolatileFileId;
5649	ksmbd_session_rpc_close(work->sess, id);
5650
5651	rsp->StructureSize = cpu_to_le16(60);
5652	rsp->Flags = 0;
5653	rsp->Reserved = 0;
5654	rsp->CreationTime = 0;
5655	rsp->LastAccessTime = 0;
5656	rsp->LastWriteTime = 0;
5657	rsp->ChangeTime = 0;
5658	rsp->AllocationSize = 0;
5659	rsp->EndOfFile = 0;
5660	rsp->Attributes = 0;
5661
5662	return ksmbd_iov_pin_rsp(work, (void *)rsp,
5663				 sizeof(struct smb2_close_rsp));
5664}
5665
5666/**
5667 * smb2_close() - handler for smb2 close file command
5668 * @work:	smb work containing close request buffer
5669 *
5670 * Return:	0
5671 */
5672int smb2_close(struct ksmbd_work *work)
5673{
5674	u64 volatile_id = KSMBD_NO_FID;
5675	u64 sess_id;
5676	struct smb2_close_req *req;
5677	struct smb2_close_rsp *rsp;
5678	struct ksmbd_conn *conn = work->conn;
5679	struct ksmbd_file *fp;
5680	u64 time;
5681	int err = 0;
5682
5683	WORK_BUFFERS(work, req, rsp);
5684
5685	if (test_share_config_flag(work->tcon->share_conf,
5686				   KSMBD_SHARE_FLAG_PIPE)) {
5687		ksmbd_debug(SMB, "IPC pipe close request\n");
5688		return smb2_close_pipe(work);
5689	}
5690
5691	sess_id = le64_to_cpu(req->hdr.SessionId);
5692	if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5693		sess_id = work->compound_sid;
5694
5695	work->compound_sid = 0;
5696	if (check_session_id(conn, sess_id)) {
5697		work->compound_sid = sess_id;
5698	} else {
5699		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5700		if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5701			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5702		err = -EBADF;
5703		goto out;
5704	}
5705
5706	if (work->next_smb2_rcv_hdr_off &&
5707	    !has_file_id(req->VolatileFileId)) {
5708		if (!has_file_id(work->compound_fid)) {
5709			/* file already closed, return FILE_CLOSED */
5710			ksmbd_debug(SMB, "file already closed\n");
5711			rsp->hdr.Status = STATUS_FILE_CLOSED;
5712			err = -EBADF;
5713			goto out;
5714		} else {
5715			ksmbd_debug(SMB,
5716				    "Compound request set FID = %llu:%llu\n",
5717				    work->compound_fid,
5718				    work->compound_pfid);
5719			volatile_id = work->compound_fid;
5720
5721			/* file closed, stored id is not valid anymore */
5722			work->compound_fid = KSMBD_NO_FID;
5723			work->compound_pfid = KSMBD_NO_FID;
5724		}
5725	} else {
5726		volatile_id = req->VolatileFileId;
5727	}
5728	ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5729
5730	rsp->StructureSize = cpu_to_le16(60);
5731	rsp->Reserved = 0;
5732
5733	if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5734		struct kstat stat;
5735		int ret;
5736
5737		fp = ksmbd_lookup_fd_fast(work, volatile_id);
5738		if (!fp) {
5739			err = -ENOENT;
5740			goto out;
5741		}
5742
5743		ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5744				  AT_STATX_SYNC_AS_STAT);
5745		if (ret) {
5746			ksmbd_fd_put(work, fp);
5747			goto out;
5748		}
5749
5750		rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5751		rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
5752			cpu_to_le64(stat.blocks << 9);
5753		rsp->EndOfFile = cpu_to_le64(stat.size);
5754		rsp->Attributes = fp->f_ci->m_fattr;
5755		rsp->CreationTime = cpu_to_le64(fp->create_time);
5756		time = ksmbd_UnixTimeToNT(stat.atime);
5757		rsp->LastAccessTime = cpu_to_le64(time);
5758		time = ksmbd_UnixTimeToNT(stat.mtime);
5759		rsp->LastWriteTime = cpu_to_le64(time);
5760		time = ksmbd_UnixTimeToNT(stat.ctime);
5761		rsp->ChangeTime = cpu_to_le64(time);
5762		ksmbd_fd_put(work, fp);
5763	} else {
5764		rsp->Flags = 0;
5765		rsp->AllocationSize = 0;
5766		rsp->EndOfFile = 0;
5767		rsp->Attributes = 0;
5768		rsp->CreationTime = 0;
5769		rsp->LastAccessTime = 0;
5770		rsp->LastWriteTime = 0;
5771		rsp->ChangeTime = 0;
5772	}
5773
5774	err = ksmbd_close_fd(work, volatile_id);
5775out:
5776	if (!err)
5777		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
5778					sizeof(struct smb2_close_rsp));
5779
5780	if (err) {
5781		if (rsp->hdr.Status == 0)
5782			rsp->hdr.Status = STATUS_FILE_CLOSED;
5783		smb2_set_err_rsp(work);
5784	}
5785
5786	return err;
5787}
5788
5789/**
5790 * smb2_echo() - handler for smb2 echo(ping) command
5791 * @work:	smb work containing echo request buffer
5792 *
5793 * Return:	0
5794 */
5795int smb2_echo(struct ksmbd_work *work)
5796{
5797	struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5798
5799	if (work->next_smb2_rcv_hdr_off)
5800		rsp = ksmbd_resp_buf_next(work);
5801
5802	rsp->StructureSize = cpu_to_le16(4);
5803	rsp->Reserved = 0;
5804	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
5805}
5806
5807static int smb2_rename(struct ksmbd_work *work,
5808		       struct ksmbd_file *fp,
5809		       struct smb2_file_rename_info *file_info,
5810		       struct nls_table *local_nls)
5811{
5812	struct ksmbd_share_config *share = fp->tcon->share_conf;
5813	char *new_name = NULL;
5814	int rc, flags = 0;
5815
5816	ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5817	new_name = smb2_get_name(file_info->FileName,
5818				 le32_to_cpu(file_info->FileNameLength),
5819				 local_nls);
5820	if (IS_ERR(new_name))
5821		return PTR_ERR(new_name);
5822
5823	if (strchr(new_name, ':')) {
5824		int s_type;
5825		char *xattr_stream_name, *stream_name = NULL;
5826		size_t xattr_stream_size;
5827		int len;
5828
5829		rc = parse_stream_name(new_name, &stream_name, &s_type);
5830		if (rc < 0)
5831			goto out;
5832
5833		len = strlen(new_name);
5834		if (len > 0 && new_name[len - 1] != '/') {
5835			pr_err("not allow base filename in rename\n");
5836			rc = -ESHARE;
5837			goto out;
5838		}
5839
5840		rc = ksmbd_vfs_xattr_stream_name(stream_name,
5841						 &xattr_stream_name,
5842						 &xattr_stream_size,
5843						 s_type);
5844		if (rc)
5845			goto out;
5846
5847		rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
5848					&fp->filp->f_path,
5849					xattr_stream_name,
5850					NULL, 0, 0, true);
5851		if (rc < 0) {
5852			pr_err("failed to store stream name in xattr: %d\n",
5853			       rc);
5854			rc = -EINVAL;
5855			goto out;
5856		}
5857
5858		goto out;
5859	}
5860
5861	ksmbd_debug(SMB, "new name %s\n", new_name);
5862	if (ksmbd_share_veto_filename(share, new_name)) {
5863		rc = -ENOENT;
5864		ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5865		goto out;
5866	}
5867
5868	if (!file_info->ReplaceIfExists)
5869		flags = RENAME_NOREPLACE;
5870
5871	rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
5872	if (!rc)
5873		smb_break_all_levII_oplock(work, fp, 0);
5874out:
5875	kfree(new_name);
5876	return rc;
5877}
5878
5879static int smb2_create_link(struct ksmbd_work *work,
5880			    struct ksmbd_share_config *share,
5881			    struct smb2_file_link_info *file_info,
5882			    unsigned int buf_len, struct file *filp,
5883			    struct nls_table *local_nls)
5884{
5885	char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5886	struct path path, parent_path;
5887	bool file_present = false;
5888	int rc;
5889
5890	if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5891			le32_to_cpu(file_info->FileNameLength))
5892		return -EINVAL;
5893
5894	ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5895	pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5896	if (!pathname)
5897		return -ENOMEM;
5898
5899	link_name = smb2_get_name(file_info->FileName,
5900				  le32_to_cpu(file_info->FileNameLength),
5901				  local_nls);
5902	if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5903		rc = -EINVAL;
5904		goto out;
5905	}
5906
5907	ksmbd_debug(SMB, "link name is %s\n", link_name);
5908	target_name = file_path(filp, pathname, PATH_MAX);
5909	if (IS_ERR(target_name)) {
5910		rc = -EINVAL;
5911		goto out;
5912	}
5913
5914	ksmbd_debug(SMB, "target name is %s\n", target_name);
5915	rc = ksmbd_vfs_kern_path_locked(work, link_name, LOOKUP_NO_SYMLINKS,
5916					&parent_path, &path, 0);
5917	if (rc) {
5918		if (rc != -ENOENT)
5919			goto out;
5920	} else
5921		file_present = true;
5922
5923	if (file_info->ReplaceIfExists) {
5924		if (file_present) {
5925			rc = ksmbd_vfs_remove_file(work, &path);
5926			if (rc) {
5927				rc = -EINVAL;
5928				ksmbd_debug(SMB, "cannot delete %s\n",
5929					    link_name);
5930				goto out;
5931			}
5932		}
5933	} else {
5934		if (file_present) {
5935			rc = -EEXIST;
5936			ksmbd_debug(SMB, "link already exists\n");
5937			goto out;
5938		}
5939	}
5940
5941	rc = ksmbd_vfs_link(work, target_name, link_name);
5942	if (rc)
5943		rc = -EINVAL;
5944out:
5945	if (file_present)
5946		ksmbd_vfs_kern_path_unlock(&parent_path, &path);
5947
5948	if (!IS_ERR(link_name))
5949		kfree(link_name);
5950	kfree(pathname);
5951	return rc;
5952}
5953
5954static int set_file_basic_info(struct ksmbd_file *fp,
5955			       struct smb2_file_basic_info *file_info,
5956			       struct ksmbd_share_config *share)
5957{
5958	struct iattr attrs;
5959	struct file *filp;
5960	struct inode *inode;
5961	struct mnt_idmap *idmap;
5962	int rc = 0;
5963
5964	if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5965		return -EACCES;
5966
5967	attrs.ia_valid = 0;
5968	filp = fp->filp;
5969	inode = file_inode(filp);
5970	idmap = file_mnt_idmap(filp);
5971
5972	if (file_info->CreationTime)
5973		fp->create_time = le64_to_cpu(file_info->CreationTime);
5974
5975	if (file_info->LastAccessTime) {
5976		attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5977		attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5978	}
5979
5980	attrs.ia_valid |= ATTR_CTIME;
5981	if (file_info->ChangeTime)
5982		attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5983	else
5984		attrs.ia_ctime = inode_get_ctime(inode);
5985
5986	if (file_info->LastWriteTime) {
5987		attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5988		attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5989	}
5990
5991	if (file_info->Attributes) {
5992		if (!S_ISDIR(inode->i_mode) &&
5993		    file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5994			pr_err("can't change a file to a directory\n");
5995			return -EINVAL;
5996		}
5997
5998		if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5999			fp->f_ci->m_fattr = file_info->Attributes |
6000				(fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
6001	}
6002
6003	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
6004	    (file_info->CreationTime || file_info->Attributes)) {
6005		struct xattr_dos_attrib da = {0};
6006
6007		da.version = 4;
6008		da.itime = fp->itime;
6009		da.create_time = fp->create_time;
6010		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
6011		da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
6012			XATTR_DOSINFO_ITIME;
6013
6014		rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
6015				true);
6016		if (rc)
6017			ksmbd_debug(SMB,
6018				    "failed to restore file attribute in EA\n");
6019		rc = 0;
6020	}
6021
6022	if (attrs.ia_valid) {
6023		struct dentry *dentry = filp->f_path.dentry;
6024		struct inode *inode = d_inode(dentry);
6025
6026		if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
6027			return -EACCES;
6028
6029		inode_lock(inode);
6030		inode_set_ctime_to_ts(inode, attrs.ia_ctime);
6031		attrs.ia_valid &= ~ATTR_CTIME;
6032		rc = notify_change(idmap, dentry, &attrs, NULL);
6033		inode_unlock(inode);
6034	}
6035	return rc;
6036}
6037
6038static int set_file_allocation_info(struct ksmbd_work *work,
6039				    struct ksmbd_file *fp,
6040				    struct smb2_file_alloc_info *file_alloc_info)
6041{
6042	/*
6043	 * TODO : It's working fine only when store dos attributes
6044	 * is not yes. need to implement a logic which works
6045	 * properly with any smb.conf option
6046	 */
6047
6048	loff_t alloc_blks;
6049	struct inode *inode;
6050	struct kstat stat;
6051	int rc;
6052
6053	if (!(fp->daccess & FILE_WRITE_DATA_LE))
6054		return -EACCES;
6055
6056	rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6057			 AT_STATX_SYNC_AS_STAT);
6058	if (rc)
6059		return rc;
6060
6061	alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
6062	inode = file_inode(fp->filp);
6063
6064	if (alloc_blks > stat.blocks) {
6065		smb_break_all_levII_oplock(work, fp, 1);
6066		rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
6067				   alloc_blks * 512);
6068		if (rc && rc != -EOPNOTSUPP) {
6069			pr_err("vfs_fallocate is failed : %d\n", rc);
6070			return rc;
6071		}
6072	} else if (alloc_blks < stat.blocks) {
6073		loff_t size;
6074
6075		/*
6076		 * Allocation size could be smaller than original one
6077		 * which means allocated blocks in file should be
6078		 * deallocated. use truncate to cut out it, but inode
6079		 * size is also updated with truncate offset.
6080		 * inode size is retained by backup inode size.
6081		 */
6082		size = i_size_read(inode);
6083		rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
6084		if (rc) {
6085			pr_err("truncate failed!, err %d\n", rc);
6086			return rc;
6087		}
6088		if (size < alloc_blks * 512)
6089			i_size_write(inode, size);
6090	}
6091	return 0;
6092}
6093
6094static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6095				struct smb2_file_eof_info *file_eof_info)
6096{
6097	loff_t newsize;
6098	struct inode *inode;
6099	int rc;
6100
6101	if (!(fp->daccess & FILE_WRITE_DATA_LE))
6102		return -EACCES;
6103
6104	newsize = le64_to_cpu(file_eof_info->EndOfFile);
6105	inode = file_inode(fp->filp);
6106
6107	/*
6108	 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
6109	 * on FAT32 shared device, truncate execution time is too long
6110	 * and network error could cause from windows client. because
6111	 * truncate of some filesystem like FAT32 fill zero data in
6112	 * truncated range.
6113	 */
6114	if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
6115		ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
6116		rc = ksmbd_vfs_truncate(work, fp, newsize);
6117		if (rc) {
6118			ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
6119			if (rc != -EAGAIN)
6120				rc = -EBADF;
6121			return rc;
6122		}
6123	}
6124	return 0;
6125}
6126
6127static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6128			   struct smb2_file_rename_info *rename_info,
6129			   unsigned int buf_len)
6130{
6131	if (!(fp->daccess & FILE_DELETE_LE)) {
6132		pr_err("no right to delete : 0x%x\n", fp->daccess);
6133		return -EACCES;
6134	}
6135
6136	if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
6137			le32_to_cpu(rename_info->FileNameLength))
6138		return -EINVAL;
6139
6140	if (!le32_to_cpu(rename_info->FileNameLength))
6141		return -EINVAL;
6142
6143	return smb2_rename(work, fp, rename_info, work->conn->local_nls);
6144}
6145
6146static int set_file_disposition_info(struct ksmbd_file *fp,
6147				     struct smb2_file_disposition_info *file_info)
6148{
6149	struct inode *inode;
6150
6151	if (!(fp->daccess & FILE_DELETE_LE)) {
6152		pr_err("no right to delete : 0x%x\n", fp->daccess);
6153		return -EACCES;
6154	}
6155
6156	inode = file_inode(fp->filp);
6157	if (file_info->DeletePending) {
6158		if (S_ISDIR(inode->i_mode) &&
6159		    ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
6160			return -EBUSY;
6161		ksmbd_set_inode_pending_delete(fp);
6162	} else {
6163		ksmbd_clear_inode_pending_delete(fp);
6164	}
6165	return 0;
6166}
6167
6168static int set_file_position_info(struct ksmbd_file *fp,
6169				  struct smb2_file_pos_info *file_info)
6170{
6171	loff_t current_byte_offset;
6172	unsigned long sector_size;
6173	struct inode *inode;
6174
6175	inode = file_inode(fp->filp);
6176	current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
6177	sector_size = inode->i_sb->s_blocksize;
6178
6179	if (current_byte_offset < 0 ||
6180	    (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
6181	     current_byte_offset & (sector_size - 1))) {
6182		pr_err("CurrentByteOffset is not valid : %llu\n",
6183		       current_byte_offset);
6184		return -EINVAL;
6185	}
6186
6187	fp->filp->f_pos = current_byte_offset;
6188	return 0;
6189}
6190
6191static int set_file_mode_info(struct ksmbd_file *fp,
6192			      struct smb2_file_mode_info *file_info)
6193{
6194	__le32 mode;
6195
6196	mode = file_info->Mode;
6197
6198	if ((mode & ~FILE_MODE_INFO_MASK)) {
6199		pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
6200		return -EINVAL;
6201	}
6202
6203	/*
6204	 * TODO : need to implement consideration for
6205	 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
6206	 */
6207	ksmbd_vfs_set_fadvise(fp->filp, mode);
6208	fp->coption = mode;
6209	return 0;
6210}
6211
6212/**
6213 * smb2_set_info_file() - handler for smb2 set info command
6214 * @work:	smb work containing set info command buffer
6215 * @fp:		ksmbd_file pointer
6216 * @req:	request buffer pointer
6217 * @share:	ksmbd_share_config pointer
6218 *
6219 * Return:	0 on success, otherwise error
6220 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
6221 */
6222static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
6223			      struct smb2_set_info_req *req,
6224			      struct ksmbd_share_config *share)
6225{
6226	unsigned int buf_len = le32_to_cpu(req->BufferLength);
6227	char *buffer = (char *)req + le16_to_cpu(req->BufferOffset);
6228
6229	switch (req->FileInfoClass) {
6230	case FILE_BASIC_INFORMATION:
6231	{
6232		if (buf_len < sizeof(struct smb2_file_basic_info))
6233			return -EINVAL;
6234
6235		return set_file_basic_info(fp, (struct smb2_file_basic_info *)buffer, share);
6236	}
6237	case FILE_ALLOCATION_INFORMATION:
6238	{
6239		if (buf_len < sizeof(struct smb2_file_alloc_info))
6240			return -EINVAL;
6241
6242		return set_file_allocation_info(work, fp,
6243						(struct smb2_file_alloc_info *)buffer);
6244	}
6245	case FILE_END_OF_FILE_INFORMATION:
6246	{
6247		if (buf_len < sizeof(struct smb2_file_eof_info))
6248			return -EINVAL;
6249
6250		return set_end_of_file_info(work, fp,
6251					    (struct smb2_file_eof_info *)buffer);
6252	}
6253	case FILE_RENAME_INFORMATION:
6254	{
6255		if (buf_len < sizeof(struct smb2_file_rename_info))
6256			return -EINVAL;
6257
6258		return set_rename_info(work, fp,
6259				       (struct smb2_file_rename_info *)buffer,
6260				       buf_len);
6261	}
6262	case FILE_LINK_INFORMATION:
6263	{
6264		if (buf_len < sizeof(struct smb2_file_link_info))
6265			return -EINVAL;
6266
6267		return smb2_create_link(work, work->tcon->share_conf,
6268					(struct smb2_file_link_info *)buffer,
6269					buf_len, fp->filp,
6270					work->conn->local_nls);
6271	}
6272	case FILE_DISPOSITION_INFORMATION:
6273	{
6274		if (buf_len < sizeof(struct smb2_file_disposition_info))
6275			return -EINVAL;
6276
6277		return set_file_disposition_info(fp,
6278						 (struct smb2_file_disposition_info *)buffer);
6279	}
6280	case FILE_FULL_EA_INFORMATION:
6281	{
6282		if (!(fp->daccess & FILE_WRITE_EA_LE)) {
6283			pr_err("Not permitted to write ext  attr: 0x%x\n",
6284			       fp->daccess);
6285			return -EACCES;
6286		}
6287
6288		if (buf_len < sizeof(struct smb2_ea_info))
6289			return -EINVAL;
6290
6291		return smb2_set_ea((struct smb2_ea_info *)buffer,
6292				   buf_len, &fp->filp->f_path, true);
6293	}
6294	case FILE_POSITION_INFORMATION:
6295	{
6296		if (buf_len < sizeof(struct smb2_file_pos_info))
6297			return -EINVAL;
6298
6299		return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
6300	}
6301	case FILE_MODE_INFORMATION:
6302	{
6303		if (buf_len < sizeof(struct smb2_file_mode_info))
6304			return -EINVAL;
6305
6306		return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
6307	}
6308	}
6309
6310	pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6311	return -EOPNOTSUPP;
6312}
6313
6314static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6315			     char *buffer, int buf_len)
6316{
6317	struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6318
6319	fp->saccess |= FILE_SHARE_DELETE_LE;
6320
6321	return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6322			buf_len, false, true);
6323}
6324
6325/**
6326 * smb2_set_info() - handler for smb2 set info command handler
6327 * @work:	smb work containing set info request buffer
6328 *
6329 * Return:	0 on success, otherwise error
6330 */
6331int smb2_set_info(struct ksmbd_work *work)
6332{
6333	struct smb2_set_info_req *req;
6334	struct smb2_set_info_rsp *rsp;
6335	struct ksmbd_file *fp = NULL;
6336	int rc = 0;
6337	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6338
6339	ksmbd_debug(SMB, "Received set info request\n");
6340
6341	if (work->next_smb2_rcv_hdr_off) {
6342		req = ksmbd_req_buf_next(work);
6343		rsp = ksmbd_resp_buf_next(work);
6344		if (!has_file_id(req->VolatileFileId)) {
6345			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6346				    work->compound_fid);
6347			id = work->compound_fid;
6348			pid = work->compound_pfid;
6349		}
6350	} else {
6351		req = smb2_get_msg(work->request_buf);
6352		rsp = smb2_get_msg(work->response_buf);
6353	}
6354
6355	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6356		ksmbd_debug(SMB, "User does not have write permission\n");
6357		pr_err("User does not have write permission\n");
6358		rc = -EACCES;
6359		goto err_out;
6360	}
6361
6362	if (!has_file_id(id)) {
6363		id = req->VolatileFileId;
6364		pid = req->PersistentFileId;
6365	}
6366
6367	fp = ksmbd_lookup_fd_slow(work, id, pid);
6368	if (!fp) {
6369		ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6370		rc = -ENOENT;
6371		goto err_out;
6372	}
6373
6374	switch (req->InfoType) {
6375	case SMB2_O_INFO_FILE:
6376		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6377		rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6378		break;
6379	case SMB2_O_INFO_SECURITY:
6380		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6381		if (ksmbd_override_fsids(work)) {
6382			rc = -ENOMEM;
6383			goto err_out;
6384		}
6385		rc = smb2_set_info_sec(fp,
6386				       le32_to_cpu(req->AdditionalInformation),
6387				       (char *)req + le16_to_cpu(req->BufferOffset),
6388				       le32_to_cpu(req->BufferLength));
6389		ksmbd_revert_fsids(work);
6390		break;
6391	default:
6392		rc = -EOPNOTSUPP;
6393	}
6394
6395	if (rc < 0)
6396		goto err_out;
6397
6398	rsp->StructureSize = cpu_to_le16(2);
6399	rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6400			       sizeof(struct smb2_set_info_rsp));
6401	if (rc)
6402		goto err_out;
6403	ksmbd_fd_put(work, fp);
6404	return 0;
6405
6406err_out:
6407	if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6408		rsp->hdr.Status = STATUS_ACCESS_DENIED;
6409	else if (rc == -EINVAL)
6410		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6411	else if (rc == -ESHARE)
6412		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6413	else if (rc == -ENOENT)
6414		rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6415	else if (rc == -EBUSY || rc == -ENOTEMPTY)
6416		rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6417	else if (rc == -EAGAIN)
6418		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6419	else if (rc == -EBADF || rc == -ESTALE)
6420		rsp->hdr.Status = STATUS_INVALID_HANDLE;
6421	else if (rc == -EEXIST)
6422		rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6423	else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6424		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6425	smb2_set_err_rsp(work);
6426	ksmbd_fd_put(work, fp);
6427	ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6428	return rc;
6429}
6430
6431/**
6432 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6433 * @work:	smb work containing read IPC pipe command buffer
6434 *
6435 * Return:	0 on success, otherwise error
6436 */
6437static noinline int smb2_read_pipe(struct ksmbd_work *work)
6438{
6439	int nbytes = 0, err;
6440	u64 id;
6441	struct ksmbd_rpc_command *rpc_resp;
6442	struct smb2_read_req *req;
6443	struct smb2_read_rsp *rsp;
6444
6445	WORK_BUFFERS(work, req, rsp);
6446
6447	id = req->VolatileFileId;
6448
6449	rpc_resp = ksmbd_rpc_read(work->sess, id);
6450	if (rpc_resp) {
6451		void *aux_payload_buf;
6452
6453		if (rpc_resp->flags != KSMBD_RPC_OK) {
6454			err = -EINVAL;
6455			goto out;
6456		}
6457
6458		aux_payload_buf =
6459			kvmalloc(rpc_resp->payload_sz, GFP_KERNEL);
6460		if (!aux_payload_buf) {
6461			err = -ENOMEM;
6462			goto out;
6463		}
6464
6465		memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
6466
6467		nbytes = rpc_resp->payload_sz;
6468		err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6469					     offsetof(struct smb2_read_rsp, Buffer),
6470					     aux_payload_buf, nbytes);
6471		if (err) {
6472			kvfree(aux_payload_buf);
6473			goto out;
6474		}
6475		kvfree(rpc_resp);
6476	} else {
6477		err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6478					offsetof(struct smb2_read_rsp, Buffer));
6479		if (err)
6480			goto out;
6481	}
6482
6483	rsp->StructureSize = cpu_to_le16(17);
6484	rsp->DataOffset = 80;
6485	rsp->Reserved = 0;
6486	rsp->DataLength = cpu_to_le32(nbytes);
6487	rsp->DataRemaining = 0;
6488	rsp->Flags = 0;
6489	return 0;
6490
6491out:
6492	rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6493	smb2_set_err_rsp(work);
6494	kvfree(rpc_resp);
6495	return err;
6496}
6497
6498static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6499					struct smb2_buffer_desc_v1 *desc,
6500					__le32 Channel,
6501					__le16 ChannelInfoLength)
6502{
6503	unsigned int i, ch_count;
6504
6505	if (work->conn->dialect == SMB30_PROT_ID &&
6506	    Channel != SMB2_CHANNEL_RDMA_V1)
6507		return -EINVAL;
6508
6509	ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6510	if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6511		for (i = 0; i < ch_count; i++) {
6512			pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6513				i,
6514				le32_to_cpu(desc[i].token),
6515				le32_to_cpu(desc[i].length));
6516		}
6517	}
6518	if (!ch_count)
6519		return -EINVAL;
6520
6521	work->need_invalidate_rkey =
6522		(Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6523	if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6524		work->remote_key = le32_to_cpu(desc->token);
6525	return 0;
6526}
6527
6528static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6529				      struct smb2_read_req *req, void *data_buf,
6530				      size_t length)
6531{
6532	int err;
6533
6534	err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6535				    (struct smb2_buffer_desc_v1 *)
6536				    ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6537				    le16_to_cpu(req->ReadChannelInfoLength));
6538	if (err)
6539		return err;
6540
6541	return length;
6542}
6543
6544/**
6545 * smb2_read() - handler for smb2 read from file
6546 * @work:	smb work containing read command buffer
6547 *
6548 * Return:	0 on success, otherwise error
6549 */
6550int smb2_read(struct ksmbd_work *work)
6551{
6552	struct ksmbd_conn *conn = work->conn;
6553	struct smb2_read_req *req;
6554	struct smb2_read_rsp *rsp;
6555	struct ksmbd_file *fp = NULL;
6556	loff_t offset;
6557	size_t length, mincount;
6558	ssize_t nbytes = 0, remain_bytes = 0;
6559	int err = 0;
6560	bool is_rdma_channel = false;
6561	unsigned int max_read_size = conn->vals->max_read_size;
6562	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6563	void *aux_payload_buf;
6564
6565	if (test_share_config_flag(work->tcon->share_conf,
6566				   KSMBD_SHARE_FLAG_PIPE)) {
6567		ksmbd_debug(SMB, "IPC pipe read request\n");
6568		return smb2_read_pipe(work);
6569	}
6570
6571	if (work->next_smb2_rcv_hdr_off) {
6572		req = ksmbd_req_buf_next(work);
6573		rsp = ksmbd_resp_buf_next(work);
6574		if (!has_file_id(req->VolatileFileId)) {
6575			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6576					work->compound_fid);
6577			id = work->compound_fid;
6578			pid = work->compound_pfid;
6579		}
6580	} else {
6581		req = smb2_get_msg(work->request_buf);
6582		rsp = smb2_get_msg(work->response_buf);
6583	}
6584
6585	if (!has_file_id(id)) {
6586		id = req->VolatileFileId;
6587		pid = req->PersistentFileId;
6588	}
6589
6590	if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6591	    req->Channel == SMB2_CHANNEL_RDMA_V1) {
6592		is_rdma_channel = true;
6593		max_read_size = get_smbd_max_read_write_size();
6594	}
6595
6596	if (is_rdma_channel == true) {
6597		unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6598
6599		if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6600			err = -EINVAL;
6601			goto out;
6602		}
6603		err = smb2_set_remote_key_for_rdma(work,
6604						   (struct smb2_buffer_desc_v1 *)
6605						   ((char *)req + ch_offset),
6606						   req->Channel,
6607						   req->ReadChannelInfoLength);
6608		if (err)
6609			goto out;
6610	}
6611
6612	fp = ksmbd_lookup_fd_slow(work, id, pid);
6613	if (!fp) {
6614		err = -ENOENT;
6615		goto out;
6616	}
6617
6618	if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6619		pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6620		err = -EACCES;
6621		goto out;
6622	}
6623
6624	offset = le64_to_cpu(req->Offset);
6625	length = le32_to_cpu(req->Length);
6626	mincount = le32_to_cpu(req->MinimumCount);
6627
6628	if (length > max_read_size) {
6629		ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6630			    max_read_size);
6631		err = -EINVAL;
6632		goto out;
6633	}
6634
6635	ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6636		    fp->filp, offset, length);
6637
6638	aux_payload_buf = kvzalloc(length, GFP_KERNEL);
6639	if (!aux_payload_buf) {
6640		err = -ENOMEM;
6641		goto out;
6642	}
6643
6644	nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
6645	if (nbytes < 0) {
6646		err = nbytes;
6647		goto out;
6648	}
6649
6650	if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6651		kvfree(aux_payload_buf);
6652		rsp->hdr.Status = STATUS_END_OF_FILE;
6653		smb2_set_err_rsp(work);
6654		ksmbd_fd_put(work, fp);
6655		return 0;
6656	}
6657
6658	ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6659		    nbytes, offset, mincount);
6660
6661	if (is_rdma_channel == true) {
6662		/* write data to the client using rdma channel */
6663		remain_bytes = smb2_read_rdma_channel(work, req,
6664						      aux_payload_buf,
6665						      nbytes);
6666		kvfree(aux_payload_buf);
6667		aux_payload_buf = NULL;
6668		nbytes = 0;
6669		if (remain_bytes < 0) {
6670			err = (int)remain_bytes;
6671			goto out;
6672		}
6673	}
6674
6675	rsp->StructureSize = cpu_to_le16(17);
6676	rsp->DataOffset = 80;
6677	rsp->Reserved = 0;
6678	rsp->DataLength = cpu_to_le32(nbytes);
6679	rsp->DataRemaining = cpu_to_le32(remain_bytes);
6680	rsp->Flags = 0;
6681	err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6682				     offsetof(struct smb2_read_rsp, Buffer),
6683				     aux_payload_buf, nbytes);
6684	if (err) {
6685		kvfree(aux_payload_buf);
6686		goto out;
6687	}
6688	ksmbd_fd_put(work, fp);
6689	return 0;
6690
6691out:
6692	if (err) {
6693		if (err == -EISDIR)
6694			rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6695		else if (err == -EAGAIN)
6696			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6697		else if (err == -ENOENT)
6698			rsp->hdr.Status = STATUS_FILE_CLOSED;
6699		else if (err == -EACCES)
6700			rsp->hdr.Status = STATUS_ACCESS_DENIED;
6701		else if (err == -ESHARE)
6702			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6703		else if (err == -EINVAL)
6704			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6705		else
6706			rsp->hdr.Status = STATUS_INVALID_HANDLE;
6707
6708		smb2_set_err_rsp(work);
6709	}
6710	ksmbd_fd_put(work, fp);
6711	return err;
6712}
6713
6714/**
6715 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6716 * @work:	smb work containing write IPC pipe command buffer
6717 *
6718 * Return:	0 on success, otherwise error
6719 */
6720static noinline int smb2_write_pipe(struct ksmbd_work *work)
6721{
6722	struct smb2_write_req *req;
6723	struct smb2_write_rsp *rsp;
6724	struct ksmbd_rpc_command *rpc_resp;
6725	u64 id = 0;
6726	int err = 0, ret = 0;
6727	char *data_buf;
6728	size_t length;
6729
6730	WORK_BUFFERS(work, req, rsp);
6731
6732	length = le32_to_cpu(req->Length);
6733	id = req->VolatileFileId;
6734
6735	if ((u64)le16_to_cpu(req->DataOffset) + length >
6736	    get_rfc1002_len(work->request_buf)) {
6737		pr_err("invalid write data offset %u, smb_len %u\n",
6738		       le16_to_cpu(req->DataOffset),
6739		       get_rfc1002_len(work->request_buf));
6740		err = -EINVAL;
6741		goto out;
6742	}
6743
6744	data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6745			   le16_to_cpu(req->DataOffset));
6746
6747	rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6748	if (rpc_resp) {
6749		if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6750			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6751			kvfree(rpc_resp);
6752			smb2_set_err_rsp(work);
6753			return -EOPNOTSUPP;
6754		}
6755		if (rpc_resp->flags != KSMBD_RPC_OK) {
6756			rsp->hdr.Status = STATUS_INVALID_HANDLE;
6757			smb2_set_err_rsp(work);
6758			kvfree(rpc_resp);
6759			return ret;
6760		}
6761		kvfree(rpc_resp);
6762	}
6763
6764	rsp->StructureSize = cpu_to_le16(17);
6765	rsp->DataOffset = 0;
6766	rsp->Reserved = 0;
6767	rsp->DataLength = cpu_to_le32(length);
6768	rsp->DataRemaining = 0;
6769	rsp->Reserved2 = 0;
6770	err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6771				offsetof(struct smb2_write_rsp, Buffer));
6772out:
6773	if (err) {
6774		rsp->hdr.Status = STATUS_INVALID_HANDLE;
6775		smb2_set_err_rsp(work);
6776	}
6777
6778	return err;
6779}
6780
6781static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6782				       struct smb2_write_req *req,
6783				       struct ksmbd_file *fp,
6784				       loff_t offset, size_t length, bool sync)
6785{
6786	char *data_buf;
6787	int ret;
6788	ssize_t nbytes;
6789
6790	data_buf = kvzalloc(length, GFP_KERNEL);
6791	if (!data_buf)
6792		return -ENOMEM;
6793
6794	ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6795				   (struct smb2_buffer_desc_v1 *)
6796				   ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6797				   le16_to_cpu(req->WriteChannelInfoLength));
6798	if (ret < 0) {
6799		kvfree(data_buf);
6800		return ret;
6801	}
6802
6803	ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6804	kvfree(data_buf);
6805	if (ret < 0)
6806		return ret;
6807
6808	return nbytes;
6809}
6810
6811/**
6812 * smb2_write() - handler for smb2 write from file
6813 * @work:	smb work containing write command buffer
6814 *
6815 * Return:	0 on success, otherwise error
6816 */
6817int smb2_write(struct ksmbd_work *work)
6818{
6819	struct smb2_write_req *req;
6820	struct smb2_write_rsp *rsp;
6821	struct ksmbd_file *fp = NULL;
6822	loff_t offset;
6823	size_t length;
6824	ssize_t nbytes;
6825	char *data_buf;
6826	bool writethrough = false, is_rdma_channel = false;
6827	int err = 0;
6828	unsigned int max_write_size = work->conn->vals->max_write_size;
6829
6830	WORK_BUFFERS(work, req, rsp);
6831
6832	if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6833		ksmbd_debug(SMB, "IPC pipe write request\n");
6834		return smb2_write_pipe(work);
6835	}
6836
6837	offset = le64_to_cpu(req->Offset);
6838	length = le32_to_cpu(req->Length);
6839
6840	if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6841	    req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6842		is_rdma_channel = true;
6843		max_write_size = get_smbd_max_read_write_size();
6844		length = le32_to_cpu(req->RemainingBytes);
6845	}
6846
6847	if (is_rdma_channel == true) {
6848		unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6849
6850		if (req->Length != 0 || req->DataOffset != 0 ||
6851		    ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6852			err = -EINVAL;
6853			goto out;
6854		}
6855		err = smb2_set_remote_key_for_rdma(work,
6856						   (struct smb2_buffer_desc_v1 *)
6857						   ((char *)req + ch_offset),
6858						   req->Channel,
6859						   req->WriteChannelInfoLength);
6860		if (err)
6861			goto out;
6862	}
6863
6864	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6865		ksmbd_debug(SMB, "User does not have write permission\n");
6866		err = -EACCES;
6867		goto out;
6868	}
6869
6870	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6871	if (!fp) {
6872		err = -ENOENT;
6873		goto out;
6874	}
6875
6876	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6877		pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6878		err = -EACCES;
6879		goto out;
6880	}
6881
6882	if (length > max_write_size) {
6883		ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6884			    max_write_size);
6885		err = -EINVAL;
6886		goto out;
6887	}
6888
6889	ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6890	if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6891		writethrough = true;
6892
6893	if (is_rdma_channel == false) {
6894		if (le16_to_cpu(req->DataOffset) <
6895		    offsetof(struct smb2_write_req, Buffer)) {
6896			err = -EINVAL;
6897			goto out;
6898		}
6899
6900		data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6901				    le16_to_cpu(req->DataOffset));
6902
6903		ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6904			    fp->filp, offset, length);
6905		err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6906				      writethrough, &nbytes);
6907		if (err < 0)
6908			goto out;
6909	} else {
6910		/* read data from the client using rdma channel, and
6911		 * write the data.
6912		 */
6913		nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6914						 writethrough);
6915		if (nbytes < 0) {
6916			err = (int)nbytes;
6917			goto out;
6918		}
6919	}
6920
6921	rsp->StructureSize = cpu_to_le16(17);
6922	rsp->DataOffset = 0;
6923	rsp->Reserved = 0;
6924	rsp->DataLength = cpu_to_le32(nbytes);
6925	rsp->DataRemaining = 0;
6926	rsp->Reserved2 = 0;
6927	err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
6928	if (err)
6929		goto out;
6930	ksmbd_fd_put(work, fp);
6931	return 0;
6932
6933out:
6934	if (err == -EAGAIN)
6935		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6936	else if (err == -ENOSPC || err == -EFBIG)
6937		rsp->hdr.Status = STATUS_DISK_FULL;
6938	else if (err == -ENOENT)
6939		rsp->hdr.Status = STATUS_FILE_CLOSED;
6940	else if (err == -EACCES)
6941		rsp->hdr.Status = STATUS_ACCESS_DENIED;
6942	else if (err == -ESHARE)
6943		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6944	else if (err == -EINVAL)
6945		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6946	else
6947		rsp->hdr.Status = STATUS_INVALID_HANDLE;
6948
6949	smb2_set_err_rsp(work);
6950	ksmbd_fd_put(work, fp);
6951	return err;
6952}
6953
6954/**
6955 * smb2_flush() - handler for smb2 flush file - fsync
6956 * @work:	smb work containing flush command buffer
6957 *
6958 * Return:	0 on success, otherwise error
6959 */
6960int smb2_flush(struct ksmbd_work *work)
6961{
6962	struct smb2_flush_req *req;
6963	struct smb2_flush_rsp *rsp;
6964	int err;
6965
6966	WORK_BUFFERS(work, req, rsp);
6967
6968	ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6969
6970	err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6971	if (err)
6972		goto out;
6973
6974	rsp->StructureSize = cpu_to_le16(4);
6975	rsp->Reserved = 0;
6976	return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
6977
6978out:
6979	rsp->hdr.Status = STATUS_INVALID_HANDLE;
6980	smb2_set_err_rsp(work);
6981	return err;
6982}
6983
6984/**
6985 * smb2_cancel() - handler for smb2 cancel command
6986 * @work:	smb work containing cancel command buffer
6987 *
6988 * Return:	0 on success, otherwise error
6989 */
6990int smb2_cancel(struct ksmbd_work *work)
6991{
6992	struct ksmbd_conn *conn = work->conn;
6993	struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6994	struct smb2_hdr *chdr;
6995	struct ksmbd_work *iter;
6996	struct list_head *command_list;
6997
6998	if (work->next_smb2_rcv_hdr_off)
6999		hdr = ksmbd_resp_buf_next(work);
7000
7001	ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
7002		    hdr->MessageId, hdr->Flags);
7003
7004	if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
7005		command_list = &conn->async_requests;
7006
7007		spin_lock(&conn->request_lock);
7008		list_for_each_entry(iter, command_list,
7009				    async_request_entry) {
7010			chdr = smb2_get_msg(iter->request_buf);
7011
7012			if (iter->async_id !=
7013			    le64_to_cpu(hdr->Id.AsyncId))
7014				continue;
7015
7016			ksmbd_debug(SMB,
7017				    "smb2 with AsyncId %llu cancelled command = 0x%x\n",
7018				    le64_to_cpu(hdr->Id.AsyncId),
7019				    le16_to_cpu(chdr->Command));
7020			iter->state = KSMBD_WORK_CANCELLED;
7021			if (iter->cancel_fn)
7022				iter->cancel_fn(iter->cancel_argv);
7023			break;
7024		}
7025		spin_unlock(&conn->request_lock);
7026	} else {
7027		command_list = &conn->requests;
7028
7029		spin_lock(&conn->request_lock);
7030		list_for_each_entry(iter, command_list, request_entry) {
7031			chdr = smb2_get_msg(iter->request_buf);
7032
7033			if (chdr->MessageId != hdr->MessageId ||
7034			    iter == work)
7035				continue;
7036
7037			ksmbd_debug(SMB,
7038				    "smb2 with mid %llu cancelled command = 0x%x\n",
7039				    le64_to_cpu(hdr->MessageId),
7040				    le16_to_cpu(chdr->Command));
7041			iter->state = KSMBD_WORK_CANCELLED;
7042			break;
7043		}
7044		spin_unlock(&conn->request_lock);
7045	}
7046
7047	/* For SMB2_CANCEL command itself send no response*/
7048	work->send_no_response = 1;
7049	return 0;
7050}
7051
7052struct file_lock *smb_flock_init(struct file *f)
7053{
7054	struct file_lock *fl;
7055
7056	fl = locks_alloc_lock();
7057	if (!fl)
7058		goto out;
7059
7060	locks_init_lock(fl);
7061
7062	fl->c.flc_owner = f;
7063	fl->c.flc_pid = current->tgid;
7064	fl->c.flc_file = f;
7065	fl->c.flc_flags = FL_POSIX;
7066	fl->fl_ops = NULL;
7067	fl->fl_lmops = NULL;
7068
7069out:
7070	return fl;
7071}
7072
7073static int smb2_set_flock_flags(struct file_lock *flock, int flags)
7074{
7075	int cmd = -EINVAL;
7076
7077	/* Checking for wrong flag combination during lock request*/
7078	switch (flags) {
7079	case SMB2_LOCKFLAG_SHARED:
7080		ksmbd_debug(SMB, "received shared request\n");
7081		cmd = F_SETLKW;
7082		flock->c.flc_type = F_RDLCK;
7083		flock->c.flc_flags |= FL_SLEEP;
7084		break;
7085	case SMB2_LOCKFLAG_EXCLUSIVE:
7086		ksmbd_debug(SMB, "received exclusive request\n");
7087		cmd = F_SETLKW;
7088		flock->c.flc_type = F_WRLCK;
7089		flock->c.flc_flags |= FL_SLEEP;
7090		break;
7091	case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7092		ksmbd_debug(SMB,
7093			    "received shared & fail immediately request\n");
7094		cmd = F_SETLK;
7095		flock->c.flc_type = F_RDLCK;
7096		break;
7097	case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7098		ksmbd_debug(SMB,
7099			    "received exclusive & fail immediately request\n");
7100		cmd = F_SETLK;
7101		flock->c.flc_type = F_WRLCK;
7102		break;
7103	case SMB2_LOCKFLAG_UNLOCK:
7104		ksmbd_debug(SMB, "received unlock request\n");
7105		flock->c.flc_type = F_UNLCK;
7106		cmd = F_SETLK;
7107		break;
7108	}
7109
7110	return cmd;
7111}
7112
7113static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
7114					 unsigned int cmd, int flags,
7115					 struct list_head *lock_list)
7116{
7117	struct ksmbd_lock *lock;
7118
7119	lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
7120	if (!lock)
7121		return NULL;
7122
7123	lock->cmd = cmd;
7124	lock->fl = flock;
7125	lock->start = flock->fl_start;
7126	lock->end = flock->fl_end;
7127	lock->flags = flags;
7128	if (lock->start == lock->end)
7129		lock->zero_len = 1;
7130	INIT_LIST_HEAD(&lock->clist);
7131	INIT_LIST_HEAD(&lock->flist);
7132	INIT_LIST_HEAD(&lock->llist);
7133	list_add_tail(&lock->llist, lock_list);
7134
7135	return lock;
7136}
7137
7138static void smb2_remove_blocked_lock(void **argv)
7139{
7140	struct file_lock *flock = (struct file_lock *)argv[0];
7141
7142	ksmbd_vfs_posix_lock_unblock(flock);
7143	locks_wake_up(flock);
7144}
7145
7146static inline bool lock_defer_pending(struct file_lock *fl)
7147{
7148	/* check pending lock waiters */
7149	return waitqueue_active(&fl->c.flc_wait);
7150}
7151
7152/**
7153 * smb2_lock() - handler for smb2 file lock command
7154 * @work:	smb work containing lock command buffer
7155 *
7156 * Return:	0 on success, otherwise error
7157 */
7158int smb2_lock(struct ksmbd_work *work)
7159{
7160	struct smb2_lock_req *req;
7161	struct smb2_lock_rsp *rsp;
7162	struct smb2_lock_element *lock_ele;
7163	struct ksmbd_file *fp = NULL;
7164	struct file_lock *flock = NULL;
7165	struct file *filp = NULL;
7166	int lock_count;
7167	int flags = 0;
7168	int cmd = 0;
7169	int err = -EIO, i, rc = 0;
7170	u64 lock_start, lock_length;
7171	struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
7172	struct ksmbd_conn *conn;
7173	int nolock = 0;
7174	LIST_HEAD(lock_list);
7175	LIST_HEAD(rollback_list);
7176	int prior_lock = 0;
7177
7178	WORK_BUFFERS(work, req, rsp);
7179
7180	ksmbd_debug(SMB, "Received lock request\n");
7181	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7182	if (!fp) {
7183		ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
7184		err = -ENOENT;
7185		goto out2;
7186	}
7187
7188	filp = fp->filp;
7189	lock_count = le16_to_cpu(req->LockCount);
7190	lock_ele = req->locks;
7191
7192	ksmbd_debug(SMB, "lock count is %d\n", lock_count);
7193	if (!lock_count) {
7194		err = -EINVAL;
7195		goto out2;
7196	}
7197
7198	for (i = 0; i < lock_count; i++) {
7199		flags = le32_to_cpu(lock_ele[i].Flags);
7200
7201		flock = smb_flock_init(filp);
7202		if (!flock)
7203			goto out;
7204
7205		cmd = smb2_set_flock_flags(flock, flags);
7206
7207		lock_start = le64_to_cpu(lock_ele[i].Offset);
7208		lock_length = le64_to_cpu(lock_ele[i].Length);
7209		if (lock_start > U64_MAX - lock_length) {
7210			pr_err("Invalid lock range requested\n");
7211			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7212			locks_free_lock(flock);
7213			goto out;
7214		}
7215
7216		if (lock_start > OFFSET_MAX)
7217			flock->fl_start = OFFSET_MAX;
7218		else
7219			flock->fl_start = lock_start;
7220
7221		lock_length = le64_to_cpu(lock_ele[i].Length);
7222		if (lock_length > OFFSET_MAX - flock->fl_start)
7223			lock_length = OFFSET_MAX - flock->fl_start;
7224
7225		flock->fl_end = flock->fl_start + lock_length;
7226
7227		if (flock->fl_end < flock->fl_start) {
7228			ksmbd_debug(SMB,
7229				    "the end offset(%llx) is smaller than the start offset(%llx)\n",
7230				    flock->fl_end, flock->fl_start);
7231			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7232			locks_free_lock(flock);
7233			goto out;
7234		}
7235
7236		/* Check conflict locks in one request */
7237		list_for_each_entry(cmp_lock, &lock_list, llist) {
7238			if (cmp_lock->fl->fl_start <= flock->fl_start &&
7239			    cmp_lock->fl->fl_end >= flock->fl_end) {
7240				if (cmp_lock->fl->c.flc_type != F_UNLCK &&
7241				    flock->c.flc_type != F_UNLCK) {
7242					pr_err("conflict two locks in one request\n");
7243					err = -EINVAL;
7244					locks_free_lock(flock);
7245					goto out;
7246				}
7247			}
7248		}
7249
7250		smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
7251		if (!smb_lock) {
7252			err = -EINVAL;
7253			locks_free_lock(flock);
7254			goto out;
7255		}
7256	}
7257
7258	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7259		if (smb_lock->cmd < 0) {
7260			err = -EINVAL;
7261			goto out;
7262		}
7263
7264		if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
7265			err = -EINVAL;
7266			goto out;
7267		}
7268
7269		if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
7270		     smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
7271		    (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
7272		     !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
7273			err = -EINVAL;
7274			goto out;
7275		}
7276
7277		prior_lock = smb_lock->flags;
7278
7279		if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
7280		    !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
7281			goto no_check_cl;
7282
7283		nolock = 1;
7284		/* check locks in connection list */
7285		down_read(&conn_list_lock);
7286		list_for_each_entry(conn, &conn_list, conns_list) {
7287			spin_lock(&conn->llist_lock);
7288			list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
7289				if (file_inode(cmp_lock->fl->c.flc_file) !=
7290				    file_inode(smb_lock->fl->c.flc_file))
7291					continue;
7292
7293				if (lock_is_unlock(smb_lock->fl)) {
7294					if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file &&
7295					    cmp_lock->start == smb_lock->start &&
7296					    cmp_lock->end == smb_lock->end &&
7297					    !lock_defer_pending(cmp_lock->fl)) {
7298						nolock = 0;
7299						list_del(&cmp_lock->flist);
7300						list_del(&cmp_lock->clist);
7301						spin_unlock(&conn->llist_lock);
7302						up_read(&conn_list_lock);
7303
7304						locks_free_lock(cmp_lock->fl);
7305						kfree(cmp_lock);
7306						goto out_check_cl;
7307					}
7308					continue;
7309				}
7310
7311				if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file) {
7312					if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
7313						continue;
7314				} else {
7315					if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
7316						continue;
7317				}
7318
7319				/* check zero byte lock range */
7320				if (cmp_lock->zero_len && !smb_lock->zero_len &&
7321				    cmp_lock->start > smb_lock->start &&
7322				    cmp_lock->start < smb_lock->end) {
7323					spin_unlock(&conn->llist_lock);
7324					up_read(&conn_list_lock);
7325					pr_err("previous lock conflict with zero byte lock range\n");
7326					goto out;
7327				}
7328
7329				if (smb_lock->zero_len && !cmp_lock->zero_len &&
7330				    smb_lock->start > cmp_lock->start &&
7331				    smb_lock->start < cmp_lock->end) {
7332					spin_unlock(&conn->llist_lock);
7333					up_read(&conn_list_lock);
7334					pr_err("current lock conflict with zero byte lock range\n");
7335					goto out;
7336				}
7337
7338				if (((cmp_lock->start <= smb_lock->start &&
7339				      cmp_lock->end > smb_lock->start) ||
7340				     (cmp_lock->start < smb_lock->end &&
7341				      cmp_lock->end >= smb_lock->end)) &&
7342				    !cmp_lock->zero_len && !smb_lock->zero_len) {
7343					spin_unlock(&conn->llist_lock);
7344					up_read(&conn_list_lock);
7345					pr_err("Not allow lock operation on exclusive lock range\n");
7346					goto out;
7347				}
7348			}
7349			spin_unlock(&conn->llist_lock);
7350		}
7351		up_read(&conn_list_lock);
7352out_check_cl:
7353		if (lock_is_unlock(smb_lock->fl) && nolock) {
7354			pr_err("Try to unlock nolocked range\n");
7355			rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7356			goto out;
7357		}
7358
7359no_check_cl:
7360		if (smb_lock->zero_len) {
7361			err = 0;
7362			goto skip;
7363		}
7364
7365		flock = smb_lock->fl;
7366		list_del(&smb_lock->llist);
7367retry:
7368		rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7369skip:
7370		if (flags & SMB2_LOCKFLAG_UNLOCK) {
7371			if (!rc) {
7372				ksmbd_debug(SMB, "File unlocked\n");
7373			} else if (rc == -ENOENT) {
7374				rsp->hdr.Status = STATUS_NOT_LOCKED;
7375				goto out;
7376			}
7377			locks_free_lock(flock);
7378			kfree(smb_lock);
7379		} else {
7380			if (rc == FILE_LOCK_DEFERRED) {
7381				void **argv;
7382
7383				ksmbd_debug(SMB,
7384					    "would have to wait for getting lock\n");
7385				list_add(&smb_lock->llist, &rollback_list);
7386
7387				argv = kmalloc(sizeof(void *), GFP_KERNEL);
7388				if (!argv) {
7389					err = -ENOMEM;
7390					goto out;
7391				}
7392				argv[0] = flock;
7393
7394				rc = setup_async_work(work,
7395						      smb2_remove_blocked_lock,
7396						      argv);
7397				if (rc) {
7398					kfree(argv);
7399					err = -ENOMEM;
7400					goto out;
7401				}
7402				spin_lock(&fp->f_lock);
7403				list_add(&work->fp_entry, &fp->blocked_works);
7404				spin_unlock(&fp->f_lock);
7405
7406				smb2_send_interim_resp(work, STATUS_PENDING);
7407
7408				ksmbd_vfs_posix_lock_wait(flock);
7409
7410				spin_lock(&fp->f_lock);
7411				list_del(&work->fp_entry);
7412				spin_unlock(&fp->f_lock);
7413
7414				if (work->state != KSMBD_WORK_ACTIVE) {
7415					list_del(&smb_lock->llist);
7416					locks_free_lock(flock);
7417
7418					if (work->state == KSMBD_WORK_CANCELLED) {
7419						rsp->hdr.Status =
7420							STATUS_CANCELLED;
7421						kfree(smb_lock);
7422						smb2_send_interim_resp(work,
7423								       STATUS_CANCELLED);
7424						work->send_no_response = 1;
7425						goto out;
7426					}
7427
7428					rsp->hdr.Status =
7429						STATUS_RANGE_NOT_LOCKED;
7430					kfree(smb_lock);
7431					goto out2;
7432				}
7433
7434				list_del(&smb_lock->llist);
7435				release_async_work(work);
7436				goto retry;
7437			} else if (!rc) {
7438				list_add(&smb_lock->llist, &rollback_list);
7439				spin_lock(&work->conn->llist_lock);
7440				list_add_tail(&smb_lock->clist,
7441					      &work->conn->lock_list);
7442				list_add_tail(&smb_lock->flist,
7443					      &fp->lock_list);
7444				spin_unlock(&work->conn->llist_lock);
7445				ksmbd_debug(SMB, "successful in taking lock\n");
7446			} else {
7447				goto out;
7448			}
7449		}
7450	}
7451
7452	if (atomic_read(&fp->f_ci->op_count) > 1)
7453		smb_break_all_oplock(work, fp);
7454
7455	rsp->StructureSize = cpu_to_le16(4);
7456	ksmbd_debug(SMB, "successful in taking lock\n");
7457	rsp->hdr.Status = STATUS_SUCCESS;
7458	rsp->Reserved = 0;
7459	err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
7460	if (err)
7461		goto out;
7462
7463	ksmbd_fd_put(work, fp);
7464	return 0;
7465
7466out:
7467	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7468		locks_free_lock(smb_lock->fl);
7469		list_del(&smb_lock->llist);
7470		kfree(smb_lock);
7471	}
7472
7473	list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7474		struct file_lock *rlock = NULL;
7475
7476		rlock = smb_flock_init(filp);
7477		rlock->c.flc_type = F_UNLCK;
7478		rlock->fl_start = smb_lock->start;
7479		rlock->fl_end = smb_lock->end;
7480
7481		rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7482		if (rc)
7483			pr_err("rollback unlock fail : %d\n", rc);
7484
7485		list_del(&smb_lock->llist);
7486		spin_lock(&work->conn->llist_lock);
7487		if (!list_empty(&smb_lock->flist))
7488			list_del(&smb_lock->flist);
7489		list_del(&smb_lock->clist);
7490		spin_unlock(&work->conn->llist_lock);
7491
7492		locks_free_lock(smb_lock->fl);
7493		locks_free_lock(rlock);
7494		kfree(smb_lock);
7495	}
7496out2:
7497	ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7498
7499	if (!rsp->hdr.Status) {
7500		if (err == -EINVAL)
7501			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7502		else if (err == -ENOMEM)
7503			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7504		else if (err == -ENOENT)
7505			rsp->hdr.Status = STATUS_FILE_CLOSED;
7506		else
7507			rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7508	}
7509
7510	smb2_set_err_rsp(work);
7511	ksmbd_fd_put(work, fp);
7512	return err;
7513}
7514
7515static int fsctl_copychunk(struct ksmbd_work *work,
7516			   struct copychunk_ioctl_req *ci_req,
7517			   unsigned int cnt_code,
7518			   unsigned int input_count,
7519			   unsigned long long volatile_id,
7520			   unsigned long long persistent_id,
7521			   struct smb2_ioctl_rsp *rsp)
7522{
7523	struct copychunk_ioctl_rsp *ci_rsp;
7524	struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7525	struct srv_copychunk *chunks;
7526	unsigned int i, chunk_count, chunk_count_written = 0;
7527	unsigned int chunk_size_written = 0;
7528	loff_t total_size_written = 0;
7529	int ret = 0;
7530
7531	ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7532
7533	rsp->VolatileFileId = volatile_id;
7534	rsp->PersistentFileId = persistent_id;
7535	ci_rsp->ChunksWritten =
7536		cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7537	ci_rsp->ChunkBytesWritten =
7538		cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7539	ci_rsp->TotalBytesWritten =
7540		cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7541
7542	chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7543	chunk_count = le32_to_cpu(ci_req->ChunkCount);
7544	if (chunk_count == 0)
7545		goto out;
7546	total_size_written = 0;
7547
7548	/* verify the SRV_COPYCHUNK_COPY packet */
7549	if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7550	    input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7551	     chunk_count * sizeof(struct srv_copychunk)) {
7552		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7553		return -EINVAL;
7554	}
7555
7556	for (i = 0; i < chunk_count; i++) {
7557		if (le32_to_cpu(chunks[i].Length) == 0 ||
7558		    le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7559			break;
7560		total_size_written += le32_to_cpu(chunks[i].Length);
7561	}
7562
7563	if (i < chunk_count ||
7564	    total_size_written > ksmbd_server_side_copy_max_total_size()) {
7565		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7566		return -EINVAL;
7567	}
7568
7569	src_fp = ksmbd_lookup_foreign_fd(work,
7570					 le64_to_cpu(ci_req->ResumeKey[0]));
7571	dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7572	ret = -EINVAL;
7573	if (!src_fp ||
7574	    src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7575		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7576		goto out;
7577	}
7578
7579	if (!dst_fp) {
7580		rsp->hdr.Status = STATUS_FILE_CLOSED;
7581		goto out;
7582	}
7583
7584	/*
7585	 * FILE_READ_DATA should only be included in
7586	 * the FSCTL_COPYCHUNK case
7587	 */
7588	if (cnt_code == FSCTL_COPYCHUNK &&
7589	    !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7590		rsp->hdr.Status = STATUS_ACCESS_DENIED;
7591		goto out;
7592	}
7593
7594	ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7595					 chunks, chunk_count,
7596					 &chunk_count_written,
7597					 &chunk_size_written,
7598					 &total_size_written);
7599	if (ret < 0) {
7600		if (ret == -EACCES)
7601			rsp->hdr.Status = STATUS_ACCESS_DENIED;
7602		if (ret == -EAGAIN)
7603			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7604		else if (ret == -EBADF)
7605			rsp->hdr.Status = STATUS_INVALID_HANDLE;
7606		else if (ret == -EFBIG || ret == -ENOSPC)
7607			rsp->hdr.Status = STATUS_DISK_FULL;
7608		else if (ret == -EINVAL)
7609			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7610		else if (ret == -EISDIR)
7611			rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7612		else if (ret == -E2BIG)
7613			rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7614		else
7615			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7616	}
7617
7618	ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7619	ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7620	ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7621out:
7622	ksmbd_fd_put(work, src_fp);
7623	ksmbd_fd_put(work, dst_fp);
7624	return ret;
7625}
7626
7627static __be32 idev_ipv4_address(struct in_device *idev)
7628{
7629	__be32 addr = 0;
7630
7631	struct in_ifaddr *ifa;
7632
7633	rcu_read_lock();
7634	in_dev_for_each_ifa_rcu(ifa, idev) {
7635		if (ifa->ifa_flags & IFA_F_SECONDARY)
7636			continue;
7637
7638		addr = ifa->ifa_address;
7639		break;
7640	}
7641	rcu_read_unlock();
7642	return addr;
7643}
7644
7645static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7646					struct smb2_ioctl_rsp *rsp,
7647					unsigned int out_buf_len)
7648{
7649	struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7650	int nbytes = 0;
7651	struct net_device *netdev;
7652	struct sockaddr_storage_rsp *sockaddr_storage;
7653	unsigned int flags;
7654	unsigned long long speed;
7655
7656	rtnl_lock();
7657	for_each_netdev(&init_net, netdev) {
7658		bool ipv4_set = false;
7659
7660		if (netdev->type == ARPHRD_LOOPBACK)
7661			continue;
7662
7663		flags = dev_get_flags(netdev);
7664		if (!(flags & IFF_RUNNING))
7665			continue;
7666ipv6_retry:
7667		if (out_buf_len <
7668		    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7669			rtnl_unlock();
7670			return -ENOSPC;
7671		}
7672
7673		nii_rsp = (struct network_interface_info_ioctl_rsp *)
7674				&rsp->Buffer[nbytes];
7675		nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7676
7677		nii_rsp->Capability = 0;
7678		if (netdev->real_num_tx_queues > 1)
7679			nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7680		if (ksmbd_rdma_capable_netdev(netdev))
7681			nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7682
7683		nii_rsp->Next = cpu_to_le32(152);
7684		nii_rsp->Reserved = 0;
7685
7686		if (netdev->ethtool_ops->get_link_ksettings) {
7687			struct ethtool_link_ksettings cmd;
7688
7689			netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7690			speed = cmd.base.speed;
7691		} else {
7692			ksmbd_debug(SMB, "%s %s\n", netdev->name,
7693				    "speed is unknown, defaulting to 1Gb/sec");
7694			speed = SPEED_1000;
7695		}
7696
7697		speed *= 1000000;
7698		nii_rsp->LinkSpeed = cpu_to_le64(speed);
7699
7700		sockaddr_storage = (struct sockaddr_storage_rsp *)
7701					nii_rsp->SockAddr_Storage;
7702		memset(sockaddr_storage, 0, 128);
7703
7704		if (!ipv4_set) {
7705			struct in_device *idev;
7706
7707			sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7708			sockaddr_storage->addr4.Port = 0;
7709
7710			idev = __in_dev_get_rtnl(netdev);
7711			if (!idev)
7712				continue;
7713			sockaddr_storage->addr4.IPv4address =
7714						idev_ipv4_address(idev);
7715			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7716			ipv4_set = true;
7717			goto ipv6_retry;
7718		} else {
7719			struct inet6_dev *idev6;
7720			struct inet6_ifaddr *ifa;
7721			__u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7722
7723			sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7724			sockaddr_storage->addr6.Port = 0;
7725			sockaddr_storage->addr6.FlowInfo = 0;
7726
7727			idev6 = __in6_dev_get(netdev);
7728			if (!idev6)
7729				continue;
7730
7731			list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7732				if (ifa->flags & (IFA_F_TENTATIVE |
7733							IFA_F_DEPRECATED))
7734					continue;
7735				memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7736				break;
7737			}
7738			sockaddr_storage->addr6.ScopeId = 0;
7739			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7740		}
7741	}
7742	rtnl_unlock();
7743
7744	/* zero if this is last one */
7745	if (nii_rsp)
7746		nii_rsp->Next = 0;
7747
7748	rsp->PersistentFileId = SMB2_NO_FID;
7749	rsp->VolatileFileId = SMB2_NO_FID;
7750	return nbytes;
7751}
7752
7753static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7754					 struct validate_negotiate_info_req *neg_req,
7755					 struct validate_negotiate_info_rsp *neg_rsp,
7756					 unsigned int in_buf_len)
7757{
7758	int ret = 0;
7759	int dialect;
7760
7761	if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7762			le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7763		return -EINVAL;
7764
7765	dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7766					     neg_req->DialectCount);
7767	if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7768		ret = -EINVAL;
7769		goto err_out;
7770	}
7771
7772	if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7773		ret = -EINVAL;
7774		goto err_out;
7775	}
7776
7777	if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7778		ret = -EINVAL;
7779		goto err_out;
7780	}
7781
7782	if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7783		ret = -EINVAL;
7784		goto err_out;
7785	}
7786
7787	neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7788	memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7789	neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7790	neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7791err_out:
7792	return ret;
7793}
7794
7795static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7796					struct file_allocated_range_buffer *qar_req,
7797					struct file_allocated_range_buffer *qar_rsp,
7798					unsigned int in_count, unsigned int *out_count)
7799{
7800	struct ksmbd_file *fp;
7801	loff_t start, length;
7802	int ret = 0;
7803
7804	*out_count = 0;
7805	if (in_count == 0)
7806		return -EINVAL;
7807
7808	start = le64_to_cpu(qar_req->file_offset);
7809	length = le64_to_cpu(qar_req->length);
7810
7811	if (start < 0 || length < 0)
7812		return -EINVAL;
7813
7814	fp = ksmbd_lookup_fd_fast(work, id);
7815	if (!fp)
7816		return -ENOENT;
7817
7818	ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7819				   qar_rsp, in_count, out_count);
7820	if (ret && ret != -E2BIG)
7821		*out_count = 0;
7822
7823	ksmbd_fd_put(work, fp);
7824	return ret;
7825}
7826
7827static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7828				 unsigned int out_buf_len,
7829				 struct smb2_ioctl_req *req,
7830				 struct smb2_ioctl_rsp *rsp)
7831{
7832	struct ksmbd_rpc_command *rpc_resp;
7833	char *data_buf = (char *)req + le32_to_cpu(req->InputOffset);
7834	int nbytes = 0;
7835
7836	rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7837				   le32_to_cpu(req->InputCount));
7838	if (rpc_resp) {
7839		if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7840			/*
7841			 * set STATUS_SOME_NOT_MAPPED response
7842			 * for unknown domain sid.
7843			 */
7844			rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7845		} else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7846			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7847			goto out;
7848		} else if (rpc_resp->flags != KSMBD_RPC_OK) {
7849			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7850			goto out;
7851		}
7852
7853		nbytes = rpc_resp->payload_sz;
7854		if (rpc_resp->payload_sz > out_buf_len) {
7855			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7856			nbytes = out_buf_len;
7857		}
7858
7859		if (!rpc_resp->payload_sz) {
7860			rsp->hdr.Status =
7861				STATUS_UNEXPECTED_IO_ERROR;
7862			goto out;
7863		}
7864
7865		memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7866	}
7867out:
7868	kvfree(rpc_resp);
7869	return nbytes;
7870}
7871
7872static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7873				   struct file_sparse *sparse)
7874{
7875	struct ksmbd_file *fp;
7876	struct mnt_idmap *idmap;
7877	int ret = 0;
7878	__le32 old_fattr;
7879
7880	fp = ksmbd_lookup_fd_fast(work, id);
7881	if (!fp)
7882		return -ENOENT;
7883	idmap = file_mnt_idmap(fp->filp);
7884
7885	old_fattr = fp->f_ci->m_fattr;
7886	if (sparse->SetSparse)
7887		fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7888	else
7889		fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7890
7891	if (fp->f_ci->m_fattr != old_fattr &&
7892	    test_share_config_flag(work->tcon->share_conf,
7893				   KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7894		struct xattr_dos_attrib da;
7895
7896		ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
7897						     fp->filp->f_path.dentry, &da);
7898		if (ret <= 0)
7899			goto out;
7900
7901		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7902		ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
7903						     &fp->filp->f_path,
7904						     &da, true);
7905		if (ret)
7906			fp->f_ci->m_fattr = old_fattr;
7907	}
7908
7909out:
7910	ksmbd_fd_put(work, fp);
7911	return ret;
7912}
7913
7914static int fsctl_request_resume_key(struct ksmbd_work *work,
7915				    struct smb2_ioctl_req *req,
7916				    struct resume_key_ioctl_rsp *key_rsp)
7917{
7918	struct ksmbd_file *fp;
7919
7920	fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7921	if (!fp)
7922		return -ENOENT;
7923
7924	memset(key_rsp, 0, sizeof(*key_rsp));
7925	key_rsp->ResumeKey[0] = req->VolatileFileId;
7926	key_rsp->ResumeKey[1] = req->PersistentFileId;
7927	ksmbd_fd_put(work, fp);
7928
7929	return 0;
7930}
7931
7932/**
7933 * smb2_ioctl() - handler for smb2 ioctl command
7934 * @work:	smb work containing ioctl command buffer
7935 *
7936 * Return:	0 on success, otherwise error
7937 */
7938int smb2_ioctl(struct ksmbd_work *work)
7939{
7940	struct smb2_ioctl_req *req;
7941	struct smb2_ioctl_rsp *rsp;
7942	unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7943	u64 id = KSMBD_NO_FID;
7944	struct ksmbd_conn *conn = work->conn;
7945	int ret = 0;
7946	char *buffer;
7947
7948	if (work->next_smb2_rcv_hdr_off) {
7949		req = ksmbd_req_buf_next(work);
7950		rsp = ksmbd_resp_buf_next(work);
7951		if (!has_file_id(req->VolatileFileId)) {
7952			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7953				    work->compound_fid);
7954			id = work->compound_fid;
7955		}
7956	} else {
7957		req = smb2_get_msg(work->request_buf);
7958		rsp = smb2_get_msg(work->response_buf);
7959	}
7960
7961	if (!has_file_id(id))
7962		id = req->VolatileFileId;
7963
7964	if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7965		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7966		goto out;
7967	}
7968
7969	buffer = (char *)req + le32_to_cpu(req->InputOffset);
7970
7971	cnt_code = le32_to_cpu(req->CtlCode);
7972	ret = smb2_calc_max_out_buf_len(work, 48,
7973					le32_to_cpu(req->MaxOutputResponse));
7974	if (ret < 0) {
7975		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7976		goto out;
7977	}
7978	out_buf_len = (unsigned int)ret;
7979	in_buf_len = le32_to_cpu(req->InputCount);
7980
7981	switch (cnt_code) {
7982	case FSCTL_DFS_GET_REFERRALS:
7983	case FSCTL_DFS_GET_REFERRALS_EX:
7984		/* Not support DFS yet */
7985		rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7986		goto out;
7987	case FSCTL_CREATE_OR_GET_OBJECT_ID:
7988	{
7989		struct file_object_buf_type1_ioctl_rsp *obj_buf;
7990
7991		nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7992		obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7993			&rsp->Buffer[0];
7994
7995		/*
7996		 * TODO: This is dummy implementation to pass smbtorture
7997		 * Need to check correct response later
7998		 */
7999		memset(obj_buf->ObjectId, 0x0, 16);
8000		memset(obj_buf->BirthVolumeId, 0x0, 16);
8001		memset(obj_buf->BirthObjectId, 0x0, 16);
8002		memset(obj_buf->DomainId, 0x0, 16);
8003
8004		break;
8005	}
8006	case FSCTL_PIPE_TRANSCEIVE:
8007		out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
8008		nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
8009		break;
8010	case FSCTL_VALIDATE_NEGOTIATE_INFO:
8011		if (conn->dialect < SMB30_PROT_ID) {
8012			ret = -EOPNOTSUPP;
8013			goto out;
8014		}
8015
8016		if (in_buf_len < offsetof(struct validate_negotiate_info_req,
8017					  Dialects)) {
8018			ret = -EINVAL;
8019			goto out;
8020		}
8021
8022		if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
8023			ret = -EINVAL;
8024			goto out;
8025		}
8026
8027		ret = fsctl_validate_negotiate_info(conn,
8028			(struct validate_negotiate_info_req *)buffer,
8029			(struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
8030			in_buf_len);
8031		if (ret < 0)
8032			goto out;
8033
8034		nbytes = sizeof(struct validate_negotiate_info_rsp);
8035		rsp->PersistentFileId = SMB2_NO_FID;
8036		rsp->VolatileFileId = SMB2_NO_FID;
8037		break;
8038	case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
8039		ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
8040		if (ret < 0)
8041			goto out;
8042		nbytes = ret;
8043		break;
8044	case FSCTL_REQUEST_RESUME_KEY:
8045		if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
8046			ret = -EINVAL;
8047			goto out;
8048		}
8049
8050		ret = fsctl_request_resume_key(work, req,
8051					       (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
8052		if (ret < 0)
8053			goto out;
8054		rsp->PersistentFileId = req->PersistentFileId;
8055		rsp->VolatileFileId = req->VolatileFileId;
8056		nbytes = sizeof(struct resume_key_ioctl_rsp);
8057		break;
8058	case FSCTL_COPYCHUNK:
8059	case FSCTL_COPYCHUNK_WRITE:
8060		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8061			ksmbd_debug(SMB,
8062				    "User does not have write permission\n");
8063			ret = -EACCES;
8064			goto out;
8065		}
8066
8067		if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
8068			ret = -EINVAL;
8069			goto out;
8070		}
8071
8072		if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
8073			ret = -EINVAL;
8074			goto out;
8075		}
8076
8077		nbytes = sizeof(struct copychunk_ioctl_rsp);
8078		rsp->VolatileFileId = req->VolatileFileId;
8079		rsp->PersistentFileId = req->PersistentFileId;
8080		fsctl_copychunk(work,
8081				(struct copychunk_ioctl_req *)buffer,
8082				le32_to_cpu(req->CtlCode),
8083				le32_to_cpu(req->InputCount),
8084				req->VolatileFileId,
8085				req->PersistentFileId,
8086				rsp);
8087		break;
8088	case FSCTL_SET_SPARSE:
8089		if (in_buf_len < sizeof(struct file_sparse)) {
8090			ret = -EINVAL;
8091			goto out;
8092		}
8093
8094		ret = fsctl_set_sparse(work, id, (struct file_sparse *)buffer);
8095		if (ret < 0)
8096			goto out;
8097		break;
8098	case FSCTL_SET_ZERO_DATA:
8099	{
8100		struct file_zero_data_information *zero_data;
8101		struct ksmbd_file *fp;
8102		loff_t off, len, bfz;
8103
8104		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8105			ksmbd_debug(SMB,
8106				    "User does not have write permission\n");
8107			ret = -EACCES;
8108			goto out;
8109		}
8110
8111		if (in_buf_len < sizeof(struct file_zero_data_information)) {
8112			ret = -EINVAL;
8113			goto out;
8114		}
8115
8116		zero_data =
8117			(struct file_zero_data_information *)buffer;
8118
8119		off = le64_to_cpu(zero_data->FileOffset);
8120		bfz = le64_to_cpu(zero_data->BeyondFinalZero);
8121		if (off < 0 || bfz < 0 || off > bfz) {
8122			ret = -EINVAL;
8123			goto out;
8124		}
8125
8126		len = bfz - off;
8127		if (len) {
8128			fp = ksmbd_lookup_fd_fast(work, id);
8129			if (!fp) {
8130				ret = -ENOENT;
8131				goto out;
8132			}
8133
8134			ret = ksmbd_vfs_zero_data(work, fp, off, len);
8135			ksmbd_fd_put(work, fp);
8136			if (ret < 0)
8137				goto out;
8138		}
8139		break;
8140	}
8141	case FSCTL_QUERY_ALLOCATED_RANGES:
8142		if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
8143			ret = -EINVAL;
8144			goto out;
8145		}
8146
8147		ret = fsctl_query_allocated_ranges(work, id,
8148			(struct file_allocated_range_buffer *)buffer,
8149			(struct file_allocated_range_buffer *)&rsp->Buffer[0],
8150			out_buf_len /
8151			sizeof(struct file_allocated_range_buffer), &nbytes);
8152		if (ret == -E2BIG) {
8153			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
8154		} else if (ret < 0) {
8155			nbytes = 0;
8156			goto out;
8157		}
8158
8159		nbytes *= sizeof(struct file_allocated_range_buffer);
8160		break;
8161	case FSCTL_GET_REPARSE_POINT:
8162	{
8163		struct reparse_data_buffer *reparse_ptr;
8164		struct ksmbd_file *fp;
8165
8166		reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
8167		fp = ksmbd_lookup_fd_fast(work, id);
8168		if (!fp) {
8169			pr_err("not found fp!!\n");
8170			ret = -ENOENT;
8171			goto out;
8172		}
8173
8174		reparse_ptr->ReparseTag =
8175			smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
8176		reparse_ptr->ReparseDataLength = 0;
8177		ksmbd_fd_put(work, fp);
8178		nbytes = sizeof(struct reparse_data_buffer);
8179		break;
8180	}
8181	case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
8182	{
8183		struct ksmbd_file *fp_in, *fp_out = NULL;
8184		struct duplicate_extents_to_file *dup_ext;
8185		loff_t src_off, dst_off, length, cloned;
8186
8187		if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
8188			ret = -EINVAL;
8189			goto out;
8190		}
8191
8192		dup_ext = (struct duplicate_extents_to_file *)buffer;
8193
8194		fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
8195					     dup_ext->PersistentFileHandle);
8196		if (!fp_in) {
8197			pr_err("not found file handle in duplicate extent to file\n");
8198			ret = -ENOENT;
8199			goto out;
8200		}
8201
8202		fp_out = ksmbd_lookup_fd_fast(work, id);
8203		if (!fp_out) {
8204			pr_err("not found fp\n");
8205			ret = -ENOENT;
8206			goto dup_ext_out;
8207		}
8208
8209		src_off = le64_to_cpu(dup_ext->SourceFileOffset);
8210		dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
8211		length = le64_to_cpu(dup_ext->ByteCount);
8212		/*
8213		 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
8214		 * should fall back to vfs_copy_file_range().  This could be
8215		 * beneficial when re-exporting nfs/smb mount, but note that
8216		 * this can result in partial copy that returns an error status.
8217		 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
8218		 * fall back to vfs_copy_file_range(), should be avoided when
8219		 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
8220		 */
8221		cloned = vfs_clone_file_range(fp_in->filp, src_off,
8222					      fp_out->filp, dst_off, length, 0);
8223		if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
8224			ret = -EOPNOTSUPP;
8225			goto dup_ext_out;
8226		} else if (cloned != length) {
8227			cloned = vfs_copy_file_range(fp_in->filp, src_off,
8228						     fp_out->filp, dst_off,
8229						     length, 0);
8230			if (cloned != length) {
8231				if (cloned < 0)
8232					ret = cloned;
8233				else
8234					ret = -EINVAL;
8235			}
8236		}
8237
8238dup_ext_out:
8239		ksmbd_fd_put(work, fp_in);
8240		ksmbd_fd_put(work, fp_out);
8241		if (ret < 0)
8242			goto out;
8243		break;
8244	}
8245	default:
8246		ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
8247			    cnt_code);
8248		ret = -EOPNOTSUPP;
8249		goto out;
8250	}
8251
8252	rsp->CtlCode = cpu_to_le32(cnt_code);
8253	rsp->InputCount = cpu_to_le32(0);
8254	rsp->InputOffset = cpu_to_le32(112);
8255	rsp->OutputOffset = cpu_to_le32(112);
8256	rsp->OutputCount = cpu_to_le32(nbytes);
8257	rsp->StructureSize = cpu_to_le16(49);
8258	rsp->Reserved = cpu_to_le16(0);
8259	rsp->Flags = cpu_to_le32(0);
8260	rsp->Reserved2 = cpu_to_le32(0);
8261	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
8262	if (!ret)
8263		return ret;
8264
8265out:
8266	if (ret == -EACCES)
8267		rsp->hdr.Status = STATUS_ACCESS_DENIED;
8268	else if (ret == -ENOENT)
8269		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
8270	else if (ret == -EOPNOTSUPP)
8271		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8272	else if (ret == -ENOSPC)
8273		rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
8274	else if (ret < 0 || rsp->hdr.Status == 0)
8275		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8276	smb2_set_err_rsp(work);
8277	return 0;
8278}
8279
8280/**
8281 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
8282 * @work:	smb work containing oplock break command buffer
8283 *
8284 * Return:	0
8285 */
8286static void smb20_oplock_break_ack(struct ksmbd_work *work)
8287{
8288	struct smb2_oplock_break *req;
8289	struct smb2_oplock_break *rsp;
8290	struct ksmbd_file *fp;
8291	struct oplock_info *opinfo = NULL;
8292	__le32 err = 0;
8293	int ret = 0;
8294	u64 volatile_id, persistent_id;
8295	char req_oplevel = 0, rsp_oplevel = 0;
8296	unsigned int oplock_change_type;
8297
8298	WORK_BUFFERS(work, req, rsp);
8299
8300	volatile_id = req->VolatileFid;
8301	persistent_id = req->PersistentFid;
8302	req_oplevel = req->OplockLevel;
8303	ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
8304		    volatile_id, persistent_id, req_oplevel);
8305
8306	fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
8307	if (!fp) {
8308		rsp->hdr.Status = STATUS_FILE_CLOSED;
8309		smb2_set_err_rsp(work);
8310		return;
8311	}
8312
8313	opinfo = opinfo_get(fp);
8314	if (!opinfo) {
8315		pr_err("unexpected null oplock_info\n");
8316		rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8317		smb2_set_err_rsp(work);
8318		ksmbd_fd_put(work, fp);
8319		return;
8320	}
8321
8322	if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
8323		rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8324		goto err_out;
8325	}
8326
8327	if (opinfo->op_state == OPLOCK_STATE_NONE) {
8328		ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
8329		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8330		goto err_out;
8331	}
8332
8333	if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8334	     opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8335	    (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
8336	     req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
8337		err = STATUS_INVALID_OPLOCK_PROTOCOL;
8338		oplock_change_type = OPLOCK_WRITE_TO_NONE;
8339	} else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8340		   req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
8341		err = STATUS_INVALID_OPLOCK_PROTOCOL;
8342		oplock_change_type = OPLOCK_READ_TO_NONE;
8343	} else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
8344		   req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8345		err = STATUS_INVALID_DEVICE_STATE;
8346		if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8347		     opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8348		    req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8349			oplock_change_type = OPLOCK_WRITE_TO_READ;
8350		} else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8351			    opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8352			   req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8353			oplock_change_type = OPLOCK_WRITE_TO_NONE;
8354		} else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8355			   req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8356			oplock_change_type = OPLOCK_READ_TO_NONE;
8357		} else {
8358			oplock_change_type = 0;
8359		}
8360	} else {
8361		oplock_change_type = 0;
8362	}
8363
8364	switch (oplock_change_type) {
8365	case OPLOCK_WRITE_TO_READ:
8366		ret = opinfo_write_to_read(opinfo);
8367		rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8368		break;
8369	case OPLOCK_WRITE_TO_NONE:
8370		ret = opinfo_write_to_none(opinfo);
8371		rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8372		break;
8373	case OPLOCK_READ_TO_NONE:
8374		ret = opinfo_read_to_none(opinfo);
8375		rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8376		break;
8377	default:
8378		pr_err("unknown oplock change 0x%x -> 0x%x\n",
8379		       opinfo->level, rsp_oplevel);
8380	}
8381
8382	if (ret < 0) {
8383		rsp->hdr.Status = err;
8384		goto err_out;
8385	}
8386
8387	opinfo->op_state = OPLOCK_STATE_NONE;
8388	wake_up_interruptible_all(&opinfo->oplock_q);
8389	opinfo_put(opinfo);
8390	ksmbd_fd_put(work, fp);
8391
8392	rsp->StructureSize = cpu_to_le16(24);
8393	rsp->OplockLevel = rsp_oplevel;
8394	rsp->Reserved = 0;
8395	rsp->Reserved2 = 0;
8396	rsp->VolatileFid = volatile_id;
8397	rsp->PersistentFid = persistent_id;
8398	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
8399	if (!ret)
8400		return;
8401
8402err_out:
8403	opinfo->op_state = OPLOCK_STATE_NONE;
8404	wake_up_interruptible_all(&opinfo->oplock_q);
8405
8406	opinfo_put(opinfo);
8407	ksmbd_fd_put(work, fp);
8408	smb2_set_err_rsp(work);
8409}
8410
8411static int check_lease_state(struct lease *lease, __le32 req_state)
8412{
8413	if ((lease->new_state ==
8414	     (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8415	    !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8416		lease->new_state = req_state;
8417		return 0;
8418	}
8419
8420	if (lease->new_state == req_state)
8421		return 0;
8422
8423	return 1;
8424}
8425
8426/**
8427 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8428 * @work:	smb work containing lease break command buffer
8429 *
8430 * Return:	0
8431 */
8432static void smb21_lease_break_ack(struct ksmbd_work *work)
8433{
8434	struct ksmbd_conn *conn = work->conn;
8435	struct smb2_lease_ack *req;
8436	struct smb2_lease_ack *rsp;
8437	struct oplock_info *opinfo;
8438	__le32 err = 0;
8439	int ret = 0;
8440	unsigned int lease_change_type;
8441	__le32 lease_state;
8442	struct lease *lease;
8443
8444	WORK_BUFFERS(work, req, rsp);
8445
8446	ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8447		    le32_to_cpu(req->LeaseState));
8448	opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8449	if (!opinfo) {
8450		ksmbd_debug(OPLOCK, "file not opened\n");
8451		smb2_set_err_rsp(work);
8452		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8453		return;
8454	}
8455	lease = opinfo->o_lease;
8456
8457	if (opinfo->op_state == OPLOCK_STATE_NONE) {
8458		pr_err("unexpected lease break state 0x%x\n",
8459		       opinfo->op_state);
8460		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8461		goto err_out;
8462	}
8463
8464	if (check_lease_state(lease, req->LeaseState)) {
8465		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8466		ksmbd_debug(OPLOCK,
8467			    "req lease state: 0x%x, expected state: 0x%x\n",
8468			    req->LeaseState, lease->new_state);
8469		goto err_out;
8470	}
8471
8472	if (!atomic_read(&opinfo->breaking_cnt)) {
8473		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8474		goto err_out;
8475	}
8476
8477	/* check for bad lease state */
8478	if (req->LeaseState &
8479	    (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8480		err = STATUS_INVALID_OPLOCK_PROTOCOL;
8481		if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8482			lease_change_type = OPLOCK_WRITE_TO_NONE;
8483		else
8484			lease_change_type = OPLOCK_READ_TO_NONE;
8485		ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8486			    le32_to_cpu(lease->state),
8487			    le32_to_cpu(req->LeaseState));
8488	} else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8489		   req->LeaseState != SMB2_LEASE_NONE_LE) {
8490		err = STATUS_INVALID_OPLOCK_PROTOCOL;
8491		lease_change_type = OPLOCK_READ_TO_NONE;
8492		ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8493			    le32_to_cpu(lease->state),
8494			    le32_to_cpu(req->LeaseState));
8495	} else {
8496		/* valid lease state changes */
8497		err = STATUS_INVALID_DEVICE_STATE;
8498		if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8499			if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8500				lease_change_type = OPLOCK_WRITE_TO_NONE;
8501			else
8502				lease_change_type = OPLOCK_READ_TO_NONE;
8503		} else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8504			if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8505				lease_change_type = OPLOCK_WRITE_TO_READ;
8506			else
8507				lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8508		} else {
8509			lease_change_type = 0;
8510		}
8511	}
8512
8513	switch (lease_change_type) {
8514	case OPLOCK_WRITE_TO_READ:
8515		ret = opinfo_write_to_read(opinfo);
8516		break;
8517	case OPLOCK_READ_HANDLE_TO_READ:
8518		ret = opinfo_read_handle_to_read(opinfo);
8519		break;
8520	case OPLOCK_WRITE_TO_NONE:
8521		ret = opinfo_write_to_none(opinfo);
8522		break;
8523	case OPLOCK_READ_TO_NONE:
8524		ret = opinfo_read_to_none(opinfo);
8525		break;
8526	default:
8527		ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8528			    le32_to_cpu(lease->state),
8529			    le32_to_cpu(req->LeaseState));
8530	}
8531
8532	if (ret < 0) {
8533		rsp->hdr.Status = err;
8534		goto err_out;
8535	}
8536
8537	lease_state = lease->state;
8538	opinfo->op_state = OPLOCK_STATE_NONE;
8539	wake_up_interruptible_all(&opinfo->oplock_q);
8540	atomic_dec(&opinfo->breaking_cnt);
8541	wake_up_interruptible_all(&opinfo->oplock_brk);
8542	opinfo_put(opinfo);
8543
8544	rsp->StructureSize = cpu_to_le16(36);
8545	rsp->Reserved = 0;
8546	rsp->Flags = 0;
8547	memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8548	rsp->LeaseState = lease_state;
8549	rsp->LeaseDuration = 0;
8550	ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
8551	if (!ret)
8552		return;
8553
8554err_out:
8555	wake_up_interruptible_all(&opinfo->oplock_q);
8556	atomic_dec(&opinfo->breaking_cnt);
8557	wake_up_interruptible_all(&opinfo->oplock_brk);
8558
8559	opinfo_put(opinfo);
8560	smb2_set_err_rsp(work);
8561}
8562
8563/**
8564 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8565 * @work:	smb work containing oplock/lease break command buffer
8566 *
8567 * Return:	0
8568 */
8569int smb2_oplock_break(struct ksmbd_work *work)
8570{
8571	struct smb2_oplock_break *req;
8572	struct smb2_oplock_break *rsp;
8573
8574	WORK_BUFFERS(work, req, rsp);
8575
8576	switch (le16_to_cpu(req->StructureSize)) {
8577	case OP_BREAK_STRUCT_SIZE_20:
8578		smb20_oplock_break_ack(work);
8579		break;
8580	case OP_BREAK_STRUCT_SIZE_21:
8581		smb21_lease_break_ack(work);
8582		break;
8583	default:
8584		ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8585			    le16_to_cpu(req->StructureSize));
8586		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8587		smb2_set_err_rsp(work);
8588	}
8589
8590	return 0;
8591}
8592
8593/**
8594 * smb2_notify() - handler for smb2 notify request
8595 * @work:   smb work containing notify command buffer
8596 *
8597 * Return:      0
8598 */
8599int smb2_notify(struct ksmbd_work *work)
8600{
8601	struct smb2_change_notify_req *req;
8602	struct smb2_change_notify_rsp *rsp;
8603
8604	WORK_BUFFERS(work, req, rsp);
8605
8606	if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8607		rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8608		smb2_set_err_rsp(work);
8609		return 0;
8610	}
8611
8612	smb2_set_err_rsp(work);
8613	rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8614	return 0;
8615}
8616
8617/**
8618 * smb2_is_sign_req() - handler for checking packet signing status
8619 * @work:	smb work containing notify command buffer
8620 * @command:	SMB2 command id
8621 *
8622 * Return:	true if packed is signed, false otherwise
8623 */
8624bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8625{
8626	struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8627
8628	if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8629	    command != SMB2_NEGOTIATE_HE &&
8630	    command != SMB2_SESSION_SETUP_HE &&
8631	    command != SMB2_OPLOCK_BREAK_HE)
8632		return true;
8633
8634	return false;
8635}
8636
8637/**
8638 * smb2_check_sign_req() - handler for req packet sign processing
8639 * @work:   smb work containing notify command buffer
8640 *
8641 * Return:	1 on success, 0 otherwise
8642 */
8643int smb2_check_sign_req(struct ksmbd_work *work)
8644{
8645	struct smb2_hdr *hdr;
8646	char signature_req[SMB2_SIGNATURE_SIZE];
8647	char signature[SMB2_HMACSHA256_SIZE];
8648	struct kvec iov[1];
8649	size_t len;
8650
8651	hdr = smb2_get_msg(work->request_buf);
8652	if (work->next_smb2_rcv_hdr_off)
8653		hdr = ksmbd_req_buf_next(work);
8654
8655	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8656		len = get_rfc1002_len(work->request_buf);
8657	else if (hdr->NextCommand)
8658		len = le32_to_cpu(hdr->NextCommand);
8659	else
8660		len = get_rfc1002_len(work->request_buf) -
8661			work->next_smb2_rcv_hdr_off;
8662
8663	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8664	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8665
8666	iov[0].iov_base = (char *)&hdr->ProtocolId;
8667	iov[0].iov_len = len;
8668
8669	if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8670				signature))
8671		return 0;
8672
8673	if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8674		pr_err("bad smb2 signature\n");
8675		return 0;
8676	}
8677
8678	return 1;
8679}
8680
8681/**
8682 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8683 * @work:   smb work containing notify command buffer
8684 *
8685 */
8686void smb2_set_sign_rsp(struct ksmbd_work *work)
8687{
8688	struct smb2_hdr *hdr;
8689	char signature[SMB2_HMACSHA256_SIZE];
8690	struct kvec *iov;
8691	int n_vec = 1;
8692
8693	hdr = ksmbd_resp_buf_curr(work);
8694	hdr->Flags |= SMB2_FLAGS_SIGNED;
8695	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8696
8697	if (hdr->Command == SMB2_READ) {
8698		iov = &work->iov[work->iov_idx - 1];
8699		n_vec++;
8700	} else {
8701		iov = &work->iov[work->iov_idx];
8702	}
8703
8704	if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8705				 signature))
8706		memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8707}
8708
8709/**
8710 * smb3_check_sign_req() - handler for req packet sign processing
8711 * @work:   smb work containing notify command buffer
8712 *
8713 * Return:	1 on success, 0 otherwise
8714 */
8715int smb3_check_sign_req(struct ksmbd_work *work)
8716{
8717	struct ksmbd_conn *conn = work->conn;
8718	char *signing_key;
8719	struct smb2_hdr *hdr;
8720	struct channel *chann;
8721	char signature_req[SMB2_SIGNATURE_SIZE];
8722	char signature[SMB2_CMACAES_SIZE];
8723	struct kvec iov[1];
8724	size_t len;
8725
8726	hdr = smb2_get_msg(work->request_buf);
8727	if (work->next_smb2_rcv_hdr_off)
8728		hdr = ksmbd_req_buf_next(work);
8729
8730	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8731		len = get_rfc1002_len(work->request_buf);
8732	else if (hdr->NextCommand)
8733		len = le32_to_cpu(hdr->NextCommand);
8734	else
8735		len = get_rfc1002_len(work->request_buf) -
8736			work->next_smb2_rcv_hdr_off;
8737
8738	if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8739		signing_key = work->sess->smb3signingkey;
8740	} else {
8741		chann = lookup_chann_list(work->sess, conn);
8742		if (!chann) {
8743			return 0;
8744		}
8745		signing_key = chann->smb3signingkey;
8746	}
8747
8748	if (!signing_key) {
8749		pr_err("SMB3 signing key is not generated\n");
8750		return 0;
8751	}
8752
8753	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8754	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8755	iov[0].iov_base = (char *)&hdr->ProtocolId;
8756	iov[0].iov_len = len;
8757
8758	if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8759		return 0;
8760
8761	if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8762		pr_err("bad smb2 signature\n");
8763		return 0;
8764	}
8765
8766	return 1;
8767}
8768
8769/**
8770 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8771 * @work:   smb work containing notify command buffer
8772 *
8773 */
8774void smb3_set_sign_rsp(struct ksmbd_work *work)
8775{
8776	struct ksmbd_conn *conn = work->conn;
8777	struct smb2_hdr *hdr;
8778	struct channel *chann;
8779	char signature[SMB2_CMACAES_SIZE];
8780	struct kvec *iov;
8781	int n_vec = 1;
8782	char *signing_key;
8783
8784	hdr = ksmbd_resp_buf_curr(work);
8785
8786	if (conn->binding == false &&
8787	    le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8788		signing_key = work->sess->smb3signingkey;
8789	} else {
8790		chann = lookup_chann_list(work->sess, work->conn);
8791		if (!chann) {
8792			return;
8793		}
8794		signing_key = chann->smb3signingkey;
8795	}
8796
8797	if (!signing_key)
8798		return;
8799
8800	hdr->Flags |= SMB2_FLAGS_SIGNED;
8801	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8802
8803	if (hdr->Command == SMB2_READ) {
8804		iov = &work->iov[work->iov_idx - 1];
8805		n_vec++;
8806	} else {
8807		iov = &work->iov[work->iov_idx];
8808	}
8809
8810	if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec,
8811				 signature))
8812		memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8813}
8814
8815/**
8816 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8817 * @work:   smb work containing response buffer
8818 *
8819 */
8820void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8821{
8822	struct ksmbd_conn *conn = work->conn;
8823	struct ksmbd_session *sess = work->sess;
8824	struct smb2_hdr *req, *rsp;
8825
8826	if (conn->dialect != SMB311_PROT_ID)
8827		return;
8828
8829	WORK_BUFFERS(work, req, rsp);
8830
8831	if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8832	    conn->preauth_info)
8833		ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8834						 conn->preauth_info->Preauth_HashValue);
8835
8836	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8837		__u8 *hash_value;
8838
8839		if (conn->binding) {
8840			struct preauth_session *preauth_sess;
8841
8842			preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8843			if (!preauth_sess)
8844				return;
8845			hash_value = preauth_sess->Preauth_HashValue;
8846		} else {
8847			hash_value = sess->Preauth_HashValue;
8848			if (!hash_value)
8849				return;
8850		}
8851		ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8852						 hash_value);
8853	}
8854}
8855
8856static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8857{
8858	struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8859	struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8860	unsigned int orig_len = get_rfc1002_len(old_buf);
8861
8862	/* tr_buf must be cleared by the caller */
8863	tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8864	tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8865	tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8866	if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8867	    cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8868		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8869	else
8870		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8871	memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8872	inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8873	inc_rfc1001_len(tr_buf, orig_len);
8874}
8875
8876int smb3_encrypt_resp(struct ksmbd_work *work)
8877{
8878	struct kvec *iov = work->iov;
8879	int rc = -ENOMEM;
8880	void *tr_buf;
8881
8882	tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8883	if (!tr_buf)
8884		return rc;
8885
8886	/* fill transform header */
8887	fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
8888
8889	iov[0].iov_base = tr_buf;
8890	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8891	work->tr_buf = tr_buf;
8892
8893	return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
8894}
8895
8896bool smb3_is_transform_hdr(void *buf)
8897{
8898	struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8899
8900	return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8901}
8902
8903int smb3_decrypt_req(struct ksmbd_work *work)
8904{
8905	struct ksmbd_session *sess;
8906	char *buf = work->request_buf;
8907	unsigned int pdu_length = get_rfc1002_len(buf);
8908	struct kvec iov[2];
8909	int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8910	struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8911	int rc = 0;
8912
8913	if (pdu_length < sizeof(struct smb2_transform_hdr) ||
8914	    buf_data_size < sizeof(struct smb2_hdr)) {
8915		pr_err("Transform message is too small (%u)\n",
8916		       pdu_length);
8917		return -ECONNABORTED;
8918	}
8919
8920	if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8921		pr_err("Transform message is broken\n");
8922		return -ECONNABORTED;
8923	}
8924
8925	sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8926	if (!sess) {
8927		pr_err("invalid session id(%llx) in transform header\n",
8928		       le64_to_cpu(tr_hdr->SessionId));
8929		return -ECONNABORTED;
8930	}
8931
8932	iov[0].iov_base = buf;
8933	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8934	iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8935	iov[1].iov_len = buf_data_size;
8936	rc = ksmbd_crypt_message(work, iov, 2, 0);
8937	if (rc)
8938		return rc;
8939
8940	memmove(buf + 4, iov[1].iov_base, buf_data_size);
8941	*(__be32 *)buf = cpu_to_be32(buf_data_size);
8942
8943	return rc;
8944}
8945
8946bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8947{
8948	struct ksmbd_conn *conn = work->conn;
8949	struct ksmbd_session *sess = work->sess;
8950	struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8951
8952	if (conn->dialect < SMB30_PROT_ID)
8953		return false;
8954
8955	if (work->next_smb2_rcv_hdr_off)
8956		rsp = ksmbd_resp_buf_next(work);
8957
8958	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8959	    sess->user && !user_guest(sess->user) &&
8960	    rsp->Status == STATUS_SUCCESS)
8961		return true;
8962	return false;
8963}
8964