smb2pdu.c 230.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 *   Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
 *   Copyright (C) 2018 Samsung Electronics Co., Ltd.
 */

#include <linux/inetdevice.h>
#include <net/addrconf.h>
#include <linux/syscalls.h>
#include <linux/namei.h>
#include <linux/statfs.h>
#include <linux/ethtool.h>
13
#include <linux/falloc.h>
14 15 16 17 18 19 20 21 22 23 24

#include "glob.h"
#include "smb2pdu.h"
#include "smbfsctl.h"
#include "oplock.h"
#include "smbacl.h"

#include "auth.h"
#include "asn1.h"
#include "connection.h"
#include "transport_ipc.h"
25
#include "transport_rdma.h"
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#include "vfs.h"
#include "vfs_cache.h"
#include "misc.h"

#include "server.h"
#include "smb_common.h"
#include "smbstatus.h"
#include "ksmbd_work.h"
#include "mgmt/user_config.h"
#include "mgmt/share_config.h"
#include "mgmt/tree_connect.h"
#include "mgmt/user_session.h"
#include "mgmt/ksmbd_ida.h"
#include "ndr.h"

static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
{
	if (work->next_smb2_rcv_hdr_off) {
44 45
		*req = ksmbd_req_buf_next(work);
		*rsp = ksmbd_resp_buf_next(work);
46
	} else {
47 48
		*req = smb2_get_msg(work->request_buf);
		*rsp = smb2_get_msg(work->response_buf);
49 50 51 52 53 54 55 56 57 58 59 60
	}
}

#define WORK_BUFFERS(w, rq, rs)	__wbuf((w), (void **)&(rq), (void **)&(rs))

/**
 * check_session_id() - check for valid session id in smb header
 * @conn:	connection instance
 * @id:		session id from smb header
 *
 * Return:      1 if valid session id, otherwise 0
 */
61
static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
62 63 64 65
{
	struct ksmbd_session *sess;

	if (id == 0 || id == -1)
66
		return false;
67

68
	sess = ksmbd_session_lookup_all(conn, id);
69
	if (sess)
70
		return true;
N
Namjae Jeon 已提交
71
	pr_err("Invalid user session id: %llu\n", id);
72
	return false;
73 74
}

75
struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
76 77 78
{
	struct channel *chann;

79
	list_for_each_entry(chann, &sess->ksmbd_chann_list, chann_list) {
80
		if (chann->conn == conn)
81 82 83 84 85 86 87
			return chann;
	}

	return NULL;
}

/**
88
 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
H
Hyunchul Lee 已提交
89
 * @work:	smb work
90
 *
91 92
 * Return:	0 if there is a tree connection matched or these are
 *		skipable commands, otherwise error
93 94 95
 */
int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
{
96
	struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
97
	unsigned int cmd = le16_to_cpu(req_hdr->Command);
98 99 100
	int tree_id;

	work->tcon = NULL;
101 102 103
	if (cmd == SMB2_TREE_CONNECT_HE ||
	    cmd ==  SMB2_CANCEL_HE ||
	    cmd ==  SMB2_LOGOFF_HE) {
104 105 106 107
		ksmbd_debug(SMB, "skip to check tree connect request\n");
		return 0;
	}

108
	if (xa_empty(&work->sess->tree_conns)) {
109
		ksmbd_debug(SMB, "NO tree connected\n");
110
		return -ENOENT;
111 112 113 114 115
	}

	tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
	work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
	if (!work->tcon) {
N
Namjae Jeon 已提交
116
		pr_err("Invalid tid %d\n", tree_id);
117
		return -EINVAL;
118 119 120 121 122 123 124 125 126 127 128 129 130 131
	}

	return 1;
}

/**
 * smb2_set_err_rsp() - set error response code on smb response
 * @work:	smb work containing response buffer
 */
void smb2_set_err_rsp(struct ksmbd_work *work)
{
	struct smb2_err_rsp *err_rsp;

	if (work->next_smb2_rcv_hdr_off)
132
		err_rsp = ksmbd_resp_buf_next(work);
133
	else
134
		err_rsp = smb2_get_msg(work->response_buf);
135 136 137 138 139 140 141

	if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
		err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
		err_rsp->ErrorContextCount = 0;
		err_rsp->Reserved = 0;
		err_rsp->ByteCount = 0;
		err_rsp->ErrorData[0] = 0;
N
Namjae Jeon 已提交
142
		inc_rfc1001_len(work->response_buf, SMB2_ERROR_STRUCTURE_SIZE2);
143 144 145 146 147 148 149
	}
}

/**
 * is_smb2_neg_cmd() - is it smb2 negotiation command
 * @work:	smb work containing smb header
 *
150
 * Return:      true if smb2 negotiation command, otherwise false
151
 */
152
bool is_smb2_neg_cmd(struct ksmbd_work *work)
153
{
154
	struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
155 156 157

	/* is it SMB2 header ? */
	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
158
		return false;
159 160 161

	/* make sure it is request not response message */
	if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
162
		return false;
163 164

	if (hdr->Command != SMB2_NEGOTIATE)
165
		return false;
166

167
	return true;
168 169 170 171 172 173
}

/**
 * is_smb2_rsp() - is it smb2 response
 * @work:	smb work containing smb response buffer
 *
174
 * Return:      true if smb2 response, otherwise false
175
 */
176
bool is_smb2_rsp(struct ksmbd_work *work)
177
{
178
	struct smb2_hdr *hdr = smb2_get_msg(work->response_buf);
179 180 181

	/* is it SMB2 header ? */
	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
182
		return false;
183 184 185

	/* make sure it is response not request message */
	if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
186
		return false;
187

188
	return true;
189 190 191 192 193 194 195 196
}

/**
 * get_smb2_cmd_val() - get smb command code from smb header
 * @work:	smb work containing smb request buffer
 *
 * Return:      smb2 request command value
 */
197
u16 get_smb2_cmd_val(struct ksmbd_work *work)
198 199 200 201
{
	struct smb2_hdr *rcv_hdr;

	if (work->next_smb2_rcv_hdr_off)
202
		rcv_hdr = ksmbd_req_buf_next(work);
203
	else
204
		rcv_hdr = smb2_get_msg(work->request_buf);
205 206 207 208 209 210
	return le16_to_cpu(rcv_hdr->Command);
}

/**
 * set_smb2_rsp_status() - set error response code on smb2 header
 * @work:	smb work containing response buffer
H
Hyunchul Lee 已提交
211
 * @err:	error response code
212 213 214 215 216 217
 */
void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
{
	struct smb2_hdr *rsp_hdr;

	if (work->next_smb2_rcv_hdr_off)
218
		rsp_hdr = ksmbd_resp_buf_next(work);
219
	else
220
		rsp_hdr = smb2_get_msg(work->response_buf);
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
	rsp_hdr->Status = err;
	smb2_set_err_rsp(work);
}

/**
 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
 * @work:	smb work containing smb request buffer
 *
 * smb2 negotiate response is sent in reply of smb1 negotiate command for
 * dialect auto-negotiation.
 */
int init_smb2_neg_rsp(struct ksmbd_work *work)
{
	struct smb2_hdr *rsp_hdr;
	struct smb2_negotiate_rsp *rsp;
	struct ksmbd_conn *conn = work->conn;

	if (conn->need_neg == false)
		return -EINVAL;

241 242
	*(__be32 *)work->response_buf =
		cpu_to_be32(conn->vals->header_size);
243

244
	rsp_hdr = smb2_get_msg(work->response_buf);
245 246 247 248 249 250 251 252 253 254 255 256 257
	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
	rsp_hdr->CreditRequest = cpu_to_le16(2);
	rsp_hdr->Command = SMB2_NEGOTIATE;
	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
	rsp_hdr->NextCommand = 0;
	rsp_hdr->MessageId = 0;
	rsp_hdr->Id.SyncId.ProcessId = 0;
	rsp_hdr->Id.SyncId.TreeId = 0;
	rsp_hdr->SessionId = 0;
	memset(rsp_hdr->Signature, 0, 16);

258
	rsp = smb2_get_msg(work->response_buf);
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278

	WARN_ON(ksmbd_conn_good(work));

	rsp->StructureSize = cpu_to_le16(65);
	ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
	rsp->DialectRevision = cpu_to_le16(conn->dialect);
	/* Not setting conn guid rsp->ServerGUID, as it
	 * not used by client for identifying connection
	 */
	rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
	/* Default Max Message Size till SMB2.0, 64K*/
	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);

	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
	rsp->ServerStartTime = 0;

	rsp->SecurityBufferOffset = cpu_to_le16(128);
	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
279
	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
280
		le16_to_cpu(rsp->SecurityBufferOffset));
281 282 283 284
	inc_rfc1001_len(work->response_buf,
			sizeof(struct smb2_negotiate_rsp) -
			sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
			AUTH_GSS_LENGTH);
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
	if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
	conn->use_spnego = true;

	ksmbd_conn_set_need_negotiate(work);
	return 0;
}

/**
 * smb2_set_rsp_credits() - set number of credits in response buffer
 * @work:	smb work containing smb response buffer
 */
int smb2_set_rsp_credits(struct ksmbd_work *work)
{
300 301
	struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
	struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
302
	struct ksmbd_conn *conn = work->conn;
303
	unsigned short credits_requested, aux_max;
H
Hyunchul Lee 已提交
304
	unsigned short credit_charge, credits_granted = 0;
305

H
Hyunchul Lee 已提交
306 307
	if (work->send_no_response)
		return 0;
308

H
Hyunchul Lee 已提交
309
	hdr->CreditCharge = req_hdr->CreditCharge;
310

311
	if (conn->total_credits > conn->vals->max_credits) {
H
Hyunchul Lee 已提交
312
		hdr->CreditRequest = 0;
N
Namjae Jeon 已提交
313
		pr_err("Total credits overflow: %d\n", conn->total_credits);
H
Hyunchul Lee 已提交
314
		return -EINVAL;
315 316
	}

H
Hyunchul Lee 已提交
317 318
	credit_charge = max_t(unsigned short,
			      le16_to_cpu(req_hdr->CreditCharge), 1);
319 320 321 322 323 324 325
	if (credit_charge > conn->total_credits) {
		ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
			    credit_charge, conn->total_credits);
		return -EINVAL;
	}

	conn->total_credits -= credit_charge;
326
	conn->outstanding_credits -= credit_charge;
H
Hyunchul Lee 已提交
327 328
	credits_requested = max_t(unsigned short,
				  le16_to_cpu(req_hdr->CreditRequest), 1);
329

H
Hyunchul Lee 已提交
330 331 332 333 334 335 336
	/* according to smb2.credits smbtorture, Windows server
	 * 2016 or later grant up to 8192 credits at once.
	 *
	 * TODO: Need to adjuct CreditRequest value according to
	 * current cpu load
	 */
	if (hdr->Command == SMB2_NEGOTIATE)
337
		aux_max = 1;
H
Hyunchul Lee 已提交
338
	else
339
		aux_max = conn->vals->max_credits - credit_charge;
340
	credits_granted = min_t(unsigned short, credits_requested, aux_max);
H
Hyunchul Lee 已提交
341

342 343
	if (conn->vals->max_credits - conn->total_credits < credits_granted)
		credits_granted = conn->vals->max_credits -
H
Hyunchul Lee 已提交
344
			conn->total_credits;
345 346 347 348 349 350 351 352 353

	conn->total_credits += credits_granted;
	work->credits_granted += credits_granted;

	if (!req_hdr->NextCommand) {
		/* Update CreditRequest in last request */
		hdr->CreditRequest = cpu_to_le16(work->credits_granted);
	}
	ksmbd_debug(SMB,
354 355 356
		    "credits: requested[%d] granted[%d] total_granted[%d]\n",
		    credits_requested, credits_granted,
		    conn->total_credits);
357 358 359 360 361 362 363 364 365
	return 0;
}

/**
 * init_chained_smb2_rsp() - initialize smb2 chained response
 * @work:	smb work containing smb response buffer
 */
static void init_chained_smb2_rsp(struct ksmbd_work *work)
{
366 367
	struct smb2_hdr *req = ksmbd_req_buf_next(work);
	struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
	struct smb2_hdr *rsp_hdr;
	struct smb2_hdr *rcv_hdr;
	int next_hdr_offset = 0;
	int len, new_len;

	/* Len of this response = updated RFC len - offset of previous cmd
	 * in the compound rsp
	 */

	/* Storing the current local FID which may be needed by subsequent
	 * command in the compound request
	 */
	if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
		work->compound_fid =
			le64_to_cpu(((struct smb2_create_rsp *)rsp)->
				VolatileFileId);
		work->compound_pfid =
			le64_to_cpu(((struct smb2_create_rsp *)rsp)->
				PersistentFileId);
		work->compound_sid = le64_to_cpu(rsp->SessionId);
	}

N
Namjae Jeon 已提交
390
	len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
391 392 393
	next_hdr_offset = le32_to_cpu(req->NextCommand);

	new_len = ALIGN(len, 8);
394 395
	inc_rfc1001_len(work->response_buf,
			sizeof(struct smb2_hdr) + new_len - len);
396 397 398 399 400
	rsp->NextCommand = cpu_to_le32(new_len);

	work->next_smb2_rcv_hdr_off += next_hdr_offset;
	work->next_smb2_rsp_hdr_off += new_len;
	ksmbd_debug(SMB,
401 402 403
		    "Compound req new_len = %d rcv off = %d rsp off = %d\n",
		    new_len, work->next_smb2_rcv_hdr_off,
		    work->next_smb2_rsp_hdr_off);
404

405 406
	rsp_hdr = ksmbd_resp_buf_next(work);
	rcv_hdr = ksmbd_req_buf_next(work);
407 408 409 410 411 412

	if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
		ksmbd_debug(SMB, "related flag should be set\n");
		work->compound_fid = KSMBD_NO_FID;
		work->compound_pfid = KSMBD_NO_FID;
	}
413
	memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
414
	rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
	rsp_hdr->Command = rcv_hdr->Command;

	/*
	 * Message is response. We don't grant oplock yet.
	 */
	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
				SMB2_FLAGS_RELATED_OPERATIONS);
	rsp_hdr->NextCommand = 0;
	rsp_hdr->MessageId = rcv_hdr->MessageId;
	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
	rsp_hdr->SessionId = rcv_hdr->SessionId;
	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
}

/**
 * is_chained_smb2_message() - check for chained command
 * @work:	smb work containing smb request buffer
 *
 * Return:      true if chained request, otherwise false
 */
bool is_chained_smb2_message(struct ksmbd_work *work)
{
439
	struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
440
	unsigned int len, next_cmd;
441 442 443 444

	if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
		return false;

445
	hdr = ksmbd_req_buf_next(work);
446 447 448 449 450 451 452 453 454 455
	next_cmd = le32_to_cpu(hdr->NextCommand);
	if (next_cmd > 0) {
		if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
			__SMB2_HEADER_STRUCTURE_SIZE >
		    get_rfc1002_len(work->request_buf)) {
			pr_err("next command(%u) offset exceeds smb msg size\n",
			       next_cmd);
			return false;
		}

456 457 458 459 460 461
		if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
		    work->response_sz) {
			pr_err("next response offset exceeds response buffer size\n");
			return false;
		}

462 463 464 465 466 467 468 469
		ksmbd_debug(SMB, "got SMB2 chained command\n");
		init_chained_smb2_rsp(work);
		return true;
	} else if (work->next_smb2_rcv_hdr_off) {
		/*
		 * This is last request in chained command,
		 * align response to 8 byte
		 */
N
Namjae Jeon 已提交
470 471
		len = ALIGN(get_rfc1002_len(work->response_buf), 8);
		len = len - get_rfc1002_len(work->response_buf);
472 473
		if (len) {
			ksmbd_debug(SMB, "padding len %u\n", len);
N
Namjae Jeon 已提交
474 475
			inc_rfc1001_len(work->response_buf, len);
			if (work->aux_payload_sz)
476 477 478 479 480 481 482 483 484 485 486 487 488 489
				work->aux_payload_sz += len;
		}
	}
	return false;
}

/**
 * init_smb2_rsp_hdr() - initialize smb2 response
 * @work:	smb work containing smb request buffer
 *
 * Return:      0
 */
int init_smb2_rsp_hdr(struct ksmbd_work *work)
{
490 491
	struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
	struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
492 493 494
	struct ksmbd_conn *conn = work->conn;

	memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
495 496
	*(__be32 *)work->response_buf =
		cpu_to_be32(conn->vals->header_size);
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
	rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
	rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
	rsp_hdr->Command = rcv_hdr->Command;

	/*
	 * Message is response. We don't grant oplock yet.
	 */
	rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
	rsp_hdr->NextCommand = 0;
	rsp_hdr->MessageId = rcv_hdr->MessageId;
	rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
	rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
	rsp_hdr->SessionId = rcv_hdr->SessionId;
	memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);

	work->syncronous = true;
	if (work->async_id) {
N
Namjae Jeon 已提交
514
		ksmbd_release_id(&conn->async_ida, work->async_id);
515 516 517 518 519 520 521 522 523 524 525 526 527 528
		work->async_id = 0;
	}

	return 0;
}

/**
 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
 * @work:	smb work containing smb request buffer
 *
 * Return:      0 on success, otherwise -ENOMEM
 */
int smb2_allocate_rsp_buf(struct ksmbd_work *work)
{
529
	struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
530
	size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
531
	size_t large_sz = small_sz + work->conn->vals->max_trans_size;
532 533 534
	size_t sz = small_sz;
	int cmd = le16_to_cpu(hdr->Command);

535
	if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
536 537 538 539 540
		sz = large_sz;

	if (cmd == SMB2_QUERY_INFO_HE) {
		struct smb2_query_info_req *req;

541
		req = smb2_get_msg(work->request_buf);
542 543 544 545
		if ((req->InfoType == SMB2_O_INFO_FILE &&
		     (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
		     req->FileInfoClass == FILE_ALL_INFORMATION)) ||
		    req->InfoType == SMB2_O_INFO_SECURITY)
546 547 548 549 550 551 552
			sz = large_sz;
	}

	/* allocate large response buf for chained commands */
	if (le32_to_cpu(hdr->NextCommand) > 0)
		sz = large_sz;

553
	work->response_buf = kvmalloc(sz, GFP_KERNEL | __GFP_ZERO);
554
	if (!work->response_buf)
555 556 557 558 559 560 561 562 563 564 565 566 567 568
		return -ENOMEM;

	work->response_sz = sz;
	return 0;
}

/**
 * smb2_check_user_session() - check for valid session for a user
 * @work:	smb work containing smb request buffer
 *
 * Return:      0 on success, otherwise error
 */
int smb2_check_user_session(struct ksmbd_work *work)
{
569
	struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
570 571 572 573 574 575 576 577 578 579 580
	struct ksmbd_conn *conn = work->conn;
	unsigned int cmd = conn->ops->get_cmd_val(work);
	unsigned long long sess_id;

	work->sess = NULL;
	/*
	 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
	 * require a session id, so no need to validate user session's for
	 * these commands.
	 */
	if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
581
	    cmd == SMB2_SESSION_SETUP_HE)
582 583 584 585 586 587 588
		return 0;

	if (!ksmbd_conn_good(work))
		return -EINVAL;

	sess_id = le64_to_cpu(req_hdr->SessionId);
	/* Check for validity of user session */
589
	work->sess = ksmbd_session_lookup_all(conn, sess_id);
590 591 592 593 594 595
	if (work->sess)
		return 1;
	ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
	return -EINVAL;
}

596 597
static void destroy_previous_session(struct ksmbd_conn *conn,
				     struct ksmbd_user *user, u64 id)
598 599 600
{
	struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
	struct ksmbd_user *prev_user;
601
	struct channel *chann;
602 603 604 605 606 607

	if (!prev_sess)
		return;

	prev_user = prev_sess->user;

608 609
	if (!prev_user ||
	    strcmp(user->name, prev_user->name) ||
610
	    user->passkey_sz != prev_user->passkey_sz ||
611
	    memcmp(user->passkey, prev_user->passkey, user->passkey_sz))
612 613
		return;

614 615 616 617 618
	prev_sess->state = SMB2_SESSION_EXPIRED;
	write_lock(&prev_sess->chann_lock);
	list_for_each_entry(chann, &prev_sess->ksmbd_chann_list, chann_list)
		chann->conn->status = KSMBD_SESS_EXITING;
	write_unlock(&prev_sess->chann_lock);
619 620 621 622 623 624
}

/**
 * smb2_get_name() - get filename string from on the wire smb format
 * @src:	source buffer
 * @maxlen:	maxlen of source string
625
 * @local_nls:	nls_table pointer
626 627 628 629
 *
 * Return:      matching converted filename on success, otherwise error ptr
 */
static char *
630
smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
631
{
632
	char *name;
633

634
	name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
635
	if (IS_ERR(name)) {
N
Namjae Jeon 已提交
636
		pr_err("failed to get name %ld\n", PTR_ERR(name));
637 638 639
		return name;
	}

640 641 642
	ksmbd_conv_path_to_unix(name);
	ksmbd_strip_last_slash(name);
	return name;
643 644 645 646 647 648 649 650
}

int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
{
	struct smb2_hdr *rsp_hdr;
	struct ksmbd_conn *conn = work->conn;
	int id;

651
	rsp_hdr = smb2_get_msg(work->response_buf);
652 653
	rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;

N
Namjae Jeon 已提交
654
	id = ksmbd_acquire_async_msg_id(&conn->async_ida);
655
	if (id < 0) {
N
Namjae Jeon 已提交
656
		pr_err("Failed to alloc async message id\n");
657 658 659 660 661 662 663
		return id;
	}
	work->syncronous = false;
	work->async_id = id;
	rsp_hdr->Id.AsyncId = cpu_to_le64(id);

	ksmbd_debug(SMB,
664 665
		    "Send interim Response to inform async request id : %d\n",
		    work->async_id);
666 667 668 669

	work->cancel_fn = fn;
	work->cancel_argv = arg;

670 671 672 673 674
	if (list_empty(&work->async_request_entry)) {
		spin_lock(&conn->request_lock);
		list_add_tail(&work->async_request_entry, &conn->async_requests);
		spin_unlock(&conn->request_lock);
	}
675 676 677 678 679 680 681 682

	return 0;
}

void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
{
	struct smb2_hdr *rsp_hdr;

683
	rsp_hdr = smb2_get_msg(work->response_buf);
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
	smb2_set_err_rsp(work);
	rsp_hdr->Status = status;

	work->multiRsp = 1;
	ksmbd_conn_write(work);
	rsp_hdr->Status = 0;
	work->multiRsp = 0;
}

static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
{
	if (S_ISDIR(mode) || S_ISREG(mode))
		return 0;

	if (S_ISLNK(mode))
		return IO_REPARSE_TAG_LX_SYMLINK_LE;
	else if (S_ISFIFO(mode))
		return IO_REPARSE_TAG_LX_FIFO_LE;
	else if (S_ISSOCK(mode))
		return IO_REPARSE_TAG_AF_UNIX_LE;
	else if (S_ISCHR(mode))
		return IO_REPARSE_TAG_LX_CHR_LE;
	else if (S_ISBLK(mode))
		return IO_REPARSE_TAG_LX_BLK_LE;

	return 0;
}

/**
 * smb2_get_dos_mode() - get file mode in dos format from unix mode
 * @stat:	kstat containing file mode
H
Hyunchul Lee 已提交
715
 * @attribute:	attribute flags
716 717 718 719 720 721 722
 *
 * Return:      converted dos mode
 */
static int smb2_get_dos_mode(struct kstat *stat, int attribute)
{
	int attr = 0;

723
	if (S_ISDIR(stat->mode)) {
724 725
		attr = ATTR_DIRECTORY |
			(attribute & (ATTR_HIDDEN | ATTR_SYSTEM));
726
	} else {
727 728 729 730 731 732 733 734 735 736 737 738 739 740
		attr = (attribute & 0x00005137) | ATTR_ARCHIVE;
		attr &= ~(ATTR_DIRECTORY);
		if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
				FILE_SUPPORTS_SPARSE_FILES))
			attr |= ATTR_SPARSE;

		if (smb2_get_reparse_tag_special_file(stat->mode))
			attr |= ATTR_REPARSE;
	}

	return attr;
}

static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
741
			       __le16 hash_id)
742 743 744 745 746 747 748 749 750 751 752
{
	pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
	pneg_ctxt->DataLength = cpu_to_le16(38);
	pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
	pneg_ctxt->Reserved = cpu_to_le32(0);
	pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
	get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
	pneg_ctxt->HashAlgorithms = hash_id;
}

static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
753
			       __le16 cipher_type)
754 755 756 757 758 759 760 761 762
{
	pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
	pneg_ctxt->DataLength = cpu_to_le16(4);
	pneg_ctxt->Reserved = cpu_to_le32(0);
	pneg_ctxt->CipherCount = cpu_to_le16(1);
	pneg_ctxt->Ciphers[0] = cipher_type;
}

static void build_compression_ctxt(struct smb2_compression_ctx *pneg_ctxt,
763
				   __le16 comp_algo)
764 765 766 767 768 769 770 771 772 773 774
{
	pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
	pneg_ctxt->DataLength =
		cpu_to_le16(sizeof(struct smb2_compression_ctx)
			- sizeof(struct smb2_neg_context));
	pneg_ctxt->Reserved = cpu_to_le32(0);
	pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(1);
	pneg_ctxt->Reserved1 = cpu_to_le32(0);
	pneg_ctxt->CompressionAlgorithms[0] = comp_algo;
}

775 776 777 778 779 780 781 782 783 784 785 786
static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
				__le16 sign_algo)
{
	pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
	pneg_ctxt->DataLength =
		cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
			- sizeof(struct smb2_neg_context));
	pneg_ctxt->Reserved = cpu_to_le32(0);
	pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
	pneg_ctxt->SigningAlgorithms[0] = sign_algo;
}

787
static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
{
	pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
	pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
	pneg_ctxt->Name[0] = 0x93;
	pneg_ctxt->Name[1] = 0xAD;
	pneg_ctxt->Name[2] = 0x25;
	pneg_ctxt->Name[3] = 0x50;
	pneg_ctxt->Name[4] = 0x9C;
	pneg_ctxt->Name[5] = 0xB4;
	pneg_ctxt->Name[6] = 0x11;
	pneg_ctxt->Name[7] = 0xE7;
	pneg_ctxt->Name[8] = 0xB4;
	pneg_ctxt->Name[9] = 0x23;
	pneg_ctxt->Name[10] = 0x83;
	pneg_ctxt->Name[11] = 0xDE;
	pneg_ctxt->Name[12] = 0x96;
	pneg_ctxt->Name[13] = 0x8B;
	pneg_ctxt->Name[14] = 0xCD;
	pneg_ctxt->Name[15] = 0x7C;
}

810
static void assemble_neg_contexts(struct ksmbd_conn *conn,
811 812
				  struct smb2_negotiate_rsp *rsp,
				  void *smb2_buf_len)
813 814
{
	char *pneg_ctxt = (char *)rsp +
815
			le32_to_cpu(rsp->NegotiateContextOffset);
816 817 818 819
	int neg_ctxt_cnt = 1;
	int ctxt_size;

	ksmbd_debug(SMB,
820
		    "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
821
	build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
822
			   conn->preauth_info->Preauth_HashId);
823
	rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
824
	inc_rfc1001_len(smb2_buf_len, AUTH_GSS_PADDING);
825 826 827 828 829 830 831
	ctxt_size = sizeof(struct smb2_preauth_neg_context);
	/* Round to 8 byte boundary */
	pneg_ctxt += round_up(sizeof(struct smb2_preauth_neg_context), 8);

	if (conn->cipher_type) {
		ctxt_size = round_up(ctxt_size, 8);
		ksmbd_debug(SMB,
832
			    "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
833
		build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt,
834
				   conn->cipher_type);
835
		rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
836
		ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
837 838
		/* Round to 8 byte boundary */
		pneg_ctxt +=
839
			round_up(sizeof(struct smb2_encryption_neg_context) + 2,
840 841 842 843 844 845
				 8);
	}

	if (conn->compress_algorithm) {
		ctxt_size = round_up(ctxt_size, 8);
		ksmbd_debug(SMB,
846
			    "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
847 848
		/* Temporarily set to SMB3_COMPRESS_NONE */
		build_compression_ctxt((struct smb2_compression_ctx *)pneg_ctxt,
849
				       conn->compress_algorithm);
850
		rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
851
		ctxt_size += sizeof(struct smb2_compression_ctx) + 2;
852
		/* Round to 8 byte boundary */
853 854
		pneg_ctxt += round_up(sizeof(struct smb2_compression_ctx) + 2,
				      8);
855 856 857 858 859
	}

	if (conn->posix_ext_supported) {
		ctxt_size = round_up(ctxt_size, 8);
		ksmbd_debug(SMB,
860
			    "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
861 862 863
		build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
		rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
		ctxt_size += sizeof(struct smb2_posix_neg_context);
864 865 866 867 868 869 870 871 872 873 874 875
		/* Round to 8 byte boundary */
		pneg_ctxt += round_up(sizeof(struct smb2_posix_neg_context), 8);
	}

	if (conn->signing_negotiated) {
		ctxt_size = round_up(ctxt_size, 8);
		ksmbd_debug(SMB,
			    "assemble SMB2_SIGNING_CAPABILITIES context\n");
		build_sign_cap_ctxt((struct smb2_signing_capabilities *)pneg_ctxt,
				    conn->signing_algorithm);
		rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
		ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
876 877
	}

878
	inc_rfc1001_len(smb2_buf_len, ctxt_size);
879 880
}

881
static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
882
				  struct smb2_preauth_neg_context *pneg_ctxt)
883 884 885
{
	__le32 err = STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;

886
	if (pneg_ctxt->HashAlgorithms == SMB2_PREAUTH_INTEGRITY_SHA512) {
887 888 889 890 891 892 893 894
		conn->preauth_info->Preauth_HashId =
			SMB2_PREAUTH_INTEGRITY_SHA512;
		err = STATUS_SUCCESS;
	}

	return err;
}

895 896 897
static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
				struct smb2_encryption_neg_context *pneg_ctxt,
				int len_of_ctxts)
898 899
{
	int cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
900
	int i, cphs_size = cph_cnt * sizeof(__le16);
901 902 903

	conn->cipher_type = 0;

904 905 906 907 908 909
	if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
	    len_of_ctxts) {
		pr_err("Invalid cipher count(%d)\n", cph_cnt);
		return;
	}

910
	if (!(server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION))
911
		return;
912 913 914

	for (i = 0; i < cph_cnt; i++) {
		if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
915 916 917
		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
		    pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
918
			ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
919
				    pneg_ctxt->Ciphers[i]);
920 921 922 923 924 925
			conn->cipher_type = pneg_ctxt->Ciphers[i];
			break;
		}
	}
}

926 927 928 929 930 931
/**
 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
 * @conn:	smb connection
 *
 * Return:	true if connection should be encrypted, else false
 */
932
bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
933 934 935 936 937 938 939 940 941 942 943 944
{
	if (!conn->ops->generate_encryptionkey)
		return false;

	/*
	 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
	 * SMB 3.1.1 uses the cipher_type field.
	 */
	return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
	    conn->cipher_type;
}

945 946
static void decode_compress_ctxt(struct ksmbd_conn *conn,
				 struct smb2_compression_ctx *pneg_ctxt)
947 948 949 950
{
	conn->compress_algorithm = SMB3_COMPRESS_NONE;
}

951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
				 struct smb2_signing_capabilities *pneg_ctxt,
				 int len_of_ctxts)
{
	int sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
	int i, sign_alos_size = sign_algo_cnt * sizeof(__le16);

	conn->signing_negotiated = false;

	if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
	    len_of_ctxts) {
		pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
		return;
	}

	for (i = 0; i < sign_algo_cnt; i++) {
		if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256 ||
		    pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC) {
			ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
				    pneg_ctxt->SigningAlgorithms[i]);
			conn->signing_negotiated = true;
			conn->signing_algorithm =
				pneg_ctxt->SigningAlgorithms[i];
			break;
		}
	}
}

979
static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
980 981
				      struct smb2_negotiate_req *req,
				      int len_of_smb)
982 983
{
	/* +4 is to account for the RFC1001 len field */
984
	struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
985 986
	int i = 0, len_of_ctxts;
	int offset = le32_to_cpu(req->NegotiateContextOffset);
987
	int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
988 989 990 991 992 993 994 995 996
	__le32 status = STATUS_INVALID_PARAMETER;

	ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
	if (len_of_smb <= offset) {
		ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
		return status;
	}

	len_of_ctxts = len_of_smb - offset;
997 998

	while (i++ < neg_ctxt_cnt) {
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
		int clen;

		/* check that offset is not beyond end of SMB */
		if (len_of_ctxts == 0)
			break;

		if (len_of_ctxts < sizeof(struct smb2_neg_context))
			break;

		pctx = (struct smb2_neg_context *)((char *)pctx + offset);
		clen = le16_to_cpu(pctx->DataLength);
		if (clen + sizeof(struct smb2_neg_context) > len_of_ctxts)
			break;

		if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1014
			ksmbd_debug(SMB,
1015
				    "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1016 1017 1018 1019
			if (conn->preauth_info->Preauth_HashId)
				break;

			status = decode_preauth_ctxt(conn,
1020 1021 1022 1023
						     (struct smb2_preauth_neg_context *)pctx);
			if (status != STATUS_SUCCESS)
				break;
		} else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1024
			ksmbd_debug(SMB,
1025
				    "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1026 1027 1028
			if (conn->cipher_type)
				break;

1029 1030 1031 1032
			decode_encrypt_ctxt(conn,
					    (struct smb2_encryption_neg_context *)pctx,
					    len_of_ctxts);
		} else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1033
			ksmbd_debug(SMB,
1034
				    "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1035 1036 1037
			if (conn->compress_algorithm)
				break;

1038 1039 1040
			decode_compress_ctxt(conn,
					     (struct smb2_compression_ctx *)pctx);
		} else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1041
			ksmbd_debug(SMB,
1042
				    "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1043
		} else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1044
			ksmbd_debug(SMB,
1045
				    "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1046
			conn->posix_ext_supported = true;
1047 1048 1049 1050 1051 1052
		} else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
			ksmbd_debug(SMB,
				    "deassemble SMB2_SIGNING_CAPABILITIES context\n");
			decode_sign_cap_ctxt(conn,
					     (struct smb2_signing_capabilities *)pctx,
					     len_of_ctxts);
1053 1054
		}

1055 1056 1057 1058
		/* offsets must be 8 byte aligned */
		clen = (clen + 7) & ~0x7;
		offset = clen + sizeof(struct smb2_neg_context);
		len_of_ctxts -= clen + sizeof(struct smb2_neg_context);
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
	}
	return status;
}

/**
 * smb2_handle_negotiate() - handler for smb2 negotiate command
 * @work:	smb work containing smb request buffer
 *
 * Return:      0
 */
