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