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