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