int smb2_handle_negotiate(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
1072 1073
	struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
	struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1074
	int rc = 0;
1075
	unsigned int smb2_buf_len, smb2_neg_size;
1076 1077 1078 1079 1080
	__le32 status;

	ksmbd_debug(SMB, "Received negotiate request\n");
	conn->need_neg = false;
	if (ksmbd_conn_good(work)) {
N
Namjae Jeon 已提交
1081
		pr_err("conn->tcp_status is already in CifsGood State\n");
1082 1083 1084 1085 1086
		work->send_no_response = 1;
		return rc;
	}

	if (req->DialectCount == 0) {
N
Namjae Jeon 已提交
1087
		pr_err("malformed packet\n");
1088 1089 1090 1091 1092
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		rc = -EINVAL;
		goto err_out;
	}

1093
	smb2_buf_len = get_rfc1002_len(work->request_buf);
1094
	smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
	if (smb2_neg_size > smb2_buf_len) {
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		rc = -EINVAL;
		goto err_out;
	}

	if (conn->dialect == SMB311_PROT_ID) {
		unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);

		if (smb2_buf_len < nego_ctxt_off) {
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
			rc = -EINVAL;
			goto err_out;
		}

		if (smb2_neg_size > nego_ctxt_off) {
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
			rc = -EINVAL;
			goto err_out;
		}

		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
		    nego_ctxt_off) {
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
			rc = -EINVAL;
			goto err_out;
		}
	} else {
		if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
		    smb2_buf_len) {
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
			rc = -EINVAL;
			goto err_out;
		}
	}

1131 1132 1133 1134 1135
	conn->cli_cap = le32_to_cpu(req->Capabilities);
	switch (conn->dialect) {
	case SMB311_PROT_ID:
		conn->preauth_info =
			kzalloc(sizeof(struct preauth_integrity_info),
1136
				GFP_KERNEL);
1137 1138 1139 1140 1141 1142
		if (!conn->preauth_info) {
			rc = -ENOMEM;
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
			goto err_out;
		}

1143 1144
		status = deassemble_neg_contexts(conn, req,
						 get_rfc1002_len(work->request_buf));
1145
		if (status != STATUS_SUCCESS) {
N
Namjae Jeon 已提交
1146 1147
			pr_err("deassemble_neg_contexts error(0x%x)\n",
			       status);
1148 1149
			rsp->hdr.Status = status;
			rc = -EINVAL;
1150 1151
			kfree(conn->preauth_info);
			conn->preauth_info = NULL;
1152 1153 1154 1155 1156 1157
			goto err_out;
		}

		rc = init_smb3_11_server(conn);
		if (rc < 0) {
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1158 1159
			kfree(conn->preauth_info);
			conn->preauth_info = NULL;
1160 1161 1162 1163
			goto err_out;
		}

		ksmbd_gen_preauth_integrity_hash(conn,
1164 1165
						 work->request_buf,
						 conn->preauth_info->Preauth_HashValue);
1166 1167
		rsp->NegotiateContextOffset =
				cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1168
		assemble_neg_contexts(conn, rsp, work->response_buf);
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
		break;
	case SMB302_PROT_ID:
		init_smb3_02_server(conn);
		break;
	case SMB30_PROT_ID:
		init_smb3_0_server(conn);
		break;
	case SMB21_PROT_ID:
		init_smb2_1_server(conn);
		break;
	case SMB2X_PROT_ID:
	case BAD_PROT_ID:
	default:
		ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1183
			    conn->dialect);
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
		rc = -EINVAL;
		goto err_out;
	}
	rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);

	/* For stats */
	conn->connection_type = conn->dialect;

	rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
	rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
	rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);

1197 1198 1199
	memcpy(conn->ClientGUID, req->ClientGUID,
			SMB2_CLIENT_GUID_SIZE);
	conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210

	rsp->StructureSize = cpu_to_le16(65);
	rsp->DialectRevision = cpu_to_le16(conn->dialect);
	/* Not setting conn guid rsp->ServerGUID, as it
	 * not used by client for identifying server
	 */
	memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);

	rsp->SystemTime = cpu_to_le64(ksmbd_systime());
	rsp->ServerStartTime = 0;
	ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1211 1212
		    le32_to_cpu(rsp->NegotiateContextOffset),
		    le16_to_cpu(rsp->NegotiateContextCount));
1213 1214 1215

	rsp->SecurityBufferOffset = cpu_to_le16(128);
	rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1216 1217 1218
	ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
				  le16_to_cpu(rsp->SecurityBufferOffset));
	inc_rfc1001_len(work->response_buf, sizeof(struct smb2_negotiate_rsp) -
1219 1220
			sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
			 AUTH_GSS_LENGTH);
1221 1222 1223 1224
	rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
	conn->use_spnego = true;

	if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1225 1226
	     server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
	    req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
		conn->sign = true;
	else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
		server_conf.enforced_signing = true;
		rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
		conn->sign = true;
	}

	conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
	ksmbd_conn_set_need_negotiate(work);

err_out:
	if (rc < 0)
		smb2_set_err_rsp(work);

	return rc;
}

static int alloc_preauth_hash(struct ksmbd_session *sess,
1245
			      struct ksmbd_conn *conn)
1246 1247 1248 1249
{
	if (sess->Preauth_HashValue)
		return 0;

1250
	sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1251
					  PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
	if (!sess->Preauth_HashValue)
		return -ENOMEM;

	return 0;
}

static int generate_preauth_hash(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_session *sess = work->sess;
1262
	u8 *preauth_hash;
1263 1264 1265 1266

	if (conn->dialect != SMB311_PROT_ID)
		return 0;

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
	if (conn->binding) {
		struct preauth_session *preauth_sess;

		preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
		if (!preauth_sess) {
			preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
			if (!preauth_sess)
				return -ENOMEM;
		}

		preauth_hash = preauth_sess->Preauth_HashValue;
	} else {
		if (!sess->Preauth_HashValue)
			if (alloc_preauth_hash(sess, conn))
				return -ENOMEM;
		preauth_hash = sess->Preauth_HashValue;
1283 1284
	}

1285
	ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1286 1287 1288
	return 0;
}

1289 1290 1291
static int decode_negotiation_token(struct ksmbd_conn *conn,
				    struct negotiate_message *negblob,
				    size_t sz)
1292 1293 1294 1295
{
	if (!conn->use_spnego)
		return -EINVAL;

1296 1297
	if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
		if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1298 1299 1300 1301 1302 1303 1304 1305 1306
			conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
			conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
			conn->use_spnego = false;
		}
	}
	return 0;
}

static int ntlm_negotiate(struct ksmbd_work *work,
1307 1308
			  struct negotiate_message *negblob,
			  size_t negblob_len)
1309
{
1310
	struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1311 1312 1313 1314 1315 1316 1317
	struct challenge_message *chgblob;
	unsigned char *spnego_blob = NULL;
	u16 spnego_blob_len;
	char *neg_blob;
	int sz, rc;

	ksmbd_debug(SMB, "negotiate phase\n");
1318
	rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1319 1320 1321 1322 1323 1324 1325 1326 1327
	if (rc)
		return rc;

	sz = le16_to_cpu(rsp->SecurityBufferOffset);
	chgblob =
		(struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
	memset(chgblob, 0, sizeof(struct challenge_message));

	if (!work->conn->use_spnego) {
1328
		sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
		if (sz < 0)
			return -ENOMEM;

		rsp->SecurityBufferLength = cpu_to_le16(sz);
		return 0;
	}

	sz = sizeof(struct challenge_message);
	sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;

	neg_blob = kzalloc(sz, GFP_KERNEL);
	if (!neg_blob)
		return -ENOMEM;

	chgblob = (struct challenge_message *)neg_blob;
1344
	sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1345 1346 1347 1348 1349
	if (sz < 0) {
		rc = -ENOMEM;
		goto out;
	}

1350 1351
	rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
					   neg_blob, sz);
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
	if (rc) {
		rc = -ENOMEM;
		goto out;
	}

	sz = le16_to_cpu(rsp->SecurityBufferOffset);
	memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
	rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);

out:
	kfree(spnego_blob);
	kfree(neg_blob);
	return rc;
}

static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1368
						  struct smb2_sess_setup_req *req)
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
{
	int sz;

	if (conn->use_spnego && conn->mechToken)
		return (struct authenticate_message *)conn->mechToken;

	sz = le16_to_cpu(req->SecurityBufferOffset);
	return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
					       + sz);
}

static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1381
				       struct smb2_sess_setup_req *req)
1382 1383 1384 1385
{
	struct authenticate_message *authblob;
	struct ksmbd_user *user;
	char *name;
1386
	unsigned int auth_msg_len, name_off, name_len, secbuf_len;
1387

1388 1389 1390 1391 1392
	secbuf_len = le16_to_cpu(req->SecurityBufferLength);
	if (secbuf_len < sizeof(struct authenticate_message)) {
		ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
		return NULL;
	}
1393
	authblob = user_authblob(conn, req);
1394 1395 1396 1397 1398 1399 1400 1401 1402
	name_off = le32_to_cpu(authblob->UserName.BufferOffset);
	name_len = le16_to_cpu(authblob->UserName.Length);
	auth_msg_len = le16_to_cpu(req->SecurityBufferOffset) + secbuf_len;

	if (auth_msg_len < (u64)name_off + name_len)
		return NULL;

	name = smb_strndup_from_utf16((const char *)authblob + name_off,
				      name_len,
1403 1404 1405
				      true,
				      conn->local_nls);
	if (IS_ERR(name)) {
N
Namjae Jeon 已提交
1406
		pr_err("cannot allocate memory\n");
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
		return NULL;
	}

	ksmbd_debug(SMB, "session setup request for user %s\n", name);
	user = ksmbd_login_user(name);
	kfree(name);
	return user;
}

static int ntlm_authenticate(struct ksmbd_work *work)
{
1418 1419
	struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
	struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1420 1421 1422 1423
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_session *sess = work->sess;
	struct channel *chann = NULL;
	struct ksmbd_user *user;
1424
	u64 prev_id;
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
	int sz, rc;

	ksmbd_debug(SMB, "authenticate phase\n");
	if (conn->use_spnego) {
		unsigned char *spnego_blob;
		u16 spnego_blob_len;

		rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
						    &spnego_blob_len,
						    0);
		if (rc)
			return -ENOMEM;

		sz = le16_to_cpu(rsp->SecurityBufferOffset);
1439
		memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1440 1441
		rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
		kfree(spnego_blob);
1442
		inc_rfc1001_len(work->response_buf, spnego_blob_len - 1);
1443 1444 1445 1446 1447
	}

	user = session_user(conn, req);
	if (!user) {
		ksmbd_debug(SMB, "Unknown user name or an error\n");
1448
		return -EPERM;
1449 1450 1451 1452 1453
	}

	/* Check for previous session */
	prev_id = le64_to_cpu(req->PreviousSessionId);
	if (prev_id && prev_id != sess->id)
1454
		destroy_previous_session(conn, user, prev_id);
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464

	if (sess->state == SMB2_SESSION_VALID) {
		/*
		 * Reuse session if anonymous try to connect
		 * on reauthetication.
		 */
		if (ksmbd_anonymous_user(user)) {
			ksmbd_free_user(user);
			return 0;
		}
1465 1466 1467 1468 1469 1470 1471 1472

		if (!ksmbd_compare_user(sess->user, user)) {
			ksmbd_free_user(user);
			return -EPERM;
		}
		ksmbd_free_user(user);
	} else {
		sess->user = user;
1473 1474 1475 1476 1477 1478 1479 1480 1481
	}

	if (user_guest(sess->user)) {
		rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
	} else {
		struct authenticate_message *authblob;

		authblob = user_authblob(conn, req);
		sz = le16_to_cpu(req->SecurityBufferLength);
1482
		rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1483 1484 1485
		if (rc) {
			set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
			ksmbd_debug(SMB, "authentication failed\n");
1486
			return -EPERM;
1487
		}
1488
	}
1489

1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
	/*
	 * If session state is SMB2_SESSION_VALID, We can assume
	 * that it is reauthentication. And the user/password
	 * has been verified, so return it here.
	 */
	if (sess->state == SMB2_SESSION_VALID) {
		if (conn->binding)
			goto binding_session;
		return 0;
	}
1500

1501 1502 1503 1504 1505 1506 1507
	if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
	     (conn->sign || server_conf.enforced_signing)) ||
	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
		sess->sign = true;

	if (smb3_encryption_negotiated(conn) &&
			!(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1508
		rc = conn->ops->generate_encryptionkey(conn, sess);
1509 1510 1511 1512
		if (rc) {
			ksmbd_debug(SMB,
					"SMB3 encryption key generation failed\n");
			return -EINVAL;
1513
		}
1514 1515 1516 1517 1518 1519 1520
		sess->enc = true;
		rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
		/*
		 * signing is disable if encryption is enable
		 * on this session
		 */
		sess->sign = false;
1521 1522
	}

1523
binding_session:
1524
	if (conn->dialect >= SMB30_PROT_ID) {
N
Namjae Jeon 已提交
1525
		read_lock(&sess->chann_lock);
1526
		chann = lookup_chann_list(sess, conn);
N
Namjae Jeon 已提交
1527
		read_unlock(&sess->chann_lock);
1528 1529 1530 1531 1532 1533 1534
		if (!chann) {
			chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
			if (!chann)
				return -ENOMEM;

			chann->conn = conn;
			INIT_LIST_HEAD(&chann->chann_list);
N
Namjae Jeon 已提交
1535
			write_lock(&sess->chann_lock);
1536
			list_add(&chann->chann_list, &sess->ksmbd_chann_list);
N
Namjae Jeon 已提交
1537
			write_unlock(&sess->chann_lock);
1538 1539 1540 1541
		}
	}

	if (conn->ops->generate_signingkey) {
1542
		rc = conn->ops->generate_signingkey(sess, conn);
1543
		if (rc) {
1544
			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1545
			return -EINVAL;
1546 1547 1548
		}
	}

1549 1550 1551
	if (!ksmbd_conn_lookup_dialect(conn)) {
		pr_err("fail to verify the dialect\n");
		return -ENOENT;
1552 1553 1554 1555 1556 1557 1558
	}
	return 0;
}

#ifdef CONFIG_SMB_SERVER_KERBEROS5
static int krb5_authenticate(struct ksmbd_work *work)
{
1559 1560
	struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
	struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1561 1562 1563 1564
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_session *sess = work->sess;
	char *in_blob, *out_blob;
	struct channel *chann = NULL;
1565
	u64 prev_sess_id;
1566 1567 1568 1569 1570 1571 1572 1573 1574
	int in_len, out_len;
	int retval;

	in_blob = (char *)&req->hdr.ProtocolId +
		le16_to_cpu(req->SecurityBufferOffset);
	in_len = le16_to_cpu(req->SecurityBufferLength);
	out_blob = (char *)&rsp->hdr.ProtocolId +
		le16_to_cpu(rsp->SecurityBufferOffset);
	out_len = work->response_sz -
1575
		(le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1576 1577 1578 1579

	/* Check previous session */
	prev_sess_id = le64_to_cpu(req->PreviousSessionId);
	if (prev_sess_id && prev_sess_id != sess->id)
1580
		destroy_previous_session(conn, sess->user, prev_sess_id);
1581 1582 1583 1584 1585

	if (sess->state == SMB2_SESSION_VALID)
		ksmbd_free_user(sess->user);

	retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1586
					 out_blob, &out_len);
1587 1588
	if (retval) {
		ksmbd_debug(SMB, "krb5 authentication failed\n");
1589
		return -EINVAL;
1590 1591
	}
	rsp->SecurityBufferLength = cpu_to_le16(out_len);
1592
	inc_rfc1001_len(work->response_buf, out_len - 1);
1593 1594

	if ((conn->sign || server_conf.enforced_signing) ||
1595
	    (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1596 1597
		sess->sign = true;

1598
	if (smb3_encryption_negotiated(conn)) {
1599
		retval = conn->ops->generate_encryptionkey(conn, sess);
1600 1601
		if (retval) {
			ksmbd_debug(SMB,
1602
				    "SMB3 encryption key generation failed\n");
1603
			return -EINVAL;
1604 1605 1606 1607 1608 1609 1610
		}
		sess->enc = true;
		rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
		sess->sign = false;
	}

	if (conn->dialect >= SMB30_PROT_ID) {
N
Namjae Jeon 已提交
1611
		read_lock(&sess->chann_lock);
1612
		chann = lookup_chann_list(sess, conn);
N
Namjae Jeon 已提交
1613
		read_unlock(&sess->chann_lock);
1614 1615 1616 1617 1618 1619 1620
		if (!chann) {
			chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
			if (!chann)
				return -ENOMEM;

			chann->conn = conn;
			INIT_LIST_HEAD(&chann->chann_list);
N
Namjae Jeon 已提交
1621
			write_lock(&sess->chann_lock);
1622
			list_add(&chann->chann_list, &sess->ksmbd_chann_list);
N
Namjae Jeon 已提交
1623
			write_unlock(&sess->chann_lock);
1624 1625 1626 1627
		}
	}

	if (conn->ops->generate_signingkey) {
1628
		retval = conn->ops->generate_signingkey(sess, conn);
1629
		if (retval) {
1630
			ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1631
			return -EINVAL;
1632 1633 1634
		}
	}

1635 1636 1637
	if (!ksmbd_conn_lookup_dialect(conn)) {
		pr_err("fail to verify the dialect\n");
		return -ENOENT;
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
	}
	return 0;
}
#else
static int krb5_authenticate(struct ksmbd_work *work)
{
	return -EOPNOTSUPP;
}
#endif

int smb2_sess_setup(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
1651 1652
	struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
	struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1653 1654
	struct ksmbd_session *sess;
	struct negotiate_message *negblob;
1655
	unsigned int negblob_len, negblob_off;
1656 1657 1658 1659 1660 1661 1662 1663
	int rc = 0;

	ksmbd_debug(SMB, "Received request for session setup\n");

	rsp->StructureSize = cpu_to_le16(9);
	rsp->SessionFlags = 0;
	rsp->SecurityBufferOffset = cpu_to_le16(72);
	rsp->SecurityBufferLength = 0;
1664
	inc_rfc1001_len(work->response_buf, 9);
1665 1666 1667 1668 1669 1670 1671 1672

	if (!req->hdr.SessionId) {
		sess = ksmbd_smb2_session_create();
		if (!sess) {
			rc = -ENOMEM;
			goto out_err;
		}
		rsp->hdr.SessionId = cpu_to_le64(sess->id);
1673 1674 1675
		rc = ksmbd_session_register(conn, sess);
		if (rc)
			goto out_err;
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
	} else if (conn->dialect >= SMB30_PROT_ID &&
		   (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
		   req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
		u64 sess_id = le64_to_cpu(req->hdr.SessionId);

		sess = ksmbd_session_lookup_slowpath(sess_id);
		if (!sess) {
			rc = -ENOENT;
			goto out_err;
		}

1687
		if (conn->dialect != sess->dialect) {
1688 1689 1690 1691 1692 1693 1694 1695 1696
			rc = -EINVAL;
			goto out_err;
		}

		if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
			rc = -EINVAL;
			goto out_err;
		}

1697
		if (strncmp(conn->ClientGUID, sess->ClientGUID,
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
			    SMB2_CLIENT_GUID_SIZE)) {
			rc = -ENOENT;
			goto out_err;
		}

		if (sess->state == SMB2_SESSION_IN_PROGRESS) {
			rc = -EACCES;
			goto out_err;
		}

		if (sess->state == SMB2_SESSION_EXPIRED) {
			rc = -EFAULT;
			goto out_err;
		}

		if (ksmbd_session_lookup(conn, sess_id)) {
			rc = -EACCES;
			goto out_err;
		}

		conn->binding = true;
	} else if ((conn->dialect < SMB30_PROT_ID ||
		    server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
		   (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1722
		sess = NULL;
1723 1724
		rc = -EACCES;
		goto out_err;
1725 1726
	} else {
		sess = ksmbd_session_lookup(conn,
1727
					    le64_to_cpu(req->hdr.SessionId));
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
		if (!sess) {
			rc = -ENOENT;
			goto out_err;
		}
	}
	work->sess = sess;

	if (sess->state == SMB2_SESSION_EXPIRED)
		sess->state = SMB2_SESSION_IN_PROGRESS;

1738 1739
	negblob_off = le16_to_cpu(req->SecurityBufferOffset);
	negblob_len = le16_to_cpu(req->SecurityBufferLength);
1740
	if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer) ||
1741 1742 1743 1744
	    negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
		rc = -EINVAL;
		goto out_err;
	}
1745

1746
	negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1747
			negblob_off);
1748

1749
	if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1750 1751 1752 1753 1754
		if (conn->mechToken)
			negblob = (struct negotiate_message *)conn->mechToken;
	}

	if (server_conf.auth_mechs & conn->auth_mechs) {
1755 1756 1757 1758
		rc = generate_preauth_hash(work);
		if (rc)
			goto out_err;

1759 1760 1761 1762
		if (conn->preferred_auth_mech &
				(KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
			rc = krb5_authenticate(work);
			if (rc) {
1763
				rc = -EINVAL;
1764 1765 1766 1767 1768
				goto out_err;
			}

			ksmbd_conn_set_good(work);
			sess->state = SMB2_SESSION_VALID;
1769
			kfree(sess->Preauth_HashValue);
1770 1771 1772
			sess->Preauth_HashValue = NULL;
		} else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
			if (negblob->MessageType == NtLmNegotiate) {
1773
				rc = ntlm_negotiate(work, negblob, negblob_len);
1774 1775 1776 1777 1778 1779 1780 1781
				if (rc)
					goto out_err;
				rsp->hdr.Status =
					STATUS_MORE_PROCESSING_REQUIRED;
				/*
				 * Note: here total size -1 is done as an
				 * adjustment for 0 size blob
				 */
1782 1783
				inc_rfc1001_len(work->response_buf,
						le16_to_cpu(rsp->SecurityBufferLength) - 1);
1784 1785 1786 1787 1788 1789 1790 1791

			} else if (negblob->MessageType == NtLmAuthenticate) {
				rc = ntlm_authenticate(work);
				if (rc)
					goto out_err;

				ksmbd_conn_set_good(work);
				sess->state = SMB2_SESSION_VALID;
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
				if (conn->binding) {
					struct preauth_session *preauth_sess;

					preauth_sess =
						ksmbd_preauth_session_lookup(conn, sess->id);
					if (preauth_sess) {
						list_del(&preauth_sess->preauth_entry);
						kfree(preauth_sess);
					}
				}
1802
				kfree(sess->Preauth_HashValue);
1803
				sess->Preauth_HashValue = NULL;
1804 1805 1806 1807
			} else {
				pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
						le32_to_cpu(negblob->MessageType));
				rc = -EINVAL;
1808 1809 1810
			}
		} else {
			/* TODO: need one more negotiation */
N
Namjae Jeon 已提交
1811
			pr_err("Not support the preferred authentication\n");
1812 1813 1814
			rc = -EINVAL;
		}
	} else {
N
Namjae Jeon 已提交
1815
		pr_err("Not support authentication\n");
1816 1817 1818 1819
		rc = -EINVAL;
	}

out_err:
1820 1821 1822 1823 1824 1825 1826 1827
	if (rc == -EINVAL)
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
	else if (rc == -ENOENT)
		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
	else if (rc == -EACCES)
		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
	else if (rc == -EFAULT)
		rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1828 1829
	else if (rc == -ENOMEM)
		rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1830 1831 1832
	else if (rc)
		rsp->hdr.Status = STATUS_LOGON_FAILURE;

1833 1834 1835 1836 1837
	if (conn->use_spnego && conn->mechToken) {
		kfree(conn->mechToken);
		conn->mechToken = NULL;
	}

1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
	if (rc < 0) {
		/*
		 * SecurityBufferOffset should be set to zero
		 * in session setup error response.
		 */
		rsp->SecurityBufferOffset = 0;

		if (sess) {
			bool try_delay = false;

			/*
			 * To avoid dictionary attacks (repeated session setups rapidly sent) to
			 * connect to server, ksmbd make a delay of a 5 seconds on session setup
			 * failure to make it harder to send enough random connection requests
			 * to break into a server.
			 */
			if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
				try_delay = true;

1857
			xa_erase(&conn->sessions, sess->id);
1858 1859 1860 1861 1862
			ksmbd_session_destroy(sess);
			work->sess = NULL;
			if (try_delay)
				ssleep(5);
		}
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
	}

	return rc;
}

/**
 * smb2_tree_connect() - handler for smb2 tree connect command
 * @work:	smb work containing smb request buffer
 *
 * Return:      0 on success, otherwise error
 */
int smb2_tree_connect(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
1877 1878
	struct smb2_tree_connect_req *req = smb2_get_msg(work->request_buf);
	struct smb2_tree_connect_rsp *rsp = smb2_get_msg(work->response_buf);
1879 1880 1881 1882 1883 1884 1885
	struct ksmbd_session *sess = work->sess;
	char *treename = NULL, *name = NULL;
	struct ksmbd_tree_conn_status status;
	struct ksmbd_share_config *share;
	int rc = -EINVAL;

	treename = smb_strndup_from_utf16(req->Buffer,
1886 1887
					  le16_to_cpu(req->PathLength), true,
					  conn->local_nls);
1888
	if (IS_ERR(treename)) {
N
Namjae Jeon 已提交
1889
		pr_err("treename is NULL\n");
1890 1891 1892 1893
		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
		goto out_err1;
	}

1894
	name = ksmbd_extract_sharename(treename);
1895 1896 1897 1898 1899 1900
	if (IS_ERR(name)) {
		status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
		goto out_err1;
	}

	ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1901
		    name, treename);
1902

1903
	status = ksmbd_tree_conn_connect(conn, sess, name);
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
	if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
		rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
	else
		goto out_err1;

	share = status.tree_conn->share_conf;
	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
		ksmbd_debug(SMB, "IPC share path request\n");
		rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
			FILE_DELETE_LE | FILE_READ_CONTROL_LE |
			FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
			FILE_SYNCHRONIZE_LE;
	} else {
		rsp->ShareType = SMB2_SHARE_TYPE_DISK;
		rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
			FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
		if (test_tree_conn_flag(status.tree_conn,
					KSMBD_TREE_CONN_FLAG_WRITABLE)) {
			rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
				FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
W
Wan Jiabing 已提交
1926 1927 1928 1929
				FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
				FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
				FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
				FILE_SYNCHRONIZE_LE;
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942
		}
	}

	status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
	if (conn->posix_ext_supported)
		status.tree_conn->posix_extensions = true;

out_err1:
	rsp->StructureSize = cpu_to_le16(16);
	rsp->Capabilities = 0;
	rsp->Reserved = 0;
	/* default manual caching */
	rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
1943
	inc_rfc1001_len(work->response_buf, 16);
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954

	if (!IS_ERR(treename))
		kfree(treename);
	if (!IS_ERR(name))
		kfree(name);

	switch (status.ret) {
	case KSMBD_TREE_CONN_STATUS_OK:
		rsp->hdr.Status = STATUS_SUCCESS;
		rc = 0;
		break;
1955
	case -ENOENT:
1956
	case KSMBD_TREE_CONN_STATUS_NO_SHARE:
1957
		rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
		break;
	case -ENOMEM:
	case KSMBD_TREE_CONN_STATUS_NOMEM:
		rsp->hdr.Status = STATUS_NO_MEMORY;
		break;
	case KSMBD_TREE_CONN_STATUS_ERROR:
	case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
	case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
		break;
	case -EINVAL:
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		break;
	default:
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
	}

	return rc;
}

/**
 * smb2_create_open_flags() - convert smb open flags to unix open flags
 * @file_present:	is file already present
 * @access:		file access flags
 * @disposition:	file disposition flags
1983
 * @may_flags:		set with MAY_ flags
1984 1985 1986 1987
 *
 * Return:      file open flags
 */
static int smb2_create_open_flags(bool file_present, __le32 access,
1988 1989
				  __le32 disposition,
				  int *may_flags)
1990 1991 1992 1993
{
	int oflags = O_NONBLOCK | O_LARGEFILE;

	if (access & FILE_READ_DESIRED_ACCESS_LE &&
1994
	    access & FILE_WRITE_DESIRE_ACCESS_LE) {
1995
		oflags |= O_RDWR;
1996 1997
		*may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
	} else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
1998
		oflags |= O_WRONLY;
1999 2000
		*may_flags = MAY_OPEN | MAY_WRITE;
	} else {
2001
		oflags |= O_RDONLY;
2002 2003
		*may_flags = MAY_OPEN | MAY_READ;
	}
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036

	if (access == FILE_READ_ATTRIBUTES_LE)
		oflags |= O_PATH;

	if (file_present) {
		switch (disposition & FILE_CREATE_MASK_LE) {
		case FILE_OPEN_LE:
		case FILE_CREATE_LE:
			break;
		case FILE_SUPERSEDE_LE:
		case FILE_OVERWRITE_LE:
		case FILE_OVERWRITE_IF_LE:
			oflags |= O_TRUNC;
			break;
		default:
			break;
		}
	} else {
		switch (disposition & FILE_CREATE_MASK_LE) {
		case FILE_SUPERSEDE_LE:
		case FILE_CREATE_LE:
		case FILE_OPEN_IF_LE:
		case FILE_OVERWRITE_IF_LE:
			oflags |= O_CREAT;
			break;
		case FILE_OPEN_LE:
		case FILE_OVERWRITE_LE:
			oflags &= ~O_CREAT;
			break;
		default:
			break;
		}
	}
2037

2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
	return oflags;
}

/**
 * smb2_tree_disconnect() - handler for smb tree connect request
 * @work:	smb work containing request buffer
 *
 * Return:      0
 */
int smb2_tree_disconnect(struct ksmbd_work *work)
{
2049
	struct smb2_tree_disconnect_rsp *rsp = smb2_get_msg(work->response_buf);
2050 2051 2052 2053
	struct ksmbd_session *sess = work->sess;
	struct ksmbd_tree_connect *tcon = work->tcon;

	rsp->StructureSize = cpu_to_le16(4);
2054
	inc_rfc1001_len(work->response_buf, 4);
2055 2056 2057 2058

	ksmbd_debug(SMB, "request\n");

	if (!tcon) {
2059 2060
		struct smb2_tree_disconnect_req *req =
			smb2_get_msg(work->request_buf);
2061 2062 2063 2064 2065 2066 2067 2068 2069

		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
		smb2_set_err_rsp(work);
		return 0;
	}

	ksmbd_close_tree_conn_fds(work);
	ksmbd_tree_conn_disconnect(sess, tcon);
2070
	work->tcon = NULL;
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
	return 0;
}

/**
 * smb2_session_logoff() - handler for session log off request
 * @work:	smb work containing request buffer
 *
 * Return:      0
 */
int smb2_session_logoff(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
2083
	struct smb2_logoff_rsp *rsp = smb2_get_msg(work->response_buf);
2084 2085 2086
	struct ksmbd_session *sess = work->sess;

	rsp->StructureSize = cpu_to_le16(4);
2087
	inc_rfc1001_len(work->response_buf, 4);
2088 2089 2090 2091 2092 2093 2094 2095 2096

	ksmbd_debug(SMB, "request\n");

	/* setting CifsExiting here may race with start_tcp_sess */
	ksmbd_conn_set_need_reconnect(work);
	ksmbd_close_session_fds(work);
	ksmbd_conn_wait_idle(conn);

	if (ksmbd_tree_conn_session_logoff(sess)) {
2097
		struct smb2_logoff_req *req = smb2_get_msg(work->request_buf);
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123

		ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
		rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
		smb2_set_err_rsp(work);
		return 0;
	}

	ksmbd_destroy_file_table(&sess->file_table);
	sess->state = SMB2_SESSION_EXPIRED;

	ksmbd_free_user(sess->user);
	sess->user = NULL;

	/* let start_tcp_sess free connection info now */
	ksmbd_conn_set_need_negotiate(work);
	return 0;
}

/**
 * create_smb2_pipe() - create IPC pipe
 * @work:	smb work containing request buffer
 *
 * Return:      0 on success, otherwise error
 */
static noinline int create_smb2_pipe(struct ksmbd_work *work)
{
2124 2125
	struct smb2_create_rsp *rsp = smb2_get_msg(work->response_buf);
	struct smb2_create_req *req = smb2_get_msg(work->request_buf);
2126 2127 2128 2129 2130
	int id;
	int err;
	char *name;

	name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2131
				      1, work->conn->local_nls);
2132 2133 2134 2135 2136 2137 2138
	if (IS_ERR(name)) {
		rsp->hdr.Status = STATUS_NO_MEMORY;
		err = PTR_ERR(name);
		goto out;
	}

	id = ksmbd_session_rpc_open(work->sess, name);
2139
	if (id < 0) {
N
Namjae Jeon 已提交
2140
		pr_err("Unable to open RPC pipe: %d\n", id);
2141 2142 2143
		err = id;
		goto out;
	}
2144

2145
	rsp->hdr.Status = STATUS_SUCCESS;
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
	rsp->StructureSize = cpu_to_le16(89);
	rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
	rsp->Reserved = 0;
	rsp->CreateAction = cpu_to_le32(FILE_OPENED);

	rsp->CreationTime = cpu_to_le64(0);
	rsp->LastAccessTime = cpu_to_le64(0);
	rsp->ChangeTime = cpu_to_le64(0);
	rsp->AllocationSize = cpu_to_le64(0);
	rsp->EndofFile = cpu_to_le64(0);
	rsp->FileAttributes = ATTR_NORMAL_LE;
	rsp->Reserved2 = 0;
	rsp->VolatileFileId = cpu_to_le64(id);
	rsp->PersistentFileId = 0;
	rsp->CreateContextsOffset = 0;
	rsp->CreateContextsLength = 0;

2163
	inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
2164 2165 2166 2167
	kfree(name);
	return 0;

out:
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180
	switch (err) {
	case -EINVAL:
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		break;
	case -ENOSPC:
	case -ENOMEM:
		rsp->hdr.Status = STATUS_NO_MEMORY;
		break;
	}

	if (!IS_ERR(name))
		kfree(name);

2181 2182 2183 2184 2185 2186 2187 2188
	smb2_set_err_rsp(work);
	return err;
}

/**
 * smb2_set_ea() - handler for setting extended attributes using set
 *		info command
 * @eabuf:	set info command buffer
2189
 * @buf_len:	set info command buffer length
2190 2191 2192 2193
 * @path:	dentry path for get ea
 *
 * Return:	0 on success, otherwise error
 */
2194 2195
static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
		       struct path *path)
