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