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