1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
4 * Copyright (C) 2018 Samsung Electronics Co., Ltd.
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 #include <linux/falloc.h>
14 #include <linux/mount.h>
15 #include <linux/filelock.h>
24 #include "connection.h"
25 #include "transport_ipc.h"
26 #include "transport_rdma.h"
28 #include "vfs_cache.h"
32 #include "smb_common.h"
33 #include "smbstatus.h"
34 #include "ksmbd_work.h"
35 #include "mgmt/user_config.h"
36 #include "mgmt/share_config.h"
37 #include "mgmt/tree_connect.h"
38 #include "mgmt/user_session.h"
39 #include "mgmt/ksmbd_ida.h"
42 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
44 if (work->next_smb2_rcv_hdr_off) {
45 *req = ksmbd_req_buf_next(work);
46 *rsp = ksmbd_resp_buf_next(work);
48 *req = smb2_get_msg(work->request_buf);
49 *rsp = smb2_get_msg(work->response_buf);
53 #define WORK_BUFFERS(w, rq, rs) __wbuf((w), (void **)&(rq), (void **)&(rs))
56 * check_session_id() - check for valid session id in smb header
57 * @conn: connection instance
58 * @id: session id from smb header
60 * Return: 1 if valid session id, otherwise 0
62 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
64 struct ksmbd_session *sess;
66 if (id == 0 || id == -1)
69 sess = ksmbd_session_lookup_all(conn, id);
72 pr_err("Invalid user session id: %llu\n", id);
76 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
78 return xa_load(&sess->ksmbd_chann_list, (long)conn);
82 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
85 * Return: 0 if there is a tree connection matched or these are
86 * skipable commands, otherwise error
88 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
90 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
91 unsigned int cmd = le16_to_cpu(req_hdr->Command);
94 if (cmd == SMB2_TREE_CONNECT_HE ||
95 cmd == SMB2_CANCEL_HE ||
96 cmd == SMB2_LOGOFF_HE) {
97 ksmbd_debug(SMB, "skip to check tree connect request\n");
101 if (xa_empty(&work->sess->tree_conns)) {
102 ksmbd_debug(SMB, "NO tree connected\n");
106 tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
109 * If request is not the first in Compound request,
110 * Just validate tree id in header with work->tcon->id.
112 if (work->next_smb2_rcv_hdr_off) {
114 pr_err("The first operation in the compound does not have tcon\n");
117 if (tree_id != UINT_MAX && work->tcon->id != tree_id) {
118 pr_err("tree id(%u) is different with id(%u) in first operation\n",
119 tree_id, work->tcon->id);
125 work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
127 pr_err("Invalid tid %d\n", tree_id);
135 * smb2_set_err_rsp() - set error response code on smb response
136 * @work: smb work containing response buffer
138 void smb2_set_err_rsp(struct ksmbd_work *work)
140 struct smb2_err_rsp *err_rsp;
142 if (work->next_smb2_rcv_hdr_off)
143 err_rsp = ksmbd_resp_buf_next(work);
145 err_rsp = smb2_get_msg(work->response_buf);
147 if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
150 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
151 err_rsp->ErrorContextCount = 0;
152 err_rsp->Reserved = 0;
153 err_rsp->ByteCount = 0;
154 err_rsp->ErrorData[0] = 0;
155 err = ksmbd_iov_pin_rsp(work, (void *)err_rsp,
156 __SMB2_HEADER_STRUCTURE_SIZE +
157 SMB2_ERROR_STRUCTURE_SIZE2);
159 work->send_no_response = 1;
164 * is_smb2_neg_cmd() - is it smb2 negotiation command
165 * @work: smb work containing smb header
167 * Return: true if smb2 negotiation command, otherwise false
169 bool is_smb2_neg_cmd(struct ksmbd_work *work)
171 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
173 /* is it SMB2 header ? */
174 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
177 /* make sure it is request not response message */
178 if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
181 if (hdr->Command != SMB2_NEGOTIATE)
188 * is_smb2_rsp() - is it smb2 response
189 * @work: smb work containing smb response buffer
191 * Return: true if smb2 response, otherwise false
193 bool is_smb2_rsp(struct ksmbd_work *work)
195 struct smb2_hdr *hdr = smb2_get_msg(work->response_buf);
197 /* is it SMB2 header ? */
198 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
201 /* make sure it is response not request message */
202 if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
209 * get_smb2_cmd_val() - get smb command code from smb header
210 * @work: smb work containing smb request buffer
212 * Return: smb2 request command value
214 u16 get_smb2_cmd_val(struct ksmbd_work *work)
216 struct smb2_hdr *rcv_hdr;
218 if (work->next_smb2_rcv_hdr_off)
219 rcv_hdr = ksmbd_req_buf_next(work);
221 rcv_hdr = smb2_get_msg(work->request_buf);
222 return le16_to_cpu(rcv_hdr->Command);
226 * set_smb2_rsp_status() - set error response code on smb2 header
227 * @work: smb work containing response buffer
228 * @err: error response code
230 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
232 struct smb2_hdr *rsp_hdr;
234 rsp_hdr = smb2_get_msg(work->response_buf);
235 rsp_hdr->Status = err;
239 work->next_smb2_rcv_hdr_off = 0;
240 smb2_set_err_rsp(work);
244 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
245 * @work: smb work containing smb request buffer
247 * smb2 negotiate response is sent in reply of smb1 negotiate command for
248 * dialect auto-negotiation.
250 int init_smb2_neg_rsp(struct ksmbd_work *work)
252 struct smb2_hdr *rsp_hdr;
253 struct smb2_negotiate_rsp *rsp;
254 struct ksmbd_conn *conn = work->conn;
257 rsp_hdr = smb2_get_msg(work->response_buf);
258 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
259 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
260 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
261 rsp_hdr->CreditRequest = cpu_to_le16(2);
262 rsp_hdr->Command = SMB2_NEGOTIATE;
263 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
264 rsp_hdr->NextCommand = 0;
265 rsp_hdr->MessageId = 0;
266 rsp_hdr->Id.SyncId.ProcessId = 0;
267 rsp_hdr->Id.SyncId.TreeId = 0;
268 rsp_hdr->SessionId = 0;
269 memset(rsp_hdr->Signature, 0, 16);
271 rsp = smb2_get_msg(work->response_buf);
273 WARN_ON(ksmbd_conn_good(conn));
275 rsp->StructureSize = cpu_to_le16(65);
276 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
277 rsp->DialectRevision = cpu_to_le16(conn->dialect);
278 /* Not setting conn guid rsp->ServerGUID, as it
279 * not used by client for identifying connection
281 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
282 /* Default Max Message Size till SMB2.0, 64K*/
283 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
284 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
285 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
287 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
288 rsp->ServerStartTime = 0;
290 rsp->SecurityBufferOffset = cpu_to_le16(128);
291 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
292 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
293 le16_to_cpu(rsp->SecurityBufferOffset));
294 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
295 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
296 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
297 err = ksmbd_iov_pin_rsp(work, rsp,
298 sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH);
301 conn->use_spnego = true;
303 ksmbd_conn_set_need_negotiate(conn);
308 * smb2_set_rsp_credits() - set number of credits in response buffer
309 * @work: smb work containing smb response buffer
311 int smb2_set_rsp_credits(struct ksmbd_work *work)
313 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
314 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
315 struct ksmbd_conn *conn = work->conn;
316 unsigned short credits_requested, aux_max;
317 unsigned short credit_charge, credits_granted = 0;
319 if (work->send_no_response)
322 hdr->CreditCharge = req_hdr->CreditCharge;
324 if (conn->total_credits > conn->vals->max_credits) {
325 hdr->CreditRequest = 0;
326 pr_err("Total credits overflow: %d\n", conn->total_credits);
330 credit_charge = max_t(unsigned short,
331 le16_to_cpu(req_hdr->CreditCharge), 1);
332 if (credit_charge > conn->total_credits) {
333 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
334 credit_charge, conn->total_credits);
338 conn->total_credits -= credit_charge;
339 conn->outstanding_credits -= credit_charge;
340 credits_requested = max_t(unsigned short,
341 le16_to_cpu(req_hdr->CreditRequest), 1);
343 /* according to smb2.credits smbtorture, Windows server
344 * 2016 or later grant up to 8192 credits at once.
346 * TODO: Need to adjuct CreditRequest value according to
349 if (hdr->Command == SMB2_NEGOTIATE)
352 aux_max = conn->vals->max_credits - conn->total_credits;
353 credits_granted = min_t(unsigned short, credits_requested, aux_max);
355 conn->total_credits += credits_granted;
356 work->credits_granted += credits_granted;
358 if (!req_hdr->NextCommand) {
359 /* Update CreditRequest in last request */
360 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
363 "credits: requested[%d] granted[%d] total_granted[%d]\n",
364 credits_requested, credits_granted,
365 conn->total_credits);
370 * init_chained_smb2_rsp() - initialize smb2 chained response
371 * @work: smb work containing smb response buffer
373 static void init_chained_smb2_rsp(struct ksmbd_work *work)
375 struct smb2_hdr *req = ksmbd_req_buf_next(work);
376 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
377 struct smb2_hdr *rsp_hdr;
378 struct smb2_hdr *rcv_hdr;
379 int next_hdr_offset = 0;
382 /* Len of this response = updated RFC len - offset of previous cmd
383 * in the compound rsp
386 /* Storing the current local FID which may be needed by subsequent
387 * command in the compound request
389 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
390 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
391 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
392 work->compound_sid = le64_to_cpu(rsp->SessionId);
395 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
396 next_hdr_offset = le32_to_cpu(req->NextCommand);
398 new_len = ALIGN(len, 8);
399 work->iov[work->iov_idx].iov_len += (new_len - len);
400 inc_rfc1001_len(work->response_buf, new_len - len);
401 rsp->NextCommand = cpu_to_le32(new_len);
403 work->next_smb2_rcv_hdr_off += next_hdr_offset;
404 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
405 work->next_smb2_rsp_hdr_off += new_len;
407 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
408 new_len, work->next_smb2_rcv_hdr_off,
409 work->next_smb2_rsp_hdr_off);
411 rsp_hdr = ksmbd_resp_buf_next(work);
412 rcv_hdr = ksmbd_req_buf_next(work);
414 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
415 ksmbd_debug(SMB, "related flag should be set\n");
416 work->compound_fid = KSMBD_NO_FID;
417 work->compound_pfid = KSMBD_NO_FID;
419 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
420 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
421 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
422 rsp_hdr->Command = rcv_hdr->Command;
425 * Message is response. We don't grant oplock yet.
427 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
428 SMB2_FLAGS_RELATED_OPERATIONS);
429 rsp_hdr->NextCommand = 0;
430 rsp_hdr->MessageId = rcv_hdr->MessageId;
431 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
432 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
433 rsp_hdr->SessionId = rcv_hdr->SessionId;
434 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
438 * is_chained_smb2_message() - check for chained command
439 * @work: smb work containing smb request buffer
441 * Return: true if chained request, otherwise false
443 bool is_chained_smb2_message(struct ksmbd_work *work)
445 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
446 unsigned int len, next_cmd;
448 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
451 hdr = ksmbd_req_buf_next(work);
452 next_cmd = le32_to_cpu(hdr->NextCommand);
454 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
455 __SMB2_HEADER_STRUCTURE_SIZE >
456 get_rfc1002_len(work->request_buf)) {
457 pr_err("next command(%u) offset exceeds smb msg size\n",
462 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
464 pr_err("next response offset exceeds response buffer size\n");
468 ksmbd_debug(SMB, "got SMB2 chained command\n");
469 init_chained_smb2_rsp(work);
471 } else if (work->next_smb2_rcv_hdr_off) {
473 * This is last request in chained command,
474 * align response to 8 byte
476 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
477 len = len - get_rfc1002_len(work->response_buf);
479 ksmbd_debug(SMB, "padding len %u\n", len);
480 work->iov[work->iov_idx].iov_len += len;
481 inc_rfc1001_len(work->response_buf, len);
483 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
489 * init_smb2_rsp_hdr() - initialize smb2 response
490 * @work: smb work containing smb request buffer
494 int init_smb2_rsp_hdr(struct ksmbd_work *work)
496 struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
497 struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
499 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
500 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
501 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
502 rsp_hdr->Command = rcv_hdr->Command;
505 * Message is response. We don't grant oplock yet.
507 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
508 rsp_hdr->NextCommand = 0;
509 rsp_hdr->MessageId = rcv_hdr->MessageId;
510 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
511 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
512 rsp_hdr->SessionId = rcv_hdr->SessionId;
513 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
519 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
520 * @work: smb work containing smb request buffer
522 * Return: 0 on success, otherwise -ENOMEM
524 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
526 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
527 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
528 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
529 size_t sz = small_sz;
530 int cmd = le16_to_cpu(hdr->Command);
532 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
535 if (cmd == SMB2_QUERY_INFO_HE) {
536 struct smb2_query_info_req *req;
538 req = smb2_get_msg(work->request_buf);
539 if ((req->InfoType == SMB2_O_INFO_FILE &&
540 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
541 req->FileInfoClass == FILE_ALL_INFORMATION)) ||
542 req->InfoType == SMB2_O_INFO_SECURITY)
546 /* allocate large response buf for chained commands */
547 if (le32_to_cpu(hdr->NextCommand) > 0)
550 work->response_buf = kvzalloc(sz, GFP_KERNEL);
551 if (!work->response_buf)
554 work->response_sz = sz;
559 * smb2_check_user_session() - check for valid session for a user
560 * @work: smb work containing smb request buffer
562 * Return: 0 on success, otherwise error
564 int smb2_check_user_session(struct ksmbd_work *work)
566 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
567 struct ksmbd_conn *conn = work->conn;
568 unsigned int cmd = le16_to_cpu(req_hdr->Command);
569 unsigned long long sess_id;
572 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
573 * require a session id, so no need to validate user session's for
576 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
577 cmd == SMB2_SESSION_SETUP_HE)
580 if (!ksmbd_conn_good(conn))
583 sess_id = le64_to_cpu(req_hdr->SessionId);
586 * If request is not the first in Compound request,
587 * Just validate session id in header with work->sess->id.
589 if (work->next_smb2_rcv_hdr_off) {
591 pr_err("The first operation in the compound does not have sess\n");
594 if (sess_id != ULLONG_MAX && work->sess->id != sess_id) {
595 pr_err("session id(%llu) is different with the first operation(%lld)\n",
596 sess_id, work->sess->id);
602 /* Check for validity of user session */
603 work->sess = ksmbd_session_lookup_all(conn, sess_id);
606 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
610 static void destroy_previous_session(struct ksmbd_conn *conn,
611 struct ksmbd_user *user, u64 id)
613 struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
614 struct ksmbd_user *prev_user;
615 struct channel *chann;
621 prev_user = prev_sess->user;
624 strcmp(user->name, prev_user->name) ||
625 user->passkey_sz != prev_user->passkey_sz ||
626 memcmp(user->passkey, prev_user->passkey, user->passkey_sz))
629 prev_sess->state = SMB2_SESSION_EXPIRED;
630 xa_for_each(&prev_sess->ksmbd_chann_list, index, chann)
631 ksmbd_conn_set_exiting(chann->conn);
635 * smb2_get_name() - get filename string from on the wire smb format
636 * @src: source buffer
637 * @maxlen: maxlen of source string
638 * @local_nls: nls_table pointer
640 * Return: matching converted filename on success, otherwise error ptr
643 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
647 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
649 pr_err("failed to get name %ld\n", PTR_ERR(name));
653 ksmbd_conv_path_to_unix(name);
654 ksmbd_strip_last_slash(name);
658 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
660 struct ksmbd_conn *conn = work->conn;
663 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
665 pr_err("Failed to alloc async message id\n");
668 work->asynchronous = true;
672 "Send interim Response to inform async request id : %d\n",
675 work->cancel_fn = fn;
676 work->cancel_argv = arg;
678 if (list_empty(&work->async_request_entry)) {
679 spin_lock(&conn->request_lock);
680 list_add_tail(&work->async_request_entry, &conn->async_requests);
681 spin_unlock(&conn->request_lock);
687 void release_async_work(struct ksmbd_work *work)
689 struct ksmbd_conn *conn = work->conn;
691 spin_lock(&conn->request_lock);
692 list_del_init(&work->async_request_entry);
693 spin_unlock(&conn->request_lock);
695 work->asynchronous = 0;
696 work->cancel_fn = NULL;
697 kfree(work->cancel_argv);
698 work->cancel_argv = NULL;
699 if (work->async_id) {
700 ksmbd_release_id(&conn->async_ida, work->async_id);
705 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
707 struct smb2_hdr *rsp_hdr;
708 struct ksmbd_work *in_work = ksmbd_alloc_work_struct();
710 if (allocate_interim_rsp_buf(in_work)) {
711 pr_err("smb_allocate_rsp_buf failed!\n");
712 ksmbd_free_work_struct(in_work);
716 in_work->conn = work->conn;
717 memcpy(smb2_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work),
718 __SMB2_HEADER_STRUCTURE_SIZE);
720 rsp_hdr = smb2_get_msg(in_work->response_buf);
721 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
722 rsp_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
723 smb2_set_err_rsp(in_work);
724 rsp_hdr->Status = status;
726 ksmbd_conn_write(in_work);
727 ksmbd_free_work_struct(in_work);
730 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
732 if (S_ISDIR(mode) || S_ISREG(mode))
736 return IO_REPARSE_TAG_LX_SYMLINK_LE;
737 else if (S_ISFIFO(mode))
738 return IO_REPARSE_TAG_LX_FIFO_LE;
739 else if (S_ISSOCK(mode))
740 return IO_REPARSE_TAG_AF_UNIX_LE;
741 else if (S_ISCHR(mode))
742 return IO_REPARSE_TAG_LX_CHR_LE;
743 else if (S_ISBLK(mode))
744 return IO_REPARSE_TAG_LX_BLK_LE;
750 * smb2_get_dos_mode() - get file mode in dos format from unix mode
751 * @stat: kstat containing file mode
752 * @attribute: attribute flags
754 * Return: converted dos mode
756 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
760 if (S_ISDIR(stat->mode)) {
761 attr = FILE_ATTRIBUTE_DIRECTORY |
762 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
764 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
765 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
766 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
767 FILE_SUPPORTS_SPARSE_FILES))
768 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
770 if (smb2_get_reparse_tag_special_file(stat->mode))
771 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
777 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
780 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
781 pneg_ctxt->DataLength = cpu_to_le16(38);
782 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
783 pneg_ctxt->Reserved = cpu_to_le32(0);
784 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
785 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
786 pneg_ctxt->HashAlgorithms = hash_id;
789 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
792 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
793 pneg_ctxt->DataLength = cpu_to_le16(4);
794 pneg_ctxt->Reserved = cpu_to_le32(0);
795 pneg_ctxt->CipherCount = cpu_to_le16(1);
796 pneg_ctxt->Ciphers[0] = cipher_type;
799 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
802 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
803 pneg_ctxt->DataLength =
804 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
805 - sizeof(struct smb2_neg_context));
806 pneg_ctxt->Reserved = cpu_to_le32(0);
807 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
808 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
811 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
813 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
814 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
815 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
816 pneg_ctxt->Name[0] = 0x93;
817 pneg_ctxt->Name[1] = 0xAD;
818 pneg_ctxt->Name[2] = 0x25;
819 pneg_ctxt->Name[3] = 0x50;
820 pneg_ctxt->Name[4] = 0x9C;
821 pneg_ctxt->Name[5] = 0xB4;
822 pneg_ctxt->Name[6] = 0x11;
823 pneg_ctxt->Name[7] = 0xE7;
824 pneg_ctxt->Name[8] = 0xB4;
825 pneg_ctxt->Name[9] = 0x23;
826 pneg_ctxt->Name[10] = 0x83;
827 pneg_ctxt->Name[11] = 0xDE;
828 pneg_ctxt->Name[12] = 0x96;
829 pneg_ctxt->Name[13] = 0x8B;
830 pneg_ctxt->Name[14] = 0xCD;
831 pneg_ctxt->Name[15] = 0x7C;
834 static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
835 struct smb2_negotiate_rsp *rsp)
837 char * const pneg_ctxt = (char *)rsp +
838 le32_to_cpu(rsp->NegotiateContextOffset);
839 int neg_ctxt_cnt = 1;
843 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
844 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
845 conn->preauth_info->Preauth_HashId);
846 ctxt_size = sizeof(struct smb2_preauth_neg_context);
848 if (conn->cipher_type) {
849 /* Round to 8 byte boundary */
850 ctxt_size = round_up(ctxt_size, 8);
852 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
853 build_encrypt_ctxt((struct smb2_encryption_neg_context *)
854 (pneg_ctxt + ctxt_size),
857 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
860 /* compression context not yet supported */
861 WARN_ON(conn->compress_algorithm != SMB3_COMPRESS_NONE);
863 if (conn->posix_ext_supported) {
864 ctxt_size = round_up(ctxt_size, 8);
866 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
867 build_posix_ctxt((struct smb2_posix_neg_context *)
868 (pneg_ctxt + ctxt_size));
870 ctxt_size += sizeof(struct smb2_posix_neg_context);
873 if (conn->signing_negotiated) {
874 ctxt_size = round_up(ctxt_size, 8);
876 "assemble SMB2_SIGNING_CAPABILITIES context\n");
877 build_sign_cap_ctxt((struct smb2_signing_capabilities *)
878 (pneg_ctxt + ctxt_size),
879 conn->signing_algorithm);
881 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
884 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
885 return ctxt_size + AUTH_GSS_PADDING;
888 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
889 struct smb2_preauth_neg_context *pneg_ctxt,
893 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
894 * which may not be present. Only check for used HashAlgorithms[1].
897 sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
898 return STATUS_INVALID_PARAMETER;
900 if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
901 return STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
903 conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
904 return STATUS_SUCCESS;
907 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
908 struct smb2_encryption_neg_context *pneg_ctxt,
914 if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
915 pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
919 conn->cipher_type = 0;
921 cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
922 cphs_size = cph_cnt * sizeof(__le16);
924 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
926 pr_err("Invalid cipher count(%d)\n", cph_cnt);
930 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
933 for (i = 0; i < cph_cnt; i++) {
934 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
935 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
936 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
937 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
938 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
939 pneg_ctxt->Ciphers[i]);
940 conn->cipher_type = pneg_ctxt->Ciphers[i];
947 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
948 * @conn: smb connection
950 * Return: true if connection should be encrypted, else false
952 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
954 if (!conn->ops->generate_encryptionkey)
958 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
959 * SMB 3.1.1 uses the cipher_type field.
961 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
965 static void decode_compress_ctxt(struct ksmbd_conn *conn,
966 struct smb2_compression_capabilities_context *pneg_ctxt)
968 conn->compress_algorithm = SMB3_COMPRESS_NONE;
971 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
972 struct smb2_signing_capabilities *pneg_ctxt,
976 int i, sign_alos_size;
978 if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
979 pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
983 conn->signing_negotiated = false;
984 sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
985 sign_alos_size = sign_algo_cnt * sizeof(__le16);
987 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
989 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
993 for (i = 0; i < sign_algo_cnt; i++) {
994 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
995 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
996 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
997 pneg_ctxt->SigningAlgorithms[i]);
998 conn->signing_negotiated = true;
999 conn->signing_algorithm =
1000 pneg_ctxt->SigningAlgorithms[i];
1006 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
1007 struct smb2_negotiate_req *req,
1008 unsigned int len_of_smb)
1010 /* +4 is to account for the RFC1001 len field */
1011 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
1012 int i = 0, len_of_ctxts;
1013 unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
1014 unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
1015 __le32 status = STATUS_INVALID_PARAMETER;
1017 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
1018 if (len_of_smb <= offset) {
1019 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
1023 len_of_ctxts = len_of_smb - offset;
1025 while (i++ < neg_ctxt_cnt) {
1028 if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
1031 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1032 clen = le16_to_cpu(pctx->DataLength);
1033 ctxt_len = clen + sizeof(struct smb2_neg_context);
1035 if (ctxt_len > len_of_ctxts)
1038 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1040 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1041 if (conn->preauth_info->Preauth_HashId)
1044 status = decode_preauth_ctxt(conn,
1045 (struct smb2_preauth_neg_context *)pctx,
1047 if (status != STATUS_SUCCESS)
1049 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1051 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1052 if (conn->cipher_type)
1055 decode_encrypt_ctxt(conn,
1056 (struct smb2_encryption_neg_context *)pctx,
1058 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1060 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1061 if (conn->compress_algorithm)
1064 decode_compress_ctxt(conn,
1065 (struct smb2_compression_capabilities_context *)pctx);
1066 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1068 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1069 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1071 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1072 conn->posix_ext_supported = true;
1073 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1075 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1077 decode_sign_cap_ctxt(conn,
1078 (struct smb2_signing_capabilities *)pctx,
1082 /* offsets must be 8 byte aligned */
1083 offset = (ctxt_len + 7) & ~0x7;
1084 len_of_ctxts -= offset;
1090 * smb2_handle_negotiate() - handler for smb2 negotiate command
1091 * @work: smb work containing smb request buffer
1095 int smb2_handle_negotiate(struct ksmbd_work *work)
1097 struct ksmbd_conn *conn = work->conn;
1098 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1099 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1101 unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0;
1104 ksmbd_debug(SMB, "Received negotiate request\n");
1105 conn->need_neg = false;
1106 if (ksmbd_conn_good(conn)) {
1107 pr_err("conn->tcp_status is already in CifsGood State\n");
1108 work->send_no_response = 1;
1112 smb2_buf_len = get_rfc1002_len(work->request_buf);
1113 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1114 if (smb2_neg_size > smb2_buf_len) {
1115 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1120 if (req->DialectCount == 0) {
1121 pr_err("malformed packet\n");
1122 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1127 if (conn->dialect == SMB311_PROT_ID) {
1128 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1130 if (smb2_buf_len < nego_ctxt_off) {
1131 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1136 if (smb2_neg_size > nego_ctxt_off) {
1137 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1142 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1144 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1149 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1151 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1157 conn->cli_cap = le32_to_cpu(req->Capabilities);
1158 switch (conn->dialect) {
1159 case SMB311_PROT_ID:
1160 conn->preauth_info =
1161 kzalloc(sizeof(struct preauth_integrity_info),
1163 if (!conn->preauth_info) {
1165 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1169 status = deassemble_neg_contexts(conn, req,
1170 get_rfc1002_len(work->request_buf));
1171 if (status != STATUS_SUCCESS) {
1172 pr_err("deassemble_neg_contexts error(0x%x)\n",
1174 rsp->hdr.Status = status;
1176 kfree(conn->preauth_info);
1177 conn->preauth_info = NULL;
1181 rc = init_smb3_11_server(conn);
1183 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1184 kfree(conn->preauth_info);
1185 conn->preauth_info = NULL;
1189 ksmbd_gen_preauth_integrity_hash(conn,
1191 conn->preauth_info->Preauth_HashValue);
1192 rsp->NegotiateContextOffset =
1193 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1194 neg_ctxt_len = assemble_neg_contexts(conn, rsp);
1196 case SMB302_PROT_ID:
1197 init_smb3_02_server(conn);
1200 init_smb3_0_server(conn);
1203 init_smb2_1_server(conn);
1208 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1210 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1214 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1217 conn->connection_type = conn->dialect;
1219 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1220 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1221 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1223 memcpy(conn->ClientGUID, req->ClientGUID,
1224 SMB2_CLIENT_GUID_SIZE);
1225 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1227 rsp->StructureSize = cpu_to_le16(65);
1228 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1229 /* Not setting conn guid rsp->ServerGUID, as it
1230 * not used by client for identifying server
1232 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1234 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1235 rsp->ServerStartTime = 0;
1236 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1237 le32_to_cpu(rsp->NegotiateContextOffset),
1238 le16_to_cpu(rsp->NegotiateContextCount));
1240 rsp->SecurityBufferOffset = cpu_to_le16(128);
1241 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1242 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1243 le16_to_cpu(rsp->SecurityBufferOffset));
1245 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1246 conn->use_spnego = true;
1248 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1249 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1250 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1252 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1253 server_conf.enforced_signing = true;
1254 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1258 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1259 ksmbd_conn_set_need_negotiate(conn);
1263 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1266 rc = ksmbd_iov_pin_rsp(work, rsp,
1267 sizeof(struct smb2_negotiate_rsp) +
1268 AUTH_GSS_LENGTH + neg_ctxt_len);
1270 smb2_set_err_rsp(work);
1274 static int alloc_preauth_hash(struct ksmbd_session *sess,
1275 struct ksmbd_conn *conn)
1277 if (sess->Preauth_HashValue)
1280 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1281 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1282 if (!sess->Preauth_HashValue)
1288 static int generate_preauth_hash(struct ksmbd_work *work)
1290 struct ksmbd_conn *conn = work->conn;
1291 struct ksmbd_session *sess = work->sess;
1294 if (conn->dialect != SMB311_PROT_ID)
1297 if (conn->binding) {
1298 struct preauth_session *preauth_sess;
1300 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1301 if (!preauth_sess) {
1302 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1307 preauth_hash = preauth_sess->Preauth_HashValue;
1309 if (!sess->Preauth_HashValue)
1310 if (alloc_preauth_hash(sess, conn))
1312 preauth_hash = sess->Preauth_HashValue;
1315 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1319 static int decode_negotiation_token(struct ksmbd_conn *conn,
1320 struct negotiate_message *negblob,
1323 if (!conn->use_spnego)
1326 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1327 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1328 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1329 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1330 conn->use_spnego = false;
1336 static int ntlm_negotiate(struct ksmbd_work *work,
1337 struct negotiate_message *negblob,
1338 size_t negblob_len, struct smb2_sess_setup_rsp *rsp)
1340 struct challenge_message *chgblob;
1341 unsigned char *spnego_blob = NULL;
1342 u16 spnego_blob_len;
1346 ksmbd_debug(SMB, "negotiate phase\n");
1347 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1351 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1353 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1354 memset(chgblob, 0, sizeof(struct challenge_message));
1356 if (!work->conn->use_spnego) {
1357 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1361 rsp->SecurityBufferLength = cpu_to_le16(sz);
1365 sz = sizeof(struct challenge_message);
1366 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1368 neg_blob = kzalloc(sz, GFP_KERNEL);
1372 chgblob = (struct challenge_message *)neg_blob;
1373 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1379 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1386 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1387 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1388 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1396 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1397 struct smb2_sess_setup_req *req)
1401 if (conn->use_spnego && conn->mechToken)
1402 return (struct authenticate_message *)conn->mechToken;
1404 sz = le16_to_cpu(req->SecurityBufferOffset);
1405 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1409 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1410 struct smb2_sess_setup_req *req)
1412 struct authenticate_message *authblob;
1413 struct ksmbd_user *user;
1415 unsigned int name_off, name_len, secbuf_len;
1417 if (conn->use_spnego && conn->mechToken)
1418 secbuf_len = conn->mechTokenLen;
1420 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1421 if (secbuf_len < sizeof(struct authenticate_message)) {
1422 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1425 authblob = user_authblob(conn, req);
1426 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1427 name_len = le16_to_cpu(authblob->UserName.Length);
1429 if (secbuf_len < (u64)name_off + name_len)
1432 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1437 pr_err("cannot allocate memory\n");
1441 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1442 user = ksmbd_login_user(name);
1447 static int ntlm_authenticate(struct ksmbd_work *work,
1448 struct smb2_sess_setup_req *req,
1449 struct smb2_sess_setup_rsp *rsp)
1451 struct ksmbd_conn *conn = work->conn;
1452 struct ksmbd_session *sess = work->sess;
1453 struct channel *chann = NULL;
1454 struct ksmbd_user *user;
1458 ksmbd_debug(SMB, "authenticate phase\n");
1459 if (conn->use_spnego) {
1460 unsigned char *spnego_blob;
1461 u16 spnego_blob_len;
1463 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1469 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1470 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1471 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1475 user = session_user(conn, req);
1477 ksmbd_debug(SMB, "Unknown user name or an error\n");
1481 /* Check for previous session */
1482 prev_id = le64_to_cpu(req->PreviousSessionId);
1483 if (prev_id && prev_id != sess->id)
1484 destroy_previous_session(conn, user, prev_id);
1486 if (sess->state == SMB2_SESSION_VALID) {
1488 * Reuse session if anonymous try to connect
1489 * on reauthetication.
1491 if (conn->binding == false && ksmbd_anonymous_user(user)) {
1492 ksmbd_free_user(user);
1496 if (!ksmbd_compare_user(sess->user, user)) {
1497 ksmbd_free_user(user);
1500 ksmbd_free_user(user);
1505 if (conn->binding == false && user_guest(sess->user)) {
1506 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1508 struct authenticate_message *authblob;
1510 authblob = user_authblob(conn, req);
1511 if (conn->use_spnego && conn->mechToken)
1512 sz = conn->mechTokenLen;
1514 sz = le16_to_cpu(req->SecurityBufferLength);
1515 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1517 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1518 ksmbd_debug(SMB, "authentication failed\n");
1524 * If session state is SMB2_SESSION_VALID, We can assume
1525 * that it is reauthentication. And the user/password
1526 * has been verified, so return it here.
1528 if (sess->state == SMB2_SESSION_VALID) {
1530 goto binding_session;
1534 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1535 (conn->sign || server_conf.enforced_signing)) ||
1536 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1539 if (smb3_encryption_negotiated(conn) &&
1540 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1541 rc = conn->ops->generate_encryptionkey(conn, sess);
1544 "SMB3 encryption key generation failed\n");
1548 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1549 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1551 * signing is disable if encryption is enable
1558 if (conn->dialect >= SMB30_PROT_ID) {
1559 chann = lookup_chann_list(sess, conn);
1561 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1566 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1570 if (conn->ops->generate_signingkey) {
1571 rc = conn->ops->generate_signingkey(sess, conn);
1573 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1578 if (!ksmbd_conn_lookup_dialect(conn)) {
1579 pr_err("fail to verify the dialect\n");
1585 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1586 static int krb5_authenticate(struct ksmbd_work *work,
1587 struct smb2_sess_setup_req *req,
1588 struct smb2_sess_setup_rsp *rsp)
1590 struct ksmbd_conn *conn = work->conn;
1591 struct ksmbd_session *sess = work->sess;
1592 char *in_blob, *out_blob;
1593 struct channel *chann = NULL;
1595 int in_len, out_len;
1598 in_blob = (char *)&req->hdr.ProtocolId +
1599 le16_to_cpu(req->SecurityBufferOffset);
1600 in_len = le16_to_cpu(req->SecurityBufferLength);
1601 out_blob = (char *)&rsp->hdr.ProtocolId +
1602 le16_to_cpu(rsp->SecurityBufferOffset);
1603 out_len = work->response_sz -
1604 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1606 /* Check previous session */
1607 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1608 if (prev_sess_id && prev_sess_id != sess->id)
1609 destroy_previous_session(conn, sess->user, prev_sess_id);
1611 if (sess->state == SMB2_SESSION_VALID)
1612 ksmbd_free_user(sess->user);
1614 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1615 out_blob, &out_len);
1617 ksmbd_debug(SMB, "krb5 authentication failed\n");
1620 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1622 if ((conn->sign || server_conf.enforced_signing) ||
1623 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1626 if (smb3_encryption_negotiated(conn)) {
1627 retval = conn->ops->generate_encryptionkey(conn, sess);
1630 "SMB3 encryption key generation failed\n");
1634 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1635 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1639 if (conn->dialect >= SMB30_PROT_ID) {
1640 chann = lookup_chann_list(sess, conn);
1642 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1647 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1651 if (conn->ops->generate_signingkey) {
1652 retval = conn->ops->generate_signingkey(sess, conn);
1654 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1659 if (!ksmbd_conn_lookup_dialect(conn)) {
1660 pr_err("fail to verify the dialect\n");
1666 static int krb5_authenticate(struct ksmbd_work *work,
1667 struct smb2_sess_setup_req *req,
1668 struct smb2_sess_setup_rsp *rsp)
1674 int smb2_sess_setup(struct ksmbd_work *work)
1676 struct ksmbd_conn *conn = work->conn;
1677 struct smb2_sess_setup_req *req;
1678 struct smb2_sess_setup_rsp *rsp;
1679 struct ksmbd_session *sess;
1680 struct negotiate_message *negblob;
1681 unsigned int negblob_len, negblob_off;
1684 ksmbd_debug(SMB, "Received request for session setup\n");
1686 WORK_BUFFERS(work, req, rsp);
1688 rsp->StructureSize = cpu_to_le16(9);
1689 rsp->SessionFlags = 0;
1690 rsp->SecurityBufferOffset = cpu_to_le16(72);
1691 rsp->SecurityBufferLength = 0;
1693 ksmbd_conn_lock(conn);
1694 if (!req->hdr.SessionId) {
1695 sess = ksmbd_smb2_session_create();
1700 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1701 rc = ksmbd_session_register(conn, sess);
1704 } else if (conn->dialect >= SMB30_PROT_ID &&
1705 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1706 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1707 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1709 sess = ksmbd_session_lookup_slowpath(sess_id);
1715 if (conn->dialect != sess->dialect) {
1720 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1725 if (strncmp(conn->ClientGUID, sess->ClientGUID,
1726 SMB2_CLIENT_GUID_SIZE)) {
1731 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1736 if (sess->state == SMB2_SESSION_EXPIRED) {
1741 if (ksmbd_conn_need_reconnect(conn)) {
1747 if (ksmbd_session_lookup(conn, sess_id)) {
1752 if (user_guest(sess->user)) {
1757 conn->binding = true;
1758 } else if ((conn->dialect < SMB30_PROT_ID ||
1759 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1760 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1765 sess = ksmbd_session_lookup(conn,
1766 le64_to_cpu(req->hdr.SessionId));
1772 if (sess->state == SMB2_SESSION_EXPIRED) {
1777 if (ksmbd_conn_need_reconnect(conn)) {
1785 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1786 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1787 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer)) {
1792 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1795 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1796 if (conn->mechToken) {
1797 negblob = (struct negotiate_message *)conn->mechToken;
1798 negblob_len = conn->mechTokenLen;
1802 if (negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1807 if (server_conf.auth_mechs & conn->auth_mechs) {
1808 rc = generate_preauth_hash(work);
1812 if (conn->preferred_auth_mech &
1813 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1814 rc = krb5_authenticate(work, req, rsp);
1820 if (!ksmbd_conn_need_reconnect(conn)) {
1821 ksmbd_conn_set_good(conn);
1822 sess->state = SMB2_SESSION_VALID;
1824 kfree(sess->Preauth_HashValue);
1825 sess->Preauth_HashValue = NULL;
1826 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1827 if (negblob->MessageType == NtLmNegotiate) {
1828 rc = ntlm_negotiate(work, negblob, negblob_len, rsp);
1832 STATUS_MORE_PROCESSING_REQUIRED;
1833 } else if (negblob->MessageType == NtLmAuthenticate) {
1834 rc = ntlm_authenticate(work, req, rsp);
1838 if (!ksmbd_conn_need_reconnect(conn)) {
1839 ksmbd_conn_set_good(conn);
1840 sess->state = SMB2_SESSION_VALID;
1842 if (conn->binding) {
1843 struct preauth_session *preauth_sess;
1846 ksmbd_preauth_session_lookup(conn, sess->id);
1848 list_del(&preauth_sess->preauth_entry);
1849 kfree(preauth_sess);
1852 kfree(sess->Preauth_HashValue);
1853 sess->Preauth_HashValue = NULL;
1855 pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
1856 le32_to_cpu(negblob->MessageType));
1860 /* TODO: need one more negotiation */
1861 pr_err("Not support the preferred authentication\n");
1865 pr_err("Not support authentication\n");
1871 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1872 else if (rc == -ENOENT)
1873 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1874 else if (rc == -EACCES)
1875 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1876 else if (rc == -EFAULT)
1877 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1878 else if (rc == -ENOMEM)
1879 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1880 else if (rc == -EOPNOTSUPP)
1881 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1883 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1885 if (conn->use_spnego && conn->mechToken) {
1886 kfree(conn->mechToken);
1887 conn->mechToken = NULL;
1892 * SecurityBufferOffset should be set to zero
1893 * in session setup error response.
1895 rsp->SecurityBufferOffset = 0;
1898 bool try_delay = false;
1901 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1902 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1903 * failure to make it harder to send enough random connection requests
1904 * to break into a server.
1906 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1909 sess->last_active = jiffies;
1910 sess->state = SMB2_SESSION_EXPIRED;
1912 ksmbd_conn_set_need_reconnect(conn);
1914 ksmbd_conn_set_need_negotiate(conn);
1917 smb2_set_err_rsp(work);
1919 unsigned int iov_len;
1921 if (rsp->SecurityBufferLength)
1922 iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) +
1923 le16_to_cpu(rsp->SecurityBufferLength);
1925 iov_len = sizeof(struct smb2_sess_setup_rsp);
1926 rc = ksmbd_iov_pin_rsp(work, rsp, iov_len);
1928 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1931 ksmbd_conn_unlock(conn);
1936 * smb2_tree_connect() - handler for smb2 tree connect command
1937 * @work: smb work containing smb request buffer
1939 * Return: 0 on success, otherwise error
1941 int smb2_tree_connect(struct ksmbd_work *work)
1943 struct ksmbd_conn *conn = work->conn;
1944 struct smb2_tree_connect_req *req;
1945 struct smb2_tree_connect_rsp *rsp;
1946 struct ksmbd_session *sess = work->sess;
1947 char *treename = NULL, *name = NULL;
1948 struct ksmbd_tree_conn_status status;
1949 struct ksmbd_share_config *share;
1952 WORK_BUFFERS(work, req, rsp);
1954 treename = smb_strndup_from_utf16(req->Buffer,
1955 le16_to_cpu(req->PathLength), true,
1957 if (IS_ERR(treename)) {
1958 pr_err("treename is NULL\n");
1959 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1963 name = ksmbd_extract_sharename(conn->um, treename);
1965 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1969 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1972 status = ksmbd_tree_conn_connect(conn, sess, name);
1973 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1974 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1978 share = status.tree_conn->share_conf;
1979 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1980 ksmbd_debug(SMB, "IPC share path request\n");
1981 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1982 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1983 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1984 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1985 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1986 FILE_SYNCHRONIZE_LE;
1988 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1989 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1990 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1991 if (test_tree_conn_flag(status.tree_conn,
1992 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1993 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1994 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1995 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1996 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1997 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1998 FILE_SYNCHRONIZE_LE;
2002 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
2003 if (conn->posix_ext_supported)
2004 status.tree_conn->posix_extensions = true;
2006 write_lock(&sess->tree_conns_lock);
2007 status.tree_conn->t_state = TREE_CONNECTED;
2008 write_unlock(&sess->tree_conns_lock);
2009 rsp->StructureSize = cpu_to_le16(16);
2011 rsp->Capabilities = 0;
2013 /* default manual caching */
2014 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
2016 rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
2018 status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
2020 if (!IS_ERR(treename))
2025 switch (status.ret) {
2026 case KSMBD_TREE_CONN_STATUS_OK:
2027 rsp->hdr.Status = STATUS_SUCCESS;
2032 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2033 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2036 case KSMBD_TREE_CONN_STATUS_NOMEM:
2037 rsp->hdr.Status = STATUS_NO_MEMORY;
2039 case KSMBD_TREE_CONN_STATUS_ERROR:
2040 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2041 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2042 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2045 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2048 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2051 if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2052 smb2_set_err_rsp(work);
2058 * smb2_create_open_flags() - convert smb open flags to unix open flags
2059 * @file_present: is file already present
2060 * @access: file access flags
2061 * @disposition: file disposition flags
2062 * @may_flags: set with MAY_ flags
2064 * Return: file open flags
2066 static int smb2_create_open_flags(bool file_present, __le32 access,
2070 int oflags = O_NONBLOCK | O_LARGEFILE;
2072 if (access & FILE_READ_DESIRED_ACCESS_LE &&
2073 access & FILE_WRITE_DESIRE_ACCESS_LE) {
2075 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2076 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2078 *may_flags = MAY_OPEN | MAY_WRITE;
2081 *may_flags = MAY_OPEN | MAY_READ;
2084 if (access == FILE_READ_ATTRIBUTES_LE)
2088 switch (disposition & FILE_CREATE_MASK_LE) {
2090 case FILE_CREATE_LE:
2092 case FILE_SUPERSEDE_LE:
2093 case FILE_OVERWRITE_LE:
2094 case FILE_OVERWRITE_IF_LE:
2101 switch (disposition & FILE_CREATE_MASK_LE) {
2102 case FILE_SUPERSEDE_LE:
2103 case FILE_CREATE_LE:
2104 case FILE_OPEN_IF_LE:
2105 case FILE_OVERWRITE_IF_LE:
2109 case FILE_OVERWRITE_LE:
2121 * smb2_tree_disconnect() - handler for smb tree connect request
2122 * @work: smb work containing request buffer
2126 int smb2_tree_disconnect(struct ksmbd_work *work)
2128 struct smb2_tree_disconnect_rsp *rsp;
2129 struct smb2_tree_disconnect_req *req;
2130 struct ksmbd_session *sess = work->sess;
2131 struct ksmbd_tree_connect *tcon = work->tcon;
2134 WORK_BUFFERS(work, req, rsp);
2136 ksmbd_debug(SMB, "request\n");
2139 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2141 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2146 ksmbd_close_tree_conn_fds(work);
2148 write_lock(&sess->tree_conns_lock);
2149 if (tcon->t_state == TREE_DISCONNECTED) {
2150 write_unlock(&sess->tree_conns_lock);
2151 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2156 WARN_ON_ONCE(atomic_dec_and_test(&tcon->refcount));
2157 tcon->t_state = TREE_DISCONNECTED;
2158 write_unlock(&sess->tree_conns_lock);
2160 err = ksmbd_tree_conn_disconnect(sess, tcon);
2162 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2168 rsp->StructureSize = cpu_to_le16(4);
2169 err = ksmbd_iov_pin_rsp(work, rsp,
2170 sizeof(struct smb2_tree_disconnect_rsp));
2172 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2179 smb2_set_err_rsp(work);
2185 * smb2_session_logoff() - handler for session log off request
2186 * @work: smb work containing request buffer
2190 int smb2_session_logoff(struct ksmbd_work *work)
2192 struct ksmbd_conn *conn = work->conn;
2193 struct smb2_logoff_req *req;
2194 struct smb2_logoff_rsp *rsp;
2195 struct ksmbd_session *sess;
2199 WORK_BUFFERS(work, req, rsp);
2201 ksmbd_debug(SMB, "request\n");
2203 ksmbd_conn_lock(conn);
2204 if (!ksmbd_conn_good(conn)) {
2205 ksmbd_conn_unlock(conn);
2206 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2207 smb2_set_err_rsp(work);
2210 sess_id = le64_to_cpu(req->hdr.SessionId);
2211 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
2212 ksmbd_conn_unlock(conn);
2214 ksmbd_close_session_fds(work);
2215 ksmbd_conn_wait_idle(conn, sess_id);
2218 * Re-lookup session to validate if session is deleted
2219 * while waiting request complete
2221 sess = ksmbd_session_lookup_all(conn, sess_id);
2222 if (ksmbd_tree_conn_session_logoff(sess)) {
2223 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2224 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2225 smb2_set_err_rsp(work);
2229 ksmbd_destroy_file_table(&sess->file_table);
2230 sess->state = SMB2_SESSION_EXPIRED;
2232 ksmbd_free_user(sess->user);
2234 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_NEGOTIATE);
2236 rsp->StructureSize = cpu_to_le16(4);
2237 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
2239 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2240 smb2_set_err_rsp(work);
2247 * create_smb2_pipe() - create IPC pipe
2248 * @work: smb work containing request buffer
2250 * Return: 0 on success, otherwise error
2252 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2254 struct smb2_create_rsp *rsp;
2255 struct smb2_create_req *req;
2260 WORK_BUFFERS(work, req, rsp);
2262 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2263 1, work->conn->local_nls);
2265 rsp->hdr.Status = STATUS_NO_MEMORY;
2266 err = PTR_ERR(name);
2270 id = ksmbd_session_rpc_open(work->sess, name);
2272 pr_err("Unable to open RPC pipe: %d\n", id);
2277 rsp->hdr.Status = STATUS_SUCCESS;
2278 rsp->StructureSize = cpu_to_le16(89);
2279 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2281 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2283 rsp->CreationTime = cpu_to_le64(0);
2284 rsp->LastAccessTime = cpu_to_le64(0);
2285 rsp->ChangeTime = cpu_to_le64(0);
2286 rsp->AllocationSize = cpu_to_le64(0);
2287 rsp->EndofFile = cpu_to_le64(0);
2288 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2290 rsp->VolatileFileId = id;
2291 rsp->PersistentFileId = 0;
2292 rsp->CreateContextsOffset = 0;
2293 rsp->CreateContextsLength = 0;
2295 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
2305 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2309 rsp->hdr.Status = STATUS_NO_MEMORY;
2316 smb2_set_err_rsp(work);
2321 * smb2_set_ea() - handler for setting extended attributes using set
2323 * @eabuf: set info command buffer
2324 * @buf_len: set info command buffer length
2325 * @path: dentry path for get ea
2326 * @get_write: get write access to a mount
2328 * Return: 0 on success, otherwise error
2330 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2331 const struct path *path, bool get_write)
2333 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2334 char *attr_name = NULL, *value;
2336 unsigned int next = 0;
2338 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2339 le16_to_cpu(eabuf->EaValueLength))
2342 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2347 if (!eabuf->EaNameLength)
2351 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2352 eabuf->name, eabuf->EaNameLength,
2353 le16_to_cpu(eabuf->EaValueLength),
2354 le32_to_cpu(eabuf->NextEntryOffset));
2356 if (eabuf->EaNameLength >
2357 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2362 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2363 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2364 eabuf->EaNameLength);
2365 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2366 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2368 if (!eabuf->EaValueLength) {
2369 rc = ksmbd_vfs_casexattr_len(idmap,
2372 XATTR_USER_PREFIX_LEN +
2373 eabuf->EaNameLength);
2375 /* delete the EA only when it exits */
2377 rc = ksmbd_vfs_remove_xattr(idmap,
2383 "remove xattr failed(%d)\n",
2389 /* if the EA doesn't exist, just do nothing. */
2392 rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
2393 le16_to_cpu(eabuf->EaValueLength),
2397 "ksmbd_vfs_setxattr is failed(%d)\n",
2404 next = le32_to_cpu(eabuf->NextEntryOffset);
2405 if (next == 0 || buf_len < next)
2408 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2409 if (buf_len < sizeof(struct smb2_ea_info)) {
2414 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2415 le16_to_cpu(eabuf->EaValueLength)) {
2419 } while (next != 0);
2425 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2426 struct ksmbd_file *fp,
2427 char *stream_name, int s_type)
2429 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2430 size_t xattr_stream_size;
2431 char *xattr_stream_name;
2434 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2441 fp->stream.name = xattr_stream_name;
2442 fp->stream.size = xattr_stream_size;
2444 /* Check if there is stream prefix in xattr space */
2445 rc = ksmbd_vfs_casexattr_len(idmap,
2452 if (fp->cdoption == FILE_OPEN_LE) {
2453 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2457 rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0, false);
2459 pr_err("Failed to store XATTR stream name :%d\n", rc);
2463 static int smb2_remove_smb_xattrs(const struct path *path)
2465 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2466 char *name, *xattr_list = NULL;
2467 ssize_t xattr_list_len;
2470 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2471 if (xattr_list_len < 0) {
2473 } else if (!xattr_list_len) {
2474 ksmbd_debug(SMB, "empty xattr in the file\n");
2478 for (name = xattr_list; name - xattr_list < xattr_list_len;
2479 name += strlen(name) + 1) {
2480 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2482 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2483 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2484 STREAM_PREFIX_LEN)) {
2485 err = ksmbd_vfs_remove_xattr(idmap, path,
2488 ksmbd_debug(SMB, "remove xattr failed : %s\n",
2497 static int smb2_create_truncate(const struct path *path)
2499 int rc = vfs_truncate(path, 0);
2502 pr_err("vfs_truncate failed, rc %d\n", rc);
2506 rc = smb2_remove_smb_xattrs(path);
2507 if (rc == -EOPNOTSUPP)
2511 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2516 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2517 struct ksmbd_file *fp)
2519 struct xattr_dos_attrib da = {0};
2522 if (!test_share_config_flag(tcon->share_conf,
2523 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2527 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2528 da.itime = da.create_time = fp->create_time;
2529 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2530 XATTR_DOSINFO_ITIME;
2532 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da, false);
2534 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2537 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2538 const struct path *path, struct ksmbd_file *fp)
2540 struct xattr_dos_attrib da;
2543 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2545 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2546 if (!test_share_config_flag(tcon->share_conf,
2547 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2550 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
2553 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2554 fp->create_time = da.create_time;
2555 fp->itime = da.itime;
2559 static int smb2_creat(struct ksmbd_work *work, struct path *parent_path,
2560 struct path *path, char *name, int open_flags,
2561 umode_t posix_mode, bool is_dir)
2563 struct ksmbd_tree_connect *tcon = work->tcon;
2564 struct ksmbd_share_config *share = tcon->share_conf;
2568 if (!(open_flags & O_CREAT))
2571 ksmbd_debug(SMB, "file does not exist, so creating\n");
2572 if (is_dir == true) {
2573 ksmbd_debug(SMB, "creating directory\n");
2575 mode = share_config_directory_mode(share, posix_mode);
2576 rc = ksmbd_vfs_mkdir(work, name, mode);
2580 ksmbd_debug(SMB, "creating regular file\n");
2582 mode = share_config_create_mode(share, posix_mode);
2583 rc = ksmbd_vfs_create(work, name, mode);
2588 rc = ksmbd_vfs_kern_path_locked(work, name, 0, parent_path, path, 0);
2590 pr_err("cannot get linux path (%s), err = %d\n",
2597 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2598 struct smb2_create_req *req,
2599 const struct path *path)
2601 struct create_context *context;
2602 struct create_sd_buf_req *sd_buf;
2604 if (!req->CreateContextsOffset)
2607 /* Parse SD BUFFER create contexts */
2608 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2611 else if (IS_ERR(context))
2612 return PTR_ERR(context);
2615 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2616 sd_buf = (struct create_sd_buf_req *)context;
2617 if (le16_to_cpu(context->DataOffset) +
2618 le32_to_cpu(context->DataLength) <
2619 sizeof(struct create_sd_buf_req))
2621 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2622 le32_to_cpu(sd_buf->ccontext.DataLength), true, false);
2625 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2626 struct mnt_idmap *idmap,
2627 struct inode *inode)
2629 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2630 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2632 fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2633 fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2634 fattr->cf_mode = inode->i_mode;
2635 fattr->cf_acls = NULL;
2636 fattr->cf_dacls = NULL;
2638 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2639 fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
2640 if (S_ISDIR(inode->i_mode))
2641 fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
2646 * smb2_open() - handler for smb file open request
2647 * @work: smb work containing request buffer
2649 * Return: 0 on success, otherwise error
2651 int smb2_open(struct ksmbd_work *work)
2653 struct ksmbd_conn *conn = work->conn;
2654 struct ksmbd_session *sess = work->sess;
2655 struct ksmbd_tree_connect *tcon = work->tcon;
2656 struct smb2_create_req *req;
2657 struct smb2_create_rsp *rsp;
2658 struct path path, parent_path;
2659 struct ksmbd_share_config *share = tcon->share_conf;
2660 struct ksmbd_file *fp = NULL;
2661 struct file *filp = NULL;
2662 struct mnt_idmap *idmap = NULL;
2664 struct create_context *context;
2665 struct lease_ctx_info *lc = NULL;
2666 struct create_ea_buf_req *ea_buf = NULL;
2667 struct oplock_info *opinfo;
2668 __le32 *next_ptr = NULL;
2669 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2671 int contxt_cnt = 0, query_disk_id = 0;
2672 int maximal_access_ctxt = 0, posix_ctxt = 0;
2676 char *stream_name = NULL;
2677 bool file_present = false, created = false, already_permitted = false;
2678 int share_ret, need_truncate = 0;
2680 umode_t posix_mode = 0;
2681 __le32 daccess, maximal_access = 0;
2684 WORK_BUFFERS(work, req, rsp);
2686 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2687 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2688 ksmbd_debug(SMB, "invalid flag in chained command\n");
2689 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2690 smb2_set_err_rsp(work);
2694 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2695 ksmbd_debug(SMB, "IPC pipe create request\n");
2696 return create_smb2_pipe(work);
2699 if (req->NameLength) {
2700 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2701 *(char *)req->Buffer == '\\') {
2702 pr_err("not allow directory name included leading slash\n");
2707 name = smb2_get_name(req->Buffer,
2708 le16_to_cpu(req->NameLength),
2709 work->conn->local_nls);
2718 ksmbd_debug(SMB, "converted name = %s\n", name);
2719 if (strchr(name, ':')) {
2720 if (!test_share_config_flag(work->tcon->share_conf,
2721 KSMBD_SHARE_FLAG_STREAMS)) {
2725 rc = parse_stream_name(name, &stream_name, &s_type);
2730 rc = ksmbd_validate_filename(name);
2734 if (ksmbd_share_veto_filename(share, name)) {
2736 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2741 name = kstrdup("", GFP_KERNEL);
2748 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2749 pr_err("Invalid impersonationlevel : 0x%x\n",
2750 le32_to_cpu(req->ImpersonationLevel));
2752 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2756 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2757 pr_err("Invalid create options : 0x%x\n",
2758 le32_to_cpu(req->CreateOptions));
2762 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2763 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2764 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2766 if (req->CreateOptions &
2767 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2768 FILE_RESERVE_OPFILTER_LE)) {
2773 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2774 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2777 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2778 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2783 if (le32_to_cpu(req->CreateDisposition) >
2784 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2785 pr_err("Invalid create disposition : 0x%x\n",
2786 le32_to_cpu(req->CreateDisposition));
2791 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2792 pr_err("Invalid desired access : 0x%x\n",
2793 le32_to_cpu(req->DesiredAccess));
2798 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2799 pr_err("Invalid file attribute : 0x%x\n",
2800 le32_to_cpu(req->FileAttributes));
2805 if (req->CreateContextsOffset) {
2806 /* Parse non-durable handle create contexts */
2807 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
2808 if (IS_ERR(context)) {
2809 rc = PTR_ERR(context);
2811 } else if (context) {
2812 ea_buf = (struct create_ea_buf_req *)context;
2813 if (le16_to_cpu(context->DataOffset) +
2814 le32_to_cpu(context->DataLength) <
2815 sizeof(struct create_ea_buf_req)) {
2819 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2820 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2826 context = smb2_find_context_vals(req,
2827 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
2828 if (IS_ERR(context)) {
2829 rc = PTR_ERR(context);
2831 } else if (context) {
2833 "get query maximal access context\n");
2834 maximal_access_ctxt = 1;
2837 context = smb2_find_context_vals(req,
2838 SMB2_CREATE_TIMEWARP_REQUEST, 4);
2839 if (IS_ERR(context)) {
2840 rc = PTR_ERR(context);
2842 } else if (context) {
2843 ksmbd_debug(SMB, "get timewarp context\n");
2848 if (tcon->posix_extensions) {
2849 context = smb2_find_context_vals(req,
2850 SMB2_CREATE_TAG_POSIX, 16);
2851 if (IS_ERR(context)) {
2852 rc = PTR_ERR(context);
2854 } else if (context) {
2855 struct create_posix *posix =
2856 (struct create_posix *)context;
2857 if (le16_to_cpu(context->DataOffset) +
2858 le32_to_cpu(context->DataLength) <
2859 sizeof(struct create_posix) - 4) {
2863 ksmbd_debug(SMB, "get posix context\n");
2865 posix_mode = le32_to_cpu(posix->Mode);
2871 if (ksmbd_override_fsids(work)) {
2876 rc = ksmbd_vfs_kern_path_locked(work, name, LOOKUP_NO_SYMLINKS,
2877 &parent_path, &path, 1);
2879 file_present = true;
2881 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2883 * If file exists with under flags, return access
2886 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2887 req->CreateDisposition == FILE_OPEN_IF_LE) {
2892 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2894 "User does not have write permission\n");
2898 } else if (d_is_symlink(path.dentry)) {
2903 file_present = true;
2904 idmap = mnt_idmap(path.mnt);
2908 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2914 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2915 if (s_type == DATA_STREAM) {
2917 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2920 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
2921 s_type == DATA_STREAM) {
2923 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2927 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2928 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2929 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2937 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2938 S_ISDIR(d_inode(path.dentry)->i_mode) &&
2939 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2940 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2941 name, req->CreateOptions);
2942 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2947 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2948 !(req->CreateDisposition == FILE_CREATE_LE) &&
2949 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
2950 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2955 if (!stream_name && file_present &&
2956 req->CreateDisposition == FILE_CREATE_LE) {
2961 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2963 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2964 rc = smb_check_perm_dacl(conn, &path, &daccess,
2970 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2971 if (!file_present) {
2972 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2974 ksmbd_vfs_query_maximal_access(idmap,
2977 already_permitted = true;
2979 maximal_access = daccess;
2982 open_flags = smb2_create_open_flags(file_present, daccess,
2983 req->CreateDisposition,
2986 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2987 if (open_flags & (O_CREAT | O_TRUNC)) {
2989 "User does not have write permission\n");
2995 /*create file if not present */
2996 if (!file_present) {
2997 rc = smb2_creat(work, &parent_path, &path, name, open_flags,
2999 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
3001 if (rc == -ENOENT) {
3003 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
3009 idmap = mnt_idmap(path.mnt);
3011 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
3012 sizeof(struct smb2_ea_info)) {
3017 rc = smb2_set_ea(&ea_buf->ea,
3018 le32_to_cpu(ea_buf->ccontext.DataLength),
3020 if (rc == -EOPNOTSUPP)
3025 } else if (!already_permitted) {
3026 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
3027 * because execute(search) permission on a parent directory,
3028 * is already granted.
3030 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
3031 rc = inode_permission(idmap,
3032 d_inode(path.dentry),
3037 if ((daccess & FILE_DELETE_LE) ||
3038 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3039 rc = inode_permission(idmap,
3040 d_inode(path.dentry->d_parent),
3041 MAY_EXEC | MAY_WRITE);
3048 rc = ksmbd_query_inode_status(path.dentry->d_parent);
3049 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
3055 filp = dentry_open(&path, open_flags, current_cred());
3058 pr_err("dentry open for dir failed, rc %d\n", rc);
3063 if (!(open_flags & O_TRUNC))
3064 file_info = FILE_OPENED;
3066 file_info = FILE_OVERWRITTEN;
3068 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
3070 file_info = FILE_SUPERSEDED;
3071 } else if (open_flags & O_CREAT) {
3072 file_info = FILE_CREATED;
3075 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
3077 /* Obtain Volatile-ID */
3078 fp = ksmbd_open_fd(work, filp);
3086 /* Get Persistent-ID */
3087 ksmbd_open_durable_fd(fp);
3088 if (!has_file_id(fp->persistent_id)) {
3093 fp->cdoption = req->CreateDisposition;
3094 fp->daccess = daccess;
3095 fp->saccess = req->ShareAccess;
3096 fp->coption = req->CreateOptions;
3098 /* Set default windows and posix acls if creating new file */
3101 struct inode *inode = d_inode(path.dentry);
3103 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
3105 d_inode(path.dentry->d_parent));
3107 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3109 if (test_share_config_flag(work->tcon->share_conf,
3110 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3111 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3116 rc = smb2_create_sd_buffer(work, req, &path);
3119 ksmbd_vfs_set_init_posix_acl(idmap,
3122 if (test_share_config_flag(work->tcon->share_conf,
3123 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3124 struct smb_fattr fattr;
3125 struct smb_ntsd *pntsd;
3126 int pntsd_size, ace_num = 0;
3128 ksmbd_acls_fattr(&fattr, idmap, inode);
3130 ace_num = fattr.cf_acls->a_count;
3132 ace_num += fattr.cf_dacls->a_count;
3134 pntsd = kmalloc(sizeof(struct smb_ntsd) +
3135 sizeof(struct smb_sid) * 3 +
3136 sizeof(struct smb_acl) +
3137 sizeof(struct smb_ace) * ace_num * 2,
3140 posix_acl_release(fattr.cf_acls);
3141 posix_acl_release(fattr.cf_dacls);
3145 rc = build_sec_desc(idmap,
3150 &pntsd_size, &fattr);
3151 posix_acl_release(fattr.cf_acls);
3152 posix_acl_release(fattr.cf_dacls);
3158 rc = ksmbd_vfs_set_sd_xattr(conn,
3166 pr_err("failed to store ntacl in xattr : %d\n",
3175 rc = smb2_set_stream_name_xattr(&path,
3181 file_info = FILE_CREATED;
3184 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3185 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3187 /* fp should be searchable through ksmbd_inode.m_fp_list
3188 * after daccess, saccess, attrib_only, and stream are
3191 write_lock(&fp->f_ci->m_lock);
3192 list_add(&fp->node, &fp->f_ci->m_fp_list);
3193 write_unlock(&fp->f_ci->m_lock);
3195 /* Check delete pending among previous fp before oplock break */
3196 if (ksmbd_inode_pending_delete(fp)) {
3201 rc = ksmbd_vfs_getattr(&path, &stat);
3205 if (stat.result_mask & STATX_BTIME)
3206 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3208 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3209 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3211 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3214 smb2_update_xattrs(tcon, &path, fp);
3216 smb2_new_xattrs(tcon, &path, fp);
3218 if (file_present || created)
3219 ksmbd_vfs_kern_path_unlock(&parent_path, &path);
3221 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3222 !fp->attrib_only && !stream_name) {
3223 smb_break_all_oplock(work, fp);
3227 req_op_level = req->RequestedOplockLevel;
3228 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
3229 lc = parse_lease_state(req, S_ISDIR(file_inode(filp)->i_mode));
3231 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3232 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3233 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3234 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3235 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3240 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3242 * Compare parent lease using parent key. If there is no
3243 * a lease that has same parent key, Send lease break
3246 smb_send_parent_lease_break_noti(fp, lc);
3248 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3250 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3251 name, req_op_level, lc->req_state);
3252 rc = find_same_lease_key(sess, fp->f_ci, lc);
3255 } else if (open_flags == O_RDONLY &&
3256 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3257 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3258 req_op_level = SMB2_OPLOCK_LEVEL_II;
3260 rc = smb_grant_oplock(work, req_op_level,
3261 fp->persistent_id, fp,
3262 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3268 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3269 ksmbd_fd_set_delete_on_close(fp, file_info);
3271 if (need_truncate) {
3272 rc = smb2_create_truncate(&fp->filp->f_path);
3277 if (req->CreateContextsOffset) {
3278 struct create_alloc_size_req *az_req;
3280 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3281 SMB2_CREATE_ALLOCATION_SIZE, 4);
3282 if (IS_ERR(az_req)) {
3283 rc = PTR_ERR(az_req);
3285 } else if (az_req) {
3289 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3290 le32_to_cpu(az_req->ccontext.DataLength) <
3291 sizeof(struct create_alloc_size_req)) {
3295 alloc_size = le64_to_cpu(az_req->AllocationSize);
3297 "request smb2 create allocate size : %llu\n",
3299 smb_break_all_levII_oplock(work, fp, 1);
3300 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3304 "vfs_fallocate is failed : %d\n",
3308 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3309 if (IS_ERR(context)) {
3310 rc = PTR_ERR(context);
3312 } else if (context) {
3313 ksmbd_debug(SMB, "get query on disk id context\n");
3318 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3320 rsp->StructureSize = cpu_to_le16(89);
3322 opinfo = rcu_dereference(fp->f_opinfo);
3323 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3326 rsp->CreateAction = cpu_to_le32(file_info);
3327 rsp->CreationTime = cpu_to_le64(fp->create_time);
3328 time = ksmbd_UnixTimeToNT(stat.atime);
3329 rsp->LastAccessTime = cpu_to_le64(time);
3330 time = ksmbd_UnixTimeToNT(stat.mtime);
3331 rsp->LastWriteTime = cpu_to_le64(time);
3332 time = ksmbd_UnixTimeToNT(stat.ctime);
3333 rsp->ChangeTime = cpu_to_le64(time);
3334 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3335 cpu_to_le64(stat.blocks << 9);
3336 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3337 rsp->FileAttributes = fp->f_ci->m_fattr;
3341 rsp->PersistentFileId = fp->persistent_id;
3342 rsp->VolatileFileId = fp->volatile_id;
3344 rsp->CreateContextsOffset = 0;
3345 rsp->CreateContextsLength = 0;
3346 iov_len = offsetof(struct smb2_create_rsp, Buffer);
3348 /* If lease is request send lease context response */
3349 if (opinfo && opinfo->is_lease) {
3350 struct create_context *lease_ccontext;
3352 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3353 name, opinfo->o_lease->state);
3354 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3356 lease_ccontext = (struct create_context *)rsp->Buffer;
3358 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3359 le32_add_cpu(&rsp->CreateContextsLength,
3360 conn->vals->create_lease_size);
3361 iov_len += conn->vals->create_lease_size;
3362 next_ptr = &lease_ccontext->Next;
3363 next_off = conn->vals->create_lease_size;
3366 if (maximal_access_ctxt) {
3367 struct create_context *mxac_ccontext;
3369 if (maximal_access == 0)
3370 ksmbd_vfs_query_maximal_access(idmap,
3373 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3374 le32_to_cpu(rsp->CreateContextsLength));
3376 create_mxac_rsp_buf(rsp->Buffer +
3377 le32_to_cpu(rsp->CreateContextsLength),
3378 le32_to_cpu(maximal_access));
3379 le32_add_cpu(&rsp->CreateContextsLength,
3380 conn->vals->create_mxac_size);
3381 iov_len += conn->vals->create_mxac_size;
3383 *next_ptr = cpu_to_le32(next_off);
3384 next_ptr = &mxac_ccontext->Next;
3385 next_off = conn->vals->create_mxac_size;
3388 if (query_disk_id) {
3389 struct create_context *disk_id_ccontext;
3391 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3392 le32_to_cpu(rsp->CreateContextsLength));
3394 create_disk_id_rsp_buf(rsp->Buffer +
3395 le32_to_cpu(rsp->CreateContextsLength),
3396 stat.ino, tcon->id);
3397 le32_add_cpu(&rsp->CreateContextsLength,
3398 conn->vals->create_disk_id_size);
3399 iov_len += conn->vals->create_disk_id_size;
3401 *next_ptr = cpu_to_le32(next_off);
3402 next_ptr = &disk_id_ccontext->Next;
3403 next_off = conn->vals->create_disk_id_size;
3408 create_posix_rsp_buf(rsp->Buffer +
3409 le32_to_cpu(rsp->CreateContextsLength),
3411 le32_add_cpu(&rsp->CreateContextsLength,
3412 conn->vals->create_posix_size);
3413 iov_len += conn->vals->create_posix_size;
3415 *next_ptr = cpu_to_le32(next_off);
3418 if (contxt_cnt > 0) {
3419 rsp->CreateContextsOffset =
3420 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3424 if (rc && (file_present || created))
3425 ksmbd_vfs_kern_path_unlock(&parent_path, &path);
3428 ksmbd_revert_fsids(work);
3432 ksmbd_update_fstate(&work->sess->file_table, fp, FP_INITED);
3433 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
3437 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3438 else if (rc == -EOPNOTSUPP)
3439 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3440 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3441 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3442 else if (rc == -ENOENT)
3443 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3444 else if (rc == -EPERM)
3445 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3446 else if (rc == -EBUSY)
3447 rsp->hdr.Status = STATUS_DELETE_PENDING;
3448 else if (rc == -EBADF)
3449 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3450 else if (rc == -ENOEXEC)
3451 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3452 else if (rc == -ENXIO)
3453 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3454 else if (rc == -EEXIST)
3455 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3456 else if (rc == -EMFILE)
3457 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3458 if (!rsp->hdr.Status)
3459 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3462 ksmbd_fd_put(work, fp);
3463 smb2_set_err_rsp(work);
3464 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3473 static int readdir_info_level_struct_sz(int info_level)
3475 switch (info_level) {
3476 case FILE_FULL_DIRECTORY_INFORMATION:
3477 return sizeof(struct file_full_directory_info);
3478 case FILE_BOTH_DIRECTORY_INFORMATION:
3479 return sizeof(struct file_both_directory_info);
3480 case FILE_DIRECTORY_INFORMATION:
3481 return sizeof(struct file_directory_info);
3482 case FILE_NAMES_INFORMATION:
3483 return sizeof(struct file_names_info);
3484 case FILEID_FULL_DIRECTORY_INFORMATION:
3485 return sizeof(struct file_id_full_dir_info);
3486 case FILEID_BOTH_DIRECTORY_INFORMATION:
3487 return sizeof(struct file_id_both_directory_info);
3488 case SMB_FIND_FILE_POSIX_INFO:
3489 return sizeof(struct smb2_posix_info);
3495 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3497 switch (info_level) {
3498 case FILE_FULL_DIRECTORY_INFORMATION:
3500 struct file_full_directory_info *ffdinfo;
3502 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3503 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3504 d_info->name = ffdinfo->FileName;
3505 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3508 case FILE_BOTH_DIRECTORY_INFORMATION:
3510 struct file_both_directory_info *fbdinfo;
3512 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3513 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3514 d_info->name = fbdinfo->FileName;
3515 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3518 case FILE_DIRECTORY_INFORMATION:
3520 struct file_directory_info *fdinfo;
3522 fdinfo = (struct file_directory_info *)d_info->rptr;
3523 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3524 d_info->name = fdinfo->FileName;
3525 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3528 case FILE_NAMES_INFORMATION:
3530 struct file_names_info *fninfo;
3532 fninfo = (struct file_names_info *)d_info->rptr;
3533 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3534 d_info->name = fninfo->FileName;
3535 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3538 case FILEID_FULL_DIRECTORY_INFORMATION:
3540 struct file_id_full_dir_info *dinfo;
3542 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3543 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3544 d_info->name = dinfo->FileName;
3545 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3548 case FILEID_BOTH_DIRECTORY_INFORMATION:
3550 struct file_id_both_directory_info *fibdinfo;
3552 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3553 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3554 d_info->name = fibdinfo->FileName;
3555 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3558 case SMB_FIND_FILE_POSIX_INFO:
3560 struct smb2_posix_info *posix_info;
3562 posix_info = (struct smb2_posix_info *)d_info->rptr;
3563 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3564 d_info->name = posix_info->name;
3565 d_info->name_len = le32_to_cpu(posix_info->name_len);
3574 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3576 * @conn: connection instance
3577 * @info_level: smb information level
3578 * @d_info: structure included variables for query dir
3579 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3581 * if directory has many entries, find first can't read it fully.
3582 * find next might be called multiple times to read remaining dir entries
3584 * Return: 0 on success, otherwise error
3586 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3587 struct ksmbd_dir_info *d_info,
3588 struct ksmbd_kstat *ksmbd_kstat)
3590 int next_entry_offset = 0;
3594 int struct_sz, rc = 0;
3596 conv_name = ksmbd_convert_dir_info_name(d_info,
3602 /* Somehow the name has only terminating NULL bytes */
3605 goto free_conv_name;
3608 struct_sz = readdir_info_level_struct_sz(info_level) + conv_len;
3609 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3610 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3612 if (next_entry_offset > d_info->out_buf_len) {
3613 d_info->out_buf_len = 0;
3615 goto free_conv_name;
3618 kstat = d_info->wptr;
3619 if (info_level != FILE_NAMES_INFORMATION)
3620 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3622 switch (info_level) {
3623 case FILE_FULL_DIRECTORY_INFORMATION:
3625 struct file_full_directory_info *ffdinfo;
3627 ffdinfo = (struct file_full_directory_info *)kstat;
3628 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3630 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3631 if (ffdinfo->EaSize)
3632 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3633 if (d_info->hide_dot_file && d_info->name[0] == '.')
3634 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3635 memcpy(ffdinfo->FileName, conv_name, conv_len);
3636 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3639 case FILE_BOTH_DIRECTORY_INFORMATION:
3641 struct file_both_directory_info *fbdinfo;
3643 fbdinfo = (struct file_both_directory_info *)kstat;
3644 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3646 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3647 if (fbdinfo->EaSize)
3648 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3649 fbdinfo->ShortNameLength = 0;
3650 fbdinfo->Reserved = 0;
3651 if (d_info->hide_dot_file && d_info->name[0] == '.')
3652 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3653 memcpy(fbdinfo->FileName, conv_name, conv_len);
3654 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3657 case FILE_DIRECTORY_INFORMATION:
3659 struct file_directory_info *fdinfo;
3661 fdinfo = (struct file_directory_info *)kstat;
3662 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3663 if (d_info->hide_dot_file && d_info->name[0] == '.')
3664 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3665 memcpy(fdinfo->FileName, conv_name, conv_len);
3666 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3669 case FILE_NAMES_INFORMATION:
3671 struct file_names_info *fninfo;
3673 fninfo = (struct file_names_info *)kstat;
3674 fninfo->FileNameLength = cpu_to_le32(conv_len);
3675 memcpy(fninfo->FileName, conv_name, conv_len);
3676 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3679 case FILEID_FULL_DIRECTORY_INFORMATION:
3681 struct file_id_full_dir_info *dinfo;
3683 dinfo = (struct file_id_full_dir_info *)kstat;
3684 dinfo->FileNameLength = cpu_to_le32(conv_len);
3686 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3688 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3689 dinfo->Reserved = 0;
3690 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3691 if (d_info->hide_dot_file && d_info->name[0] == '.')
3692 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3693 memcpy(dinfo->FileName, conv_name, conv_len);
3694 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3697 case FILEID_BOTH_DIRECTORY_INFORMATION:
3699 struct file_id_both_directory_info *fibdinfo;
3701 fibdinfo = (struct file_id_both_directory_info *)kstat;
3702 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3704 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3705 if (fibdinfo->EaSize)
3706 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3707 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3708 fibdinfo->ShortNameLength = 0;
3709 fibdinfo->Reserved = 0;
3710 fibdinfo->Reserved2 = cpu_to_le16(0);
3711 if (d_info->hide_dot_file && d_info->name[0] == '.')
3712 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3713 memcpy(fibdinfo->FileName, conv_name, conv_len);
3714 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3717 case SMB_FIND_FILE_POSIX_INFO:
3719 struct smb2_posix_info *posix_info;
3722 posix_info = (struct smb2_posix_info *)kstat;
3723 posix_info->Ignored = 0;
3724 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3725 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3726 posix_info->ChangeTime = cpu_to_le64(time);
3727 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3728 posix_info->LastAccessTime = cpu_to_le64(time);
3729 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3730 posix_info->LastWriteTime = cpu_to_le64(time);
3731 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3732 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3733 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3734 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3735 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
3736 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3737 posix_info->DosAttributes =
3738 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3739 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3740 if (d_info->hide_dot_file && d_info->name[0] == '.')
3741 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3743 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
3744 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
3745 * sub_auth(4 * 1(num_subauth)) + RID(4).
3747 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3748 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3749 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3750 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
3751 memcpy(posix_info->name, conv_name, conv_len);
3752 posix_info->name_len = cpu_to_le32(conv_len);
3753 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3757 } /* switch (info_level) */
3759 d_info->last_entry_offset = d_info->data_count;
3760 d_info->data_count += next_entry_offset;
3761 d_info->out_buf_len -= next_entry_offset;
3762 d_info->wptr += next_entry_offset;
3765 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3766 info_level, d_info->out_buf_len,
3767 next_entry_offset, d_info->data_count);
3774 struct smb2_query_dir_private {
3775 struct ksmbd_work *work;
3776 char *search_pattern;
3777 struct ksmbd_file *dir_fp;
3779 struct ksmbd_dir_info *d_info;
3783 static void lock_dir(struct ksmbd_file *dir_fp)
3785 struct dentry *dir = dir_fp->filp->f_path.dentry;
3787 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3790 static void unlock_dir(struct ksmbd_file *dir_fp)
3792 struct dentry *dir = dir_fp->filp->f_path.dentry;
3794 inode_unlock(d_inode(dir));
3797 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3799 struct mnt_idmap *idmap = file_mnt_idmap(priv->dir_fp->filp);
3801 struct ksmbd_kstat ksmbd_kstat;
3805 for (i = 0; i < priv->d_info->num_entry; i++) {
3806 struct dentry *dent;
3808 if (dentry_name(priv->d_info, priv->info_level))
3811 lock_dir(priv->dir_fp);
3812 dent = lookup_one(idmap, priv->d_info->name,
3813 priv->dir_fp->filp->f_path.dentry,
3814 priv->d_info->name_len);
3815 unlock_dir(priv->dir_fp);
3818 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3823 if (unlikely(d_is_negative(dent))) {
3825 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3826 priv->d_info->name);
3830 ksmbd_kstat.kstat = &kstat;
3831 if (priv->info_level != FILE_NAMES_INFORMATION)
3832 ksmbd_vfs_fill_dentry_attrs(priv->work,
3837 rc = smb2_populate_readdir_entry(priv->work->conn,
3848 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3853 int next_entry_offset;
3855 struct_sz = readdir_info_level_struct_sz(info_level);
3856 if (struct_sz == -EOPNOTSUPP)
3859 conv_len = (d_info->name_len + 1) * 2;
3860 next_entry_offset = ALIGN(struct_sz + conv_len,
3861 KSMBD_DIR_INFO_ALIGNMENT);
3863 if (next_entry_offset > d_info->out_buf_len) {
3864 d_info->out_buf_len = 0;
3868 switch (info_level) {
3869 case FILE_FULL_DIRECTORY_INFORMATION:
3871 struct file_full_directory_info *ffdinfo;
3873 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3874 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3875 ffdinfo->FileName[d_info->name_len] = 0x00;
3876 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3877 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3880 case FILE_BOTH_DIRECTORY_INFORMATION:
3882 struct file_both_directory_info *fbdinfo;
3884 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3885 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3886 fbdinfo->FileName[d_info->name_len] = 0x00;
3887 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3888 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3891 case FILE_DIRECTORY_INFORMATION:
3893 struct file_directory_info *fdinfo;
3895 fdinfo = (struct file_directory_info *)d_info->wptr;
3896 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3897 fdinfo->FileName[d_info->name_len] = 0x00;
3898 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3899 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3902 case FILE_NAMES_INFORMATION:
3904 struct file_names_info *fninfo;
3906 fninfo = (struct file_names_info *)d_info->wptr;
3907 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3908 fninfo->FileName[d_info->name_len] = 0x00;
3909 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3910 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3913 case FILEID_FULL_DIRECTORY_INFORMATION:
3915 struct file_id_full_dir_info *dinfo;
3917 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3918 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3919 dinfo->FileName[d_info->name_len] = 0x00;
3920 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3921 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3924 case FILEID_BOTH_DIRECTORY_INFORMATION:
3926 struct file_id_both_directory_info *fibdinfo;
3928 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3929 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3930 fibdinfo->FileName[d_info->name_len] = 0x00;
3931 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3932 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3935 case SMB_FIND_FILE_POSIX_INFO:
3937 struct smb2_posix_info *posix_info;
3939 posix_info = (struct smb2_posix_info *)d_info->wptr;
3940 memcpy(posix_info->name, d_info->name, d_info->name_len);
3941 posix_info->name[d_info->name_len] = 0x00;
3942 posix_info->name_len = cpu_to_le32(d_info->name_len);
3943 posix_info->NextEntryOffset =
3944 cpu_to_le32(next_entry_offset);
3947 } /* switch (info_level) */
3949 d_info->num_entry++;
3950 d_info->out_buf_len -= next_entry_offset;
3951 d_info->wptr += next_entry_offset;
3955 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
3956 loff_t offset, u64 ino, unsigned int d_type)
3958 struct ksmbd_readdir_data *buf;
3959 struct smb2_query_dir_private *priv;
3960 struct ksmbd_dir_info *d_info;
3963 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3964 priv = buf->private;
3965 d_info = priv->d_info;
3967 /* dot and dotdot entries are already reserved */
3968 if (!strcmp(".", name) || !strcmp("..", name))
3970 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3972 if (!match_pattern(name, namlen, priv->search_pattern))
3975 d_info->name = name;
3976 d_info->name_len = namlen;
3977 rc = reserve_populate_dentry(d_info, priv->info_level);
3980 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
3981 d_info->out_buf_len = 0;
3985 static int verify_info_level(int info_level)
3987 switch (info_level) {
3988 case FILE_FULL_DIRECTORY_INFORMATION:
3989 case FILE_BOTH_DIRECTORY_INFORMATION:
3990 case FILE_DIRECTORY_INFORMATION:
3991 case FILE_NAMES_INFORMATION:
3992 case FILEID_FULL_DIRECTORY_INFORMATION:
3993 case FILEID_BOTH_DIRECTORY_INFORMATION:
3994 case SMB_FIND_FILE_POSIX_INFO:
4003 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
4007 free_len = (int)(work->response_sz -
4008 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
4012 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
4013 unsigned short hdr2_len,
4014 unsigned int out_buf_len)
4018 if (out_buf_len > work->conn->vals->max_trans_size)
4021 free_len = smb2_resp_buf_len(work, hdr2_len);
4025 return min_t(int, out_buf_len, free_len);
4028 int smb2_query_dir(struct ksmbd_work *work)
4030 struct ksmbd_conn *conn = work->conn;
4031 struct smb2_query_directory_req *req;
4032 struct smb2_query_directory_rsp *rsp;
4033 struct ksmbd_share_config *share = work->tcon->share_conf;
4034 struct ksmbd_file *dir_fp = NULL;
4035 struct ksmbd_dir_info d_info;
4037 char *srch_ptr = NULL;
4038 unsigned char srch_flag;
4040 struct smb2_query_dir_private query_dir_private = {NULL, };
4042 WORK_BUFFERS(work, req, rsp);
4044 if (ksmbd_override_fsids(work)) {
4045 rsp->hdr.Status = STATUS_NO_MEMORY;
4046 smb2_set_err_rsp(work);
4050 rc = verify_info_level(req->FileInformationClass);
4056 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
4062 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
4063 inode_permission(file_mnt_idmap(dir_fp->filp),
4064 file_inode(dir_fp->filp),
4065 MAY_READ | MAY_EXEC)) {
4066 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
4071 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
4072 pr_err("can't do query dir for a file\n");
4077 srch_flag = req->Flags;
4078 srch_ptr = smb_strndup_from_utf16(req->Buffer,
4079 le16_to_cpu(req->FileNameLength), 1,
4081 if (IS_ERR(srch_ptr)) {
4082 ksmbd_debug(SMB, "Search Pattern not found\n");
4086 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
4089 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
4090 ksmbd_debug(SMB, "Restart directory scan\n");
4091 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
4094 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
4095 d_info.wptr = (char *)rsp->Buffer;
4096 d_info.rptr = (char *)rsp->Buffer;
4097 d_info.out_buf_len =
4098 smb2_calc_max_out_buf_len(work, 8,
4099 le32_to_cpu(req->OutputBufferLength));
4100 if (d_info.out_buf_len < 0) {
4104 d_info.flags = srch_flag;
4107 * reserve dot and dotdot entries in head of buffer
4110 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4111 dir_fp, &d_info, srch_ptr,
4112 smb2_populate_readdir_entry);
4118 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4119 d_info.hide_dot_file = true;
4121 buffer_sz = d_info.out_buf_len;
4122 d_info.rptr = d_info.wptr;
4123 query_dir_private.work = work;
4124 query_dir_private.search_pattern = srch_ptr;
4125 query_dir_private.dir_fp = dir_fp;
4126 query_dir_private.d_info = &d_info;
4127 query_dir_private.info_level = req->FileInformationClass;
4128 dir_fp->readdir_data.private = &query_dir_private;
4129 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4131 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4133 * req->OutputBufferLength is too small to contain even one entry.
4134 * In this case, it immediately returns OutputBufferLength 0 to client.
4136 if (!d_info.out_buf_len && !d_info.num_entry)
4138 if (rc > 0 || rc == -ENOSPC)
4143 d_info.wptr = d_info.rptr;
4144 d_info.out_buf_len = buffer_sz;
4145 rc = process_query_dir_entries(&query_dir_private);
4149 if (!d_info.data_count && d_info.out_buf_len >= 0) {
4150 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4151 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4153 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4154 rsp->hdr.Status = STATUS_NO_MORE_FILES;
4156 rsp->StructureSize = cpu_to_le16(9);
4157 rsp->OutputBufferOffset = cpu_to_le16(0);
4158 rsp->OutputBufferLength = cpu_to_le32(0);
4160 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4161 sizeof(struct smb2_query_directory_rsp));
4166 ((struct file_directory_info *)
4167 ((char *)rsp->Buffer + d_info.last_entry_offset))
4168 ->NextEntryOffset = 0;
4169 if (d_info.data_count >= d_info.last_entry_off_align)
4170 d_info.data_count -= d_info.last_entry_off_align;
4172 rsp->StructureSize = cpu_to_le16(9);
4173 rsp->OutputBufferOffset = cpu_to_le16(72);
4174 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4175 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4176 offsetof(struct smb2_query_directory_rsp, Buffer) +
4183 ksmbd_fd_put(work, dir_fp);
4184 ksmbd_revert_fsids(work);
4188 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4193 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4194 else if (rc == -EACCES)
4195 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4196 else if (rc == -ENOENT)
4197 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4198 else if (rc == -EBADF)
4199 rsp->hdr.Status = STATUS_FILE_CLOSED;
4200 else if (rc == -ENOMEM)
4201 rsp->hdr.Status = STATUS_NO_MEMORY;
4202 else if (rc == -EFAULT)
4203 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4204 else if (rc == -EIO)
4205 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4206 if (!rsp->hdr.Status)
4207 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4209 smb2_set_err_rsp(work);
4210 ksmbd_fd_put(work, dir_fp);
4211 ksmbd_revert_fsids(work);
4216 * buffer_check_err() - helper function to check buffer errors
4217 * @reqOutputBufferLength: max buffer length expected in command response
4218 * @rsp: query info response buffer contains output buffer length
4219 * @rsp_org: base response buffer pointer in case of chained response
4221 * Return: 0 on success, otherwise error
4223 static int buffer_check_err(int reqOutputBufferLength,
4224 struct smb2_query_info_rsp *rsp,
4227 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4228 pr_err("Invalid Buffer Size Requested\n");
4229 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4230 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4236 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4239 struct smb2_file_standard_info *sinfo;
4241 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4243 sinfo->AllocationSize = cpu_to_le64(4096);
4244 sinfo->EndOfFile = cpu_to_le64(0);
4245 sinfo->NumberOfLinks = cpu_to_le32(1);
4246 sinfo->DeletePending = 1;
4247 sinfo->Directory = 0;
4248 rsp->OutputBufferLength =
4249 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4252 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4255 struct smb2_file_internal_info *file_info;
4257 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4259 /* any unique number */
4260 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4261 rsp->OutputBufferLength =
4262 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4265 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4266 struct smb2_query_info_req *req,
4267 struct smb2_query_info_rsp *rsp,
4274 * Windows can sometime send query file info request on
4275 * pipe without opening it, checking error condition here
4277 id = req->VolatileFileId;
4278 if (!ksmbd_session_rpc_method(sess, id))
4281 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4282 req->FileInfoClass, req->VolatileFileId);
4284 switch (req->FileInfoClass) {
4285 case FILE_STANDARD_INFORMATION:
4286 get_standard_info_pipe(rsp, rsp_org);
4287 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4290 case FILE_INTERNAL_INFORMATION:
4291 get_internal_info_pipe(rsp, id, rsp_org);
4292 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4296 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4297 req->FileInfoClass);
4304 * smb2_get_ea() - handler for smb2 get extended attribute command
4305 * @work: smb work containing query info command buffer
4306 * @fp: ksmbd_file pointer
4307 * @req: get extended attribute request
4308 * @rsp: response buffer pointer
4309 * @rsp_org: base response buffer pointer in case of chained response
4311 * Return: 0 on success, otherwise error
4313 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4314 struct smb2_query_info_req *req,
4315 struct smb2_query_info_rsp *rsp, void *rsp_org)
4317 struct smb2_ea_info *eainfo, *prev_eainfo;
4318 char *name, *ptr, *xattr_list = NULL, *buf;
4319 int rc, name_len, value_len, xattr_list_len, idx;
4320 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4321 struct smb2_ea_info_req *ea_req = NULL;
4322 const struct path *path;
4323 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4325 if (!(fp->daccess & FILE_READ_EA_LE)) {
4326 pr_err("Not permitted to read ext attr : 0x%x\n",
4331 path = &fp->filp->f_path;
4332 /* single EA entry is requested with given user.* name */
4333 if (req->InputBufferLength) {
4334 if (le32_to_cpu(req->InputBufferLength) <
4335 sizeof(struct smb2_ea_info_req))
4338 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4340 /* need to send all EAs, if no specific EA is requested*/
4341 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4343 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4344 le32_to_cpu(req->Flags));
4348 smb2_calc_max_out_buf_len(work, 8,
4349 le32_to_cpu(req->OutputBufferLength));
4350 if (buf_free_len < 0)
4353 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4355 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4357 } else if (!rc) { /* there is no EA in the file */
4358 ksmbd_debug(SMB, "no ea data in the file\n");
4361 xattr_list_len = rc;
4363 ptr = (char *)rsp->Buffer;
4364 eainfo = (struct smb2_ea_info *)ptr;
4365 prev_eainfo = eainfo;
4368 while (idx < xattr_list_len) {
4369 name = xattr_list + idx;
4370 name_len = strlen(name);
4372 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4373 idx += name_len + 1;
4376 * CIFS does not support EA other than user.* namespace,
4377 * still keep the framework generic, to list other attrs
4380 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4383 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4387 if (req->InputBufferLength &&
4388 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4389 ea_req->EaNameLength))
4392 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4393 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4396 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4397 name_len -= XATTR_USER_PREFIX_LEN;
4399 ptr = eainfo->name + name_len + 1;
4400 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4402 /* bailout if xattr can't fit in buf_free_len */
4403 value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
4405 if (value_len <= 0) {
4407 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4411 buf_free_len -= value_len;
4412 if (buf_free_len < 0) {
4417 memcpy(ptr, buf, value_len);
4422 eainfo->EaNameLength = name_len;
4424 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4425 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4428 memcpy(eainfo->name, name, name_len);
4430 eainfo->name[name_len] = '\0';
4431 eainfo->EaValueLength = cpu_to_le16(value_len);
4432 next_offset = offsetof(struct smb2_ea_info, name) +
4433 name_len + 1 + value_len;
4435 /* align next xattr entry at 4 byte bundary */
4436 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4437 if (alignment_bytes) {
4438 memset(ptr, '\0', alignment_bytes);
4439 ptr += alignment_bytes;
4440 next_offset += alignment_bytes;
4441 buf_free_len -= alignment_bytes;
4443 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4444 prev_eainfo = eainfo;
4445 eainfo = (struct smb2_ea_info *)ptr;
4446 rsp_data_cnt += next_offset;
4448 if (req->InputBufferLength) {
4449 ksmbd_debug(SMB, "single entry requested\n");
4454 /* no more ea entries */
4455 prev_eainfo->NextEntryOffset = 0;
4458 if (rsp_data_cnt == 0)
4459 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4460 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4466 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4467 struct ksmbd_file *fp, void *rsp_org)
4469 struct smb2_file_access_info *file_info;
4471 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4472 file_info->AccessFlags = fp->daccess;
4473 rsp->OutputBufferLength =
4474 cpu_to_le32(sizeof(struct smb2_file_access_info));
4477 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4478 struct ksmbd_file *fp, void *rsp_org)
4480 struct smb2_file_basic_info *basic_info;
4484 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4485 pr_err("no right to read the attributes : 0x%x\n",
4490 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4491 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4492 file_inode(fp->filp), &stat);
4493 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4494 time = ksmbd_UnixTimeToNT(stat.atime);
4495 basic_info->LastAccessTime = cpu_to_le64(time);
4496 time = ksmbd_UnixTimeToNT(stat.mtime);
4497 basic_info->LastWriteTime = cpu_to_le64(time);
4498 time = ksmbd_UnixTimeToNT(stat.ctime);
4499 basic_info->ChangeTime = cpu_to_le64(time);
4500 basic_info->Attributes = fp->f_ci->m_fattr;
4501 basic_info->Pad1 = 0;
4502 rsp->OutputBufferLength =
4503 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4507 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4508 struct ksmbd_file *fp, void *rsp_org)
4510 struct smb2_file_standard_info *sinfo;
4511 unsigned int delete_pending;
4512 struct inode *inode;
4515 inode = file_inode(fp->filp);
4516 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS, inode, &stat);
4518 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4519 delete_pending = ksmbd_inode_pending_delete(fp);
4521 sinfo->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4522 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4523 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4524 sinfo->DeletePending = delete_pending;
4525 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4526 rsp->OutputBufferLength =
4527 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4530 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4533 struct smb2_file_alignment_info *file_info;
4535 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4536 file_info->AlignmentRequirement = 0;
4537 rsp->OutputBufferLength =
4538 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4541 static int get_file_all_info(struct ksmbd_work *work,
4542 struct smb2_query_info_rsp *rsp,
4543 struct ksmbd_file *fp,
4546 struct ksmbd_conn *conn = work->conn;
4547 struct smb2_file_all_info *file_info;
4548 unsigned int delete_pending;
4549 struct inode *inode;
4555 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4556 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4561 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4562 if (IS_ERR(filename))
4563 return PTR_ERR(filename);
4565 inode = file_inode(fp->filp);
4566 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS, inode, &stat);
4568 ksmbd_debug(SMB, "filename = %s\n", filename);
4569 delete_pending = ksmbd_inode_pending_delete(fp);
4570 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4572 file_info->CreationTime = cpu_to_le64(fp->create_time);
4573 time = ksmbd_UnixTimeToNT(stat.atime);
4574 file_info->LastAccessTime = cpu_to_le64(time);
4575 time = ksmbd_UnixTimeToNT(stat.mtime);
4576 file_info->LastWriteTime = cpu_to_le64(time);
4577 time = ksmbd_UnixTimeToNT(stat.ctime);
4578 file_info->ChangeTime = cpu_to_le64(time);
4579 file_info->Attributes = fp->f_ci->m_fattr;
4580 file_info->Pad1 = 0;
4581 file_info->AllocationSize =
4582 cpu_to_le64(inode->i_blocks << 9);
4583 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4584 file_info->NumberOfLinks =
4585 cpu_to_le32(get_nlink(&stat) - delete_pending);
4586 file_info->DeletePending = delete_pending;
4587 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4588 file_info->Pad2 = 0;
4589 file_info->IndexNumber = cpu_to_le64(stat.ino);
4590 file_info->EASize = 0;
4591 file_info->AccessFlags = fp->daccess;
4592 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4593 file_info->Mode = fp->coption;
4594 file_info->AlignmentRequirement = 0;
4595 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4596 PATH_MAX, conn->local_nls, 0);
4598 file_info->FileNameLength = cpu_to_le32(conv_len);
4599 rsp->OutputBufferLength =
4600 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4605 static void get_file_alternate_info(struct ksmbd_work *work,
4606 struct smb2_query_info_rsp *rsp,
4607 struct ksmbd_file *fp,
4610 struct ksmbd_conn *conn = work->conn;
4611 struct smb2_file_alt_name_info *file_info;
4612 struct dentry *dentry = fp->filp->f_path.dentry;
4615 spin_lock(&dentry->d_lock);
4616 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4617 conv_len = ksmbd_extract_shortname(conn,
4618 dentry->d_name.name,
4619 file_info->FileName);
4620 spin_unlock(&dentry->d_lock);
4621 file_info->FileNameLength = cpu_to_le32(conv_len);
4622 rsp->OutputBufferLength =
4623 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4626 static void get_file_stream_info(struct ksmbd_work *work,
4627 struct smb2_query_info_rsp *rsp,
4628 struct ksmbd_file *fp,
4631 struct ksmbd_conn *conn = work->conn;
4632 struct smb2_file_stream_info *file_info;
4633 char *stream_name, *xattr_list = NULL, *stream_buf;
4635 const struct path *path = &fp->filp->f_path;
4636 ssize_t xattr_list_len;
4637 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4639 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4641 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4642 file_inode(fp->filp), &stat);
4643 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4646 smb2_calc_max_out_buf_len(work, 8,
4647 le32_to_cpu(req->OutputBufferLength));
4648 if (buf_free_len < 0)
4651 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4652 if (xattr_list_len < 0) {
4654 } else if (!xattr_list_len) {
4655 ksmbd_debug(SMB, "empty xattr in the file\n");
4659 while (idx < xattr_list_len) {
4660 stream_name = xattr_list + idx;
4661 streamlen = strlen(stream_name);
4662 idx += streamlen + 1;
4664 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4666 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4667 STREAM_PREFIX, STREAM_PREFIX_LEN))
4670 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4672 streamlen = stream_name_len;
4676 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4680 streamlen = snprintf(stream_buf, streamlen + 1,
4681 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4683 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4684 if (next > buf_free_len) {
4689 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4690 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4691 stream_buf, streamlen,
4692 conn->local_nls, 0);
4695 file_info->StreamNameLength = cpu_to_le32(streamlen);
4696 file_info->StreamSize = cpu_to_le64(stream_name_len);
4697 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4700 buf_free_len -= next;
4701 file_info->NextEntryOffset = cpu_to_le32(next);
4705 if (!S_ISDIR(stat.mode) &&
4706 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4707 file_info = (struct smb2_file_stream_info *)
4708 &rsp->Buffer[nbytes];
4709 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4710 "::$DATA", 7, conn->local_nls, 0);
4712 file_info->StreamNameLength = cpu_to_le32(streamlen);
4713 file_info->StreamSize = cpu_to_le64(stat.size);
4714 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4715 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4718 /* last entry offset should be 0 */
4719 file_info->NextEntryOffset = 0;
4722 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4725 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4726 struct ksmbd_file *fp, void *rsp_org)
4728 struct smb2_file_internal_info *file_info;
4731 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4732 file_inode(fp->filp), &stat);
4733 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4734 file_info->IndexNumber = cpu_to_le64(stat.ino);
4735 rsp->OutputBufferLength =
4736 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4739 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4740 struct ksmbd_file *fp, void *rsp_org)
4742 struct smb2_file_ntwrk_info *file_info;
4743 struct inode *inode;
4747 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4748 pr_err("no right to read the attributes : 0x%x\n",
4753 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4755 inode = file_inode(fp->filp);
4756 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS, inode, &stat);
4758 file_info->CreationTime = cpu_to_le64(fp->create_time);
4759 time = ksmbd_UnixTimeToNT(stat.atime);
4760 file_info->LastAccessTime = cpu_to_le64(time);
4761 time = ksmbd_UnixTimeToNT(stat.mtime);
4762 file_info->LastWriteTime = cpu_to_le64(time);
4763 time = ksmbd_UnixTimeToNT(stat.ctime);
4764 file_info->ChangeTime = cpu_to_le64(time);
4765 file_info->Attributes = fp->f_ci->m_fattr;
4766 file_info->AllocationSize =
4767 cpu_to_le64(inode->i_blocks << 9);
4768 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4769 file_info->Reserved = cpu_to_le32(0);
4770 rsp->OutputBufferLength =
4771 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4775 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4777 struct smb2_file_ea_info *file_info;
4779 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4780 file_info->EASize = 0;
4781 rsp->OutputBufferLength =
4782 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4785 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4786 struct ksmbd_file *fp, void *rsp_org)
4788 struct smb2_file_pos_info *file_info;
4790 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4791 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4792 rsp->OutputBufferLength =
4793 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4796 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4797 struct ksmbd_file *fp, void *rsp_org)
4799 struct smb2_file_mode_info *file_info;
4801 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4802 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4803 rsp->OutputBufferLength =
4804 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4807 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4808 struct ksmbd_file *fp, void *rsp_org)
4810 struct smb2_file_comp_info *file_info;
4813 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4814 file_inode(fp->filp), &stat);
4816 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4817 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4818 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4819 file_info->CompressionUnitShift = 0;
4820 file_info->ChunkShift = 0;
4821 file_info->ClusterShift = 0;
4822 memset(&file_info->Reserved[0], 0, 3);
4824 rsp->OutputBufferLength =
4825 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4828 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4829 struct ksmbd_file *fp, void *rsp_org)
4831 struct smb2_file_attr_tag_info *file_info;
4833 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4834 pr_err("no right to read the attributes : 0x%x\n",
4839 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4840 file_info->FileAttributes = fp->f_ci->m_fattr;
4841 file_info->ReparseTag = 0;
4842 rsp->OutputBufferLength =
4843 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4847 static void find_file_posix_info(struct smb2_query_info_rsp *rsp,
4848 struct ksmbd_file *fp, void *rsp_org)
4850 struct smb311_posix_qinfo *file_info;
4851 struct inode *inode = file_inode(fp->filp);
4852 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4853 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
4854 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
4856 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
4858 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4859 file_info->CreationTime = cpu_to_le64(fp->create_time);
4860 time = ksmbd_UnixTimeToNT(inode->i_atime);
4861 file_info->LastAccessTime = cpu_to_le64(time);
4862 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4863 file_info->LastWriteTime = cpu_to_le64(time);
4864 time = ksmbd_UnixTimeToNT(inode_get_ctime(inode));
4865 file_info->ChangeTime = cpu_to_le64(time);
4866 file_info->DosAttributes = fp->f_ci->m_fattr;
4867 file_info->Inode = cpu_to_le64(inode->i_ino);
4868 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4869 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4870 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4871 file_info->Mode = cpu_to_le32(inode->i_mode & 0777);
4872 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4875 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4876 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4877 * sub_auth(4 * 1(num_subauth)) + RID(4).
4879 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
4880 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
4881 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
4882 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
4884 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
4887 static int smb2_get_info_file(struct ksmbd_work *work,
4888 struct smb2_query_info_req *req,
4889 struct smb2_query_info_rsp *rsp)
4891 struct ksmbd_file *fp;
4892 int fileinfoclass = 0;
4894 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4896 if (test_share_config_flag(work->tcon->share_conf,
4897 KSMBD_SHARE_FLAG_PIPE)) {
4898 /* smb2 info file called for pipe */
4899 return smb2_get_info_file_pipe(work->sess, req, rsp,
4900 work->response_buf);
4903 if (work->next_smb2_rcv_hdr_off) {
4904 if (!has_file_id(req->VolatileFileId)) {
4905 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4906 work->compound_fid);
4907 id = work->compound_fid;
4908 pid = work->compound_pfid;
4912 if (!has_file_id(id)) {
4913 id = req->VolatileFileId;
4914 pid = req->PersistentFileId;
4917 fp = ksmbd_lookup_fd_slow(work, id, pid);
4921 fileinfoclass = req->FileInfoClass;
4923 switch (fileinfoclass) {
4924 case FILE_ACCESS_INFORMATION:
4925 get_file_access_info(rsp, fp, work->response_buf);
4928 case FILE_BASIC_INFORMATION:
4929 rc = get_file_basic_info(rsp, fp, work->response_buf);
4932 case FILE_STANDARD_INFORMATION:
4933 get_file_standard_info(rsp, fp, work->response_buf);
4936 case FILE_ALIGNMENT_INFORMATION:
4937 get_file_alignment_info(rsp, work->response_buf);
4940 case FILE_ALL_INFORMATION:
4941 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4944 case FILE_ALTERNATE_NAME_INFORMATION:
4945 get_file_alternate_info(work, rsp, fp, work->response_buf);
4948 case FILE_STREAM_INFORMATION:
4949 get_file_stream_info(work, rsp, fp, work->response_buf);
4952 case FILE_INTERNAL_INFORMATION:
4953 get_file_internal_info(rsp, fp, work->response_buf);
4956 case FILE_NETWORK_OPEN_INFORMATION:
4957 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4960 case FILE_EA_INFORMATION:
4961 get_file_ea_info(rsp, work->response_buf);
4964 case FILE_FULL_EA_INFORMATION:
4965 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4968 case FILE_POSITION_INFORMATION:
4969 get_file_position_info(rsp, fp, work->response_buf);
4972 case FILE_MODE_INFORMATION:
4973 get_file_mode_info(rsp, fp, work->response_buf);
4976 case FILE_COMPRESSION_INFORMATION:
4977 get_file_compression_info(rsp, fp, work->response_buf);
4980 case FILE_ATTRIBUTE_TAG_INFORMATION:
4981 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4983 case SMB_FIND_FILE_POSIX_INFO:
4984 if (!work->tcon->posix_extensions) {
4985 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4988 find_file_posix_info(rsp, fp, work->response_buf);
4992 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4997 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4998 rsp, work->response_buf);
4999 ksmbd_fd_put(work, fp);
5003 static int smb2_get_info_filesystem(struct ksmbd_work *work,
5004 struct smb2_query_info_req *req,
5005 struct smb2_query_info_rsp *rsp)
5007 struct ksmbd_session *sess = work->sess;
5008 struct ksmbd_conn *conn = work->conn;
5009 struct ksmbd_share_config *share = work->tcon->share_conf;
5010 int fsinfoclass = 0;
5011 struct kstatfs stfs;
5018 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
5020 pr_err("cannot create vfs path\n");
5024 rc = vfs_statfs(&path, &stfs);
5026 pr_err("cannot do stat of path %s\n", share->path);
5031 fsinfoclass = req->FileInfoClass;
5033 switch (fsinfoclass) {
5034 case FS_DEVICE_INFORMATION:
5036 struct filesystem_device_info *info;
5038 info = (struct filesystem_device_info *)rsp->Buffer;
5040 info->DeviceType = cpu_to_le32(stfs.f_type);
5041 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
5042 rsp->OutputBufferLength = cpu_to_le32(8);
5045 case FS_ATTRIBUTE_INFORMATION:
5047 struct filesystem_attribute_info *info;
5050 info = (struct filesystem_attribute_info *)rsp->Buffer;
5051 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
5052 FILE_PERSISTENT_ACLS |
5053 FILE_UNICODE_ON_DISK |
5054 FILE_CASE_PRESERVED_NAMES |
5055 FILE_CASE_SENSITIVE_SEARCH |
5056 FILE_SUPPORTS_BLOCK_REFCOUNTING);
5058 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
5060 if (test_share_config_flag(work->tcon->share_conf,
5061 KSMBD_SHARE_FLAG_STREAMS))
5062 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
5064 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
5065 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
5066 "NTFS", PATH_MAX, conn->local_nls, 0);
5068 info->FileSystemNameLen = cpu_to_le32(len);
5069 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
5070 rsp->OutputBufferLength = cpu_to_le32(sz);
5073 case FS_VOLUME_INFORMATION:
5075 struct filesystem_vol_info *info;
5077 unsigned int serial_crc = 0;
5079 info = (struct filesystem_vol_info *)(rsp->Buffer);
5080 info->VolumeCreationTime = 0;
5081 serial_crc = crc32_le(serial_crc, share->name,
5082 strlen(share->name));
5083 serial_crc = crc32_le(serial_crc, share->path,
5084 strlen(share->path));
5085 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
5086 strlen(ksmbd_netbios_name()));
5087 /* Taking dummy value of serial number*/
5088 info->SerialNumber = cpu_to_le32(serial_crc);
5089 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
5090 share->name, PATH_MAX,
5091 conn->local_nls, 0);
5093 info->VolumeLabelSize = cpu_to_le32(len);
5095 sz = sizeof(struct filesystem_vol_info) - 2 + len;
5096 rsp->OutputBufferLength = cpu_to_le32(sz);
5099 case FS_SIZE_INFORMATION:
5101 struct filesystem_info *info;
5103 info = (struct filesystem_info *)(rsp->Buffer);
5104 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5105 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
5106 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5107 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5108 rsp->OutputBufferLength = cpu_to_le32(24);
5111 case FS_FULL_SIZE_INFORMATION:
5113 struct smb2_fs_full_size_info *info;
5115 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5116 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5117 info->CallerAvailableAllocationUnits =
5118 cpu_to_le64(stfs.f_bavail);
5119 info->ActualAvailableAllocationUnits =
5120 cpu_to_le64(stfs.f_bfree);
5121 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5122 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5123 rsp->OutputBufferLength = cpu_to_le32(32);
5126 case FS_OBJECT_ID_INFORMATION:
5128 struct object_id_info *info;
5130 info = (struct object_id_info *)(rsp->Buffer);
5132 if (!user_guest(sess->user))
5133 memcpy(info->objid, user_passkey(sess->user), 16);
5135 memset(info->objid, 0, 16);
5137 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5138 info->extended_info.version = cpu_to_le32(1);
5139 info->extended_info.release = cpu_to_le32(1);
5140 info->extended_info.rel_date = 0;
5141 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5142 rsp->OutputBufferLength = cpu_to_le32(64);
5145 case FS_SECTOR_SIZE_INFORMATION:
5147 struct smb3_fs_ss_info *info;
5148 unsigned int sector_size =
5149 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5151 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5153 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5154 info->PhysicalBytesPerSectorForAtomicity =
5155 cpu_to_le32(sector_size);
5156 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5157 info->FSEffPhysicalBytesPerSectorForAtomicity =
5158 cpu_to_le32(sector_size);
5159 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5160 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5161 info->ByteOffsetForSectorAlignment = 0;
5162 info->ByteOffsetForPartitionAlignment = 0;
5163 rsp->OutputBufferLength = cpu_to_le32(28);
5166 case FS_CONTROL_INFORMATION:
5169 * TODO : The current implementation is based on
5170 * test result with win7(NTFS) server. It's need to
5171 * modify this to get valid Quota values
5174 struct smb2_fs_control_info *info;
5176 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5177 info->FreeSpaceStartFiltering = 0;
5178 info->FreeSpaceThreshold = 0;
5179 info->FreeSpaceStopFiltering = 0;
5180 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5181 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5183 rsp->OutputBufferLength = cpu_to_le32(48);
5186 case FS_POSIX_INFORMATION:
5188 struct filesystem_posix_info *info;
5190 if (!work->tcon->posix_extensions) {
5191 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5194 info = (struct filesystem_posix_info *)(rsp->Buffer);
5195 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5196 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5197 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5198 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5199 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5200 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5201 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5202 rsp->OutputBufferLength = cpu_to_le32(56);
5210 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5211 rsp, work->response_buf);
5216 static int smb2_get_info_sec(struct ksmbd_work *work,
5217 struct smb2_query_info_req *req,
5218 struct smb2_query_info_rsp *rsp)
5220 struct ksmbd_file *fp;
5221 struct mnt_idmap *idmap;
5222 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5223 struct smb_fattr fattr = {{0}};
5224 struct inode *inode;
5225 __u32 secdesclen = 0;
5226 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5227 int addition_info = le32_to_cpu(req->AdditionalInformation);
5228 int rc = 0, ppntsd_size = 0;
5230 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5231 PROTECTED_DACL_SECINFO |
5232 UNPROTECTED_DACL_SECINFO)) {
5233 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5236 pntsd->revision = cpu_to_le16(1);
5237 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5238 pntsd->osidoffset = 0;
5239 pntsd->gsidoffset = 0;
5240 pntsd->sacloffset = 0;
5241 pntsd->dacloffset = 0;
5243 secdesclen = sizeof(struct smb_ntsd);
5244 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5249 if (work->next_smb2_rcv_hdr_off) {
5250 if (!has_file_id(req->VolatileFileId)) {
5251 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5252 work->compound_fid);
5253 id = work->compound_fid;
5254 pid = work->compound_pfid;
5258 if (!has_file_id(id)) {
5259 id = req->VolatileFileId;
5260 pid = req->PersistentFileId;
5263 fp = ksmbd_lookup_fd_slow(work, id, pid);
5267 idmap = file_mnt_idmap(fp->filp);
5268 inode = file_inode(fp->filp);
5269 ksmbd_acls_fattr(&fattr, idmap, inode);
5271 if (test_share_config_flag(work->tcon->share_conf,
5272 KSMBD_SHARE_FLAG_ACL_XATTR))
5273 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
5274 fp->filp->f_path.dentry,
5277 /* Check if sd buffer size exceeds response buffer size */
5278 if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5279 rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
5280 addition_info, &secdesclen, &fattr);
5281 posix_acl_release(fattr.cf_acls);
5282 posix_acl_release(fattr.cf_dacls);
5284 ksmbd_fd_put(work, fp);
5288 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5293 * smb2_query_info() - handler for smb2 query info command
5294 * @work: smb work containing query info request buffer
5296 * Return: 0 on success, otherwise error
5298 int smb2_query_info(struct ksmbd_work *work)
5300 struct smb2_query_info_req *req;
5301 struct smb2_query_info_rsp *rsp;
5304 WORK_BUFFERS(work, req, rsp);
5306 ksmbd_debug(SMB, "GOT query info request\n");
5308 switch (req->InfoType) {
5309 case SMB2_O_INFO_FILE:
5310 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5311 rc = smb2_get_info_file(work, req, rsp);
5313 case SMB2_O_INFO_FILESYSTEM:
5314 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5315 rc = smb2_get_info_filesystem(work, req, rsp);
5317 case SMB2_O_INFO_SECURITY:
5318 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5319 rc = smb2_get_info_sec(work, req, rsp);
5322 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5328 rsp->StructureSize = cpu_to_le16(9);
5329 rsp->OutputBufferOffset = cpu_to_le16(72);
5330 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5331 offsetof(struct smb2_query_info_rsp, Buffer) +
5332 le32_to_cpu(rsp->OutputBufferLength));
5337 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5338 else if (rc == -ENOENT)
5339 rsp->hdr.Status = STATUS_FILE_CLOSED;
5340 else if (rc == -EIO)
5341 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5342 else if (rc == -ENOMEM)
5343 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5344 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5345 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5346 smb2_set_err_rsp(work);
5348 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5356 * smb2_close_pipe() - handler for closing IPC pipe
5357 * @work: smb work containing close request buffer
5361 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5364 struct smb2_close_req *req;
5365 struct smb2_close_rsp *rsp;
5367 WORK_BUFFERS(work, req, rsp);
5369 id = req->VolatileFileId;
5370 ksmbd_session_rpc_close(work->sess, id);
5372 rsp->StructureSize = cpu_to_le16(60);
5375 rsp->CreationTime = 0;
5376 rsp->LastAccessTime = 0;
5377 rsp->LastWriteTime = 0;
5378 rsp->ChangeTime = 0;
5379 rsp->AllocationSize = 0;
5381 rsp->Attributes = 0;
5383 return ksmbd_iov_pin_rsp(work, (void *)rsp,
5384 sizeof(struct smb2_close_rsp));
5388 * smb2_close() - handler for smb2 close file command
5389 * @work: smb work containing close request buffer
5393 int smb2_close(struct ksmbd_work *work)
5395 u64 volatile_id = KSMBD_NO_FID;
5397 struct smb2_close_req *req;
5398 struct smb2_close_rsp *rsp;
5399 struct ksmbd_conn *conn = work->conn;
5400 struct ksmbd_file *fp;
5401 struct inode *inode;
5405 WORK_BUFFERS(work, req, rsp);
5407 if (test_share_config_flag(work->tcon->share_conf,
5408 KSMBD_SHARE_FLAG_PIPE)) {
5409 ksmbd_debug(SMB, "IPC pipe close request\n");
5410 return smb2_close_pipe(work);
5413 sess_id = le64_to_cpu(req->hdr.SessionId);
5414 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5415 sess_id = work->compound_sid;
5417 work->compound_sid = 0;
5418 if (check_session_id(conn, sess_id)) {
5419 work->compound_sid = sess_id;
5421 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5422 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5423 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5428 if (work->next_smb2_rcv_hdr_off &&
5429 !has_file_id(req->VolatileFileId)) {
5430 if (!has_file_id(work->compound_fid)) {
5431 /* file already closed, return FILE_CLOSED */
5432 ksmbd_debug(SMB, "file already closed\n");
5433 rsp->hdr.Status = STATUS_FILE_CLOSED;
5438 "Compound request set FID = %llu:%llu\n",
5440 work->compound_pfid);
5441 volatile_id = work->compound_fid;
5443 /* file closed, stored id is not valid anymore */
5444 work->compound_fid = KSMBD_NO_FID;
5445 work->compound_pfid = KSMBD_NO_FID;
5448 volatile_id = req->VolatileFileId;
5450 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5452 rsp->StructureSize = cpu_to_le16(60);
5455 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5456 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5462 inode = file_inode(fp->filp);
5463 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5464 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5465 cpu_to_le64(inode->i_blocks << 9);
5466 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5467 rsp->Attributes = fp->f_ci->m_fattr;
5468 rsp->CreationTime = cpu_to_le64(fp->create_time);
5469 time = ksmbd_UnixTimeToNT(inode->i_atime);
5470 rsp->LastAccessTime = cpu_to_le64(time);
5471 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5472 rsp->LastWriteTime = cpu_to_le64(time);
5473 time = ksmbd_UnixTimeToNT(inode_get_ctime(inode));
5474 rsp->ChangeTime = cpu_to_le64(time);
5475 ksmbd_fd_put(work, fp);
5478 rsp->AllocationSize = 0;
5480 rsp->Attributes = 0;
5481 rsp->CreationTime = 0;
5482 rsp->LastAccessTime = 0;
5483 rsp->LastWriteTime = 0;
5484 rsp->ChangeTime = 0;
5487 err = ksmbd_close_fd(work, volatile_id);
5490 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
5491 sizeof(struct smb2_close_rsp));
5494 if (rsp->hdr.Status == 0)
5495 rsp->hdr.Status = STATUS_FILE_CLOSED;
5496 smb2_set_err_rsp(work);
5503 * smb2_echo() - handler for smb2 echo(ping) command
5504 * @work: smb work containing echo request buffer
5508 int smb2_echo(struct ksmbd_work *work)
5510 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5512 if (work->next_smb2_rcv_hdr_off)
5513 rsp = ksmbd_resp_buf_next(work);
5515 rsp->StructureSize = cpu_to_le16(4);
5517 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
5520 static int smb2_rename(struct ksmbd_work *work,
5521 struct ksmbd_file *fp,
5522 struct smb2_file_rename_info *file_info,
5523 struct nls_table *local_nls)
5525 struct ksmbd_share_config *share = fp->tcon->share_conf;
5526 char *new_name = NULL;
5529 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5530 new_name = smb2_get_name(file_info->FileName,
5531 le32_to_cpu(file_info->FileNameLength),
5533 if (IS_ERR(new_name))
5534 return PTR_ERR(new_name);
5536 if (strchr(new_name, ':')) {
5538 char *xattr_stream_name, *stream_name = NULL;
5539 size_t xattr_stream_size;
5542 rc = parse_stream_name(new_name, &stream_name, &s_type);
5546 len = strlen(new_name);
5547 if (len > 0 && new_name[len - 1] != '/') {
5548 pr_err("not allow base filename in rename\n");
5553 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5560 rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
5565 pr_err("failed to store stream name in xattr: %d\n",
5574 ksmbd_debug(SMB, "new name %s\n", new_name);
5575 if (ksmbd_share_veto_filename(share, new_name)) {
5577 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5581 if (!file_info->ReplaceIfExists)
5582 flags = RENAME_NOREPLACE;
5584 rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
5590 static int smb2_create_link(struct ksmbd_work *work,
5591 struct ksmbd_share_config *share,
5592 struct smb2_file_link_info *file_info,
5593 unsigned int buf_len, struct file *filp,
5594 struct nls_table *local_nls)
5596 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5597 struct path path, parent_path;
5598 bool file_present = false;
5601 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5602 le32_to_cpu(file_info->FileNameLength))
5605 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5606 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5610 link_name = smb2_get_name(file_info->FileName,
5611 le32_to_cpu(file_info->FileNameLength),
5613 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5618 ksmbd_debug(SMB, "link name is %s\n", link_name);
5619 target_name = file_path(filp, pathname, PATH_MAX);
5620 if (IS_ERR(target_name)) {
5625 ksmbd_debug(SMB, "target name is %s\n", target_name);
5626 rc = ksmbd_vfs_kern_path_locked(work, link_name, LOOKUP_NO_SYMLINKS,
5627 &parent_path, &path, 0);
5632 file_present = true;
5634 if (file_info->ReplaceIfExists) {
5636 rc = ksmbd_vfs_remove_file(work, &path);
5639 ksmbd_debug(SMB, "cannot delete %s\n",
5647 ksmbd_debug(SMB, "link already exists\n");
5652 rc = ksmbd_vfs_link(work, target_name, link_name);
5657 ksmbd_vfs_kern_path_unlock(&parent_path, &path);
5659 if (!IS_ERR(link_name))
5665 static int set_file_basic_info(struct ksmbd_file *fp,
5666 struct smb2_file_basic_info *file_info,
5667 struct ksmbd_share_config *share)
5671 struct inode *inode;
5672 struct mnt_idmap *idmap;
5675 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5680 inode = file_inode(filp);
5681 idmap = file_mnt_idmap(filp);
5683 if (file_info->CreationTime)
5684 fp->create_time = le64_to_cpu(file_info->CreationTime);
5686 if (file_info->LastAccessTime) {
5687 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5688 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5691 attrs.ia_valid |= ATTR_CTIME;
5692 if (file_info->ChangeTime)
5693 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5695 attrs.ia_ctime = inode_get_ctime(inode);
5697 if (file_info->LastWriteTime) {
5698 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5699 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5702 if (file_info->Attributes) {
5703 if (!S_ISDIR(inode->i_mode) &&
5704 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5705 pr_err("can't change a file to a directory\n");
5709 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5710 fp->f_ci->m_fattr = file_info->Attributes |
5711 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5714 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5715 (file_info->CreationTime || file_info->Attributes)) {
5716 struct xattr_dos_attrib da = {0};
5719 da.itime = fp->itime;
5720 da.create_time = fp->create_time;
5721 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5722 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5723 XATTR_DOSINFO_ITIME;
5725 rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
5729 "failed to restore file attribute in EA\n");
5733 if (attrs.ia_valid) {
5734 struct dentry *dentry = filp->f_path.dentry;
5735 struct inode *inode = d_inode(dentry);
5737 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5741 inode_set_ctime_to_ts(inode, attrs.ia_ctime);
5742 attrs.ia_valid &= ~ATTR_CTIME;
5743 rc = notify_change(idmap, dentry, &attrs, NULL);
5744 inode_unlock(inode);
5749 static int set_file_allocation_info(struct ksmbd_work *work,
5750 struct ksmbd_file *fp,
5751 struct smb2_file_alloc_info *file_alloc_info)
5754 * TODO : It's working fine only when store dos attributes
5755 * is not yes. need to implement a logic which works
5756 * properly with any smb.conf option
5760 struct inode *inode;
5763 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5766 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5767 inode = file_inode(fp->filp);
5769 if (alloc_blks > inode->i_blocks) {
5770 smb_break_all_levII_oplock(work, fp, 1);
5771 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5773 if (rc && rc != -EOPNOTSUPP) {
5774 pr_err("vfs_fallocate is failed : %d\n", rc);
5777 } else if (alloc_blks < inode->i_blocks) {
5781 * Allocation size could be smaller than original one
5782 * which means allocated blocks in file should be
5783 * deallocated. use truncate to cut out it, but inode
5784 * size is also updated with truncate offset.
5785 * inode size is retained by backup inode size.
5787 size = i_size_read(inode);
5788 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5790 pr_err("truncate failed!, err %d\n", rc);
5793 if (size < alloc_blks * 512)
5794 i_size_write(inode, size);
5799 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5800 struct smb2_file_eof_info *file_eof_info)
5803 struct inode *inode;
5806 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5809 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5810 inode = file_inode(fp->filp);
5813 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5814 * on FAT32 shared device, truncate execution time is too long
5815 * and network error could cause from windows client. because
5816 * truncate of some filesystem like FAT32 fill zero data in
5819 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5820 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
5821 rc = ksmbd_vfs_truncate(work, fp, newsize);
5823 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
5832 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5833 struct smb2_file_rename_info *rename_info,
5834 unsigned int buf_len)
5836 if (!(fp->daccess & FILE_DELETE_LE)) {
5837 pr_err("no right to delete : 0x%x\n", fp->daccess);
5841 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5842 le32_to_cpu(rename_info->FileNameLength))
5845 if (!le32_to_cpu(rename_info->FileNameLength))
5848 return smb2_rename(work, fp, rename_info, work->conn->local_nls);
5851 static int set_file_disposition_info(struct ksmbd_file *fp,
5852 struct smb2_file_disposition_info *file_info)
5854 struct inode *inode;
5856 if (!(fp->daccess & FILE_DELETE_LE)) {
5857 pr_err("no right to delete : 0x%x\n", fp->daccess);
5861 inode = file_inode(fp->filp);
5862 if (file_info->DeletePending) {
5863 if (S_ISDIR(inode->i_mode) &&
5864 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5866 ksmbd_set_inode_pending_delete(fp);
5868 ksmbd_clear_inode_pending_delete(fp);
5873 static int set_file_position_info(struct ksmbd_file *fp,
5874 struct smb2_file_pos_info *file_info)
5876 loff_t current_byte_offset;
5877 unsigned long sector_size;
5878 struct inode *inode;
5880 inode = file_inode(fp->filp);
5881 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5882 sector_size = inode->i_sb->s_blocksize;
5884 if (current_byte_offset < 0 ||
5885 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5886 current_byte_offset & (sector_size - 1))) {
5887 pr_err("CurrentByteOffset is not valid : %llu\n",
5888 current_byte_offset);
5892 fp->filp->f_pos = current_byte_offset;
5896 static int set_file_mode_info(struct ksmbd_file *fp,
5897 struct smb2_file_mode_info *file_info)
5901 mode = file_info->Mode;
5903 if ((mode & ~FILE_MODE_INFO_MASK)) {
5904 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5909 * TODO : need to implement consideration for
5910 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5912 ksmbd_vfs_set_fadvise(fp->filp, mode);
5918 * smb2_set_info_file() - handler for smb2 set info command
5919 * @work: smb work containing set info command buffer
5920 * @fp: ksmbd_file pointer
5921 * @req: request buffer pointer
5922 * @share: ksmbd_share_config pointer
5924 * Return: 0 on success, otherwise error
5925 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5927 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5928 struct smb2_set_info_req *req,
5929 struct ksmbd_share_config *share)
5931 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5933 switch (req->FileInfoClass) {
5934 case FILE_BASIC_INFORMATION:
5936 if (buf_len < sizeof(struct smb2_file_basic_info))
5939 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5941 case FILE_ALLOCATION_INFORMATION:
5943 if (buf_len < sizeof(struct smb2_file_alloc_info))
5946 return set_file_allocation_info(work, fp,
5947 (struct smb2_file_alloc_info *)req->Buffer);
5949 case FILE_END_OF_FILE_INFORMATION:
5951 if (buf_len < sizeof(struct smb2_file_eof_info))
5954 return set_end_of_file_info(work, fp,
5955 (struct smb2_file_eof_info *)req->Buffer);
5957 case FILE_RENAME_INFORMATION:
5959 if (buf_len < sizeof(struct smb2_file_rename_info))
5962 return set_rename_info(work, fp,
5963 (struct smb2_file_rename_info *)req->Buffer,
5966 case FILE_LINK_INFORMATION:
5968 if (buf_len < sizeof(struct smb2_file_link_info))
5971 return smb2_create_link(work, work->tcon->share_conf,
5972 (struct smb2_file_link_info *)req->Buffer,
5974 work->conn->local_nls);
5976 case FILE_DISPOSITION_INFORMATION:
5978 if (buf_len < sizeof(struct smb2_file_disposition_info))
5981 return set_file_disposition_info(fp,
5982 (struct smb2_file_disposition_info *)req->Buffer);
5984 case FILE_FULL_EA_INFORMATION:
5986 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5987 pr_err("Not permitted to write ext attr: 0x%x\n",
5992 if (buf_len < sizeof(struct smb2_ea_info))
5995 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
5996 buf_len, &fp->filp->f_path, true);
5998 case FILE_POSITION_INFORMATION:
6000 if (buf_len < sizeof(struct smb2_file_pos_info))
6003 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
6005 case FILE_MODE_INFORMATION:
6007 if (buf_len < sizeof(struct smb2_file_mode_info))
6010 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
6014 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6018 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6019 char *buffer, int buf_len)
6021 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6023 fp->saccess |= FILE_SHARE_DELETE_LE;
6025 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6026 buf_len, false, true);
6030 * smb2_set_info() - handler for smb2 set info command handler
6031 * @work: smb work containing set info request buffer
6033 * Return: 0 on success, otherwise error
6035 int smb2_set_info(struct ksmbd_work *work)
6037 struct smb2_set_info_req *req;
6038 struct smb2_set_info_rsp *rsp;
6039 struct ksmbd_file *fp = NULL;
6041 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6043 ksmbd_debug(SMB, "Received set info request\n");
6045 if (work->next_smb2_rcv_hdr_off) {
6046 req = ksmbd_req_buf_next(work);
6047 rsp = ksmbd_resp_buf_next(work);
6048 if (!has_file_id(req->VolatileFileId)) {
6049 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6050 work->compound_fid);
6051 id = work->compound_fid;
6052 pid = work->compound_pfid;
6055 req = smb2_get_msg(work->request_buf);
6056 rsp = smb2_get_msg(work->response_buf);
6059 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6060 ksmbd_debug(SMB, "User does not have write permission\n");
6061 pr_err("User does not have write permission\n");
6066 if (!has_file_id(id)) {
6067 id = req->VolatileFileId;
6068 pid = req->PersistentFileId;
6071 fp = ksmbd_lookup_fd_slow(work, id, pid);
6073 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6078 switch (req->InfoType) {
6079 case SMB2_O_INFO_FILE:
6080 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6081 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6083 case SMB2_O_INFO_SECURITY:
6084 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6085 if (ksmbd_override_fsids(work)) {
6089 rc = smb2_set_info_sec(fp,
6090 le32_to_cpu(req->AdditionalInformation),
6092 le32_to_cpu(req->BufferLength));
6093 ksmbd_revert_fsids(work);
6102 rsp->StructureSize = cpu_to_le16(2);
6103 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6104 sizeof(struct smb2_set_info_rsp));
6107 ksmbd_fd_put(work, fp);
6111 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6112 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6113 else if (rc == -EINVAL)
6114 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6115 else if (rc == -ESHARE)
6116 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6117 else if (rc == -ENOENT)
6118 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6119 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6120 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6121 else if (rc == -EAGAIN)
6122 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6123 else if (rc == -EBADF || rc == -ESTALE)
6124 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6125 else if (rc == -EEXIST)
6126 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6127 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6128 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6129 smb2_set_err_rsp(work);
6130 ksmbd_fd_put(work, fp);
6131 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6136 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6137 * @work: smb work containing read IPC pipe command buffer
6139 * Return: 0 on success, otherwise error
6141 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6143 int nbytes = 0, err;
6145 struct ksmbd_rpc_command *rpc_resp;
6146 struct smb2_read_req *req;
6147 struct smb2_read_rsp *rsp;
6149 WORK_BUFFERS(work, req, rsp);
6151 id = req->VolatileFileId;
6153 rpc_resp = ksmbd_rpc_read(work->sess, id);
6155 void *aux_payload_buf;
6157 if (rpc_resp->flags != KSMBD_RPC_OK) {
6163 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL);
6164 if (!aux_payload_buf) {
6169 memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
6171 nbytes = rpc_resp->payload_sz;
6172 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6173 offsetof(struct smb2_read_rsp, Buffer),
6174 aux_payload_buf, nbytes);
6179 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6180 offsetof(struct smb2_read_rsp, Buffer));
6185 rsp->StructureSize = cpu_to_le16(17);
6186 rsp->DataOffset = 80;
6188 rsp->DataLength = cpu_to_le32(nbytes);
6189 rsp->DataRemaining = 0;
6194 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6195 smb2_set_err_rsp(work);
6200 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6201 struct smb2_buffer_desc_v1 *desc,
6203 __le16 ChannelInfoLength)
6205 unsigned int i, ch_count;
6207 if (work->conn->dialect == SMB30_PROT_ID &&
6208 Channel != SMB2_CHANNEL_RDMA_V1)
6211 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6212 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6213 for (i = 0; i < ch_count; i++) {
6214 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6216 le32_to_cpu(desc[i].token),
6217 le32_to_cpu(desc[i].length));
6223 work->need_invalidate_rkey =
6224 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6225 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6226 work->remote_key = le32_to_cpu(desc->token);
6230 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6231 struct smb2_read_req *req, void *data_buf,
6236 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6237 (struct smb2_buffer_desc_v1 *)
6238 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6239 le16_to_cpu(req->ReadChannelInfoLength));
6247 * smb2_read() - handler for smb2 read from file
6248 * @work: smb work containing read command buffer
6250 * Return: 0 on success, otherwise error
6252 int smb2_read(struct ksmbd_work *work)
6254 struct ksmbd_conn *conn = work->conn;
6255 struct smb2_read_req *req;
6256 struct smb2_read_rsp *rsp;
6257 struct ksmbd_file *fp = NULL;
6259 size_t length, mincount;
6260 ssize_t nbytes = 0, remain_bytes = 0;
6262 bool is_rdma_channel = false;
6263 unsigned int max_read_size = conn->vals->max_read_size;
6264 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6265 void *aux_payload_buf;
6267 if (test_share_config_flag(work->tcon->share_conf,
6268 KSMBD_SHARE_FLAG_PIPE)) {
6269 ksmbd_debug(SMB, "IPC pipe read request\n");
6270 return smb2_read_pipe(work);
6273 if (work->next_smb2_rcv_hdr_off) {
6274 req = ksmbd_req_buf_next(work);
6275 rsp = ksmbd_resp_buf_next(work);
6276 if (!has_file_id(req->VolatileFileId)) {
6277 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6278 work->compound_fid);
6279 id = work->compound_fid;
6280 pid = work->compound_pfid;
6283 req = smb2_get_msg(work->request_buf);
6284 rsp = smb2_get_msg(work->response_buf);
6287 if (!has_file_id(id)) {
6288 id = req->VolatileFileId;
6289 pid = req->PersistentFileId;
6292 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6293 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6294 is_rdma_channel = true;
6295 max_read_size = get_smbd_max_read_write_size();
6298 if (is_rdma_channel == true) {
6299 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6301 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6305 err = smb2_set_remote_key_for_rdma(work,
6306 (struct smb2_buffer_desc_v1 *)
6307 ((char *)req + ch_offset),
6309 req->ReadChannelInfoLength);
6314 fp = ksmbd_lookup_fd_slow(work, id, pid);
6320 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6321 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6326 offset = le64_to_cpu(req->Offset);
6327 length = le32_to_cpu(req->Length);
6328 mincount = le32_to_cpu(req->MinimumCount);
6330 if (length > max_read_size) {
6331 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6337 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6338 fp->filp, offset, length);
6340 aux_payload_buf = kvzalloc(length, GFP_KERNEL);
6341 if (!aux_payload_buf) {
6346 nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
6352 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6353 kvfree(aux_payload_buf);
6354 rsp->hdr.Status = STATUS_END_OF_FILE;
6355 smb2_set_err_rsp(work);
6356 ksmbd_fd_put(work, fp);
6360 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6361 nbytes, offset, mincount);
6363 if (is_rdma_channel == true) {
6364 /* write data to the client using rdma channel */
6365 remain_bytes = smb2_read_rdma_channel(work, req,
6368 kvfree(aux_payload_buf);
6369 aux_payload_buf = NULL;
6371 if (remain_bytes < 0) {
6372 err = (int)remain_bytes;
6377 rsp->StructureSize = cpu_to_le16(17);
6378 rsp->DataOffset = 80;
6380 rsp->DataLength = cpu_to_le32(nbytes);
6381 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6383 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6384 offsetof(struct smb2_read_rsp, Buffer),
6385 aux_payload_buf, nbytes);
6388 ksmbd_fd_put(work, fp);
6394 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6395 else if (err == -EAGAIN)
6396 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6397 else if (err == -ENOENT)
6398 rsp->hdr.Status = STATUS_FILE_CLOSED;
6399 else if (err == -EACCES)
6400 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6401 else if (err == -ESHARE)
6402 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6403 else if (err == -EINVAL)
6404 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6406 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6408 smb2_set_err_rsp(work);
6410 ksmbd_fd_put(work, fp);
6415 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6416 * @work: smb work containing write IPC pipe command buffer
6418 * Return: 0 on success, otherwise error
6420 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6422 struct smb2_write_req *req;
6423 struct smb2_write_rsp *rsp;
6424 struct ksmbd_rpc_command *rpc_resp;
6426 int err = 0, ret = 0;
6430 WORK_BUFFERS(work, req, rsp);
6432 length = le32_to_cpu(req->Length);
6433 id = req->VolatileFileId;
6435 if ((u64)le16_to_cpu(req->DataOffset) + length >
6436 get_rfc1002_len(work->request_buf)) {
6437 pr_err("invalid write data offset %u, smb_len %u\n",
6438 le16_to_cpu(req->DataOffset),
6439 get_rfc1002_len(work->request_buf));
6444 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6445 le16_to_cpu(req->DataOffset));
6447 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6449 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6450 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6452 smb2_set_err_rsp(work);
6455 if (rpc_resp->flags != KSMBD_RPC_OK) {
6456 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6457 smb2_set_err_rsp(work);
6464 rsp->StructureSize = cpu_to_le16(17);
6465 rsp->DataOffset = 0;
6467 rsp->DataLength = cpu_to_le32(length);
6468 rsp->DataRemaining = 0;
6470 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6471 offsetof(struct smb2_write_rsp, Buffer));
6474 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6475 smb2_set_err_rsp(work);
6481 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6482 struct smb2_write_req *req,
6483 struct ksmbd_file *fp,
6484 loff_t offset, size_t length, bool sync)
6490 data_buf = kvzalloc(length, GFP_KERNEL);
6494 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6495 (struct smb2_buffer_desc_v1 *)
6496 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6497 le16_to_cpu(req->WriteChannelInfoLength));
6503 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6512 * smb2_write() - handler for smb2 write from file
6513 * @work: smb work containing write command buffer
6515 * Return: 0 on success, otherwise error
6517 int smb2_write(struct ksmbd_work *work)
6519 struct smb2_write_req *req;
6520 struct smb2_write_rsp *rsp;
6521 struct ksmbd_file *fp = NULL;
6526 bool writethrough = false, is_rdma_channel = false;
6528 unsigned int max_write_size = work->conn->vals->max_write_size;
6530 WORK_BUFFERS(work, req, rsp);
6532 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6533 ksmbd_debug(SMB, "IPC pipe write request\n");
6534 return smb2_write_pipe(work);
6537 offset = le64_to_cpu(req->Offset);
6538 length = le32_to_cpu(req->Length);
6540 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6541 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6542 is_rdma_channel = true;
6543 max_write_size = get_smbd_max_read_write_size();
6544 length = le32_to_cpu(req->RemainingBytes);
6547 if (is_rdma_channel == true) {
6548 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6550 if (req->Length != 0 || req->DataOffset != 0 ||
6551 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6555 err = smb2_set_remote_key_for_rdma(work,
6556 (struct smb2_buffer_desc_v1 *)
6557 ((char *)req + ch_offset),
6559 req->WriteChannelInfoLength);
6564 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6565 ksmbd_debug(SMB, "User does not have write permission\n");
6570 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6576 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6577 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6582 if (length > max_write_size) {
6583 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6589 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6590 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6591 writethrough = true;
6593 if (is_rdma_channel == false) {
6594 if (le16_to_cpu(req->DataOffset) <
6595 offsetof(struct smb2_write_req, Buffer)) {
6600 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6601 le16_to_cpu(req->DataOffset));
6603 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6604 fp->filp, offset, length);
6605 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6606 writethrough, &nbytes);
6610 /* read data from the client using rdma channel, and
6613 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6621 rsp->StructureSize = cpu_to_le16(17);
6622 rsp->DataOffset = 0;
6624 rsp->DataLength = cpu_to_le32(nbytes);
6625 rsp->DataRemaining = 0;
6627 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
6630 ksmbd_fd_put(work, fp);
6635 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6636 else if (err == -ENOSPC || err == -EFBIG)
6637 rsp->hdr.Status = STATUS_DISK_FULL;
6638 else if (err == -ENOENT)
6639 rsp->hdr.Status = STATUS_FILE_CLOSED;
6640 else if (err == -EACCES)
6641 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6642 else if (err == -ESHARE)
6643 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6644 else if (err == -EINVAL)
6645 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6647 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6649 smb2_set_err_rsp(work);
6650 ksmbd_fd_put(work, fp);
6655 * smb2_flush() - handler for smb2 flush file - fsync
6656 * @work: smb work containing flush command buffer
6658 * Return: 0 on success, otherwise error
6660 int smb2_flush(struct ksmbd_work *work)
6662 struct smb2_flush_req *req;
6663 struct smb2_flush_rsp *rsp;
6666 WORK_BUFFERS(work, req, rsp);
6668 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6670 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6674 rsp->StructureSize = cpu_to_le16(4);
6676 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
6679 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6680 smb2_set_err_rsp(work);
6685 * smb2_cancel() - handler for smb2 cancel command
6686 * @work: smb work containing cancel command buffer
6688 * Return: 0 on success, otherwise error
6690 int smb2_cancel(struct ksmbd_work *work)
6692 struct ksmbd_conn *conn = work->conn;
6693 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6694 struct smb2_hdr *chdr;
6695 struct ksmbd_work *iter;
6696 struct list_head *command_list;
6698 if (work->next_smb2_rcv_hdr_off)
6699 hdr = ksmbd_resp_buf_next(work);
6701 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6702 hdr->MessageId, hdr->Flags);
6704 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6705 command_list = &conn->async_requests;
6707 spin_lock(&conn->request_lock);
6708 list_for_each_entry(iter, command_list,
6709 async_request_entry) {
6710 chdr = smb2_get_msg(iter->request_buf);
6712 if (iter->async_id !=
6713 le64_to_cpu(hdr->Id.AsyncId))
6717 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6718 le64_to_cpu(hdr->Id.AsyncId),
6719 le16_to_cpu(chdr->Command));
6720 iter->state = KSMBD_WORK_CANCELLED;
6721 if (iter->cancel_fn)
6722 iter->cancel_fn(iter->cancel_argv);
6725 spin_unlock(&conn->request_lock);
6727 command_list = &conn->requests;
6729 spin_lock(&conn->request_lock);
6730 list_for_each_entry(iter, command_list, request_entry) {
6731 chdr = smb2_get_msg(iter->request_buf);
6733 if (chdr->MessageId != hdr->MessageId ||
6738 "smb2 with mid %llu cancelled command = 0x%x\n",
6739 le64_to_cpu(hdr->MessageId),
6740 le16_to_cpu(chdr->Command));
6741 iter->state = KSMBD_WORK_CANCELLED;
6744 spin_unlock(&conn->request_lock);
6747 /* For SMB2_CANCEL command itself send no response*/
6748 work->send_no_response = 1;
6752 struct file_lock *smb_flock_init(struct file *f)
6754 struct file_lock *fl;
6756 fl = locks_alloc_lock();
6760 locks_init_lock(fl);
6763 fl->fl_pid = current->tgid;
6765 fl->fl_flags = FL_POSIX;
6767 fl->fl_lmops = NULL;
6773 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6777 /* Checking for wrong flag combination during lock request*/
6779 case SMB2_LOCKFLAG_SHARED:
6780 ksmbd_debug(SMB, "received shared request\n");
6782 flock->fl_type = F_RDLCK;
6783 flock->fl_flags |= FL_SLEEP;
6785 case SMB2_LOCKFLAG_EXCLUSIVE:
6786 ksmbd_debug(SMB, "received exclusive request\n");
6788 flock->fl_type = F_WRLCK;
6789 flock->fl_flags |= FL_SLEEP;
6791 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6793 "received shared & fail immediately request\n");
6795 flock->fl_type = F_RDLCK;
6797 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6799 "received exclusive & fail immediately request\n");
6801 flock->fl_type = F_WRLCK;
6803 case SMB2_LOCKFLAG_UNLOCK:
6804 ksmbd_debug(SMB, "received unlock request\n");
6805 flock->fl_type = F_UNLCK;
6813 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6814 unsigned int cmd, int flags,
6815 struct list_head *lock_list)
6817 struct ksmbd_lock *lock;
6819 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6825 lock->start = flock->fl_start;
6826 lock->end = flock->fl_end;
6827 lock->flags = flags;
6828 if (lock->start == lock->end)
6830 INIT_LIST_HEAD(&lock->clist);
6831 INIT_LIST_HEAD(&lock->flist);
6832 INIT_LIST_HEAD(&lock->llist);
6833 list_add_tail(&lock->llist, lock_list);
6838 static void smb2_remove_blocked_lock(void **argv)
6840 struct file_lock *flock = (struct file_lock *)argv[0];
6842 ksmbd_vfs_posix_lock_unblock(flock);
6843 wake_up(&flock->fl_wait);
6846 static inline bool lock_defer_pending(struct file_lock *fl)
6848 /* check pending lock waiters */
6849 return waitqueue_active(&fl->fl_wait);
6853 * smb2_lock() - handler for smb2 file lock command
6854 * @work: smb work containing lock command buffer
6856 * Return: 0 on success, otherwise error
6858 int smb2_lock(struct ksmbd_work *work)
6860 struct smb2_lock_req *req;
6861 struct smb2_lock_rsp *rsp;
6862 struct smb2_lock_element *lock_ele;
6863 struct ksmbd_file *fp = NULL;
6864 struct file_lock *flock = NULL;
6865 struct file *filp = NULL;
6869 int err = -EIO, i, rc = 0;
6870 u64 lock_start, lock_length;
6871 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6872 struct ksmbd_conn *conn;
6874 LIST_HEAD(lock_list);
6875 LIST_HEAD(rollback_list);
6878 WORK_BUFFERS(work, req, rsp);
6880 ksmbd_debug(SMB, "Received lock request\n");
6881 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6883 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6889 lock_count = le16_to_cpu(req->LockCount);
6890 lock_ele = req->locks;
6892 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6898 for (i = 0; i < lock_count; i++) {
6899 flags = le32_to_cpu(lock_ele[i].Flags);
6901 flock = smb_flock_init(filp);
6905 cmd = smb2_set_flock_flags(flock, flags);
6907 lock_start = le64_to_cpu(lock_ele[i].Offset);
6908 lock_length = le64_to_cpu(lock_ele[i].Length);
6909 if (lock_start > U64_MAX - lock_length) {
6910 pr_err("Invalid lock range requested\n");
6911 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6912 locks_free_lock(flock);
6916 if (lock_start > OFFSET_MAX)
6917 flock->fl_start = OFFSET_MAX;
6919 flock->fl_start = lock_start;
6921 lock_length = le64_to_cpu(lock_ele[i].Length);
6922 if (lock_length > OFFSET_MAX - flock->fl_start)
6923 lock_length = OFFSET_MAX - flock->fl_start;
6925 flock->fl_end = flock->fl_start + lock_length;
6927 if (flock->fl_end < flock->fl_start) {
6929 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6930 flock->fl_end, flock->fl_start);
6931 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6932 locks_free_lock(flock);
6936 /* Check conflict locks in one request */
6937 list_for_each_entry(cmp_lock, &lock_list, llist) {
6938 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6939 cmp_lock->fl->fl_end >= flock->fl_end) {
6940 if (cmp_lock->fl->fl_type != F_UNLCK &&
6941 flock->fl_type != F_UNLCK) {
6942 pr_err("conflict two locks in one request\n");
6944 locks_free_lock(flock);
6950 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6953 locks_free_lock(flock);
6958 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6959 if (smb_lock->cmd < 0) {
6964 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6969 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6970 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6971 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6972 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6977 prior_lock = smb_lock->flags;
6979 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6980 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6984 /* check locks in connection list */
6985 down_read(&conn_list_lock);
6986 list_for_each_entry(conn, &conn_list, conns_list) {
6987 spin_lock(&conn->llist_lock);
6988 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6989 if (file_inode(cmp_lock->fl->fl_file) !=
6990 file_inode(smb_lock->fl->fl_file))
6993 if (smb_lock->fl->fl_type == F_UNLCK) {
6994 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6995 cmp_lock->start == smb_lock->start &&
6996 cmp_lock->end == smb_lock->end &&
6997 !lock_defer_pending(cmp_lock->fl)) {
6999 list_del(&cmp_lock->flist);
7000 list_del(&cmp_lock->clist);
7001 spin_unlock(&conn->llist_lock);
7002 up_read(&conn_list_lock);
7004 locks_free_lock(cmp_lock->fl);
7011 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
7012 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
7015 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
7019 /* check zero byte lock range */
7020 if (cmp_lock->zero_len && !smb_lock->zero_len &&
7021 cmp_lock->start > smb_lock->start &&
7022 cmp_lock->start < smb_lock->end) {
7023 spin_unlock(&conn->llist_lock);
7024 up_read(&conn_list_lock);
7025 pr_err("previous lock conflict with zero byte lock range\n");
7029 if (smb_lock->zero_len && !cmp_lock->zero_len &&
7030 smb_lock->start > cmp_lock->start &&
7031 smb_lock->start < cmp_lock->end) {
7032 spin_unlock(&conn->llist_lock);
7033 up_read(&conn_list_lock);
7034 pr_err("current lock conflict with zero byte lock range\n");
7038 if (((cmp_lock->start <= smb_lock->start &&
7039 cmp_lock->end > smb_lock->start) ||
7040 (cmp_lock->start < smb_lock->end &&
7041 cmp_lock->end >= smb_lock->end)) &&
7042 !cmp_lock->zero_len && !smb_lock->zero_len) {
7043 spin_unlock(&conn->llist_lock);
7044 up_read(&conn_list_lock);
7045 pr_err("Not allow lock operation on exclusive lock range\n");
7049 spin_unlock(&conn->llist_lock);
7051 up_read(&conn_list_lock);
7053 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
7054 pr_err("Try to unlock nolocked range\n");
7055 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7060 if (smb_lock->zero_len) {
7065 flock = smb_lock->fl;
7066 list_del(&smb_lock->llist);
7068 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7070 if (flags & SMB2_LOCKFLAG_UNLOCK) {
7072 ksmbd_debug(SMB, "File unlocked\n");
7073 } else if (rc == -ENOENT) {
7074 rsp->hdr.Status = STATUS_NOT_LOCKED;
7077 locks_free_lock(flock);
7080 if (rc == FILE_LOCK_DEFERRED) {
7084 "would have to wait for getting lock\n");
7085 list_add(&smb_lock->llist, &rollback_list);
7087 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7094 rc = setup_async_work(work,
7095 smb2_remove_blocked_lock,
7102 spin_lock(&fp->f_lock);
7103 list_add(&work->fp_entry, &fp->blocked_works);
7104 spin_unlock(&fp->f_lock);
7106 smb2_send_interim_resp(work, STATUS_PENDING);
7108 ksmbd_vfs_posix_lock_wait(flock);
7110 spin_lock(&fp->f_lock);
7111 list_del(&work->fp_entry);
7112 spin_unlock(&fp->f_lock);
7114 if (work->state != KSMBD_WORK_ACTIVE) {
7115 list_del(&smb_lock->llist);
7116 locks_free_lock(flock);
7118 if (work->state == KSMBD_WORK_CANCELLED) {
7122 smb2_send_interim_resp(work,
7124 work->send_no_response = 1;
7129 STATUS_RANGE_NOT_LOCKED;
7134 list_del(&smb_lock->llist);
7135 release_async_work(work);
7138 list_add(&smb_lock->llist, &rollback_list);
7139 spin_lock(&work->conn->llist_lock);
7140 list_add_tail(&smb_lock->clist,
7141 &work->conn->lock_list);
7142 list_add_tail(&smb_lock->flist,
7144 spin_unlock(&work->conn->llist_lock);
7145 ksmbd_debug(SMB, "successful in taking lock\n");
7152 if (atomic_read(&fp->f_ci->op_count) > 1)
7153 smb_break_all_oplock(work, fp);
7155 rsp->StructureSize = cpu_to_le16(4);
7156 ksmbd_debug(SMB, "successful in taking lock\n");
7157 rsp->hdr.Status = STATUS_SUCCESS;
7159 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
7163 ksmbd_fd_put(work, fp);
7167 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7168 locks_free_lock(smb_lock->fl);
7169 list_del(&smb_lock->llist);
7173 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7174 struct file_lock *rlock = NULL;
7176 rlock = smb_flock_init(filp);
7177 rlock->fl_type = F_UNLCK;
7178 rlock->fl_start = smb_lock->start;
7179 rlock->fl_end = smb_lock->end;
7181 rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7183 pr_err("rollback unlock fail : %d\n", rc);
7185 list_del(&smb_lock->llist);
7186 spin_lock(&work->conn->llist_lock);
7187 if (!list_empty(&smb_lock->flist))
7188 list_del(&smb_lock->flist);
7189 list_del(&smb_lock->clist);
7190 spin_unlock(&work->conn->llist_lock);
7192 locks_free_lock(smb_lock->fl);
7193 locks_free_lock(rlock);
7197 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7199 if (!rsp->hdr.Status) {
7201 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7202 else if (err == -ENOMEM)
7203 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7204 else if (err == -ENOENT)
7205 rsp->hdr.Status = STATUS_FILE_CLOSED;
7207 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7210 smb2_set_err_rsp(work);
7211 ksmbd_fd_put(work, fp);
7215 static int fsctl_copychunk(struct ksmbd_work *work,
7216 struct copychunk_ioctl_req *ci_req,
7217 unsigned int cnt_code,
7218 unsigned int input_count,
7219 unsigned long long volatile_id,
7220 unsigned long long persistent_id,
7221 struct smb2_ioctl_rsp *rsp)
7223 struct copychunk_ioctl_rsp *ci_rsp;
7224 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7225 struct srv_copychunk *chunks;
7226 unsigned int i, chunk_count, chunk_count_written = 0;
7227 unsigned int chunk_size_written = 0;
7228 loff_t total_size_written = 0;
7231 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7233 rsp->VolatileFileId = volatile_id;
7234 rsp->PersistentFileId = persistent_id;
7235 ci_rsp->ChunksWritten =
7236 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7237 ci_rsp->ChunkBytesWritten =
7238 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7239 ci_rsp->TotalBytesWritten =
7240 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7242 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7243 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7244 if (chunk_count == 0)
7246 total_size_written = 0;
7248 /* verify the SRV_COPYCHUNK_COPY packet */
7249 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7250 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7251 chunk_count * sizeof(struct srv_copychunk)) {
7252 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7256 for (i = 0; i < chunk_count; i++) {
7257 if (le32_to_cpu(chunks[i].Length) == 0 ||
7258 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7260 total_size_written += le32_to_cpu(chunks[i].Length);
7263 if (i < chunk_count ||
7264 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7265 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7269 src_fp = ksmbd_lookup_foreign_fd(work,
7270 le64_to_cpu(ci_req->ResumeKey[0]));
7271 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7274 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7275 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7280 rsp->hdr.Status = STATUS_FILE_CLOSED;
7285 * FILE_READ_DATA should only be included in
7286 * the FSCTL_COPYCHUNK case
7288 if (cnt_code == FSCTL_COPYCHUNK &&
7289 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7290 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7294 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7295 chunks, chunk_count,
7296 &chunk_count_written,
7297 &chunk_size_written,
7298 &total_size_written);
7301 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7303 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7304 else if (ret == -EBADF)
7305 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7306 else if (ret == -EFBIG || ret == -ENOSPC)
7307 rsp->hdr.Status = STATUS_DISK_FULL;
7308 else if (ret == -EINVAL)
7309 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7310 else if (ret == -EISDIR)
7311 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7312 else if (ret == -E2BIG)
7313 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7315 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7318 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7319 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7320 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7322 ksmbd_fd_put(work, src_fp);
7323 ksmbd_fd_put(work, dst_fp);
7327 static __be32 idev_ipv4_address(struct in_device *idev)
7331 struct in_ifaddr *ifa;
7334 in_dev_for_each_ifa_rcu(ifa, idev) {
7335 if (ifa->ifa_flags & IFA_F_SECONDARY)
7338 addr = ifa->ifa_address;
7345 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7346 struct smb2_ioctl_rsp *rsp,
7347 unsigned int out_buf_len)
7349 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7351 struct net_device *netdev;
7352 struct sockaddr_storage_rsp *sockaddr_storage;
7354 unsigned long long speed;
7357 for_each_netdev(&init_net, netdev) {
7358 bool ipv4_set = false;
7360 if (netdev->type == ARPHRD_LOOPBACK)
7363 flags = dev_get_flags(netdev);
7364 if (!(flags & IFF_RUNNING))
7368 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7373 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7374 &rsp->Buffer[nbytes];
7375 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7377 nii_rsp->Capability = 0;
7378 if (netdev->real_num_tx_queues > 1)
7379 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7380 if (ksmbd_rdma_capable_netdev(netdev))
7381 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7383 nii_rsp->Next = cpu_to_le32(152);
7384 nii_rsp->Reserved = 0;
7386 if (netdev->ethtool_ops->get_link_ksettings) {
7387 struct ethtool_link_ksettings cmd;
7389 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7390 speed = cmd.base.speed;
7392 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7393 "speed is unknown, defaulting to 1Gb/sec");
7398 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7400 sockaddr_storage = (struct sockaddr_storage_rsp *)
7401 nii_rsp->SockAddr_Storage;
7402 memset(sockaddr_storage, 0, 128);
7405 struct in_device *idev;
7407 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7408 sockaddr_storage->addr4.Port = 0;
7410 idev = __in_dev_get_rtnl(netdev);
7413 sockaddr_storage->addr4.IPv4address =
7414 idev_ipv4_address(idev);
7415 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7419 struct inet6_dev *idev6;
7420 struct inet6_ifaddr *ifa;
7421 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7423 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7424 sockaddr_storage->addr6.Port = 0;
7425 sockaddr_storage->addr6.FlowInfo = 0;
7427 idev6 = __in6_dev_get(netdev);
7431 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7432 if (ifa->flags & (IFA_F_TENTATIVE |
7435 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7438 sockaddr_storage->addr6.ScopeId = 0;
7439 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7444 /* zero if this is last one */
7448 rsp->PersistentFileId = SMB2_NO_FID;
7449 rsp->VolatileFileId = SMB2_NO_FID;
7453 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7454 struct validate_negotiate_info_req *neg_req,
7455 struct validate_negotiate_info_rsp *neg_rsp,
7456 unsigned int in_buf_len)
7461 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7462 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7465 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7466 neg_req->DialectCount);
7467 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7472 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7477 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7482 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7487 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7488 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7489 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7490 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7495 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7496 struct file_allocated_range_buffer *qar_req,
7497 struct file_allocated_range_buffer *qar_rsp,
7498 unsigned int in_count, unsigned int *out_count)
7500 struct ksmbd_file *fp;
7501 loff_t start, length;
7508 start = le64_to_cpu(qar_req->file_offset);
7509 length = le64_to_cpu(qar_req->length);
7511 if (start < 0 || length < 0)
7514 fp = ksmbd_lookup_fd_fast(work, id);
7518 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7519 qar_rsp, in_count, out_count);
7520 if (ret && ret != -E2BIG)
7523 ksmbd_fd_put(work, fp);
7527 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7528 unsigned int out_buf_len,
7529 struct smb2_ioctl_req *req,
7530 struct smb2_ioctl_rsp *rsp)
7532 struct ksmbd_rpc_command *rpc_resp;
7533 char *data_buf = (char *)&req->Buffer[0];
7536 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7537 le32_to_cpu(req->InputCount));
7539 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7541 * set STATUS_SOME_NOT_MAPPED response
7542 * for unknown domain sid.
7544 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7545 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7546 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7548 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7549 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7553 nbytes = rpc_resp->payload_sz;
7554 if (rpc_resp->payload_sz > out_buf_len) {
7555 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7556 nbytes = out_buf_len;
7559 if (!rpc_resp->payload_sz) {
7561 STATUS_UNEXPECTED_IO_ERROR;
7565 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7572 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7573 struct file_sparse *sparse)
7575 struct ksmbd_file *fp;
7576 struct mnt_idmap *idmap;
7580 fp = ksmbd_lookup_fd_fast(work, id);
7583 idmap = file_mnt_idmap(fp->filp);
7585 old_fattr = fp->f_ci->m_fattr;
7586 if (sparse->SetSparse)
7587 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7589 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7591 if (fp->f_ci->m_fattr != old_fattr &&
7592 test_share_config_flag(work->tcon->share_conf,
7593 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7594 struct xattr_dos_attrib da;
7596 ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
7597 fp->filp->f_path.dentry, &da);
7601 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7602 ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
7606 fp->f_ci->m_fattr = old_fattr;
7610 ksmbd_fd_put(work, fp);
7614 static int fsctl_request_resume_key(struct ksmbd_work *work,
7615 struct smb2_ioctl_req *req,
7616 struct resume_key_ioctl_rsp *key_rsp)
7618 struct ksmbd_file *fp;
7620 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7624 memset(key_rsp, 0, sizeof(*key_rsp));
7625 key_rsp->ResumeKey[0] = req->VolatileFileId;
7626 key_rsp->ResumeKey[1] = req->PersistentFileId;
7627 ksmbd_fd_put(work, fp);
7633 * smb2_ioctl() - handler for smb2 ioctl command
7634 * @work: smb work containing ioctl command buffer
7636 * Return: 0 on success, otherwise error
7638 int smb2_ioctl(struct ksmbd_work *work)
7640 struct smb2_ioctl_req *req;
7641 struct smb2_ioctl_rsp *rsp;
7642 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7643 u64 id = KSMBD_NO_FID;
7644 struct ksmbd_conn *conn = work->conn;
7647 if (work->next_smb2_rcv_hdr_off) {
7648 req = ksmbd_req_buf_next(work);
7649 rsp = ksmbd_resp_buf_next(work);
7650 if (!has_file_id(req->VolatileFileId)) {
7651 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7652 work->compound_fid);
7653 id = work->compound_fid;
7656 req = smb2_get_msg(work->request_buf);
7657 rsp = smb2_get_msg(work->response_buf);
7660 if (!has_file_id(id))
7661 id = req->VolatileFileId;
7663 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7664 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7668 cnt_code = le32_to_cpu(req->CtlCode);
7669 ret = smb2_calc_max_out_buf_len(work, 48,
7670 le32_to_cpu(req->MaxOutputResponse));
7672 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7675 out_buf_len = (unsigned int)ret;
7676 in_buf_len = le32_to_cpu(req->InputCount);
7679 case FSCTL_DFS_GET_REFERRALS:
7680 case FSCTL_DFS_GET_REFERRALS_EX:
7681 /* Not support DFS yet */
7682 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7684 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7686 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7688 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7689 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7693 * TODO: This is dummy implementation to pass smbtorture
7694 * Need to check correct response later
7696 memset(obj_buf->ObjectId, 0x0, 16);
7697 memset(obj_buf->BirthVolumeId, 0x0, 16);
7698 memset(obj_buf->BirthObjectId, 0x0, 16);
7699 memset(obj_buf->DomainId, 0x0, 16);
7703 case FSCTL_PIPE_TRANSCEIVE:
7704 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7705 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7707 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7708 if (conn->dialect < SMB30_PROT_ID) {
7713 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
7719 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
7724 ret = fsctl_validate_negotiate_info(conn,
7725 (struct validate_negotiate_info_req *)&req->Buffer[0],
7726 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7731 nbytes = sizeof(struct validate_negotiate_info_rsp);
7732 rsp->PersistentFileId = SMB2_NO_FID;
7733 rsp->VolatileFileId = SMB2_NO_FID;
7735 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7736 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7741 case FSCTL_REQUEST_RESUME_KEY:
7742 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7747 ret = fsctl_request_resume_key(work, req,
7748 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7751 rsp->PersistentFileId = req->PersistentFileId;
7752 rsp->VolatileFileId = req->VolatileFileId;
7753 nbytes = sizeof(struct resume_key_ioctl_rsp);
7755 case FSCTL_COPYCHUNK:
7756 case FSCTL_COPYCHUNK_WRITE:
7757 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7759 "User does not have write permission\n");
7764 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7769 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7774 nbytes = sizeof(struct copychunk_ioctl_rsp);
7775 rsp->VolatileFileId = req->VolatileFileId;
7776 rsp->PersistentFileId = req->PersistentFileId;
7777 fsctl_copychunk(work,
7778 (struct copychunk_ioctl_req *)&req->Buffer[0],
7779 le32_to_cpu(req->CtlCode),
7780 le32_to_cpu(req->InputCount),
7781 req->VolatileFileId,
7782 req->PersistentFileId,
7785 case FSCTL_SET_SPARSE:
7786 if (in_buf_len < sizeof(struct file_sparse)) {
7791 ret = fsctl_set_sparse(work, id,
7792 (struct file_sparse *)&req->Buffer[0]);
7796 case FSCTL_SET_ZERO_DATA:
7798 struct file_zero_data_information *zero_data;
7799 struct ksmbd_file *fp;
7800 loff_t off, len, bfz;
7802 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7804 "User does not have write permission\n");
7809 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7815 (struct file_zero_data_information *)&req->Buffer[0];
7817 off = le64_to_cpu(zero_data->FileOffset);
7818 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
7819 if (off < 0 || bfz < 0 || off > bfz) {
7826 fp = ksmbd_lookup_fd_fast(work, id);
7832 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7833 ksmbd_fd_put(work, fp);
7839 case FSCTL_QUERY_ALLOCATED_RANGES:
7840 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7845 ret = fsctl_query_allocated_ranges(work, id,
7846 (struct file_allocated_range_buffer *)&req->Buffer[0],
7847 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7849 sizeof(struct file_allocated_range_buffer), &nbytes);
7850 if (ret == -E2BIG) {
7851 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7852 } else if (ret < 0) {
7857 nbytes *= sizeof(struct file_allocated_range_buffer);
7859 case FSCTL_GET_REPARSE_POINT:
7861 struct reparse_data_buffer *reparse_ptr;
7862 struct ksmbd_file *fp;
7864 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7865 fp = ksmbd_lookup_fd_fast(work, id);
7867 pr_err("not found fp!!\n");
7872 reparse_ptr->ReparseTag =
7873 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7874 reparse_ptr->ReparseDataLength = 0;
7875 ksmbd_fd_put(work, fp);
7876 nbytes = sizeof(struct reparse_data_buffer);
7879 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7881 struct ksmbd_file *fp_in, *fp_out = NULL;
7882 struct duplicate_extents_to_file *dup_ext;
7883 loff_t src_off, dst_off, length, cloned;
7885 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7890 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7892 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7893 dup_ext->PersistentFileHandle);
7895 pr_err("not found file handle in duplicate extent to file\n");
7900 fp_out = ksmbd_lookup_fd_fast(work, id);
7902 pr_err("not found fp\n");
7907 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7908 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7909 length = le64_to_cpu(dup_ext->ByteCount);
7911 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
7912 * should fall back to vfs_copy_file_range(). This could be
7913 * beneficial when re-exporting nfs/smb mount, but note that
7914 * this can result in partial copy that returns an error status.
7915 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
7916 * fall back to vfs_copy_file_range(), should be avoided when
7917 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
7919 cloned = vfs_clone_file_range(fp_in->filp, src_off,
7920 fp_out->filp, dst_off, length, 0);
7921 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7924 } else if (cloned != length) {
7925 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7926 fp_out->filp, dst_off,
7928 if (cloned != length) {
7937 ksmbd_fd_put(work, fp_in);
7938 ksmbd_fd_put(work, fp_out);
7944 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7950 rsp->CtlCode = cpu_to_le32(cnt_code);
7951 rsp->InputCount = cpu_to_le32(0);
7952 rsp->InputOffset = cpu_to_le32(112);
7953 rsp->OutputOffset = cpu_to_le32(112);
7954 rsp->OutputCount = cpu_to_le32(nbytes);
7955 rsp->StructureSize = cpu_to_le16(49);
7956 rsp->Reserved = cpu_to_le16(0);
7957 rsp->Flags = cpu_to_le32(0);
7958 rsp->Reserved2 = cpu_to_le32(0);
7959 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
7965 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7966 else if (ret == -ENOENT)
7967 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7968 else if (ret == -EOPNOTSUPP)
7969 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7970 else if (ret == -ENOSPC)
7971 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7972 else if (ret < 0 || rsp->hdr.Status == 0)
7973 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7974 smb2_set_err_rsp(work);
7979 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7980 * @work: smb work containing oplock break command buffer
7984 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7986 struct smb2_oplock_break *req;
7987 struct smb2_oplock_break *rsp;
7988 struct ksmbd_file *fp;
7989 struct oplock_info *opinfo = NULL;
7992 u64 volatile_id, persistent_id;
7993 char req_oplevel = 0, rsp_oplevel = 0;
7994 unsigned int oplock_change_type;
7996 WORK_BUFFERS(work, req, rsp);
7998 volatile_id = req->VolatileFid;
7999 persistent_id = req->PersistentFid;
8000 req_oplevel = req->OplockLevel;
8001 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
8002 volatile_id, persistent_id, req_oplevel);
8004 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
8006 rsp->hdr.Status = STATUS_FILE_CLOSED;
8007 smb2_set_err_rsp(work);
8011 opinfo = opinfo_get(fp);
8013 pr_err("unexpected null oplock_info\n");
8014 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8015 smb2_set_err_rsp(work);
8016 ksmbd_fd_put(work, fp);
8020 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
8021 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8025 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8026 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
8027 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8031 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8032 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8033 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
8034 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
8035 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8036 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8037 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8038 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
8039 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8040 oplock_change_type = OPLOCK_READ_TO_NONE;
8041 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
8042 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8043 err = STATUS_INVALID_DEVICE_STATE;
8044 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8045 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8046 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8047 oplock_change_type = OPLOCK_WRITE_TO_READ;
8048 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8049 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8050 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8051 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8052 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8053 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8054 oplock_change_type = OPLOCK_READ_TO_NONE;
8056 oplock_change_type = 0;
8059 oplock_change_type = 0;
8062 switch (oplock_change_type) {
8063 case OPLOCK_WRITE_TO_READ:
8064 ret = opinfo_write_to_read(opinfo);
8065 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8067 case OPLOCK_WRITE_TO_NONE:
8068 ret = opinfo_write_to_none(opinfo);
8069 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8071 case OPLOCK_READ_TO_NONE:
8072 ret = opinfo_read_to_none(opinfo);
8073 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8076 pr_err("unknown oplock change 0x%x -> 0x%x\n",
8077 opinfo->level, rsp_oplevel);
8081 rsp->hdr.Status = err;
8085 opinfo->op_state = OPLOCK_STATE_NONE;
8086 wake_up_interruptible_all(&opinfo->oplock_q);
8088 ksmbd_fd_put(work, fp);
8090 rsp->StructureSize = cpu_to_le16(24);
8091 rsp->OplockLevel = rsp_oplevel;
8094 rsp->VolatileFid = volatile_id;
8095 rsp->PersistentFid = persistent_id;
8096 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
8101 opinfo->op_state = OPLOCK_STATE_NONE;
8102 wake_up_interruptible_all(&opinfo->oplock_q);
8105 ksmbd_fd_put(work, fp);
8106 smb2_set_err_rsp(work);
8109 static int check_lease_state(struct lease *lease, __le32 req_state)
8111 if ((lease->new_state ==
8112 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8113 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8114 lease->new_state = req_state;
8118 if (lease->new_state == req_state)
8125 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8126 * @work: smb work containing lease break command buffer
8130 static void smb21_lease_break_ack(struct ksmbd_work *work)
8132 struct ksmbd_conn *conn = work->conn;
8133 struct smb2_lease_ack *req;
8134 struct smb2_lease_ack *rsp;
8135 struct oplock_info *opinfo;
8138 unsigned int lease_change_type;
8140 struct lease *lease;
8142 WORK_BUFFERS(work, req, rsp);
8144 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8145 le32_to_cpu(req->LeaseState));
8146 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8148 ksmbd_debug(OPLOCK, "file not opened\n");
8149 smb2_set_err_rsp(work);
8150 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8153 lease = opinfo->o_lease;
8155 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8156 pr_err("unexpected lease break state 0x%x\n",
8158 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8162 if (check_lease_state(lease, req->LeaseState)) {
8163 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8165 "req lease state: 0x%x, expected state: 0x%x\n",
8166 req->LeaseState, lease->new_state);
8170 if (!atomic_read(&opinfo->breaking_cnt)) {
8171 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8175 /* check for bad lease state */
8176 if (req->LeaseState &
8177 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8178 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8179 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8180 lease_change_type = OPLOCK_WRITE_TO_NONE;
8182 lease_change_type = OPLOCK_READ_TO_NONE;
8183 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8184 le32_to_cpu(lease->state),
8185 le32_to_cpu(req->LeaseState));
8186 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8187 req->LeaseState != SMB2_LEASE_NONE_LE) {
8188 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8189 lease_change_type = OPLOCK_READ_TO_NONE;
8190 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8191 le32_to_cpu(lease->state),
8192 le32_to_cpu(req->LeaseState));
8194 /* valid lease state changes */
8195 err = STATUS_INVALID_DEVICE_STATE;
8196 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8197 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8198 lease_change_type = OPLOCK_WRITE_TO_NONE;
8200 lease_change_type = OPLOCK_READ_TO_NONE;
8201 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8202 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8203 lease_change_type = OPLOCK_WRITE_TO_READ;
8205 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8207 lease_change_type = 0;
8211 switch (lease_change_type) {
8212 case OPLOCK_WRITE_TO_READ:
8213 ret = opinfo_write_to_read(opinfo);
8215 case OPLOCK_READ_HANDLE_TO_READ:
8216 ret = opinfo_read_handle_to_read(opinfo);
8218 case OPLOCK_WRITE_TO_NONE:
8219 ret = opinfo_write_to_none(opinfo);
8221 case OPLOCK_READ_TO_NONE:
8222 ret = opinfo_read_to_none(opinfo);
8225 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8226 le32_to_cpu(lease->state),
8227 le32_to_cpu(req->LeaseState));
8231 rsp->hdr.Status = err;
8235 lease_state = lease->state;
8236 opinfo->op_state = OPLOCK_STATE_NONE;
8237 wake_up_interruptible_all(&opinfo->oplock_q);
8238 atomic_dec(&opinfo->breaking_cnt);
8239 wake_up_interruptible_all(&opinfo->oplock_brk);
8242 rsp->StructureSize = cpu_to_le16(36);
8245 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8246 rsp->LeaseState = lease_state;
8247 rsp->LeaseDuration = 0;
8248 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
8253 wake_up_interruptible_all(&opinfo->oplock_q);
8254 atomic_dec(&opinfo->breaking_cnt);
8255 wake_up_interruptible_all(&opinfo->oplock_brk);
8258 smb2_set_err_rsp(work);
8262 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8263 * @work: smb work containing oplock/lease break command buffer
8267 int smb2_oplock_break(struct ksmbd_work *work)
8269 struct smb2_oplock_break *req;
8270 struct smb2_oplock_break *rsp;
8272 WORK_BUFFERS(work, req, rsp);
8274 switch (le16_to_cpu(req->StructureSize)) {
8275 case OP_BREAK_STRUCT_SIZE_20:
8276 smb20_oplock_break_ack(work);
8278 case OP_BREAK_STRUCT_SIZE_21:
8279 smb21_lease_break_ack(work);
8282 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8283 le16_to_cpu(req->StructureSize));
8284 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8285 smb2_set_err_rsp(work);
8292 * smb2_notify() - handler for smb2 notify request
8293 * @work: smb work containing notify command buffer
8297 int smb2_notify(struct ksmbd_work *work)
8299 struct smb2_change_notify_req *req;
8300 struct smb2_change_notify_rsp *rsp;
8302 WORK_BUFFERS(work, req, rsp);
8304 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8305 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8306 smb2_set_err_rsp(work);
8310 smb2_set_err_rsp(work);
8311 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8316 * smb2_is_sign_req() - handler for checking packet signing status
8317 * @work: smb work containing notify command buffer
8318 * @command: SMB2 command id
8320 * Return: true if packed is signed, false otherwise
8322 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8324 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8326 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8327 command != SMB2_NEGOTIATE_HE &&
8328 command != SMB2_SESSION_SETUP_HE &&
8329 command != SMB2_OPLOCK_BREAK_HE)
8336 * smb2_check_sign_req() - handler for req packet sign processing
8337 * @work: smb work containing notify command buffer
8339 * Return: 1 on success, 0 otherwise
8341 int smb2_check_sign_req(struct ksmbd_work *work)
8343 struct smb2_hdr *hdr;
8344 char signature_req[SMB2_SIGNATURE_SIZE];
8345 char signature[SMB2_HMACSHA256_SIZE];
8349 hdr = smb2_get_msg(work->request_buf);
8350 if (work->next_smb2_rcv_hdr_off)
8351 hdr = ksmbd_req_buf_next(work);
8353 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8354 len = get_rfc1002_len(work->request_buf);
8355 else if (hdr->NextCommand)
8356 len = le32_to_cpu(hdr->NextCommand);
8358 len = get_rfc1002_len(work->request_buf) -
8359 work->next_smb2_rcv_hdr_off;
8361 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8362 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8364 iov[0].iov_base = (char *)&hdr->ProtocolId;
8365 iov[0].iov_len = len;
8367 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8371 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8372 pr_err("bad smb2 signature\n");
8380 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8381 * @work: smb work containing notify command buffer
8384 void smb2_set_sign_rsp(struct ksmbd_work *work)
8386 struct smb2_hdr *hdr;
8387 char signature[SMB2_HMACSHA256_SIZE];
8391 hdr = ksmbd_resp_buf_curr(work);
8392 hdr->Flags |= SMB2_FLAGS_SIGNED;
8393 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8395 if (hdr->Command == SMB2_READ) {
8396 iov = &work->iov[work->iov_idx - 1];
8399 iov = &work->iov[work->iov_idx];
8402 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8404 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8408 * smb3_check_sign_req() - handler for req packet sign processing
8409 * @work: smb work containing notify command buffer
8411 * Return: 1 on success, 0 otherwise
8413 int smb3_check_sign_req(struct ksmbd_work *work)
8415 struct ksmbd_conn *conn = work->conn;
8417 struct smb2_hdr *hdr;
8418 struct channel *chann;
8419 char signature_req[SMB2_SIGNATURE_SIZE];
8420 char signature[SMB2_CMACAES_SIZE];
8424 hdr = smb2_get_msg(work->request_buf);
8425 if (work->next_smb2_rcv_hdr_off)
8426 hdr = ksmbd_req_buf_next(work);
8428 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8429 len = get_rfc1002_len(work->request_buf);
8430 else if (hdr->NextCommand)
8431 len = le32_to_cpu(hdr->NextCommand);
8433 len = get_rfc1002_len(work->request_buf) -
8434 work->next_smb2_rcv_hdr_off;
8436 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8437 signing_key = work->sess->smb3signingkey;
8439 chann = lookup_chann_list(work->sess, conn);
8443 signing_key = chann->smb3signingkey;
8447 pr_err("SMB3 signing key is not generated\n");
8451 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8452 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8453 iov[0].iov_base = (char *)&hdr->ProtocolId;
8454 iov[0].iov_len = len;
8456 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8459 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8460 pr_err("bad smb2 signature\n");
8468 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8469 * @work: smb work containing notify command buffer
8472 void smb3_set_sign_rsp(struct ksmbd_work *work)
8474 struct ksmbd_conn *conn = work->conn;
8475 struct smb2_hdr *hdr;
8476 struct channel *chann;
8477 char signature[SMB2_CMACAES_SIZE];
8482 hdr = ksmbd_resp_buf_curr(work);
8484 if (conn->binding == false &&
8485 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8486 signing_key = work->sess->smb3signingkey;
8488 chann = lookup_chann_list(work->sess, work->conn);
8492 signing_key = chann->smb3signingkey;
8498 hdr->Flags |= SMB2_FLAGS_SIGNED;
8499 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8501 if (hdr->Command == SMB2_READ) {
8502 iov = &work->iov[work->iov_idx - 1];
8505 iov = &work->iov[work->iov_idx];
8508 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec,
8510 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8514 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8515 * @work: smb work containing response buffer
8518 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8520 struct ksmbd_conn *conn = work->conn;
8521 struct ksmbd_session *sess = work->sess;
8522 struct smb2_hdr *req, *rsp;
8524 if (conn->dialect != SMB311_PROT_ID)
8527 WORK_BUFFERS(work, req, rsp);
8529 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8531 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8532 conn->preauth_info->Preauth_HashValue);
8534 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8537 if (conn->binding) {
8538 struct preauth_session *preauth_sess;
8540 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8543 hash_value = preauth_sess->Preauth_HashValue;
8545 hash_value = sess->Preauth_HashValue;
8549 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8554 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8556 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8557 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8558 unsigned int orig_len = get_rfc1002_len(old_buf);
8560 /* tr_buf must be cleared by the caller */
8561 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8562 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8563 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8564 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8565 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8566 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8568 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8569 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8570 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8571 inc_rfc1001_len(tr_buf, orig_len);
8574 int smb3_encrypt_resp(struct ksmbd_work *work)
8576 struct kvec *iov = work->iov;
8580 tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8584 /* fill transform header */
8585 fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
8587 iov[0].iov_base = tr_buf;
8588 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8589 work->tr_buf = tr_buf;
8591 return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
8594 bool smb3_is_transform_hdr(void *buf)
8596 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8598 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8601 int smb3_decrypt_req(struct ksmbd_work *work)
8603 struct ksmbd_session *sess;
8604 char *buf = work->request_buf;
8605 unsigned int pdu_length = get_rfc1002_len(buf);
8607 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8608 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8611 if (pdu_length < sizeof(struct smb2_transform_hdr) ||
8612 buf_data_size < sizeof(struct smb2_hdr)) {
8613 pr_err("Transform message is too small (%u)\n",
8615 return -ECONNABORTED;
8618 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8619 pr_err("Transform message is broken\n");
8620 return -ECONNABORTED;
8623 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8625 pr_err("invalid session id(%llx) in transform header\n",
8626 le64_to_cpu(tr_hdr->SessionId));
8627 return -ECONNABORTED;
8630 iov[0].iov_base = buf;
8631 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8632 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8633 iov[1].iov_len = buf_data_size;
8634 rc = ksmbd_crypt_message(work, iov, 2, 0);
8638 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8639 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8644 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8646 struct ksmbd_conn *conn = work->conn;
8647 struct ksmbd_session *sess = work->sess;
8648 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8650 if (conn->dialect < SMB30_PROT_ID)
8653 if (work->next_smb2_rcv_hdr_off)
8654 rsp = ksmbd_resp_buf_next(work);
8656 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8657 sess->user && !user_guest(sess->user) &&
8658 rsp->Status == STATUS_SUCCESS)