2196 2197 2198
{
	char *attr_name = NULL, *value;
	int rc = 0;
2199 2200 2201 2202 2203
	unsigned int next = 0;

	if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
			le16_to_cpu(eabuf->EaValueLength))
		return -EINVAL;
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213

	attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
	if (!attr_name)
		return -ENOMEM;

	do {
		if (!eabuf->EaNameLength)
			goto next;

		ksmbd_debug(SMB,
2214 2215 2216 2217
			    "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
			    eabuf->name, eabuf->EaNameLength,
			    le16_to_cpu(eabuf->EaValueLength),
			    le32_to_cpu(eabuf->NextEntryOffset));
2218 2219

		if (eabuf->EaNameLength >
2220
		    (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2221 2222 2223 2224 2225 2226
			rc = -EINVAL;
			break;
		}

		memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
		memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2227
		       eabuf->EaNameLength);
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
		attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
		value = (char *)&eabuf->name + eabuf->EaNameLength + 1;

		if (!eabuf->EaValueLength) {
			rc = ksmbd_vfs_casexattr_len(path->dentry,
						     attr_name,
						     XATTR_USER_PREFIX_LEN +
						     eabuf->EaNameLength);

			/* delete the EA only when it exits */
			if (rc > 0) {
				rc = ksmbd_vfs_remove_xattr(path->dentry,
							    attr_name);

				if (rc < 0) {
					ksmbd_debug(SMB,
2244 2245
						    "remove xattr failed(%d)\n",
						    rc);
2246 2247 2248 2249 2250 2251 2252 2253
					break;
				}
			}

			/* if the EA doesn't exist, just do nothing. */
			rc = 0;
		} else {
			rc = ksmbd_vfs_setxattr(path->dentry, attr_name, value,
2254
						le16_to_cpu(eabuf->EaValueLength), 0);
2255 2256
			if (rc < 0) {
				ksmbd_debug(SMB,
2257 2258
					    "ksmbd_vfs_setxattr is failed(%d)\n",
					    rc);
2259 2260 2261 2262 2263 2264
				break;
			}
		}

next:
		next = le32_to_cpu(eabuf->NextEntryOffset);
2265 2266 2267
		if (next == 0 || buf_len < next)
			break;
		buf_len -= next;
2268
		eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2269 2270 2271
		if (next < (u32)eabuf->EaNameLength + le16_to_cpu(eabuf->EaValueLength))
			break;

2272 2273 2274 2275 2276 2277 2278
	} while (next != 0);

	kfree(attr_name);
	return rc;
}

static noinline int smb2_set_stream_name_xattr(struct path *path,
2279 2280
					       struct ksmbd_file *fp,
					       char *stream_name, int s_type)
2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309
{
	size_t xattr_stream_size;
	char *xattr_stream_name;
	int rc;

	rc = ksmbd_vfs_xattr_stream_name(stream_name,
					 &xattr_stream_name,
					 &xattr_stream_size,
					 s_type);
	if (rc)
		return rc;

	fp->stream.name = xattr_stream_name;
	fp->stream.size = xattr_stream_size;

	/* Check if there is stream prefix in xattr space */
	rc = ksmbd_vfs_casexattr_len(path->dentry,
				     xattr_stream_name,
				     xattr_stream_size);
	if (rc >= 0)
		return 0;

	if (fp->cdoption == FILE_OPEN_LE) {
		ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
		return -EBADF;
	}

	rc = ksmbd_vfs_setxattr(path->dentry, xattr_stream_name, NULL, 0, 0);
	if (rc < 0)
N
Namjae Jeon 已提交
2310
		pr_err("Failed to store XATTR stream name :%d\n", rc);
2311 2312 2313
	return 0;
}

2314
static int smb2_remove_smb_xattrs(struct path *path)
2315 2316 2317 2318 2319
{
	char *name, *xattr_list = NULL;
	ssize_t xattr_list_len;
	int err = 0;

2320
	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
	if (xattr_list_len < 0) {
		goto out;
	} else if (!xattr_list_len) {
		ksmbd_debug(SMB, "empty xattr in the file\n");
		goto out;
	}

	for (name = xattr_list; name - xattr_list < xattr_list_len;
			name += strlen(name) + 1) {
		ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));

		if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2333 2334 2335
		    strncmp(&name[XATTR_USER_PREFIX_LEN], DOS_ATTRIBUTE_PREFIX,
			    DOS_ATTRIBUTE_PREFIX_LEN) &&
		    strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX, STREAM_PREFIX_LEN))
2336 2337
			continue;

2338
		err = ksmbd_vfs_remove_xattr(path->dentry, name);
2339 2340 2341 2342
		if (err)
			ksmbd_debug(SMB, "remove xattr failed : %s\n", name);
	}
out:
2343
	kvfree(xattr_list);
2344 2345 2346 2347 2348 2349 2350 2351
	return err;
}

static int smb2_create_truncate(struct path *path)
{
	int rc = vfs_truncate(path, 0);

	if (rc) {
N
Namjae Jeon 已提交
2352
		pr_err("vfs_truncate failed, rc %d\n", rc);
2353 2354 2355
		return rc;
	}

2356
	rc = smb2_remove_smb_xattrs(path);
2357 2358 2359 2360
	if (rc == -EOPNOTSUPP)
		rc = 0;
	if (rc)
		ksmbd_debug(SMB,
2361 2362
			    "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
			    rc);
2363 2364 2365
	return rc;
}

2366
static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, struct path *path,
2367
			    struct ksmbd_file *fp)
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
{
	struct xattr_dos_attrib da = {0};
	int rc;

	if (!test_share_config_flag(tcon->share_conf,
				    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
		return;

	da.version = 4;
	da.attr = le32_to_cpu(fp->f_ci->m_fattr);
	da.itime = da.create_time = fp->create_time;
	da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
		XATTR_DOSINFO_ITIME;

	rc = ksmbd_vfs_set_dos_attrib_xattr(path->dentry, &da);
	if (rc)
		ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
}

static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2388
			       struct path *path, struct ksmbd_file *fp)
2389 2390 2391 2392 2393 2394 2395 2396
{
	struct xattr_dos_attrib da;
	int rc;

	fp->f_ci->m_fattr &= ~(ATTR_HIDDEN_LE | ATTR_SYSTEM_LE);

	/* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
	if (!test_share_config_flag(tcon->share_conf,
2397
				    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407
		return;

	rc = ksmbd_vfs_get_dos_attrib_xattr(path->dentry, &da);
	if (rc > 0) {
		fp->f_ci->m_fattr = cpu_to_le32(da.attr);
		fp->create_time = da.create_time;
		fp->itime = da.itime;
	}
}

2408
static int smb2_creat(struct ksmbd_work *work, struct path *path, char *name,
2409
		      int open_flags, umode_t posix_mode, bool is_dir)
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
{
	struct ksmbd_tree_connect *tcon = work->tcon;
	struct ksmbd_share_config *share = tcon->share_conf;
	umode_t mode;
	int rc;

	if (!(open_flags & O_CREAT))
		return -EBADF;

	ksmbd_debug(SMB, "file does not exist, so creating\n");
	if (is_dir == true) {
		ksmbd_debug(SMB, "creating directory\n");

		mode = share_config_directory_mode(share, posix_mode);
		rc = ksmbd_vfs_mkdir(work, name, mode);
		if (rc)
			return rc;
	} else {
		ksmbd_debug(SMB, "creating regular file\n");

		mode = share_config_create_mode(share, posix_mode);
		rc = ksmbd_vfs_create(work, name, mode);
		if (rc)
			return rc;
	}

2436
	rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
2437
	if (rc) {
N
Namjae Jeon 已提交
2438 2439
		pr_err("cannot get linux path (%s), err = %d\n",
		       name, rc);
2440 2441 2442 2443 2444 2445
		return rc;
	}
	return 0;
}

static int smb2_create_sd_buffer(struct ksmbd_work *work,
2446
				 struct smb2_create_req *req,
2447
				 struct path *path)
2448 2449
{
	struct create_context *context;
2450
	struct create_sd_buf_req *sd_buf;
2451 2452

	if (!req->CreateContextsOffset)
2453
		return -ENOENT;
2454 2455

	/* Parse SD BUFFER create contexts */
2456
	context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2457 2458 2459 2460
	if (!context)
		return -ENOENT;
	else if (IS_ERR(context))
		return PTR_ERR(context);
2461

2462 2463 2464
	ksmbd_debug(SMB,
		    "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
	sd_buf = (struct create_sd_buf_req *)context;
2465 2466 2467 2468
	if (le16_to_cpu(context->DataOffset) +
	    le32_to_cpu(context->DataLength) <
	    sizeof(struct create_sd_buf_req))
		return -EINVAL;
2469 2470
	return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
			    le32_to_cpu(sd_buf->ccontext.DataLength), true);
2471 2472
}

2473 2474 2475 2476 2477
static void ksmbd_acls_fattr(struct smb_fattr *fattr, struct inode *inode)
{
	fattr->cf_uid = inode->i_uid;
	fattr->cf_gid = inode->i_gid;
	fattr->cf_mode = inode->i_mode;
2478
	fattr->cf_acls = NULL;
2479 2480
	fattr->cf_dacls = NULL;

2481 2482 2483 2484 2485
	if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
		fattr->cf_acls = get_acl(inode, ACL_TYPE_ACCESS);
		if (S_ISDIR(inode->i_mode))
			fattr->cf_dacls = get_acl(inode, ACL_TYPE_DEFAULT);
	}
2486 2487
}

2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
/**
 * smb2_open() - handler for smb file open request
 * @work:	smb work containing request buffer
 *
 * Return:      0 on success, otherwise error
 */
int smb2_open(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_session *sess = work->sess;
	struct ksmbd_tree_connect *tcon = work->tcon;
	struct smb2_create_req *req;
2500
	struct smb2_create_rsp *rsp;
2501 2502 2503 2504 2505 2506 2507 2508 2509 2510
	struct path path;
	struct ksmbd_share_config *share = tcon->share_conf;
	struct ksmbd_file *fp = NULL;
	struct file *filp = NULL;
	struct kstat stat;
	struct create_context *context;
	struct lease_ctx_info *lc = NULL;
	struct create_ea_buf_req *ea_buf = NULL;
	struct oplock_info *opinfo;
	__le32 *next_ptr = NULL;
2511
	int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2512
	int rc = 0;
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
	int contxt_cnt = 0, query_disk_id = 0;
	int maximal_access_ctxt = 0, posix_ctxt = 0;
	int s_type = 0;
	int next_off = 0;
	char *name = NULL;
	char *stream_name = NULL;
	bool file_present = false, created = false, already_permitted = false;
	int share_ret, need_truncate = 0;
	u64 time;
	umode_t posix_mode = 0;
	__le32 daccess, maximal_access = 0;

	WORK_BUFFERS(work, req, rsp);

	if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2528
	    (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541
		ksmbd_debug(SMB, "invalid flag in chained command\n");
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		smb2_set_err_rsp(work);
		return -EINVAL;
	}

	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
		ksmbd_debug(SMB, "IPC pipe create request\n");
		return create_smb2_pipe(work);
	}

	if (req->NameLength) {
		if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2542
		    *(char *)req->Buffer == '\\') {
N
Namjae Jeon 已提交
2543
			pr_err("not allow directory name included leading slash\n");
2544 2545 2546 2547
			rc = -EINVAL;
			goto err_out1;
		}

2548
		name = smb2_get_name(req->Buffer,
2549 2550 2551 2552 2553 2554
				     le16_to_cpu(req->NameLength),
				     work->conn->local_nls);
		if (IS_ERR(name)) {
			rc = PTR_ERR(name);
			if (rc != -ENOMEM)
				rc = -ENOENT;
2555
			name = NULL;
2556 2557 2558 2559 2560 2561
			goto err_out1;
		}

		ksmbd_debug(SMB, "converted name = %s\n", name);
		if (strchr(name, ':')) {
			if (!test_share_config_flag(work->tcon->share_conf,
2562
						    KSMBD_SHARE_FLAG_STREAMS)) {
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577
				rc = -EBADF;
				goto err_out1;
			}
			rc = parse_stream_name(name, &stream_name, &s_type);
			if (rc < 0)
				goto err_out1;
		}

		rc = ksmbd_validate_filename(name);
		if (rc < 0)
			goto err_out1;

		if (ksmbd_share_veto_filename(share, name)) {
			rc = -ENOENT;
			ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2578
				    name);
2579 2580 2581
			goto err_out1;
		}
	} else {
2582
		name = kstrdup("", GFP_KERNEL);
2583 2584 2585 2586 2587 2588 2589
		if (!name) {
			rc = -ENOMEM;
			goto err_out1;
		}
	}

	req_op_level = req->RequestedOplockLevel;
2590
	if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2591 2592
		lc = parse_lease_state(req);

2593
	if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE_LE)) {
N
Namjae Jeon 已提交
2594 2595
		pr_err("Invalid impersonationlevel : 0x%x\n",
		       le32_to_cpu(req->ImpersonationLevel));
2596 2597 2598 2599 2600 2601
		rc = -EIO;
		rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
		goto err_out1;
	}

	if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK)) {
N
Namjae Jeon 已提交
2602 2603
		pr_err("Invalid create options : 0x%x\n",
		       le32_to_cpu(req->CreateOptions));
2604 2605 2606 2607
		rc = -EINVAL;
		goto err_out1;
	} else {
		if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2608
		    req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2609 2610
			req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);

2611 2612 2613
		if (req->CreateOptions &
		    (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
		     FILE_RESERVE_OPFILTER_LE)) {
2614 2615 2616 2617 2618 2619 2620 2621
			rc = -EOPNOTSUPP;
			goto err_out1;
		}

		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
			if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
				rc = -EINVAL;
				goto err_out1;
2622
			} else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2623
				req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2624
			}
2625 2626 2627 2628
		}
	}

	if (le32_to_cpu(req->CreateDisposition) >
2629
	    le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
N
Namjae Jeon 已提交
2630 2631
		pr_err("Invalid create disposition : 0x%x\n",
		       le32_to_cpu(req->CreateDisposition));
2632 2633 2634 2635 2636
		rc = -EINVAL;
		goto err_out1;
	}

	if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
N
Namjae Jeon 已提交
2637 2638
		pr_err("Invalid desired access : 0x%x\n",
		       le32_to_cpu(req->DesiredAccess));
2639 2640 2641 2642
		rc = -EACCES;
		goto err_out1;
	}

2643
	if (req->FileAttributes && !(req->FileAttributes & ATTR_MASK_LE)) {
N
Namjae Jeon 已提交
2644 2645
		pr_err("Invalid file attribute : 0x%x\n",
		       le32_to_cpu(req->FileAttributes));
2646 2647 2648 2649 2650 2651
		rc = -EINVAL;
		goto err_out1;
	}

	if (req->CreateContextsOffset) {
		/* Parse non-durable handle create contexts */
2652
		context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
2653 2654 2655 2656
		if (IS_ERR(context)) {
			rc = PTR_ERR(context);
			goto err_out1;
		} else if (context) {
2657
			ea_buf = (struct create_ea_buf_req *)context;
2658 2659 2660 2661 2662 2663
			if (le16_to_cpu(context->DataOffset) +
			    le32_to_cpu(context->DataLength) <
			    sizeof(struct create_ea_buf_req)) {
				rc = -EINVAL;
				goto err_out1;
			}
2664 2665 2666 2667 2668 2669 2670 2671
			if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
				rsp->hdr.Status = STATUS_ACCESS_DENIED;
				rc = -EACCES;
				goto err_out1;
			}
		}

		context = smb2_find_context_vals(req,
2672
						 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
2673 2674 2675 2676
		if (IS_ERR(context)) {
			rc = PTR_ERR(context);
			goto err_out1;
		} else if (context) {
2677
			ksmbd_debug(SMB,
2678
				    "get query maximal access context\n");
2679 2680 2681 2682
			maximal_access_ctxt = 1;
		}

		context = smb2_find_context_vals(req,
2683
						 SMB2_CREATE_TIMEWARP_REQUEST, 4);
2684 2685 2686 2687
		if (IS_ERR(context)) {
			rc = PTR_ERR(context);
			goto err_out1;
		} else if (context) {
2688 2689 2690 2691 2692 2693 2694
			ksmbd_debug(SMB, "get timewarp context\n");
			rc = -EBADF;
			goto err_out1;
		}

		if (tcon->posix_extensions) {
			context = smb2_find_context_vals(req,
2695
							 SMB2_CREATE_TAG_POSIX, 16);
2696 2697 2698 2699
			if (IS_ERR(context)) {
				rc = PTR_ERR(context);
				goto err_out1;
			} else if (context) {
2700 2701
				struct create_posix *posix =
					(struct create_posix *)context;
2702 2703
				if (le16_to_cpu(context->DataOffset) +
				    le32_to_cpu(context->DataLength) <
2704
				    sizeof(struct create_posix) - 4) {
2705 2706 2707
					rc = -EINVAL;
					goto err_out1;
				}
2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
				ksmbd_debug(SMB, "get posix context\n");

				posix_mode = le32_to_cpu(posix->Mode);
				posix_ctxt = 1;
			}
		}
	}

	if (ksmbd_override_fsids(work)) {
		rc = -ENOMEM;
		goto err_out1;
	}

2721
	rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS, &path, 1);
2722 2723
	if (!rc) {
		if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2724 2725 2726 2727 2728
			/*
			 * If file exists with under flags, return access
			 * denied error.
			 */
			if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2729
			    req->CreateDisposition == FILE_OPEN_IF_LE) {
2730 2731 2732 2733 2734
				rc = -EACCES;
				path_put(&path);
				goto err_out;
			}

2735
			if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2736
				ksmbd_debug(SMB,
2737
					    "User does not have write permission\n");
2738 2739 2740 2741
				rc = -EACCES;
				path_put(&path);
				goto err_out;
			}
2742 2743 2744 2745
		} else if (d_is_symlink(path.dentry)) {
			rc = -EACCES;
			path_put(&path);
			goto err_out;
2746 2747 2748 2749
		}
	}

	if (rc) {
2750
		if (rc != -ENOENT)
2751 2752
			goto err_out;
		ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2753
			    name, rc);
2754 2755 2756
		rc = 0;
	} else {
		file_present = true;
J
Jason Yan 已提交
2757
		generic_fillattr(d_inode(path.dentry), &stat);
2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772
	}
	if (stream_name) {
		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
			if (s_type == DATA_STREAM) {
				rc = -EIO;
				rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
			}
		} else {
			if (S_ISDIR(stat.mode) && s_type == DATA_STREAM) {
				rc = -EIO;
				rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
			}
		}

		if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2773
		    req->FileAttributes & ATTR_NORMAL_LE) {
2774 2775 2776 2777 2778 2779 2780 2781
			rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
			rc = -EIO;
		}

		if (rc < 0)
			goto err_out;
	}

2782 2783
	if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
	    S_ISDIR(stat.mode) && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2784
		ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2785
			    name, req->CreateOptions);
2786 2787 2788 2789 2790 2791
		rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
		rc = -EIO;
		goto err_out;
	}

	if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2792 2793
	    !(req->CreateDisposition == FILE_CREATE_LE) &&
	    !S_ISDIR(stat.mode)) {
2794 2795 2796 2797 2798 2799
		rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
		rc = -EIO;
		goto err_out;
	}

	if (!stream_name && file_present &&
2800
	    req->CreateDisposition == FILE_CREATE_LE) {
2801 2802 2803 2804 2805 2806 2807
		rc = -EEXIST;
		goto err_out;
	}

	daccess = smb_map_generic_desired_access(req->DesiredAccess);

	if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2808
		rc = smb_check_perm_dacl(conn, &path, &daccess,
2809
					 sess->user->uid);
2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
		if (rc)
			goto err_out;
	}

	if (daccess & FILE_MAXIMAL_ACCESS_LE) {
		if (!file_present) {
			daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
		} else {
			rc = ksmbd_vfs_query_maximal_access(path.dentry,
							    &daccess);
			if (rc)
				goto err_out;
			already_permitted = true;
		}
		maximal_access = daccess;
	}

2827
	open_flags = smb2_create_open_flags(file_present, daccess,
2828 2829
					    req->CreateDisposition,
					    &may_flags);
2830 2831 2832 2833

	if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
		if (open_flags & O_CREAT) {
			ksmbd_debug(SMB,
2834
				    "User does not have write permission\n");
2835 2836 2837 2838 2839 2840 2841 2842
			rc = -EACCES;
			goto err_out;
		}
	}

	/*create file if not present */
	if (!file_present) {
		rc = smb2_creat(work, &path, name, open_flags, posix_mode,
2843
				req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2844 2845 2846 2847 2848
		if (rc) {
			if (rc == -ENOENT) {
				rc = -EIO;
				rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
			}
2849
			goto err_out;
2850
		}
2851 2852 2853

		created = true;
		if (ea_buf) {
2854 2855 2856 2857 2858 2859 2860 2861 2862
			if (le32_to_cpu(ea_buf->ccontext.DataLength) <
			    sizeof(struct smb2_ea_info)) {
				rc = -EINVAL;
				goto err_out;
			}

			rc = smb2_set_ea(&ea_buf->ea,
					 le32_to_cpu(ea_buf->ccontext.DataLength),
					 &path);
2863 2864 2865 2866 2867 2868 2869 2870 2871 2872
			if (rc == -EOPNOTSUPP)
				rc = 0;
			else if (rc)
				goto err_out;
		}
	} else if (!already_permitted) {
		/* FILE_READ_ATTRIBUTE is allowed without inode_permission,
		 * because execute(search) permission on a parent directory,
		 * is already granted.
		 */
2873
		if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
J
Jason Yan 已提交
2874
			rc = inode_permission(d_inode(path.dentry),
2875
					      may_flags);
2876
			if (rc)
2877
				goto err_out;
2878 2879 2880 2881 2882 2883 2884

			if ((daccess & FILE_DELETE_LE) ||
			    (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
				rc = ksmbd_vfs_may_delete(path.dentry);
				if (rc)
					goto err_out;
			}
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897
		}
	}

	rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
	if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
		rc = -EBUSY;
		goto err_out;
	}

	rc = 0;
	filp = dentry_open(&path, open_flags, current_cred());
	if (IS_ERR(filp)) {
		rc = PTR_ERR(filp);
N
Namjae Jeon 已提交
2898
		pr_err("dentry open for dir failed, rc %d\n", rc);
2899 2900 2901 2902 2903 2904 2905 2906 2907
		goto err_out;
	}

	if (file_present) {
		if (!(open_flags & O_TRUNC))
			file_info = FILE_OPENED;
		else
			file_info = FILE_OVERWRITTEN;

2908 2909
		if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
		    FILE_SUPERSEDE_LE)
2910
			file_info = FILE_SUPERSEDED;
2911
	} else if (open_flags & O_CREAT) {
2912
		file_info = FILE_CREATED;
2913
	}
2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927

	ksmbd_vfs_set_fadvise(filp, req->CreateOptions);

	/* Obtain Volatile-ID */
	fp = ksmbd_open_fd(work, filp);
	if (IS_ERR(fp)) {
		fput(filp);
		rc = PTR_ERR(fp);
		fp = NULL;
		goto err_out;
	}

	/* Get Persistent-ID */
	ksmbd_open_durable_fd(fp);
2928
	if (!has_file_id(fp->persistent_id)) {
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941
		rc = -ENOMEM;
		goto err_out;
	}

	fp->filename = name;
	fp->cdoption = req->CreateDisposition;
	fp->daccess = daccess;
	fp->saccess = req->ShareAccess;
	fp->coption = req->CreateOptions;

	/* Set default windows and posix acls if creating new file */
	if (created) {
		int posix_acl_rc;
N
Namjae Jeon 已提交
2942
		struct inode *inode = d_inode(path.dentry);
2943

N
Namjae Jeon 已提交
2944
		posix_acl_rc = ksmbd_vfs_inherit_posix_acl(inode, d_inode(path.dentry->d_parent));
2945 2946 2947 2948
		if (posix_acl_rc)
			ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);

		if (test_share_config_flag(work->tcon->share_conf,
2949
					   KSMBD_SHARE_FLAG_ACL_XATTR)) {
2950
			rc = smb_inherit_dacl(conn, &path, sess->user->uid,
2951
					      sess->user->gid);
2952 2953 2954
		}

		if (rc) {
2955
			rc = smb2_create_sd_buffer(work, req, &path);
2956 2957 2958 2959 2960
			if (rc) {
				if (posix_acl_rc)
					ksmbd_vfs_set_init_posix_acl(inode);

				if (test_share_config_flag(work->tcon->share_conf,
2961
							   KSMBD_SHARE_FLAG_ACL_XATTR)) {
2962 2963
					struct smb_fattr fattr;
					struct smb_ntsd *pntsd;
2964
					int pntsd_size, ace_num = 0;
2965

2966
					ksmbd_acls_fattr(&fattr, inode);
2967 2968
					if (fattr.cf_acls)
						ace_num = fattr.cf_acls->a_count;
2969 2970
					if (fattr.cf_dacls)
						ace_num += fattr.cf_dacls->a_count;
2971 2972

					pntsd = kmalloc(sizeof(struct smb_ntsd) +
2973
							sizeof(struct smb_sid) * 3 +
2974
							sizeof(struct smb_acl) +
2975
							sizeof(struct smb_ace) * ace_num * 2,
2976 2977 2978 2979
							GFP_KERNEL);
					if (!pntsd)
						goto err_out;

2980
					rc = build_sec_desc(pntsd, NULL, 0,
2981 2982 2983 2984
							    OWNER_SECINFO |
							     GROUP_SECINFO |
							     DACL_SECINFO,
							    &pntsd_size, &fattr);
2985 2986
					posix_acl_release(fattr.cf_acls);
					posix_acl_release(fattr.cf_dacls);
2987 2988 2989 2990
					if (rc) {
						kfree(pntsd);
						goto err_out;
					}
2991 2992

					rc = ksmbd_vfs_set_sd_xattr(conn,
2993 2994 2995
								    path.dentry,
								    pntsd,
								    pntsd_size);
2996
					kfree(pntsd);
2997
					if (rc)
N
Namjae Jeon 已提交
2998 2999
						pr_err("failed to store ntacl in xattr : %d\n",
						       rc);
3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017
				}
			}
		}
		rc = 0;
	}

	if (stream_name) {
		rc = smb2_set_stream_name_xattr(&path,
						fp,
						stream_name,
						s_type);
		if (rc)
			goto err_out;
		file_info = FILE_CREATED;
	}

	fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
			FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3018 3019
	if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
	    !fp->attrib_only && !stream_name) {
3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033
		smb_break_all_oplock(work, fp);
		need_truncate = 1;
	}

	/* fp should be searchable through ksmbd_inode.m_fp_list
	 * after daccess, saccess, attrib_only, and stream are
	 * initialized.
	 */
	write_lock(&fp->f_ci->m_lock);
	list_add(&fp->node, &fp->f_ci->m_fp_list);
	write_unlock(&fp->f_ci->m_lock);

	rc = ksmbd_vfs_getattr(&path, &stat);
	if (rc) {
J
Jason Yan 已提交
3034
		generic_fillattr(d_inode(path.dentry), &stat);
3035 3036 3037 3038 3039 3040 3041 3042 3043 3044
		rc = 0;
	}

	/* Check delete pending among previous fp before oplock break */
	if (ksmbd_inode_pending_delete(fp)) {
		rc = -EBUSY;
		goto err_out;
	}

	share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3045 3046 3047
	if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
	    (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
	     !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3048
		if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3049 3050 3051 3052 3053 3054 3055
			rc = share_ret;
			goto err_out;
		}
	} else {
		if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
			req_op_level = smb2_map_lease_to_oplock(lc->req_state);
			ksmbd_debug(SMB,
3056 3057
				    "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
				    name, req_op_level, lc->req_state);
3058 3059 3060 3061
			rc = find_same_lease_key(sess, fp->f_ci, lc);
			if (rc)
				goto err_out;
		} else if (open_flags == O_RDONLY &&
3062 3063
			   (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
			    req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
			req_op_level = SMB2_OPLOCK_LEVEL_II;

		rc = smb_grant_oplock(work, req_op_level,
				      fp->persistent_id, fp,
				      le32_to_cpu(req->hdr.Id.SyncId.TreeId),
				      lc, share_ret);
		if (rc < 0)
			goto err_out;
	}

	if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
		ksmbd_fd_set_delete_on_close(fp, file_info);

	if (need_truncate) {
		rc = smb2_create_truncate(&path);
		if (rc)
			goto err_out;
	}

	if (req->CreateContextsOffset) {
		struct create_alloc_size_req *az_req;

3086
		az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3087
					SMB2_CREATE_ALLOCATION_SIZE, 4);
3088 3089 3090 3091
		if (IS_ERR(az_req)) {
			rc = PTR_ERR(az_req);
			goto err_out;
		} else if (az_req) {
3092
			loff_t alloc_size;
3093 3094
			int err;

3095 3096 3097 3098 3099 3100 3101
			if (le16_to_cpu(az_req->ccontext.DataOffset) +
			    le32_to_cpu(az_req->ccontext.DataLength) <
			    sizeof(struct create_alloc_size_req)) {
				rc = -EINVAL;
				goto err_out;
			}
			alloc_size = le64_to_cpu(az_req->AllocationSize);
3102
			ksmbd_debug(SMB,
3103 3104
				    "request smb2 create allocate size : %llu\n",
				    alloc_size);
3105 3106 3107
			smb_break_all_levII_oplock(work, fp, 1);
			err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
					    alloc_size);
3108 3109
			if (err < 0)
				ksmbd_debug(SMB,
3110
					    "vfs_fallocate is failed : %d\n",
3111
					    err);
3112 3113
		}

3114
		context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3115 3116 3117 3118
		if (IS_ERR(context)) {
			rc = PTR_ERR(context);
			goto err_out;
		} else if (context) {
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128
			ksmbd_debug(SMB, "get query on disk id context\n");
			query_disk_id = 1;
		}
	}

	if (stat.result_mask & STATX_BTIME)
		fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
	else
		fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
	if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3129 3130
		fp->f_ci->m_fattr =
			cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3131 3132 3133 3134 3135 3136 3137 3138

	if (!created)
		smb2_update_xattrs(tcon, &path, fp);
	else
		smb2_new_xattrs(tcon, &path, fp);

	memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);

J
Jason Yan 已提交
3139
	generic_fillattr(file_inode(fp->filp), &stat);
3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166

	rsp->StructureSize = cpu_to_le16(89);
	rcu_read_lock();
	opinfo = rcu_dereference(fp->f_opinfo);
	rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
	rcu_read_unlock();
	rsp->Reserved = 0;
	rsp->CreateAction = cpu_to_le32(file_info);
	rsp->CreationTime = cpu_to_le64(fp->create_time);
	time = ksmbd_UnixTimeToNT(stat.atime);
	rsp->LastAccessTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(stat.mtime);
	rsp->LastWriteTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(stat.ctime);
	rsp->ChangeTime = cpu_to_le64(time);
	rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
		cpu_to_le64(stat.blocks << 9);
	rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
	rsp->FileAttributes = fp->f_ci->m_fattr;

	rsp->Reserved2 = 0;

	rsp->PersistentFileId = cpu_to_le64(fp->persistent_id);
	rsp->VolatileFileId = cpu_to_le64(fp->volatile_id);

	rsp->CreateContextsOffset = 0;
	rsp->CreateContextsLength = 0;
3167
	inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
3168 3169 3170 3171 3172 3173

	/* If lease is request send lease context response */
	if (opinfo && opinfo->is_lease) {
		struct create_context *lease_ccontext;

		ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3174
			    name, opinfo->o_lease->state);
3175 3176 3177 3178 3179 3180 3181
		rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;

		lease_ccontext = (struct create_context *)rsp->Buffer;
		contxt_cnt++;
		create_lease_buf(rsp->Buffer, opinfo->o_lease);
		le32_add_cpu(&rsp->CreateContextsLength,
			     conn->vals->create_lease_size);
3182 3183
		inc_rfc1001_len(work->response_buf,
				conn->vals->create_lease_size);
3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201
		next_ptr = &lease_ccontext->Next;
		next_off = conn->vals->create_lease_size;
	}

	if (maximal_access_ctxt) {
		struct create_context *mxac_ccontext;

		if (maximal_access == 0)
			ksmbd_vfs_query_maximal_access(path.dentry,
						       &maximal_access);
		mxac_ccontext = (struct create_context *)(rsp->Buffer +
				le32_to_cpu(rsp->CreateContextsLength));
		contxt_cnt++;
		create_mxac_rsp_buf(rsp->Buffer +
				le32_to_cpu(rsp->CreateContextsLength),
				le32_to_cpu(maximal_access));
		le32_add_cpu(&rsp->CreateContextsLength,
			     conn->vals->create_mxac_size);
3202 3203
		inc_rfc1001_len(work->response_buf,
				conn->vals->create_mxac_size);
3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
		if (next_ptr)
			*next_ptr = cpu_to_le32(next_off);
		next_ptr = &mxac_ccontext->Next;
		next_off = conn->vals->create_mxac_size;
	}

	if (query_disk_id) {
		struct create_context *disk_id_ccontext;

		disk_id_ccontext = (struct create_context *)(rsp->Buffer +
				le32_to_cpu(rsp->CreateContextsLength));
		contxt_cnt++;
		create_disk_id_rsp_buf(rsp->Buffer +
				le32_to_cpu(rsp->CreateContextsLength),
				stat.ino, tcon->id);
		le32_add_cpu(&rsp->CreateContextsLength,
			     conn->vals->create_disk_id_size);
3221 3222
		inc_rfc1001_len(work->response_buf,
				conn->vals->create_disk_id_size);
3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235
		if (next_ptr)
			*next_ptr = cpu_to_le32(next_off);
		next_ptr = &disk_id_ccontext->Next;
		next_off = conn->vals->create_disk_id_size;
	}

	if (posix_ctxt) {
		contxt_cnt++;
		create_posix_rsp_buf(rsp->Buffer +
				le32_to_cpu(rsp->CreateContextsLength),
				fp);
		le32_add_cpu(&rsp->CreateContextsLength,
			     conn->vals->create_posix_size);
3236 3237
		inc_rfc1001_len(work->response_buf,
				conn->vals->create_posix_size);
3238 3239 3240 3241 3242 3243
		if (next_ptr)
			*next_ptr = cpu_to_le32(next_off);
	}

	if (contxt_cnt > 0) {
		rsp->CreateContextsOffset =
3244
			cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256
	}

err_out:
	if (file_present || created)
		path_put(&path);
	ksmbd_revert_fsids(work);
err_out1:
	if (rc) {
		if (rc == -EINVAL)
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		else if (rc == -EOPNOTSUPP)
			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3257
		else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403
			rsp->hdr.Status = STATUS_ACCESS_DENIED;
		else if (rc == -ENOENT)
			rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
		else if (rc == -EPERM)
			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
		else if (rc == -EBUSY)
			rsp->hdr.Status = STATUS_DELETE_PENDING;
		else if (rc == -EBADF)
			rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
		else if (rc == -ENOEXEC)
			rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
		else if (rc == -ENXIO)
			rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
		else if (rc == -EEXIST)
			rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
		else if (rc == -EMFILE)
			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
		if (!rsp->hdr.Status)
			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;

		if (!fp || !fp->filename)
			kfree(name);
		if (fp)
			ksmbd_fd_put(work, fp);
		smb2_set_err_rsp(work);
		ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
	}

	kfree(lc);

	return 0;
}

