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