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