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