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