static int readdir_info_level_struct_sz(int info_level)
{
	switch (info_level) {
	case FILE_FULL_DIRECTORY_INFORMATION:
		return sizeof(struct file_full_directory_info);
	case FILE_BOTH_DIRECTORY_INFORMATION:
		return sizeof(struct file_both_directory_info);
	case FILE_DIRECTORY_INFORMATION:
		return sizeof(struct file_directory_info);
	case FILE_NAMES_INFORMATION:
		return sizeof(struct file_names_info);
	case FILEID_FULL_DIRECTORY_INFORMATION:
		return sizeof(struct file_id_full_dir_info);
	case FILEID_BOTH_DIRECTORY_INFORMATION:
		return sizeof(struct file_id_both_directory_info);
	case SMB_FIND_FILE_POSIX_INFO:
		return sizeof(struct smb2_posix_info);
	default:
		return -EOPNOTSUPP;
	}
}

static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
{
	switch (info_level) {
	case FILE_FULL_DIRECTORY_INFORMATION:
	{
		struct file_full_directory_info *ffdinfo;

		ffdinfo = (struct file_full_directory_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
		d_info->name = ffdinfo->FileName;
		d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
		return 0;
	}
	case FILE_BOTH_DIRECTORY_INFORMATION:
	{
		struct file_both_directory_info *fbdinfo;

		fbdinfo = (struct file_both_directory_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
		d_info->name = fbdinfo->FileName;
		d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
		return 0;
	}
	case FILE_DIRECTORY_INFORMATION:
	{
		struct file_directory_info *fdinfo;

		fdinfo = (struct file_directory_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
		d_info->name = fdinfo->FileName;
		d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
		return 0;
	}
	case FILE_NAMES_INFORMATION:
	{
		struct file_names_info *fninfo;

		fninfo = (struct file_names_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
		d_info->name = fninfo->FileName;
		d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
		return 0;
	}
	case FILEID_FULL_DIRECTORY_INFORMATION:
	{
		struct file_id_full_dir_info *dinfo;

		dinfo = (struct file_id_full_dir_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
		d_info->name = dinfo->FileName;
		d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
		return 0;
	}
	case FILEID_BOTH_DIRECTORY_INFORMATION:
	{
		struct file_id_both_directory_info *fibdinfo;

		fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
		d_info->name = fibdinfo->FileName;
		d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
		return 0;
	}
	case SMB_FIND_FILE_POSIX_INFO:
	{
		struct smb2_posix_info *posix_info;

		posix_info = (struct smb2_posix_info *)d_info->rptr;
		d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
		d_info->name = posix_info->name;
		d_info->name_len = le32_to_cpu(posix_info->name_len);
		return 0;
	}
	default:
		return -EINVAL;
	}
}

/**
 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
 * buffer
 * @conn:	connection instance
 * @info_level:	smb information level
 * @d_info:	structure included variables for query dir
 * @ksmbd_kstat:	ksmbd wrapper of dirent stat information
 *
 * if directory has many entries, find first can't read it fully.
 * find next might be called multiple times to read remaining dir entries
 *
 * Return:	0 on success, otherwise error
 */
3404
static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3405 3406
				       struct ksmbd_dir_info *d_info,
				       struct ksmbd_kstat *ksmbd_kstat)
3407 3408 3409 3410 3411
{
	int next_entry_offset = 0;
	char *conv_name;
	int conv_len;
	void *kstat;
3412
	int struct_sz, rc = 0;
3413 3414 3415 3416 3417 3418 3419 3420 3421

	conv_name = ksmbd_convert_dir_info_name(d_info,
						conn->local_nls,
						&conv_len);
	if (!conv_name)
		return -ENOMEM;

	/* Somehow the name has only terminating NULL bytes */
	if (conv_len < 0) {
3422 3423
		rc = -EINVAL;
		goto free_conv_name;
3424 3425
	}

3426 3427 3428
	struct_sz = readdir_info_level_struct_sz(info_level) - 1 + conv_len;
	next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
	d_info->last_entry_off_align = next_entry_offset - struct_sz;
3429 3430 3431

	if (next_entry_offset > d_info->out_buf_len) {
		d_info->out_buf_len = 0;
3432 3433
		rc = -ENOSPC;
		goto free_conv_name;
3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559
	}

	kstat = d_info->wptr;
	if (info_level != FILE_NAMES_INFORMATION)
		kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);

	switch (info_level) {
	case FILE_FULL_DIRECTORY_INFORMATION:
	{
		struct file_full_directory_info *ffdinfo;

		ffdinfo = (struct file_full_directory_info *)kstat;
		ffdinfo->FileNameLength = cpu_to_le32(conv_len);
		ffdinfo->EaSize =
			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
		if (ffdinfo->EaSize)
			ffdinfo->ExtFileAttributes = ATTR_REPARSE_POINT_LE;
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			ffdinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
		memcpy(ffdinfo->FileName, conv_name, conv_len);
		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_BOTH_DIRECTORY_INFORMATION:
	{
		struct file_both_directory_info *fbdinfo;

		fbdinfo = (struct file_both_directory_info *)kstat;
		fbdinfo->FileNameLength = cpu_to_le32(conv_len);
		fbdinfo->EaSize =
			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
		if (fbdinfo->EaSize)
			fbdinfo->ExtFileAttributes = ATTR_REPARSE_POINT_LE;
		fbdinfo->ShortNameLength = 0;
		fbdinfo->Reserved = 0;
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			fbdinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
		memcpy(fbdinfo->FileName, conv_name, conv_len);
		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_DIRECTORY_INFORMATION:
	{
		struct file_directory_info *fdinfo;

		fdinfo = (struct file_directory_info *)kstat;
		fdinfo->FileNameLength = cpu_to_le32(conv_len);
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			fdinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
		memcpy(fdinfo->FileName, conv_name, conv_len);
		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_NAMES_INFORMATION:
	{
		struct file_names_info *fninfo;

		fninfo = (struct file_names_info *)kstat;
		fninfo->FileNameLength = cpu_to_le32(conv_len);
		memcpy(fninfo->FileName, conv_name, conv_len);
		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILEID_FULL_DIRECTORY_INFORMATION:
	{
		struct file_id_full_dir_info *dinfo;

		dinfo = (struct file_id_full_dir_info *)kstat;
		dinfo->FileNameLength = cpu_to_le32(conv_len);
		dinfo->EaSize =
			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
		if (dinfo->EaSize)
			dinfo->ExtFileAttributes = ATTR_REPARSE_POINT_LE;
		dinfo->Reserved = 0;
		dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			dinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
		memcpy(dinfo->FileName, conv_name, conv_len);
		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILEID_BOTH_DIRECTORY_INFORMATION:
	{
		struct file_id_both_directory_info *fibdinfo;

		fibdinfo = (struct file_id_both_directory_info *)kstat;
		fibdinfo->FileNameLength = cpu_to_le32(conv_len);
		fibdinfo->EaSize =
			smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
		if (fibdinfo->EaSize)
			fibdinfo->ExtFileAttributes = ATTR_REPARSE_POINT_LE;
		fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
		fibdinfo->ShortNameLength = 0;
		fibdinfo->Reserved = 0;
		fibdinfo->Reserved2 = cpu_to_le16(0);
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			fibdinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
		memcpy(fibdinfo->FileName, conv_name, conv_len);
		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case SMB_FIND_FILE_POSIX_INFO:
	{
		struct smb2_posix_info *posix_info;
		u64 time;

		posix_info = (struct smb2_posix_info *)kstat;
		posix_info->Ignored = 0;
		posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
		posix_info->ChangeTime = cpu_to_le64(time);
		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
		posix_info->LastAccessTime = cpu_to_le64(time);
		time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
		posix_info->LastWriteTime = cpu_to_le64(time);
		posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
		posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
		posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
		posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
		posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode);
		posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
		posix_info->DosAttributes =
			S_ISDIR(ksmbd_kstat->kstat->mode) ? ATTR_DIRECTORY_LE : ATTR_ARCHIVE_LE;
		if (d_info->hide_dot_file && d_info->name[0] == '.')
			posix_info->DosAttributes |= ATTR_HIDDEN_LE;
		id_to_sid(from_kuid(&init_user_ns, ksmbd_kstat->kstat->uid),
3560
			  SIDNFS_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3561
		id_to_sid(from_kgid(&init_user_ns, ksmbd_kstat->kstat->gid),
3562
			  SIDNFS_GROUP, (struct smb_sid *)&posix_info->SidBuffer[20]);
3563 3564 3565 3566 3567 3568 3569 3570 3571 3572
		memcpy(posix_info->name, conv_name, conv_len);
		posix_info->name_len = cpu_to_le32(conv_len);
		posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}

	} /* switch (info_level) */

	d_info->last_entry_offset = d_info->data_count;
	d_info->data_count += next_entry_offset;
3573
	d_info->out_buf_len -= next_entry_offset;
3574 3575 3576
	d_info->wptr += next_entry_offset;

	ksmbd_debug(SMB,
3577 3578 3579
		    "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
		    info_level, d_info->out_buf_len,
		    next_entry_offset, d_info->data_count);
3580

3581 3582 3583
free_conv_name:
	kfree(conv_name);
	return rc;
3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629
}

struct smb2_query_dir_private {
	struct ksmbd_work	*work;
	char			*search_pattern;
	struct ksmbd_file	*dir_fp;

	struct ksmbd_dir_info	*d_info;
	int			info_level;
};

static void lock_dir(struct ksmbd_file *dir_fp)
{
	struct dentry *dir = dir_fp->filp->f_path.dentry;

	inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
}

static void unlock_dir(struct ksmbd_file *dir_fp)
{
	struct dentry *dir = dir_fp->filp->f_path.dentry;

	inode_unlock(d_inode(dir));
}

static int process_query_dir_entries(struct smb2_query_dir_private *priv)
{
	struct kstat		kstat;
	struct ksmbd_kstat	ksmbd_kstat;
	int			rc;
	int			i;

	for (i = 0; i < priv->d_info->num_entry; i++) {
		struct dentry *dent;

		if (dentry_name(priv->d_info, priv->info_level))
			return -EINVAL;

		lock_dir(priv->dir_fp);
		dent = lookup_one_len(priv->d_info->name,
				      priv->dir_fp->filp->f_path.dentry,
				      priv->d_info->name_len);
		unlock_dir(priv->dir_fp);

		if (IS_ERR(dent)) {
			ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3630 3631
				    priv->d_info->name,
				    PTR_ERR(dent));
3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658
			continue;
		}
		if (unlikely(d_is_negative(dent))) {
			dput(dent);
			ksmbd_debug(SMB, "Negative dentry `%s'\n",
				    priv->d_info->name);
			continue;
		}

		ksmbd_kstat.kstat = &kstat;
		if (priv->info_level != FILE_NAMES_INFORMATION)
			ksmbd_vfs_fill_dentry_attrs(priv->work,
						    dent,
						    &ksmbd_kstat);

		rc = smb2_populate_readdir_entry(priv->work->conn,
						 priv->info_level,
						 priv->d_info,
						 &ksmbd_kstat);
		dput(dent);
		if (rc)
			return rc;
	}
	return 0;
}

static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3659
				   int info_level)
3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764
{
	int struct_sz;
	int conv_len;
	int next_entry_offset;

	struct_sz = readdir_info_level_struct_sz(info_level);
	if (struct_sz == -EOPNOTSUPP)
		return -EOPNOTSUPP;

	conv_len = (d_info->name_len + 1) * 2;
	next_entry_offset = ALIGN(struct_sz - 1 + conv_len,
				  KSMBD_DIR_INFO_ALIGNMENT);

	if (next_entry_offset > d_info->out_buf_len) {
		d_info->out_buf_len = 0;
		return -ENOSPC;
	}

	switch (info_level) {
	case FILE_FULL_DIRECTORY_INFORMATION:
	{
		struct file_full_directory_info *ffdinfo;

		ffdinfo = (struct file_full_directory_info *)d_info->wptr;
		memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
		ffdinfo->FileName[d_info->name_len] = 0x00;
		ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
		ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_BOTH_DIRECTORY_INFORMATION:
	{
		struct file_both_directory_info *fbdinfo;

		fbdinfo = (struct file_both_directory_info *)d_info->wptr;
		memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
		fbdinfo->FileName[d_info->name_len] = 0x00;
		fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
		fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_DIRECTORY_INFORMATION:
	{
		struct file_directory_info *fdinfo;

		fdinfo = (struct file_directory_info *)d_info->wptr;
		memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
		fdinfo->FileName[d_info->name_len] = 0x00;
		fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
		fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILE_NAMES_INFORMATION:
	{
		struct file_names_info *fninfo;

		fninfo = (struct file_names_info *)d_info->wptr;
		memcpy(fninfo->FileName, d_info->name, d_info->name_len);
		fninfo->FileName[d_info->name_len] = 0x00;
		fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
		fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILEID_FULL_DIRECTORY_INFORMATION:
	{
		struct file_id_full_dir_info *dinfo;

		dinfo = (struct file_id_full_dir_info *)d_info->wptr;
		memcpy(dinfo->FileName, d_info->name, d_info->name_len);
		dinfo->FileName[d_info->name_len] = 0x00;
		dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
		dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case FILEID_BOTH_DIRECTORY_INFORMATION:
	{
		struct file_id_both_directory_info *fibdinfo;

		fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
		memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
		fibdinfo->FileName[d_info->name_len] = 0x00;
		fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
		fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
		break;
	}
	case SMB_FIND_FILE_POSIX_INFO:
	{
		struct smb2_posix_info *posix_info;

		posix_info = (struct smb2_posix_info *)d_info->wptr;
		memcpy(posix_info->name, d_info->name, d_info->name_len);
		posix_info->name[d_info->name_len] = 0x00;
		posix_info->name_len = cpu_to_le32(d_info->name_len);
		posix_info->NextEntryOffset =
			cpu_to_le32(next_entry_offset);
		break;
	}
	} /* switch (info_level) */

	d_info->num_entry++;
	d_info->out_buf_len -= next_entry_offset;
	d_info->wptr += next_entry_offset;
	return 0;
}

3765
static int __query_dir(struct dir_context *ctx, const char *name, int namlen,
3766
		       loff_t offset, u64 ino, unsigned int d_type)
3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781
{
	struct ksmbd_readdir_data	*buf;
	struct smb2_query_dir_private	*priv;
	struct ksmbd_dir_info		*d_info;
	int				rc;

	buf	= container_of(ctx, struct ksmbd_readdir_data, ctx);
	priv	= buf->private;
	d_info	= priv->d_info;

	/* dot and dotdot entries are already reserved */
	if (!strcmp(".", name) || !strcmp("..", name))
		return 0;
	if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
		return 0;
3782
	if (!match_pattern(name, namlen, priv->search_pattern))
3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814
		return 0;

	d_info->name		= name;
	d_info->name_len	= namlen;
	rc = reserve_populate_dentry(d_info, priv->info_level);
	if (rc)
		return rc;
	if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY) {
		d_info->out_buf_len = 0;
		return 0;
	}
	return 0;
}

static int verify_info_level(int info_level)
{
	switch (info_level) {
	case FILE_FULL_DIRECTORY_INFORMATION:
	case FILE_BOTH_DIRECTORY_INFORMATION:
	case FILE_DIRECTORY_INFORMATION:
	case FILE_NAMES_INFORMATION:
	case FILEID_FULL_DIRECTORY_INFORMATION:
	case FILEID_BOTH_DIRECTORY_INFORMATION:
	case SMB_FIND_FILE_POSIX_INFO:
		break;
	default:
		return -EOPNOTSUPP;
	}

	return 0;
}

3815 3816 3817 3818 3819 3820 3821 3822 3823
static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
{
	int free_len;

	free_len = (int)(work->response_sz -
		(get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
	return free_len;
}

3824 3825 3826 3827 3828 3829 3830 3831 3832
static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
				     unsigned short hdr2_len,
				     unsigned int out_buf_len)
{
	int free_len;

	if (out_buf_len > work->conn->vals->max_trans_size)
		return -EINVAL;

3833
	free_len = smb2_resp_buf_len(work, hdr2_len);
3834 3835 3836 3837 3838 3839
	if (free_len < 0)
		return -EINVAL;

	return min_t(int, out_buf_len, free_len);
}

3840 3841 3842 3843
int smb2_query_dir(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_query_directory_req *req;
3844
	struct smb2_query_directory_rsp *rsp;
3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868
	struct ksmbd_share_config *share = work->tcon->share_conf;
	struct ksmbd_file *dir_fp = NULL;
	struct ksmbd_dir_info d_info;
	int rc = 0;
	char *srch_ptr = NULL;
	unsigned char srch_flag;
	int buffer_sz;
	struct smb2_query_dir_private query_dir_private = {NULL, };

	WORK_BUFFERS(work, req, rsp);

	if (ksmbd_override_fsids(work)) {
		rsp->hdr.Status = STATUS_NO_MEMORY;
		smb2_set_err_rsp(work);
		return -ENOMEM;
	}

	rc = verify_info_level(req->FileInformationClass);
	if (rc) {
		rc = -EFAULT;
		goto err_out2;
	}

	dir_fp = ksmbd_lookup_fd_slow(work,
3869 3870
				      le64_to_cpu(req->VolatileFileId),
				      le64_to_cpu(req->PersistentFileId));
3871 3872 3873 3874 3875 3876
	if (!dir_fp) {
		rc = -EBADF;
		goto err_out2;
	}

	if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
J
Jason Yan 已提交
3877
	    inode_permission(file_inode(dir_fp->filp),
3878
			     MAY_READ | MAY_EXEC)) {
N
Namjae Jeon 已提交
3879 3880
		pr_err("no right to enumerate directory (%pd)\n",
		       dir_fp->filp->f_path.dentry);
3881 3882 3883 3884 3885
		rc = -EACCES;
		goto err_out2;
	}

	if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
N
Namjae Jeon 已提交
3886
		pr_err("can't do query dir for a file\n");
3887 3888 3889 3890 3891 3892
		rc = -EINVAL;
		goto err_out2;
	}

	srch_flag = req->Flags;
	srch_ptr = smb_strndup_from_utf16(req->Buffer,
3893 3894
					  le16_to_cpu(req->FileNameLength), 1,
					  conn->local_nls);
3895 3896 3897 3898
	if (IS_ERR(srch_ptr)) {
		ksmbd_debug(SMB, "Search Pattern not found\n");
		rc = -EINVAL;
		goto err_out2;
3899
	} else {
3900
		ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
3901
	}
3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912

	ksmbd_debug(SMB, "Directory name is %s\n", dir_fp->filename);

	if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
		ksmbd_debug(SMB, "Restart directory scan\n");
		generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
	}

	memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
	d_info.wptr = (char *)rsp->Buffer;
	d_info.rptr = (char *)rsp->Buffer;
3913 3914 3915 3916 3917 3918 3919
	d_info.out_buf_len =
		smb2_calc_max_out_buf_len(work, 8,
					  le32_to_cpu(req->OutputBufferLength));
	if (d_info.out_buf_len < 0) {
		rc = -EINVAL;
		goto err_out;
	}
3920 3921 3922 3923 3924 3925 3926
	d_info.flags = srch_flag;

	/*
	 * reserve dot and dotdot entries in head of buffer
	 * in first response
	 */
	rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
3927 3928
					       dir_fp, &d_info, srch_ptr,
					       smb2_populate_readdir_entry);
3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946
	if (rc == -ENOSPC)
		rc = 0;
	else if (rc)
		goto err_out;

	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
		d_info.hide_dot_file = true;

	buffer_sz				= d_info.out_buf_len;
	d_info.rptr				= d_info.wptr;
	query_dir_private.work			= work;
	query_dir_private.search_pattern	= srch_ptr;
	query_dir_private.dir_fp		= dir_fp;
	query_dir_private.d_info		= &d_info;
	query_dir_private.info_level		= req->FileInformationClass;
	dir_fp->readdir_data.private		= &query_dir_private;
	set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);

3947
	rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
3948 3949 3950 3951 3952 3953
	/*
	 * req->OutputBufferLength is too small to contain even one entry.
	 * In this case, it immediately returns OutputBufferLength 0 to client.
	 */
	if (!d_info.out_buf_len && !d_info.num_entry)
		goto no_buf_len;
3954
	if (rc > 0 || rc == -ENOSPC)
3955
		rc = 0;
3956
	else if (rc)
3957 3958 3959 3960 3961 3962 3963 3964 3965
		goto err_out;

	d_info.wptr = d_info.rptr;
	d_info.out_buf_len = buffer_sz;
	rc = process_query_dir_entries(&query_dir_private);
	if (rc)
		goto err_out;

	if (!d_info.data_count && d_info.out_buf_len >= 0) {
3966
		if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
3967
			rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3968
		} else {
3969 3970 3971 3972 3973 3974 3975
			dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
			rsp->hdr.Status = STATUS_NO_MORE_FILES;
		}
		rsp->StructureSize = cpu_to_le16(9);
		rsp->OutputBufferOffset = cpu_to_le16(0);
		rsp->OutputBufferLength = cpu_to_le32(0);
		rsp->Buffer[0] = 0;
3976
		inc_rfc1001_len(work->response_buf, 9);
3977
	} else {
3978
no_buf_len:
3979 3980 3981
		((struct file_directory_info *)
		((char *)rsp->Buffer + d_info.last_entry_offset))
		->NextEntryOffset = 0;
3982 3983
		if (d_info.data_count >= d_info.last_entry_off_align)
			d_info.data_count -= d_info.last_entry_off_align;
3984 3985 3986 3987

		rsp->StructureSize = cpu_to_le16(9);
		rsp->OutputBufferOffset = cpu_to_le16(72);
		rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
3988
		inc_rfc1001_len(work->response_buf, 8 + d_info.data_count);
3989 3990 3991 3992 3993 3994 3995 3996
	}

	kfree(srch_ptr);
	ksmbd_fd_put(work, dir_fp);
	ksmbd_revert_fsids(work);
	return 0;

err_out:
N
Namjae Jeon 已提交
3997
	pr_err("error while processing smb2 query dir rc = %d\n", rc);
3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012
	kfree(srch_ptr);

err_out2:
	if (rc == -EINVAL)
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
	else if (rc == -EACCES)
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
	else if (rc == -ENOENT)
		rsp->hdr.Status = STATUS_NO_SUCH_FILE;
	else if (rc == -EBADF)
		rsp->hdr.Status = STATUS_FILE_CLOSED;
	else if (rc == -ENOMEM)
		rsp->hdr.Status = STATUS_NO_MEMORY;
	else if (rc == -EFAULT)
		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4013 4014
	else if (rc == -EIO)
		rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027
	if (!rsp->hdr.Status)
		rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;

	smb2_set_err_rsp(work);
	ksmbd_fd_put(work, dir_fp);
	ksmbd_revert_fsids(work);
	return 0;
}

/**
 * buffer_check_err() - helper function to check buffer errors
 * @reqOutputBufferLength:	max buffer length expected in command response
 * @rsp:		query info response buffer contains output buffer length
4028
 * @rsp_org:		base response buffer pointer in case of chained response
4029 4030 4031 4032 4033
 * @infoclass_size:	query info class response buffer size
 *
 * Return:	0 on success, otherwise error
 */
static int buffer_check_err(int reqOutputBufferLength,
4034 4035
			    struct smb2_query_info_rsp *rsp,
			    void *rsp_org, int infoclass_size)
4036 4037 4038
{
	if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
		if (reqOutputBufferLength < infoclass_size) {
N
Namjae Jeon 已提交
4039
			pr_err("Invalid Buffer Size Requested\n");
4040
			rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4041
			*(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4042 4043 4044 4045 4046
			return -EINVAL;
		}

		ksmbd_debug(SMB, "Buffer Overflow\n");
		rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
4047
		*(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr) +
4048 4049
				reqOutputBufferLength);
		rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
4050 4051 4052 4053
	}
	return 0;
}

4054 4055
static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
				   void *rsp_org)
4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067
{
	struct smb2_file_standard_info *sinfo;

	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;

	sinfo->AllocationSize = cpu_to_le64(4096);
	sinfo->EndOfFile = cpu_to_le64(0);
	sinfo->NumberOfLinks = cpu_to_le32(1);
	sinfo->DeletePending = 1;
	sinfo->Directory = 0;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_standard_info));
4068
	inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_standard_info));
4069 4070
}

4071 4072
static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
				   void *rsp_org)
4073 4074 4075 4076 4077 4078 4079 4080 4081
{
	struct smb2_file_internal_info *file_info;

	file_info = (struct smb2_file_internal_info *)rsp->Buffer;

	/* any unique number */
	file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_internal_info));
4082
	inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4083 4084 4085
}

static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4086
				   struct smb2_query_info_req *req,
4087 4088
				   struct smb2_query_info_rsp *rsp,
				   void *rsp_org)
4089
{
4090
	u64 id;
4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101
	int rc;

	/*
	 * Windows can sometime send query file info request on
	 * pipe without opening it, checking error condition here
	 */
	id = le64_to_cpu(req->VolatileFileId);
	if (!ksmbd_session_rpc_method(sess, id))
		return -ENOENT;

	ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4102
		    req->FileInfoClass, le64_to_cpu(req->VolatileFileId));
4103 4104 4105

	switch (req->FileInfoClass) {
	case FILE_STANDARD_INFORMATION:
4106
		get_standard_info_pipe(rsp, rsp_org);
4107
		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4108 4109
				      rsp, rsp_org,
				      FILE_STANDARD_INFORMATION_SIZE);
4110 4111
		break;
	case FILE_INTERNAL_INFORMATION:
4112
		get_internal_info_pipe(rsp, id, rsp_org);
4113
		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4114 4115
				      rsp, rsp_org,
				      FILE_INTERNAL_INFORMATION_SIZE);
4116 4117 4118
		break;
	default:
		ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4119
			    req->FileInfoClass);
4120 4121 4122 4123 4124 4125 4126 4127
		rc = -EOPNOTSUPP;
	}
	return rc;
}

/**
 * smb2_get_ea() - handler for smb2 get extended attribute command
 * @work:	smb work containing query info command buffer
H
Hyunchul Lee 已提交
4128 4129 4130 4131
 * @fp:		ksmbd_file pointer
 * @req:	get extended attribute request
 * @rsp:	response buffer pointer
 * @rsp_org:	base response buffer pointer in case of chained response
4132 4133 4134
 *
 * Return:	0 on success, otherwise error
 */
4135
static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4136 4137
		       struct smb2_query_info_req *req,
		       struct smb2_query_info_rsp *rsp, void *rsp_org)
4138 4139 4140 4141 4142 4143 4144 4145 4146
{
	struct smb2_ea_info *eainfo, *prev_eainfo;
	char *name, *ptr, *xattr_list = NULL, *buf;
	int rc, name_len, value_len, xattr_list_len, idx;
	ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
	struct smb2_ea_info_req *ea_req = NULL;
	struct path *path;

	if (!(fp->daccess & FILE_READ_EA_LE)) {
N
Namjae Jeon 已提交
4147 4148
		pr_err("Not permitted to read ext attr : 0x%x\n",
		       fp->daccess);
4149 4150 4151 4152 4153
		return -EACCES;
	}

	path = &fp->filp->f_path;
	/* single EA entry is requested with given user.* name */
4154
	if (req->InputBufferLength) {
4155 4156 4157 4158
		if (le32_to_cpu(req->InputBufferLength) <
		    sizeof(struct smb2_ea_info_req))
			return -EINVAL;

4159
		ea_req = (struct smb2_ea_info_req *)req->Buffer;
4160
	} else {
4161 4162 4163
		/* need to send all EAs, if no specific EA is requested*/
		if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
			ksmbd_debug(SMB,
4164 4165
				    "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
				    le32_to_cpu(req->Flags));
4166 4167
	}

4168 4169 4170 4171 4172
	buf_free_len =
		smb2_calc_max_out_buf_len(work, 8,
					  le32_to_cpu(req->OutputBufferLength));
	if (buf_free_len < 0)
		return -EINVAL;
4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204

	rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
	if (rc < 0) {
		rsp->hdr.Status = STATUS_INVALID_HANDLE;
		goto out;
	} else if (!rc) { /* there is no EA in the file */
		ksmbd_debug(SMB, "no ea data in the file\n");
		goto done;
	}
	xattr_list_len = rc;

	ptr = (char *)rsp->Buffer;
	eainfo = (struct smb2_ea_info *)ptr;
	prev_eainfo = eainfo;
	idx = 0;

	while (idx < xattr_list_len) {
		name = xattr_list + idx;
		name_len = strlen(name);

		ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
		idx += name_len + 1;

		/*
		 * CIFS does not support EA other than user.* namespace,
		 * still keep the framework generic, to list other attrs
		 * in future.
		 */
		if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
			continue;

		if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4205
			     STREAM_PREFIX_LEN))
4206 4207 4208
			continue;

		if (req->InputBufferLength &&
4209 4210
		    strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
			    ea_req->EaNameLength))
4211 4212 4213
			continue;

		if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4214
			     DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232
			continue;

		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
			name_len -= XATTR_USER_PREFIX_LEN;

		ptr = (char *)(&eainfo->name + name_len + 1);
		buf_free_len -= (offsetof(struct smb2_ea_info, name) +
				name_len + 1);
		/* bailout if xattr can't fit in buf_free_len */
		value_len = ksmbd_vfs_getxattr(path->dentry, name, &buf);
		if (value_len <= 0) {
			rc = -ENOENT;
			rsp->hdr.Status = STATUS_INVALID_HANDLE;
			goto out;
		}

		buf_free_len -= value_len;
		if (buf_free_len < 0) {
4233
			kfree(buf);
4234 4235 4236 4237
			break;
		}

		memcpy(ptr, buf, value_len);
4238
		kfree(buf);
4239 4240 4241 4242 4243

		ptr += value_len;
		eainfo->Flags = 0;
		eainfo->EaNameLength = name_len;

4244
		if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4245
			memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4246
			       name_len);
4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282
		else
			memcpy(eainfo->name, name, name_len);

		eainfo->name[name_len] = '\0';
		eainfo->EaValueLength = cpu_to_le16(value_len);
		next_offset = offsetof(struct smb2_ea_info, name) +
			name_len + 1 + value_len;

		/* align next xattr entry at 4 byte bundary */
		alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
		if (alignment_bytes) {
			memset(ptr, '\0', alignment_bytes);
			ptr += alignment_bytes;
			next_offset += alignment_bytes;
			buf_free_len -= alignment_bytes;
		}
		eainfo->NextEntryOffset = cpu_to_le32(next_offset);
		prev_eainfo = eainfo;
		eainfo = (struct smb2_ea_info *)ptr;
		rsp_data_cnt += next_offset;

		if (req->InputBufferLength) {
			ksmbd_debug(SMB, "single entry requested\n");
			break;
		}
	}

	/* no more ea entries */
	prev_eainfo->NextEntryOffset = 0;
done:
	rc = 0;
	if (rsp_data_cnt == 0)
		rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
	rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
	inc_rfc1001_len(rsp_org, rsp_data_cnt);
out:
4283
	kvfree(xattr_list);
4284 4285 4286 4287
	return rc;
}

static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4288
				 struct ksmbd_file *fp, void *rsp_org)
4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299
{
	struct smb2_file_access_info *file_info;

	file_info = (struct smb2_file_access_info *)rsp->Buffer;
	file_info->AccessFlags = fp->daccess;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_access_info));
	inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_access_info));
}

static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4300
			       struct ksmbd_file *fp, void *rsp_org)
4301
{
4302
	struct smb2_file_basic_info *basic_info;
4303 4304 4305 4306
	struct kstat stat;
	u64 time;

	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
N
Namjae Jeon 已提交
4307 4308
		pr_err("no right to read the attributes : 0x%x\n",
		       fp->daccess);
4309 4310 4311
		return -EACCES;
	}

4312
	basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
J
Jason Yan 已提交
4313
	generic_fillattr(file_inode(fp->filp), &stat);
4314 4315 4316 4317 4318 4319 4320 4321 4322 4323
	basic_info->CreationTime = cpu_to_le64(fp->create_time);
	time = ksmbd_UnixTimeToNT(stat.atime);
	basic_info->LastAccessTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(stat.mtime);
	basic_info->LastWriteTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(stat.ctime);
	basic_info->ChangeTime = cpu_to_le64(time);
	basic_info->Attributes = fp->f_ci->m_fattr;
	basic_info->Pad1 = 0;
	rsp->OutputBufferLength =
4324 4325
		cpu_to_le32(sizeof(struct smb2_file_basic_info));
	inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_basic_info));
4326 4327 4328 4329
	return 0;
}

static unsigned long long get_allocation_size(struct inode *inode,
4330
					      struct kstat *stat)
4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344
{
	unsigned long long alloc_size = 0;

	if (!S_ISDIR(stat->mode)) {
		if ((inode->i_blocks << 9) <= stat->size)
			alloc_size = stat->size;
		else
			alloc_size = inode->i_blocks << 9;
	}

	return alloc_size;
}

static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4345
				   struct ksmbd_file *fp, void *rsp_org)
4346 4347 4348 4349 4350 4351
{
	struct smb2_file_standard_info *sinfo;
	unsigned int delete_pending;
	struct inode *inode;
	struct kstat stat;

4352
	inode = file_inode(fp->filp);
J
Jason Yan 已提交
4353
	generic_fillattr(inode, &stat);
4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369

	sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
	delete_pending = ksmbd_inode_pending_delete(fp);

	sinfo->AllocationSize = cpu_to_le64(get_allocation_size(inode, &stat));
	sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
	sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
	sinfo->DeletePending = delete_pending;
	sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_standard_info));
	inc_rfc1001_len(rsp_org,
			sizeof(struct smb2_file_standard_info));
}

static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4370
				    void *rsp_org)
4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382
{
	struct smb2_file_alignment_info *file_info;

	file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
	file_info->AlignmentRequirement = 0;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_alignment_info));
	inc_rfc1001_len(rsp_org,
			sizeof(struct smb2_file_alignment_info));
}

static int get_file_all_info(struct ksmbd_work *work,
4383 4384 4385
			     struct smb2_query_info_rsp *rsp,
			     struct ksmbd_file *fp,
			     void *rsp_org)
4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_file_all_info *file_info;
	unsigned int delete_pending;
	struct inode *inode;
	struct kstat stat;
	int conv_len;
	char *filename;
	u64 time;

	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
		ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4398
			    fp->daccess);
4399 4400 4401
		return -EACCES;
	}

4402
	filename = convert_to_nt_pathname(fp->filename);
4403 4404 4405
	if (!filename)
		return -ENOMEM;

4406
	inode = file_inode(fp->filp);
