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