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