J
Jason Yan 已提交
4407
	generic_fillattr(inode, &stat);
4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435

	ksmbd_debug(SMB, "filename = %s\n", filename);
	delete_pending = ksmbd_inode_pending_delete(fp);
	file_info = (struct smb2_file_all_info *)rsp->Buffer;

	file_info->CreationTime = cpu_to_le64(fp->create_time);
	time = ksmbd_UnixTimeToNT(stat.atime);
	file_info->LastAccessTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(stat.mtime);
	file_info->LastWriteTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(stat.ctime);
	file_info->ChangeTime = cpu_to_le64(time);
	file_info->Attributes = fp->f_ci->m_fattr;
	file_info->Pad1 = 0;
	file_info->AllocationSize =
		cpu_to_le64(get_allocation_size(inode, &stat));
	file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
	file_info->NumberOfLinks =
			cpu_to_le32(get_nlink(&stat) - delete_pending);
	file_info->DeletePending = delete_pending;
	file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
	file_info->Pad2 = 0;
	file_info->IndexNumber = cpu_to_le64(stat.ino);
	file_info->EASize = 0;
	file_info->AccessFlags = fp->daccess;
	file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
	file_info->Mode = fp->coption;
	file_info->AlignmentRequirement = 0;
4436 4437
	conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
				     PATH_MAX, conn->local_nls, 0);
4438 4439 4440 4441 4442 4443 4444 4445 4446 4447
	conv_len *= 2;
	file_info->FileNameLength = cpu_to_le32(conv_len);
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
	kfree(filename);
	inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
	return 0;
}

static void get_file_alternate_info(struct ksmbd_work *work,
4448 4449 4450
				    struct smb2_query_info_rsp *rsp,
				    struct ksmbd_file *fp,
				    void *rsp_org)
4451 4452 4453
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_file_alt_name_info *file_info;
N
Namjae Jeon 已提交
4454
	struct dentry *dentry = fp->filp->f_path.dentry;
4455 4456
	int conv_len;

N
Namjae Jeon 已提交
4457
	spin_lock(&dentry->d_lock);
4458 4459
	file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
	conv_len = ksmbd_extract_shortname(conn,
N
Namjae Jeon 已提交
4460
					   dentry->d_name.name,
4461
					   file_info->FileName);
N
Namjae Jeon 已提交
4462
	spin_unlock(&dentry->d_lock);
4463 4464 4465 4466 4467 4468 4469
	file_info->FileNameLength = cpu_to_le32(conv_len);
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
	inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
}

static void get_file_stream_info(struct ksmbd_work *work,
4470 4471 4472
				 struct smb2_query_info_rsp *rsp,
				 struct ksmbd_file *fp,
				 void *rsp_org)
4473 4474 4475 4476 4477 4478 4479 4480
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_file_stream_info *file_info;
	char *stream_name, *xattr_list = NULL, *stream_buf;
	struct kstat stat;
	struct path *path = &fp->filp->f_path;
	ssize_t xattr_list_len;
	int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4481 4482
	int buf_free_len;
	struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4483

J
Jason Yan 已提交
4484
	generic_fillattr(file_inode(fp->filp), &stat);
4485 4486
	file_info = (struct smb2_file_stream_info *)rsp->Buffer;

4487 4488 4489 4490 4491 4492
	buf_free_len =
		smb2_calc_max_out_buf_len(work, 8,
					  le32_to_cpu(req->OutputBufferLength));
	if (buf_free_len < 0)
		goto out;

4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508
	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
	if (xattr_list_len < 0) {
		goto out;
	} else if (!xattr_list_len) {
		ksmbd_debug(SMB, "empty xattr in the file\n");
		goto out;
	}

	while (idx < xattr_list_len) {
		stream_name = xattr_list + idx;
		streamlen = strlen(stream_name);
		idx += streamlen + 1;

		ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);

		if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4509
			    STREAM_PREFIX, STREAM_PREFIX_LEN))
4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522
			continue;

		stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
				STREAM_PREFIX_LEN);
		streamlen = stream_name_len;

		/* plus : size */
		streamlen += 1;
		stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
		if (!stream_buf)
			break;

		streamlen = snprintf(stream_buf, streamlen + 1,
4523
				     ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4524

4525
		next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4526 4527
		if (next > buf_free_len) {
			kfree(stream_buf);
4528
			break;
4529
		}
4530

4531
		file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4532
		streamlen  = smbConvertToUTF16((__le16 *)file_info->StreamName,
4533 4534
					       stream_buf, streamlen,
					       conn->local_nls, 0);
4535 4536 4537 4538 4539 4540 4541
		streamlen *= 2;
		kfree(stream_buf);
		file_info->StreamNameLength = cpu_to_le32(streamlen);
		file_info->StreamSize = cpu_to_le64(stream_name_len);
		file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);

		nbytes += next;
4542
		buf_free_len -= next;
4543 4544 4545
		file_info->NextEntryOffset = cpu_to_le32(next);
	}

4546
out:
4547 4548
	if (!S_ISDIR(stat.mode) &&
	    buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4549 4550 4551
		file_info = (struct smb2_file_stream_info *)
			&rsp->Buffer[nbytes];
		streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4552
					      "::$DATA", 7, conn->local_nls, 0);
4553 4554
		streamlen *= 2;
		file_info->StreamNameLength = cpu_to_le32(streamlen);
4555 4556
		file_info->StreamSize = cpu_to_le64(stat.size);
		file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4557 4558 4559 4560 4561
		nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
	}

	/* last entry offset should be 0 */
	file_info->NextEntryOffset = 0;
4562
	kvfree(xattr_list);
4563 4564 4565 4566 4567 4568

	rsp->OutputBufferLength = cpu_to_le32(nbytes);
	inc_rfc1001_len(rsp_org, nbytes);
}

static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4569
				   struct ksmbd_file *fp, void *rsp_org)
4570 4571 4572 4573
{
	struct smb2_file_internal_info *file_info;
	struct kstat stat;

J
Jason Yan 已提交
4574
	generic_fillattr(file_inode(fp->filp), &stat);
4575 4576 4577 4578 4579 4580 4581 4582
	file_info = (struct smb2_file_internal_info *)rsp->Buffer;
	file_info->IndexNumber = cpu_to_le64(stat.ino);
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_internal_info));
	inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
}

static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4583
				      struct ksmbd_file *fp, void *rsp_org)
4584 4585 4586 4587 4588 4589 4590
{
	struct smb2_file_ntwrk_info *file_info;
	struct inode *inode;
	struct kstat stat;
	u64 time;

	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
N
Namjae Jeon 已提交
4591 4592
		pr_err("no right to read the attributes : 0x%x\n",
		       fp->daccess);
4593 4594 4595 4596 4597
		return -EACCES;
	}

	file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;

4598
	inode = file_inode(fp->filp);
J
Jason Yan 已提交
4599
	generic_fillattr(inode, &stat);
4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618

	file_info->CreationTime = cpu_to_le64(fp->create_time);
	time = ksmbd_UnixTimeToNT(stat.atime);
	file_info->LastAccessTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(stat.mtime);
	file_info->LastWriteTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(stat.ctime);
	file_info->ChangeTime = cpu_to_le64(time);
	file_info->Attributes = fp->f_ci->m_fattr;
	file_info->AllocationSize =
		cpu_to_le64(get_allocation_size(inode, &stat));
	file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
	file_info->Reserved = cpu_to_le32(0);
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
	inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ntwrk_info));
	return 0;
}

4619
static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630
{
	struct smb2_file_ea_info *file_info;

	file_info = (struct smb2_file_ea_info *)rsp->Buffer;
	file_info->EASize = 0;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_ea_info));
	inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ea_info));
}

static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4631
				   struct ksmbd_file *fp, void *rsp_org)
4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642
{
	struct smb2_file_pos_info *file_info;

	file_info = (struct smb2_file_pos_info *)rsp->Buffer;
	file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_pos_info));
	inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_pos_info));
}

static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4643
			       struct ksmbd_file *fp, void *rsp_org)
4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654
{
	struct smb2_file_mode_info *file_info;

	file_info = (struct smb2_file_mode_info *)rsp->Buffer;
	file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_mode_info));
	inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_mode_info));
}

static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4655
				      struct ksmbd_file *fp, void *rsp_org)
4656 4657 4658 4659
{
	struct smb2_file_comp_info *file_info;
	struct kstat stat;

J
Jason Yan 已提交
4660
	generic_fillattr(file_inode(fp->filp), &stat);
4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675

	file_info = (struct smb2_file_comp_info *)rsp->Buffer;
	file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
	file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
	file_info->CompressionUnitShift = 0;
	file_info->ChunkShift = 0;
	file_info->ClusterShift = 0;
	memset(&file_info->Reserved[0], 0, 3);

	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_comp_info));
	inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_comp_info));
}

static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4676
				       struct ksmbd_file *fp, void *rsp_org)
4677 4678 4679 4680
{
	struct smb2_file_attr_tag_info *file_info;

	if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
N
Namjae Jeon 已提交
4681 4682
		pr_err("no right to read the attributes : 0x%x\n",
		       fp->daccess);
4683 4684 4685 4686 4687 4688 4689 4690
		return -EACCES;
	}

	file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
	file_info->FileAttributes = fp->f_ci->m_fattr;
	file_info->ReparseTag = 0;
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4691
	inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_attr_tag_info));
4692 4693 4694 4695
	return 0;
}

static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
4696
				struct ksmbd_file *fp, void *rsp_org)
4697 4698
{
	struct smb311_posix_qinfo *file_info;
4699
	struct inode *inode = file_inode(fp->filp);
4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718
	u64 time;

	file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
	file_info->CreationTime = cpu_to_le64(fp->create_time);
	time = ksmbd_UnixTimeToNT(inode->i_atime);
	file_info->LastAccessTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(inode->i_mtime);
	file_info->LastWriteTime = cpu_to_le64(time);
	time = ksmbd_UnixTimeToNT(inode->i_ctime);
	file_info->ChangeTime = cpu_to_le64(time);
	file_info->DosAttributes = fp->f_ci->m_fattr;
	file_info->Inode = cpu_to_le64(inode->i_ino);
	file_info->EndOfFile = cpu_to_le64(inode->i_size);
	file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
	file_info->HardLinks = cpu_to_le32(inode->i_nlink);
	file_info->Mode = cpu_to_le32(inode->i_mode);
	file_info->DeviceId = cpu_to_le32(inode->i_rdev);
	rsp->OutputBufferLength =
		cpu_to_le32(sizeof(struct smb311_posix_qinfo));
4719
	inc_rfc1001_len(rsp_org, sizeof(struct smb311_posix_qinfo));
4720 4721 4722 4723
	return 0;
}

static int smb2_get_info_file(struct ksmbd_work *work,
4724
			      struct smb2_query_info_req *req,
4725
			      struct smb2_query_info_rsp *rsp)
4726 4727 4728 4729 4730 4731 4732 4733
{
	struct ksmbd_file *fp;
	int fileinfoclass = 0;
	int rc = 0;
	int file_infoclass_size;
	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;

	if (test_share_config_flag(work->tcon->share_conf,
4734
				   KSMBD_SHARE_FLAG_PIPE)) {
4735
		/* smb2 info file called for pipe */
4736 4737
		return smb2_get_info_file_pipe(work->sess, req, rsp,
					       work->response_buf);
4738 4739 4740
	}

	if (work->next_smb2_rcv_hdr_off) {
4741 4742
		if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4743
				    work->compound_fid);
4744 4745 4746 4747 4748
			id = work->compound_fid;
			pid = work->compound_pfid;
		}
	}

4749
	if (!has_file_id(id)) {
4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761
		id = le64_to_cpu(req->VolatileFileId);
		pid = le64_to_cpu(req->PersistentFileId);
	}

	fp = ksmbd_lookup_fd_slow(work, id, pid);
	if (!fp)
		return -ENOENT;

	fileinfoclass = req->FileInfoClass;

	switch (fileinfoclass) {
	case FILE_ACCESS_INFORMATION:
4762
		get_file_access_info(rsp, fp, work->response_buf);
4763 4764 4765 4766
		file_infoclass_size = FILE_ACCESS_INFORMATION_SIZE;
		break;

	case FILE_BASIC_INFORMATION:
4767
		rc = get_file_basic_info(rsp, fp, work->response_buf);
4768 4769 4770 4771
		file_infoclass_size = FILE_BASIC_INFORMATION_SIZE;
		break;

	case FILE_STANDARD_INFORMATION:
4772
		get_file_standard_info(rsp, fp, work->response_buf);
4773 4774 4775 4776
		file_infoclass_size = FILE_STANDARD_INFORMATION_SIZE;
		break;

	case FILE_ALIGNMENT_INFORMATION:
4777
		get_file_alignment_info(rsp, work->response_buf);
4778 4779 4780 4781
		file_infoclass_size = FILE_ALIGNMENT_INFORMATION_SIZE;
		break;

	case FILE_ALL_INFORMATION:
4782
		rc = get_file_all_info(work, rsp, fp, work->response_buf);
4783 4784 4785 4786
		file_infoclass_size = FILE_ALL_INFORMATION_SIZE;
		break;

	case FILE_ALTERNATE_NAME_INFORMATION:
4787
		get_file_alternate_info(work, rsp, fp, work->response_buf);
4788 4789 4790 4791
		file_infoclass_size = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
		break;

	case FILE_STREAM_INFORMATION:
4792
		get_file_stream_info(work, rsp, fp, work->response_buf);
4793 4794 4795 4796
		file_infoclass_size = FILE_STREAM_INFORMATION_SIZE;
		break;

	case FILE_INTERNAL_INFORMATION:
4797
		get_file_internal_info(rsp, fp, work->response_buf);
4798 4799 4800 4801
		file_infoclass_size = FILE_INTERNAL_INFORMATION_SIZE;
		break;

	case FILE_NETWORK_OPEN_INFORMATION:
4802
		rc = get_file_network_open_info(rsp, fp, work->response_buf);
4803 4804 4805 4806
		file_infoclass_size = FILE_NETWORK_OPEN_INFORMATION_SIZE;
		break;

	case FILE_EA_INFORMATION:
4807
		get_file_ea_info(rsp, work->response_buf);
4808 4809 4810 4811
		file_infoclass_size = FILE_EA_INFORMATION_SIZE;
		break;

	case FILE_FULL_EA_INFORMATION:
4812
		rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4813 4814 4815 4816
		file_infoclass_size = FILE_FULL_EA_INFORMATION_SIZE;
		break;

	case FILE_POSITION_INFORMATION:
4817
		get_file_position_info(rsp, fp, work->response_buf);
4818 4819 4820 4821
		file_infoclass_size = FILE_POSITION_INFORMATION_SIZE;
		break;

	case FILE_MODE_INFORMATION:
4822
		get_file_mode_info(rsp, fp, work->response_buf);
4823 4824 4825 4826
		file_infoclass_size = FILE_MODE_INFORMATION_SIZE;
		break;

	case FILE_COMPRESSION_INFORMATION:
4827
		get_file_compression_info(rsp, fp, work->response_buf);
4828 4829 4830 4831
		file_infoclass_size = FILE_COMPRESSION_INFORMATION_SIZE;
		break;

	case FILE_ATTRIBUTE_TAG_INFORMATION:
4832
		rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4833 4834 4835 4836
		file_infoclass_size = FILE_ATTRIBUTE_TAG_INFORMATION_SIZE;
		break;
	case SMB_FIND_FILE_POSIX_INFO:
		if (!work->tcon->posix_extensions) {
N
Namjae Jeon 已提交
4837
			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4838 4839
			rc = -EOPNOTSUPP;
		} else {
4840
			rc = find_file_posix_info(rsp, fp, work->response_buf);
4841 4842 4843 4844 4845 4846 4847 4848 4849 4850
			file_infoclass_size = sizeof(struct smb311_posix_qinfo);
		}
		break;
	default:
		ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
			    fileinfoclass);
		rc = -EOPNOTSUPP;
	}
	if (!rc)
		rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4851
				      rsp, work->response_buf,
4852 4853 4854 4855 4856 4857
				      file_infoclass_size);
	ksmbd_fd_put(work, fp);
	return rc;
}

static int smb2_get_info_filesystem(struct ksmbd_work *work,
4858
				    struct smb2_query_info_req *req,
4859
				    struct smb2_query_info_rsp *rsp)
4860 4861
{
	struct ksmbd_session *sess = work->sess;
4862
	struct ksmbd_conn *conn = work->conn;
4863 4864 4865 4866 4867 4868
	struct ksmbd_share_config *share = work->tcon->share_conf;
	int fsinfoclass = 0;
	struct kstatfs stfs;
	struct path path;
	int rc = 0, len;
	int fs_infoclass_size = 0;
4869

4870 4871 4872
	if (!share->path)
		return -EIO;

4873
	rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4874
	if (rc) {
N
Namjae Jeon 已提交
4875
		pr_err("cannot create vfs path\n");
4876 4877 4878 4879 4880
		return -EIO;
	}

	rc = vfs_statfs(&path, &stfs);
	if (rc) {
N
Namjae Jeon 已提交
4881
		pr_err("cannot do stat of path %s\n", share->path);
4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897
		path_put(&path);
		return -EIO;
	}

	fsinfoclass = req->FileInfoClass;

	switch (fsinfoclass) {
	case FS_DEVICE_INFORMATION:
	{
		struct filesystem_device_info *info;

		info = (struct filesystem_device_info *)rsp->Buffer;

		info->DeviceType = cpu_to_le32(stfs.f_type);
		info->DeviceCharacteristics = cpu_to_le32(0x00000020);
		rsp->OutputBufferLength = cpu_to_le32(8);
4898
		inc_rfc1001_len(work->response_buf, 8);
4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911
		fs_infoclass_size = FS_DEVICE_INFORMATION_SIZE;
		break;
	}
	case FS_ATTRIBUTE_INFORMATION:
	{
		struct filesystem_attribute_info *info;
		size_t sz;

		info = (struct filesystem_attribute_info *)rsp->Buffer;
		info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
					       FILE_PERSISTENT_ACLS |
					       FILE_UNICODE_ON_DISK |
					       FILE_CASE_PRESERVED_NAMES |
4912 4913
					       FILE_CASE_SENSITIVE_SEARCH |
					       FILE_SUPPORTS_BLOCK_REFCOUNTING);
4914 4915 4916 4917 4918 4919 4920 4921 4922 4923

		info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);

		info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
		len = smbConvertToUTF16((__le16 *)info->FileSystemName,
					"NTFS", PATH_MAX, conn->local_nls, 0);
		len = len * 2;
		info->FileSystemNameLen = cpu_to_le32(len);
		sz = sizeof(struct filesystem_attribute_info) - 2 + len;
		rsp->OutputBufferLength = cpu_to_le32(sz);
4924
		inc_rfc1001_len(work->response_buf, sz);
4925 4926 4927 4928 4929 4930 4931
		fs_infoclass_size = FS_ATTRIBUTE_INFORMATION_SIZE;
		break;
	}
	case FS_VOLUME_INFORMATION:
	{
		struct filesystem_vol_info *info;
		size_t sz;
4932
		unsigned int serial_crc = 0;
4933 4934 4935

		info = (struct filesystem_vol_info *)(rsp->Buffer);
		info->VolumeCreationTime = 0;
4936 4937 4938 4939 4940 4941
		serial_crc = crc32_le(serial_crc, share->name,
				      strlen(share->name));
		serial_crc = crc32_le(serial_crc, share->path,
				      strlen(share->path));
		serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
				      strlen(ksmbd_netbios_name()));
4942
		/* Taking dummy value of serial number*/
4943
		info->SerialNumber = cpu_to_le32(serial_crc);
4944 4945 4946 4947 4948 4949 4950 4951
		len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
					share->name, PATH_MAX,
					conn->local_nls, 0);
		len = len * 2;
		info->VolumeLabelSize = cpu_to_le32(len);
		info->Reserved = 0;
		sz = sizeof(struct filesystem_vol_info) - 2 + len;
		rsp->OutputBufferLength = cpu_to_le32(sz);
4952
		inc_rfc1001_len(work->response_buf, sz);
4953 4954 4955 4956 4957 4958 4959 4960 4961 4962
		fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
		break;
	}
	case FS_SIZE_INFORMATION:
	{
		struct filesystem_info *info;

		info = (struct filesystem_info *)(rsp->Buffer);
		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
		info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
4963 4964
		info->SectorsPerAllocationUnit = cpu_to_le32(1);
		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4965
		rsp->OutputBufferLength = cpu_to_le32(24);
4966
		inc_rfc1001_len(work->response_buf, 24);
4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979
		fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
		break;
	}
	case FS_FULL_SIZE_INFORMATION:
	{
		struct smb2_fs_full_size_info *info;

		info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
		info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
		info->CallerAvailableAllocationUnits =
					cpu_to_le64(stfs.f_bavail);
		info->ActualAvailableAllocationUnits =
					cpu_to_le64(stfs.f_bfree);
4980 4981
		info->SectorsPerAllocationUnit = cpu_to_le32(1);
		info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4982
		rsp->OutputBufferLength = cpu_to_le32(32);
4983
		inc_rfc1001_len(work->response_buf, 32);
4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001
		fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
		break;
	}
	case FS_OBJECT_ID_INFORMATION:
	{
		struct object_id_info *info;

		info = (struct object_id_info *)(rsp->Buffer);

		if (!user_guest(sess->user))
			memcpy(info->objid, user_passkey(sess->user), 16);
		else
			memset(info->objid, 0, 16);

		info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
		info->extended_info.version = cpu_to_le32(1);
		info->extended_info.release = cpu_to_le32(1);
		info->extended_info.rel_date = 0;
5002
		memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5003
		rsp->OutputBufferLength = cpu_to_le32(64);
5004
		inc_rfc1001_len(work->response_buf, 64);
5005 5006 5007 5008 5009 5010 5011 5012 5013
		fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
		break;
	}
	case FS_SECTOR_SIZE_INFORMATION:
	{
		struct smb3_fs_ss_info *info;

		info = (struct smb3_fs_ss_info *)(rsp->Buffer);

5014
		info->LogicalBytesPerSector = cpu_to_le32(stfs.f_bsize);
5015
		info->PhysicalBytesPerSectorForAtomicity =
5016 5017
				cpu_to_le32(stfs.f_bsize);
		info->PhysicalBytesPerSectorForPerf = cpu_to_le32(stfs.f_bsize);
5018
		info->FSEffPhysicalBytesPerSectorForAtomicity =
5019
				cpu_to_le32(stfs.f_bsize);
5020 5021 5022 5023 5024
		info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
				    SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
		info->ByteOffsetForSectorAlignment = 0;
		info->ByteOffsetForPartitionAlignment = 0;
		rsp->OutputBufferLength = cpu_to_le32(28);
5025
		inc_rfc1001_len(work->response_buf, 28);
5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046
		fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
		break;
	}
	case FS_CONTROL_INFORMATION:
	{
		/*
		 * TODO : The current implementation is based on
		 * test result with win7(NTFS) server. It's need to
		 * modify this to get valid Quota values
		 * from Linux kernel
		 */
		struct smb2_fs_control_info *info;

		info = (struct smb2_fs_control_info *)(rsp->Buffer);
		info->FreeSpaceStartFiltering = 0;
		info->FreeSpaceThreshold = 0;
		info->FreeSpaceStopFiltering = 0;
		info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
		info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
		info->Padding = 0;
		rsp->OutputBufferLength = cpu_to_le32(48);
5047
		inc_rfc1001_len(work->response_buf, 48);
5048 5049 5050 5051 5052 5053 5054 5055
		fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
		break;
	}
	case FS_POSIX_INFORMATION:
	{
		struct filesystem_posix_info *info;

		if (!work->tcon->posix_extensions) {
N
Namjae Jeon 已提交
5056
			pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5057 5058 5059
			rc = -EOPNOTSUPP;
		} else {
			info = (struct filesystem_posix_info *)(rsp->Buffer);
5060
			info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5061 5062 5063 5064 5065 5066 5067
			info->BlockSize = cpu_to_le32(stfs.f_bsize);
			info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
			info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
			info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
			info->TotalFileNodes = cpu_to_le64(stfs.f_files);
			info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
			rsp->OutputBufferLength = cpu_to_le32(56);
5068
			inc_rfc1001_len(work->response_buf, 56);
5069 5070 5071 5072 5073 5074 5075 5076 5077
			fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
		}
		break;
	}
	default:
		path_put(&path);
		return -EOPNOTSUPP;
	}
	rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5078
			      rsp, work->response_buf,
5079 5080 5081 5082 5083 5084
			      fs_infoclass_size);
	path_put(&path);
	return rc;
}

static int smb2_get_info_sec(struct ksmbd_work *work,
5085
			     struct smb2_query_info_req *req,
5086
			     struct smb2_query_info_rsp *rsp)
5087 5088 5089 5090 5091
{
	struct ksmbd_file *fp;
	struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
	struct smb_fattr fattr = {{0}};
	struct inode *inode;
5092
	__u32 secdesclen = 0;
5093 5094
	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
	int addition_info = le32_to_cpu(req->AdditionalInformation);
5095
	int rc = 0, ppntsd_size = 0;
5096

5097 5098 5099
	if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
			      PROTECTED_DACL_SECINFO |
			      UNPROTECTED_DACL_SECINFO)) {
5100
		ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5101
		       addition_info);
5102 5103 5104 5105 5106 5107 5108 5109 5110 5111

		pntsd->revision = cpu_to_le16(1);
		pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
		pntsd->osidoffset = 0;
		pntsd->gsidoffset = 0;
		pntsd->sacloffset = 0;
		pntsd->dacloffset = 0;

		secdesclen = sizeof(struct smb_ntsd);
		rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5112
		inc_rfc1001_len(work->response_buf, secdesclen);
5113 5114 5115 5116

		return 0;
	}

5117
	if (work->next_smb2_rcv_hdr_off) {
5118 5119
		if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5120
				    work->compound_fid);
5121 5122 5123 5124 5125
			id = work->compound_fid;
			pid = work->compound_pfid;
		}
	}

5126
	if (!has_file_id(id)) {
5127 5128 5129 5130 5131 5132 5133 5134
		id = le64_to_cpu(req->VolatileFileId);
		pid = le64_to_cpu(req->PersistentFileId);
	}

	fp = ksmbd_lookup_fd_slow(work, id, pid);
	if (!fp)
		return -ENOENT;

5135
	inode = file_inode(fp->filp);
5136
	ksmbd_acls_fattr(&fattr, inode);
5137 5138

	if (test_share_config_flag(work->tcon->share_conf,
5139
				   KSMBD_SHARE_FLAG_ACL_XATTR))
5140 5141 5142 5143 5144 5145 5146 5147
		ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn,
						     fp->filp->f_path.dentry,
						     &ppntsd);

	/* Check if sd buffer size exceeds response buffer size */
	if (smb2_resp_buf_len(work, 8) > ppntsd_size)
		rc = build_sec_desc(pntsd, ppntsd, ppntsd_size,
				    addition_info, &secdesclen, &fattr);
5148 5149 5150 5151 5152 5153 5154 5155
	posix_acl_release(fattr.cf_acls);
	posix_acl_release(fattr.cf_dacls);
	kfree(ppntsd);
	ksmbd_fd_put(work, fp);
	if (rc)
		return rc;

	rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5156
	inc_rfc1001_len(work->response_buf, secdesclen);
5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168
	return 0;
}

/**
 * smb2_query_info() - handler for smb2 query info command
 * @work:	smb work containing query info request buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_query_info(struct ksmbd_work *work)
{
	struct smb2_query_info_req *req;
5169
	struct smb2_query_info_rsp *rsp;
5170 5171 5172 5173 5174 5175 5176 5177 5178
	int rc = 0;

	WORK_BUFFERS(work, req, rsp);

	ksmbd_debug(SMB, "GOT query info request\n");

	switch (req->InfoType) {
	case SMB2_O_INFO_FILE:
		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5179
		rc = smb2_get_info_file(work, req, rsp);
5180 5181 5182
		break;
	case SMB2_O_INFO_FILESYSTEM:
		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5183
		rc = smb2_get_info_filesystem(work, req, rsp);
5184 5185 5186
		break;
	case SMB2_O_INFO_SECURITY:
		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5187
		rc = smb2_get_info_sec(work, req, rsp);
5188 5189 5190
		break;
	default:
		ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5191
			    req->InfoType);
5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206
		rc = -EOPNOTSUPP;
	}

	if (rc < 0) {
		if (rc == -EACCES)
			rsp->hdr.Status = STATUS_ACCESS_DENIED;
		else if (rc == -ENOENT)
			rsp->hdr.Status = STATUS_FILE_CLOSED;
		else if (rc == -EIO)
			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
		else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
			rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
		smb2_set_err_rsp(work);

		ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5207
			    rc);
5208 5209 5210 5211
		return rc;
	}
	rsp->StructureSize = cpu_to_le16(9);
	rsp->OutputBufferOffset = cpu_to_le16(72);
5212
	inc_rfc1001_len(work->response_buf, 8);
5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223
	return 0;
}

/**
 * smb2_close_pipe() - handler for closing IPC pipe
 * @work:	smb work containing close request buffer
 *
 * Return:	0
 */
static noinline int smb2_close_pipe(struct ksmbd_work *work)
{
5224
	u64 id;
5225 5226
	struct smb2_close_req *req = smb2_get_msg(work->request_buf);
	struct smb2_close_rsp *rsp = smb2_get_msg(work->response_buf);
5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240

	id = le64_to_cpu(req->VolatileFileId);
	ksmbd_session_rpc_close(work->sess, id);

	rsp->StructureSize = cpu_to_le16(60);
	rsp->Flags = 0;
	rsp->Reserved = 0;
	rsp->CreationTime = 0;
	rsp->LastAccessTime = 0;
	rsp->LastWriteTime = 0;
	rsp->ChangeTime = 0;
	rsp->AllocationSize = 0;
	rsp->EndOfFile = 0;
	rsp->Attributes = 0;
5241
	inc_rfc1001_len(work->response_buf, 60);
5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252
	return 0;
}

/**
 * smb2_close() - handler for smb2 close file command
 * @work:	smb work containing close request buffer
 *
 * Return:	0
 */
int smb2_close(struct ksmbd_work *work)
{
5253
	u64 volatile_id = KSMBD_NO_FID;
5254
	u64 sess_id;
5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275
	struct smb2_close_req *req;
	struct smb2_close_rsp *rsp;
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_file *fp;
	struct inode *inode;
	u64 time;
	int err = 0;

	WORK_BUFFERS(work, req, rsp);

	if (test_share_config_flag(work->tcon->share_conf,
				   KSMBD_SHARE_FLAG_PIPE)) {
		ksmbd_debug(SMB, "IPC pipe close request\n");
		return smb2_close_pipe(work);
	}

	sess_id = le64_to_cpu(req->hdr.SessionId);
	if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
		sess_id = work->compound_sid;

	work->compound_sid = 0;
5276
	if (check_session_id(conn, sess_id)) {
5277
		work->compound_sid = sess_id;
5278
	} else {
5279 5280 5281 5282 5283 5284 5285 5286
		rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
		if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		err = -EBADF;
		goto out;
	}

	if (work->next_smb2_rcv_hdr_off &&
5287 5288
	    !has_file_id(le64_to_cpu(req->VolatileFileId))) {
		if (!has_file_id(work->compound_fid)) {
5289 5290 5291 5292 5293 5294
			/* file already closed, return FILE_CLOSED */
			ksmbd_debug(SMB, "file already closed\n");
			rsp->hdr.Status = STATUS_FILE_CLOSED;
			err = -EBADF;
			goto out;
		} else {
5295 5296
			ksmbd_debug(SMB,
				    "Compound request set FID = %llu:%llu\n",
5297 5298
				    work->compound_fid,
				    work->compound_pfid);
5299 5300 5301 5302 5303 5304 5305 5306 5307
			volatile_id = work->compound_fid;

			/* file closed, stored id is not valid anymore */
			work->compound_fid = KSMBD_NO_FID;
			work->compound_pfid = KSMBD_NO_FID;
		}
	} else {
		volatile_id = le64_to_cpu(req->VolatileFileId);
	}
5308
	ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319

	rsp->StructureSize = cpu_to_le16(60);
	rsp->Reserved = 0;

	if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
		fp = ksmbd_lookup_fd_fast(work, volatile_id);
		if (!fp) {
			err = -ENOENT;
			goto out;
		}

5320
		inode = file_inode(fp->filp);
5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351
		rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
		rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
			cpu_to_le64(inode->i_blocks << 9);
		rsp->EndOfFile = cpu_to_le64(inode->i_size);
		rsp->Attributes = fp->f_ci->m_fattr;
		rsp->CreationTime = cpu_to_le64(fp->create_time);
		time = ksmbd_UnixTimeToNT(inode->i_atime);
		rsp->LastAccessTime = cpu_to_le64(time);
		time = ksmbd_UnixTimeToNT(inode->i_mtime);
		rsp->LastWriteTime = cpu_to_le64(time);
		time = ksmbd_UnixTimeToNT(inode->i_ctime);
		rsp->ChangeTime = cpu_to_le64(time);
		ksmbd_fd_put(work, fp);
	} else {
		rsp->Flags = 0;
		rsp->AllocationSize = 0;
		rsp->EndOfFile = 0;
		rsp->Attributes = 0;
		rsp->CreationTime = 0;
		rsp->LastAccessTime = 0;
		rsp->LastWriteTime = 0;
		rsp->ChangeTime = 0;
	}

	err = ksmbd_close_fd(work, volatile_id);
out:
	if (err) {
		if (rsp->hdr.Status == 0)
			rsp->hdr.Status = STATUS_FILE_CLOSED;
		smb2_set_err_rsp(work);
	} else {
5352
		inc_rfc1001_len(work->response_buf, 60);
5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365
	}

	return 0;
}

/**
 * smb2_echo() - handler for smb2 echo(ping) command
 * @work:	smb work containing echo request buffer
 *
 * Return:	0
 */
int smb2_echo(struct ksmbd_work *work)
{
5366
	struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5367 5368 5369

	rsp->StructureSize = cpu_to_le16(4);
	rsp->Reserved = 0;
5370
	inc_rfc1001_len(work->response_buf, 4);
5371 5372 5373 5374
	return 0;
}

static int smb2_rename(struct ksmbd_work *work, struct ksmbd_file *fp,
5375 5376
		       struct smb2_file_rename_info *file_info,
		       struct nls_table *local_nls)
