994b95b6b3c2e7f13e4545c9494fbba669f70a13
[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 inline int check_context_err(void *ctx, char *str)
2130 {
2131         int err;
2132
2133         err = PTR_ERR(ctx);
2134         ksmbd_debug(SMB, "find context %s err %d\n", str, err);
2135
2136         if (err == -EINVAL) {
2137                 pr_err("bad name length\n");
2138                 return err;
2139         }
2140
2141         return 0;
2142 }
2143
2144 static noinline int smb2_set_stream_name_xattr(struct path *path,
2145                                                struct ksmbd_file *fp,
2146                                                char *stream_name, int s_type)
2147 {
2148         struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2149         size_t xattr_stream_size;
2150         char *xattr_stream_name;
2151         int rc;
2152
2153         rc = ksmbd_vfs_xattr_stream_name(stream_name,
2154                                          &xattr_stream_name,
2155                                          &xattr_stream_size,
2156                                          s_type);
2157         if (rc)
2158                 return rc;
2159
2160         fp->stream.name = xattr_stream_name;
2161         fp->stream.size = xattr_stream_size;
2162
2163         /* Check if there is stream prefix in xattr space */
2164         rc = ksmbd_vfs_casexattr_len(user_ns,
2165                                      path->dentry,
2166                                      xattr_stream_name,
2167                                      xattr_stream_size);
2168         if (rc >= 0)
2169                 return 0;
2170
2171         if (fp->cdoption == FILE_OPEN_LE) {
2172                 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2173                 return -EBADF;
2174         }
2175
2176         rc = ksmbd_vfs_setxattr(user_ns, path->dentry,
2177                                 xattr_stream_name, NULL, 0, 0);
2178         if (rc < 0)
2179                 pr_err("Failed to store XATTR stream name :%d\n", rc);
2180         return 0;
2181 }
2182
2183 static int smb2_remove_smb_xattrs(struct path *path)
2184 {
2185         struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2186         char *name, *xattr_list = NULL;
2187         ssize_t xattr_list_len;
2188         int err = 0;
2189
2190         xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2191         if (xattr_list_len < 0) {
2192                 goto out;
2193         } else if (!xattr_list_len) {
2194                 ksmbd_debug(SMB, "empty xattr in the file\n");
2195                 goto out;
2196         }
2197
2198         for (name = xattr_list; name - xattr_list < xattr_list_len;
2199                         name += strlen(name) + 1) {
2200                 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2201
2202                 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2203                     strncmp(&name[XATTR_USER_PREFIX_LEN], DOS_ATTRIBUTE_PREFIX,
2204                             DOS_ATTRIBUTE_PREFIX_LEN) &&
2205                     strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX, STREAM_PREFIX_LEN))
2206                         continue;
2207
2208                 err = ksmbd_vfs_remove_xattr(user_ns, path->dentry, name);
2209                 if (err)
2210                         ksmbd_debug(SMB, "remove xattr failed : %s\n", name);
2211         }
2212 out:
2213         kvfree(xattr_list);
2214         return err;
2215 }
2216
2217 static int smb2_create_truncate(struct path *path)
2218 {
2219         int rc = vfs_truncate(path, 0);
2220
2221         if (rc) {
2222                 pr_err("vfs_truncate failed, rc %d\n", rc);
2223                 return rc;
2224         }
2225
2226         rc = smb2_remove_smb_xattrs(path);
2227         if (rc == -EOPNOTSUPP)
2228                 rc = 0;
2229         if (rc)
2230                 ksmbd_debug(SMB,
2231                             "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2232                             rc);
2233         return rc;
2234 }
2235
2236 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, struct path *path,
2237                             struct ksmbd_file *fp)
2238 {
2239         struct xattr_dos_attrib da = {0};
2240         int rc;
2241
2242         if (!test_share_config_flag(tcon->share_conf,
2243                                     KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2244                 return;
2245
2246         da.version = 4;
2247         da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2248         da.itime = da.create_time = fp->create_time;
2249         da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2250                 XATTR_DOSINFO_ITIME;
2251
2252         rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_user_ns(path->mnt),
2253                                             path->dentry, &da);
2254         if (rc)
2255                 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2256 }
2257
2258 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2259                                struct path *path, struct ksmbd_file *fp)
2260 {
2261         struct xattr_dos_attrib da;
2262         int rc;
2263
2264         fp->f_ci->m_fattr &= ~(ATTR_HIDDEN_LE | ATTR_SYSTEM_LE);
2265
2266         /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2267         if (!test_share_config_flag(tcon->share_conf,
2268                                     KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2269                 return;
2270
2271         rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_user_ns(path->mnt),
2272                                             path->dentry, &da);
2273         if (rc > 0) {
2274                 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2275                 fp->create_time = da.create_time;
2276                 fp->itime = da.itime;
2277         }
2278 }
2279
2280 static int smb2_creat(struct ksmbd_work *work, struct path *path, char *name,
2281                       int open_flags, umode_t posix_mode, bool is_dir)
2282 {
2283         struct ksmbd_tree_connect *tcon = work->tcon;
2284         struct ksmbd_share_config *share = tcon->share_conf;
2285         umode_t mode;
2286         int rc;
2287
2288         if (!(open_flags & O_CREAT))
2289                 return -EBADF;
2290
2291         ksmbd_debug(SMB, "file does not exist, so creating\n");
2292         if (is_dir == true) {
2293                 ksmbd_debug(SMB, "creating directory\n");
2294
2295                 mode = share_config_directory_mode(share, posix_mode);
2296                 rc = ksmbd_vfs_mkdir(work, name, mode);
2297                 if (rc)
2298                         return rc;
2299         } else {
2300                 ksmbd_debug(SMB, "creating regular file\n");
2301
2302                 mode = share_config_create_mode(share, posix_mode);
2303                 rc = ksmbd_vfs_create(work, name, mode);
2304                 if (rc)
2305                         return rc;
2306         }
2307
2308         rc = ksmbd_vfs_kern_path(name, 0, path, 0);
2309         if (rc) {
2310                 pr_err("cannot get linux path (%s), err = %d\n",
2311                        name, rc);
2312                 return rc;
2313         }
2314         return 0;
2315 }
2316
2317 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2318                                  struct smb2_create_req *req,
2319                                  struct path *path)
2320 {
2321         struct create_context *context;
2322         int rc = -ENOENT;
2323
2324         if (!req->CreateContextsOffset)
2325                 return rc;
2326
2327         /* Parse SD BUFFER create contexts */
2328         context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER);
2329         if (context && !IS_ERR(context)) {
2330                 struct create_sd_buf_req *sd_buf;
2331
2332                 ksmbd_debug(SMB,
2333                             "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2334                 sd_buf = (struct create_sd_buf_req *)context;
2335                 rc = set_info_sec(work->conn, work->tcon,
2336                                   path, &sd_buf->ntsd,
2337                                   le32_to_cpu(sd_buf->ccontext.DataLength), true);
2338         }
2339
2340         return rc;
2341 }
2342
2343 static void ksmbd_acls_fattr(struct smb_fattr *fattr, struct inode *inode)
2344 {
2345         fattr->cf_uid = inode->i_uid;
2346         fattr->cf_gid = inode->i_gid;
2347         fattr->cf_mode = inode->i_mode;
2348         fattr->cf_dacls = NULL;
2349
2350         fattr->cf_acls = get_acl(inode, ACL_TYPE_ACCESS);
2351         if (S_ISDIR(inode->i_mode))
2352                 fattr->cf_dacls = get_acl(inode, ACL_TYPE_DEFAULT);
2353 }
2354
2355 /**
2356  * smb2_open() - handler for smb file open request
2357  * @work:       smb work containing request buffer
2358  *
2359  * Return:      0 on success, otherwise error
2360  */
2361 int smb2_open(struct ksmbd_work *work)
2362 {
2363         struct ksmbd_conn *conn = work->conn;
2364         struct ksmbd_session *sess = work->sess;
2365         struct ksmbd_tree_connect *tcon = work->tcon;
2366         struct smb2_create_req *req;
2367         struct smb2_create_rsp *rsp, *rsp_org;
2368         struct path path;
2369         struct ksmbd_share_config *share = tcon->share_conf;
2370         struct ksmbd_file *fp = NULL;
2371         struct file *filp = NULL;
2372         struct user_namespace *user_ns = NULL;
2373         struct kstat stat;
2374         struct create_context *context;
2375         struct lease_ctx_info *lc = NULL;
2376         struct create_ea_buf_req *ea_buf = NULL;
2377         struct oplock_info *opinfo;
2378         __le32 *next_ptr = NULL;
2379         int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2380         int rc = 0, len = 0;
2381         int contxt_cnt = 0, query_disk_id = 0;
2382         int maximal_access_ctxt = 0, posix_ctxt = 0;
2383         int s_type = 0;
2384         int next_off = 0;
2385         char *name = NULL;
2386         char *stream_name = NULL;
2387         bool file_present = false, created = false, already_permitted = false;
2388         int share_ret, need_truncate = 0;
2389         u64 time;
2390         umode_t posix_mode = 0;
2391         __le32 daccess, maximal_access = 0;
2392
2393         rsp_org = work->response_buf;
2394         WORK_BUFFERS(work, req, rsp);
2395
2396         if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2397             (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2398                 ksmbd_debug(SMB, "invalid flag in chained command\n");
2399                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2400                 smb2_set_err_rsp(work);
2401                 return -EINVAL;
2402         }
2403
2404         if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2405                 ksmbd_debug(SMB, "IPC pipe create request\n");
2406                 return create_smb2_pipe(work);
2407         }
2408
2409         if (req->NameLength) {
2410                 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2411                     *(char *)req->Buffer == '\\') {
2412                         pr_err("not allow directory name included leading slash\n");
2413                         rc = -EINVAL;
2414                         goto err_out1;
2415                 }
2416
2417                 name = smb2_get_name(share,
2418                                      req->Buffer,
2419                                      le16_to_cpu(req->NameLength),
2420                                      work->conn->local_nls);
2421                 if (IS_ERR(name)) {
2422                         rc = PTR_ERR(name);
2423                         if (rc != -ENOMEM)
2424                                 rc = -ENOENT;
2425                         goto err_out1;
2426                 }
2427
2428                 ksmbd_debug(SMB, "converted name = %s\n", name);
2429                 if (strchr(name, ':')) {
2430                         if (!test_share_config_flag(work->tcon->share_conf,
2431                                                     KSMBD_SHARE_FLAG_STREAMS)) {
2432                                 rc = -EBADF;
2433                                 goto err_out1;
2434                         }
2435                         rc = parse_stream_name(name, &stream_name, &s_type);
2436                         if (rc < 0)
2437                                 goto err_out1;
2438                 }
2439
2440                 rc = ksmbd_validate_filename(name);
2441                 if (rc < 0)
2442                         goto err_out1;
2443
2444                 if (ksmbd_share_veto_filename(share, name)) {
2445                         rc = -ENOENT;
2446                         ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2447                                     name);
2448                         goto err_out1;
2449                 }
2450         } else {
2451                 len = strlen(share->path);
2452                 ksmbd_debug(SMB, "share path len %d\n", len);
2453                 name = kmalloc(len + 1, GFP_KERNEL);
2454                 if (!name) {
2455                         rsp->hdr.Status = STATUS_NO_MEMORY;
2456                         rc = -ENOMEM;
2457                         goto err_out1;
2458                 }
2459
2460                 memcpy(name, share->path, len);
2461                 *(name + len) = '\0';
2462         }
2463
2464         req_op_level = req->RequestedOplockLevel;
2465         if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2466                 lc = parse_lease_state(req);
2467
2468         if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE_LE)) {
2469                 pr_err("Invalid impersonationlevel : 0x%x\n",
2470                        le32_to_cpu(req->ImpersonationLevel));
2471                 rc = -EIO;
2472                 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2473                 goto err_out1;
2474         }
2475
2476         if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK)) {
2477                 pr_err("Invalid create options : 0x%x\n",
2478                        le32_to_cpu(req->CreateOptions));
2479                 rc = -EINVAL;
2480                 goto err_out1;
2481         } else {
2482                 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2483                     req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2484                         req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2485
2486                 if (req->CreateOptions &
2487                     (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2488                      FILE_RESERVE_OPFILTER_LE)) {
2489                         rc = -EOPNOTSUPP;
2490                         goto err_out1;
2491                 }
2492
2493                 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2494                         if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2495                                 rc = -EINVAL;
2496                                 goto err_out1;
2497                         } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2498                                 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2499                         }
2500                 }
2501         }
2502
2503         if (le32_to_cpu(req->CreateDisposition) >
2504             le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2505                 pr_err("Invalid create disposition : 0x%x\n",
2506                        le32_to_cpu(req->CreateDisposition));
2507                 rc = -EINVAL;
2508                 goto err_out1;
2509         }
2510
2511         if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2512                 pr_err("Invalid desired access : 0x%x\n",
2513                        le32_to_cpu(req->DesiredAccess));
2514                 rc = -EACCES;
2515                 goto err_out1;
2516         }
2517
2518         if (req->FileAttributes && !(req->FileAttributes & ATTR_MASK_LE)) {
2519                 pr_err("Invalid file attribute : 0x%x\n",
2520                        le32_to_cpu(req->FileAttributes));
2521                 rc = -EINVAL;
2522                 goto err_out1;
2523         }
2524
2525         if (req->CreateContextsOffset) {
2526                 /* Parse non-durable handle create contexts */
2527                 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER);
2528                 if (IS_ERR(context)) {
2529                         rc = check_context_err(context, SMB2_CREATE_EA_BUFFER);
2530                         if (rc < 0)
2531                                 goto err_out1;
2532                 } else {
2533                         ea_buf = (struct create_ea_buf_req *)context;
2534                         if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2535                                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2536                                 rc = -EACCES;
2537                                 goto err_out1;
2538                         }
2539                 }
2540
2541                 context = smb2_find_context_vals(req,
2542                                                  SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST);
2543                 if (IS_ERR(context)) {
2544                         rc = check_context_err(context,
2545                                                SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST);
2546                         if (rc < 0)
2547                                 goto err_out1;
2548                 } else {
2549                         ksmbd_debug(SMB,
2550                                     "get query maximal access context\n");
2551                         maximal_access_ctxt = 1;
2552                 }
2553
2554                 context = smb2_find_context_vals(req,
2555                                                  SMB2_CREATE_TIMEWARP_REQUEST);
2556                 if (IS_ERR(context)) {
2557                         rc = check_context_err(context,
2558                                                SMB2_CREATE_TIMEWARP_REQUEST);
2559                         if (rc < 0)
2560                                 goto err_out1;
2561                 } else {
2562                         ksmbd_debug(SMB, "get timewarp context\n");
2563                         rc = -EBADF;
2564                         goto err_out1;
2565                 }
2566
2567                 if (tcon->posix_extensions) {
2568                         context = smb2_find_context_vals(req,
2569                                                          SMB2_CREATE_TAG_POSIX);
2570                         if (IS_ERR(context)) {
2571                                 rc = check_context_err(context,
2572                                                        SMB2_CREATE_TAG_POSIX);
2573                                 if (rc < 0)
2574                                         goto err_out1;
2575                         } else {
2576                                 struct create_posix *posix =
2577                                         (struct create_posix *)context;
2578                                 ksmbd_debug(SMB, "get posix context\n");
2579
2580                                 posix_mode = le32_to_cpu(posix->Mode);
2581                                 posix_ctxt = 1;
2582                         }
2583                 }
2584         }
2585
2586         if (ksmbd_override_fsids(work)) {
2587                 rc = -ENOMEM;
2588                 goto err_out1;
2589         }
2590
2591         if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2592                 /*
2593                  * On delete request, instead of following up, need to
2594                  * look the current entity
2595                  */
2596                 rc = ksmbd_vfs_kern_path(name, 0, &path, 1);
2597                 if (!rc) {
2598                         /*
2599                          * If file exists with under flags, return access
2600                          * denied error.
2601                          */
2602                         if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2603                             req->CreateDisposition == FILE_OPEN_IF_LE) {
2604                                 rc = -EACCES;
2605                                 path_put(&path);
2606                                 goto err_out;
2607                         }
2608
2609                         if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2610                                 ksmbd_debug(SMB,
2611                                             "User does not have write permission\n");
2612                                 rc = -EACCES;
2613                                 path_put(&path);
2614                                 goto err_out;
2615                         }
2616                 }
2617         } else {
2618                 if (test_share_config_flag(work->tcon->share_conf,
2619                                            KSMBD_SHARE_FLAG_FOLLOW_SYMLINKS)) {
2620                         /*
2621                          * Use LOOKUP_FOLLOW to follow the path of
2622                          * symlink in path buildup
2623                          */
2624                         rc = ksmbd_vfs_kern_path(name, LOOKUP_FOLLOW, &path, 1);
2625                         if (rc) { /* Case for broken link ?*/
2626                                 rc = ksmbd_vfs_kern_path(name, 0, &path, 1);
2627                         }
2628                 } else {
2629                         rc = ksmbd_vfs_kern_path(name, 0, &path, 1);
2630                         if (!rc && d_is_symlink(path.dentry)) {
2631                                 rc = -EACCES;
2632                                 path_put(&path);
2633                                 goto err_out;
2634                         }
2635                 }
2636         }
2637
2638         if (rc) {
2639                 if (rc == -EACCES) {
2640                         ksmbd_debug(SMB,
2641                                     "User does not have right permission\n");
2642                         goto err_out;
2643                 }
2644                 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2645                             name, rc);
2646                 rc = 0;
2647         } else {
2648                 file_present = true;
2649                 user_ns = mnt_user_ns(path.mnt);
2650                 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
2651         }
2652         if (stream_name) {
2653                 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2654                         if (s_type == DATA_STREAM) {
2655                                 rc = -EIO;
2656                                 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2657                         }
2658                 } else {
2659                         if (S_ISDIR(stat.mode) && s_type == DATA_STREAM) {
2660                                 rc = -EIO;
2661                                 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2662                         }
2663                 }
2664
2665                 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2666                     req->FileAttributes & ATTR_NORMAL_LE) {
2667                         rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2668                         rc = -EIO;
2669                 }
2670
2671                 if (rc < 0)
2672                         goto err_out;
2673         }
2674
2675         if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2676             S_ISDIR(stat.mode) && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2677                 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2678                             name, req->CreateOptions);
2679                 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2680                 rc = -EIO;
2681                 goto err_out;
2682         }
2683
2684         if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2685             !(req->CreateDisposition == FILE_CREATE_LE) &&
2686             !S_ISDIR(stat.mode)) {
2687                 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2688                 rc = -EIO;
2689                 goto err_out;
2690         }
2691
2692         if (!stream_name && file_present &&
2693             req->CreateDisposition == FILE_CREATE_LE) {
2694                 rc = -EEXIST;
2695                 goto err_out;
2696         }
2697
2698         daccess = smb_map_generic_desired_access(req->DesiredAccess);
2699
2700         if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2701                 rc = smb_check_perm_dacl(conn, &path, &daccess,
2702                                          sess->user->uid);
2703                 if (rc)
2704                         goto err_out;
2705         }
2706
2707         if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2708                 if (!file_present) {
2709                         daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2710                 } else {
2711                         rc = ksmbd_vfs_query_maximal_access(user_ns,
2712                                                             path.dentry,
2713                                                             &daccess);
2714                         if (rc)
2715                                 goto err_out;
2716                         already_permitted = true;
2717                 }
2718                 maximal_access = daccess;
2719         }
2720
2721         open_flags = smb2_create_open_flags(file_present, daccess,
2722                                             req->CreateDisposition,
2723                                             &may_flags);
2724
2725         if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2726                 if (open_flags & O_CREAT) {
2727                         ksmbd_debug(SMB,
2728                                     "User does not have write permission\n");
2729                         rc = -EACCES;
2730                         goto err_out;
2731                 }
2732         }
2733
2734         /*create file if not present */
2735         if (!file_present) {
2736                 rc = smb2_creat(work, &path, name, open_flags, posix_mode,
2737                                 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2738                 if (rc)
2739                         goto err_out;
2740
2741                 created = true;
2742                 user_ns = mnt_user_ns(path.mnt);
2743                 if (ea_buf) {
2744                         rc = smb2_set_ea(&ea_buf->ea, &path);
2745                         if (rc == -EOPNOTSUPP)
2746                                 rc = 0;
2747                         else if (rc)
2748                                 goto err_out;
2749                 }
2750         } else if (!already_permitted) {
2751                 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
2752                  * because execute(search) permission on a parent directory,
2753                  * is already granted.
2754                  */
2755                 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
2756                         rc = inode_permission(user_ns,
2757                                               d_inode(path.dentry),
2758                                               may_flags);
2759                         if (rc)
2760                                 goto err_out;
2761
2762                         if ((daccess & FILE_DELETE_LE) ||
2763                             (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2764                                 rc = ksmbd_vfs_may_delete(user_ns,
2765                                                           path.dentry);
2766                                 if (rc)
2767                                         goto err_out;
2768                         }
2769                 }
2770         }
2771
2772         rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
2773         if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
2774                 rc = -EBUSY;
2775                 goto err_out;
2776         }
2777
2778         rc = 0;
2779         filp = dentry_open(&path, open_flags, current_cred());
2780         if (IS_ERR(filp)) {
2781                 rc = PTR_ERR(filp);
2782                 pr_err("dentry open for dir failed, rc %d\n", rc);
2783                 goto err_out;
2784         }
2785
2786         if (file_present) {
2787                 if (!(open_flags & O_TRUNC))
2788                         file_info = FILE_OPENED;
2789                 else
2790                         file_info = FILE_OVERWRITTEN;
2791
2792                 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
2793                     FILE_SUPERSEDE_LE)
2794                         file_info = FILE_SUPERSEDED;
2795         } else if (open_flags & O_CREAT) {
2796                 file_info = FILE_CREATED;
2797         }
2798
2799         ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
2800
2801         /* Obtain Volatile-ID */
2802         fp = ksmbd_open_fd(work, filp);
2803         if (IS_ERR(fp)) {
2804                 fput(filp);
2805                 rc = PTR_ERR(fp);
2806                 fp = NULL;
2807                 goto err_out;
2808         }
2809
2810         /* Get Persistent-ID */
2811         ksmbd_open_durable_fd(fp);
2812         if (!HAS_FILE_ID(fp->persistent_id)) {
2813                 rc = -ENOMEM;
2814                 goto err_out;
2815         }
2816
2817         fp->filename = name;
2818         fp->cdoption = req->CreateDisposition;
2819         fp->daccess = daccess;
2820         fp->saccess = req->ShareAccess;
2821         fp->coption = req->CreateOptions;
2822
2823         /* Set default windows and posix acls if creating new file */
2824         if (created) {
2825                 int posix_acl_rc;
2826                 struct inode *inode = d_inode(path.dentry);
2827
2828                 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(user_ns,
2829                                                            inode,
2830                                                            d_inode(path.dentry->d_parent));
2831                 if (posix_acl_rc)
2832                         ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
2833
2834                 if (test_share_config_flag(work->tcon->share_conf,
2835                                            KSMBD_SHARE_FLAG_ACL_XATTR)) {
2836                         rc = smb_inherit_dacl(conn, &path, sess->user->uid,
2837                                               sess->user->gid);
2838                 }
2839
2840                 if (rc) {
2841                         rc = smb2_create_sd_buffer(work, req, &path);
2842                         if (rc) {
2843                                 if (posix_acl_rc)
2844                                         ksmbd_vfs_set_init_posix_acl(user_ns,
2845                                                                      inode);
2846
2847                                 if (test_share_config_flag(work->tcon->share_conf,
2848                                                            KSMBD_SHARE_FLAG_ACL_XATTR)) {
2849                                         struct smb_fattr fattr;
2850                                         struct smb_ntsd *pntsd;
2851                                         int pntsd_size, ace_num = 0;
2852
2853                                         ksmbd_acls_fattr(&fattr, inode);
2854                                         if (fattr.cf_acls)
2855                                                 ace_num = fattr.cf_acls->a_count;
2856                                         if (fattr.cf_dacls)
2857                                                 ace_num += fattr.cf_dacls->a_count;
2858
2859                                         pntsd = kmalloc(sizeof(struct smb_ntsd) +
2860                                                         sizeof(struct smb_sid) * 3 +
2861                                                         sizeof(struct smb_acl) +
2862                                                         sizeof(struct smb_ace) * ace_num * 2,
2863                                                         GFP_KERNEL);
2864                                         if (!pntsd)
2865                                                 goto err_out;
2866
2867                                         rc = build_sec_desc(user_ns,
2868                                                             pntsd, NULL,
2869                                                             OWNER_SECINFO |
2870                                                             GROUP_SECINFO |
2871                                                             DACL_SECINFO,
2872                                                             &pntsd_size, &fattr);
2873                                         posix_acl_release(fattr.cf_acls);
2874                                         posix_acl_release(fattr.cf_dacls);
2875
2876                                         rc = ksmbd_vfs_set_sd_xattr(conn,
2877                                                                     user_ns,
2878                                                                     path.dentry,
2879                                                                     pntsd,
2880                                                                     pntsd_size);
2881                                         kfree(pntsd);
2882                                         if (rc)
2883                                                 pr_err("failed to store ntacl in xattr : %d\n",
2884                                                        rc);
2885                                 }
2886                         }
2887                 }
2888                 rc = 0;
2889         }
2890
2891         if (stream_name) {
2892                 rc = smb2_set_stream_name_xattr(&path,
2893                                                 fp,
2894                                                 stream_name,
2895                                                 s_type);
2896                 if (rc)
2897                         goto err_out;
2898                 file_info = FILE_CREATED;
2899         }
2900
2901         fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
2902                         FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
2903         if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
2904             !fp->attrib_only && !stream_name) {
2905                 smb_break_all_oplock(work, fp);
2906                 need_truncate = 1;
2907         }
2908
2909         /* fp should be searchable through ksmbd_inode.m_fp_list
2910          * after daccess, saccess, attrib_only, and stream are
2911          * initialized.
2912          */
2913         write_lock(&fp->f_ci->m_lock);
2914         list_add(&fp->node, &fp->f_ci->m_fp_list);
2915         write_unlock(&fp->f_ci->m_lock);
2916
2917         rc = ksmbd_vfs_getattr(&path, &stat);
2918         if (rc) {
2919                 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
2920                 rc = 0;
2921         }
2922
2923         /* Check delete pending among previous fp before oplock break */
2924         if (ksmbd_inode_pending_delete(fp)) {
2925                 rc = -EBUSY;
2926                 goto err_out;
2927         }
2928
2929         share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
2930         if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
2931             (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
2932              !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
2933                 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
2934                         rc = share_ret;
2935                         goto err_out;
2936                 }
2937         } else {
2938                 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
2939                         req_op_level = smb2_map_lease_to_oplock(lc->req_state);
2940                         ksmbd_debug(SMB,
2941                                     "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
2942                                     name, req_op_level, lc->req_state);
2943                         rc = find_same_lease_key(sess, fp->f_ci, lc);
2944                         if (rc)
2945                                 goto err_out;
2946                 } else if (open_flags == O_RDONLY &&
2947                            (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
2948                             req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
2949                         req_op_level = SMB2_OPLOCK_LEVEL_II;
2950
2951                 rc = smb_grant_oplock(work, req_op_level,
2952                                       fp->persistent_id, fp,
2953                                       le32_to_cpu(req->hdr.Id.SyncId.TreeId),
2954                                       lc, share_ret);
2955                 if (rc < 0)
2956                         goto err_out;
2957         }
2958
2959         if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
2960                 ksmbd_fd_set_delete_on_close(fp, file_info);
2961
2962         if (need_truncate) {
2963                 rc = smb2_create_truncate(&path);
2964                 if (rc)
2965                         goto err_out;
2966         }
2967
2968         if (req->CreateContextsOffset) {
2969                 struct create_alloc_size_req *az_req;
2970
2971                 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
2972                                         SMB2_CREATE_ALLOCATION_SIZE);
2973                 if (IS_ERR(az_req)) {
2974                         rc = check_context_err(az_req,
2975                                                SMB2_CREATE_ALLOCATION_SIZE);
2976                         if (rc < 0)
2977                                 goto err_out;
2978                 } else {
2979                         loff_t alloc_size = le64_to_cpu(az_req->AllocationSize);
2980                         int err;
2981
2982                         ksmbd_debug(SMB,
2983                                     "request smb2 create allocate size : %llu\n",
2984                                     alloc_size);
2985                         smb_break_all_levII_oplock(work, fp, 1);
2986                         err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
2987                                             alloc_size);
2988                         if (err < 0)
2989                                 ksmbd_debug(SMB,
2990                                             "vfs_fallocate is failed : %d\n",
2991                                             err);
2992                 }
2993
2994                 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID);
2995                 if (IS_ERR(context)) {
2996                         rc = check_context_err(context, SMB2_CREATE_QUERY_ON_DISK_ID);
2997                         if (rc < 0)
2998                                 goto err_out;
2999                 } else {
3000                         ksmbd_debug(SMB, "get query on disk id context\n");
3001                         query_disk_id = 1;
3002                 }
3003         }
3004
3005         if (stat.result_mask & STATX_BTIME)
3006                 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3007         else
3008                 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3009         if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3010                 fp->f_ci->m_fattr =
3011                         cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3012
3013         if (!created)
3014                 smb2_update_xattrs(tcon, &path, fp);
3015         else
3016                 smb2_new_xattrs(tcon, &path, fp);
3017
3018         memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3019
3020         generic_fillattr(user_ns, file_inode(fp->filp),
3021                          &stat);
3022
3023         rsp->StructureSize = cpu_to_le16(89);
3024         rcu_read_lock();
3025         opinfo = rcu_dereference(fp->f_opinfo);
3026         rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3027         rcu_read_unlock();
3028         rsp->Reserved = 0;
3029         rsp->CreateAction = cpu_to_le32(file_info);
3030         rsp->CreationTime = cpu_to_le64(fp->create_time);
3031         time = ksmbd_UnixTimeToNT(stat.atime);
3032         rsp->LastAccessTime = cpu_to_le64(time);
3033         time = ksmbd_UnixTimeToNT(stat.mtime);
3034         rsp->LastWriteTime = cpu_to_le64(time);
3035         time = ksmbd_UnixTimeToNT(stat.ctime);
3036         rsp->ChangeTime = cpu_to_le64(time);
3037         rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3038                 cpu_to_le64(stat.blocks << 9);
3039         rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3040         rsp->FileAttributes = fp->f_ci->m_fattr;
3041
3042         rsp->Reserved2 = 0;
3043
3044         rsp->PersistentFileId = cpu_to_le64(fp->persistent_id);
3045         rsp->VolatileFileId = cpu_to_le64(fp->volatile_id);
3046
3047         rsp->CreateContextsOffset = 0;
3048         rsp->CreateContextsLength = 0;
3049         inc_rfc1001_len(rsp_org, 88); /* StructureSize - 1*/
3050
3051         /* If lease is request send lease context response */
3052         if (opinfo && opinfo->is_lease) {
3053                 struct create_context *lease_ccontext;
3054
3055                 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3056                             name, opinfo->o_lease->state);
3057                 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3058
3059                 lease_ccontext = (struct create_context *)rsp->Buffer;
3060                 contxt_cnt++;
3061                 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3062                 le32_add_cpu(&rsp->CreateContextsLength,
3063                              conn->vals->create_lease_size);
3064                 inc_rfc1001_len(rsp_org, conn->vals->create_lease_size);
3065                 next_ptr = &lease_ccontext->Next;
3066                 next_off = conn->vals->create_lease_size;
3067         }
3068
3069         if (maximal_access_ctxt) {
3070                 struct create_context *mxac_ccontext;
3071
3072                 if (maximal_access == 0)
3073                         ksmbd_vfs_query_maximal_access(user_ns,
3074                                                        path.dentry,
3075                                                        &maximal_access);
3076                 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3077                                 le32_to_cpu(rsp->CreateContextsLength));
3078                 contxt_cnt++;
3079                 create_mxac_rsp_buf(rsp->Buffer +
3080                                 le32_to_cpu(rsp->CreateContextsLength),
3081                                 le32_to_cpu(maximal_access));
3082                 le32_add_cpu(&rsp->CreateContextsLength,
3083                              conn->vals->create_mxac_size);
3084                 inc_rfc1001_len(rsp_org, conn->vals->create_mxac_size);
3085                 if (next_ptr)
3086                         *next_ptr = cpu_to_le32(next_off);
3087                 next_ptr = &mxac_ccontext->Next;
3088                 next_off = conn->vals->create_mxac_size;
3089         }
3090
3091         if (query_disk_id) {
3092                 struct create_context *disk_id_ccontext;
3093
3094                 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3095                                 le32_to_cpu(rsp->CreateContextsLength));
3096                 contxt_cnt++;
3097                 create_disk_id_rsp_buf(rsp->Buffer +
3098                                 le32_to_cpu(rsp->CreateContextsLength),
3099                                 stat.ino, tcon->id);
3100                 le32_add_cpu(&rsp->CreateContextsLength,
3101                              conn->vals->create_disk_id_size);
3102                 inc_rfc1001_len(rsp_org, conn->vals->create_disk_id_size);
3103                 if (next_ptr)
3104                         *next_ptr = cpu_to_le32(next_off);
3105                 next_ptr = &disk_id_ccontext->Next;
3106                 next_off = conn->vals->create_disk_id_size;
3107         }
3108
3109         if (posix_ctxt) {
3110                 contxt_cnt++;
3111                 create_posix_rsp_buf(rsp->Buffer +
3112                                 le32_to_cpu(rsp->CreateContextsLength),
3113                                 fp);
3114                 le32_add_cpu(&rsp->CreateContextsLength,
3115                              conn->vals->create_posix_size);
3116                 inc_rfc1001_len(rsp_org, conn->vals->create_posix_size);
3117                 if (next_ptr)
3118                         *next_ptr = cpu_to_le32(next_off);
3119         }
3120
3121         if (contxt_cnt > 0) {
3122                 rsp->CreateContextsOffset =
3123                         cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer)
3124                         - 4);
3125         }
3126
3127 err_out:
3128         if (file_present || created)
3129                 path_put(&path);
3130         ksmbd_revert_fsids(work);
3131 err_out1:
3132         if (rc) {
3133                 if (rc == -EINVAL)
3134                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3135                 else if (rc == -EOPNOTSUPP)
3136                         rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3137                 else if (rc == -EACCES || rc == -ESTALE)
3138                         rsp->hdr.Status = STATUS_ACCESS_DENIED;
3139                 else if (rc == -ENOENT)
3140                         rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3141                 else if (rc == -EPERM)
3142                         rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3143                 else if (rc == -EBUSY)
3144                         rsp->hdr.Status = STATUS_DELETE_PENDING;
3145                 else if (rc == -EBADF)
3146                         rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3147                 else if (rc == -ENOEXEC)
3148                         rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3149                 else if (rc == -ENXIO)
3150                         rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3151                 else if (rc == -EEXIST)
3152                         rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3153                 else if (rc == -EMFILE)
3154                         rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3155                 if (!rsp->hdr.Status)
3156                         rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3157
3158                 if (!fp || !fp->filename)
3159                         kfree(name);
3160                 if (fp)
3161                         ksmbd_fd_put(work, fp);
3162                 smb2_set_err_rsp(work);
3163                 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3164         }
3165
3166         kfree(lc);
3167
3168         return 0;
3169 }
3170
3171 static int readdir_info_level_struct_sz(int info_level)
3172 {
3173         switch (info_level) {
3174         case FILE_FULL_DIRECTORY_INFORMATION:
3175                 return sizeof(struct file_full_directory_info);
3176         case FILE_BOTH_DIRECTORY_INFORMATION:
3177                 return sizeof(struct file_both_directory_info);
3178         case FILE_DIRECTORY_INFORMATION:
3179                 return sizeof(struct file_directory_info);
3180         case FILE_NAMES_INFORMATION:
3181                 return sizeof(struct file_names_info);
3182         case FILEID_FULL_DIRECTORY_INFORMATION:
3183                 return sizeof(struct file_id_full_dir_info);
3184         case FILEID_BOTH_DIRECTORY_INFORMATION:
3185                 return sizeof(struct file_id_both_directory_info);
3186         case SMB_FIND_FILE_POSIX_INFO:
3187                 return sizeof(struct smb2_posix_info);
3188         default:
3189                 return -EOPNOTSUPP;
3190         }
3191 }
3192
3193 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3194 {
3195         switch (info_level) {
3196         case FILE_FULL_DIRECTORY_INFORMATION:
3197         {
3198                 struct file_full_directory_info *ffdinfo;
3199
3200                 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3201                 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3202                 d_info->name = ffdinfo->FileName;
3203                 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3204                 return 0;
3205         }
3206         case FILE_BOTH_DIRECTORY_INFORMATION:
3207         {
3208                 struct file_both_directory_info *fbdinfo;
3209
3210                 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3211                 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3212                 d_info->name = fbdinfo->FileName;
3213                 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3214                 return 0;
3215         }
3216         case FILE_DIRECTORY_INFORMATION:
3217         {
3218                 struct file_directory_info *fdinfo;
3219
3220                 fdinfo = (struct file_directory_info *)d_info->rptr;
3221                 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3222                 d_info->name = fdinfo->FileName;
3223                 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3224                 return 0;
3225         }
3226         case FILE_NAMES_INFORMATION:
3227         {
3228                 struct file_names_info *fninfo;
3229
3230                 fninfo = (struct file_names_info *)d_info->rptr;
3231                 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3232                 d_info->name = fninfo->FileName;
3233                 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3234                 return 0;
3235         }
3236         case FILEID_FULL_DIRECTORY_INFORMATION:
3237         {
3238                 struct file_id_full_dir_info *dinfo;
3239
3240                 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3241                 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3242                 d_info->name = dinfo->FileName;
3243                 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3244                 return 0;
3245         }
3246         case FILEID_BOTH_DIRECTORY_INFORMATION:
3247         {
3248                 struct file_id_both_directory_info *fibdinfo;
3249
3250                 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3251                 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3252                 d_info->name = fibdinfo->FileName;
3253                 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3254                 return 0;
3255         }
3256         case SMB_FIND_FILE_POSIX_INFO:
3257         {
3258                 struct smb2_posix_info *posix_info;
3259
3260                 posix_info = (struct smb2_posix_info *)d_info->rptr;
3261                 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3262                 d_info->name = posix_info->name;
3263                 d_info->name_len = le32_to_cpu(posix_info->name_len);
3264                 return 0;
3265         }
3266         default:
3267                 return -EINVAL;
3268         }
3269 }
3270
3271 /**
3272  * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3273  * buffer
3274  * @conn:       connection instance
3275  * @info_level: smb information level
3276  * @d_info:     structure included variables for query dir
3277  * @user_ns:    user namespace
3278  * @ksmbd_kstat:        ksmbd wrapper of dirent stat information
3279  *
3280  * if directory has many entries, find first can't read it fully.
3281  * find next might be called multiple times to read remaining dir entries
3282  *
3283  * Return:      0 on success, otherwise error
3284  */
3285 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3286                                        struct ksmbd_dir_info *d_info,
3287                                        struct user_namespace *user_ns,
3288                                        struct ksmbd_kstat *ksmbd_kstat)
3289 {
3290         int next_entry_offset = 0;
3291         char *conv_name;
3292         int conv_len;
3293         void *kstat;
3294         int struct_sz;
3295
3296         conv_name = ksmbd_convert_dir_info_name(d_info,
3297                                                 conn->local_nls,
3298                                                 &conv_len);
3299         if (!conv_name)
3300                 return -ENOMEM;
3301
3302         /* Somehow the name has only terminating NULL bytes */
3303         if (conv_len < 0) {
3304                 kfree(conv_name);
3305                 return -EINVAL;
3306         }
3307
3308         struct_sz = readdir_info_level_struct_sz(info_level);
3309         next_entry_offset = ALIGN(struct_sz - 1 + conv_len,
3310                                   KSMBD_DIR_INFO_ALIGNMENT);
3311
3312         if (next_entry_offset > d_info->out_buf_len) {
3313                 d_info->out_buf_len = 0;
3314                 return -ENOSPC;
3315         }
3316
3317         kstat = d_info->wptr;
3318         if (info_level != FILE_NAMES_INFORMATION)
3319                 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3320
3321         switch (info_level) {
3322         case FILE_FULL_DIRECTORY_INFORMATION:
3323         {
3324                 struct file_full_directory_info *ffdinfo;
3325
3326                 ffdinfo = (struct file_full_directory_info *)kstat;
3327                 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3328                 ffdinfo->EaSize =
3329                         smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3330                 if (ffdinfo->EaSize)
3331                         ffdinfo->ExtFileAttributes = ATTR_REPARSE_POINT_LE;
3332                 if (d_info->hide_dot_file && d_info->name[0] == '.')
3333                         ffdinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
3334                 memcpy(ffdinfo->FileName, conv_name, conv_len);
3335                 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3336                 break;
3337         }
3338         case FILE_BOTH_DIRECTORY_INFORMATION:
3339         {
3340                 struct file_both_directory_info *fbdinfo;
3341
3342                 fbdinfo = (struct file_both_directory_info *)kstat;
3343                 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3344                 fbdinfo->EaSize =
3345                         smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3346                 if (fbdinfo->EaSize)
3347                         fbdinfo->ExtFileAttributes = ATTR_REPARSE_POINT_LE;
3348                 fbdinfo->ShortNameLength = 0;
3349                 fbdinfo->Reserved = 0;
3350                 if (d_info->hide_dot_file && d_info->name[0] == '.')
3351                         fbdinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
3352                 memcpy(fbdinfo->FileName, conv_name, conv_len);
3353                 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3354                 break;
3355         }
3356         case FILE_DIRECTORY_INFORMATION:
3357         {
3358                 struct file_directory_info *fdinfo;
3359
3360                 fdinfo = (struct file_directory_info *)kstat;
3361                 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3362                 if (d_info->hide_dot_file && d_info->name[0] == '.')
3363                         fdinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
3364                 memcpy(fdinfo->FileName, conv_name, conv_len);
3365                 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3366                 break;
3367         }
3368         case FILE_NAMES_INFORMATION:
3369         {
3370                 struct file_names_info *fninfo;
3371
3372                 fninfo = (struct file_names_info *)kstat;
3373                 fninfo->FileNameLength = cpu_to_le32(conv_len);
3374                 memcpy(fninfo->FileName, conv_name, conv_len);
3375                 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3376                 break;
3377         }
3378         case FILEID_FULL_DIRECTORY_INFORMATION:
3379         {
3380                 struct file_id_full_dir_info *dinfo;
3381
3382                 dinfo = (struct file_id_full_dir_info *)kstat;
3383                 dinfo->FileNameLength = cpu_to_le32(conv_len);
3384                 dinfo->EaSize =
3385                         smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3386                 if (dinfo->EaSize)
3387                         dinfo->ExtFileAttributes = ATTR_REPARSE_POINT_LE;
3388                 dinfo->Reserved = 0;
3389                 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3390                 if (d_info->hide_dot_file && d_info->name[0] == '.')
3391                         dinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
3392                 memcpy(dinfo->FileName, conv_name, conv_len);
3393                 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3394                 break;
3395         }
3396         case FILEID_BOTH_DIRECTORY_INFORMATION:
3397         {
3398                 struct file_id_both_directory_info *fibdinfo;
3399
3400                 fibdinfo = (struct file_id_both_directory_info *)kstat;
3401                 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3402                 fibdinfo->EaSize =
3403                         smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3404                 if (fibdinfo->EaSize)
3405                         fibdinfo->ExtFileAttributes = ATTR_REPARSE_POINT_LE;
3406                 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3407                 fibdinfo->ShortNameLength = 0;
3408                 fibdinfo->Reserved = 0;
3409                 fibdinfo->Reserved2 = cpu_to_le16(0);
3410                 if (d_info->hide_dot_file && d_info->name[0] == '.')
3411                         fibdinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
3412                 memcpy(fibdinfo->FileName, conv_name, conv_len);
3413                 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3414                 break;
3415         }
3416         case SMB_FIND_FILE_POSIX_INFO:
3417         {
3418                 struct smb2_posix_info *posix_info;
3419                 u64 time;
3420
3421                 posix_info = (struct smb2_posix_info *)kstat;
3422                 posix_info->Ignored = 0;
3423                 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3424                 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3425                 posix_info->ChangeTime = cpu_to_le64(time);
3426                 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3427                 posix_info->LastAccessTime = cpu_to_le64(time);
3428                 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3429                 posix_info->LastWriteTime = cpu_to_le64(time);
3430                 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3431                 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3432                 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3433                 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3434                 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode);
3435                 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3436                 posix_info->DosAttributes =
3437                         S_ISDIR(ksmbd_kstat->kstat->mode) ? ATTR_DIRECTORY_LE : ATTR_ARCHIVE_LE;
3438                 if (d_info->hide_dot_file && d_info->name[0] == '.')
3439                         posix_info->DosAttributes |= ATTR_HIDDEN_LE;
3440                 id_to_sid(from_kuid(user_ns, ksmbd_kstat->kstat->uid),
3441                           SIDNFS_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3442                 id_to_sid(from_kgid(user_ns, ksmbd_kstat->kstat->gid),
3443                           SIDNFS_GROUP, (struct smb_sid *)&posix_info->SidBuffer[20]);
3444                 memcpy(posix_info->name, conv_name, conv_len);
3445                 posix_info->name_len = cpu_to_le32(conv_len);
3446                 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3447                 break;
3448         }
3449
3450         } /* switch (info_level) */
3451
3452         d_info->last_entry_offset = d_info->data_count;
3453         d_info->data_count += next_entry_offset;
3454         d_info->out_buf_len -= next_entry_offset;
3455         d_info->wptr += next_entry_offset;
3456         kfree(conv_name);
3457
3458         ksmbd_debug(SMB,
3459                     "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3460                     info_level, d_info->out_buf_len,
3461                     next_entry_offset, d_info->data_count);
3462
3463         return 0;
3464 }
3465
3466 struct smb2_query_dir_private {
3467         struct ksmbd_work       *work;
3468         char                    *search_pattern;
3469         struct ksmbd_file       *dir_fp;
3470
3471         struct ksmbd_dir_info   *d_info;
3472         int                     info_level;
3473 };
3474
3475 static void lock_dir(struct ksmbd_file *dir_fp)
3476 {
3477         struct dentry *dir = dir_fp->filp->f_path.dentry;
3478
3479         inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3480 }
3481
3482 static void unlock_dir(struct ksmbd_file *dir_fp)
3483 {
3484         struct dentry *dir = dir_fp->filp->f_path.dentry;
3485
3486         inode_unlock(d_inode(dir));
3487 }
3488
3489 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3490 {
3491         struct user_namespace   *user_ns = file_mnt_user_ns(priv->dir_fp->filp);
3492         struct kstat            kstat;
3493         struct ksmbd_kstat      ksmbd_kstat;
3494         int                     rc;
3495         int                     i;
3496
3497         for (i = 0; i < priv->d_info->num_entry; i++) {
3498                 struct dentry *dent;
3499
3500                 if (dentry_name(priv->d_info, priv->info_level))
3501                         return -EINVAL;
3502
3503                 lock_dir(priv->dir_fp);
3504                 dent = lookup_one_len(priv->d_info->name,
3505                                       priv->dir_fp->filp->f_path.dentry,
3506                                       priv->d_info->name_len);
3507                 unlock_dir(priv->dir_fp);
3508
3509                 if (IS_ERR(dent)) {
3510                         ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3511                                     priv->d_info->name,
3512                                     PTR_ERR(dent));
3513                         continue;
3514                 }
3515                 if (unlikely(d_is_negative(dent))) {
3516                         dput(dent);
3517                         ksmbd_debug(SMB, "Negative dentry `%s'\n",
3518                                     priv->d_info->name);
3519                         continue;
3520                 }
3521
3522                 ksmbd_kstat.kstat = &kstat;
3523                 if (priv->info_level != FILE_NAMES_INFORMATION)
3524                         ksmbd_vfs_fill_dentry_attrs(priv->work,
3525                                                     user_ns,
3526                                                     dent,
3527                                                     &ksmbd_kstat);
3528
3529                 rc = smb2_populate_readdir_entry(priv->work->conn,
3530                                                  priv->info_level,
3531                                                  priv->d_info,
3532                                                  user_ns,
3533                                                  &ksmbd_kstat);
3534                 dput(dent);
3535                 if (rc)
3536                         return rc;
3537         }
3538         return 0;
3539 }
3540
3541 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3542                                    int info_level)
3543 {
3544         int struct_sz;
3545         int conv_len;
3546         int next_entry_offset;
3547
3548         struct_sz = readdir_info_level_struct_sz(info_level);
3549         if (struct_sz == -EOPNOTSUPP)
3550                 return -EOPNOTSUPP;
3551
3552         conv_len = (d_info->name_len + 1) * 2;
3553         next_entry_offset = ALIGN(struct_sz - 1 + conv_len,
3554                                   KSMBD_DIR_INFO_ALIGNMENT);
3555
3556         if (next_entry_offset > d_info->out_buf_len) {
3557                 d_info->out_buf_len = 0;
3558                 return -ENOSPC;
3559         }
3560
3561         switch (info_level) {
3562         case FILE_FULL_DIRECTORY_INFORMATION:
3563         {
3564                 struct file_full_directory_info *ffdinfo;
3565
3566                 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3567                 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3568                 ffdinfo->FileName[d_info->name_len] = 0x00;
3569                 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3570                 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3571                 break;
3572         }
3573         case FILE_BOTH_DIRECTORY_INFORMATION:
3574         {
3575                 struct file_both_directory_info *fbdinfo;
3576
3577                 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3578                 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3579                 fbdinfo->FileName[d_info->name_len] = 0x00;
3580                 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3581                 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3582                 break;
3583         }
3584         case FILE_DIRECTORY_INFORMATION:
3585         {
3586                 struct file_directory_info *fdinfo;
3587
3588                 fdinfo = (struct file_directory_info *)d_info->wptr;
3589                 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3590                 fdinfo->FileName[d_info->name_len] = 0x00;
3591                 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3592                 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3593                 break;
3594         }
3595         case FILE_NAMES_INFORMATION:
3596         {
3597                 struct file_names_info *fninfo;
3598
3599                 fninfo = (struct file_names_info *)d_info->wptr;
3600                 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3601                 fninfo->FileName[d_info->name_len] = 0x00;
3602                 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3603                 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3604                 break;
3605         }
3606         case FILEID_FULL_DIRECTORY_INFORMATION:
3607         {
3608                 struct file_id_full_dir_info *dinfo;
3609
3610                 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3611                 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3612                 dinfo->FileName[d_info->name_len] = 0x00;
3613                 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3614                 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3615                 break;
3616         }
3617         case FILEID_BOTH_DIRECTORY_INFORMATION:
3618         {
3619                 struct file_id_both_directory_info *fibdinfo;
3620
3621                 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3622                 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3623                 fibdinfo->FileName[d_info->name_len] = 0x00;
3624                 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3625                 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3626                 break;
3627         }
3628         case SMB_FIND_FILE_POSIX_INFO:
3629         {
3630                 struct smb2_posix_info *posix_info;
3631
3632                 posix_info = (struct smb2_posix_info *)d_info->wptr;
3633                 memcpy(posix_info->name, d_info->name, d_info->name_len);
3634                 posix_info->name[d_info->name_len] = 0x00;
3635                 posix_info->name_len = cpu_to_le32(d_info->name_len);
3636                 posix_info->NextEntryOffset =
3637                         cpu_to_le32(next_entry_offset);
3638                 break;
3639         }
3640         } /* switch (info_level) */
3641
3642         d_info->num_entry++;
3643         d_info->out_buf_len -= next_entry_offset;
3644         d_info->wptr += next_entry_offset;
3645         return 0;
3646 }
3647
3648 static int __query_dir(struct dir_context *ctx, const char *name, int namlen,
3649                        loff_t offset, u64 ino, unsigned int d_type)
3650 {
3651         struct ksmbd_readdir_data       *buf;
3652         struct smb2_query_dir_private   *priv;
3653         struct ksmbd_dir_info           *d_info;
3654         int                             rc;
3655
3656         buf     = container_of(ctx, struct ksmbd_readdir_data, ctx);
3657         priv    = buf->private;
3658         d_info  = priv->d_info;
3659
3660         /* dot and dotdot entries are already reserved */
3661         if (!strcmp(".", name) || !strcmp("..", name))
3662                 return 0;
3663         if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3664                 return 0;
3665         if (!match_pattern(name, namlen, priv->search_pattern))
3666                 return 0;
3667
3668         d_info->name            = name;
3669         d_info->name_len        = namlen;
3670         rc = reserve_populate_dentry(d_info, priv->info_level);
3671         if (rc)
3672                 return rc;
3673         if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY) {
3674                 d_info->out_buf_len = 0;
3675                 return 0;
3676         }
3677         return 0;
3678 }
3679
3680 static void restart_ctx(struct dir_context *ctx)
3681 {
3682         ctx->pos = 0;
3683 }
3684
3685 static int verify_info_level(int info_level)
3686 {
3687         switch (info_level) {
3688         case FILE_FULL_DIRECTORY_INFORMATION:
3689         case FILE_BOTH_DIRECTORY_INFORMATION:
3690         case FILE_DIRECTORY_INFORMATION:
3691         case FILE_NAMES_INFORMATION:
3692         case FILEID_FULL_DIRECTORY_INFORMATION:
3693         case FILEID_BOTH_DIRECTORY_INFORMATION:
3694         case SMB_FIND_FILE_POSIX_INFO:
3695                 break;
3696         default:
3697                 return -EOPNOTSUPP;
3698         }
3699
3700         return 0;
3701 }
3702
3703 int smb2_query_dir(struct ksmbd_work *work)
3704 {
3705         struct ksmbd_conn *conn = work->conn;
3706         struct smb2_query_directory_req *req;
3707         struct smb2_query_directory_rsp *rsp, *rsp_org;
3708         struct ksmbd_share_config *share = work->tcon->share_conf;
3709         struct ksmbd_file *dir_fp = NULL;
3710         struct ksmbd_dir_info d_info;
3711         int rc = 0;
3712         char *srch_ptr = NULL;
3713         unsigned char srch_flag;
3714         int buffer_sz;
3715         struct smb2_query_dir_private query_dir_private = {NULL, };
3716
3717         rsp_org = work->response_buf;
3718         WORK_BUFFERS(work, req, rsp);
3719
3720         if (ksmbd_override_fsids(work)) {
3721                 rsp->hdr.Status = STATUS_NO_MEMORY;
3722                 smb2_set_err_rsp(work);
3723                 return -ENOMEM;
3724         }
3725
3726         rc = verify_info_level(req->FileInformationClass);
3727         if (rc) {
3728                 rc = -EFAULT;
3729                 goto err_out2;
3730         }
3731
3732         dir_fp = ksmbd_lookup_fd_slow(work,
3733                                       le64_to_cpu(req->VolatileFileId),
3734                                       le64_to_cpu(req->PersistentFileId));
3735         if (!dir_fp) {
3736                 rc = -EBADF;
3737                 goto err_out2;
3738         }
3739
3740         if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
3741             inode_permission(file_mnt_user_ns(dir_fp->filp),
3742                              file_inode(dir_fp->filp),
3743                              MAY_READ | MAY_EXEC)) {
3744                 pr_err("no right to enumerate directory (%pd)\n",
3745                        dir_fp->filp->f_path.dentry);
3746                 rc = -EACCES;
3747                 goto err_out2;
3748         }
3749
3750         if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
3751                 pr_err("can't do query dir for a file\n");
3752                 rc = -EINVAL;
3753                 goto err_out2;
3754         }
3755
3756         srch_flag = req->Flags;
3757         srch_ptr = smb_strndup_from_utf16(req->Buffer,
3758                                           le16_to_cpu(req->FileNameLength), 1,
3759                                           conn->local_nls);
3760         if (IS_ERR(srch_ptr)) {
3761                 ksmbd_debug(SMB, "Search Pattern not found\n");
3762                 rc = -EINVAL;
3763                 goto err_out2;
3764         } else {
3765                 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
3766         }
3767
3768         ksmbd_debug(SMB, "Directory name is %s\n", dir_fp->filename);
3769
3770         if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
3771                 ksmbd_debug(SMB, "Restart directory scan\n");
3772                 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
3773                 restart_ctx(&dir_fp->readdir_data.ctx);
3774         }
3775
3776         memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
3777         d_info.wptr = (char *)rsp->Buffer;
3778         d_info.rptr = (char *)rsp->Buffer;
3779         d_info.out_buf_len = (work->response_sz - (get_rfc1002_len(rsp_org) + 4));
3780         d_info.out_buf_len = min_t(int, d_info.out_buf_len, le32_to_cpu(req->OutputBufferLength)) -
3781                 sizeof(struct smb2_query_directory_rsp);
3782         d_info.flags = srch_flag;
3783
3784         /*
3785          * reserve dot and dotdot entries in head of buffer
3786          * in first response
3787          */
3788         rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
3789                                                dir_fp, &d_info, srch_ptr,
3790                                                smb2_populate_readdir_entry);
3791         if (rc == -ENOSPC)
3792                 rc = 0;
3793         else if (rc)
3794                 goto err_out;
3795
3796         if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
3797                 d_info.hide_dot_file = true;
3798
3799         buffer_sz                               = d_info.out_buf_len;
3800         d_info.rptr                             = d_info.wptr;
3801         query_dir_private.work                  = work;
3802         query_dir_private.search_pattern        = srch_ptr;
3803         query_dir_private.dir_fp                = dir_fp;
3804         query_dir_private.d_info                = &d_info;
3805         query_dir_private.info_level            = req->FileInformationClass;
3806         dir_fp->readdir_data.private            = &query_dir_private;
3807         set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
3808
3809         rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
3810         if (rc == 0)
3811                 restart_ctx(&dir_fp->readdir_data.ctx);
3812         if (rc == -ENOSPC)
3813                 rc = 0;
3814         if (rc)
3815                 goto err_out;
3816
3817         d_info.wptr = d_info.rptr;
3818         d_info.out_buf_len = buffer_sz;
3819         rc = process_query_dir_entries(&query_dir_private);
3820         if (rc)
3821                 goto err_out;
3822
3823         if (!d_info.data_count && d_info.out_buf_len >= 0) {
3824                 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
3825                         rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3826                 } else {
3827                         dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
3828                         rsp->hdr.Status = STATUS_NO_MORE_FILES;
3829                 }
3830                 rsp->StructureSize = cpu_to_le16(9);
3831                 rsp->OutputBufferOffset = cpu_to_le16(0);
3832                 rsp->OutputBufferLength = cpu_to_le32(0);
3833                 rsp->Buffer[0] = 0;
3834                 inc_rfc1001_len(rsp_org, 9);
3835         } else {
3836                 ((struct file_directory_info *)
3837                 ((char *)rsp->Buffer + d_info.last_entry_offset))
3838                 ->NextEntryOffset = 0;
3839
3840                 rsp->StructureSize = cpu_to_le16(9);
3841                 rsp->OutputBufferOffset = cpu_to_le16(72);
3842                 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
3843                 inc_rfc1001_len(rsp_org, 8 + d_info.data_count);
3844         }
3845
3846         kfree(srch_ptr);
3847         ksmbd_fd_put(work, dir_fp);
3848         ksmbd_revert_fsids(work);
3849         return 0;
3850
3851 err_out:
3852         pr_err("error while processing smb2 query dir rc = %d\n", rc);
3853         kfree(srch_ptr);
3854
3855 err_out2:
3856         if (rc == -EINVAL)
3857                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3858         else if (rc == -EACCES)
3859                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3860         else if (rc == -ENOENT)
3861                 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3862         else if (rc == -EBADF)
3863                 rsp->hdr.Status = STATUS_FILE_CLOSED;
3864         else if (rc == -ENOMEM)
3865                 rsp->hdr.Status = STATUS_NO_MEMORY;
3866         else if (rc == -EFAULT)
3867                 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
3868         if (!rsp->hdr.Status)
3869                 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3870
3871         smb2_set_err_rsp(work);
3872         ksmbd_fd_put(work, dir_fp);
3873         ksmbd_revert_fsids(work);
3874         return 0;
3875 }
3876
3877 /**
3878  * buffer_check_err() - helper function to check buffer errors
3879  * @reqOutputBufferLength:      max buffer length expected in command response
3880  * @rsp:                query info response buffer contains output buffer length
3881  * @infoclass_size:     query info class response buffer size
3882  *
3883  * Return:      0 on success, otherwise error
3884  */
3885 static int buffer_check_err(int reqOutputBufferLength,
3886                             struct smb2_query_info_rsp *rsp, int infoclass_size)
3887 {
3888         if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
3889                 if (reqOutputBufferLength < infoclass_size) {
3890                         pr_err("Invalid Buffer Size Requested\n");
3891                         rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
3892                         rsp->hdr.smb2_buf_length = cpu_to_be32(sizeof(struct smb2_hdr) - 4);
3893                         return -EINVAL;
3894                 }
3895
3896                 ksmbd_debug(SMB, "Buffer Overflow\n");
3897                 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
3898                 rsp->hdr.smb2_buf_length = cpu_to_be32(sizeof(struct smb2_hdr) - 4 +
3899                                 reqOutputBufferLength);
3900                 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
3901         }
3902         return 0;
3903 }
3904
3905 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp)
3906 {
3907         struct smb2_file_standard_info *sinfo;
3908
3909         sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
3910
3911         sinfo->AllocationSize = cpu_to_le64(4096);
3912         sinfo->EndOfFile = cpu_to_le64(0);
3913         sinfo->NumberOfLinks = cpu_to_le32(1);
3914         sinfo->DeletePending = 1;
3915         sinfo->Directory = 0;
3916         rsp->OutputBufferLength =
3917                 cpu_to_le32(sizeof(struct smb2_file_standard_info));
3918         inc_rfc1001_len(rsp, sizeof(struct smb2_file_standard_info));
3919 }
3920
3921 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num)
3922 {
3923         struct smb2_file_internal_info *file_info;
3924
3925         file_info = (struct smb2_file_internal_info *)rsp->Buffer;
3926
3927         /* any unique number */
3928         file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
3929         rsp->OutputBufferLength =
3930                 cpu_to_le32(sizeof(struct smb2_file_internal_info));
3931         inc_rfc1001_len(rsp, sizeof(struct smb2_file_internal_info));
3932 }
3933
3934 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
3935                                    struct smb2_query_info_req *req,
3936                                    struct smb2_query_info_rsp *rsp)
3937 {
3938         u64 id;
3939         int rc;
3940
3941         /*
3942          * Windows can sometime send query file info request on
3943          * pipe without opening it, checking error condition here
3944          */
3945         id = le64_to_cpu(req->VolatileFileId);
3946         if (!ksmbd_session_rpc_method(sess, id))
3947                 return -ENOENT;
3948
3949         ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
3950                     req->FileInfoClass, le64_to_cpu(req->VolatileFileId));
3951
3952         switch (req->FileInfoClass) {
3953         case FILE_STANDARD_INFORMATION:
3954                 get_standard_info_pipe(rsp);
3955                 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
3956                                       rsp, FILE_STANDARD_INFORMATION_SIZE);
3957                 break;
3958         case FILE_INTERNAL_INFORMATION:
3959                 get_internal_info_pipe(rsp, id);
3960                 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
3961                                       rsp, FILE_INTERNAL_INFORMATION_SIZE);
3962                 break;
3963         default:
3964                 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
3965                             req->FileInfoClass);
3966                 rc = -EOPNOTSUPP;
3967         }
3968         return rc;
3969 }
3970
3971 /**
3972  * smb2_get_ea() - handler for smb2 get extended attribute command
3973  * @work:       smb work containing query info command buffer
3974  * @fp:         ksmbd_file pointer
3975  * @req:        get extended attribute request
3976  * @rsp:        response buffer pointer
3977  * @rsp_org:    base response buffer pointer in case of chained response
3978  *
3979  * Return:      0 on success, otherwise error
3980  */
3981 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
3982                        struct smb2_query_info_req *req,
3983                        struct smb2_query_info_rsp *rsp, void *rsp_org)
3984 {
3985         struct smb2_ea_info *eainfo, *prev_eainfo;
3986         char *name, *ptr, *xattr_list = NULL, *buf;
3987         int rc, name_len, value_len, xattr_list_len, idx;
3988         ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
3989         struct smb2_ea_info_req *ea_req = NULL;
3990         struct path *path;
3991         struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
3992
3993         if (!(fp->daccess & FILE_READ_EA_LE)) {
3994                 pr_err("Not permitted to read ext attr : 0x%x\n",
3995                        fp->daccess);
3996                 return -EACCES;
3997         }
3998
3999         path = &fp->filp->f_path;
4000         /* single EA entry is requested with given user.* name */
4001         if (req->InputBufferLength) {
4002                 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4003         } else {
4004                 /* need to send all EAs, if no specific EA is requested*/
4005                 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4006                         ksmbd_debug(SMB,
4007                                     "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4008                                     le32_to_cpu(req->Flags));
4009         }
4010
4011         buf_free_len = work->response_sz -
4012                         (get_rfc1002_len(rsp_org) + 4) -
4013                         sizeof(struct smb2_query_info_rsp);
4014
4015         if (le32_to_cpu(req->OutputBufferLength) < buf_free_len)
4016                 buf_free_len = le32_to_cpu(req->OutputBufferLength);
4017
4018         rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4019         if (rc < 0) {
4020                 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4021                 goto out;
4022         } else if (!rc) { /* there is no EA in the file */
4023                 ksmbd_debug(SMB, "no ea data in the file\n");
4024                 goto done;
4025         }
4026         xattr_list_len = rc;
4027
4028         ptr = (char *)rsp->Buffer;
4029         eainfo = (struct smb2_ea_info *)ptr;
4030         prev_eainfo = eainfo;
4031         idx = 0;
4032
4033         while (idx < xattr_list_len) {
4034                 name = xattr_list + idx;
4035                 name_len = strlen(name);
4036
4037                 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4038                 idx += name_len + 1;
4039
4040                 /*
4041                  * CIFS does not support EA other than user.* namespace,
4042                  * still keep the framework generic, to list other attrs
4043                  * in future.
4044                  */
4045                 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4046                         continue;
4047
4048                 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4049                              STREAM_PREFIX_LEN))
4050                         continue;
4051
4052                 if (req->InputBufferLength &&
4053                     strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4054                             ea_req->EaNameLength))
4055                         continue;
4056
4057                 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4058                              DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4059                         continue;
4060
4061                 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4062                         name_len -= XATTR_USER_PREFIX_LEN;
4063
4064                 ptr = (char *)(&eainfo->name + name_len + 1);
4065                 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4066                                 name_len + 1);
4067                 /* bailout if xattr can't fit in buf_free_len */
4068                 value_len = ksmbd_vfs_getxattr(user_ns, path->dentry,
4069                                                name, &buf);
4070                 if (value_len <= 0) {
4071                         rc = -ENOENT;
4072                         rsp->hdr.Status = STATUS_INVALID_HANDLE;
4073                         goto out;
4074                 }
4075
4076                 buf_free_len -= value_len;
4077                 if (buf_free_len < 0) {
4078                         kfree(buf);
4079                         break;
4080                 }
4081
4082                 memcpy(ptr, buf, value_len);
4083                 kfree(buf);
4084
4085                 ptr += value_len;
4086                 eainfo->Flags = 0;
4087                 eainfo->EaNameLength = name_len;
4088
4089                 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4090                         memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4091                                name_len);
4092                 else
4093                         memcpy(eainfo->name, name, name_len);
4094
4095                 eainfo->name[name_len] = '\0';
4096                 eainfo->EaValueLength = cpu_to_le16(value_len);
4097                 next_offset = offsetof(struct smb2_ea_info, name) +
4098                         name_len + 1 + value_len;
4099
4100                 /* align next xattr entry at 4 byte bundary */
4101                 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4102                 if (alignment_bytes) {
4103                         memset(ptr, '\0', alignment_bytes);
4104                         ptr += alignment_bytes;
4105                         next_offset += alignment_bytes;
4106                         buf_free_len -= alignment_bytes;
4107                 }
4108                 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4109                 prev_eainfo = eainfo;
4110                 eainfo = (struct smb2_ea_info *)ptr;
4111                 rsp_data_cnt += next_offset;
4112
4113                 if (req->InputBufferLength) {
4114                         ksmbd_debug(SMB, "single entry requested\n");
4115                         break;
4116                 }
4117         }
4118
4119         /* no more ea entries */
4120         prev_eainfo->NextEntryOffset = 0;
4121 done:
4122         rc = 0;
4123         if (rsp_data_cnt == 0)
4124                 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4125         rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4126         inc_rfc1001_len(rsp_org, rsp_data_cnt);
4127 out:
4128         kvfree(xattr_list);
4129         return rc;
4130 }
4131
4132 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4133                                  struct ksmbd_file *fp, void *rsp_org)
4134 {
4135         struct smb2_file_access_info *file_info;
4136
4137         file_info = (struct smb2_file_access_info *)rsp->Buffer;
4138         file_info->AccessFlags = fp->daccess;
4139         rsp->OutputBufferLength =
4140                 cpu_to_le32(sizeof(struct smb2_file_access_info));
4141         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_access_info));
4142 }
4143
4144 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4145                                struct ksmbd_file *fp, void *rsp_org)
4146 {
4147         struct smb2_file_all_info *basic_info;
4148         struct kstat stat;
4149         u64 time;
4150
4151         if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4152                 pr_err("no right to read the attributes : 0x%x\n",
4153                        fp->daccess);
4154                 return -EACCES;
4155         }
4156
4157         basic_info = (struct smb2_file_all_info *)rsp->Buffer;
4158         generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4159                          &stat);
4160         basic_info->CreationTime = cpu_to_le64(fp->create_time);
4161         time = ksmbd_UnixTimeToNT(stat.atime);
4162         basic_info->LastAccessTime = cpu_to_le64(time);
4163         time = ksmbd_UnixTimeToNT(stat.mtime);
4164         basic_info->LastWriteTime = cpu_to_le64(time);
4165         time = ksmbd_UnixTimeToNT(stat.ctime);
4166         basic_info->ChangeTime = cpu_to_le64(time);
4167         basic_info->Attributes = fp->f_ci->m_fattr;
4168         basic_info->Pad1 = 0;
4169         rsp->OutputBufferLength =
4170                 cpu_to_le32(offsetof(struct smb2_file_all_info, AllocationSize));
4171         inc_rfc1001_len(rsp_org, offsetof(struct smb2_file_all_info,
4172                                           AllocationSize));
4173         return 0;
4174 }
4175
4176 static unsigned long long get_allocation_size(struct inode *inode,
4177                                               struct kstat *stat)
4178 {
4179         unsigned long long alloc_size = 0;
4180
4181         if (!S_ISDIR(stat->mode)) {
4182                 if ((inode->i_blocks << 9) <= stat->size)
4183                         alloc_size = stat->size;
4184                 else
4185                         alloc_size = inode->i_blocks << 9;
4186         }
4187
4188         return alloc_size;
4189 }
4190
4191 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4192                                    struct ksmbd_file *fp, void *rsp_org)
4193 {
4194         struct smb2_file_standard_info *sinfo;
4195         unsigned int delete_pending;
4196         struct inode *inode;
4197         struct kstat stat;
4198
4199         inode = file_inode(fp->filp);
4200         generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4201
4202         sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4203         delete_pending = ksmbd_inode_pending_delete(fp);
4204
4205         sinfo->AllocationSize = cpu_to_le64(get_allocation_size(inode, &stat));
4206         sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4207         sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4208         sinfo->DeletePending = delete_pending;
4209         sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4210         rsp->OutputBufferLength =
4211                 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4212         inc_rfc1001_len(rsp_org,
4213                         sizeof(struct smb2_file_standard_info));
4214 }
4215
4216 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4217                                     void *rsp_org)
4218 {
4219         struct smb2_file_alignment_info *file_info;
4220
4221         file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4222         file_info->AlignmentRequirement = 0;
4223         rsp->OutputBufferLength =
4224                 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4225         inc_rfc1001_len(rsp_org,
4226                         sizeof(struct smb2_file_alignment_info));
4227 }
4228
4229 static int get_file_all_info(struct ksmbd_work *work,
4230                              struct smb2_query_info_rsp *rsp,
4231                              struct ksmbd_file *fp,
4232                              void *rsp_org)
4233 {
4234         struct ksmbd_conn *conn = work->conn;
4235         struct smb2_file_all_info *file_info;
4236         unsigned int delete_pending;
4237         struct inode *inode;
4238         struct kstat stat;
4239         int conv_len;
4240         char *filename;
4241         u64 time;
4242
4243         if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4244                 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4245                             fp->daccess);
4246                 return -EACCES;
4247         }
4248
4249         filename = convert_to_nt_pathname(fp->filename,
4250                                           work->tcon->share_conf->path);
4251         if (!filename)
4252                 return -ENOMEM;
4253
4254         inode = file_inode(fp->filp);
4255         generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4256
4257         ksmbd_debug(SMB, "filename = %s\n", filename);
4258         delete_pending = ksmbd_inode_pending_delete(fp);
4259         file_info = (struct smb2_file_all_info *)rsp->Buffer;
4260
4261         file_info->CreationTime = cpu_to_le64(fp->create_time);
4262         time = ksmbd_UnixTimeToNT(stat.atime);
4263         file_info->LastAccessTime = cpu_to_le64(time);
4264         time = ksmbd_UnixTimeToNT(stat.mtime);
4265         file_info->LastWriteTime = cpu_to_le64(time);
4266         time = ksmbd_UnixTimeToNT(stat.ctime);
4267         file_info->ChangeTime = cpu_to_le64(time);
4268         file_info->Attributes = fp->f_ci->m_fattr;
4269         file_info->Pad1 = 0;
4270         file_info->AllocationSize =
4271                 cpu_to_le64(get_allocation_size(inode, &stat));
4272         file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4273         file_info->NumberOfLinks =
4274                         cpu_to_le32(get_nlink(&stat) - delete_pending);
4275         file_info->DeletePending = delete_pending;
4276         file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4277         file_info->Pad2 = 0;
4278         file_info->IndexNumber = cpu_to_le64(stat.ino);
4279         file_info->EASize = 0;
4280         file_info->AccessFlags = fp->daccess;
4281         file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4282         file_info->Mode = fp->coption;
4283         file_info->AlignmentRequirement = 0;
4284         conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4285                                      PATH_MAX, conn->local_nls, 0);
4286         conv_len *= 2;
4287         file_info->FileNameLength = cpu_to_le32(conv_len);
4288         rsp->OutputBufferLength =
4289                 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4290         kfree(filename);
4291         inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4292         return 0;
4293 }
4294
4295 static void get_file_alternate_info(struct ksmbd_work *work,
4296                                     struct smb2_query_info_rsp *rsp,
4297                                     struct ksmbd_file *fp,
4298                                     void *rsp_org)
4299 {
4300         struct ksmbd_conn *conn = work->conn;
4301         struct smb2_file_alt_name_info *file_info;
4302         struct dentry *dentry = fp->filp->f_path.dentry;
4303         int conv_len;
4304
4305         spin_lock(&dentry->d_lock);
4306         file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4307         conv_len = ksmbd_extract_shortname(conn,
4308                                            dentry->d_name.name,
4309                                            file_info->FileName);
4310         spin_unlock(&dentry->d_lock);
4311         file_info->FileNameLength = cpu_to_le32(conv_len);
4312         rsp->OutputBufferLength =
4313                 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4314         inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4315 }
4316
4317 static void get_file_stream_info(struct ksmbd_work *work,
4318                                  struct smb2_query_info_rsp *rsp,
4319                                  struct ksmbd_file *fp,
4320                                  void *rsp_org)
4321 {
4322         struct ksmbd_conn *conn = work->conn;
4323         struct smb2_file_stream_info *file_info;
4324         char *stream_name, *xattr_list = NULL, *stream_buf;
4325         struct kstat stat;
4326         struct path *path = &fp->filp->f_path;
4327         ssize_t xattr_list_len;
4328         int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4329
4330         generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4331                          &stat);
4332         file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4333
4334         xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4335         if (xattr_list_len < 0) {
4336                 goto out;
4337         } else if (!xattr_list_len) {
4338                 ksmbd_debug(SMB, "empty xattr in the file\n");
4339                 goto out;
4340         }
4341
4342         while (idx < xattr_list_len) {
4343                 stream_name = xattr_list + idx;
4344                 streamlen = strlen(stream_name);
4345                 idx += streamlen + 1;
4346
4347                 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4348
4349                 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4350                             STREAM_PREFIX, STREAM_PREFIX_LEN))
4351                         continue;
4352
4353                 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4354                                 STREAM_PREFIX_LEN);
4355                 streamlen = stream_name_len;
4356
4357                 /* plus : size */
4358                 streamlen += 1;
4359                 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4360                 if (!stream_buf)
4361                         break;
4362
4363                 streamlen = snprintf(stream_buf, streamlen + 1,
4364                                      ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4365
4366                 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4367                 streamlen  = smbConvertToUTF16((__le16 *)file_info->StreamName,
4368                                                stream_buf, streamlen,
4369                                                conn->local_nls, 0);
4370                 streamlen *= 2;
4371                 kfree(stream_buf);
4372                 file_info->StreamNameLength = cpu_to_le32(streamlen);
4373                 file_info->StreamSize = cpu_to_le64(stream_name_len);
4374                 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4375
4376                 next = sizeof(struct smb2_file_stream_info) + streamlen;
4377                 nbytes += next;
4378                 file_info->NextEntryOffset = cpu_to_le32(next);
4379         }
4380
4381         if (nbytes) {
4382                 file_info = (struct smb2_file_stream_info *)
4383                         &rsp->Buffer[nbytes];
4384                 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4385                                               "::$DATA", 7, conn->local_nls, 0);
4386                 streamlen *= 2;
4387                 file_info->StreamNameLength = cpu_to_le32(streamlen);
4388                 file_info->StreamSize = S_ISDIR(stat.mode) ? 0 :
4389                         cpu_to_le64(stat.size);
4390                 file_info->StreamAllocationSize = S_ISDIR(stat.mode) ? 0 :
4391                         cpu_to_le64(stat.size);
4392                 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4393         }
4394
4395         /* last entry offset should be 0 */
4396         file_info->NextEntryOffset = 0;
4397 out:
4398         kvfree(xattr_list);
4399
4400         rsp->OutputBufferLength = cpu_to_le32(nbytes);
4401         inc_rfc1001_len(rsp_org, nbytes);
4402 }
4403
4404 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4405                                    struct ksmbd_file *fp, void *rsp_org)
4406 {
4407         struct smb2_file_internal_info *file_info;
4408         struct kstat stat;
4409
4410         generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4411                          &stat);
4412         file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4413         file_info->IndexNumber = cpu_to_le64(stat.ino);
4414         rsp->OutputBufferLength =
4415                 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4416         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4417 }
4418
4419 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4420                                       struct ksmbd_file *fp, void *rsp_org)
4421 {
4422         struct smb2_file_ntwrk_info *file_info;
4423         struct inode *inode;
4424         struct kstat stat;
4425         u64 time;
4426
4427         if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4428                 pr_err("no right to read the attributes : 0x%x\n",
4429                        fp->daccess);
4430                 return -EACCES;
4431         }
4432
4433         file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4434
4435         inode = file_inode(fp->filp);
4436         generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4437
4438         file_info->CreationTime = cpu_to_le64(fp->create_time);
4439         time = ksmbd_UnixTimeToNT(stat.atime);
4440         file_info->LastAccessTime = cpu_to_le64(time);
4441         time = ksmbd_UnixTimeToNT(stat.mtime);
4442         file_info->LastWriteTime = cpu_to_le64(time);
4443         time = ksmbd_UnixTimeToNT(stat.ctime);
4444         file_info->ChangeTime = cpu_to_le64(time);
4445         file_info->Attributes = fp->f_ci->m_fattr;
4446         file_info->AllocationSize =
4447                 cpu_to_le64(get_allocation_size(inode, &stat));
4448         file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4449         file_info->Reserved = cpu_to_le32(0);
4450         rsp->OutputBufferLength =
4451                 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4452         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ntwrk_info));
4453         return 0;
4454 }
4455
4456 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4457 {
4458         struct smb2_file_ea_info *file_info;
4459
4460         file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4461         file_info->EASize = 0;
4462         rsp->OutputBufferLength =
4463                 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4464         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ea_info));
4465 }
4466
4467 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4468                                    struct ksmbd_file *fp, void *rsp_org)
4469 {
4470         struct smb2_file_pos_info *file_info;
4471
4472         file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4473         file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4474         rsp->OutputBufferLength =
4475                 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4476         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_pos_info));
4477 }
4478
4479 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4480                                struct ksmbd_file *fp, void *rsp_org)
4481 {
4482         struct smb2_file_mode_info *file_info;
4483
4484         file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4485         file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4486         rsp->OutputBufferLength =
4487                 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4488         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_mode_info));
4489 }
4490
4491 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4492                                       struct ksmbd_file *fp, void *rsp_org)
4493 {
4494         struct smb2_file_comp_info *file_info;
4495         struct kstat stat;
4496
4497         generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4498                          &stat);
4499
4500         file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4501         file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4502         file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4503         file_info->CompressionUnitShift = 0;
4504         file_info->ChunkShift = 0;
4505         file_info->ClusterShift = 0;
4506         memset(&file_info->Reserved[0], 0, 3);
4507
4508         rsp->OutputBufferLength =
4509                 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4510         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_comp_info));
4511 }
4512
4513 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4514                                        struct ksmbd_file *fp, void *rsp_org)
4515 {
4516         struct smb2_file_attr_tag_info *file_info;
4517
4518         if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4519                 pr_err("no right to read the attributes : 0x%x\n",
4520                        fp->daccess);
4521                 return -EACCES;
4522         }
4523
4524         file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4525         file_info->FileAttributes = fp->f_ci->m_fattr;
4526         file_info->ReparseTag = 0;
4527         rsp->OutputBufferLength =
4528                 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4529         inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_attr_tag_info));
4530         return 0;
4531 }
4532
4533 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
4534                                 struct ksmbd_file *fp, void *rsp_org)
4535 {
4536         struct smb311_posix_qinfo *file_info;
4537         struct inode *inode = file_inode(fp->filp);
4538         u64 time;
4539
4540         file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4541         file_info->CreationTime = cpu_to_le64(fp->create_time);
4542         time = ksmbd_UnixTimeToNT(inode->i_atime);
4543         file_info->LastAccessTime = cpu_to_le64(time);
4544         time = ksmbd_UnixTimeToNT(inode->i_mtime);
4545         file_info->LastWriteTime = cpu_to_le64(time);
4546         time = ksmbd_UnixTimeToNT(inode->i_ctime);
4547         file_info->ChangeTime = cpu_to_le64(time);
4548         file_info->DosAttributes = fp->f_ci->m_fattr;
4549         file_info->Inode = cpu_to_le64(inode->i_ino);
4550         file_info->EndOfFile = cpu_to_le64(inode->i_size);
4551         file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4552         file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4553         file_info->Mode = cpu_to_le32(inode->i_mode);
4554         file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4555         rsp->OutputBufferLength =
4556                 cpu_to_le32(sizeof(struct smb311_posix_qinfo));
4557         inc_rfc1001_len(rsp_org, sizeof(struct smb311_posix_qinfo));
4558         return 0;
4559 }
4560
4561 static int smb2_get_info_file(struct ksmbd_work *work,
4562                               struct smb2_query_info_req *req,
4563                               struct smb2_query_info_rsp *rsp, void *rsp_org)
4564 {
4565         struct ksmbd_file *fp;
4566         int fileinfoclass = 0;
4567         int rc = 0;
4568         int file_infoclass_size;
4569         unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4570
4571         if (test_share_config_flag(work->tcon->share_conf,
4572                                    KSMBD_SHARE_FLAG_PIPE)) {
4573                 /* smb2 info file called for pipe */
4574                 return smb2_get_info_file_pipe(work->sess, req, rsp);
4575         }
4576
4577         if (work->next_smb2_rcv_hdr_off) {
4578                 if (!HAS_FILE_ID(le64_to_cpu(req->VolatileFileId))) {
4579                         ksmbd_debug(SMB, "Compound request set FID = %u\n",
4580                                     work->compound_fid);
4581                         id = work->compound_fid;
4582                         pid = work->compound_pfid;
4583                 }
4584         }
4585
4586         if (!HAS_FILE_ID(id)) {
4587                 id = le64_to_cpu(req->VolatileFileId);
4588                 pid = le64_to_cpu(req->PersistentFileId);
4589         }
4590
4591         fp = ksmbd_lookup_fd_slow(work, id, pid);
4592         if (!fp)
4593                 return -ENOENT;
4594
4595         fileinfoclass = req->FileInfoClass;
4596
4597         switch (fileinfoclass) {
4598         case FILE_ACCESS_INFORMATION:
4599                 get_file_access_info(rsp, fp, rsp_org);
4600                 file_infoclass_size = FILE_ACCESS_INFORMATION_SIZE;
4601                 break;
4602
4603         case FILE_BASIC_INFORMATION:
4604                 rc = get_file_basic_info(rsp, fp, rsp_org);
4605                 file_infoclass_size = FILE_BASIC_INFORMATION_SIZE;
4606                 break;
4607
4608         case FILE_STANDARD_INFORMATION:
4609                 get_file_standard_info(rsp, fp, rsp_org);
4610                 file_infoclass_size = FILE_STANDARD_INFORMATION_SIZE;
4611                 break;
4612
4613         case FILE_ALIGNMENT_INFORMATION:
4614                 get_file_alignment_info(rsp, rsp_org);
4615                 file_infoclass_size = FILE_ALIGNMENT_INFORMATION_SIZE;
4616                 break;
4617
4618         case FILE_ALL_INFORMATION:
4619                 rc = get_file_all_info(work, rsp, fp, rsp_org);
4620                 file_infoclass_size = FILE_ALL_INFORMATION_SIZE;
4621                 break;
4622
4623         case FILE_ALTERNATE_NAME_INFORMATION:
4624                 get_file_alternate_info(work, rsp, fp, rsp_org);
4625                 file_infoclass_size = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
4626                 break;
4627
4628         case FILE_STREAM_INFORMATION:
4629                 get_file_stream_info(work, rsp, fp, rsp_org);
4630                 file_infoclass_size = FILE_STREAM_INFORMATION_SIZE;
4631                 break;
4632
4633         case FILE_INTERNAL_INFORMATION:
4634                 get_file_internal_info(rsp, fp, rsp_org);
4635                 file_infoclass_size = FILE_INTERNAL_INFORMATION_SIZE;
4636                 break;
4637
4638         case FILE_NETWORK_OPEN_INFORMATION:
4639                 rc = get_file_network_open_info(rsp, fp, rsp_org);
4640                 file_infoclass_size = FILE_NETWORK_OPEN_INFORMATION_SIZE;
4641                 break;
4642
4643         case FILE_EA_INFORMATION:
4644                 get_file_ea_info(rsp, rsp_org);
4645                 file_infoclass_size = FILE_EA_INFORMATION_SIZE;
4646                 break;
4647
4648         case FILE_FULL_EA_INFORMATION:
4649                 rc = smb2_get_ea(work, fp, req, rsp, rsp_org);
4650                 file_infoclass_size = FILE_FULL_EA_INFORMATION_SIZE;
4651                 break;
4652
4653         case FILE_POSITION_INFORMATION:
4654                 get_file_position_info(rsp, fp, rsp_org);
4655                 file_infoclass_size = FILE_POSITION_INFORMATION_SIZE;
4656                 break;
4657
4658         case FILE_MODE_INFORMATION:
4659                 get_file_mode_info(rsp, fp, rsp_org);
4660                 file_infoclass_size = FILE_MODE_INFORMATION_SIZE;
4661                 break;
4662
4663         case FILE_COMPRESSION_INFORMATION:
4664                 get_file_compression_info(rsp, fp, rsp_org);
4665                 file_infoclass_size = FILE_COMPRESSION_INFORMATION_SIZE;
4666                 break;
4667
4668         case FILE_ATTRIBUTE_TAG_INFORMATION:
4669                 rc = get_file_attribute_tag_info(rsp, fp, rsp_org);
4670                 file_infoclass_size = FILE_ATTRIBUTE_TAG_INFORMATION_SIZE;
4671                 break;
4672         case SMB_FIND_FILE_POSIX_INFO:
4673                 if (!work->tcon->posix_extensions) {
4674                         pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4675                         rc = -EOPNOTSUPP;
4676                 } else {
4677                         rc = find_file_posix_info(rsp, fp, rsp_org);
4678                         file_infoclass_size = sizeof(struct smb311_posix_qinfo);
4679                 }
4680                 break;
4681         default:
4682                 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4683                             fileinfoclass);
4684                 rc = -EOPNOTSUPP;
4685         }
4686         if (!rc)
4687                 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4688                                       rsp,
4689                                       file_infoclass_size);
4690         ksmbd_fd_put(work, fp);
4691         return rc;
4692 }
4693
4694 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4695                                     struct smb2_query_info_req *req,
4696                                     struct smb2_query_info_rsp *rsp, void *rsp_org)
4697 {
4698         struct ksmbd_session *sess = work->sess;
4699         struct ksmbd_conn *conn = sess->conn;
4700         struct ksmbd_share_config *share = work->tcon->share_conf;
4701         int fsinfoclass = 0;
4702         struct kstatfs stfs;
4703         struct path path;
4704         int rc = 0, len;
4705         int fs_infoclass_size = 0;
4706         int lookup_flags = 0;
4707
4708         if (test_share_config_flag(share, KSMBD_SHARE_FLAG_FOLLOW_SYMLINKS))
4709                 lookup_flags = LOOKUP_FOLLOW;
4710
4711         rc = ksmbd_vfs_kern_path(share->path, lookup_flags, &path, 0);
4712         if (rc) {
4713                 pr_err("cannot create vfs path\n");
4714                 return -EIO;
4715         }
4716
4717         rc = vfs_statfs(&path, &stfs);
4718         if (rc) {
4719                 pr_err("cannot do stat of path %s\n", share->path);
4720                 path_put(&path);
4721                 return -EIO;
4722         }
4723
4724         fsinfoclass = req->FileInfoClass;
4725
4726         switch (fsinfoclass) {
4727         case FS_DEVICE_INFORMATION:
4728         {
4729                 struct filesystem_device_info *info;
4730
4731                 info = (struct filesystem_device_info *)rsp->Buffer;
4732
4733                 info->DeviceType = cpu_to_le32(stfs.f_type);
4734                 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
4735                 rsp->OutputBufferLength = cpu_to_le32(8);
4736                 inc_rfc1001_len(rsp_org, 8);
4737                 fs_infoclass_size = FS_DEVICE_INFORMATION_SIZE;
4738                 break;
4739         }
4740         case FS_ATTRIBUTE_INFORMATION:
4741         {
4742                 struct filesystem_attribute_info *info;
4743                 size_t sz;
4744
4745                 info = (struct filesystem_attribute_info *)rsp->Buffer;
4746                 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
4747                                                FILE_PERSISTENT_ACLS |
4748                                                FILE_UNICODE_ON_DISK |
4749                                                FILE_CASE_PRESERVED_NAMES |
4750                                                FILE_CASE_SENSITIVE_SEARCH |
4751                                                FILE_SUPPORTS_BLOCK_REFCOUNTING);
4752
4753                 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
4754
4755                 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
4756                 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
4757                                         "NTFS", PATH_MAX, conn->local_nls, 0);
4758                 len = len * 2;
4759                 info->FileSystemNameLen = cpu_to_le32(len);
4760                 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
4761                 rsp->OutputBufferLength = cpu_to_le32(sz);
4762                 inc_rfc1001_len(rsp_org, sz);
4763                 fs_infoclass_size = FS_ATTRIBUTE_INFORMATION_SIZE;
4764                 break;
4765         }
4766         case FS_VOLUME_INFORMATION:
4767         {
4768                 struct filesystem_vol_info *info;
4769                 size_t sz;
4770
4771                 info = (struct filesystem_vol_info *)(rsp->Buffer);
4772                 info->VolumeCreationTime = 0;
4773                 /* Taking dummy value of serial number*/
4774                 info->SerialNumber = cpu_to_le32(0xbc3ac512);
4775                 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
4776                                         share->name, PATH_MAX,
4777                                         conn->local_nls, 0);
4778                 len = len * 2;
4779                 info->VolumeLabelSize = cpu_to_le32(len);
4780                 info->Reserved = 0;
4781                 sz = sizeof(struct filesystem_vol_info) - 2 + len;
4782                 rsp->OutputBufferLength = cpu_to_le32(sz);
4783                 inc_rfc1001_len(rsp_org, sz);
4784                 fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
4785                 break;
4786         }
4787         case FS_SIZE_INFORMATION:
4788         {
4789                 struct filesystem_info *info;
4790
4791                 info = (struct filesystem_info *)(rsp->Buffer);
4792                 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4793                 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
4794                 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4795                 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4796                 rsp->OutputBufferLength = cpu_to_le32(24);
4797                 inc_rfc1001_len(rsp_org, 24);
4798                 fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
4799                 break;
4800         }
4801         case FS_FULL_SIZE_INFORMATION:
4802         {
4803                 struct smb2_fs_full_size_info *info;
4804
4805                 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
4806                 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4807                 info->CallerAvailableAllocationUnits =
4808                                         cpu_to_le64(stfs.f_bavail);
4809                 info->ActualAvailableAllocationUnits =
4810                                         cpu_to_le64(stfs.f_bfree);
4811                 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4812                 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4813                 rsp->OutputBufferLength = cpu_to_le32(32);
4814                 inc_rfc1001_len(rsp_org, 32);
4815                 fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
4816                 break;
4817         }
4818         case FS_OBJECT_ID_INFORMATION:
4819         {
4820                 struct object_id_info *info;
4821
4822                 info = (struct object_id_info *)(rsp->Buffer);
4823
4824                 if (!user_guest(sess->user))
4825                         memcpy(info->objid, user_passkey(sess->user), 16);
4826                 else
4827                         memset(info->objid, 0, 16);
4828
4829                 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
4830                 info->extended_info.version = cpu_to_le32(1);
4831                 info->extended_info.release = cpu_to_le32(1);
4832                 info->extended_info.rel_date = 0;
4833                 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
4834                 rsp->OutputBufferLength = cpu_to_le32(64);
4835                 inc_rfc1001_len(rsp_org, 64);
4836                 fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
4837                 break;
4838         }
4839         case FS_SECTOR_SIZE_INFORMATION:
4840         {
4841                 struct smb3_fs_ss_info *info;
4842
4843                 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
4844
4845                 info->LogicalBytesPerSector = cpu_to_le32(stfs.f_bsize);
4846                 info->PhysicalBytesPerSectorForAtomicity =
4847                                 cpu_to_le32(stfs.f_bsize);
4848                 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(stfs.f_bsize);
4849                 info->FSEffPhysicalBytesPerSectorForAtomicity =
4850                                 cpu_to_le32(stfs.f_bsize);
4851                 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
4852                                     SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
4853                 info->ByteOffsetForSectorAlignment = 0;
4854                 info->ByteOffsetForPartitionAlignment = 0;
4855                 rsp->OutputBufferLength = cpu_to_le32(28);
4856                 inc_rfc1001_len(rsp_org, 28);
4857                 fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
4858                 break;
4859         }
4860         case FS_CONTROL_INFORMATION:
4861         {
4862                 /*
4863                  * TODO : The current implementation is based on
4864                  * test result with win7(NTFS) server. It's need to
4865                  * modify this to get valid Quota values
4866                  * from Linux kernel
4867                  */
4868                 struct smb2_fs_control_info *info;
4869
4870                 info = (struct smb2_fs_control_info *)(rsp->Buffer);
4871                 info->FreeSpaceStartFiltering = 0;
4872                 info->FreeSpaceThreshold = 0;
4873                 info->FreeSpaceStopFiltering = 0;
4874                 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
4875                 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
4876                 info->Padding = 0;
4877                 rsp->OutputBufferLength = cpu_to_le32(48);
4878                 inc_rfc1001_len(rsp_org, 48);
4879                 fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
4880                 break;
4881         }
4882         case FS_POSIX_INFORMATION:
4883         {
4884                 struct filesystem_posix_info *info;
4885
4886                 if (!work->tcon->posix_extensions) {
4887                         pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4888                         rc = -EOPNOTSUPP;
4889                 } else {
4890                         info = (struct filesystem_posix_info *)(rsp->Buffer);
4891                         info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
4892                         info->BlockSize = cpu_to_le32(stfs.f_bsize);
4893                         info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
4894                         info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
4895                         info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
4896                         info->TotalFileNodes = cpu_to_le64(stfs.f_files);
4897                         info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
4898                         rsp->OutputBufferLength = cpu_to_le32(56);
4899                         inc_rfc1001_len(rsp_org, 56);
4900                         fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
4901                 }
4902                 break;
4903         }
4904         default:
4905                 path_put(&path);
4906                 return -EOPNOTSUPP;
4907         }
4908         rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4909                               rsp,
4910                               fs_infoclass_size);
4911         path_put(&path);
4912         return rc;
4913 }
4914
4915 static int smb2_get_info_sec(struct ksmbd_work *work,
4916                              struct smb2_query_info_req *req,
4917                              struct smb2_query_info_rsp *rsp, void *rsp_org)
4918 {
4919         struct ksmbd_file *fp;
4920         struct user_namespace *user_ns;
4921         struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
4922         struct smb_fattr fattr = {{0}};
4923         struct inode *inode;
4924         __u32 secdesclen;
4925         unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4926         int addition_info = le32_to_cpu(req->AdditionalInformation);
4927         int rc;
4928
4929         if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
4930                               PROTECTED_DACL_SECINFO |
4931                               UNPROTECTED_DACL_SECINFO)) {
4932                 pr_err("Unsupported addition info: 0x%x)\n",
4933                        addition_info);
4934
4935                 pntsd->revision = cpu_to_le16(1);
4936                 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
4937                 pntsd->osidoffset = 0;
4938                 pntsd->gsidoffset = 0;
4939                 pntsd->sacloffset = 0;
4940                 pntsd->dacloffset = 0;
4941
4942                 secdesclen = sizeof(struct smb_ntsd);
4943                 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
4944                 inc_rfc1001_len(rsp_org, secdesclen);
4945
4946                 return 0;
4947         }
4948
4949         if (work->next_smb2_rcv_hdr_off) {
4950                 if (!HAS_FILE_ID(le64_to_cpu(req->VolatileFileId))) {
4951                         ksmbd_debug(SMB, "Compound request set FID = %u\n",
4952                                     work->compound_fid);
4953                         id = work->compound_fid;
4954                         pid = work->compound_pfid;
4955                 }
4956         }
4957
4958         if (!HAS_FILE_ID(id)) {
4959                 id = le64_to_cpu(req->VolatileFileId);
4960                 pid = le64_to_cpu(req->PersistentFileId);
4961         }
4962
4963         fp = ksmbd_lookup_fd_slow(work, id, pid);
4964         if (!fp)
4965                 return -ENOENT;
4966
4967         user_ns = file_mnt_user_ns(fp->filp);
4968         inode = file_inode(fp->filp);
4969         ksmbd_acls_fattr(&fattr, inode);
4970
4971         if (test_share_config_flag(work->tcon->share_conf,
4972                                    KSMBD_SHARE_FLAG_ACL_XATTR))
4973                 ksmbd_vfs_get_sd_xattr(work->conn, user_ns,
4974                                        fp->filp->f_path.dentry, &ppntsd);
4975
4976         rc = build_sec_desc(user_ns, pntsd, ppntsd, addition_info,
4977                             &secdesclen, &fattr);
4978         posix_acl_release(fattr.cf_acls);
4979         posix_acl_release(fattr.cf_dacls);
4980         kfree(ppntsd);
4981         ksmbd_fd_put(work, fp);
4982         if (rc)
4983                 return rc;
4984
4985         rsp->OutputBufferLength = cpu_to_le32(secdesclen);
4986         inc_rfc1001_len(rsp_org, secdesclen);
4987         return 0;
4988 }
4989
4990 /**
4991  * smb2_query_info() - handler for smb2 query info command
4992  * @work:       smb work containing query info request buffer
4993  *
4994  * Return:      0 on success, otherwise error
4995  */
4996 int smb2_query_info(struct ksmbd_work *work)
4997 {
4998         struct smb2_query_info_req *req;
4999         struct smb2_query_info_rsp *rsp, *rsp_org;
5000         int rc = 0;
5001
5002         rsp_org = work->response_buf;
5003         WORK_BUFFERS(work, req, rsp);
5004
5005         ksmbd_debug(SMB, "GOT query info request\n");
5006
5007         switch (req->InfoType) {
5008         case SMB2_O_INFO_FILE:
5009                 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5010                 rc = smb2_get_info_file(work, req, rsp, (void *)rsp_org);
5011                 break;
5012         case SMB2_O_INFO_FILESYSTEM:
5013                 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5014                 rc = smb2_get_info_filesystem(work, req, rsp, (void *)rsp_org);
5015                 break;
5016         case SMB2_O_INFO_SECURITY:
5017                 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5018                 rc = smb2_get_info_sec(work, req, rsp, (void *)rsp_org);
5019                 break;
5020         default:
5021                 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5022                             req->InfoType);
5023                 rc = -EOPNOTSUPP;
5024         }
5025
5026         if (rc < 0) {
5027                 if (rc == -EACCES)
5028                         rsp->hdr.Status = STATUS_ACCESS_DENIED;
5029                 else if (rc == -ENOENT)
5030                         rsp->hdr.Status = STATUS_FILE_CLOSED;
5031                 else if (rc == -EIO)
5032                         rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5033                 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5034                         rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5035                 smb2_set_err_rsp(work);
5036
5037                 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5038                             rc);
5039                 return rc;
5040         }
5041         rsp->StructureSize = cpu_to_le16(9);
5042         rsp->OutputBufferOffset = cpu_to_le16(72);
5043         inc_rfc1001_len(rsp_org, 8);
5044         return 0;
5045 }
5046
5047 /**
5048  * smb2_close_pipe() - handler for closing IPC pipe
5049  * @work:       smb work containing close request buffer
5050  *
5051  * Return:      0
5052  */
5053 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5054 {
5055         u64 id;
5056         struct smb2_close_req *req = work->request_buf;
5057         struct smb2_close_rsp *rsp = work->response_buf;
5058
5059         id = le64_to_cpu(req->VolatileFileId);
5060         ksmbd_session_rpc_close(work->sess, id);
5061
5062         rsp->StructureSize = cpu_to_le16(60);
5063         rsp->Flags = 0;
5064         rsp->Reserved = 0;
5065         rsp->CreationTime = 0;
5066         rsp->LastAccessTime = 0;
5067         rsp->LastWriteTime = 0;
5068         rsp->ChangeTime = 0;
5069         rsp->AllocationSize = 0;
5070         rsp->EndOfFile = 0;
5071         rsp->Attributes = 0;
5072         inc_rfc1001_len(rsp, 60);
5073         return 0;
5074 }
5075
5076 /**
5077  * smb2_close() - handler for smb2 close file command
5078  * @work:       smb work containing close request buffer
5079  *
5080  * Return:      0
5081  */
5082 int smb2_close(struct ksmbd_work *work)
5083 {
5084         unsigned int volatile_id = KSMBD_NO_FID;
5085         u64 sess_id;
5086         struct smb2_close_req *req;
5087         struct smb2_close_rsp *rsp;
5088         struct smb2_close_rsp *rsp_org;
5089         struct ksmbd_conn *conn = work->conn;
5090         struct ksmbd_file *fp;
5091         struct inode *inode;
5092         u64 time;
5093         int err = 0;
5094
5095         rsp_org = work->response_buf;
5096         WORK_BUFFERS(work, req, rsp);
5097
5098         if (test_share_config_flag(work->tcon->share_conf,
5099                                    KSMBD_SHARE_FLAG_PIPE)) {
5100                 ksmbd_debug(SMB, "IPC pipe close request\n");
5101                 return smb2_close_pipe(work);
5102         }
5103
5104         sess_id = le64_to_cpu(req->hdr.SessionId);
5105         if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5106                 sess_id = work->compound_sid;
5107
5108         work->compound_sid = 0;
5109         if (check_session_id(conn, sess_id)) {
5110                 work->compound_sid = sess_id;
5111         } else {
5112                 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5113                 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5114                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5115                 err = -EBADF;
5116                 goto out;
5117         }
5118
5119         if (work->next_smb2_rcv_hdr_off &&
5120             !HAS_FILE_ID(le64_to_cpu(req->VolatileFileId))) {
5121                 if (!HAS_FILE_ID(work->compound_fid)) {
5122                         /* file already closed, return FILE_CLOSED */
5123                         ksmbd_debug(SMB, "file already closed\n");
5124                         rsp->hdr.Status = STATUS_FILE_CLOSED;
5125                         err = -EBADF;
5126                         goto out;
5127                 } else {
5128                         ksmbd_debug(SMB, "Compound request set FID = %u:%u\n",
5129                                     work->compound_fid,
5130                                     work->compound_pfid);
5131                         volatile_id = work->compound_fid;
5132
5133                         /* file closed, stored id is not valid anymore */
5134                         work->compound_fid = KSMBD_NO_FID;
5135                         work->compound_pfid = KSMBD_NO_FID;
5136                 }
5137         } else {
5138                 volatile_id = le64_to_cpu(req->VolatileFileId);
5139         }
5140         ksmbd_debug(SMB, "volatile_id = %u\n", volatile_id);
5141
5142         rsp->StructureSize = cpu_to_le16(60);
5143         rsp->Reserved = 0;
5144
5145         if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5146                 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5147                 if (!fp) {
5148                         err = -ENOENT;
5149                         goto out;
5150                 }
5151
5152                 inode = file_inode(fp->filp);
5153                 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5154                 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5155                         cpu_to_le64(inode->i_blocks << 9);
5156                 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5157                 rsp->Attributes = fp->f_ci->m_fattr;
5158                 rsp->CreationTime = cpu_to_le64(fp->create_time);
5159                 time = ksmbd_UnixTimeToNT(inode->i_atime);
5160                 rsp->LastAccessTime = cpu_to_le64(time);
5161                 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5162                 rsp->LastWriteTime = cpu_to_le64(time);
5163                 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5164                 rsp->ChangeTime = cpu_to_le64(time);
5165                 ksmbd_fd_put(work, fp);
5166         } else {
5167                 rsp->Flags = 0;
5168                 rsp->AllocationSize = 0;
5169                 rsp->EndOfFile = 0;
5170                 rsp->Attributes = 0;
5171                 rsp->CreationTime = 0;
5172                 rsp->LastAccessTime = 0;
5173                 rsp->LastWriteTime = 0;
5174                 rsp->ChangeTime = 0;
5175         }
5176
5177         err = ksmbd_close_fd(work, volatile_id);
5178 out:
5179         if (err) {
5180                 if (rsp->hdr.Status == 0)
5181                         rsp->hdr.Status = STATUS_FILE_CLOSED;
5182                 smb2_set_err_rsp(work);
5183         } else {
5184                 inc_rfc1001_len(rsp_org, 60);
5185         }
5186
5187         return 0;
5188 }
5189
5190 /**
5191  * smb2_echo() - handler for smb2 echo(ping) command
5192  * @work:       smb work containing echo request buffer
5193  *
5194  * Return:      0
5195  */
5196 int smb2_echo(struct ksmbd_work *work)
5197 {
5198         struct smb2_echo_rsp *rsp = work->response_buf;
5199
5200         rsp->StructureSize = cpu_to_le16(4);
5201         rsp->Reserved = 0;
5202         inc_rfc1001_len(rsp, 4);
5203         return 0;
5204 }
5205
5206 static int smb2_rename(struct ksmbd_work *work, struct ksmbd_file *fp,
5207                        struct smb2_file_rename_info *file_info,
5208                        struct nls_table *local_nls)
5209 {
5210         struct ksmbd_share_config *share = fp->tcon->share_conf;
5211         char *new_name = NULL, *abs_oldname = NULL, *old_name = NULL;
5212         char *pathname = NULL;
5213         struct path path;
5214         bool file_present = true;
5215         int rc;
5216
5217         ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5218         pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5219         if (!pathname)
5220                 return -ENOMEM;
5221
5222         abs_oldname = d_path(&fp->filp->f_path, pathname, PATH_MAX);
5223         if (IS_ERR(abs_oldname)) {
5224                 rc = -EINVAL;
5225                 goto out;
5226         }
5227         old_name = strrchr(abs_oldname, '/');
5228         if (old_name && old_name[1] != '\0') {
5229                 old_name++;
5230         } else {
5231                 ksmbd_debug(SMB, "can't get last component in path %s\n",
5232                             abs_oldname);
5233                 rc = -ENOENT;
5234                 goto out;
5235         }
5236
5237         new_name = smb2_get_name(share,
5238                                  file_info->FileName,
5239                                  le32_to_cpu(file_info->FileNameLength),
5240                                  local_nls);
5241         if (IS_ERR(new_name)) {
5242                 rc = PTR_ERR(new_name);
5243                 goto out;
5244         }
5245
5246         if (strchr(new_name, ':')) {
5247                 int s_type;
5248                 char *xattr_stream_name, *stream_name = NULL;
5249                 size_t xattr_stream_size;
5250                 int len;
5251
5252                 rc = parse_stream_name(new_name, &stream_name, &s_type);
5253                 if (rc < 0)
5254                         goto out;
5255
5256                 len = strlen(new_name);
5257                 if (new_name[len - 1] != '/') {
5258                         pr_err("not allow base filename in rename\n");
5259                         rc = -ESHARE;
5260                         goto out;
5261                 }
5262
5263                 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5264                                                  &xattr_stream_name,
5265                                                  &xattr_stream_size,
5266                                                  s_type);
5267                 if (rc)
5268                         goto out;
5269
5270                 rc = ksmbd_vfs_setxattr(file_mnt_user_ns(fp->filp),
5271                                         fp->filp->f_path.dentry,
5272                                         xattr_stream_name,
5273                                         NULL, 0, 0);
5274                 if (rc < 0) {
5275                         pr_err("failed to store stream name in xattr: %d\n",
5276                                rc);
5277                         rc = -EINVAL;
5278                         goto out;
5279                 }
5280
5281                 goto out;
5282         }
5283
5284         ksmbd_debug(SMB, "new name %s\n", new_name);
5285         rc = ksmbd_vfs_kern_path(new_name, 0, &path, 1);
5286         if (rc)
5287                 file_present = false;
5288         else
5289                 path_put(&path);
5290
5291         if (ksmbd_share_veto_filename(share, new_name)) {
5292                 rc = -ENOENT;
5293                 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5294                 goto out;
5295         }
5296
5297         if (file_info->ReplaceIfExists) {
5298                 if (file_present) {
5299                         rc = ksmbd_vfs_remove_file(work, new_name);
5300                         if (rc) {
5301                                 if (rc != -ENOTEMPTY)
5302                                         rc = -EINVAL;
5303                                 ksmbd_debug(SMB, "cannot delete %s, rc %d\n",
5304                                             new_name, rc);
5305                                 goto out;
5306                         }
5307                 }
5308         } else {
5309                 if (file_present &&
5310                     strncmp(old_name, path.dentry->d_name.name, strlen(old_name))) {
5311                         rc = -EEXIST;
5312                         ksmbd_debug(SMB,
5313                                     "cannot rename already existing file\n");
5314                         goto out;
5315                 }
5316         }
5317
5318         rc = ksmbd_vfs_fp_rename(work, fp, new_name);
5319 out:
5320         kfree(pathname);
5321         if (!IS_ERR(new_name))
5322                 kfree(new_name);
5323         return rc;
5324 }
5325
5326 static int smb2_create_link(struct ksmbd_work *work,
5327                             struct ksmbd_share_config *share,
5328                             struct smb2_file_link_info *file_info,
5329                             struct file *filp,
5330                             struct nls_table *local_nls)
5331 {
5332         char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5333         struct path path;
5334         bool file_present = true;
5335         int rc;
5336
5337         ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5338         pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5339         if (!pathname)
5340                 return -ENOMEM;
5341
5342         link_name = smb2_get_name(share,
5343                                   file_info->FileName,
5344                                   le32_to_cpu(file_info->FileNameLength),
5345                                   local_nls);
5346         if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5347                 rc = -EINVAL;
5348                 goto out;
5349         }
5350
5351         ksmbd_debug(SMB, "link name is %s\n", link_name);
5352         target_name = d_path(&filp->f_path, pathname, PATH_MAX);
5353         if (IS_ERR(target_name)) {
5354                 rc = -EINVAL;
5355                 goto out;
5356         }
5357
5358         ksmbd_debug(SMB, "target name is %s\n", target_name);
5359         rc = ksmbd_vfs_kern_path(link_name, 0, &path, 0);
5360         if (rc)
5361                 file_present = false;
5362         else
5363                 path_put(&path);
5364
5365         if (file_info->ReplaceIfExists) {
5366                 if (file_present) {
5367                         rc = ksmbd_vfs_remove_file(work, link_name);
5368                         if (rc) {
5369                                 rc = -EINVAL;
5370                                 ksmbd_debug(SMB, "cannot delete %s\n",
5371                                             link_name);
5372                                 goto out;
5373                         }
5374                 }
5375         } else {
5376                 if (file_present) {
5377                         rc = -EEXIST;
5378                         ksmbd_debug(SMB, "link already exists\n");
5379                         goto out;
5380                 }
5381         }
5382
5383         rc = ksmbd_vfs_link(work, target_name, link_name);
5384         if (rc)
5385                 rc = -EINVAL;
5386 out:
5387         if (!IS_ERR(link_name))
5388                 kfree(link_name);
5389         kfree(pathname);
5390         return rc;
5391 }
5392
5393 static int set_file_basic_info(struct ksmbd_file *fp, char *buf,
5394                                struct ksmbd_share_config *share)
5395 {
5396         struct smb2_file_all_info *file_info;
5397         struct iattr attrs;
5398         struct iattr temp_attrs;
5399         struct file *filp;
5400         struct inode *inode;
5401         struct user_namespace *user_ns;
5402         int rc;
5403
5404         if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5405                 return -EACCES;
5406
5407         file_info = (struct smb2_file_all_info *)buf;
5408         attrs.ia_valid = 0;
5409         filp = fp->filp;
5410         inode = file_inode(filp);
5411         user_ns = file_mnt_user_ns(filp);
5412
5413         if (file_info->CreationTime)
5414                 fp->create_time = le64_to_cpu(file_info->CreationTime);
5415
5416         if (file_info->LastAccessTime) {
5417                 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5418                 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5419         }
5420
5421         if (file_info->ChangeTime) {
5422                 temp_attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5423                 attrs.ia_ctime = temp_attrs.ia_ctime;
5424                 attrs.ia_valid |= ATTR_CTIME;
5425         } else {
5426                 temp_attrs.ia_ctime = inode->i_ctime;
5427         }
5428
5429         if (file_info->LastWriteTime) {
5430                 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5431                 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5432         }
5433
5434         if (file_info->Attributes) {
5435                 if (!S_ISDIR(inode->i_mode) &&
5436                     file_info->Attributes & ATTR_DIRECTORY_LE) {
5437                         pr_err("can't change a file to a directory\n");
5438                         return -EINVAL;
5439                 }
5440
5441                 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == ATTR_NORMAL_LE))
5442                         fp->f_ci->m_fattr = file_info->Attributes |
5443                                 (fp->f_ci->m_fattr & ATTR_DIRECTORY_LE);
5444         }
5445
5446         if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5447             (file_info->CreationTime || file_info->Attributes)) {
5448                 struct xattr_dos_attrib da = {0};
5449
5450                 da.version = 4;
5451                 da.itime = fp->itime;
5452                 da.create_time = fp->create_time;
5453                 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5454                 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5455                         XATTR_DOSINFO_ITIME;
5456
5457                 rc = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
5458                                                     filp->f_path.dentry, &da);
5459                 if (rc)
5460                         ksmbd_debug(SMB,
5461                                     "failed to restore file attribute in EA\n");
5462                 rc = 0;
5463         }
5464
5465         /*
5466          * HACK : set ctime here to avoid ctime changed
5467          * when file_info->ChangeTime is zero.
5468          */
5469         attrs.ia_ctime = temp_attrs.ia_ctime;
5470         attrs.ia_valid |= ATTR_CTIME;
5471
5472         if (attrs.ia_valid) {
5473                 struct dentry *dentry = filp->f_path.dentry;
5474                 struct inode *inode = d_inode(dentry);
5475
5476                 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5477                         return -EACCES;
5478
5479                 rc = setattr_prepare(user_ns, dentry, &attrs);
5480                 if (rc)
5481                         return -EINVAL;
5482
5483                 inode_lock(inode);
5484                 setattr_copy(user_ns, inode, &attrs);
5485                 attrs.ia_valid &= ~ATTR_CTIME;
5486                 rc = notify_change(user_ns, dentry, &attrs, NULL);
5487                 inode_unlock(inode);
5488         }
5489         return 0;
5490 }
5491
5492 static int set_file_allocation_info(struct ksmbd_work *work,
5493                                     struct ksmbd_file *fp, char *buf)
5494 {
5495         /*
5496          * TODO : It's working fine only when store dos attributes
5497          * is not yes. need to implement a logic which works
5498          * properly with any smb.conf option
5499          */
5500
5501         struct smb2_file_alloc_info *file_alloc_info;
5502         loff_t alloc_blks;
5503         struct inode *inode;
5504         int rc;
5505
5506         if (!(fp->daccess & FILE_WRITE_DATA_LE))
5507                 return -EACCES;
5508
5509         file_alloc_info = (struct smb2_file_alloc_info *)buf;
5510         alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5511         inode = file_inode(fp->filp);
5512
5513         if (alloc_blks > inode->i_blocks) {
5514                 smb_break_all_levII_oplock(work, fp, 1);
5515                 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5516                                    alloc_blks * 512);
5517                 if (rc && rc != -EOPNOTSUPP) {
5518                         pr_err("vfs_fallocate is failed : %d\n", rc);
5519                         return rc;
5520                 }
5521         } else if (alloc_blks < inode->i_blocks) {
5522                 loff_t size;
5523
5524                 /*
5525                  * Allocation size could be smaller than original one
5526                  * which means allocated blocks in file should be
5527                  * deallocated. use truncate to cut out it, but inode
5528                  * size is also updated with truncate offset.
5529                  * inode size is retained by backup inode size.
5530                  */
5531                 size = i_size_read(inode);
5532                 rc = ksmbd_vfs_truncate(work, NULL, fp, alloc_blks * 512);
5533                 if (rc) {
5534                         pr_err("truncate failed! filename : %s, err %d\n",
5535                                fp->filename, rc);
5536                         return rc;
5537                 }
5538                 if (size < alloc_blks * 512)
5539                         i_size_write(inode, size);
5540         }
5541         return 0;
5542 }
5543
5544 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5545                                 char *buf)
5546 {
5547         struct smb2_file_eof_info *file_eof_info;
5548         loff_t newsize;
5549         struct inode *inode;
5550         int rc;
5551
5552         if (!(fp->daccess & FILE_WRITE_DATA_LE))
5553                 return -EACCES;
5554
5555         file_eof_info = (struct smb2_file_eof_info *)buf;
5556         newsize = le64_to_cpu(file_eof_info->EndOfFile);
5557         inode = file_inode(fp->filp);
5558
5559         /*
5560          * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5561          * on FAT32 shared device, truncate execution time is too long
5562          * and network error could cause from windows client. because
5563          * truncate of some filesystem like FAT32 fill zero data in
5564          * truncated range.
5565          */
5566         if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5567                 ksmbd_debug(SMB, "filename : %s truncated to newsize %lld\n",
5568                             fp->filename, newsize);
5569                 rc = ksmbd_vfs_truncate(work, NULL, fp, newsize);
5570                 if (rc) {
5571                         ksmbd_debug(SMB, "truncate failed! filename : %s err %d\n",
5572                                     fp->filename, rc);
5573                         if (rc != -EAGAIN)
5574                                 rc = -EBADF;
5575                         return rc;
5576                 }
5577         }
5578         return 0;
5579 }
5580
5581 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5582                            char *buf)
5583 {
5584         struct ksmbd_file *parent_fp;
5585         struct dentry *parent;
5586         struct dentry *dentry = fp->filp->f_path.dentry;
5587         int ret;
5588
5589         if (!(fp->daccess & FILE_DELETE_LE)) {
5590                 pr_err("no right to delete : 0x%x\n", fp->daccess);
5591                 return -EACCES;
5592         }
5593
5594         if (ksmbd_stream_fd(fp))
5595                 goto next;
5596
5597         parent = dget_parent(dentry);
5598         ret = ksmbd_vfs_lock_parent(parent, dentry);
5599         if (ret) {
5600                 dput(parent);
5601                 return ret;
5602         }
5603
5604         parent_fp = ksmbd_lookup_fd_inode(d_inode(parent));
5605         inode_unlock(d_inode(parent));
5606         dput(parent);
5607
5608         if (parent_fp) {
5609                 if (parent_fp->daccess & FILE_DELETE_LE) {
5610                         pr_err("parent dir is opened with delete access\n");
5611                         return -ESHARE;
5612                 }
5613         }
5614 next:
5615         return smb2_rename(work, fp,
5616                            (struct smb2_file_rename_info *)buf,
5617                            work->sess->conn->local_nls);
5618 }
5619
5620 static int set_file_disposition_info(struct ksmbd_file *fp, char *buf)
5621 {
5622         struct smb2_file_disposition_info *file_info;
5623         struct inode *inode;
5624
5625         if (!(fp->daccess & FILE_DELETE_LE)) {
5626                 pr_err("no right to delete : 0x%x\n", fp->daccess);
5627                 return -EACCES;
5628         }
5629
5630         inode = file_inode(fp->filp);
5631         file_info = (struct smb2_file_disposition_info *)buf;
5632         if (file_info->DeletePending) {
5633                 if (S_ISDIR(inode->i_mode) &&
5634                     ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5635                         return -EBUSY;
5636                 ksmbd_set_inode_pending_delete(fp);
5637         } else {
5638                 ksmbd_clear_inode_pending_delete(fp);
5639         }
5640         return 0;
5641 }
5642
5643 static int set_file_position_info(struct ksmbd_file *fp, char *buf)
5644 {
5645         struct smb2_file_pos_info *file_info;
5646         loff_t current_byte_offset;
5647         unsigned long sector_size;
5648         struct inode *inode;
5649
5650         inode = file_inode(fp->filp);
5651         file_info = (struct smb2_file_pos_info *)buf;
5652         current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5653         sector_size = inode->i_sb->s_blocksize;
5654
5655         if (current_byte_offset < 0 ||
5656             (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5657              current_byte_offset & (sector_size - 1))) {
5658                 pr_err("CurrentByteOffset is not valid : %llu\n",
5659                        current_byte_offset);
5660                 return -EINVAL;
5661         }
5662
5663         fp->filp->f_pos = current_byte_offset;
5664         return 0;
5665 }
5666
5667 static int set_file_mode_info(struct ksmbd_file *fp, char *buf)
5668 {
5669         struct smb2_file_mode_info *file_info;
5670         __le32 mode;
5671
5672         file_info = (struct smb2_file_mode_info *)buf;
5673         mode = file_info->Mode;
5674
5675         if ((mode & ~FILE_MODE_INFO_MASK) ||
5676             (mode & FILE_SYNCHRONOUS_IO_ALERT_LE &&
5677              mode & FILE_SYNCHRONOUS_IO_NONALERT_LE)) {
5678                 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5679                 return -EINVAL;
5680         }
5681
5682         /*
5683          * TODO : need to implement consideration for
5684          * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5685          */
5686         ksmbd_vfs_set_fadvise(fp->filp, mode);
5687         fp->coption = mode;
5688         return 0;
5689 }
5690
5691 /**
5692  * smb2_set_info_file() - handler for smb2 set info command
5693  * @work:       smb work containing set info command buffer
5694  * @fp:         ksmbd_file pointer
5695  * @info_class: smb2 set info class
5696  * @share:      ksmbd_share_config pointer
5697  *
5698  * Return:      0 on success, otherwise error
5699  * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5700  */
5701 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5702                               int info_class, char *buf,
5703                               struct ksmbd_share_config *share)
5704 {
5705         switch (info_class) {
5706         case FILE_BASIC_INFORMATION:
5707                 return set_file_basic_info(fp, buf, share);
5708
5709         case FILE_ALLOCATION_INFORMATION:
5710                 return set_file_allocation_info(work, fp, buf);
5711
5712         case FILE_END_OF_FILE_INFORMATION:
5713                 return set_end_of_file_info(work, fp, buf);
5714
5715         case FILE_RENAME_INFORMATION:
5716                 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5717                         ksmbd_debug(SMB,
5718                                     "User does not have write permission\n");
5719                         return -EACCES;
5720                 }
5721                 return set_rename_info(work, fp, buf);
5722
5723         case FILE_LINK_INFORMATION:
5724                 return smb2_create_link(work, work->tcon->share_conf,
5725                                         (struct smb2_file_link_info *)buf, fp->filp,
5726                                         work->sess->conn->local_nls);
5727
5728         case FILE_DISPOSITION_INFORMATION:
5729                 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5730                         ksmbd_debug(SMB,
5731                                     "User does not have write permission\n");
5732                         return -EACCES;
5733                 }
5734                 return set_file_disposition_info(fp, buf);
5735
5736         case FILE_FULL_EA_INFORMATION:
5737         {
5738                 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5739                         pr_err("Not permitted to write ext  attr: 0x%x\n",
5740                                fp->daccess);
5741                         return -EACCES;
5742                 }
5743
5744                 return smb2_set_ea((struct smb2_ea_info *)buf,
5745                                    &fp->filp->f_path);
5746         }
5747
5748         case FILE_POSITION_INFORMATION:
5749                 return set_file_position_info(fp, buf);
5750
5751         case FILE_MODE_INFORMATION:
5752                 return set_file_mode_info(fp, buf);
5753         }
5754
5755         pr_err("Unimplemented Fileinfoclass :%d\n", info_class);
5756         return -EOPNOTSUPP;
5757 }
5758
5759 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
5760                              char *buffer, int buf_len)
5761 {
5762         struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
5763
5764         fp->saccess |= FILE_SHARE_DELETE_LE;
5765
5766         return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
5767                         buf_len, false);
5768 }
5769
5770 /**
5771  * smb2_set_info() - handler for smb2 set info command handler
5772  * @work:       smb work containing set info request buffer
5773  *
5774  * Return:      0 on success, otherwise error
5775  */
5776 int smb2_set_info(struct ksmbd_work *work)
5777 {
5778         struct smb2_set_info_req *req;
5779         struct smb2_set_info_rsp *rsp, *rsp_org;
5780         struct ksmbd_file *fp;
5781         int rc = 0;
5782         unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5783
5784         ksmbd_debug(SMB, "Received set info request\n");
5785
5786         rsp_org = work->response_buf;
5787         if (work->next_smb2_rcv_hdr_off) {
5788                 req = ksmbd_req_buf_next(work);
5789                 rsp = ksmbd_resp_buf_next(work);
5790                 if (!HAS_FILE_ID(le64_to_cpu(req->VolatileFileId))) {
5791                         ksmbd_debug(SMB, "Compound request set FID = %u\n",
5792                                     work->compound_fid);
5793                         id = work->compound_fid;
5794                         pid = work->compound_pfid;
5795                 }
5796         } else {
5797                 req = work->request_buf;
5798                 rsp = work->response_buf;
5799         }
5800
5801         if (!HAS_FILE_ID(id)) {
5802                 id = le64_to_cpu(req->VolatileFileId);
5803                 pid = le64_to_cpu(req->PersistentFileId);
5804         }
5805
5806         fp = ksmbd_lookup_fd_slow(work, id, pid);
5807         if (!fp) {
5808                 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
5809                 rc = -ENOENT;
5810                 goto err_out;
5811         }
5812
5813         switch (req->InfoType) {
5814         case SMB2_O_INFO_FILE:
5815                 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5816                 rc = smb2_set_info_file(work, fp, req->FileInfoClass,
5817                                         req->Buffer, work->tcon->share_conf);
5818                 break;
5819         case SMB2_O_INFO_SECURITY:
5820                 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5821                 rc = smb2_set_info_sec(fp,
5822                                        le32_to_cpu(req->AdditionalInformation),
5823                                        req->Buffer,
5824                                        le32_to_cpu(req->BufferLength));
5825                 break;
5826         default:
5827                 rc = -EOPNOTSUPP;
5828         }
5829
5830         if (rc < 0)
5831                 goto err_out;
5832
5833         rsp->StructureSize = cpu_to_le16(2);
5834         inc_rfc1001_len(rsp_org, 2);
5835         ksmbd_fd_put(work, fp);
5836         return 0;
5837
5838 err_out:
5839         if (rc == -EACCES || rc == -EPERM)
5840                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5841         else if (rc == -EINVAL)
5842                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5843         else if (rc == -ESHARE)
5844                 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
5845         else if (rc == -ENOENT)
5846                 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
5847         else if (rc == -EBUSY || rc == -ENOTEMPTY)
5848                 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
5849         else if (rc == -EAGAIN)
5850                 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
5851         else if (rc == -EBADF || rc == -ESTALE)
5852                 rsp->hdr.Status = STATUS_INVALID_HANDLE;
5853         else if (rc == -EEXIST)
5854                 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
5855         else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
5856                 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5857         smb2_set_err_rsp(work);
5858         ksmbd_fd_put(work, fp);
5859         ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
5860         return rc;
5861 }
5862
5863 /**
5864  * smb2_read_pipe() - handler for smb2 read from IPC pipe
5865  * @work:       smb work containing read IPC pipe command buffer
5866  *
5867  * Return:      0 on success, otherwise error
5868  */
5869 static noinline int smb2_read_pipe(struct ksmbd_work *work)
5870 {
5871         int nbytes = 0, err;
5872         u64 id;
5873         struct ksmbd_rpc_command *rpc_resp;
5874         struct smb2_read_req *req = work->request_buf;
5875         struct smb2_read_rsp *rsp = work->response_buf;
5876
5877         id = le64_to_cpu(req->VolatileFileId);
5878
5879         inc_rfc1001_len(rsp, 16);
5880         rpc_resp = ksmbd_rpc_read(work->sess, id);
5881         if (rpc_resp) {
5882                 if (rpc_resp->flags != KSMBD_RPC_OK) {
5883                         err = -EINVAL;
5884                         goto out;
5885                 }
5886
5887                 work->aux_payload_buf =
5888                         kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
5889                 if (!work->aux_payload_buf) {
5890                         err = -ENOMEM;
5891                         goto out;
5892                 }
5893
5894                 memcpy(work->aux_payload_buf, rpc_resp->payload,
5895                        rpc_resp->payload_sz);
5896
5897                 nbytes = rpc_resp->payload_sz;
5898                 work->resp_hdr_sz = get_rfc1002_len(rsp) + 4;
5899                 work->aux_payload_sz = nbytes;
5900                 kvfree(rpc_resp);
5901         }
5902
5903         rsp->StructureSize = cpu_to_le16(17);
5904         rsp->DataOffset = 80;
5905         rsp->Reserved = 0;
5906         rsp->DataLength = cpu_to_le32(nbytes);
5907         rsp->DataRemaining = 0;
5908         rsp->Reserved2 = 0;
5909         inc_rfc1001_len(rsp, nbytes);
5910         return 0;
5911
5912 out:
5913         rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5914         smb2_set_err_rsp(work);
5915         kvfree(rpc_resp);
5916         return err;
5917 }
5918
5919 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
5920                                       struct smb2_read_req *req, void *data_buf,
5921                                       size_t length)
5922 {
5923         struct smb2_buffer_desc_v1 *desc =
5924                 (struct smb2_buffer_desc_v1 *)&req->Buffer[0];
5925         int err;
5926
5927         if (work->conn->dialect == SMB30_PROT_ID &&
5928             req->Channel != SMB2_CHANNEL_RDMA_V1)
5929                 return -EINVAL;
5930
5931         if (req->ReadChannelInfoOffset == 0 ||
5932             le16_to_cpu(req->ReadChannelInfoLength) < sizeof(*desc))
5933                 return -EINVAL;
5934
5935         work->need_invalidate_rkey =
5936                 (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
5937         work->remote_key = le32_to_cpu(desc->token);
5938
5939         err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
5940                                     le32_to_cpu(desc->token),
5941                                     le64_to_cpu(desc->offset),
5942                                     le32_to_cpu(desc->length));
5943         if (err)
5944                 return err;
5945
5946         return length;
5947 }
5948
5949 /**
5950  * smb2_read() - handler for smb2 read from file
5951  * @work:       smb work containing read command buffer
5952  *
5953  * Return:      0 on success, otherwise error
5954  */
5955 int smb2_read(struct ksmbd_work *work)
5956 {
5957         struct ksmbd_conn *conn = work->conn;
5958         struct smb2_read_req *req;
5959         struct smb2_read_rsp *rsp, *rsp_org;
5960         struct ksmbd_file *fp;
5961         loff_t offset;
5962         size_t length, mincount;
5963         ssize_t nbytes = 0, remain_bytes = 0;
5964         int err = 0;
5965
5966         rsp_org = work->response_buf;
5967         WORK_BUFFERS(work, req, rsp);
5968
5969         if (test_share_config_flag(work->tcon->share_conf,
5970                                    KSMBD_SHARE_FLAG_PIPE)) {
5971                 ksmbd_debug(SMB, "IPC pipe read request\n");
5972                 return smb2_read_pipe(work);
5973         }
5974
5975         fp = ksmbd_lookup_fd_slow(work, le64_to_cpu(req->VolatileFileId),
5976                                   le64_to_cpu(req->PersistentFileId));
5977         if (!fp) {
5978                 err = -ENOENT;
5979                 goto out;
5980         }
5981
5982         if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
5983                 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
5984                 err = -EACCES;
5985                 goto out;
5986         }
5987
5988         offset = le64_to_cpu(req->Offset);
5989         length = le32_to_cpu(req->Length);
5990         mincount = le32_to_cpu(req->MinimumCount);
5991
5992         if (length > conn->vals->max_read_size) {
5993                 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
5994                             conn->vals->max_read_size);
5995                 err = -EINVAL;
5996                 goto out;
5997         }
5998
5999         ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6000                     fp->filp->f_path.dentry, offset, length);
6001
6002         work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6003         if (!work->aux_payload_buf) {
6004                 err = -ENOMEM;
6005                 goto out;
6006         }
6007
6008         nbytes = ksmbd_vfs_read(work, fp, length, &offset);
6009         if (nbytes < 0) {
6010                 err = nbytes;
6011                 goto out;
6012         }
6013
6014         if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6015                 kvfree(work->aux_payload_buf);
6016                 work->aux_payload_buf = NULL;
6017                 rsp->hdr.Status = STATUS_END_OF_FILE;
6018                 smb2_set_err_rsp(work);
6019                 ksmbd_fd_put(work, fp);
6020                 return 0;
6021         }
6022
6023         ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6024                     nbytes, offset, mincount);
6025
6026         if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6027             req->Channel == SMB2_CHANNEL_RDMA_V1) {
6028                 /* write data to the client using rdma channel */
6029                 remain_bytes = smb2_read_rdma_channel(work, req,
6030                                                       work->aux_payload_buf,
6031                                                       nbytes);
6032                 kvfree(work->aux_payload_buf);
6033                 work->aux_payload_buf = NULL;
6034
6035                 nbytes = 0;
6036                 if (remain_bytes < 0) {
6037                         err = (int)remain_bytes;
6038                         goto out;
6039                 }
6040         }
6041
6042         rsp->StructureSize = cpu_to_le16(17);
6043         rsp->DataOffset = 80;
6044         rsp->Reserved = 0;
6045         rsp->DataLength = cpu_to_le32(nbytes);
6046         rsp->DataRemaining = cpu_to_le32(remain_bytes);
6047         rsp->Reserved2 = 0;
6048         inc_rfc1001_len(rsp_org, 16);
6049         work->resp_hdr_sz = get_rfc1002_len(rsp_org) + 4;
6050         work->aux_payload_sz = nbytes;
6051         inc_rfc1001_len(rsp_org, nbytes);
6052         ksmbd_fd_put(work, fp);
6053         return 0;
6054
6055 out:
6056         if (err) {
6057                 if (err == -EISDIR)
6058                         rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6059                 else if (err == -EAGAIN)
6060                         rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6061                 else if (err == -ENOENT)
6062                         rsp->hdr.Status = STATUS_FILE_CLOSED;
6063                 else if (err == -EACCES)
6064                         rsp->hdr.Status = STATUS_ACCESS_DENIED;
6065                 else if (err == -ESHARE)
6066                         rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6067                 else if (err == -EINVAL)
6068                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6069                 else
6070                         rsp->hdr.Status = STATUS_INVALID_HANDLE;
6071
6072                 smb2_set_err_rsp(work);
6073         }
6074         ksmbd_fd_put(work, fp);
6075         return err;
6076 }
6077
6078 /**
6079  * smb2_write_pipe() - handler for smb2 write on IPC pipe
6080  * @work:       smb work containing write IPC pipe command buffer
6081  *
6082  * Return:      0 on success, otherwise error
6083  */
6084 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6085 {
6086         struct smb2_write_req *req = work->request_buf;
6087         struct smb2_write_rsp *rsp = work->response_buf;
6088         struct ksmbd_rpc_command *rpc_resp;
6089         u64 id = 0;
6090         int err = 0, ret = 0;
6091         char *data_buf;
6092         size_t length;
6093
6094         length = le32_to_cpu(req->Length);
6095         id = le64_to_cpu(req->VolatileFileId);
6096
6097         if (le16_to_cpu(req->DataOffset) ==
6098             (offsetof(struct smb2_write_req, Buffer) - 4)) {
6099                 data_buf = (char *)&req->Buffer[0];
6100         } else {
6101                 if ((le16_to_cpu(req->DataOffset) > get_rfc1002_len(req)) ||
6102                     (le16_to_cpu(req->DataOffset) + length > get_rfc1002_len(req))) {
6103                         pr_err("invalid write data offset %u, smb_len %u\n",
6104                                le16_to_cpu(req->DataOffset),
6105                                get_rfc1002_len(req));
6106                         err = -EINVAL;
6107                         goto out;
6108                 }
6109
6110                 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6111                                 le16_to_cpu(req->DataOffset));
6112         }
6113
6114         rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6115         if (rpc_resp) {
6116                 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6117                         rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6118                         kvfree(rpc_resp);
6119                         smb2_set_err_rsp(work);
6120                         return -EOPNOTSUPP;
6121                 }
6122                 if (rpc_resp->flags != KSMBD_RPC_OK) {
6123                         rsp->hdr.Status = STATUS_INVALID_HANDLE;
6124                         smb2_set_err_rsp(work);
6125                         kvfree(rpc_resp);
6126                         return ret;
6127                 }
6128                 kvfree(rpc_resp);
6129         }
6130
6131         rsp->StructureSize = cpu_to_le16(17);
6132         rsp->DataOffset = 0;
6133         rsp->Reserved = 0;
6134         rsp->DataLength = cpu_to_le32(length);
6135         rsp->DataRemaining = 0;
6136         rsp->Reserved2 = 0;
6137         inc_rfc1001_len(rsp, 16);
6138         return 0;
6139 out:
6140         if (err) {
6141                 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6142                 smb2_set_err_rsp(work);
6143         }
6144
6145         return err;
6146 }
6147
6148 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6149                                        struct smb2_write_req *req,
6150                                        struct ksmbd_file *fp,
6151                                        loff_t offset, size_t length, bool sync)
6152 {
6153         struct smb2_buffer_desc_v1 *desc;
6154         char *data_buf;
6155         int ret;
6156         ssize_t nbytes;
6157
6158         desc = (struct smb2_buffer_desc_v1 *)&req->Buffer[0];
6159
6160         if (work->conn->dialect == SMB30_PROT_ID &&
6161             req->Channel != SMB2_CHANNEL_RDMA_V1)
6162                 return -EINVAL;
6163
6164         if (req->Length != 0 || req->DataOffset != 0)
6165                 return -EINVAL;
6166
6167         if (req->WriteChannelInfoOffset == 0 ||
6168             le16_to_cpu(req->WriteChannelInfoLength) < sizeof(*desc))
6169                 return -EINVAL;
6170
6171         work->need_invalidate_rkey =
6172                 (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6173         work->remote_key = le32_to_cpu(desc->token);
6174
6175         data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6176         if (!data_buf)
6177                 return -ENOMEM;
6178
6179         ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6180                                    le32_to_cpu(desc->token),
6181                                    le64_to_cpu(desc->offset),
6182                                    le32_to_cpu(desc->length));
6183         if (ret < 0) {
6184                 kvfree(data_buf);
6185                 return ret;
6186         }
6187
6188         ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6189         kvfree(data_buf);
6190         if (ret < 0)
6191                 return ret;
6192
6193         return nbytes;
6194 }
6195
6196 /**
6197  * smb2_write() - handler for smb2 write from file
6198  * @work:       smb work containing write command buffer
6199  *
6200  * Return:      0 on success, otherwise error
6201  */
6202 int smb2_write(struct ksmbd_work *work)
6203 {
6204         struct smb2_write_req *req;
6205         struct smb2_write_rsp *rsp, *rsp_org;
6206         struct ksmbd_file *fp = NULL;
6207         loff_t offset;
6208         size_t length;
6209         ssize_t nbytes;
6210         char *data_buf;
6211         bool writethrough = false;
6212         int err = 0;
6213
6214         rsp_org = work->response_buf;
6215         WORK_BUFFERS(work, req, rsp);
6216
6217         if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6218                 ksmbd_debug(SMB, "IPC pipe write request\n");
6219                 return smb2_write_pipe(work);
6220         }
6221
6222         if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6223                 ksmbd_debug(SMB, "User does not have write permission\n");
6224                 err = -EACCES;
6225                 goto out;
6226         }
6227
6228         fp = ksmbd_lookup_fd_slow(work, le64_to_cpu(req->VolatileFileId),
6229                                   le64_to_cpu(req->PersistentFileId));
6230         if (!fp) {
6231                 err = -ENOENT;
6232                 goto out;
6233         }
6234
6235         if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6236                 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6237                 err = -EACCES;
6238                 goto out;
6239         }
6240
6241         offset = le64_to_cpu(req->Offset);
6242         length = le32_to_cpu(req->Length);
6243
6244         if (length > work->conn->vals->max_write_size) {
6245                 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6246                             work->conn->vals->max_write_size);
6247                 err = -EINVAL;
6248                 goto out;
6249         }
6250
6251         if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6252                 writethrough = true;
6253
6254         if (req->Channel != SMB2_CHANNEL_RDMA_V1 &&
6255             req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6256                 if (le16_to_cpu(req->DataOffset) ==
6257                     (offsetof(struct smb2_write_req, Buffer) - 4)) {
6258                         data_buf = (char *)&req->Buffer[0];
6259                 } else {
6260                         if ((le16_to_cpu(req->DataOffset) > get_rfc1002_len(req)) ||
6261                             (le16_to_cpu(req->DataOffset) + length > get_rfc1002_len(req))) {
6262                                 pr_err("invalid write data offset %u, smb_len %u\n",
6263                                        le16_to_cpu(req->DataOffset),
6264                                        get_rfc1002_len(req));
6265                                 err = -EINVAL;
6266                                 goto out;
6267                         }
6268
6269                         data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6270                                         le16_to_cpu(req->DataOffset));
6271                 }
6272
6273                 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6274                 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6275                         writethrough = true;
6276
6277                 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6278                             fp->filp->f_path.dentry, offset, length);
6279                 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6280                                       writethrough, &nbytes);
6281                 if (err < 0)
6282                         goto out;
6283         } else {
6284                 /* read data from the client using rdma channel, and
6285                  * write the data.
6286                  */
6287                 nbytes = smb2_write_rdma_channel(work, req, fp, offset,
6288                                                  le32_to_cpu(req->RemainingBytes),
6289                                                  writethrough);
6290                 if (nbytes < 0) {
6291                         err = (int)nbytes;
6292                         goto out;
6293                 }
6294         }
6295
6296         rsp->StructureSize = cpu_to_le16(17);
6297         rsp->DataOffset = 0;
6298         rsp->Reserved = 0;
6299         rsp->DataLength = cpu_to_le32(nbytes);
6300         rsp->DataRemaining = 0;
6301         rsp->Reserved2 = 0;
6302         inc_rfc1001_len(rsp_org, 16);
6303         ksmbd_fd_put(work, fp);
6304         return 0;
6305
6306 out:
6307         if (err == -EAGAIN)
6308                 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6309         else if (err == -ENOSPC || err == -EFBIG)
6310                 rsp->hdr.Status = STATUS_DISK_FULL;
6311         else if (err == -ENOENT)
6312                 rsp->hdr.Status = STATUS_FILE_CLOSED;
6313         else if (err == -EACCES)
6314                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6315         else if (err == -ESHARE)
6316                 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6317         else if (err == -EINVAL)
6318                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6319         else
6320                 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6321
6322         smb2_set_err_rsp(work);
6323         ksmbd_fd_put(work, fp);
6324         return err;
6325 }
6326
6327 /**
6328  * smb2_flush() - handler for smb2 flush file - fsync
6329  * @work:       smb work containing flush command buffer
6330  *
6331  * Return:      0 on success, otherwise error
6332  */
6333 int smb2_flush(struct ksmbd_work *work)
6334 {
6335         struct smb2_flush_req *req;
6336         struct smb2_flush_rsp *rsp, *rsp_org;
6337         int err;
6338
6339         rsp_org = work->response_buf;
6340         WORK_BUFFERS(work, req, rsp);
6341
6342         ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n",
6343                     le64_to_cpu(req->VolatileFileId));
6344
6345         err = ksmbd_vfs_fsync(work,
6346                               le64_to_cpu(req->VolatileFileId),
6347                               le64_to_cpu(req->PersistentFileId));
6348         if (err)
6349                 goto out;
6350
6351         rsp->StructureSize = cpu_to_le16(4);
6352         rsp->Reserved = 0;
6353         inc_rfc1001_len(rsp_org, 4);
6354         return 0;
6355
6356 out:
6357         if (err) {
6358                 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6359                 smb2_set_err_rsp(work);
6360         }
6361
6362         return err;
6363 }
6364
6365 /**
6366  * smb2_cancel() - handler for smb2 cancel command
6367  * @work:       smb work containing cancel command buffer
6368  *
6369  * Return:      0 on success, otherwise error
6370  */
6371 int smb2_cancel(struct ksmbd_work *work)
6372 {
6373         struct ksmbd_conn *conn = work->conn;
6374         struct smb2_hdr *hdr = work->request_buf;
6375         struct smb2_hdr *chdr;
6376         struct ksmbd_work *cancel_work = NULL;
6377         int canceled = 0;
6378         struct list_head *command_list;
6379
6380         ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6381                     hdr->MessageId, hdr->Flags);
6382
6383         if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6384                 command_list = &conn->async_requests;
6385
6386                 spin_lock(&conn->request_lock);
6387                 list_for_each_entry(cancel_work, command_list,
6388                                     async_request_entry) {
6389                         chdr = cancel_work->request_buf;
6390
6391                         if (cancel_work->async_id !=
6392                             le64_to_cpu(hdr->Id.AsyncId))
6393                                 continue;
6394
6395                         ksmbd_debug(SMB,
6396                                     "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6397                                     le64_to_cpu(hdr->Id.AsyncId),
6398                                     le16_to_cpu(chdr->Command));
6399                         canceled = 1;
6400                         break;
6401                 }
6402                 spin_unlock(&conn->request_lock);
6403         } else {
6404                 command_list = &conn->requests;
6405
6406                 spin_lock(&conn->request_lock);
6407                 list_for_each_entry(cancel_work, command_list, request_entry) {
6408                         chdr = cancel_work->request_buf;
6409
6410                         if (chdr->MessageId != hdr->MessageId ||
6411                             cancel_work == work)
6412                                 continue;
6413
6414                         ksmbd_debug(SMB,
6415                                     "smb2 with mid %llu cancelled command = 0x%x\n",
6416                                     le64_to_cpu(hdr->MessageId),
6417                                     le16_to_cpu(chdr->Command));
6418                         canceled = 1;
6419                         break;
6420                 }
6421                 spin_unlock(&conn->request_lock);
6422         }
6423
6424         if (canceled) {
6425                 cancel_work->state = KSMBD_WORK_CANCELLED;
6426                 if (cancel_work->cancel_fn)
6427                         cancel_work->cancel_fn(cancel_work->cancel_argv);
6428         }
6429
6430         /* For SMB2_CANCEL command itself send no response*/
6431         work->send_no_response = 1;
6432         return 0;
6433 }
6434
6435 struct file_lock *smb_flock_init(struct file *f)
6436 {
6437         struct file_lock *fl;
6438
6439         fl = locks_alloc_lock();
6440         if (!fl)
6441                 goto out;
6442
6443         locks_init_lock(fl);
6444
6445         fl->fl_owner = f;
6446         fl->fl_pid = current->tgid;
6447         fl->fl_file = f;
6448         fl->fl_flags = FL_POSIX;
6449         fl->fl_ops = NULL;
6450         fl->fl_lmops = NULL;
6451
6452 out:
6453         return fl;
6454 }
6455
6456 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6457 {
6458         int cmd = -EINVAL;
6459
6460         /* Checking for wrong flag combination during lock request*/
6461         switch (flags) {
6462         case SMB2_LOCKFLAG_SHARED:
6463                 ksmbd_debug(SMB, "received shared request\n");
6464                 cmd = F_SETLKW;
6465                 flock->fl_type = F_RDLCK;
6466                 flock->fl_flags |= FL_SLEEP;
6467                 break;
6468         case SMB2_LOCKFLAG_EXCLUSIVE:
6469                 ksmbd_debug(SMB, "received exclusive request\n");
6470                 cmd = F_SETLKW;
6471                 flock->fl_type = F_WRLCK;
6472                 flock->fl_flags |= FL_SLEEP;
6473                 break;
6474         case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6475                 ksmbd_debug(SMB,
6476                             "received shared & fail immediately request\n");
6477                 cmd = F_SETLK;
6478                 flock->fl_type = F_RDLCK;
6479                 break;
6480         case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6481                 ksmbd_debug(SMB,
6482                             "received exclusive & fail immediately request\n");
6483                 cmd = F_SETLK;
6484                 flock->fl_type = F_WRLCK;
6485                 break;
6486         case SMB2_LOCKFLAG_UNLOCK:
6487                 ksmbd_debug(SMB, "received unlock request\n");
6488                 flock->fl_type = F_UNLCK;
6489                 cmd = 0;
6490                 break;
6491         }
6492
6493         return cmd;
6494 }
6495
6496 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6497                                          unsigned int cmd, int flags,
6498                                          struct list_head *lock_list)
6499 {
6500         struct ksmbd_lock *lock;
6501
6502         lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6503         if (!lock)
6504                 return NULL;
6505
6506         lock->cmd = cmd;
6507         lock->fl = flock;
6508         lock->start = flock->fl_start;
6509         lock->end = flock->fl_end;
6510         lock->flags = flags;
6511         if (lock->start == lock->end)
6512                 lock->zero_len = 1;
6513         INIT_LIST_HEAD(&lock->llist);
6514         INIT_LIST_HEAD(&lock->glist);
6515         list_add_tail(&lock->llist, lock_list);
6516
6517         return lock;
6518 }
6519
6520 static void smb2_remove_blocked_lock(void **argv)
6521 {
6522         struct file_lock *flock = (struct file_lock *)argv[0];
6523
6524         ksmbd_vfs_posix_lock_unblock(flock);
6525         wake_up(&flock->fl_wait);
6526 }
6527
6528 static inline bool lock_defer_pending(struct file_lock *fl)
6529 {
6530         /* check pending lock waiters */
6531         return waitqueue_active(&fl->fl_wait);
6532 }
6533
6534 /**
6535  * smb2_lock() - handler for smb2 file lock command
6536  * @work:       smb work containing lock command buffer
6537  *
6538  * Return:      0 on success, otherwise error
6539  */
6540 int smb2_lock(struct ksmbd_work *work)
6541 {
6542         struct smb2_lock_req *req = work->request_buf;
6543         struct smb2_lock_rsp *rsp = work->response_buf;
6544         struct smb2_lock_element *lock_ele;
6545         struct ksmbd_file *fp = NULL;
6546         struct file_lock *flock = NULL;
6547         struct file *filp = NULL;
6548         int lock_count;
6549         int flags = 0;
6550         int cmd = 0;
6551         int err = 0, i;
6552         u64 lock_start, lock_length;
6553         struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp;
6554         int nolock = 0;
6555         LIST_HEAD(lock_list);
6556         LIST_HEAD(rollback_list);
6557         int prior_lock = 0;
6558
6559         ksmbd_debug(SMB, "Received lock request\n");
6560         fp = ksmbd_lookup_fd_slow(work,
6561                                   le64_to_cpu(req->VolatileFileId),
6562                                   le64_to_cpu(req->PersistentFileId));
6563         if (!fp) {
6564                 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n",
6565                             le64_to_cpu(req->VolatileFileId));
6566                 rsp->hdr.Status = STATUS_FILE_CLOSED;
6567                 goto out2;
6568         }
6569
6570         filp = fp->filp;
6571         lock_count = le16_to_cpu(req->LockCount);
6572         lock_ele = req->locks;
6573
6574         ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6575         if (!lock_count) {
6576                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6577                 goto out2;
6578         }
6579
6580         for (i = 0; i < lock_count; i++) {
6581                 flags = le32_to_cpu(lock_ele[i].Flags);
6582
6583                 flock = smb_flock_init(filp);
6584                 if (!flock) {
6585                         rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
6586                         goto out;
6587                 }
6588
6589                 cmd = smb2_set_flock_flags(flock, flags);
6590
6591                 lock_start = le64_to_cpu(lock_ele[i].Offset);
6592                 lock_length = le64_to_cpu(lock_ele[i].Length);
6593                 if (lock_start > U64_MAX - lock_length) {
6594                         pr_err("Invalid lock range requested\n");
6595                         rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6596                         goto out;
6597                 }
6598
6599                 if (lock_start > OFFSET_MAX)
6600                         flock->fl_start = OFFSET_MAX;
6601                 else
6602                         flock->fl_start = lock_start;
6603
6604                 lock_length = le64_to_cpu(lock_ele[i].Length);
6605                 if (lock_length > OFFSET_MAX - flock->fl_start)
6606                         lock_length = OFFSET_MAX - flock->fl_start;
6607
6608                 flock->fl_end = flock->fl_start + lock_length;
6609
6610                 if (flock->fl_end < flock->fl_start) {
6611                         ksmbd_debug(SMB,
6612                                     "the end offset(%llx) is smaller than the start offset(%llx)\n",
6613                                     flock->fl_end, flock->fl_start);
6614                         rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6615                         goto out;
6616                 }
6617
6618                 /* Check conflict locks in one request */
6619                 list_for_each_entry(cmp_lock, &lock_list, llist) {
6620                         if (cmp_lock->fl->fl_start <= flock->fl_start &&
6621                             cmp_lock->fl->fl_end >= flock->fl_end) {
6622                                 if (cmp_lock->fl->fl_type != F_UNLCK &&
6623                                     flock->fl_type != F_UNLCK) {
6624                                         pr_err("conflict two locks in one request\n");
6625                                         rsp->hdr.Status =
6626                                                 STATUS_INVALID_PARAMETER;
6627                                         goto out;
6628                                 }
6629                         }
6630                 }
6631
6632                 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6633                 if (!smb_lock) {
6634                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6635                         goto out;
6636                 }
6637         }
6638
6639         list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6640                 if (smb_lock->cmd < 0) {
6641                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6642                         goto out;
6643                 }
6644
6645                 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6646                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6647                         goto out;
6648                 }
6649
6650                 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6651                      smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6652                     (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6653                      !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6654                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6655                         goto out;
6656                 }
6657
6658                 prior_lock = smb_lock->flags;
6659
6660                 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6661                     !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6662                         goto no_check_gl;
6663
6664                 nolock = 1;
6665                 /* check locks in global list */
6666                 list_for_each_entry(cmp_lock, &global_lock_list, glist) {
6667                         if (file_inode(cmp_lock->fl->fl_file) !=
6668                             file_inode(smb_lock->fl->fl_file))
6669                                 continue;
6670
6671                         if (smb_lock->fl->fl_type == F_UNLCK) {
6672                                 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6673                                     cmp_lock->start == smb_lock->start &&
6674                                     cmp_lock->end == smb_lock->end &&
6675                                     !lock_defer_pending(cmp_lock->fl)) {
6676                                         nolock = 0;
6677                                         locks_free_lock(cmp_lock->fl);
6678                                         list_del(&cmp_lock->glist);
6679                                         kfree(cmp_lock);
6680                                         break;
6681                                 }
6682                                 continue;
6683                         }
6684
6685                         if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6686                                 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6687                                         continue;
6688                         } else {
6689                                 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
6690                                         continue;
6691                         }
6692
6693                         /* check zero byte lock range */
6694                         if (cmp_lock->zero_len && !smb_lock->zero_len &&
6695                             cmp_lock->start > smb_lock->start &&
6696                             cmp_lock->start < smb_lock->end) {
6697                                 pr_err("previous lock conflict with zero byte lock range\n");
6698                                 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
6699                                         goto out;
6700                         }
6701
6702                         if (smb_lock->zero_len && !cmp_lock->zero_len &&
6703                             smb_lock->start > cmp_lock->start &&
6704                             smb_lock->start < cmp_lock->end) {
6705                                 pr_err("current lock conflict with zero byte lock range\n");
6706                                 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
6707                                         goto out;
6708                         }
6709
6710                         if (((cmp_lock->start <= smb_lock->start &&
6711                               cmp_lock->end > smb_lock->start) ||
6712                              (cmp_lock->start < smb_lock->end && cmp_lock->end >= smb_lock->end)) &&
6713                             !cmp_lock->zero_len && !smb_lock->zero_len) {
6714                                 pr_err("Not allow lock operation on exclusive lock range\n");
6715                                 rsp->hdr.Status =
6716                                         STATUS_LOCK_NOT_GRANTED;
6717                                 goto out;
6718                         }
6719                 }
6720
6721                 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
6722                         pr_err("Try to unlock nolocked range\n");
6723                         rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
6724                         goto out;
6725                 }
6726
6727 no_check_gl:
6728                 if (smb_lock->zero_len) {
6729                         err = 0;
6730                         goto skip;
6731                 }
6732
6733                 flock = smb_lock->fl;
6734                 list_del(&smb_lock->llist);
6735 retry:
6736                 err = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
6737 skip:
6738                 if (flags & SMB2_LOCKFLAG_UNLOCK) {
6739                         if (!err) {
6740                                 ksmbd_debug(SMB, "File unlocked\n");
6741                         } else if (err == -ENOENT) {
6742                                 rsp->hdr.Status = STATUS_NOT_LOCKED;
6743                                 goto out;
6744                         }
6745                         locks_free_lock(flock);
6746                         kfree(smb_lock);
6747                 } else {
6748                         if (err == FILE_LOCK_DEFERRED) {
6749                                 void **argv;
6750
6751                                 ksmbd_debug(SMB,
6752                                             "would have to wait for getting lock\n");
6753                                 list_add_tail(&smb_lock->glist,
6754                                               &global_lock_list);
6755                                 list_add(&smb_lock->llist, &rollback_list);
6756
6757                                 argv = kmalloc(sizeof(void *), GFP_KERNEL);
6758                                 if (!argv) {
6759                                         err = -ENOMEM;
6760                                         goto out;
6761                                 }
6762                                 argv[0] = flock;
6763
6764                                 err = setup_async_work(work,
6765                                                        smb2_remove_blocked_lock,
6766                                                        argv);
6767                                 if (err) {
6768                                         rsp->hdr.Status =
6769                                            STATUS_INSUFFICIENT_RESOURCES;
6770                                         goto out;
6771                                 }
6772                                 spin_lock(&fp->f_lock);
6773                                 list_add(&work->fp_entry, &fp->blocked_works);
6774                                 spin_unlock(&fp->f_lock);
6775
6776                                 smb2_send_interim_resp(work, STATUS_PENDING);
6777
6778                                 err = ksmbd_vfs_posix_lock_wait(flock);
6779
6780                                 if (work->state != KSMBD_WORK_ACTIVE) {
6781                                         list_del(&smb_lock->llist);
6782                                         list_del(&smb_lock->glist);
6783                                         locks_free_lock(flock);
6784
6785                                         if (work->state == KSMBD_WORK_CANCELLED) {
6786                                                 spin_lock(&fp->f_lock);
6787                                                 list_del(&work->fp_entry);
6788                                                 spin_unlock(&fp->f_lock);
6789                                                 rsp->hdr.Status =
6790                                                         STATUS_CANCELLED;
6791                                                 kfree(smb_lock);
6792                                                 smb2_send_interim_resp(work,
6793                                                                        STATUS_CANCELLED);
6794                                                 work->send_no_response = 1;
6795                                                 goto out;
6796                                         }
6797                                         init_smb2_rsp_hdr(work);
6798                                         smb2_set_err_rsp(work);
6799                                         rsp->hdr.Status =
6800                                                 STATUS_RANGE_NOT_LOCKED;
6801                                         kfree(smb_lock);
6802                                         goto out2;
6803                                 }
6804
6805                                 list_del(&smb_lock->llist);
6806                                 list_del(&smb_lock->glist);
6807                                 spin_lock(&fp->f_lock);
6808                                 list_del(&work->fp_entry);
6809                                 spin_unlock(&fp->f_lock);
6810                                 goto retry;
6811                         } else if (!err) {
6812                                 list_add_tail(&smb_lock->glist,
6813                                               &global_lock_list);
6814                                 list_add(&smb_lock->llist, &rollback_list);
6815                                 ksmbd_debug(SMB, "successful in taking lock\n");
6816                         } else {
6817                                 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
6818                                 goto out;
6819                         }
6820                 }
6821         }
6822
6823         if (atomic_read(&fp->f_ci->op_count) > 1)
6824                 smb_break_all_oplock(work, fp);
6825
6826         rsp->StructureSize = cpu_to_le16(4);
6827         ksmbd_debug(SMB, "successful in taking lock\n");
6828         rsp->hdr.Status = STATUS_SUCCESS;
6829         rsp->Reserved = 0;
6830         inc_rfc1001_len(rsp, 4);
6831         ksmbd_fd_put(work, fp);
6832         return err;
6833
6834 out:
6835         list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6836                 locks_free_lock(smb_lock->fl);
6837                 list_del(&smb_lock->llist);
6838                 kfree(smb_lock);
6839         }
6840
6841         list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
6842                 struct file_lock *rlock = NULL;
6843
6844                 rlock = smb_flock_init(filp);
6845                 rlock->fl_type = F_UNLCK;
6846                 rlock->fl_start = smb_lock->start;
6847                 rlock->fl_end = smb_lock->end;
6848
6849                 err = vfs_lock_file(filp, 0, rlock, NULL);
6850                 if (err)
6851                         pr_err("rollback unlock fail : %d\n", err);
6852                 list_del(&smb_lock->llist);
6853                 list_del(&smb_lock->glist);
6854                 locks_free_lock(smb_lock->fl);
6855                 locks_free_lock(rlock);
6856                 kfree(smb_lock);
6857         }
6858 out2:
6859         ksmbd_debug(SMB, "failed in taking lock(flags : %x)\n", flags);
6860         smb2_set_err_rsp(work);
6861         ksmbd_fd_put(work, fp);
6862         return 0;
6863 }
6864
6865 static int fsctl_copychunk(struct ksmbd_work *work, struct smb2_ioctl_req *req,
6866                            struct smb2_ioctl_rsp *rsp)
6867 {
6868         struct copychunk_ioctl_req *ci_req;
6869         struct copychunk_ioctl_rsp *ci_rsp;
6870         struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
6871         struct srv_copychunk *chunks;
6872         unsigned int i, chunk_count, chunk_count_written = 0;
6873         unsigned int chunk_size_written = 0;
6874         loff_t total_size_written = 0;
6875         int ret, cnt_code;
6876
6877         cnt_code = le32_to_cpu(req->CntCode);
6878         ci_req = (struct copychunk_ioctl_req *)&req->Buffer[0];
6879         ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
6880
6881         rsp->VolatileFileId = req->VolatileFileId;
6882         rsp->PersistentFileId = req->PersistentFileId;
6883         ci_rsp->ChunksWritten =
6884                 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
6885         ci_rsp->ChunkBytesWritten =
6886                 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
6887         ci_rsp->TotalBytesWritten =
6888                 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
6889
6890         chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
6891         chunk_count = le32_to_cpu(ci_req->ChunkCount);
6892         total_size_written = 0;
6893
6894         /* verify the SRV_COPYCHUNK_COPY packet */
6895         if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
6896             le32_to_cpu(req->InputCount) <
6897              offsetof(struct copychunk_ioctl_req, Chunks) +
6898              chunk_count * sizeof(struct srv_copychunk)) {
6899                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6900                 return -EINVAL;
6901         }
6902
6903         for (i = 0; i < chunk_count; i++) {
6904                 if (le32_to_cpu(chunks[i].Length) == 0 ||
6905                     le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
6906                         break;
6907                 total_size_written += le32_to_cpu(chunks[i].Length);
6908         }
6909
6910         if (i < chunk_count ||
6911             total_size_written > ksmbd_server_side_copy_max_total_size()) {
6912                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6913                 return -EINVAL;
6914         }
6915
6916         src_fp = ksmbd_lookup_foreign_fd(work,
6917                                          le64_to_cpu(ci_req->ResumeKey[0]));
6918         dst_fp = ksmbd_lookup_fd_slow(work,
6919                                       le64_to_cpu(req->VolatileFileId),
6920                                       le64_to_cpu(req->PersistentFileId));
6921         ret = -EINVAL;
6922         if (!src_fp ||
6923             src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
6924                 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
6925                 goto out;
6926         }
6927
6928         if (!dst_fp) {
6929                 rsp->hdr.Status = STATUS_FILE_CLOSED;
6930                 goto out;
6931         }
6932
6933         /*
6934          * FILE_READ_DATA should only be included in
6935          * the FSCTL_COPYCHUNK case
6936          */
6937         if (cnt_code == FSCTL_COPYCHUNK &&
6938             !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
6939                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6940                 goto out;
6941         }
6942
6943         ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
6944                                          chunks, chunk_count,
6945                                          &chunk_count_written,
6946                                          &chunk_size_written,
6947                                          &total_size_written);
6948         if (ret < 0) {
6949                 if (ret == -EACCES)
6950                         rsp->hdr.Status = STATUS_ACCESS_DENIED;
6951                 if (ret == -EAGAIN)
6952                         rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6953                 else if (ret == -EBADF)
6954                         rsp->hdr.Status = STATUS_INVALID_HANDLE;
6955                 else if (ret == -EFBIG || ret == -ENOSPC)
6956                         rsp->hdr.Status = STATUS_DISK_FULL;
6957                 else if (ret == -EINVAL)
6958                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6959                 else if (ret == -EISDIR)
6960                         rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
6961                 else if (ret == -E2BIG)
6962                         rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
6963                 else
6964                         rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6965         }
6966
6967         ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
6968         ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
6969         ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
6970 out:
6971         ksmbd_fd_put(work, src_fp);
6972         ksmbd_fd_put(work, dst_fp);
6973         return ret;
6974 }
6975
6976 static __be32 idev_ipv4_address(struct in_device *idev)
6977 {
6978         __be32 addr = 0;
6979
6980         struct in_ifaddr *ifa;
6981
6982         rcu_read_lock();
6983         in_dev_for_each_ifa_rcu(ifa, idev) {
6984                 if (ifa->ifa_flags & IFA_F_SECONDARY)
6985                         continue;
6986
6987                 addr = ifa->ifa_address;
6988                 break;
6989         }
6990         rcu_read_unlock();
6991         return addr;
6992 }
6993
6994 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
6995                                         struct smb2_ioctl_req *req,
6996                                         struct smb2_ioctl_rsp *rsp)
6997 {
6998         struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
6999         int nbytes = 0;
7000         struct net_device *netdev;
7001         struct sockaddr_storage_rsp *sockaddr_storage;
7002         unsigned int flags;
7003         unsigned long long speed;
7004
7005         rtnl_lock();
7006         for_each_netdev(&init_net, netdev) {
7007                 if (unlikely(!netdev)) {
7008                         rtnl_unlock();
7009                         return -EINVAL;
7010                 }
7011
7012                 if (netdev->type == ARPHRD_LOOPBACK)
7013                         continue;
7014
7015                 flags = dev_get_flags(netdev);
7016                 if (!(flags & IFF_RUNNING))
7017                         continue;
7018
7019                 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7020                                 &rsp->Buffer[nbytes];
7021                 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7022
7023                 /* TODO: specify the RDMA capabilities */
7024                 if (netdev->num_tx_queues > 1)
7025                         nii_rsp->Capability = cpu_to_le32(RSS_CAPABLE);
7026                 else
7027                         nii_rsp->Capability = 0;
7028
7029                 nii_rsp->Next = cpu_to_le32(152);
7030                 nii_rsp->Reserved = 0;
7031
7032                 if (netdev->ethtool_ops->get_link_ksettings) {
7033                         struct ethtool_link_ksettings cmd;
7034
7035                         netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7036                         speed = cmd.base.speed;
7037                 } else {
7038                         pr_err("%s %s\n", netdev->name,
7039                                "speed is unknown, defaulting to 1Gb/sec");
7040                         speed = SPEED_1000;
7041                 }
7042
7043                 speed *= 1000000;
7044                 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7045
7046                 sockaddr_storage = (struct sockaddr_storage_rsp *)
7047                                         nii_rsp->SockAddr_Storage;
7048                 memset(sockaddr_storage, 0, 128);
7049
7050                 if (conn->peer_addr.ss_family == PF_INET) {
7051                         struct in_device *idev;
7052
7053                         sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7054                         sockaddr_storage->addr4.Port = 0;
7055
7056                         idev = __in_dev_get_rtnl(netdev);
7057                         if (!idev)
7058                                 continue;
7059                         sockaddr_storage->addr4.IPv4address =
7060                                                 idev_ipv4_address(idev);
7061                 } else {
7062                         struct inet6_dev *idev6;
7063                         struct inet6_ifaddr *ifa;
7064                         __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7065
7066                         sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7067                         sockaddr_storage->addr6.Port = 0;
7068                         sockaddr_storage->addr6.FlowInfo = 0;
7069
7070                         idev6 = __in6_dev_get(netdev);
7071                         if (!idev6)
7072                                 continue;
7073
7074                         list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7075                                 if (ifa->flags & (IFA_F_TENTATIVE |
7076                                                         IFA_F_DEPRECATED))
7077                                         continue;
7078                                 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7079                                 break;
7080                         }
7081                         sockaddr_storage->addr6.ScopeId = 0;
7082                 }
7083
7084                 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7085         }
7086         rtnl_unlock();
7087
7088         /* zero if this is last one */
7089         if (nii_rsp)
7090                 nii_rsp->Next = 0;
7091
7092         if (!nbytes) {
7093                 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7094                 return -EINVAL;
7095         }
7096
7097         rsp->PersistentFileId = cpu_to_le64(SMB2_NO_FID);
7098         rsp->VolatileFileId = cpu_to_le64(SMB2_NO_FID);
7099         return nbytes;
7100 }
7101
7102 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7103                                          struct validate_negotiate_info_req *neg_req,
7104                                          struct validate_negotiate_info_rsp *neg_rsp)
7105 {
7106         int ret = 0;
7107         int dialect;
7108
7109         dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7110                                              neg_req->DialectCount);
7111         if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7112                 ret = -EINVAL;
7113                 goto err_out;
7114         }
7115
7116         if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7117                 ret = -EINVAL;
7118                 goto err_out;
7119         }
7120
7121         if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7122                 ret = -EINVAL;
7123                 goto err_out;
7124         }
7125
7126         if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7127                 ret = -EINVAL;
7128                 goto err_out;
7129         }
7130
7131         neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7132         memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7133         neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7134         neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7135 err_out:
7136         return ret;
7137 }
7138
7139 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7140                                         struct file_allocated_range_buffer *qar_req,
7141                                         struct file_allocated_range_buffer *qar_rsp,
7142                                         int in_count, int *out_count)
7143 {
7144         struct ksmbd_file *fp;
7145         loff_t start, length;
7146         int ret = 0;
7147
7148         *out_count = 0;
7149         if (in_count == 0)
7150                 return -EINVAL;
7151
7152         fp = ksmbd_lookup_fd_fast(work, id);
7153         if (!fp)
7154                 return -ENOENT;
7155
7156         start = le64_to_cpu(qar_req->file_offset);
7157         length = le64_to_cpu(qar_req->length);
7158
7159         ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7160                                    qar_rsp, in_count, out_count);
7161         if (ret && ret != -E2BIG)
7162                 *out_count = 0;
7163
7164         ksmbd_fd_put(work, fp);
7165         return ret;
7166 }
7167
7168 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7169                                  int out_buf_len, struct smb2_ioctl_req *req,
7170                                  struct smb2_ioctl_rsp *rsp)
7171 {
7172         struct ksmbd_rpc_command *rpc_resp;
7173         char *data_buf = (char *)&req->Buffer[0];
7174         int nbytes = 0;
7175
7176         rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7177                                    le32_to_cpu(req->InputCount));
7178         if (rpc_resp) {
7179                 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7180                         /*
7181                          * set STATUS_SOME_NOT_MAPPED response
7182                          * for unknown domain sid.
7183                          */
7184                         rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7185                 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7186                         rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7187                         goto out;
7188                 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7189                         rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7190                         goto out;
7191                 }
7192
7193                 nbytes = rpc_resp->payload_sz;
7194                 if (rpc_resp->payload_sz > out_buf_len) {
7195                         rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7196                         nbytes = out_buf_len;
7197                 }
7198
7199                 if (!rpc_resp->payload_sz) {
7200                         rsp->hdr.Status =
7201                                 STATUS_UNEXPECTED_IO_ERROR;
7202                         goto out;
7203                 }
7204
7205                 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7206         }
7207 out:
7208         kvfree(rpc_resp);
7209         return nbytes;
7210 }
7211
7212 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7213                                    struct file_sparse *sparse)
7214 {
7215         struct ksmbd_file *fp;
7216         struct user_namespace *user_ns;
7217         int ret = 0;
7218         __le32 old_fattr;
7219
7220         fp = ksmbd_lookup_fd_fast(work, id);
7221         if (!fp)
7222                 return -ENOENT;
7223         user_ns = file_mnt_user_ns(fp->filp);
7224
7225         old_fattr = fp->f_ci->m_fattr;
7226         if (sparse->SetSparse)
7227                 fp->f_ci->m_fattr |= ATTR_SPARSE_FILE_LE;
7228         else
7229                 fp->f_ci->m_fattr &= ~ATTR_SPARSE_FILE_LE;
7230
7231         if (fp->f_ci->m_fattr != old_fattr &&
7232             test_share_config_flag(work->tcon->share_conf,
7233                                    KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7234                 struct xattr_dos_attrib da;
7235
7236                 ret = ksmbd_vfs_get_dos_attrib_xattr(user_ns,
7237                                                      fp->filp->f_path.dentry, &da);
7238                 if (ret <= 0)
7239                         goto out;
7240
7241                 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7242                 ret = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
7243                                                      fp->filp->f_path.dentry, &da);
7244                 if (ret)
7245                         fp->f_ci->m_fattr = old_fattr;
7246         }
7247
7248 out:
7249         ksmbd_fd_put(work, fp);
7250         return ret;
7251 }
7252
7253 static int fsctl_request_resume_key(struct ksmbd_work *work,
7254                                     struct smb2_ioctl_req *req,
7255                                     struct resume_key_ioctl_rsp *key_rsp)
7256 {
7257         struct ksmbd_file *fp;
7258
7259         fp = ksmbd_lookup_fd_slow(work,
7260                                   le64_to_cpu(req->VolatileFileId),
7261                                   le64_to_cpu(req->PersistentFileId));
7262         if (!fp)
7263                 return -ENOENT;
7264
7265         memset(key_rsp, 0, sizeof(*key_rsp));
7266         key_rsp->ResumeKey[0] = req->VolatileFileId;
7267         key_rsp->ResumeKey[1] = req->PersistentFileId;
7268         ksmbd_fd_put(work, fp);
7269
7270         return 0;
7271 }
7272
7273 /**
7274  * smb2_ioctl() - handler for smb2 ioctl command
7275  * @work:       smb work containing ioctl command buffer
7276  *
7277  * Return:      0 on success, otherwise error
7278  */
7279 int smb2_ioctl(struct ksmbd_work *work)
7280 {
7281         struct smb2_ioctl_req *req;
7282         struct smb2_ioctl_rsp *rsp, *rsp_org;
7283         int cnt_code, nbytes = 0;
7284         int out_buf_len;
7285         u64 id = KSMBD_NO_FID;
7286         struct ksmbd_conn *conn = work->conn;
7287         int ret = 0;
7288
7289         rsp_org = work->response_buf;
7290         if (work->next_smb2_rcv_hdr_off) {
7291                 req = ksmbd_req_buf_next(work);
7292                 rsp = ksmbd_resp_buf_next(work);
7293                 if (!HAS_FILE_ID(le64_to_cpu(req->VolatileFileId))) {
7294                         ksmbd_debug(SMB, "Compound request set FID = %u\n",
7295                                     work->compound_fid);
7296                         id = work->compound_fid;
7297                 }
7298         } else {
7299                 req = work->request_buf;
7300                 rsp = work->response_buf;
7301         }
7302
7303         if (!HAS_FILE_ID(id))
7304                 id = le64_to_cpu(req->VolatileFileId);
7305
7306         if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7307                 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7308                 goto out;
7309         }
7310
7311         cnt_code = le32_to_cpu(req->CntCode);
7312         out_buf_len = le32_to_cpu(req->MaxOutputResponse);
7313         out_buf_len = min(KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7314
7315         switch (cnt_code) {
7316         case FSCTL_DFS_GET_REFERRALS:
7317         case FSCTL_DFS_GET_REFERRALS_EX:
7318                 /* Not support DFS yet */
7319                 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7320                 goto out;
7321         case FSCTL_CREATE_OR_GET_OBJECT_ID:
7322         {
7323                 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7324
7325                 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7326                 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7327                         &rsp->Buffer[0];
7328
7329                 /*
7330                  * TODO: This is dummy implementation to pass smbtorture
7331                  * Need to check correct response later
7332                  */
7333                 memset(obj_buf->ObjectId, 0x0, 16);
7334                 memset(obj_buf->BirthVolumeId, 0x0, 16);
7335                 memset(obj_buf->BirthObjectId, 0x0, 16);
7336                 memset(obj_buf->DomainId, 0x0, 16);
7337
7338                 break;
7339         }
7340         case FSCTL_PIPE_TRANSCEIVE:
7341                 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7342                 break;
7343         case FSCTL_VALIDATE_NEGOTIATE_INFO:
7344                 if (conn->dialect < SMB30_PROT_ID) {
7345                         ret = -EOPNOTSUPP;
7346                         goto out;
7347                 }
7348
7349                 ret = fsctl_validate_negotiate_info(conn,
7350                         (struct validate_negotiate_info_req *)&req->Buffer[0],
7351                         (struct validate_negotiate_info_rsp *)&rsp->Buffer[0]);
7352                 if (ret < 0)
7353                         goto out;
7354
7355                 nbytes = sizeof(struct validate_negotiate_info_rsp);
7356                 rsp->PersistentFileId = cpu_to_le64(SMB2_NO_FID);
7357                 rsp->VolatileFileId = cpu_to_le64(SMB2_NO_FID);
7358                 break;
7359         case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7360                 nbytes = fsctl_query_iface_info_ioctl(conn, req, rsp);
7361                 if (nbytes < 0)
7362                         goto out;
7363                 break;
7364         case FSCTL_REQUEST_RESUME_KEY:
7365                 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7366                         ret = -EINVAL;
7367                         goto out;
7368                 }
7369
7370                 ret = fsctl_request_resume_key(work, req,
7371                                                (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7372                 if (ret < 0)
7373                         goto out;
7374                 rsp->PersistentFileId = req->PersistentFileId;
7375                 rsp->VolatileFileId = req->VolatileFileId;
7376                 nbytes = sizeof(struct resume_key_ioctl_rsp);
7377                 break;
7378         case FSCTL_COPYCHUNK:
7379         case FSCTL_COPYCHUNK_WRITE:
7380                 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7381                         ksmbd_debug(SMB,
7382                                     "User does not have write permission\n");
7383                         ret = -EACCES;
7384                         goto out;
7385                 }
7386
7387                 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7388                         ret = -EINVAL;
7389                         goto out;
7390                 }
7391
7392                 nbytes = sizeof(struct copychunk_ioctl_rsp);
7393                 fsctl_copychunk(work, req, rsp);
7394                 break;
7395         case FSCTL_SET_SPARSE:
7396                 ret = fsctl_set_sparse(work, id,
7397                                        (struct file_sparse *)&req->Buffer[0]);
7398                 if (ret < 0)
7399                         goto out;
7400                 break;
7401         case FSCTL_SET_ZERO_DATA:
7402         {
7403                 struct file_zero_data_information *zero_data;
7404                 struct ksmbd_file *fp;
7405                 loff_t off, len;
7406
7407                 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7408                         ksmbd_debug(SMB,
7409                                     "User does not have write permission\n");
7410                         ret = -EACCES;
7411                         goto out;
7412                 }
7413
7414                 zero_data =
7415                         (struct file_zero_data_information *)&req->Buffer[0];
7416
7417                 fp = ksmbd_lookup_fd_fast(work, id);
7418                 if (!fp) {
7419                         ret = -ENOENT;
7420                         goto out;
7421                 }
7422
7423                 off = le64_to_cpu(zero_data->FileOffset);
7424                 len = le64_to_cpu(zero_data->BeyondFinalZero) - off;
7425
7426                 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7427                 ksmbd_fd_put(work, fp);
7428                 if (ret < 0)
7429                         goto out;
7430                 break;
7431         }
7432         case FSCTL_QUERY_ALLOCATED_RANGES:
7433                 ret = fsctl_query_allocated_ranges(work, id,
7434                         (struct file_allocated_range_buffer *)&req->Buffer[0],
7435                         (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7436                         out_buf_len /
7437                         sizeof(struct file_allocated_range_buffer), &nbytes);
7438                 if (ret == -E2BIG) {
7439                         rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7440                 } else if (ret < 0) {
7441                         nbytes = 0;
7442                         goto out;
7443                 }
7444
7445                 nbytes *= sizeof(struct file_allocated_range_buffer);
7446                 break;
7447         case FSCTL_GET_REPARSE_POINT:
7448         {
7449                 struct reparse_data_buffer *reparse_ptr;
7450                 struct ksmbd_file *fp;
7451
7452                 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7453                 fp = ksmbd_lookup_fd_fast(work, id);
7454                 if (!fp) {
7455                         pr_err("not found fp!!\n");
7456                         ret = -ENOENT;
7457                         goto out;
7458                 }
7459
7460                 reparse_ptr->ReparseTag =
7461                         smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7462                 reparse_ptr->ReparseDataLength = 0;
7463                 ksmbd_fd_put(work, fp);
7464                 nbytes = sizeof(struct reparse_data_buffer);
7465                 break;
7466         }
7467         case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7468         {
7469                 struct ksmbd_file *fp_in, *fp_out = NULL;
7470                 struct duplicate_extents_to_file *dup_ext;
7471                 loff_t src_off, dst_off, length, cloned;
7472
7473                 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7474
7475                 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7476                                              dup_ext->PersistentFileHandle);
7477                 if (!fp_in) {
7478                         pr_err("not found file handle in duplicate extent to file\n");
7479                         ret = -ENOENT;
7480                         goto out;
7481                 }
7482
7483                 fp_out = ksmbd_lookup_fd_fast(work, id);
7484                 if (!fp_out) {
7485                         pr_err("not found fp\n");
7486                         ret = -ENOENT;
7487                         goto dup_ext_out;
7488                 }
7489
7490                 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7491                 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7492                 length = le64_to_cpu(dup_ext->ByteCount);
7493                 cloned = vfs_clone_file_range(fp_in->filp, src_off, fp_out->filp,
7494                                               dst_off, length, 0);
7495                 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7496                         ret = -EOPNOTSUPP;
7497                         goto dup_ext_out;
7498                 } else if (cloned != length) {
7499                         cloned = vfs_copy_file_range(fp_in->filp, src_off,
7500                                                      fp_out->filp, dst_off, length, 0);
7501                         if (cloned != length) {
7502                                 if (cloned < 0)
7503                                         ret = cloned;
7504                                 else
7505                                         ret = -EINVAL;
7506                         }
7507                 }
7508
7509 dup_ext_out:
7510                 ksmbd_fd_put(work, fp_in);
7511                 ksmbd_fd_put(work, fp_out);
7512                 if (ret < 0)
7513                         goto out;
7514                 break;
7515         }
7516         default:
7517                 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7518                             cnt_code);
7519                 ret = -EOPNOTSUPP;
7520                 goto out;
7521         }
7522
7523         rsp->CntCode = cpu_to_le32(cnt_code);
7524         rsp->InputCount = cpu_to_le32(0);
7525         rsp->InputOffset = cpu_to_le32(112);
7526         rsp->OutputOffset = cpu_to_le32(112);
7527         rsp->OutputCount = cpu_to_le32(nbytes);
7528         rsp->StructureSize = cpu_to_le16(49);
7529         rsp->Reserved = cpu_to_le16(0);
7530         rsp->Flags = cpu_to_le32(0);
7531         rsp->Reserved2 = cpu_to_le32(0);
7532         inc_rfc1001_len(rsp_org, 48 + nbytes);
7533
7534         return 0;
7535
7536 out:
7537         if (ret == -EACCES)
7538                 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7539         else if (ret == -ENOENT)
7540                 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7541         else if (ret == -EOPNOTSUPP)
7542                 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7543         else if (ret < 0 || rsp->hdr.Status == 0)
7544                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7545         smb2_set_err_rsp(work);
7546         return 0;
7547 }
7548
7549 /**
7550  * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7551  * @work:       smb work containing oplock break command buffer
7552  *
7553  * Return:      0
7554  */
7555 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7556 {
7557         struct smb2_oplock_break *req = work->request_buf;
7558         struct smb2_oplock_break *rsp = work->response_buf;
7559         struct ksmbd_file *fp;
7560         struct oplock_info *opinfo = NULL;
7561         __le32 err = 0;
7562         int ret = 0;
7563         u64 volatile_id, persistent_id;
7564         char req_oplevel = 0, rsp_oplevel = 0;
7565         unsigned int oplock_change_type;
7566
7567         volatile_id = le64_to_cpu(req->VolatileFid);
7568         persistent_id = le64_to_cpu(req->PersistentFid);
7569         req_oplevel = req->OplockLevel;
7570         ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7571                     volatile_id, persistent_id, req_oplevel);
7572
7573         fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7574         if (!fp) {
7575                 rsp->hdr.Status = STATUS_FILE_CLOSED;
7576                 smb2_set_err_rsp(work);
7577                 return;
7578         }
7579
7580         opinfo = opinfo_get(fp);
7581         if (!opinfo) {
7582                 pr_err("unexpected null oplock_info\n");
7583                 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7584                 smb2_set_err_rsp(work);
7585                 ksmbd_fd_put(work, fp);
7586                 return;
7587         }
7588
7589         if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
7590                 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7591                 goto err_out;
7592         }
7593
7594         if (opinfo->op_state == OPLOCK_STATE_NONE) {
7595                 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
7596                 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7597                 goto err_out;
7598         }
7599
7600         if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7601              opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7602             (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
7603              req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
7604                 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7605                 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7606         } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7607                    req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
7608                 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7609                 oplock_change_type = OPLOCK_READ_TO_NONE;
7610         } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
7611                    req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7612                 err = STATUS_INVALID_DEVICE_STATE;
7613                 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7614                      opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7615                     req_oplevel == SMB2_OPLOCK_LEVEL_II) {
7616                         oplock_change_type = OPLOCK_WRITE_TO_READ;
7617                 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7618                             opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7619                            req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7620                         oplock_change_type = OPLOCK_WRITE_TO_NONE;
7621                 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7622                            req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7623                         oplock_change_type = OPLOCK_READ_TO_NONE;
7624                 } else {
7625                         oplock_change_type = 0;
7626                 }
7627         } else {
7628                 oplock_change_type = 0;
7629         }
7630
7631         switch (oplock_change_type) {
7632         case OPLOCK_WRITE_TO_READ:
7633                 ret = opinfo_write_to_read(opinfo);
7634                 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
7635                 break;
7636         case OPLOCK_WRITE_TO_NONE:
7637                 ret = opinfo_write_to_none(opinfo);
7638                 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7639                 break;
7640         case OPLOCK_READ_TO_NONE:
7641                 ret = opinfo_read_to_none(opinfo);
7642                 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7643                 break;
7644         default:
7645                 pr_err("unknown oplock change 0x%x -> 0x%x\n",
7646                        opinfo->level, rsp_oplevel);
7647         }
7648
7649         if (ret < 0) {
7650                 rsp->hdr.Status = err;
7651                 goto err_out;
7652         }
7653
7654         opinfo_put(opinfo);
7655         ksmbd_fd_put(work, fp);
7656         opinfo->op_state = OPLOCK_STATE_NONE;
7657         wake_up_interruptible_all(&opinfo->oplock_q);
7658
7659         rsp->StructureSize = cpu_to_le16(24);
7660         rsp->OplockLevel = rsp_oplevel;
7661         rsp->Reserved = 0;
7662         rsp->Reserved2 = 0;
7663         rsp->VolatileFid = cpu_to_le64(volatile_id);
7664         rsp->PersistentFid = cpu_to_le64(persistent_id);
7665         inc_rfc1001_len(rsp, 24);
7666         return;
7667
7668 err_out:
7669         opinfo->op_state = OPLOCK_STATE_NONE;
7670         wake_up_interruptible_all(&opinfo->oplock_q);
7671
7672         opinfo_put(opinfo);
7673         ksmbd_fd_put(work, fp);
7674         smb2_set_err_rsp(work);
7675 }
7676
7677 static int check_lease_state(struct lease *lease, __le32 req_state)
7678 {
7679         if ((lease->new_state ==
7680              (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
7681             !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
7682                 lease->new_state = req_state;
7683                 return 0;
7684         }
7685
7686         if (lease->new_state == req_state)
7687                 return 0;
7688
7689         return 1;
7690 }
7691
7692 /**
7693  * smb21_lease_break_ack() - handler for smb2.1 lease break command
7694  * @work:       smb work containing lease break command buffer
7695  *
7696  * Return:      0
7697  */
7698 static void smb21_lease_break_ack(struct ksmbd_work *work)
7699 {
7700         struct ksmbd_conn *conn = work->conn;
7701         struct smb2_lease_ack *req = work->request_buf;
7702         struct smb2_lease_ack *rsp = work->response_buf;
7703         struct oplock_info *opinfo;
7704         __le32 err = 0;
7705         int ret = 0;
7706         unsigned int lease_change_type;
7707         __le32 lease_state;
7708         struct lease *lease;
7709
7710         ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
7711                     le32_to_cpu(req->LeaseState));
7712         opinfo = lookup_lease_in_table(conn, req->LeaseKey);
7713         if (!opinfo) {
7714                 ksmbd_debug(OPLOCK, "file not opened\n");
7715                 smb2_set_err_rsp(work);
7716                 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7717                 return;
7718         }
7719         lease = opinfo->o_lease;
7720
7721         if (opinfo->op_state == OPLOCK_STATE_NONE) {
7722                 pr_err("unexpected lease break state 0x%x\n",
7723                        opinfo->op_state);
7724                 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7725                 goto err_out;
7726         }
7727
7728         if (check_lease_state(lease, req->LeaseState)) {
7729                 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
7730                 ksmbd_debug(OPLOCK,
7731                             "req lease state: 0x%x, expected state: 0x%x\n",
7732                             req->LeaseState, lease->new_state);
7733                 goto err_out;
7734         }
7735
7736         if (!atomic_read(&opinfo->breaking_cnt)) {
7737                 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7738                 goto err_out;
7739         }
7740
7741         /* check for bad lease state */
7742         if (req->LeaseState &
7743             (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
7744                 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7745                 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
7746                         lease_change_type = OPLOCK_WRITE_TO_NONE;
7747                 else
7748                         lease_change_type = OPLOCK_READ_TO_NONE;
7749                 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
7750                             le32_to_cpu(lease->state),
7751                             le32_to_cpu(req->LeaseState));
7752         } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
7753                    req->LeaseState != SMB2_LEASE_NONE_LE) {
7754                 err = STATUS_INVALID_OPLOCK_PROTOCOL;
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 {
7760                 /* valid lease state changes */
7761                 err = STATUS_INVALID_DEVICE_STATE;
7762                 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
7763                         if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
7764                                 lease_change_type = OPLOCK_WRITE_TO_NONE;
7765                         else
7766                                 lease_change_type = OPLOCK_READ_TO_NONE;
7767                 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
7768                         if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
7769                                 lease_change_type = OPLOCK_WRITE_TO_READ;
7770                         else
7771                                 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
7772                 } else {
7773                         lease_change_type = 0;
7774                 }
7775         }
7776
7777         switch (lease_change_type) {
7778         case OPLOCK_WRITE_TO_READ:
7779                 ret = opinfo_write_to_read(opinfo);
7780                 break;
7781         case OPLOCK_READ_HANDLE_TO_READ:
7782                 ret = opinfo_read_handle_to_read(opinfo);
7783                 break;
7784         case OPLOCK_WRITE_TO_NONE:
7785                 ret = opinfo_write_to_none(opinfo);
7786                 break;
7787         case OPLOCK_READ_TO_NONE:
7788                 ret = opinfo_read_to_none(opinfo);
7789                 break;
7790         default:
7791                 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
7792                             le32_to_cpu(lease->state),
7793                             le32_to_cpu(req->LeaseState));
7794         }
7795
7796         lease_state = lease->state;
7797         opinfo->op_state = OPLOCK_STATE_NONE;
7798         wake_up_interruptible_all(&opinfo->oplock_q);
7799         atomic_dec(&opinfo->breaking_cnt);
7800         wake_up_interruptible_all(&opinfo->oplock_brk);
7801         opinfo_put(opinfo);
7802
7803         if (ret < 0) {
7804                 rsp->hdr.Status = err;
7805                 goto err_out;
7806         }
7807
7808         rsp->StructureSize = cpu_to_le16(36);
7809         rsp->Reserved = 0;
7810         rsp->Flags = 0;
7811         memcpy(rsp->LeaseKey, req->LeaseKey, 16);
7812         rsp->LeaseState = lease_state;
7813         rsp->LeaseDuration = 0;
7814         inc_rfc1001_len(rsp, 36);
7815         return;
7816
7817 err_out:
7818         opinfo->op_state = OPLOCK_STATE_NONE;
7819         wake_up_interruptible_all(&opinfo->oplock_q);
7820         atomic_dec(&opinfo->breaking_cnt);
7821         wake_up_interruptible_all(&opinfo->oplock_brk);
7822
7823         opinfo_put(opinfo);
7824         smb2_set_err_rsp(work);
7825 }
7826
7827 /**
7828  * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
7829  * @work:       smb work containing oplock/lease break command buffer
7830  *
7831  * Return:      0
7832  */
7833 int smb2_oplock_break(struct ksmbd_work *work)
7834 {
7835         struct smb2_oplock_break *req = work->request_buf;
7836         struct smb2_oplock_break *rsp = work->response_buf;
7837
7838         switch (le16_to_cpu(req->StructureSize)) {
7839         case OP_BREAK_STRUCT_SIZE_20:
7840                 smb20_oplock_break_ack(work);
7841                 break;
7842         case OP_BREAK_STRUCT_SIZE_21:
7843                 smb21_lease_break_ack(work);
7844                 break;
7845         default:
7846                 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
7847                             le16_to_cpu(req->StructureSize));
7848                 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7849                 smb2_set_err_rsp(work);
7850         }
7851
7852         return 0;
7853 }
7854
7855 /**
7856  * smb2_notify() - handler for smb2 notify request
7857  * @work:   smb work containing notify command buffer
7858  *
7859  * Return:      0
7860  */
7861 int smb2_notify(struct ksmbd_work *work)
7862 {
7863         struct smb2_notify_req *req;
7864         struct smb2_notify_rsp *rsp;
7865
7866         WORK_BUFFERS(work, req, rsp);
7867
7868         if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
7869                 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
7870                 smb2_set_err_rsp(work);
7871                 return 0;
7872         }
7873
7874         smb2_set_err_rsp(work);
7875         rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
7876         return 0;
7877 }
7878
7879 /**
7880  * smb2_is_sign_req() - handler for checking packet signing status
7881  * @work:       smb work containing notify command buffer
7882  * @command:    SMB2 command id
7883  *
7884  * Return:      true if packed is signed, false otherwise
7885  */
7886 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
7887 {
7888         struct smb2_hdr *rcv_hdr2 = work->request_buf;
7889
7890         if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
7891             command != SMB2_NEGOTIATE_HE &&
7892             command != SMB2_SESSION_SETUP_HE &&
7893             command != SMB2_OPLOCK_BREAK_HE)
7894                 return true;
7895
7896         return false;
7897 }
7898
7899 /**
7900  * smb2_check_sign_req() - handler for req packet sign processing
7901  * @work:   smb work containing notify command buffer
7902  *
7903  * Return:      1 on success, 0 otherwise
7904  */
7905 int smb2_check_sign_req(struct ksmbd_work *work)
7906 {
7907         struct smb2_hdr *hdr, *hdr_org;
7908         char signature_req[SMB2_SIGNATURE_SIZE];
7909         char signature[SMB2_HMACSHA256_SIZE];
7910         struct kvec iov[1];
7911         size_t len;
7912
7913         hdr_org = hdr = work->request_buf;
7914         if (work->next_smb2_rcv_hdr_off)
7915                 hdr = ksmbd_req_buf_next(work);
7916
7917         if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
7918                 len = be32_to_cpu(hdr_org->smb2_buf_length);
7919         else if (hdr->NextCommand)
7920                 len = le32_to_cpu(hdr->NextCommand);
7921         else
7922                 len = be32_to_cpu(hdr_org->smb2_buf_length) -
7923                         work->next_smb2_rcv_hdr_off;
7924
7925         memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
7926         memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
7927
7928         iov[0].iov_base = (char *)&hdr->ProtocolId;
7929         iov[0].iov_len = len;
7930
7931         if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
7932                                 signature))
7933                 return 0;
7934
7935         if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
7936                 pr_err("bad smb2 signature\n");
7937                 return 0;
7938         }
7939
7940         return 1;
7941 }
7942
7943 /**
7944  * smb2_set_sign_rsp() - handler for rsp packet sign processing
7945  * @work:   smb work containing notify command buffer
7946  *
7947  */
7948 void smb2_set_sign_rsp(struct ksmbd_work *work)
7949 {
7950         struct smb2_hdr *hdr, *hdr_org;
7951         struct smb2_hdr *req_hdr;
7952         char signature[SMB2_HMACSHA256_SIZE];
7953         struct kvec iov[2];
7954         size_t len;
7955         int n_vec = 1;
7956
7957         hdr_org = hdr = work->response_buf;
7958         if (work->next_smb2_rsp_hdr_off)
7959                 hdr = ksmbd_resp_buf_next(work);
7960
7961         req_hdr = ksmbd_req_buf_next(work);
7962
7963         if (!work->next_smb2_rsp_hdr_off) {
7964                 len = get_rfc1002_len(hdr_org);
7965                 if (req_hdr->NextCommand)
7966                         len = ALIGN(len, 8);
7967         } else {
7968                 len = get_rfc1002_len(hdr_org) - work->next_smb2_rsp_hdr_off;
7969                 len = ALIGN(len, 8);
7970         }
7971
7972         if (req_hdr->NextCommand)
7973                 hdr->NextCommand = cpu_to_le32(len);
7974
7975         hdr->Flags |= SMB2_FLAGS_SIGNED;
7976         memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
7977
7978         iov[0].iov_base = (char *)&hdr->ProtocolId;
7979         iov[0].iov_len = len;
7980
7981         if (work->aux_payload_sz) {
7982                 iov[0].iov_len -= work->aux_payload_sz;
7983
7984                 iov[1].iov_base = work->aux_payload_buf;
7985                 iov[1].iov_len = work->aux_payload_sz;
7986                 n_vec++;
7987         }
7988
7989         if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
7990                                  signature))
7991                 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
7992 }
7993
7994 /**
7995  * smb3_check_sign_req() - handler for req packet sign processing
7996  * @work:   smb work containing notify command buffer
7997  *
7998  * Return:      1 on success, 0 otherwise
7999  */
8000 int smb3_check_sign_req(struct ksmbd_work *work)
8001 {
8002         struct ksmbd_conn *conn = work->conn;
8003         char *signing_key;
8004         struct smb2_hdr *hdr, *hdr_org;
8005         struct channel *chann;
8006         char signature_req[SMB2_SIGNATURE_SIZE];
8007         char signature[SMB2_CMACAES_SIZE];
8008         struct kvec iov[1];
8009         size_t len;
8010
8011         hdr_org = hdr = work->request_buf;
8012         if (work->next_smb2_rcv_hdr_off)
8013                 hdr = ksmbd_req_buf_next(work);
8014
8015         if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8016                 len = be32_to_cpu(hdr_org->smb2_buf_length);
8017         else if (hdr->NextCommand)
8018                 len = le32_to_cpu(hdr->NextCommand);
8019         else
8020                 len = be32_to_cpu(hdr_org->smb2_buf_length) -
8021                         work->next_smb2_rcv_hdr_off;
8022
8023         if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8024                 signing_key = work->sess->smb3signingkey;
8025         } else {
8026                 chann = lookup_chann_list(work->sess, conn);
8027                 if (!chann)
8028                         return 0;
8029                 signing_key = chann->smb3signingkey;
8030         }
8031
8032         if (!signing_key) {
8033                 pr_err("SMB3 signing key is not generated\n");
8034                 return 0;
8035         }
8036
8037         memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8038         memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8039         iov[0].iov_base = (char *)&hdr->ProtocolId;
8040         iov[0].iov_len = len;
8041
8042         if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8043                 return 0;
8044
8045         if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8046                 pr_err("bad smb2 signature\n");
8047                 return 0;
8048         }
8049
8050         return 1;
8051 }
8052
8053 /**
8054  * smb3_set_sign_rsp() - handler for rsp packet sign processing
8055  * @work:   smb work containing notify command buffer
8056  *
8057  */
8058 void smb3_set_sign_rsp(struct ksmbd_work *work)
8059 {
8060         struct ksmbd_conn *conn = work->conn;
8061         struct smb2_hdr *req_hdr;
8062         struct smb2_hdr *hdr, *hdr_org;
8063         struct channel *chann;
8064         char signature[SMB2_CMACAES_SIZE];
8065         struct kvec iov[2];
8066         int n_vec = 1;
8067         size_t len;
8068         char *signing_key;
8069
8070         hdr_org = hdr = work->response_buf;
8071         if (work->next_smb2_rsp_hdr_off)
8072                 hdr = ksmbd_resp_buf_next(work);
8073
8074         req_hdr = ksmbd_req_buf_next(work);
8075
8076         if (!work->next_smb2_rsp_hdr_off) {
8077                 len = get_rfc1002_len(hdr_org);
8078                 if (req_hdr->NextCommand)
8079                         len = ALIGN(len, 8);
8080         } else {
8081                 len = get_rfc1002_len(hdr_org) - work->next_smb2_rsp_hdr_off;
8082                 len = ALIGN(len, 8);
8083         }
8084
8085         if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8086                 signing_key = work->sess->smb3signingkey;
8087         } else {
8088                 chann = lookup_chann_list(work->sess, work->conn);
8089                 if (!chann)
8090                         return;
8091                 signing_key = chann->smb3signingkey;
8092         }
8093
8094         if (!signing_key)
8095                 return;
8096
8097         if (req_hdr->NextCommand)
8098                 hdr->NextCommand = cpu_to_le32(len);
8099
8100         hdr->Flags |= SMB2_FLAGS_SIGNED;
8101         memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8102         iov[0].iov_base = (char *)&hdr->ProtocolId;
8103         iov[0].iov_len = len;
8104         if (work->aux_payload_sz) {
8105                 iov[0].iov_len -= work->aux_payload_sz;
8106                 iov[1].iov_base = work->aux_payload_buf;
8107                 iov[1].iov_len = work->aux_payload_sz;
8108                 n_vec++;
8109         }
8110
8111         if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
8112                 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8113 }
8114
8115 /**
8116  * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8117  * @work:   smb work containing response buffer
8118  *
8119  */
8120 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8121 {
8122         struct ksmbd_conn *conn = work->conn;
8123         struct ksmbd_session *sess = work->sess;
8124         struct smb2_hdr *req, *rsp;
8125
8126         if (conn->dialect != SMB311_PROT_ID)
8127                 return;
8128
8129         WORK_BUFFERS(work, req, rsp);
8130
8131         if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE)
8132                 ksmbd_gen_preauth_integrity_hash(conn, (char *)rsp,
8133                                                  conn->preauth_info->Preauth_HashValue);
8134
8135         if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8136                 __u8 *hash_value;
8137
8138                 if (conn->binding) {
8139                         struct preauth_session *preauth_sess;
8140
8141                         preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8142                         if (!preauth_sess)
8143                                 return;
8144                         hash_value = preauth_sess->Preauth_HashValue;
8145                 } else {
8146                         hash_value = sess->Preauth_HashValue;
8147                         if (!hash_value)
8148                                 return;
8149                 }
8150                 ksmbd_gen_preauth_integrity_hash(conn, (char *)rsp,
8151                                                  hash_value);
8152         }
8153 }
8154
8155 static void fill_transform_hdr(struct smb2_transform_hdr *tr_hdr, char *old_buf,
8156                                __le16 cipher_type)
8157 {
8158         struct smb2_hdr *hdr = (struct smb2_hdr *)old_buf;
8159         unsigned int orig_len = get_rfc1002_len(old_buf);
8160
8161         memset(tr_hdr, 0, sizeof(struct smb2_transform_hdr));
8162         tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8163         tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8164         tr_hdr->Flags = cpu_to_le16(0x01);
8165         if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8166             cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8167                 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8168         else
8169                 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8170         memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8171         inc_rfc1001_len(tr_hdr, sizeof(struct smb2_transform_hdr) - 4);
8172         inc_rfc1001_len(tr_hdr, orig_len);
8173 }
8174
8175 int smb3_encrypt_resp(struct ksmbd_work *work)
8176 {
8177         char *buf = work->response_buf;
8178         struct smb2_transform_hdr *tr_hdr;
8179         struct kvec iov[3];
8180         int rc = -ENOMEM;
8181         int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8182
8183         if (ARRAY_SIZE(iov) < rq_nvec)
8184                 return -ENOMEM;
8185
8186         tr_hdr = kzalloc(sizeof(struct smb2_transform_hdr), GFP_KERNEL);
8187         if (!tr_hdr)
8188                 return rc;
8189
8190         /* fill transform header */
8191         fill_transform_hdr(tr_hdr, buf, work->conn->cipher_type);
8192
8193         iov[0].iov_base = tr_hdr;
8194         iov[0].iov_len = sizeof(struct smb2_transform_hdr);
8195         buf_size += iov[0].iov_len - 4;
8196
8197         iov[1].iov_base = buf + 4;
8198         iov[1].iov_len = get_rfc1002_len(buf);
8199         if (work->aux_payload_sz) {
8200                 iov[1].iov_len = work->resp_hdr_sz - 4;
8201
8202                 iov[2].iov_base = work->aux_payload_buf;
8203                 iov[2].iov_len = work->aux_payload_sz;
8204                 buf_size += iov[2].iov_len;
8205         }
8206         buf_size += iov[1].iov_len;
8207         work->resp_hdr_sz = iov[1].iov_len;
8208
8209         rc = ksmbd_crypt_message(work->conn, iov, rq_nvec, 1);
8210         if (rc)
8211                 return rc;
8212
8213         memmove(buf, iov[1].iov_base, iov[1].iov_len);
8214         tr_hdr->smb2_buf_length = cpu_to_be32(buf_size);
8215         work->tr_buf = tr_hdr;
8216
8217         return rc;
8218 }
8219
8220 int smb3_is_transform_hdr(void *buf)
8221 {
8222         struct smb2_transform_hdr *trhdr = buf;
8223
8224         return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8225 }
8226
8227 int smb3_decrypt_req(struct ksmbd_work *work)
8228 {
8229         struct ksmbd_conn *conn = work->conn;
8230         struct ksmbd_session *sess;
8231         char *buf = work->request_buf;
8232         struct smb2_hdr *hdr;
8233         unsigned int pdu_length = get_rfc1002_len(buf);
8234         struct kvec iov[2];
8235         unsigned int buf_data_size = pdu_length + 4 -
8236                 sizeof(struct smb2_transform_hdr);
8237         struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
8238         unsigned int orig_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
8239         int rc = 0;
8240
8241         sess = ksmbd_session_lookup_all(conn, le64_to_cpu(tr_hdr->SessionId));
8242         if (!sess) {
8243                 pr_err("invalid session id(%llx) in transform header\n",
8244                        le64_to_cpu(tr_hdr->SessionId));
8245                 return -ECONNABORTED;
8246         }
8247
8248         if (pdu_length + 4 <
8249             sizeof(struct smb2_transform_hdr) + sizeof(struct smb2_hdr)) {
8250                 pr_err("Transform message is too small (%u)\n",
8251                        pdu_length);
8252                 return -ECONNABORTED;
8253         }
8254
8255         if (pdu_length + 4 < orig_len + sizeof(struct smb2_transform_hdr)) {
8256                 pr_err("Transform message is broken\n");
8257                 return -ECONNABORTED;
8258         }
8259
8260         iov[0].iov_base = buf;
8261         iov[0].iov_len = sizeof(struct smb2_transform_hdr);
8262         iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr);
8263         iov[1].iov_len = buf_data_size;
8264         rc = ksmbd_crypt_message(conn, iov, 2, 0);
8265         if (rc)
8266                 return rc;
8267
8268         memmove(buf + 4, iov[1].iov_base, buf_data_size);
8269         hdr = (struct smb2_hdr *)buf;
8270         hdr->smb2_buf_length = cpu_to_be32(buf_data_size);
8271
8272         return rc;
8273 }
8274
8275 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8276 {
8277         struct ksmbd_conn *conn = work->conn;
8278         struct smb2_hdr *rsp = work->response_buf;
8279
8280         if (conn->dialect < SMB30_PROT_ID)
8281                 return false;
8282
8283         if (work->next_smb2_rcv_hdr_off)
8284                 rsp = ksmbd_resp_buf_next(work);
8285
8286         if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8287             rsp->Status == STATUS_SUCCESS)
8288                 return true;
8289         return false;
8290 }