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