5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395
{
	struct ksmbd_share_config *share = fp->tcon->share_conf;
	char *new_name = NULL, *abs_oldname = NULL, *old_name = NULL;
	char *pathname = NULL;
	struct path path;
	bool file_present = true;
	int rc;

	ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
	pathname = kmalloc(PATH_MAX, GFP_KERNEL);
	if (!pathname)
		return -ENOMEM;

	abs_oldname = d_path(&fp->filp->f_path, pathname, PATH_MAX);
	if (IS_ERR(abs_oldname)) {
		rc = -EINVAL;
		goto out;
	}
	old_name = strrchr(abs_oldname, '/');
5396
	if (old_name && old_name[1] != '\0') {
5397
		old_name++;
5398
	} else {
5399
		ksmbd_debug(SMB, "can't get last component in path %s\n",
5400
			    abs_oldname);
5401 5402 5403 5404
		rc = -ENOENT;
		goto out;
	}

5405
	new_name = smb2_get_name(file_info->FileName,
5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423
				 le32_to_cpu(file_info->FileNameLength),
				 local_nls);
	if (IS_ERR(new_name)) {
		rc = PTR_ERR(new_name);
		goto out;
	}

	if (strchr(new_name, ':')) {
		int s_type;
		char *xattr_stream_name, *stream_name = NULL;
		size_t xattr_stream_size;
		int len;

		rc = parse_stream_name(new_name, &stream_name, &s_type);
		if (rc < 0)
			goto out;

		len = strlen(new_name);
5424
		if (len > 0 && new_name[len - 1] != '/') {
N
Namjae Jeon 已提交
5425
			pr_err("not allow base filename in rename\n");
5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440
			rc = -ESHARE;
			goto out;
		}

		rc = ksmbd_vfs_xattr_stream_name(stream_name,
						 &xattr_stream_name,
						 &xattr_stream_size,
						 s_type);
		if (rc)
			goto out;

		rc = ksmbd_vfs_setxattr(fp->filp->f_path.dentry,
					xattr_stream_name,
					NULL, 0, 0);
		if (rc < 0) {
N
Namjae Jeon 已提交
5441 5442
			pr_err("failed to store stream name in xattr: %d\n",
			       rc);
5443 5444 5445 5446 5447 5448 5449 5450
			rc = -EINVAL;
			goto out;
		}

		goto out;
	}

	ksmbd_debug(SMB, "new name %s\n", new_name);
5451 5452 5453 5454
	rc = ksmbd_vfs_kern_path(work, new_name, LOOKUP_NO_SYMLINKS, &path, 1);
	if (rc) {
		if (rc != -ENOENT)
			goto out;
5455
		file_present = false;
5456
	} else {
5457
		path_put(&path);
5458
	}
5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472

	if (ksmbd_share_veto_filename(share, new_name)) {
		rc = -ENOENT;
		ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
		goto out;
	}

	if (file_info->ReplaceIfExists) {
		if (file_present) {
			rc = ksmbd_vfs_remove_file(work, new_name);
			if (rc) {
				if (rc != -ENOTEMPTY)
					rc = -EINVAL;
				ksmbd_debug(SMB, "cannot delete %s, rc %d\n",
5473
					    new_name, rc);
5474 5475 5476 5477 5478
				goto out;
			}
		}
	} else {
		if (file_present &&
5479
		    strncmp(old_name, path.dentry->d_name.name, strlen(old_name))) {
5480 5481
			rc = -EEXIST;
			ksmbd_debug(SMB,
5482
				    "cannot rename already existing file\n");
5483 5484 5485 5486 5487 5488 5489 5490
			goto out;
		}
	}

	rc = ksmbd_vfs_fp_rename(work, fp, new_name);
out:
	kfree(pathname);
	if (!IS_ERR(new_name))
M
Marios Makassikis 已提交
5491
		kfree(new_name);
5492 5493 5494 5495
	return rc;
}

static int smb2_create_link(struct ksmbd_work *work,
5496 5497
			    struct ksmbd_share_config *share,
			    struct smb2_file_link_info *file_info,
5498
			    unsigned int buf_len, struct file *filp,
5499
			    struct nls_table *local_nls)
5500 5501 5502 5503 5504 5505
{
	char *link_name = NULL, *target_name = NULL, *pathname = NULL;
	struct path path;
	bool file_present = true;
	int rc;

5506 5507 5508 5509
	if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
			le32_to_cpu(file_info->FileNameLength))
		return -EINVAL;

5510 5511 5512 5513 5514
	ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
	pathname = kmalloc(PATH_MAX, GFP_KERNEL);
	if (!pathname)
		return -ENOMEM;

5515
	link_name = smb2_get_name(file_info->FileName,
5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530
				  le32_to_cpu(file_info->FileNameLength),
				  local_nls);
	if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
		rc = -EINVAL;
		goto out;
	}

	ksmbd_debug(SMB, "link name is %s\n", link_name);
	target_name = d_path(&filp->f_path, pathname, PATH_MAX);
	if (IS_ERR(target_name)) {
		rc = -EINVAL;
		goto out;
	}

	ksmbd_debug(SMB, "target name is %s\n", target_name);
5531 5532 5533 5534
	rc = ksmbd_vfs_kern_path(work, link_name, LOOKUP_NO_SYMLINKS, &path, 0);
	if (rc) {
		if (rc != -ENOENT)
			goto out;
5535
		file_present = false;
5536
	} else {
5537
		path_put(&path);
5538
	}
5539 5540 5541 5542 5543 5544 5545

	if (file_info->ReplaceIfExists) {
		if (file_present) {
			rc = ksmbd_vfs_remove_file(work, link_name);
			if (rc) {
				rc = -EINVAL;
				ksmbd_debug(SMB, "cannot delete %s\n",
5546
					    link_name);
5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562
				goto out;
			}
		}
	} else {
		if (file_present) {
			rc = -EEXIST;
			ksmbd_debug(SMB, "link already exists\n");
			goto out;
		}
	}

	rc = ksmbd_vfs_link(work, target_name, link_name);
	if (rc)
		rc = -EINVAL;
out:
	if (!IS_ERR(link_name))
M
Marios Makassikis 已提交
5563
		kfree(link_name);
5564 5565 5566 5567
	kfree(pathname);
	return rc;
}

5568 5569
static int set_file_basic_info(struct ksmbd_file *fp,
			       struct smb2_file_basic_info *file_info,
5570
			       struct ksmbd_share_config *share)
5571 5572 5573 5574
{
	struct iattr attrs;
	struct file *filp;
	struct inode *inode;
5575
	int rc = 0;
5576

5577
	if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591
		return -EACCES;

	attrs.ia_valid = 0;
	filp = fp->filp;
	inode = file_inode(filp);

	if (file_info->CreationTime)
		fp->create_time = le64_to_cpu(file_info->CreationTime);

	if (file_info->LastAccessTime) {
		attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
		attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
	}

N
Namjae Jeon 已提交
5592 5593
	attrs.ia_valid |= ATTR_CTIME;
	if (file_info->ChangeTime)
5594
		attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
N
Namjae Jeon 已提交
5595 5596
	else
		attrs.ia_ctime = inode->i_ctime;
5597 5598 5599 5600 5601 5602 5603 5604

	if (file_info->LastWriteTime) {
		attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
		attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
	}

	if (file_info->Attributes) {
		if (!S_ISDIR(inode->i_mode) &&
5605
		    file_info->Attributes & ATTR_DIRECTORY_LE) {
N
Namjae Jeon 已提交
5606
			pr_err("can't change a file to a directory\n");
5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628
			return -EINVAL;
		}

		if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == ATTR_NORMAL_LE))
			fp->f_ci->m_fattr = file_info->Attributes |
				(fp->f_ci->m_fattr & ATTR_DIRECTORY_LE);
	}

	if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
	    (file_info->CreationTime || file_info->Attributes)) {
		struct xattr_dos_attrib da = {0};

		da.version = 4;
		da.itime = fp->itime;
		da.create_time = fp->create_time;
		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
		da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
			XATTR_DOSINFO_ITIME;

		rc = ksmbd_vfs_set_dos_attrib_xattr(filp->f_path.dentry, &da);
		if (rc)
			ksmbd_debug(SMB,
5629
				    "failed to restore file attribute in EA\n");
5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640
		rc = 0;
	}

	if (attrs.ia_valid) {
		struct dentry *dentry = filp->f_path.dentry;
		struct inode *inode = d_inode(dentry);

		if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
			return -EACCES;

		inode_lock(inode);
N
Namjae Jeon 已提交
5641 5642
		inode->i_ctime = attrs.ia_ctime;
		attrs.ia_valid &= ~ATTR_CTIME;
J
Jason Yan 已提交
5643
		rc = notify_change(dentry, &attrs, NULL);
5644 5645
		inode_unlock(inode);
	}
5646
	return rc;
5647 5648 5649
}

static int set_file_allocation_info(struct ksmbd_work *work,
5650 5651
				    struct ksmbd_file *fp,
				    struct smb2_file_alloc_info *file_alloc_info)
5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662
{
	/*
	 * TODO : It's working fine only when store dos attributes
	 * is not yes. need to implement a logic which works
	 * properly with any smb.conf option
	 */

	loff_t alloc_blks;
	struct inode *inode;
	int rc;

5663
	if (!(fp->daccess & FILE_WRITE_DATA_LE))
5664 5665 5666 5667 5668 5669
		return -EACCES;

	alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
	inode = file_inode(fp->filp);

	if (alloc_blks > inode->i_blocks) {
5670 5671 5672
		smb_break_all_levII_oplock(work, fp, 1);
		rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
				   alloc_blks * 512);
5673
		if (rc && rc != -EOPNOTSUPP) {
5674
			pr_err("vfs_fallocate is failed : %d\n", rc);
5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687
			return rc;
		}
	} else if (alloc_blks < inode->i_blocks) {
		loff_t size;

		/*
		 * Allocation size could be smaller than original one
		 * which means allocated blocks in file should be
		 * deallocated. use truncate to cut out it, but inode
		 * size is also updated with truncate offset.
		 * inode size is retained by backup inode size.
		 */
		size = i_size_read(inode);
5688
		rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5689
		if (rc) {
N
Namjae Jeon 已提交
5690 5691
			pr_err("truncate failed! filename : %s, err %d\n",
			       fp->filename, rc);
5692 5693 5694 5695 5696 5697 5698 5699
			return rc;
		}
		if (size < alloc_blks * 512)
			i_size_write(inode, size);
	}
	return 0;
}

5700
static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5701
				struct smb2_file_eof_info *file_eof_info)
5702 5703 5704 5705 5706
{
	loff_t newsize;
	struct inode *inode;
	int rc;

5707
	if (!(fp->daccess & FILE_WRITE_DATA_LE))
5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721
		return -EACCES;

	newsize = le64_to_cpu(file_eof_info->EndOfFile);
	inode = file_inode(fp->filp);

	/*
	 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
	 * on FAT32 shared device, truncate execution time is too long
	 * and network error could cause from windows client. because
	 * truncate of some filesystem like FAT32 fill zero data in
	 * truncated range.
	 */
	if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
		ksmbd_debug(SMB, "filename : %s truncated to newsize %lld\n",
5722
			    fp->filename, newsize);
5723
		rc = ksmbd_vfs_truncate(work, fp, newsize);
5724
		if (rc) {
5725
			ksmbd_debug(SMB, "truncate failed! filename : %s err %d\n",
5726
				    fp->filename, rc);
5727 5728 5729 5730 5731 5732 5733 5734
			if (rc != -EAGAIN)
				rc = -EBADF;
			return rc;
		}
	}
	return 0;
}

5735
static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5736 5737
			   struct smb2_file_rename_info *rename_info,
			   unsigned int buf_len)
5738 5739
{
	struct ksmbd_file *parent_fp;
5740 5741 5742
	struct dentry *parent;
	struct dentry *dentry = fp->filp->f_path.dentry;
	int ret;
5743 5744

	if (!(fp->daccess & FILE_DELETE_LE)) {
N
Namjae Jeon 已提交
5745
		pr_err("no right to delete : 0x%x\n", fp->daccess);
5746 5747 5748
		return -EACCES;
	}

5749 5750 5751 5752
	if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
			le32_to_cpu(rename_info->FileNameLength))
		return -EINVAL;

5753 5754 5755
	if (ksmbd_stream_fd(fp))
		goto next;

5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766
	parent = dget_parent(dentry);
	ret = ksmbd_vfs_lock_parent(parent, dentry);
	if (ret) {
		dput(parent);
		return ret;
	}

	parent_fp = ksmbd_lookup_fd_inode(d_inode(parent));
	inode_unlock(d_inode(parent));
	dput(parent);

5767 5768
	if (parent_fp) {
		if (parent_fp->daccess & FILE_DELETE_LE) {
N
Namjae Jeon 已提交
5769
			pr_err("parent dir is opened with delete access\n");
5770 5771 5772 5773
			return -ESHARE;
		}
	}
next:
5774
	return smb2_rename(work, fp, rename_info,
5775
			   work->conn->local_nls);
5776 5777
}

5778 5779
static int set_file_disposition_info(struct ksmbd_file *fp,
				     struct smb2_file_disposition_info *file_info)
5780 5781 5782 5783
{
	struct inode *inode;

	if (!(fp->daccess & FILE_DELETE_LE)) {
N
Namjae Jeon 已提交
5784
		pr_err("no right to delete : 0x%x\n", fp->daccess);
5785 5786 5787 5788 5789 5790
		return -EACCES;
	}

	inode = file_inode(fp->filp);
	if (file_info->DeletePending) {
		if (S_ISDIR(inode->i_mode) &&
5791
		    ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5792 5793 5794 5795 5796 5797 5798 5799
			return -EBUSY;
		ksmbd_set_inode_pending_delete(fp);
	} else {
		ksmbd_clear_inode_pending_delete(fp);
	}
	return 0;
}

5800 5801
static int set_file_position_info(struct ksmbd_file *fp,
				  struct smb2_file_pos_info *file_info)
5802 5803
{
	loff_t current_byte_offset;
5804
	unsigned long sector_size;
5805 5806 5807 5808
	struct inode *inode;

	inode = file_inode(fp->filp);
	current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5809
	sector_size = inode->i_sb->s_blocksize;
5810 5811

	if (current_byte_offset < 0 ||
5812 5813
	    (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
	     current_byte_offset & (sector_size - 1))) {
N
Namjae Jeon 已提交
5814 5815
		pr_err("CurrentByteOffset is not valid : %llu\n",
		       current_byte_offset);
5816 5817 5818 5819 5820 5821 5822
		return -EINVAL;
	}

	fp->filp->f_pos = current_byte_offset;
	return 0;
}

5823 5824
static int set_file_mode_info(struct ksmbd_file *fp,
			      struct smb2_file_mode_info *file_info)
5825 5826 5827 5828 5829
{
	__le32 mode;

	mode = file_info->Mode;

5830 5831 5832
	if ((mode & ~FILE_MODE_INFO_MASK) ||
	    (mode & FILE_SYNCHRONOUS_IO_ALERT_LE &&
	     mode & FILE_SYNCHRONOUS_IO_NONALERT_LE)) {
N
Namjae Jeon 已提交
5833
		pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848
		return -EINVAL;
	}

	/*
	 * TODO : need to implement consideration for
	 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
	 */
	ksmbd_vfs_set_fadvise(fp->filp, mode);
	fp->coption = mode;
	return 0;
}

/**
 * smb2_set_info_file() - handler for smb2 set info command
 * @work:	smb work containing set info command buffer
H
Hyunchul Lee 已提交
5849
 * @fp:		ksmbd_file pointer
5850
 * @req:	request buffer pointer
H
Hyunchul Lee 已提交
5851
 * @share:	ksmbd_share_config pointer
5852 5853 5854 5855
 *
 * Return:	0 on success, otherwise error
 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
 */
5856
static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5857
			      struct smb2_set_info_req *req,
5858
			      struct ksmbd_share_config *share)
5859
{
5860 5861 5862
	unsigned int buf_len = le32_to_cpu(req->BufferLength);

	switch (req->FileInfoClass) {
5863
	case FILE_BASIC_INFORMATION:
5864 5865 5866
	{
		if (buf_len < sizeof(struct smb2_file_basic_info))
			return -EINVAL;
5867

5868 5869
		return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
	}
5870
	case FILE_ALLOCATION_INFORMATION:
5871 5872 5873
	{
		if (buf_len < sizeof(struct smb2_file_alloc_info))
			return -EINVAL;
5874

5875 5876 5877
		return set_file_allocation_info(work, fp,
						(struct smb2_file_alloc_info *)req->Buffer);
	}
5878
	case FILE_END_OF_FILE_INFORMATION:
5879 5880 5881
	{
		if (buf_len < sizeof(struct smb2_file_eof_info))
			return -EINVAL;
5882

5883 5884 5885
		return set_end_of_file_info(work, fp,
					    (struct smb2_file_eof_info *)req->Buffer);
	}
5886
	case FILE_RENAME_INFORMATION:
5887
	{
5888
		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5889
			ksmbd_debug(SMB,
5890
				    "User does not have write permission\n");
5891 5892 5893
			return -EACCES;
		}

5894 5895 5896 5897 5898 5899 5900
		if (buf_len < sizeof(struct smb2_file_rename_info))
			return -EINVAL;

		return set_rename_info(work, fp,
				       (struct smb2_file_rename_info *)req->Buffer,
				       buf_len);
	}
5901
	case FILE_LINK_INFORMATION:
5902 5903 5904 5905
	{
		if (buf_len < sizeof(struct smb2_file_link_info))
			return -EINVAL;

5906
		return smb2_create_link(work, work->tcon->share_conf,
5907 5908
					(struct smb2_file_link_info *)req->Buffer,
					buf_len, fp->filp,
5909
					work->conn->local_nls);
5910
	}
5911
	case FILE_DISPOSITION_INFORMATION:
5912
	{
5913
		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5914
			ksmbd_debug(SMB,
5915
				    "User does not have write permission\n");
5916 5917 5918
			return -EACCES;
		}

5919 5920 5921 5922 5923 5924
		if (buf_len < sizeof(struct smb2_file_disposition_info))
			return -EINVAL;

		return set_file_disposition_info(fp,
						 (struct smb2_file_disposition_info *)req->Buffer);
	}
5925 5926 5927
	case FILE_FULL_EA_INFORMATION:
	{
		if (!(fp->daccess & FILE_WRITE_EA_LE)) {
N
Namjae Jeon 已提交
5928 5929
			pr_err("Not permitted to write ext  attr: 0x%x\n",
			       fp->daccess);
5930 5931 5932
			return -EACCES;
		}

5933 5934
		if (buf_len < sizeof(struct smb2_ea_info))
			return -EINVAL;
5935

5936 5937 5938
		return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
				   buf_len, &fp->filp->f_path);
	}
5939
	case FILE_POSITION_INFORMATION:
5940 5941 5942
	{
		if (buf_len < sizeof(struct smb2_file_pos_info))
			return -EINVAL;
5943

5944 5945
		return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
	}
5946
	case FILE_MODE_INFORMATION:
5947 5948 5949 5950 5951 5952
	{
		if (buf_len < sizeof(struct smb2_file_mode_info))
			return -EINVAL;

		return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
	}
5953 5954
	}

5955
	pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
5956 5957 5958
	return -EOPNOTSUPP;
}

5959
static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
5960
			     char *buffer, int buf_len)
5961 5962 5963 5964 5965
{
	struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;

	fp->saccess |= FILE_SHARE_DELETE_LE;

5966
	return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978
			buf_len, false);
}

/**
 * smb2_set_info() - handler for smb2 set info command handler
 * @work:	smb work containing set info request buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_set_info(struct ksmbd_work *work)
{
	struct smb2_set_info_req *req;
5979
	struct smb2_set_info_rsp *rsp;
5980 5981 5982 5983 5984 5985 5986
	struct ksmbd_file *fp;
	int rc = 0;
	unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;

	ksmbd_debug(SMB, "Received set info request\n");

	if (work->next_smb2_rcv_hdr_off) {
5987 5988
		req = ksmbd_req_buf_next(work);
		rsp = ksmbd_resp_buf_next(work);
5989 5990
		if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5991
				    work->compound_fid);
5992 5993 5994 5995
			id = work->compound_fid;
			pid = work->compound_pfid;
		}
	} else {
5996 5997
		req = smb2_get_msg(work->request_buf);
		rsp = smb2_get_msg(work->response_buf);
5998 5999
	}

6000
	if (!has_file_id(id)) {
6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014
		id = le64_to_cpu(req->VolatileFileId);
		pid = le64_to_cpu(req->PersistentFileId);
	}

	fp = ksmbd_lookup_fd_slow(work, id, pid);
	if (!fp) {
		ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
		rc = -ENOENT;
		goto err_out;
	}

	switch (req->InfoType) {
	case SMB2_O_INFO_FILE:
		ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6015
		rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6016 6017 6018
		break;
	case SMB2_O_INFO_SECURITY:
		ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6019 6020 6021 6022
		if (ksmbd_override_fsids(work)) {
			rc = -ENOMEM;
			goto err_out;
		}
6023
		rc = smb2_set_info_sec(fp,
6024 6025 6026
				       le32_to_cpu(req->AdditionalInformation),
				       req->Buffer,
				       le32_to_cpu(req->BufferLength));
6027
		ksmbd_revert_fsids(work);
6028 6029 6030 6031 6032 6033 6034 6035 6036
		break;
	default:
		rc = -EOPNOTSUPP;
	}

	if (rc < 0)
		goto err_out;

	rsp->StructureSize = cpu_to_le16(2);
6037
	inc_rfc1001_len(work->response_buf, 2);
6038 6039 6040 6041
	ksmbd_fd_put(work, fp);
	return 0;

err_out:
6042
	if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
	else if (rc == -EINVAL)
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
	else if (rc == -ESHARE)
		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
	else if (rc == -ENOENT)
		rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
	else if (rc == -EBUSY || rc == -ENOTEMPTY)
		rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
	else if (rc == -EAGAIN)
		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6054
	else if (rc == -EBADF || rc == -ESTALE)
6055 6056 6057 6058 6059 6060 6061
		rsp->hdr.Status = STATUS_INVALID_HANDLE;
	else if (rc == -EEXIST)
		rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
	else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
		rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
	smb2_set_err_rsp(work);
	ksmbd_fd_put(work, fp);
6062
	ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074
	return rc;
}

/**
 * smb2_read_pipe() - handler for smb2 read from IPC pipe
 * @work:	smb work containing read IPC pipe command buffer
 *
 * Return:	0 on success, otherwise error
 */
static noinline int smb2_read_pipe(struct ksmbd_work *work)
{
	int nbytes = 0, err;
6075
	u64 id;
6076
	struct ksmbd_rpc_command *rpc_resp;
6077 6078
	struct smb2_read_req *req = smb2_get_msg(work->request_buf);
	struct smb2_read_rsp *rsp = smb2_get_msg(work->response_buf);
6079 6080 6081

	id = le64_to_cpu(req->VolatileFileId);

6082
	inc_rfc1001_len(work->response_buf, 16);
6083 6084 6085 6086 6087 6088 6089 6090
	rpc_resp = ksmbd_rpc_read(work->sess, id);
	if (rpc_resp) {
		if (rpc_resp->flags != KSMBD_RPC_OK) {
			err = -EINVAL;
			goto out;
		}

		work->aux_payload_buf =
6091
			kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
6092 6093 6094 6095 6096 6097
		if (!work->aux_payload_buf) {
			err = -ENOMEM;
			goto out;
		}

		memcpy(work->aux_payload_buf, rpc_resp->payload,
6098
		       rpc_resp->payload_sz);
6099 6100

		nbytes = rpc_resp->payload_sz;
6101
		work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6102
		work->aux_payload_sz = nbytes;
6103
		kvfree(rpc_resp);
6104 6105 6106 6107 6108 6109 6110 6111
	}

	rsp->StructureSize = cpu_to_le16(17);
	rsp->DataOffset = 80;
	rsp->Reserved = 0;
	rsp->DataLength = cpu_to_le32(nbytes);
	rsp->DataRemaining = 0;
	rsp->Reserved2 = 0;
6112
	inc_rfc1001_len(work->response_buf, nbytes);
6113 6114 6115 6116 6117
	return 0;

out:
	rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
	smb2_set_err_rsp(work);
6118
	kvfree(rpc_resp);
6119 6120 6121
	return err;
}

6122 6123 6124 6125 6126
static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
					struct smb2_buffer_desc_v1 *desc,
					__le32 Channel,
					__le16 ChannelInfoOffset,
					__le16 ChannelInfoLength)
6127
{
6128 6129
	unsigned int i, ch_count;

6130
	if (work->conn->dialect == SMB30_PROT_ID &&
6131
	    Channel != SMB2_CHANNEL_RDMA_V1)
6132 6133
		return -EINVAL;

6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145
	ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
	if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
		for (i = 0; i < ch_count; i++) {
			pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
				i,
				le32_to_cpu(desc[i].token),
				le32_to_cpu(desc[i].length));
		}
	}
	if (ch_count != 1) {
		ksmbd_debug(RDMA, "RDMA multiple buffer descriptors %d are not supported yet\n",
			    ch_count);
6146
		return -EINVAL;
6147
	}
6148 6149

	work->need_invalidate_rkey =
6150
		(Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6151
	work->remote_key = le32_to_cpu(desc->token);
6152 6153 6154 6155 6156 6157 6158 6159 6160 6161
	return 0;
}

static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
				      struct smb2_read_req *req, void *data_buf,
				      size_t length)
{
	struct smb2_buffer_desc_v1 *desc =
		(struct smb2_buffer_desc_v1 *)&req->Buffer[0];
	int err;
6162

6163
	err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6164 6165 6166
				    le32_to_cpu(desc->token),
				    le64_to_cpu(desc->offset),
				    le32_to_cpu(desc->length));
6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182
	if (err)
		return err;

	return length;
}

/**
 * smb2_read() - handler for smb2 read from file
 * @work:	smb work containing read command buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_read(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct smb2_read_req *req;
6183
	struct smb2_read_rsp *rsp;
6184
	struct ksmbd_file *fp = NULL;
6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197
	loff_t offset;
	size_t length, mincount;
	ssize_t nbytes = 0, remain_bytes = 0;
	int err = 0;

	WORK_BUFFERS(work, req, rsp);

	if (test_share_config_flag(work->tcon->share_conf,
				   KSMBD_SHARE_FLAG_PIPE)) {
		ksmbd_debug(SMB, "IPC pipe read request\n");
		return smb2_read_pipe(work);
	}

6198 6199
	if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
	    req->Channel == SMB2_CHANNEL_RDMA_V1) {
6200 6201 6202 6203 6204 6205
		unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);

		if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
			err = -EINVAL;
			goto out;
		}
6206 6207
		err = smb2_set_remote_key_for_rdma(work,
						   (struct smb2_buffer_desc_v1 *)
6208
						   ((char *)req + ch_offset),
6209 6210 6211 6212 6213 6214 6215
						   req->Channel,
						   req->ReadChannelInfoOffset,
						   req->ReadChannelInfoLength);
		if (err)
			goto out;
	}

6216 6217
	fp = ksmbd_lookup_fd_slow(work, le64_to_cpu(req->VolatileFileId),
				  le64_to_cpu(req->PersistentFileId));
6218
	if (!fp) {
6219 6220
		err = -ENOENT;
		goto out;
6221 6222 6223
	}

	if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
N
Namjae Jeon 已提交
6224
		pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239
		err = -EACCES;
		goto out;
	}

	offset = le64_to_cpu(req->Offset);
	length = le32_to_cpu(req->Length);
	mincount = le32_to_cpu(req->MinimumCount);

	if (length > conn->vals->max_read_size) {
		ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
			    conn->vals->max_read_size);
		err = -EINVAL;
		goto out;
	}

N
Namjae Jeon 已提交
6240 6241
	ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
		    fp->filp->f_path.dentry, offset, length);
6242

6243
	work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6244
	if (!work->aux_payload_buf) {
6245
		err = -ENOMEM;
6246 6247 6248 6249 6250 6251 6252 6253 6254 6255
		goto out;
	}

	nbytes = ksmbd_vfs_read(work, fp, length, &offset);
	if (nbytes < 0) {
		err = nbytes;
		goto out;
	}

	if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6256
		kvfree(work->aux_payload_buf);
N
Namjae Jeon 已提交
6257
		work->aux_payload_buf = NULL;
6258 6259 6260 6261 6262 6263 6264
		rsp->hdr.Status = STATUS_END_OF_FILE;
		smb2_set_err_rsp(work);
		ksmbd_fd_put(work, fp);
		return 0;
	}

	ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6265
		    nbytes, offset, mincount);
6266 6267

	if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6268
	    req->Channel == SMB2_CHANNEL_RDMA_V1) {
6269 6270
		/* write data to the client using rdma channel */
		remain_bytes = smb2_read_rdma_channel(work, req,
6271 6272
						      work->aux_payload_buf,
						      nbytes);
6273
		kvfree(work->aux_payload_buf);
N
Namjae Jeon 已提交
6274
		work->aux_payload_buf = NULL;
6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288

		nbytes = 0;
		if (remain_bytes < 0) {
			err = (int)remain_bytes;
			goto out;
		}
	}

	rsp->StructureSize = cpu_to_le16(17);
	rsp->DataOffset = 80;
	rsp->Reserved = 0;
	rsp->DataLength = cpu_to_le32(nbytes);
	rsp->DataRemaining = cpu_to_le32(remain_bytes);
	rsp->Reserved2 = 0;
6289 6290
	inc_rfc1001_len(work->response_buf, 16);
	work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6291
	work->aux_payload_sz = nbytes;
6292
	inc_rfc1001_len(work->response_buf, nbytes);
6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326
	ksmbd_fd_put(work, fp);
	return 0;

out:
	if (err) {
		if (err == -EISDIR)
			rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
		else if (err == -EAGAIN)
			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
		else if (err == -ENOENT)
			rsp->hdr.Status = STATUS_FILE_CLOSED;
		else if (err == -EACCES)
			rsp->hdr.Status = STATUS_ACCESS_DENIED;
		else if (err == -ESHARE)
			rsp->hdr.Status = STATUS_SHARING_VIOLATION;
		else if (err == -EINVAL)
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		else
			rsp->hdr.Status = STATUS_INVALID_HANDLE;

		smb2_set_err_rsp(work);
	}
	ksmbd_fd_put(work, fp);
	return err;
}

/**
 * smb2_write_pipe() - handler for smb2 write on IPC pipe
 * @work:	smb work containing write IPC pipe command buffer
 *
 * Return:	0 on success, otherwise error
 */
static noinline int smb2_write_pipe(struct ksmbd_work *work)
{
6327 6328
	struct smb2_write_req *req = smb2_get_msg(work->request_buf);
	struct smb2_write_rsp *rsp = smb2_get_msg(work->response_buf);
6329
	struct ksmbd_rpc_command *rpc_resp;
6330
	u64 id = 0;
6331 6332 6333 6334 6335 6336 6337
	int err = 0, ret = 0;
	char *data_buf;
	size_t length;

	length = le32_to_cpu(req->Length);
	id = le64_to_cpu(req->VolatileFileId);

6338 6339 6340 6341 6342 6343 6344
	if ((u64)le16_to_cpu(req->DataOffset) + length >
	    get_rfc1002_len(work->request_buf)) {
		pr_err("invalid write data offset %u, smb_len %u\n",
		       le16_to_cpu(req->DataOffset),
		       get_rfc1002_len(work->request_buf));
		err = -EINVAL;
		goto out;
6345 6346
	}

6347 6348 6349
	data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
			   le16_to_cpu(req->DataOffset));

6350 6351 6352 6353
	rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
	if (rpc_resp) {
		if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6354
			kvfree(rpc_resp);
6355 6356 6357 6358 6359 6360
			smb2_set_err_rsp(work);
			return -EOPNOTSUPP;
		}
		if (rpc_resp->flags != KSMBD_RPC_OK) {
			rsp->hdr.Status = STATUS_INVALID_HANDLE;
			smb2_set_err_rsp(work);
6361
			kvfree(rpc_resp);
6362 6363
			return ret;
		}
6364
		kvfree(rpc_resp);
6365 6366 6367 6368 6369 6370 6371 6372
	}

	rsp->StructureSize = cpu_to_le16(17);
	rsp->DataOffset = 0;
	rsp->Reserved = 0;
	rsp->DataLength = cpu_to_le32(length);
	rsp->DataRemaining = 0;
	rsp->Reserved2 = 0;
6373
	inc_rfc1001_len(work->response_buf, 16);
6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384
	return 0;
out:
	if (err) {
		rsp->hdr.Status = STATUS_INVALID_HANDLE;
		smb2_set_err_rsp(work);
	}

	return err;
}

static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6385 6386 6387
				       struct smb2_write_req *req,
				       struct ksmbd_file *fp,
				       loff_t offset, size_t length, bool sync)
6388 6389 6390 6391 6392 6393 6394 6395
{
	struct smb2_buffer_desc_v1 *desc;
	char *data_buf;
	int ret;
	ssize_t nbytes;

	desc = (struct smb2_buffer_desc_v1 *)&req->Buffer[0];

6396
	data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6397 6398 6399 6400
	if (!data_buf)
		return -ENOMEM;

	ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6401 6402 6403
				   le32_to_cpu(desc->token),
				   le64_to_cpu(desc->offset),
				   le32_to_cpu(desc->length));
6404
	if (ret < 0) {
6405
		kvfree(data_buf);
6406 6407 6408
		return ret;
	}

6409
	ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6410
	kvfree(data_buf);
6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425
	if (ret < 0)
		return ret;

	return nbytes;
}

/**
 * smb2_write() - handler for smb2 write from file
 * @work:	smb work containing write command buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_write(struct ksmbd_work *work)
{
	struct smb2_write_req *req;
6426
	struct smb2_write_rsp *rsp;
6427
	struct ksmbd_file *fp = NULL;
6428 6429 6430 6431 6432 6433 6434 6435 6436
	loff_t offset;
	size_t length;
	ssize_t nbytes;
	char *data_buf;
	bool writethrough = false;
	int err = 0;

	WORK_BUFFERS(work, req, rsp);

6437
	if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6438 6439 6440 6441
		ksmbd_debug(SMB, "IPC pipe write request\n");
		return smb2_write_pipe(work);
	}

6442 6443
	if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
	    req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6444 6445 6446 6447 6448 6449 6450
		unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);

		if (req->Length != 0 || req->DataOffset != 0 ||
		    ch_offset < offsetof(struct smb2_write_req, Buffer)) {
			err = -EINVAL;
			goto out;
		}
6451 6452
		err = smb2_set_remote_key_for_rdma(work,
						   (struct smb2_buffer_desc_v1 *)
6453
						   ((char *)req + ch_offset),
6454 6455 6456 6457 6458 6459 6460
						   req->Channel,
						   req->WriteChannelInfoOffset,
						   req->WriteChannelInfoLength);
		if (err)
			goto out;
	}

6461 6462 6463 6464 6465 6466
	if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
		ksmbd_debug(SMB, "User does not have write permission\n");
		err = -EACCES;
		goto out;
	}

6467
	fp = ksmbd_lookup_fd_slow(work, le64_to_cpu(req->VolatileFileId),
6468
				  le64_to_cpu(req->PersistentFileId));
6469
	if (!fp) {
6470 6471
		err = -ENOENT;
		goto out;
6472 6473 6474
	}

	if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
N
Namjae Jeon 已提交
6475
		pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493
		err = -EACCES;
		goto out;
	}

	offset = le64_to_cpu(req->Offset);
	length = le32_to_cpu(req->Length);

	if (length > work->conn->vals->max_write_size) {
		ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
			    work->conn->vals->max_write_size);
		err = -EINVAL;
		goto out;
	}

	if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
		writethrough = true;

	if (req->Channel != SMB2_CHANNEL_RDMA_V1 &&
6494
	    req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6495 6496
		if (le16_to_cpu(req->DataOffset) <
		    offsetof(struct smb2_write_req, Buffer)) {
6497 6498
			err = -EINVAL;
			goto out;
6499
		}
6500

6501 6502
		data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
				    le16_to_cpu(req->DataOffset));
6503 6504 6505 6506 6507

		ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
		if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
			writethrough = true;

N
Namjae Jeon 已提交
6508 6509
		ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
			    fp->filp->f_path.dentry, offset, length);
6510 6511 6512 6513 6514 6515 6516 6517 6518
		err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
				      writethrough, &nbytes);
		if (err < 0)
			goto out;
	} else {
		/* read data from the client using rdma channel, and
		 * write the data.
		 */
		nbytes = smb2_write_rdma_channel(work, req, fp, offset,
6519 6520
						 le32_to_cpu(req->RemainingBytes),
						 writethrough);
