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