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