6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532
		if (nbytes < 0) {
			err = (int)nbytes;
			goto out;
		}
	}

	rsp->StructureSize = cpu_to_le16(17);
	rsp->DataOffset = 0;
	rsp->Reserved = 0;
	rsp->DataLength = cpu_to_le32(nbytes);
	rsp->DataRemaining = 0;
	rsp->Reserved2 = 0;
6533
	inc_rfc1001_len(work->response_buf, 16);
6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566
	ksmbd_fd_put(work, fp);
	return 0;

out:
	if (err == -EAGAIN)
		rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
	else if (err == -ENOSPC || err == -EFBIG)
		rsp->hdr.Status = STATUS_DISK_FULL;
	else if (err == -ENOENT)
		rsp->hdr.Status = STATUS_FILE_CLOSED;
	else if (err == -EACCES)
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
	else if (err == -ESHARE)
		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
	else if (err == -EINVAL)
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
	else
		rsp->hdr.Status = STATUS_INVALID_HANDLE;

	smb2_set_err_rsp(work);
	ksmbd_fd_put(work, fp);
	return err;
}

/**
 * smb2_flush() - handler for smb2 flush file - fsync
 * @work:	smb work containing flush command buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_flush(struct ksmbd_work *work)
{
	struct smb2_flush_req *req;
6567
	struct smb2_flush_rsp *rsp;
6568 6569 6570 6571 6572
	int err;

	WORK_BUFFERS(work, req, rsp);

	ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n",
6573
		    le64_to_cpu(req->VolatileFileId));
6574 6575 6576 6577 6578 6579 6580 6581 6582

	err = ksmbd_vfs_fsync(work,
			      le64_to_cpu(req->VolatileFileId),
			      le64_to_cpu(req->PersistentFileId));
	if (err)
		goto out;

	rsp->StructureSize = cpu_to_le16(4);
	rsp->Reserved = 0;
6583
	inc_rfc1001_len(work->response_buf, 4);
6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603
	return 0;

out:
	if (err) {
		rsp->hdr.Status = STATUS_INVALID_HANDLE;
		smb2_set_err_rsp(work);
	}

	return err;
}

/**
 * smb2_cancel() - handler for smb2 cancel command
 * @work:	smb work containing cancel command buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_cancel(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
6604
	struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6605 6606 6607 6608 6609 6610
	struct smb2_hdr *chdr;
	struct ksmbd_work *cancel_work = NULL;
	int canceled = 0;
	struct list_head *command_list;

	ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6611
		    hdr->MessageId, hdr->Flags);
6612 6613 6614 6615 6616

	if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
		command_list = &conn->async_requests;

		spin_lock(&conn->request_lock);
6617 6618
		list_for_each_entry(cancel_work, command_list,
				    async_request_entry) {
6619
			chdr = smb2_get_msg(cancel_work->request_buf);
6620 6621

			if (cancel_work->async_id !=
6622
			    le64_to_cpu(hdr->Id.AsyncId))
6623 6624 6625
				continue;

			ksmbd_debug(SMB,
6626 6627 6628
				    "smb2 with AsyncId %llu cancelled command = 0x%x\n",
				    le64_to_cpu(hdr->Id.AsyncId),
				    le16_to_cpu(chdr->Command));
6629 6630 6631 6632 6633 6634 6635 6636
			canceled = 1;
			break;
		}
		spin_unlock(&conn->request_lock);
	} else {
		command_list = &conn->requests;

		spin_lock(&conn->request_lock);
6637
		list_for_each_entry(cancel_work, command_list, request_entry) {
6638
			chdr = smb2_get_msg(cancel_work->request_buf);
6639 6640

			if (chdr->MessageId != hdr->MessageId ||
6641
			    cancel_work == work)
6642 6643 6644
				continue;

			ksmbd_debug(SMB,
6645 6646 6647
				    "smb2 with mid %llu cancelled command = 0x%x\n",
				    le64_to_cpu(hdr->MessageId),
				    le16_to_cpu(chdr->Command));
6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703
			canceled = 1;
			break;
		}
		spin_unlock(&conn->request_lock);
	}

	if (canceled) {
		cancel_work->state = KSMBD_WORK_CANCELLED;
		if (cancel_work->cancel_fn)
			cancel_work->cancel_fn(cancel_work->cancel_argv);
	}

	/* For SMB2_CANCEL command itself send no response*/
	work->send_no_response = 1;
	return 0;
}

struct file_lock *smb_flock_init(struct file *f)
{
	struct file_lock *fl;

	fl = locks_alloc_lock();
	if (!fl)
		goto out;

	locks_init_lock(fl);

	fl->fl_owner = f;
	fl->fl_pid = current->tgid;
	fl->fl_file = f;
	fl->fl_flags = FL_POSIX;
	fl->fl_ops = NULL;
	fl->fl_lmops = NULL;

out:
	return fl;
}

static int smb2_set_flock_flags(struct file_lock *flock, int flags)
{
	int cmd = -EINVAL;

	/* Checking for wrong flag combination during lock request*/
	switch (flags) {
	case SMB2_LOCKFLAG_SHARED:
		ksmbd_debug(SMB, "received shared request\n");
		cmd = F_SETLKW;
		flock->fl_type = F_RDLCK;
		flock->fl_flags |= FL_SLEEP;
		break;
	case SMB2_LOCKFLAG_EXCLUSIVE:
		ksmbd_debug(SMB, "received exclusive request\n");
		cmd = F_SETLKW;
		flock->fl_type = F_WRLCK;
		flock->fl_flags |= FL_SLEEP;
		break;
6704
	case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6705
		ksmbd_debug(SMB,
6706
			    "received shared & fail immediately request\n");
6707 6708 6709
		cmd = F_SETLK;
		flock->fl_type = F_RDLCK;
		break;
6710
	case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6711
		ksmbd_debug(SMB,
6712
			    "received exclusive & fail immediately request\n");
6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726
		cmd = F_SETLK;
		flock->fl_type = F_WRLCK;
		break;
	case SMB2_LOCKFLAG_UNLOCK:
		ksmbd_debug(SMB, "received unlock request\n");
		flock->fl_type = F_UNLCK;
		cmd = 0;
		break;
	}

	return cmd;
}

static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6727 6728
					 unsigned int cmd, int flags,
					 struct list_head *lock_list)
6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742
{
	struct ksmbd_lock *lock;

	lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
	if (!lock)
		return NULL;

	lock->cmd = cmd;
	lock->fl = flock;
	lock->start = flock->fl_start;
	lock->end = flock->fl_end;
	lock->flags = flags;
	if (lock->start == lock->end)
		lock->zero_len = 1;
6743 6744
	INIT_LIST_HEAD(&lock->clist);
	INIT_LIST_HEAD(&lock->flist);
6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772
	INIT_LIST_HEAD(&lock->llist);
	list_add_tail(&lock->llist, lock_list);

	return lock;
}

static void smb2_remove_blocked_lock(void **argv)
{
	struct file_lock *flock = (struct file_lock *)argv[0];

	ksmbd_vfs_posix_lock_unblock(flock);
	wake_up(&flock->fl_wait);
}

static inline bool lock_defer_pending(struct file_lock *fl)
{
	/* check pending lock waiters */
	return waitqueue_active(&fl->fl_wait);
}

/**
 * smb2_lock() - handler for smb2 file lock command
 * @work:	smb work containing lock command buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_lock(struct ksmbd_work *work)
{
6773 6774
	struct smb2_lock_req *req = smb2_get_msg(work->request_buf);
	struct smb2_lock_rsp *rsp = smb2_get_msg(work->response_buf);
6775 6776 6777 6778 6779 6780 6781
	struct smb2_lock_element *lock_ele;
	struct ksmbd_file *fp = NULL;
	struct file_lock *flock = NULL;
	struct file *filp = NULL;
	int lock_count;
	int flags = 0;
	int cmd = 0;
6782
	int err = -EIO, i, rc = 0;
6783
	u64 lock_start, lock_length;
6784 6785
	struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
	struct ksmbd_conn *conn;
6786 6787 6788 6789 6790 6791 6792
	int nolock = 0;
	LIST_HEAD(lock_list);
	LIST_HEAD(rollback_list);
	int prior_lock = 0;

	ksmbd_debug(SMB, "Received lock request\n");
	fp = ksmbd_lookup_fd_slow(work,
6793 6794
				  le64_to_cpu(req->VolatileFileId),
				  le64_to_cpu(req->PersistentFileId));
6795 6796
	if (!fp) {
		ksmbd_debug(SMB, "Invalid file id for lock : %llu\n",
6797
			    le64_to_cpu(req->VolatileFileId));
6798
		err = -ENOENT;
6799 6800 6801 6802 6803 6804 6805 6806
		goto out2;
	}

	filp = fp->filp;
	lock_count = le16_to_cpu(req->LockCount);
	lock_ele = req->locks;

	ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6807
	if (!lock_count) {
6808
		err = -EINVAL;
6809 6810 6811 6812 6813 6814 6815
		goto out2;
	}

	for (i = 0; i < lock_count; i++) {
		flags = le32_to_cpu(lock_ele[i].Flags);

		flock = smb_flock_init(filp);
6816
		if (!flock)
6817 6818 6819 6820
			goto out;

		cmd = smb2_set_flock_flags(flock, flags);

6821 6822 6823
		lock_start = le64_to_cpu(lock_ele[i].Offset);
		lock_length = le64_to_cpu(lock_ele[i].Length);
		if (lock_start > U64_MAX - lock_length) {
N
Namjae Jeon 已提交
6824
			pr_err("Invalid lock range requested\n");
6825 6826 6827 6828
			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
			goto out;
		}

6829 6830 6831 6832 6833
		if (lock_start > OFFSET_MAX)
			flock->fl_start = OFFSET_MAX;
		else
			flock->fl_start = lock_start;

6834
		lock_length = le64_to_cpu(lock_ele[i].Length);
6835 6836
		if (lock_length > OFFSET_MAX - flock->fl_start)
			lock_length = OFFSET_MAX - flock->fl_start;
6837 6838 6839 6840 6841

		flock->fl_end = flock->fl_start + lock_length;

		if (flock->fl_end < flock->fl_start) {
			ksmbd_debug(SMB,
6842 6843
				    "the end offset(%llx) is smaller than the start offset(%llx)\n",
				    flock->fl_end, flock->fl_start);
6844 6845 6846 6847 6848 6849 6850
			rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
			goto out;
		}

		/* Check conflict locks in one request */
		list_for_each_entry(cmp_lock, &lock_list, llist) {
			if (cmp_lock->fl->fl_start <= flock->fl_start &&
6851
			    cmp_lock->fl->fl_end >= flock->fl_end) {
6852
				if (cmp_lock->fl->fl_type != F_UNLCK &&
6853
				    flock->fl_type != F_UNLCK) {
N
Namjae Jeon 已提交
6854
					pr_err("conflict two locks in one request\n");
6855
					err = -EINVAL;
6856 6857 6858 6859 6860 6861 6862
					goto out;
				}
			}
		}

		smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
		if (!smb_lock) {
6863
			err = -EINVAL;
6864 6865 6866 6867 6868 6869
			goto out;
		}
	}

	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
		if (smb_lock->cmd < 0) {
6870
			err = -EINVAL;
6871 6872 6873 6874
			goto out;
		}

		if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6875
			err = -EINVAL;
6876 6877 6878
			goto out;
		}

6879 6880 6881 6882
		if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
		     smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
		    (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
		     !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6883
			err = -EINVAL;
6884 6885 6886 6887 6888 6889
			goto out;
		}

		prior_lock = smb_lock->flags;

		if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6890
		    !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6891
			goto no_check_cl;
6892 6893

		nolock = 1;
6894 6895 6896 6897 6898 6899 6900 6901
		/* check locks in connection list */
		read_lock(&conn_list_lock);
		list_for_each_entry(conn, &conn_list, conns_list) {
			spin_lock(&conn->llist_lock);
			list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
				if (file_inode(cmp_lock->fl->fl_file) !=
				    file_inode(smb_lock->fl->fl_file))
					continue;
6902

6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918
				if (smb_lock->fl->fl_type == F_UNLCK) {
					if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
					    cmp_lock->start == smb_lock->start &&
					    cmp_lock->end == smb_lock->end &&
					    !lock_defer_pending(cmp_lock->fl)) {
						nolock = 0;
						list_del(&cmp_lock->flist);
						list_del(&cmp_lock->clist);
						spin_unlock(&conn->llist_lock);
						read_unlock(&conn_list_lock);

						locks_free_lock(cmp_lock->fl);
						kfree(cmp_lock);
						goto out_check_cl;
					}
					continue;
6919 6920
				}

6921 6922 6923 6924 6925 6926 6927
				if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
					if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
						continue;
				} else {
					if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
						continue;
				}
6928

6929 6930 6931 6932 6933 6934 6935
				/* check zero byte lock range */
				if (cmp_lock->zero_len && !smb_lock->zero_len &&
				    cmp_lock->start > smb_lock->start &&
				    cmp_lock->start < smb_lock->end) {
					spin_unlock(&conn->llist_lock);
					read_unlock(&conn_list_lock);
					pr_err("previous lock conflict with zero byte lock range\n");
6936
					goto out;
6937
				}
6938

6939 6940 6941 6942 6943 6944
				if (smb_lock->zero_len && !cmp_lock->zero_len &&
				    smb_lock->start > cmp_lock->start &&
				    smb_lock->start < cmp_lock->end) {
					spin_unlock(&conn->llist_lock);
					read_unlock(&conn_list_lock);
					pr_err("current lock conflict with zero byte lock range\n");
6945
					goto out;
6946
				}
6947

6948 6949 6950 6951 6952 6953 6954 6955 6956 6957
				if (((cmp_lock->start <= smb_lock->start &&
				      cmp_lock->end > smb_lock->start) ||
				     (cmp_lock->start < smb_lock->end &&
				      cmp_lock->end >= smb_lock->end)) &&
				    !cmp_lock->zero_len && !smb_lock->zero_len) {
					spin_unlock(&conn->llist_lock);
					read_unlock(&conn_list_lock);
					pr_err("Not allow lock operation on exclusive lock range\n");
					goto out;
				}
6958
			}
6959
			spin_unlock(&conn->llist_lock);
6960
		}
6961 6962
		read_unlock(&conn_list_lock);
out_check_cl:
6963
		if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
N
Namjae Jeon 已提交
6964
			pr_err("Try to unlock nolocked range\n");
6965 6966 6967 6968
			rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
			goto out;
		}

6969
no_check_cl:
6970 6971 6972 6973 6974 6975 6976 6977
		if (smb_lock->zero_len) {
			err = 0;
			goto skip;
		}

		flock = smb_lock->fl;
		list_del(&smb_lock->llist);
retry:
6978
		rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
6979 6980
skip:
		if (flags & SMB2_LOCKFLAG_UNLOCK) {
6981
			if (!rc) {
6982
				ksmbd_debug(SMB, "File unlocked\n");
6983
			} else if (rc == -ENOENT) {
6984 6985 6986 6987 6988 6989
				rsp->hdr.Status = STATUS_NOT_LOCKED;
				goto out;
			}
			locks_free_lock(flock);
			kfree(smb_lock);
		} else {
6990
			if (rc == FILE_LOCK_DEFERRED) {
6991 6992 6993
				void **argv;

				ksmbd_debug(SMB,
6994
					    "would have to wait for getting lock\n");
6995 6996 6997 6998
				spin_lock(&work->conn->llist_lock);
				list_add_tail(&smb_lock->clist,
					      &work->conn->lock_list);
				spin_unlock(&work->conn->llist_lock);
6999 7000 7001 7002 7003 7004 7005 7006 7007
				list_add(&smb_lock->llist, &rollback_list);

				argv = kmalloc(sizeof(void *), GFP_KERNEL);
				if (!argv) {
					err = -ENOMEM;
					goto out;
				}
				argv[0] = flock;

7008 7009 7010 7011 7012
				rc = setup_async_work(work,
						      smb2_remove_blocked_lock,
						      argv);
				if (rc) {
					err = -ENOMEM;
7013 7014 7015 7016 7017 7018 7019 7020
					goto out;
				}
				spin_lock(&fp->f_lock);
				list_add(&work->fp_entry, &fp->blocked_works);
				spin_unlock(&fp->f_lock);

				smb2_send_interim_resp(work, STATUS_PENDING);

7021
				ksmbd_vfs_posix_lock_wait(flock);
7022

7023
				if (work->state != KSMBD_WORK_ACTIVE) {
7024
					list_del(&smb_lock->llist);
7025 7026 7027
					spin_lock(&work->conn->llist_lock);
					list_del(&smb_lock->clist);
					spin_unlock(&work->conn->llist_lock);
7028 7029
					locks_free_lock(flock);

7030
					if (work->state == KSMBD_WORK_CANCELLED) {
7031 7032 7033 7034 7035 7036 7037
						spin_lock(&fp->f_lock);
						list_del(&work->fp_entry);
						spin_unlock(&fp->f_lock);
						rsp->hdr.Status =
							STATUS_CANCELLED;
						kfree(smb_lock);
						smb2_send_interim_resp(work,
7038
								       STATUS_CANCELLED);
7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050
						work->send_no_response = 1;
						goto out;
					}
					init_smb2_rsp_hdr(work);
					smb2_set_err_rsp(work);
					rsp->hdr.Status =
						STATUS_RANGE_NOT_LOCKED;
					kfree(smb_lock);
					goto out2;
				}

				list_del(&smb_lock->llist);
7051 7052 7053 7054
				spin_lock(&work->conn->llist_lock);
				list_del(&smb_lock->clist);
				spin_unlock(&work->conn->llist_lock);

7055 7056 7057 7058
				spin_lock(&fp->f_lock);
				list_del(&work->fp_entry);
				spin_unlock(&fp->f_lock);
				goto retry;
7059
			} else if (!rc) {
7060 7061 7062 7063 7064 7065
				spin_lock(&work->conn->llist_lock);
				list_add_tail(&smb_lock->clist,
					      &work->conn->lock_list);
				list_add_tail(&smb_lock->flist,
					      &fp->lock_list);
				spin_unlock(&work->conn->llist_lock);
7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080
				list_add(&smb_lock->llist, &rollback_list);
				ksmbd_debug(SMB, "successful in taking lock\n");
			} else {
				goto out;
			}
		}
	}

	if (atomic_read(&fp->f_ci->op_count) > 1)
		smb_break_all_oplock(work, fp);

	rsp->StructureSize = cpu_to_le16(4);
	ksmbd_debug(SMB, "successful in taking lock\n");
	rsp->hdr.Status = STATUS_SUCCESS;
	rsp->Reserved = 0;
7081
	inc_rfc1001_len(work->response_buf, 4);
7082
	ksmbd_fd_put(work, fp);
7083
	return 0;
7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099

out:
	list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
		locks_free_lock(smb_lock->fl);
		list_del(&smb_lock->llist);
		kfree(smb_lock);
	}

	list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
		struct file_lock *rlock = NULL;

		rlock = smb_flock_init(filp);
		rlock->fl_type = F_UNLCK;
		rlock->fl_start = smb_lock->start;
		rlock->fl_end = smb_lock->end;

7100 7101 7102
		rc = vfs_lock_file(filp, 0, rlock, NULL);
		if (rc)
			pr_err("rollback unlock fail : %d\n", rc);
7103

7104
		list_del(&smb_lock->llist);
7105 7106 7107 7108 7109 7110
		spin_lock(&work->conn->llist_lock);
		if (!list_empty(&smb_lock->flist))
			list_del(&smb_lock->flist);
		list_del(&smb_lock->clist);
		spin_unlock(&work->conn->llist_lock);

7111 7112 7113 7114 7115
		locks_free_lock(smb_lock->fl);
		locks_free_lock(rlock);
		kfree(smb_lock);
	}
out2:
7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128
	ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);

	if (!rsp->hdr.Status) {
		if (err == -EINVAL)
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		else if (err == -ENOMEM)
			rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
		else if (err == -ENOENT)
			rsp->hdr.Status = STATUS_FILE_CLOSED;
		else
			rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
	}

7129 7130
	smb2_set_err_rsp(work);
	ksmbd_fd_put(work, fp);
7131
	return err;
7132 7133
}

N
Namjae Jeon 已提交
7134 7135 7136 7137 7138 7139
static int 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,
7140
			   struct smb2_ioctl_rsp *rsp)
7141 7142 7143 7144 7145 7146 7147
{
	struct copychunk_ioctl_rsp *ci_rsp;
	struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
	struct srv_copychunk *chunks;
	unsigned int i, chunk_count, chunk_count_written = 0;
	unsigned int chunk_size_written = 0;
	loff_t total_size_written = 0;
N
Namjae Jeon 已提交
7148
	int ret = 0;
7149 7150 7151

	ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];

N
Namjae Jeon 已提交
7152 7153
	rsp->VolatileFileId = cpu_to_le64(volatile_id);
	rsp->PersistentFileId = cpu_to_le64(persistent_id);
7154 7155 7156 7157 7158 7159
	ci_rsp->ChunksWritten =
		cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
	ci_rsp->ChunkBytesWritten =
		cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
	ci_rsp->TotalBytesWritten =
		cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7160 7161 7162

	chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
	chunk_count = le32_to_cpu(ci_req->ChunkCount);
N
Namjae Jeon 已提交
7163 7164
	if (chunk_count == 0)
		goto out;
7165 7166 7167 7168
	total_size_written = 0;

	/* verify the SRV_COPYCHUNK_COPY packet */
	if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
N
Namjae Jeon 已提交
7169
	    input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7170
	     chunk_count * sizeof(struct srv_copychunk)) {
7171 7172 7173 7174 7175 7176
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		return -EINVAL;
	}

	for (i = 0; i < chunk_count; i++) {
		if (le32_to_cpu(chunks[i].Length) == 0 ||
7177
		    le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7178 7179 7180
			break;
		total_size_written += le32_to_cpu(chunks[i].Length);
	}
7181 7182 7183

	if (i < chunk_count ||
	    total_size_written > ksmbd_server_side_copy_max_total_size()) {
7184 7185 7186 7187 7188
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		return -EINVAL;
	}

	src_fp = ksmbd_lookup_foreign_fd(work,
7189
					 le64_to_cpu(ci_req->ResumeKey[0]));
N
Namjae Jeon 已提交
7190
	dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7191
	ret = -EINVAL;
7192 7193
	if (!src_fp ||
	    src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7194 7195 7196
		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
		goto out;
	}
7197

7198 7199 7200 7201 7202 7203 7204 7205 7206
	if (!dst_fp) {
		rsp->hdr.Status = STATUS_FILE_CLOSED;
		goto out;
	}

	/*
	 * FILE_READ_DATA should only be included in
	 * the FSCTL_COPYCHUNK case
	 */
7207 7208
	if (cnt_code == FSCTL_COPYCHUNK &&
	    !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7209 7210 7211 7212 7213
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
		goto out;
	}

	ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7214 7215 7216 7217
					 chunks, chunk_count,
					 &chunk_count_written,
					 &chunk_size_written,
					 &total_size_written);
7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264
	if (ret < 0) {
		if (ret == -EACCES)
			rsp->hdr.Status = STATUS_ACCESS_DENIED;
		if (ret == -EAGAIN)
			rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
		else if (ret == -EBADF)
			rsp->hdr.Status = STATUS_INVALID_HANDLE;
		else if (ret == -EFBIG || ret == -ENOSPC)
			rsp->hdr.Status = STATUS_DISK_FULL;
		else if (ret == -EINVAL)
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		else if (ret == -EISDIR)
			rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
		else if (ret == -E2BIG)
			rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
		else
			rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
	}

	ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
	ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
	ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
out:
	ksmbd_fd_put(work, src_fp);
	ksmbd_fd_put(work, dst_fp);
	return ret;
}

static __be32 idev_ipv4_address(struct in_device *idev)
{
	__be32 addr = 0;

	struct in_ifaddr *ifa;

	rcu_read_lock();
	in_dev_for_each_ifa_rcu(ifa, idev) {
		if (ifa->ifa_flags & IFA_F_SECONDARY)
			continue;

		addr = ifa->ifa_address;
		break;
	}
	rcu_read_unlock();
	return addr;
}

static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
N
Namjae Jeon 已提交
7265 7266
					struct smb2_ioctl_rsp *rsp,
					unsigned int out_buf_len)
7267 7268 7269 7270 7271 7272 7273 7274 7275 7276
{
	struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
	int nbytes = 0;
	struct net_device *netdev;
	struct sockaddr_storage_rsp *sockaddr_storage;
	unsigned int flags;
	unsigned long long speed;

	rtnl_lock();
	for_each_netdev(&init_net, netdev) {
7277
		bool ipv4_set = false;
N
Namjae Jeon 已提交
7278

7279 7280 7281 7282 7283 7284
		if (netdev->type == ARPHRD_LOOPBACK)
			continue;

		flags = dev_get_flags(netdev);
		if (!(flags & IFF_RUNNING))
			continue;
7285 7286 7287 7288 7289 7290
ipv6_retry:
		if (out_buf_len <
		    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
			rtnl_unlock();
			return -ENOSPC;
		}
7291 7292 7293 7294 7295

		nii_rsp = (struct network_interface_info_ioctl_rsp *)
				&rsp->Buffer[nbytes];
		nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);

7296
		nii_rsp->Capability = 0;
7297 7298
		if (netdev->real_num_tx_queues > 1)
			nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7299 7300
		if (ksmbd_rdma_capable_netdev(netdev))
			nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7301 7302 7303 7304 7305 7306 7307 7308 7309 7310

		nii_rsp->Next = cpu_to_le32(152);
		nii_rsp->Reserved = 0;

		if (netdev->ethtool_ops->get_link_ksettings) {
			struct ethtool_link_ksettings cmd;

			netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
			speed = cmd.base.speed;
		} else {
7311 7312
			ksmbd_debug(SMB, "%s %s\n", netdev->name,
				    "speed is unknown, defaulting to 1Gb/sec");
7313 7314 7315 7316 7317 7318 7319 7320 7321 7322
			speed = SPEED_1000;
		}

		speed *= 1000000;
		nii_rsp->LinkSpeed = cpu_to_le64(speed);

		sockaddr_storage = (struct sockaddr_storage_rsp *)
					nii_rsp->SockAddr_Storage;
		memset(sockaddr_storage, 0, 128);

7323
		if (!ipv4_set) {
7324 7325 7326 7327 7328 7329 7330 7331 7332 7333
			struct in_device *idev;

			sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
			sockaddr_storage->addr4.Port = 0;

			idev = __in_dev_get_rtnl(netdev);
			if (!idev)
				continue;
			sockaddr_storage->addr4.IPv4address =
						idev_ipv4_address(idev);
7334 7335 7336
			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
			ipv4_set = true;
			goto ipv6_retry;
7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357
		} else {
			struct inet6_dev *idev6;
			struct inet6_ifaddr *ifa;
			__u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;

			sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
			sockaddr_storage->addr6.Port = 0;
			sockaddr_storage->addr6.FlowInfo = 0;

			idev6 = __in6_dev_get(netdev);
			if (!idev6)
				continue;

			list_for_each_entry(ifa, &idev6->addr_list, if_list) {
				if (ifa->flags & (IFA_F_TENTATIVE |
							IFA_F_DEPRECATED))
					continue;
				memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
				break;
			}
			sockaddr_storage->addr6.ScopeId = 0;
7358
			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372
		}
	}
	rtnl_unlock();

	/* zero if this is last one */
	if (nii_rsp)
		nii_rsp->Next = 0;

	rsp->PersistentFileId = cpu_to_le64(SMB2_NO_FID);
	rsp->VolatileFileId = cpu_to_le64(SMB2_NO_FID);
	return nbytes;
}

static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7373
					 struct validate_negotiate_info_req *neg_req,
N
Namjae Jeon 已提交
7374 7375
					 struct validate_negotiate_info_rsp *neg_rsp,
					 unsigned int in_buf_len)
7376 7377 7378 7379
{
	int ret = 0;
	int dialect;

7380
	if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
N
Namjae Jeon 已提交
7381 7382 7383
			le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
		return -EINVAL;

7384
	dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7385
					     neg_req->DialectCount);
7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413
	if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
		ret = -EINVAL;
		goto err_out;
	}

	if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
		ret = -EINVAL;
		goto err_out;
	}

	if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
		ret = -EINVAL;
		goto err_out;
	}

	if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
		ret = -EINVAL;
		goto err_out;
	}

	neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
	memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
	neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
	neg_rsp->Dialect = cpu_to_le16(conn->dialect);
err_out:
	return ret;
}

7414
static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7415 7416
					struct file_allocated_range_buffer *qar_req,
					struct file_allocated_range_buffer *qar_rsp,
N
Namjae Jeon 已提交
7417
					unsigned int in_count, unsigned int *out_count)
7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434
{
	struct ksmbd_file *fp;
	loff_t start, length;
	int ret = 0;

	*out_count = 0;
	if (in_count == 0)
		return -EINVAL;

	fp = ksmbd_lookup_fd_fast(work, id);
	if (!fp)
		return -ENOENT;

	start = le64_to_cpu(qar_req->file_offset);
	length = le64_to_cpu(qar_req->length);

	ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7435
				   qar_rsp, in_count, out_count);
7436 7437 7438 7439 7440 7441 7442
	if (ret && ret != -E2BIG)
		*out_count = 0;

	ksmbd_fd_put(work, fp);
	return ret;
}

7443
static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
N
Namjae Jeon 已提交
7444 7445
				 unsigned int out_buf_len,
				 struct smb2_ioctl_req *req,
7446
				 struct smb2_ioctl_rsp *rsp)
7447 7448 7449 7450 7451
{
	struct ksmbd_rpc_command *rpc_resp;
	char *data_buf = (char *)&req->Buffer[0];
	int nbytes = 0;

7452
	rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7453
				   le32_to_cpu(req->InputCount));
7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483
	if (rpc_resp) {
		if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
			/*
			 * set STATUS_SOME_NOT_MAPPED response
			 * for unknown domain sid.
			 */
			rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
		} else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
			goto out;
		} else if (rpc_resp->flags != KSMBD_RPC_OK) {
			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
			goto out;
		}

		nbytes = rpc_resp->payload_sz;
		if (rpc_resp->payload_sz > out_buf_len) {
			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
			nbytes = out_buf_len;
		}

		if (!rpc_resp->payload_sz) {
			rsp->hdr.Status =
				STATUS_UNEXPECTED_IO_ERROR;
			goto out;
		}

		memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
	}
out:
7484
	kvfree(rpc_resp);
7485 7486 7487
	return nbytes;
}

7488
static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7489
				   struct file_sparse *sparse)
7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505
{
	struct ksmbd_file *fp;
	int ret = 0;
	__le32 old_fattr;

	fp = ksmbd_lookup_fd_fast(work, id);
	if (!fp)
		return -ENOENT;

	old_fattr = fp->f_ci->m_fattr;
	if (sparse->SetSparse)
		fp->f_ci->m_fattr |= ATTR_SPARSE_FILE_LE;
	else
		fp->f_ci->m_fattr &= ~ATTR_SPARSE_FILE_LE;

	if (fp->f_ci->m_fattr != old_fattr &&
7506 7507
	    test_share_config_flag(work->tcon->share_conf,
				   KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525
		struct xattr_dos_attrib da;

		ret = ksmbd_vfs_get_dos_attrib_xattr(fp->filp->f_path.dentry, &da);
		if (ret <= 0)
			goto out;

		da.attr = le32_to_cpu(fp->f_ci->m_fattr);
		ret = ksmbd_vfs_set_dos_attrib_xattr(fp->filp->f_path.dentry, &da);
		if (ret)
			fp->f_ci->m_fattr = old_fattr;
	}

out:
	ksmbd_fd_put(work, fp);
	return ret;
}

static int fsctl_request_resume_key(struct ksmbd_work *work,
7526 7527
				    struct smb2_ioctl_req *req,
				    struct resume_key_ioctl_rsp *key_rsp)
7528 7529 7530 7531
{
	struct ksmbd_file *fp;

	fp = ksmbd_lookup_fd_slow(work,
7532 7533
				  le64_to_cpu(req->VolatileFileId),
				  le64_to_cpu(req->PersistentFileId));
7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553
	if (!fp)
		return -ENOENT;

	memset(key_rsp, 0, sizeof(*key_rsp));
	key_rsp->ResumeKey[0] = req->VolatileFileId;
	key_rsp->ResumeKey[1] = req->PersistentFileId;
	ksmbd_fd_put(work, fp);

	return 0;
}

/**
 * smb2_ioctl() - handler for smb2 ioctl command
 * @work:	smb work containing ioctl command buffer
 *
 * Return:	0 on success, otherwise error
 */
int smb2_ioctl(struct ksmbd_work *work)
{
	struct smb2_ioctl_req *req;
7554
	struct smb2_ioctl_rsp *rsp;
N
Namjae Jeon 已提交
7555
	unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7556
	u64 id = KSMBD_NO_FID;
7557 7558 7559 7560
	struct ksmbd_conn *conn = work->conn;
	int ret = 0;

	if (work->next_smb2_rcv_hdr_off) {
7561 7562
		req = ksmbd_req_buf_next(work);
		rsp = ksmbd_resp_buf_next(work);
7563 7564
		if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
			ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7565
				    work->compound_fid);
7566 7567 7568
			id = work->compound_fid;
		}
	} else {
7569 7570
		req = smb2_get_msg(work->request_buf);
		rsp = smb2_get_msg(work->response_buf);
7571 7572
	}

7573
	if (!has_file_id(id))
