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