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