7574 7575 7576 7577 7578 7579 7580 7581
		id = le64_to_cpu(req->VolatileFileId);

	if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
		goto out;
	}

	cnt_code = le32_to_cpu(req->CntCode);
7582 7583 7584 7585 7586 7587 7588
	ret = smb2_calc_max_out_buf_len(work, 48,
					le32_to_cpu(req->MaxOutputResponse));
	if (ret < 0) {
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		goto out;
	}
	out_buf_len = (unsigned int)ret;
N
Namjae Jeon 已提交
7589
	in_buf_len = le32_to_cpu(req->InputCount);
7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616

	switch (cnt_code) {
	case FSCTL_DFS_GET_REFERRALS:
	case FSCTL_DFS_GET_REFERRALS_EX:
		/* Not support DFS yet */
		rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
		goto out;
	case FSCTL_CREATE_OR_GET_OBJECT_ID:
	{
		struct file_object_buf_type1_ioctl_rsp *obj_buf;

		nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
		obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
			&rsp->Buffer[0];

		/*
		 * TODO: This is dummy implementation to pass smbtorture
		 * Need to check correct response later
		 */
		memset(obj_buf->ObjectId, 0x0, 16);
		memset(obj_buf->BirthVolumeId, 0x0, 16);
		memset(obj_buf->BirthObjectId, 0x0, 16);
		memset(obj_buf->DomainId, 0x0, 16);

		break;
	}
	case FSCTL_PIPE_TRANSCEIVE:
N
Namjae Jeon 已提交
7617
		out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7618 7619 7620 7621 7622 7623 7624 7625
		nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
		break;
	case FSCTL_VALIDATE_NEGOTIATE_INFO:
		if (conn->dialect < SMB30_PROT_ID) {
			ret = -EOPNOTSUPP;
			goto out;
		}

7626 7627 7628 7629 7630
		if (in_buf_len < offsetof(struct validate_negotiate_info_req,
					  Dialects)) {
			ret = -EINVAL;
			goto out;
		}
N
Namjae Jeon 已提交
7631

7632 7633 7634 7635
		if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
			ret = -EINVAL;
			goto out;
		}
N
Namjae Jeon 已提交
7636

7637 7638
		ret = fsctl_validate_negotiate_info(conn,
			(struct validate_negotiate_info_req *)&req->Buffer[0],
N
Namjae Jeon 已提交
7639 7640
			(struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
			in_buf_len);
7641 7642 7643 7644 7645 7646 7647 7648
		if (ret < 0)
			goto out;

		nbytes = sizeof(struct validate_negotiate_info_rsp);
		rsp->PersistentFileId = cpu_to_le64(SMB2_NO_FID);
		rsp->VolatileFileId = cpu_to_le64(SMB2_NO_FID);
		break;
	case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
N
Namjae Jeon 已提交
7649 7650
		ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
		if (ret < 0)
7651
			goto out;
N
Namjae Jeon 已提交
7652
		nbytes = ret;
7653 7654 7655 7656 7657 7658 7659 7660
		break;
	case FSCTL_REQUEST_RESUME_KEY:
		if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
			ret = -EINVAL;
			goto out;
		}

		ret = fsctl_request_resume_key(work, req,
7661
					       (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7662 7663 7664 7665 7666 7667 7668 7669
		if (ret < 0)
			goto out;
		rsp->PersistentFileId = req->PersistentFileId;
		rsp->VolatileFileId = req->VolatileFileId;
		nbytes = sizeof(struct resume_key_ioctl_rsp);
		break;
	case FSCTL_COPYCHUNK:
	case FSCTL_COPYCHUNK_WRITE:
7670
		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7671
			ksmbd_debug(SMB,
7672
				    "User does not have write permission\n");
7673 7674 7675 7676
			ret = -EACCES;
			goto out;
		}

N
Namjae Jeon 已提交
7677 7678 7679 7680 7681
		if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
			ret = -EINVAL;
			goto out;
		}

7682 7683 7684 7685 7686 7687
		if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
			ret = -EINVAL;
			goto out;
		}

		nbytes = sizeof(struct copychunk_ioctl_rsp);
N
Namjae Jeon 已提交
7688 7689 7690 7691 7692 7693 7694 7695 7696
		rsp->VolatileFileId = req->VolatileFileId;
		rsp->PersistentFileId = req->PersistentFileId;
		fsctl_copychunk(work,
				(struct copychunk_ioctl_req *)&req->Buffer[0],
				le32_to_cpu(req->CntCode),
				le32_to_cpu(req->InputCount),
				le64_to_cpu(req->VolatileFileId),
				le64_to_cpu(req->PersistentFileId),
				rsp);
7697 7698
		break;
	case FSCTL_SET_SPARSE:
N
Namjae Jeon 已提交
7699 7700 7701 7702 7703
		if (in_buf_len < sizeof(struct file_sparse)) {
			ret = -EINVAL;
			goto out;
		}

7704
		ret = fsctl_set_sparse(work, id,
7705
				       (struct file_sparse *)&req->Buffer[0]);
7706 7707 7708 7709 7710 7711 7712 7713 7714
		if (ret < 0)
			goto out;
		break;
	case FSCTL_SET_ZERO_DATA:
	{
		struct file_zero_data_information *zero_data;
		struct ksmbd_file *fp;
		loff_t off, len;

7715
		if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7716
			ksmbd_debug(SMB,
7717
				    "User does not have write permission\n");
7718 7719 7720 7721
			ret = -EACCES;
			goto out;
		}

N
Namjae Jeon 已提交
7722 7723 7724 7725 7726
		if (in_buf_len < sizeof(struct file_zero_data_information)) {
			ret = -EINVAL;
			goto out;
		}

7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745
		zero_data =
			(struct file_zero_data_information *)&req->Buffer[0];

		fp = ksmbd_lookup_fd_fast(work, id);
		if (!fp) {
			ret = -ENOENT;
			goto out;
		}

		off = le64_to_cpu(zero_data->FileOffset);
		len = le64_to_cpu(zero_data->BeyondFinalZero) - off;

		ret = ksmbd_vfs_zero_data(work, fp, off, len);
		ksmbd_fd_put(work, fp);
		if (ret < 0)
			goto out;
		break;
	}
	case FSCTL_QUERY_ALLOCATED_RANGES:
N
Namjae Jeon 已提交
7746 7747 7748 7749 7750
		if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
			ret = -EINVAL;
			goto out;
		}

7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772
		ret = fsctl_query_allocated_ranges(work, id,
			(struct file_allocated_range_buffer *)&req->Buffer[0],
			(struct file_allocated_range_buffer *)&rsp->Buffer[0],
			out_buf_len /
			sizeof(struct file_allocated_range_buffer), &nbytes);
		if (ret == -E2BIG) {
			rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
		} else if (ret < 0) {
			nbytes = 0;
			goto out;
		}

		nbytes *= sizeof(struct file_allocated_range_buffer);
		break;
	case FSCTL_GET_REPARSE_POINT:
	{
		struct reparse_data_buffer *reparse_ptr;
		struct ksmbd_file *fp;

		reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
		fp = ksmbd_lookup_fd_fast(work, id);
		if (!fp) {
N
Namjae Jeon 已提交
7773
			pr_err("not found fp!!\n");
7774 7775 7776 7777 7778
			ret = -ENOENT;
			goto out;
		}

		reparse_ptr->ReparseTag =
7779
			smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7780 7781 7782 7783 7784
		reparse_ptr->ReparseDataLength = 0;
		ksmbd_fd_put(work, fp);
		nbytes = sizeof(struct reparse_data_buffer);
		break;
	}
7785 7786 7787 7788 7789 7790
	case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
	{
		struct ksmbd_file *fp_in, *fp_out = NULL;
		struct duplicate_extents_to_file *dup_ext;
		loff_t src_off, dst_off, length, cloned;

N
Namjae Jeon 已提交
7791 7792 7793 7794 7795
		if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
			ret = -EINVAL;
			goto out;
		}

7796 7797 7798
		dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];

		fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7799
					     dup_ext->PersistentFileHandle);
7800
		if (!fp_in) {
N
Namjae Jeon 已提交
7801
			pr_err("not found file handle in duplicate extent to file\n");
7802 7803 7804 7805 7806 7807
			ret = -ENOENT;
			goto out;
		}

		fp_out = ksmbd_lookup_fd_fast(work, id);
		if (!fp_out) {
N
Namjae Jeon 已提交
7808
			pr_err("not found fp\n");
7809 7810 7811 7812 7813 7814 7815 7816
			ret = -ENOENT;
			goto dup_ext_out;
		}

		src_off = le64_to_cpu(dup_ext->SourceFileOffset);
		dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
		length = le64_to_cpu(dup_ext->ByteCount);
		cloned = vfs_clone_file_range(fp_in->filp, src_off, fp_out->filp,
7817
					      dst_off, length, 0);
7818 7819 7820 7821
		if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
			ret = -EOPNOTSUPP;
			goto dup_ext_out;
		} else if (cloned != length) {
7822 7823
			cloned = vfs_copy_file_range(fp_in->filp, src_off,
						     fp_out->filp, dst_off, length, 0);
7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838
			if (cloned != length) {
				if (cloned < 0)
					ret = cloned;
				else
					ret = -EINVAL;
			}
		}

dup_ext_out:
		ksmbd_fd_put(work, fp_in);
		ksmbd_fd_put(work, fp_out);
		if (ret < 0)
			goto out;
		break;
	}
7839 7840
	default:
		ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7841
			    cnt_code);
7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854
		ret = -EOPNOTSUPP;
		goto out;
	}

	rsp->CntCode = cpu_to_le32(cnt_code);
	rsp->InputCount = cpu_to_le32(0);
	rsp->InputOffset = cpu_to_le32(112);
	rsp->OutputOffset = cpu_to_le32(112);
	rsp->OutputCount = cpu_to_le32(nbytes);
	rsp->StructureSize = cpu_to_le16(49);
	rsp->Reserved = cpu_to_le16(0);
	rsp->Flags = cpu_to_le32(0);
	rsp->Reserved2 = cpu_to_le32(0);
7855
	inc_rfc1001_len(work->response_buf, 48 + nbytes);
7856 7857 7858 7859 7860 7861 7862 7863 7864 7865

	return 0;

out:
	if (ret == -EACCES)
		rsp->hdr.Status = STATUS_ACCESS_DENIED;
	else if (ret == -ENOENT)
		rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
	else if (ret == -EOPNOTSUPP)
		rsp->hdr.Status = STATUS_NOT_SUPPORTED;
N
Namjae Jeon 已提交
7866 7867
	else if (ret == -ENOSPC)
		rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881
	else if (ret < 0 || rsp->hdr.Status == 0)
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
	smb2_set_err_rsp(work);
	return 0;
}

/**
 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
 * @work:	smb work containing oplock break command buffer
 *
 * Return:	0
 */
static void smb20_oplock_break_ack(struct ksmbd_work *work)
{
7882 7883
	struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
	struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
7884 7885 7886 7887
	struct ksmbd_file *fp;
	struct oplock_info *opinfo = NULL;
	__le32 err = 0;
	int ret = 0;
7888
	u64 volatile_id, persistent_id;
7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906
	char req_oplevel = 0, rsp_oplevel = 0;
	unsigned int oplock_change_type;

	volatile_id = le64_to_cpu(req->VolatileFid);
	persistent_id = le64_to_cpu(req->PersistentFid);
	req_oplevel = req->OplockLevel;
	ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
		    volatile_id, persistent_id, req_oplevel);

	fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
	if (!fp) {
		rsp->hdr.Status = STATUS_FILE_CLOSED;
		smb2_set_err_rsp(work);
		return;
	}

	opinfo = opinfo_get(fp);
	if (!opinfo) {
N
Namjae Jeon 已提交
7907
		pr_err("unexpected null oplock_info\n");
7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924
		rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
		smb2_set_err_rsp(work);
		ksmbd_fd_put(work, fp);
		return;
	}

	if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
		rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
		goto err_out;
	}

	if (opinfo->op_state == OPLOCK_STATE_NONE) {
		ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
		goto err_out;
	}

7925 7926 7927 7928
	if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
	     opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
	    (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
	     req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
7929 7930
		err = STATUS_INVALID_OPLOCK_PROTOCOL;
		oplock_change_type = OPLOCK_WRITE_TO_NONE;
7931 7932
	} else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
		   req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
7933 7934
		err = STATUS_INVALID_OPLOCK_PROTOCOL;
		oplock_change_type = OPLOCK_READ_TO_NONE;
7935 7936
	} else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
		   req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7937
		err = STATUS_INVALID_DEVICE_STATE;
7938 7939 7940
		if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
		     opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
		    req_oplevel == SMB2_OPLOCK_LEVEL_II) {
7941
			oplock_change_type = OPLOCK_WRITE_TO_READ;
7942 7943 7944
		} else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
			    opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
			   req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7945
			oplock_change_type = OPLOCK_WRITE_TO_NONE;
7946 7947
		} else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
			   req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7948
			oplock_change_type = OPLOCK_READ_TO_NONE;
7949
		} else {
7950
			oplock_change_type = 0;
7951 7952
		}
	} else {
7953
		oplock_change_type = 0;
7954
	}
7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969

	switch (oplock_change_type) {
	case OPLOCK_WRITE_TO_READ:
		ret = opinfo_write_to_read(opinfo);
		rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
		break;
	case OPLOCK_WRITE_TO_NONE:
		ret = opinfo_write_to_none(opinfo);
		rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
		break;
	case OPLOCK_READ_TO_NONE:
		ret = opinfo_read_to_none(opinfo);
		rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
		break;
	default:
N
Namjae Jeon 已提交
7970 7971
		pr_err("unknown oplock change 0x%x -> 0x%x\n",
		       opinfo->level, rsp_oplevel);
7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989
	}

	if (ret < 0) {
		rsp->hdr.Status = err;
		goto err_out;
	}

	opinfo_put(opinfo);
	ksmbd_fd_put(work, fp);
	opinfo->op_state = OPLOCK_STATE_NONE;
	wake_up_interruptible_all(&opinfo->oplock_q);

	rsp->StructureSize = cpu_to_le16(24);
	rsp->OplockLevel = rsp_oplevel;
	rsp->Reserved = 0;
	rsp->Reserved2 = 0;
	rsp->VolatileFid = cpu_to_le64(volatile_id);
	rsp->PersistentFid = cpu_to_le64(persistent_id);
7990
	inc_rfc1001_len(work->response_buf, 24);
7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004
	return;

err_out:
	opinfo->op_state = OPLOCK_STATE_NONE;
	wake_up_interruptible_all(&opinfo->oplock_q);

	opinfo_put(opinfo);
	ksmbd_fd_put(work, fp);
	smb2_set_err_rsp(work);
}

static int check_lease_state(struct lease *lease, __le32 req_state)
{
	if ((lease->new_state ==
8005 8006
	     (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
	    !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025
		lease->new_state = req_state;
		return 0;
	}

	if (lease->new_state == req_state)
		return 0;

	return 1;
}

/**
 * smb21_lease_break_ack() - handler for smb2.1 lease break command
 * @work:	smb work containing lease break command buffer
 *
 * Return:	0
 */
static void smb21_lease_break_ack(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
8026 8027
	struct smb2_lease_ack *req = smb2_get_msg(work->request_buf);
	struct smb2_lease_ack *rsp = smb2_get_msg(work->response_buf);
8028 8029 8030 8031 8032 8033 8034 8035
	struct oplock_info *opinfo;
	__le32 err = 0;
	int ret = 0;
	unsigned int lease_change_type;
	__le32 lease_state;
	struct lease *lease;

	ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8036
		    le32_to_cpu(req->LeaseState));
8037 8038 8039 8040 8041 8042 8043 8044 8045 8046
	opinfo = lookup_lease_in_table(conn, req->LeaseKey);
	if (!opinfo) {
		ksmbd_debug(OPLOCK, "file not opened\n");
		smb2_set_err_rsp(work);
		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
		return;
	}
	lease = opinfo->o_lease;

	if (opinfo->op_state == OPLOCK_STATE_NONE) {
N
Namjae Jeon 已提交
8047 8048
		pr_err("unexpected lease break state 0x%x\n",
		       opinfo->op_state);
8049 8050 8051 8052 8053 8054 8055
		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
		goto err_out;
	}

	if (check_lease_state(lease, req->LeaseState)) {
		rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
		ksmbd_debug(OPLOCK,
8056 8057
			    "req lease state: 0x%x, expected state: 0x%x\n",
			    req->LeaseState, lease->new_state);
8058 8059 8060 8061 8062 8063 8064 8065 8066
		goto err_out;
	}

	if (!atomic_read(&opinfo->breaking_cnt)) {
		rsp->hdr.Status = STATUS_UNSUCCESSFUL;
		goto err_out;
	}

	/* check for bad lease state */
8067 8068
	if (req->LeaseState &
	    (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8069 8070 8071 8072 8073 8074
		err = STATUS_INVALID_OPLOCK_PROTOCOL;
		if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
			lease_change_type = OPLOCK_WRITE_TO_NONE;
		else
			lease_change_type = OPLOCK_READ_TO_NONE;
		ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8075 8076
			    le32_to_cpu(lease->state),
			    le32_to_cpu(req->LeaseState));
8077 8078
	} else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
		   req->LeaseState != SMB2_LEASE_NONE_LE) {
8079 8080 8081
		err = STATUS_INVALID_OPLOCK_PROTOCOL;
		lease_change_type = OPLOCK_READ_TO_NONE;
		ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8082 8083
			    le32_to_cpu(lease->state),
			    le32_to_cpu(req->LeaseState));
8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096
	} else {
		/* valid lease state changes */
		err = STATUS_INVALID_DEVICE_STATE;
		if (req->LeaseState == SMB2_LEASE_NONE_LE) {
			if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
				lease_change_type = OPLOCK_WRITE_TO_NONE;
			else
				lease_change_type = OPLOCK_READ_TO_NONE;
		} else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
			if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
				lease_change_type = OPLOCK_WRITE_TO_READ;
			else
				lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8097
		} else {
8098
			lease_change_type = 0;
8099
		}
8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116
	}

	switch (lease_change_type) {
	case OPLOCK_WRITE_TO_READ:
		ret = opinfo_write_to_read(opinfo);
		break;
	case OPLOCK_READ_HANDLE_TO_READ:
		ret = opinfo_read_handle_to_read(opinfo);
		break;
	case OPLOCK_WRITE_TO_NONE:
		ret = opinfo_write_to_none(opinfo);
		break;
	case OPLOCK_READ_TO_NONE:
		ret = opinfo_read_to_none(opinfo);
		break;
	default:
		ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8117 8118
			    le32_to_cpu(lease->state),
			    le32_to_cpu(req->LeaseState));
8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138
	}

	lease_state = lease->state;
	opinfo->op_state = OPLOCK_STATE_NONE;
	wake_up_interruptible_all(&opinfo->oplock_q);
	atomic_dec(&opinfo->breaking_cnt);
	wake_up_interruptible_all(&opinfo->oplock_brk);
	opinfo_put(opinfo);

	if (ret < 0) {
		rsp->hdr.Status = err;
		goto err_out;
	}

	rsp->StructureSize = cpu_to_le16(36);
	rsp->Reserved = 0;
	rsp->Flags = 0;
	memcpy(rsp->LeaseKey, req->LeaseKey, 16);
	rsp->LeaseState = lease_state;
	rsp->LeaseDuration = 0;
8139
	inc_rfc1001_len(work->response_buf, 36);
8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159
	return;

err_out:
	opinfo->op_state = OPLOCK_STATE_NONE;
	wake_up_interruptible_all(&opinfo->oplock_q);
	atomic_dec(&opinfo->breaking_cnt);
	wake_up_interruptible_all(&opinfo->oplock_brk);

	opinfo_put(opinfo);
	smb2_set_err_rsp(work);
}

/**
 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
 * @work:	smb work containing oplock/lease break command buffer
 *
 * Return:	0
 */
int smb2_oplock_break(struct ksmbd_work *work)
{
8160 8161
	struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
	struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
8162 8163 8164 8165 8166 8167 8168 8169 8170 8171

	switch (le16_to_cpu(req->StructureSize)) {
	case OP_BREAK_STRUCT_SIZE_20:
		smb20_oplock_break_ack(work);
		break;
	case OP_BREAK_STRUCT_SIZE_21:
		smb21_lease_break_ack(work);
		break;
	default:
		ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8172
			    le16_to_cpu(req->StructureSize));
8173 8174 8175 8176 8177 8178 8179 8180 8181
		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
		smb2_set_err_rsp(work);
	}

	return 0;
}

/**
 * smb2_notify() - handler for smb2 notify request
H
Hyunchul Lee 已提交
8182
 * @work:   smb work containing notify command buffer
8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205
 *
 * Return:      0
 */
int smb2_notify(struct ksmbd_work *work)
{
	struct smb2_notify_req *req;
	struct smb2_notify_rsp *rsp;

	WORK_BUFFERS(work, req, rsp);

	if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
		rsp->hdr.Status = STATUS_INTERNAL_ERROR;
		smb2_set_err_rsp(work);
		return 0;
	}

	smb2_set_err_rsp(work);
	rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
	return 0;
}

/**
 * smb2_is_sign_req() - handler for checking packet signing status
H
Hyunchul Lee 已提交
8206 8207
 * @work:	smb work containing notify command buffer
 * @command:	SMB2 command id
8208 8209 8210 8211 8212
 *
 * Return:	true if packed is signed, false otherwise
 */
bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
{
8213
	struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8214 8215

	if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8216 8217 8218
	    command != SMB2_NEGOTIATE_HE &&
	    command != SMB2_SESSION_SETUP_HE &&
	    command != SMB2_OPLOCK_BREAK_HE)
8219 8220
		return true;

8221
	return false;
8222 8223 8224 8225 8226 8227 8228 8229 8230 8231
}

/**
 * smb2_check_sign_req() - handler for req packet sign processing
 * @work:   smb work containing notify command buffer
 *
 * Return:	1 on success, 0 otherwise
 */
int smb2_check_sign_req(struct ksmbd_work *work)
{
8232
	struct smb2_hdr *hdr;
8233 8234 8235 8236 8237
	char signature_req[SMB2_SIGNATURE_SIZE];
	char signature[SMB2_HMACSHA256_SIZE];
	struct kvec iov[1];
	size_t len;

8238
	hdr = smb2_get_msg(work->request_buf);
8239
	if (work->next_smb2_rcv_hdr_off)
8240
		hdr = ksmbd_req_buf_next(work);
8241 8242

	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8243
		len = get_rfc1002_len(work->request_buf);
8244 8245 8246
	else if (hdr->NextCommand)
		len = le32_to_cpu(hdr->NextCommand);
	else
8247
		len = get_rfc1002_len(work->request_buf) -
8248 8249 8250 8251 8252 8253 8254 8255 8256
			work->next_smb2_rcv_hdr_off;

	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);

	iov[0].iov_base = (char *)&hdr->ProtocolId;
	iov[0].iov_len = len;

	if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8257
				signature))
8258 8259 8260
		return 0;

	if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
N
Namjae Jeon 已提交
8261
		pr_err("bad smb2 signature\n");
8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274
		return 0;
	}

	return 1;
}

/**
 * smb2_set_sign_rsp() - handler for rsp packet sign processing
 * @work:   smb work containing notify command buffer
 *
 */
void smb2_set_sign_rsp(struct ksmbd_work *work)
{
8275
	struct smb2_hdr *hdr;
8276 8277 8278 8279 8280 8281
	struct smb2_hdr *req_hdr;
	char signature[SMB2_HMACSHA256_SIZE];
	struct kvec iov[2];
	size_t len;
	int n_vec = 1;

8282
	hdr = smb2_get_msg(work->response_buf);
8283
	if (work->next_smb2_rsp_hdr_off)
8284
		hdr = ksmbd_resp_buf_next(work);
8285

8286
	req_hdr = ksmbd_req_buf_next(work);
8287 8288

	if (!work->next_smb2_rsp_hdr_off) {
8289
		len = get_rfc1002_len(work->response_buf);
8290 8291 8292
		if (req_hdr->NextCommand)
			len = ALIGN(len, 8);
	} else {
8293 8294
		len = get_rfc1002_len(work->response_buf) -
			work->next_smb2_rsp_hdr_off;
8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306
		len = ALIGN(len, 8);
	}

	if (req_hdr->NextCommand)
		hdr->NextCommand = cpu_to_le32(len);

	hdr->Flags |= SMB2_FLAGS_SIGNED;
	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);

	iov[0].iov_base = (char *)&hdr->ProtocolId;
	iov[0].iov_len = len;

N
Namjae Jeon 已提交
8307 8308
	if (work->aux_payload_sz) {
		iov[0].iov_len -= work->aux_payload_sz;
8309

N
Namjae Jeon 已提交
8310 8311
		iov[1].iov_base = work->aux_payload_buf;
		iov[1].iov_len = work->aux_payload_sz;
8312 8313 8314 8315
		n_vec++;
	}

	if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8316
				 signature))
8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327
		memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
}

/**
 * smb3_check_sign_req() - handler for req packet sign processing
 * @work:   smb work containing notify command buffer
 *
 * Return:	1 on success, 0 otherwise
 */
int smb3_check_sign_req(struct ksmbd_work *work)
{
8328
	struct ksmbd_conn *conn = work->conn;
8329
	char *signing_key;
8330
	struct smb2_hdr *hdr;
8331 8332 8333 8334 8335 8336
	struct channel *chann;
	char signature_req[SMB2_SIGNATURE_SIZE];
	char signature[SMB2_CMACAES_SIZE];
	struct kvec iov[1];
	size_t len;

8337
	hdr = smb2_get_msg(work->request_buf);
8338
	if (work->next_smb2_rcv_hdr_off)
8339
		hdr = ksmbd_req_buf_next(work);
8340 8341

	if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8342
		len = get_rfc1002_len(work->request_buf);
8343 8344 8345
	else if (hdr->NextCommand)
		len = le32_to_cpu(hdr->NextCommand);
	else
8346
		len = get_rfc1002_len(work->request_buf) -
8347 8348 8349 8350 8351
			work->next_smb2_rcv_hdr_off;

	if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
		signing_key = work->sess->smb3signingkey;
	} else {
N
Namjae Jeon 已提交
8352
		read_lock(&work->sess->chann_lock);
8353
		chann = lookup_chann_list(work->sess, conn);
N
Namjae Jeon 已提交
8354 8355
		if (!chann) {
			read_unlock(&work->sess->chann_lock);
8356
			return 0;
N
Namjae Jeon 已提交
8357
		}
8358
		signing_key = chann->smb3signingkey;
N
Namjae Jeon 已提交
8359
		read_unlock(&work->sess->chann_lock);
8360 8361 8362
	}

	if (!signing_key) {
N
Namjae Jeon 已提交
8363
		pr_err("SMB3 signing key is not generated\n");
8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375
		return 0;
	}

	memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
	iov[0].iov_base = (char *)&hdr->ProtocolId;
	iov[0].iov_len = len;

	if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
		return 0;

	if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
N
Namjae Jeon 已提交
8376
		pr_err("bad smb2 signature\n");
8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389
		return 0;
	}

	return 1;
}

/**
 * smb3_set_sign_rsp() - handler for rsp packet sign processing
 * @work:   smb work containing notify command buffer
 *
 */
void smb3_set_sign_rsp(struct ksmbd_work *work)
{
8390
	struct ksmbd_conn *conn = work->conn;
8391
	struct smb2_hdr *req_hdr, *hdr;
8392 8393 8394 8395 8396 8397 8398
	struct channel *chann;
	char signature[SMB2_CMACAES_SIZE];
	struct kvec iov[2];
	int n_vec = 1;
	size_t len;
	char *signing_key;

8399
	hdr = smb2_get_msg(work->response_buf);
8400
	if (work->next_smb2_rsp_hdr_off)
8401
		hdr = ksmbd_resp_buf_next(work);
8402

8403
	req_hdr = ksmbd_req_buf_next(work);
8404 8405

	if (!work->next_smb2_rsp_hdr_off) {
8406
		len = get_rfc1002_len(work->response_buf);
8407 8408 8409
		if (req_hdr->NextCommand)
			len = ALIGN(len, 8);
	} else {
8410 8411
		len = get_rfc1002_len(work->response_buf) -
			work->next_smb2_rsp_hdr_off;
8412 8413 8414
		len = ALIGN(len, 8);
	}

8415 8416
	if (conn->binding == false &&
	    le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8417 8418
		signing_key = work->sess->smb3signingkey;
	} else {
N
Namjae Jeon 已提交
8419
		read_lock(&work->sess->chann_lock);
8420
		chann = lookup_chann_list(work->sess, work->conn);
N
Namjae Jeon 已提交
8421 8422
		if (!chann) {
			read_unlock(&work->sess->chann_lock);
8423
			return;
N
Namjae Jeon 已提交
8424
		}
8425
		signing_key = chann->smb3signingkey;
N
Namjae Jeon 已提交
8426
		read_unlock(&work->sess->chann_lock);
8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438
	}

	if (!signing_key)
		return;

	if (req_hdr->NextCommand)
		hdr->NextCommand = cpu_to_le32(len);

	hdr->Flags |= SMB2_FLAGS_SIGNED;
	memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
	iov[0].iov_base = (char *)&hdr->ProtocolId;
	iov[0].iov_len = len;
N
Namjae Jeon 已提交
8439 8440 8441 8442
	if (work->aux_payload_sz) {
		iov[0].iov_len -= work->aux_payload_sz;
		iov[1].iov_base = work->aux_payload_buf;
		iov[1].iov_len = work->aux_payload_sz;
8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465
		n_vec++;
	}

	if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
		memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
}

/**
 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
 * @work:   smb work containing response buffer
 *
 */
void smb3_preauth_hash_rsp(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
	struct ksmbd_session *sess = work->sess;
	struct smb2_hdr *req, *rsp;

	if (conn->dialect != SMB311_PROT_ID)
		return;

	WORK_BUFFERS(work, req, rsp);

8466 8467
	if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
	    conn->preauth_info)
8468
		ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8469
						 conn->preauth_info->Preauth_HashValue);
8470

8471
	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8472 8473
		__u8 *hash_value;

8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485
		if (conn->binding) {
			struct preauth_session *preauth_sess;

			preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
			if (!preauth_sess)
				return;
			hash_value = preauth_sess->Preauth_HashValue;
		} else {
			hash_value = sess->Preauth_HashValue;
			if (!hash_value)
				return;
		}
8486
		ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8487
						 hash_value);
8488 8489 8490
	}
}

8491
static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8492
{
8493 8494
	struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
	struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8495 8496
	unsigned int orig_len = get_rfc1002_len(old_buf);

8497
	memset(tr_buf, 0, sizeof(struct smb2_transform_hdr) + 4);
8498 8499 8500
	tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
	tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
	tr_hdr->Flags = cpu_to_le16(0x01);
8501 8502 8503
	if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
	    cipher_type == SMB2_ENCRYPTION_AES256_GCM)
		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8504
	else
8505
		get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8506
	memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8507 8508
	inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
	inc_rfc1001_len(tr_buf, orig_len);
8509 8510 8511 8512
}

int smb3_encrypt_resp(struct ksmbd_work *work)
{
N
Namjae Jeon 已提交
8513
	char *buf = work->response_buf;
8514 8515
	struct kvec iov[3];
	int rc = -ENOMEM;
N
Namjae Jeon 已提交
8516
	int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8517 8518 8519 8520

	if (ARRAY_SIZE(iov) < rq_nvec)
		return -ENOMEM;

8521 8522
	work->tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
	if (!work->tr_buf)
8523 8524 8525
		return rc;

	/* fill transform header */
8526
	fill_transform_hdr(work->tr_buf, buf, work->conn->cipher_type);
8527

8528 8529
	iov[0].iov_base = work->tr_buf;
	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8530 8531 8532 8533
	buf_size += iov[0].iov_len - 4;

	iov[1].iov_base = buf + 4;
	iov[1].iov_len = get_rfc1002_len(buf);
N
Namjae Jeon 已提交
8534 8535
	if (work->aux_payload_sz) {
		iov[1].iov_len = work->resp_hdr_sz - 4;
8536

N
Namjae Jeon 已提交
8537 8538
		iov[2].iov_base = work->aux_payload_buf;
		iov[2].iov_len = work->aux_payload_sz;
8539 8540 8541 8542 8543
		buf_size += iov[2].iov_len;
	}
	buf_size += iov[1].iov_len;
	work->resp_hdr_sz = iov[1].iov_len;

8544
	rc = ksmbd_crypt_message(work, iov, rq_nvec, 1);
8545 8546 8547 8548
	if (rc)
		return rc;

	memmove(buf, iov[1].iov_base, iov[1].iov_len);
8549
	*(__be32 *)work->tr_buf = cpu_to_be32(buf_size);
8550 8551 8552 8553

	return rc;
}

8554
bool smb3_is_transform_hdr(void *buf)
8555
{
8556
	struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8557 8558 8559 8560 8561 8562 8563

	return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
}

int smb3_decrypt_req(struct ksmbd_work *work)
{
	struct ksmbd_session *sess;
N
Namjae Jeon 已提交
8564
	char *buf = work->request_buf;
8565 8566
	unsigned int pdu_length = get_rfc1002_len(buf);
	struct kvec iov[2];
8567 8568
	int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
	struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8569 8570
	int rc = 0;

8571
	if (buf_data_size < sizeof(struct smb2_hdr)) {
N
Namjae Jeon 已提交
8572 8573
		pr_err("Transform message is too small (%u)\n",
		       pdu_length);
8574 8575 8576
		return -ECONNABORTED;
	}

8577
	if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
N
Namjae Jeon 已提交
8578
		pr_err("Transform message is broken\n");
8579 8580 8581
		return -ECONNABORTED;
	}

8582
	sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8583 8584 8585 8586 8587 8588
	if (!sess) {
		pr_err("invalid session id(%llx) in transform header\n",
		       le64_to_cpu(tr_hdr->SessionId));
		return -ECONNABORTED;
	}

8589
	iov[0].iov_base = buf;
8590 8591
	iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
	iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8592
	iov[1].iov_len = buf_data_size;
8593
	rc = ksmbd_crypt_message(work, iov, 2, 0);
8594 8595 8596 8597
	if (rc)
		return rc;

	memmove(buf + 4, iov[1].iov_base, buf_data_size);
8598
	*(__be32 *)buf = cpu_to_be32(buf_data_size);
8599 8600 8601 8602 8603 8604 8605

	return rc;
}

bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
{
	struct ksmbd_conn *conn = work->conn;
8606
	struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8607 8608 8609 8610 8611

	if (conn->dialect < SMB30_PROT_ID)
		return false;

	if (work->next_smb2_rcv_hdr_off)
8612
		rsp = ksmbd_resp_buf_next(work);
8613 8614

	if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8615
	    rsp->Status == STATUS_SUCCESS)
8616 8617 8618
		return true;
	return false;
}