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