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