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