s3: smbd: Reformat users of can_write_to_file().
[samba.git] / source3 / smbd / nttrans.c
1 /*
2    Unix SMB/CIFS implementation.
3    SMB NT transaction handling
4    Copyright (C) Jeremy Allison                 1994-2007
5    Copyright (C) Stefan (metze) Metzmacher      2003
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "system/filesys.h"
23 #include "smbd/smbd.h"
24 #include "smbd/globals.h"
25 #include "fake_file.h"
26 #include "../libcli/security/security.h"
27 #include "../librpc/gen_ndr/ndr_security.h"
28 #include "passdb/lookup_sid.h"
29 #include "auth.h"
30 #include "smbprofile.h"
31 #include "libsmb/libsmb.h"
32 #include "lib/util_ea.h"
33 #include "librpc/gen_ndr/ndr_quota.h"
34 #include "librpc/gen_ndr/ndr_security.h"
35
36 extern const struct generic_mapping file_generic_mapping;
37
38 static char *nttrans_realloc(char **ptr, size_t size)
39 {
40         if (ptr==NULL) {
41                 smb_panic("nttrans_realloc() called with NULL ptr");
42         }
43
44         *ptr = (char *)SMB_REALLOC(*ptr, size);
45         if(*ptr == NULL) {
46                 return NULL;
47         }
48         memset(*ptr,'\0',size);
49         return *ptr;
50 }
51
52 /****************************************************************************
53  Send the required number of replies back.
54  We assume all fields other than the data fields are
55  set correctly for the type of call.
56  HACK ! Always assumes smb_setup field is zero.
57 ****************************************************************************/
58
59 static void send_nt_replies(connection_struct *conn,
60                             struct smb_request *req, NTSTATUS nt_error,
61                             char *params, int paramsize,
62                             char *pdata, int datasize)
63 {
64         int data_to_send = datasize;
65         int params_to_send = paramsize;
66         int useable_space;
67         char *pp = params;
68         char *pd = pdata;
69         int params_sent_thistime, data_sent_thistime, total_sent_thistime;
70         int alignment_offset = 1;
71         int data_alignment_offset = 0;
72         struct smbXsrv_connection *xconn = req->xconn;
73         int max_send = xconn->smb1.sessions.max_send;
74
75         /*
76          * If there genuinely are no parameters or data to send just send
77          * the empty packet.
78          */
79
80         if(params_to_send == 0 && data_to_send == 0) {
81                 reply_outbuf(req, 18, 0);
82                 if (NT_STATUS_V(nt_error)) {
83                         error_packet_set((char *)req->outbuf,
84                                          0, 0, nt_error,
85                                          __LINE__,__FILE__);
86                 }
87                 show_msg((char *)req->outbuf);
88                 if (!srv_send_smb(xconn,
89                                 (char *)req->outbuf,
90                                 true, req->seqnum+1,
91                                 IS_CONN_ENCRYPTED(conn),
92                                 &req->pcd)) {
93                         exit_server_cleanly("send_nt_replies: srv_send_smb failed.");
94                 }
95                 TALLOC_FREE(req->outbuf);
96                 return;
97         }
98
99         /*
100          * When sending params and data ensure that both are nicely aligned.
101          * Only do this alignment when there is also data to send - else
102          * can cause NT redirector problems.
103          */
104
105         if (((params_to_send % 4) != 0) && (data_to_send != 0)) {
106                 data_alignment_offset = 4 - (params_to_send % 4);
107         }
108
109         /*
110          * Space is bufsize minus Netbios over TCP header minus SMB header.
111          * The alignment_offset is to align the param bytes on a four byte
112          * boundary (2 bytes for data len, one byte pad).
113          * NT needs this to work correctly.
114          */
115
116         useable_space = max_send - (smb_size
117                                     + 2 * 18 /* wct */
118                                     + alignment_offset
119                                     + data_alignment_offset);
120
121         if (useable_space < 0) {
122                 char *msg = talloc_asprintf(
123                         talloc_tos(),
124                         "send_nt_replies failed sanity useable_space = %d!!!",
125                         useable_space);
126                 DEBUG(0, ("%s\n", msg));
127                 exit_server_cleanly(msg);
128         }
129
130         while (params_to_send || data_to_send) {
131
132                 /*
133                  * Calculate whether we will totally or partially fill this packet.
134                  */
135
136                 total_sent_thistime = params_to_send + data_to_send;
137
138                 /*
139                  * We can never send more than useable_space.
140                  */
141
142                 total_sent_thistime = MIN(total_sent_thistime, useable_space);
143
144                 reply_outbuf(req, 18,
145                              total_sent_thistime + alignment_offset
146                              + data_alignment_offset);
147
148                 /*
149                  * Set total params and data to be sent.
150                  */
151
152                 SIVAL(req->outbuf,smb_ntr_TotalParameterCount,paramsize);
153                 SIVAL(req->outbuf,smb_ntr_TotalDataCount,datasize);
154
155                 /*
156                  * Calculate how many parameters and data we can fit into
157                  * this packet. Parameters get precedence.
158                  */
159
160                 params_sent_thistime = MIN(params_to_send,useable_space);
161                 data_sent_thistime = useable_space - params_sent_thistime;
162                 data_sent_thistime = MIN(data_sent_thistime,data_to_send);
163
164                 SIVAL(req->outbuf, smb_ntr_ParameterCount,
165                       params_sent_thistime);
166
167                 if(params_sent_thistime == 0) {
168                         SIVAL(req->outbuf,smb_ntr_ParameterOffset,0);
169                         SIVAL(req->outbuf,smb_ntr_ParameterDisplacement,0);
170                 } else {
171                         /*
172                          * smb_ntr_ParameterOffset is the offset from the start of the SMB header to the
173                          * parameter bytes, however the first 4 bytes of outbuf are
174                          * the Netbios over TCP header. Thus use smb_base() to subtract
175                          * them from the calculation.
176                          */
177
178                         SIVAL(req->outbuf,smb_ntr_ParameterOffset,
179                               ((smb_buf(req->outbuf)+alignment_offset)
180                                - smb_base(req->outbuf)));
181                         /*
182                          * Absolute displacement of param bytes sent in this packet.
183                          */
184
185                         SIVAL(req->outbuf, smb_ntr_ParameterDisplacement,
186                               pp - params);
187                 }
188
189                 /*
190                  * Deal with the data portion.
191                  */
192
193                 SIVAL(req->outbuf, smb_ntr_DataCount, data_sent_thistime);
194
195                 if(data_sent_thistime == 0) {
196                         SIVAL(req->outbuf,smb_ntr_DataOffset,0);
197                         SIVAL(req->outbuf,smb_ntr_DataDisplacement, 0);
198                 } else {
199                         /*
200                          * The offset of the data bytes is the offset of the
201                          * parameter bytes plus the number of parameters being sent this time.
202                          */
203
204                         SIVAL(req->outbuf, smb_ntr_DataOffset,
205                               ((smb_buf(req->outbuf)+alignment_offset) -
206                                smb_base(req->outbuf))
207                               + params_sent_thistime + data_alignment_offset);
208                         SIVAL(req->outbuf,smb_ntr_DataDisplacement, pd - pdata);
209                 }
210
211                 /*
212                  * Copy the param bytes into the packet.
213                  */
214
215                 if(params_sent_thistime) {
216                         if (alignment_offset != 0) {
217                                 memset(smb_buf(req->outbuf), 0,
218                                        alignment_offset);
219                         }
220                         memcpy((smb_buf(req->outbuf)+alignment_offset), pp,
221                                params_sent_thistime);
222                 }
223
224                 /*
225                  * Copy in the data bytes
226                  */
227
228                 if(data_sent_thistime) {
229                         if (data_alignment_offset != 0) {
230                                 memset((smb_buf(req->outbuf)+alignment_offset+
231                                         params_sent_thistime), 0,
232                                        data_alignment_offset);
233                         }
234                         memcpy(smb_buf(req->outbuf)+alignment_offset
235                                +params_sent_thistime+data_alignment_offset,
236                                pd,data_sent_thistime);
237                 }
238
239                 DEBUG(9,("nt_rep: params_sent_thistime = %d, data_sent_thistime = %d, useable_space = %d\n",
240                         params_sent_thistime, data_sent_thistime, useable_space));
241                 DEBUG(9,("nt_rep: params_to_send = %d, data_to_send = %d, paramsize = %d, datasize = %d\n",
242                         params_to_send, data_to_send, paramsize, datasize));
243
244                 if (NT_STATUS_V(nt_error)) {
245                         error_packet_set((char *)req->outbuf,
246                                          0, 0, nt_error,
247                                          __LINE__,__FILE__);
248                 }
249
250                 /* Send the packet */
251                 show_msg((char *)req->outbuf);
252                 if (!srv_send_smb(xconn,
253                                 (char *)req->outbuf,
254                                 true, req->seqnum+1,
255                                 IS_CONN_ENCRYPTED(conn),
256                                 &req->pcd)) {
257                         exit_server_cleanly("send_nt_replies: srv_send_smb failed.");
258                 }
259
260                 TALLOC_FREE(req->outbuf);
261
262                 pp += params_sent_thistime;
263                 pd += data_sent_thistime;
264
265                 params_to_send -= params_sent_thistime;
266                 data_to_send -= data_sent_thistime;
267
268                 /*
269                  * Sanity check
270                  */
271
272                 if(params_to_send < 0 || data_to_send < 0) {
273                         DEBUG(0,("send_nt_replies failed sanity check pts = %d, dts = %d\n!!!",
274                                 params_to_send, data_to_send));
275                         exit_server_cleanly("send_nt_replies: internal error");
276                 }
277         }
278 }
279
280 /****************************************************************************
281  Reply to an NT create and X call on a pipe
282 ****************************************************************************/
283
284 static void nt_open_pipe(char *fname, connection_struct *conn,
285                          struct smb_request *req, uint16_t *ppnum)
286 {
287         files_struct *fsp;
288         NTSTATUS status;
289
290         DEBUG(4,("nt_open_pipe: Opening pipe %s.\n", fname));
291
292         /* Strip \\ off the name if present. */
293         while (fname[0] == '\\') {
294                 fname++;
295         }
296
297         status = open_np_file(req, fname, &fsp);
298         if (!NT_STATUS_IS_OK(status)) {
299                 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
300                         reply_botherror(req, NT_STATUS_OBJECT_NAME_NOT_FOUND,
301                                         ERRDOS, ERRbadpipe);
302                         return;
303                 }
304                 reply_nterror(req, status);
305                 return;
306         }
307
308         *ppnum = fsp->fnum;
309         return;
310 }
311
312 /****************************************************************************
313  Reply to an NT create and X call for pipes.
314 ****************************************************************************/
315
316 static void do_ntcreate_pipe_open(connection_struct *conn,
317                                   struct smb_request *req)
318 {
319         char *fname = NULL;
320         uint16_t pnum = FNUM_FIELD_INVALID;
321         char *p = NULL;
322         uint32_t flags = IVAL(req->vwv+3, 1);
323         TALLOC_CTX *ctx = talloc_tos();
324
325         srvstr_pull_req_talloc(ctx, req, &fname, req->buf, STR_TERMINATE);
326
327         if (!fname) {
328                 reply_botherror(req, NT_STATUS_OBJECT_NAME_NOT_FOUND,
329                                 ERRDOS, ERRbadpipe);
330                 return;
331         }
332         nt_open_pipe(fname, conn, req, &pnum);
333
334         if (req->outbuf) {
335                 /* error reply */
336                 return;
337         }
338
339         /*
340          * Deal with pipe return.
341          */
342
343         if (flags & EXTENDED_RESPONSE_REQUIRED) {
344                 /* This is very strange. We
345                  * return 50 words, but only set
346                  * the wcnt to 42 ? It's definitely
347                  * what happens on the wire....
348                  */
349                 reply_outbuf(req, 50, 0);
350                 SCVAL(req->outbuf,smb_wct,42);
351         } else {
352                 reply_outbuf(req, 34, 0);
353         }
354
355         SSVAL(req->outbuf, smb_vwv0, 0xff); /* andx chain ends */
356         SSVAL(req->outbuf, smb_vwv1, 0);    /* no andx offset */
357
358         p = (char *)req->outbuf + smb_vwv2;
359         p++;
360         SSVAL(p,0,pnum);
361         p += 2;
362         SIVAL(p,0,FILE_WAS_OPENED);
363         p += 4;
364         p += 32;
365         SIVAL(p,0,FILE_ATTRIBUTE_NORMAL); /* File Attributes. */
366         p += 20;
367         /* File type. */
368         SSVAL(p,0,FILE_TYPE_MESSAGE_MODE_PIPE);
369         /* Device state. */
370         SSVAL(p,2, 0x5FF); /* ? */
371         p += 4;
372
373         if (flags & EXTENDED_RESPONSE_REQUIRED) {
374                 p += 25;
375                 SIVAL(p,0,FILE_GENERIC_ALL);
376                 /*
377                  * For pipes W2K3 seems to return
378                  * 0x12019B next.
379                  * This is ((FILE_GENERIC_READ|FILE_GENERIC_WRITE) & ~FILE_APPEND_DATA)
380                  */
381                 SIVAL(p,4,(FILE_GENERIC_READ|FILE_GENERIC_WRITE)&~FILE_APPEND_DATA);
382         }
383
384         DEBUG(5,("do_ntcreate_pipe_open: open pipe = %s\n", fname));
385 }
386
387 struct case_semantics_state {
388         connection_struct *conn;
389         bool case_sensitive;
390         bool case_preserve;
391         bool short_case_preserve;
392 };
393
394 /****************************************************************************
395  Restore case semantics.
396 ****************************************************************************/
397
398 static int restore_case_semantics(struct case_semantics_state *state)
399 {
400         state->conn->case_sensitive = state->case_sensitive;
401         state->conn->case_preserve = state->case_preserve;
402         state->conn->short_case_preserve = state->short_case_preserve;
403         return 0;
404 }
405
406 /****************************************************************************
407  Save case semantics.
408 ****************************************************************************/
409
410 static struct case_semantics_state *set_posix_case_semantics(TALLOC_CTX *mem_ctx,
411                                                 connection_struct *conn)
412 {
413         struct case_semantics_state *result;
414
415         if (!(result = talloc(mem_ctx, struct case_semantics_state))) {
416                 return NULL;
417         }
418
419         result->conn = conn;
420         result->case_sensitive = conn->case_sensitive;
421         result->case_preserve = conn->case_preserve;
422         result->short_case_preserve = conn->short_case_preserve;
423
424         /* Set to POSIX. */
425         conn->case_sensitive = True;
426         conn->case_preserve = True;
427         conn->short_case_preserve = True;
428
429         talloc_set_destructor(result, restore_case_semantics);
430
431         return result;
432 }
433
434 /****************************************************************************
435  Reply to an NT create and X call.
436 ****************************************************************************/
437
438 void reply_ntcreate_and_X(struct smb_request *req)
439 {
440         connection_struct *conn = req->conn;
441         struct smb_filename *smb_fname = NULL;
442         char *fname = NULL;
443         uint32_t flags;
444         uint32_t access_mask;
445         uint32_t file_attributes;
446         uint32_t share_access;
447         uint32_t create_disposition;
448         uint32_t create_options;
449         uint16_t root_dir_fid;
450         uint64_t allocation_size;
451         /* Breakout the oplock request bits so we can set the
452            reply bits separately. */
453         uint32_t fattr=0;
454         off_t file_len = 0;
455         int info = 0;
456         files_struct *fsp = NULL;
457         char *p = NULL;
458         struct timespec create_timespec;
459         struct timespec c_timespec;
460         struct timespec a_timespec;
461         struct timespec m_timespec;
462         NTSTATUS status;
463         int oplock_request;
464         uint8_t oplock_granted = NO_OPLOCK_RETURN;
465         struct case_semantics_state *case_state = NULL;
466         uint32_t ucf_flags;
467         TALLOC_CTX *ctx = talloc_tos();
468
469         START_PROFILE(SMBntcreateX);
470
471         if (req->wct < 24) {
472                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
473                 goto out;
474         }
475
476         flags = IVAL(req->vwv+3, 1);
477         access_mask = IVAL(req->vwv+7, 1);
478         file_attributes = IVAL(req->vwv+13, 1);
479         share_access = IVAL(req->vwv+15, 1);
480         create_disposition = IVAL(req->vwv+17, 1);
481         create_options = IVAL(req->vwv+19, 1);
482         root_dir_fid = (uint16_t)IVAL(req->vwv+5, 1);
483
484         allocation_size = BVAL(req->vwv+9, 1);
485
486         srvstr_get_path_req(ctx, req, &fname, (const char *)req->buf,
487                             STR_TERMINATE, &status);
488
489         if (!NT_STATUS_IS_OK(status)) {
490                 reply_nterror(req, status);
491                 goto out;
492         }
493
494         DEBUG(10,("reply_ntcreate_and_X: flags = 0x%x, access_mask = 0x%x "
495                   "file_attributes = 0x%x, share_access = 0x%x, "
496                   "create_disposition = 0x%x create_options = 0x%x "
497                   "root_dir_fid = 0x%x, fname = %s\n",
498                         (unsigned int)flags,
499                         (unsigned int)access_mask,
500                         (unsigned int)file_attributes,
501                         (unsigned int)share_access,
502                         (unsigned int)create_disposition,
503                         (unsigned int)create_options,
504                         (unsigned int)root_dir_fid,
505                         fname));
506
507         /*
508          * we need to remove ignored bits when they come directly from the client
509          * because we reuse some of them for internal stuff
510          */
511         create_options &= ~NTCREATEX_OPTIONS_MUST_IGNORE_MASK;
512
513         /*
514          * If it's an IPC, use the pipe handler.
515          */
516
517         if (IS_IPC(conn)) {
518                 if (lp_nt_pipe_support()) {
519                         do_ntcreate_pipe_open(conn, req);
520                         goto out;
521                 }
522                 reply_nterror(req, NT_STATUS_ACCESS_DENIED);
523                 goto out;
524         }
525
526         oplock_request = (flags & REQUEST_OPLOCK) ? EXCLUSIVE_OPLOCK : 0;
527         if (oplock_request) {
528                 oplock_request |= (flags & REQUEST_BATCH_OPLOCK)
529                         ? BATCH_OPLOCK : 0;
530         }
531
532         if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
533                 case_state = set_posix_case_semantics(ctx, conn);
534                 if (!case_state) {
535                         reply_nterror(req, NT_STATUS_NO_MEMORY);
536                         goto out;
537                 }
538         }
539
540         ucf_flags = filename_create_ucf_flags(req, create_disposition);
541         status = filename_convert(ctx,
542                                 conn,
543                                 fname,
544                                 ucf_flags,
545                                 NULL,
546                                 NULL,
547                                 &smb_fname);
548
549         TALLOC_FREE(case_state);
550
551         if (!NT_STATUS_IS_OK(status)) {
552                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
553                         reply_botherror(req,
554                                 NT_STATUS_PATH_NOT_COVERED,
555                                 ERRSRV, ERRbadpath);
556                         goto out;
557                 }
558                 reply_nterror(req, status);
559                 goto out;
560         }
561
562         /*
563          * Bug #6898 - clients using Windows opens should
564          * never be able to set this attribute into the
565          * VFS.
566          */
567         file_attributes &= ~FILE_FLAG_POSIX_SEMANTICS;
568
569         status = SMB_VFS_CREATE_FILE(
570                 conn,                                   /* conn */
571                 req,                                    /* req */
572                 root_dir_fid,                           /* root_dir_fid */
573                 smb_fname,                              /* fname */
574                 access_mask,                            /* access_mask */
575                 share_access,                           /* share_access */
576                 create_disposition,                     /* create_disposition*/
577                 create_options,                         /* create_options */
578                 file_attributes,                        /* file_attributes */
579                 oplock_request,                         /* oplock_request */
580                 NULL,                                   /* lease */
581                 allocation_size,                        /* allocation_size */
582                 0,                                      /* private_flags */
583                 NULL,                                   /* sd */
584                 NULL,                                   /* ea_list */
585                 &fsp,                                   /* result */
586                 &info,                                  /* pinfo */
587                 NULL, NULL);                            /* create context */
588
589         if (!NT_STATUS_IS_OK(status)) {
590                 if (open_was_deferred(req->xconn, req->mid)) {
591                         /* We have re-scheduled this call, no error. */
592                         goto out;
593                 }
594                 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
595                         bool ok = defer_smb1_sharing_violation(req);
596                         if (ok) {
597                                 goto out;
598                         }
599                 }
600                 reply_openerror(req, status);
601                 goto out;
602         }
603
604         /* Ensure we're pointing at the correct stat struct. */
605         TALLOC_FREE(smb_fname);
606         smb_fname = fsp->fsp_name;
607
608         /*
609          * If the caller set the extended oplock request bit
610          * and we granted one (by whatever means) - set the
611          * correct bit for extended oplock reply.
612          */
613
614         if (oplock_request &&
615             (lp_fake_oplocks(SNUM(conn))
616              || EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type))) {
617
618                 /*
619                  * Exclusive oplock granted
620                  */
621
622                 if (flags & REQUEST_BATCH_OPLOCK) {
623                         oplock_granted = BATCH_OPLOCK_RETURN;
624                 } else {
625                         oplock_granted = EXCLUSIVE_OPLOCK_RETURN;
626                 }
627         } else if (fsp->oplock_type == LEVEL_II_OPLOCK) {
628                 oplock_granted = LEVEL_II_OPLOCK_RETURN;
629         } else {
630                 oplock_granted = NO_OPLOCK_RETURN;
631         }
632
633         file_len = smb_fname->st.st_ex_size;
634
635         if (flags & EXTENDED_RESPONSE_REQUIRED) {
636                 /* This is very strange. We
637                  * return 50 words, but only set
638                  * the wcnt to 42 ? It's definitely
639                  * what happens on the wire....
640                  */
641                 reply_outbuf(req, 50, 0);
642                 SCVAL(req->outbuf,smb_wct,42);
643         } else {
644                 reply_outbuf(req, 34, 0);
645         }
646
647         SSVAL(req->outbuf, smb_vwv0, 0xff); /* andx chain ends */
648         SSVAL(req->outbuf, smb_vwv1, 0);    /* no andx offset */
649
650         p = (char *)req->outbuf + smb_vwv2;
651
652         SCVAL(p, 0, oplock_granted);
653
654         p++;
655         SSVAL(p,0,fsp->fnum);
656         p += 2;
657         if ((create_disposition == FILE_SUPERSEDE)
658             && (info == FILE_WAS_OVERWRITTEN)) {
659                 SIVAL(p,0,FILE_WAS_SUPERSEDED);
660         } else {
661                 SIVAL(p,0,info);
662         }
663         p += 4;
664
665         fattr = dos_mode(conn, smb_fname);
666         if (fattr == 0) {
667                 fattr = FILE_ATTRIBUTE_NORMAL;
668         }
669
670         /* Create time. */
671         create_timespec = get_create_timespec(conn, fsp, smb_fname);
672         a_timespec = smb_fname->st.st_ex_atime;
673         m_timespec = smb_fname->st.st_ex_mtime;
674         c_timespec = get_change_timespec(conn, fsp, smb_fname);
675
676         if (lp_dos_filetime_resolution(SNUM(conn))) {
677                 dos_filetime_timespec(&create_timespec);
678                 dos_filetime_timespec(&a_timespec);
679                 dos_filetime_timespec(&m_timespec);
680                 dos_filetime_timespec(&c_timespec);
681         }
682
683         put_long_date_full_timespec(conn->ts_res, p, &create_timespec); /* create time. */
684         p += 8;
685         put_long_date_full_timespec(conn->ts_res, p, &a_timespec); /* access time */
686         p += 8;
687         put_long_date_full_timespec(conn->ts_res, p, &m_timespec); /* write time */
688         p += 8;
689         put_long_date_full_timespec(conn->ts_res, p, &c_timespec); /* change time */
690         p += 8;
691         SIVAL(p,0,fattr); /* File Attributes. */
692         p += 4;
693         SOFF_T(p, 0, SMB_VFS_GET_ALLOC_SIZE(conn,fsp,&smb_fname->st));
694         p += 8;
695         SOFF_T(p,0,file_len);
696         p += 8;
697         if (flags & EXTENDED_RESPONSE_REQUIRED) {
698                 uint16_t file_status = (NO_EAS|NO_SUBSTREAMS|NO_REPARSETAG);
699                 unsigned int num_streams = 0;
700                 struct stream_struct *streams = NULL;
701
702                 if (lp_ea_support(SNUM(conn))) {
703                         size_t num_names = 0;
704                         /* Do we have any EA's ? */
705                         status = get_ea_names_from_file(
706                             ctx, conn, fsp, smb_fname, NULL, &num_names);
707                         if (NT_STATUS_IS_OK(status) && num_names) {
708                                 file_status &= ~NO_EAS;
709                         }
710                 }
711
712                 status = vfs_streaminfo(conn, NULL, smb_fname, ctx,
713                         &num_streams, &streams);
714                 /* There is always one stream, ::$DATA. */
715                 if (NT_STATUS_IS_OK(status) && num_streams > 1) {
716                         file_status &= ~NO_SUBSTREAMS;
717                 }
718                 TALLOC_FREE(streams);
719                 SSVAL(p,2,file_status);
720         }
721         p += 4;
722         SCVAL(p,0,fsp->fsp_flags.is_directory ? 1 : 0);
723
724         if (flags & EXTENDED_RESPONSE_REQUIRED) {
725                 uint32_t perms = 0;
726                 p += 25;
727                 if (fsp->fsp_flags.is_directory ||
728                     fsp->fsp_flags.can_write ||
729                     can_write_to_file(conn,
730                                 smb_fname))
731                 {
732                         perms = FILE_GENERIC_ALL;
733                 } else {
734                         perms = FILE_GENERIC_READ|FILE_EXECUTE;
735                 }
736                 SIVAL(p,0,perms);
737         }
738
739         DEBUG(5,("reply_ntcreate_and_X: %s, open name = %s\n",
740                 fsp_fnum_dbg(fsp), smb_fname_str_dbg(smb_fname)));
741
742  out:
743         END_PROFILE(SMBntcreateX);
744         return;
745 }
746
747 /****************************************************************************
748  Reply to a NT_TRANSACT_CREATE call to open a pipe.
749 ****************************************************************************/
750
751 static void do_nt_transact_create_pipe(connection_struct *conn,
752                                        struct smb_request *req,
753                                        uint16_t **ppsetup, uint32_t setup_count,
754                                        char **ppparams, uint32_t parameter_count,
755                                        char **ppdata, uint32_t data_count)
756 {
757         char *fname = NULL;
758         char *params = *ppparams;
759         uint16_t pnum = FNUM_FIELD_INVALID;
760         char *p = NULL;
761         NTSTATUS status;
762         size_t param_len;
763         uint32_t flags;
764         TALLOC_CTX *ctx = talloc_tos();
765
766         /*
767          * Ensure minimum number of parameters sent.
768          */
769
770         if(parameter_count < 54) {
771                 DEBUG(0,("do_nt_transact_create_pipe - insufficient parameters (%u)\n", (unsigned int)parameter_count));
772                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
773                 return;
774         }
775
776         flags = IVAL(params,0);
777
778         if (req->posix_pathnames) {
779                 srvstr_get_path_posix(ctx,
780                         params,
781                         req->flags2,
782                         &fname,
783                         params+53,
784                         parameter_count-53,
785                         STR_TERMINATE,
786                         &status);
787         } else {
788                 srvstr_get_path(ctx,
789                         params,
790                         req->flags2,
791                         &fname,
792                         params+53,
793                         parameter_count-53,
794                         STR_TERMINATE,
795                         &status);
796         }
797         if (!NT_STATUS_IS_OK(status)) {
798                 reply_nterror(req, status);
799                 return;
800         }
801
802         nt_open_pipe(fname, conn, req, &pnum);
803
804         if (req->outbuf) {
805                 /* Error return */
806                 return;
807         }
808
809         /* Realloc the size of parameters and data we will return */
810         if (flags & EXTENDED_RESPONSE_REQUIRED) {
811                 /* Extended response is 32 more byyes. */
812                 param_len = 101;
813         } else {
814                 param_len = 69;
815         }
816         params = nttrans_realloc(ppparams, param_len);
817         if(params == NULL) {
818                 reply_nterror(req, NT_STATUS_NO_MEMORY);
819                 return;
820         }
821
822         p = params;
823         SCVAL(p,0,NO_OPLOCK_RETURN);
824
825         p += 2;
826         SSVAL(p,0,pnum);
827         p += 2;
828         SIVAL(p,0,FILE_WAS_OPENED);
829         p += 8;
830
831         p += 32;
832         SIVAL(p,0,FILE_ATTRIBUTE_NORMAL); /* File Attributes. */
833         p += 20;
834         /* File type. */
835         SSVAL(p,0,FILE_TYPE_MESSAGE_MODE_PIPE);
836         /* Device state. */
837         SSVAL(p,2, 0x5FF); /* ? */
838         p += 4;
839
840         if (flags & EXTENDED_RESPONSE_REQUIRED) {
841                 p += 25;
842                 SIVAL(p,0,FILE_GENERIC_ALL);
843                 /*
844                  * For pipes W2K3 seems to return
845                  * 0x12019B next.
846                  * This is ((FILE_GENERIC_READ|FILE_GENERIC_WRITE) & ~FILE_APPEND_DATA)
847                  */
848                 SIVAL(p,4,(FILE_GENERIC_READ|FILE_GENERIC_WRITE)&~FILE_APPEND_DATA);
849         }
850
851         DEBUG(5,("do_nt_transact_create_pipe: open name = %s\n", fname));
852
853         /* Send the required number of replies */
854         send_nt_replies(conn, req, NT_STATUS_OK, params, param_len, *ppdata, 0);
855
856         return;
857 }
858
859 /*********************************************************************
860  Windows seems to do canonicalization of inheritance bits. Do the
861  same.
862 *********************************************************************/
863
864 static void canonicalize_inheritance_bits(struct security_descriptor *psd)
865 {
866         bool set_auto_inherited = false;
867
868         /*
869          * We need to filter out the
870          * SEC_DESC_DACL_AUTO_INHERITED|SEC_DESC_DACL_AUTO_INHERIT_REQ
871          * bits. If both are set we store SEC_DESC_DACL_AUTO_INHERITED
872          * as this alters whether SEC_ACE_FLAG_INHERITED_ACE is set
873          * when an ACE is inherited. Otherwise we zero these bits out.
874          * See:
875          *
876          * http://social.msdn.microsoft.com/Forums/eu/os_fileservices/thread/11f77b68-731e-407d-b1b3-064750716531
877          *
878          * for details.
879          */
880
881         if ((psd->type & (SEC_DESC_DACL_AUTO_INHERITED|SEC_DESC_DACL_AUTO_INHERIT_REQ))
882                         == (SEC_DESC_DACL_AUTO_INHERITED|SEC_DESC_DACL_AUTO_INHERIT_REQ)) {
883                 set_auto_inherited = true;
884         }
885
886         psd->type &= ~(SEC_DESC_DACL_AUTO_INHERITED|SEC_DESC_DACL_AUTO_INHERIT_REQ);
887         if (set_auto_inherited) {
888                 psd->type |= SEC_DESC_DACL_AUTO_INHERITED;
889         }
890 }
891
892 /****************************************************************************
893  Internal fn to set security descriptors.
894 ****************************************************************************/
895
896 NTSTATUS set_sd(files_struct *fsp, struct security_descriptor *psd,
897                        uint32_t security_info_sent)
898 {
899         NTSTATUS status;
900
901         if (!CAN_WRITE(fsp->conn)) {
902                 return NT_STATUS_ACCESS_DENIED;
903         }
904
905         if (!lp_nt_acl_support(SNUM(fsp->conn))) {
906                 return NT_STATUS_OK;
907         }
908
909         if (S_ISLNK(fsp->fsp_name->st.st_ex_mode)) {
910                 DEBUG(10, ("ACL set on symlink %s denied.\n",
911                         fsp_str_dbg(fsp)));
912                 return NT_STATUS_ACCESS_DENIED;
913         }
914
915         if (psd->owner_sid == NULL) {
916                 security_info_sent &= ~SECINFO_OWNER;
917         }
918         if (psd->group_sid == NULL) {
919                 security_info_sent &= ~SECINFO_GROUP;
920         }
921
922         /* Ensure we have at least one thing set. */
923         if ((security_info_sent & (SECINFO_OWNER|SECINFO_GROUP|SECINFO_DACL|SECINFO_SACL)) == 0) {
924                 /* Just like W2K3 */
925                 return NT_STATUS_OK;
926         }
927
928         /* Ensure we have the rights to do this. */
929         if (security_info_sent & SECINFO_OWNER) {
930                 if (!(fsp->access_mask & SEC_STD_WRITE_OWNER)) {
931                         return NT_STATUS_ACCESS_DENIED;
932                 }
933         }
934
935         if (security_info_sent & SECINFO_GROUP) {
936                 if (!(fsp->access_mask & SEC_STD_WRITE_OWNER)) {
937                         return NT_STATUS_ACCESS_DENIED;
938                 }
939         }
940
941         if (security_info_sent & SECINFO_DACL) {
942                 if (!(fsp->access_mask & SEC_STD_WRITE_DAC)) {
943                         return NT_STATUS_ACCESS_DENIED;
944                 }
945                 /* Convert all the generic bits. */
946                 if (psd->dacl) {
947                         security_acl_map_generic(psd->dacl, &file_generic_mapping);
948                 }
949         }
950
951         if (security_info_sent & SECINFO_SACL) {
952                 if (!(fsp->access_mask & SEC_FLAG_SYSTEM_SECURITY)) {
953                         return NT_STATUS_ACCESS_DENIED;
954                 }
955                 /*
956                  * Setting a SACL also requires WRITE_DAC.
957                  * See the smbtorture3 SMB2-SACL test.
958                  */
959                 if (!(fsp->access_mask & SEC_STD_WRITE_DAC)) {
960                         return NT_STATUS_ACCESS_DENIED;
961                 }
962                 /* Convert all the generic bits. */
963                 if (psd->sacl) {
964                         security_acl_map_generic(psd->sacl, &file_generic_mapping);
965                 }
966         }
967
968         canonicalize_inheritance_bits(psd);
969
970         if (DEBUGLEVEL >= 10) {
971                 DEBUG(10,("set_sd for file %s\n", fsp_str_dbg(fsp)));
972                 NDR_PRINT_DEBUG(security_descriptor, psd);
973         }
974
975         status = SMB_VFS_FSET_NT_ACL(fsp, security_info_sent, psd);
976
977         TALLOC_FREE(psd);
978
979         return status;
980 }
981
982 /****************************************************************************
983  Internal fn to set security descriptors from a data blob.
984 ****************************************************************************/
985
986 NTSTATUS set_sd_blob(files_struct *fsp, uint8_t *data, uint32_t sd_len,
987                        uint32_t security_info_sent)
988 {
989         struct security_descriptor *psd = NULL;
990         NTSTATUS status;
991
992         if (sd_len == 0) {
993                 return NT_STATUS_INVALID_PARAMETER;
994         }
995
996         status = unmarshall_sec_desc(talloc_tos(), data, sd_len, &psd);
997
998         if (!NT_STATUS_IS_OK(status)) {
999                 return status;
1000         }
1001
1002         return set_sd(fsp, psd, security_info_sent);
1003 }
1004
1005 /****************************************************************************
1006  Reply to a NT_TRANSACT_CREATE call (needs to process SD's).
1007 ****************************************************************************/
1008
1009 static void call_nt_transact_create(connection_struct *conn,
1010                                     struct smb_request *req,
1011                                     uint16_t **ppsetup, uint32_t setup_count,
1012                                     char **ppparams, uint32_t parameter_count,
1013                                     char **ppdata, uint32_t data_count,
1014                                     uint32_t max_data_count)
1015 {
1016         struct smb_filename *smb_fname = NULL;
1017         char *fname = NULL;
1018         char *params = *ppparams;
1019         char *data = *ppdata;
1020         /* Breakout the oplock request bits so we can set the reply bits separately. */
1021         uint32_t fattr=0;
1022         off_t file_len = 0;
1023         int info = 0;
1024         files_struct *fsp = NULL;
1025         char *p = NULL;
1026         uint32_t flags;
1027         uint32_t access_mask;
1028         uint32_t file_attributes;
1029         uint32_t share_access;
1030         uint32_t create_disposition;
1031         uint32_t create_options;
1032         uint32_t sd_len;
1033         struct security_descriptor *sd = NULL;
1034         uint32_t ea_len;
1035         uint16_t root_dir_fid;
1036         struct timespec create_timespec;
1037         struct timespec c_timespec;
1038         struct timespec a_timespec;
1039         struct timespec m_timespec;
1040         struct ea_list *ea_list = NULL;
1041         NTSTATUS status;
1042         size_t param_len;
1043         uint64_t allocation_size;
1044         int oplock_request;
1045         uint8_t oplock_granted;
1046         struct case_semantics_state *case_state = NULL;
1047         uint32_t ucf_flags;
1048         TALLOC_CTX *ctx = talloc_tos();
1049
1050         DEBUG(5,("call_nt_transact_create\n"));
1051
1052         /*
1053          * If it's an IPC, use the pipe handler.
1054          */
1055
1056         if (IS_IPC(conn)) {
1057                 if (lp_nt_pipe_support()) {
1058                         do_nt_transact_create_pipe(
1059                                 conn, req,
1060                                 ppsetup, setup_count,
1061                                 ppparams, parameter_count,
1062                                 ppdata, data_count);
1063                         goto out;
1064                 }
1065                 reply_nterror(req, NT_STATUS_ACCESS_DENIED);
1066                 goto out;
1067         }
1068
1069         /*
1070          * Ensure minimum number of parameters sent.
1071          */
1072
1073         if(parameter_count < 54) {
1074                 DEBUG(0,("call_nt_transact_create - insufficient parameters (%u)\n", (unsigned int)parameter_count));
1075                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1076                 goto out;
1077         }
1078
1079         flags = IVAL(params,0);
1080         access_mask = IVAL(params,8);
1081         file_attributes = IVAL(params,20);
1082         share_access = IVAL(params,24);
1083         create_disposition = IVAL(params,28);
1084         create_options = IVAL(params,32);
1085         sd_len = IVAL(params,36);
1086         ea_len = IVAL(params,40);
1087         root_dir_fid = (uint16_t)IVAL(params,4);
1088         allocation_size = BVAL(params,12);
1089
1090         /*
1091          * we need to remove ignored bits when they come directly from the client
1092          * because we reuse some of them for internal stuff
1093          */
1094         create_options &= ~NTCREATEX_OPTIONS_MUST_IGNORE_MASK;
1095
1096         if (req->posix_pathnames) {
1097                 srvstr_get_path_posix(ctx,
1098                         params,
1099                         req->flags2,
1100                         &fname,
1101                         params+53,
1102                         parameter_count-53,
1103                         STR_TERMINATE,
1104                         &status);
1105         } else {
1106                 srvstr_get_path(ctx,
1107                         params,
1108                         req->flags2,
1109                         &fname,
1110                         params+53,
1111                         parameter_count-53,
1112                         STR_TERMINATE,
1113                         &status);
1114         }
1115         if (!NT_STATUS_IS_OK(status)) {
1116                 reply_nterror(req, status);
1117                 goto out;
1118         }
1119
1120         if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
1121                 case_state = set_posix_case_semantics(ctx, conn);
1122                 if (!case_state) {
1123                         reply_nterror(req, NT_STATUS_NO_MEMORY);
1124                         goto out;
1125                 }
1126         }
1127
1128         ucf_flags = filename_create_ucf_flags(req, create_disposition);
1129         status = filename_convert(ctx,
1130                                 conn,
1131                                 fname,
1132                                 ucf_flags,
1133                                 NULL,
1134                                 NULL,
1135                                 &smb_fname);
1136
1137         TALLOC_FREE(case_state);
1138
1139         if (!NT_STATUS_IS_OK(status)) {
1140                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
1141                         reply_botherror(req,
1142                                 NT_STATUS_PATH_NOT_COVERED,
1143                                 ERRSRV, ERRbadpath);
1144                         goto out;
1145                 }
1146                 reply_nterror(req, status);
1147                 goto out;
1148         }
1149
1150         /* Ensure the data_len is correct for the sd and ea values given. */
1151         if ((ea_len + sd_len > data_count)
1152             || (ea_len > data_count) || (sd_len > data_count)
1153             || (ea_len + sd_len < ea_len) || (ea_len + sd_len < sd_len)) {
1154                 DEBUG(10, ("call_nt_transact_create - ea_len = %u, sd_len = "
1155                            "%u, data_count = %u\n", (unsigned int)ea_len,
1156                            (unsigned int)sd_len, (unsigned int)data_count));
1157                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1158                 goto out;
1159         }
1160
1161         if (sd_len) {
1162                 DEBUG(10, ("call_nt_transact_create - sd_len = %d\n",
1163                            sd_len));
1164
1165                 status = unmarshall_sec_desc(ctx, (uint8_t *)data, sd_len,
1166                                              &sd);
1167                 if (!NT_STATUS_IS_OK(status)) {
1168                         DEBUG(10, ("call_nt_transact_create: "
1169                                    "unmarshall_sec_desc failed: %s\n",
1170                                    nt_errstr(status)));
1171                         reply_nterror(req, status);
1172                         goto out;
1173                 }
1174         }
1175
1176         if (ea_len) {
1177                 if (!lp_ea_support(SNUM(conn))) {
1178                         DEBUG(10, ("call_nt_transact_create - ea_len = %u but "
1179                                    "EA's not supported.\n",
1180                                    (unsigned int)ea_len));
1181                         reply_nterror(req, NT_STATUS_EAS_NOT_SUPPORTED);
1182                         goto out;
1183                 }
1184
1185                 if (ea_len < 10) {
1186                         DEBUG(10,("call_nt_transact_create - ea_len = %u - "
1187                                   "too small (should be more than 10)\n",
1188                                   (unsigned int)ea_len ));
1189                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1190                         goto out;
1191                 }
1192
1193                 /* We have already checked that ea_len <= data_count here. */
1194                 ea_list = read_nttrans_ea_list(talloc_tos(), data + sd_len,
1195                                                ea_len);
1196                 if (ea_list == NULL) {
1197                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1198                         goto out;
1199                 }
1200
1201                 if (!req->posix_pathnames &&
1202                                 ea_list_has_invalid_name(ea_list)) {
1203                         /* Realloc the size of parameters and data we will return */
1204                         if (flags & EXTENDED_RESPONSE_REQUIRED) {
1205                                 /* Extended response is 32 more byyes. */
1206                                 param_len = 101;
1207                         } else {
1208                                 param_len = 69;
1209                         }
1210                         params = nttrans_realloc(ppparams, param_len);
1211                         if(params == NULL) {
1212                                 reply_nterror(req, NT_STATUS_NO_MEMORY);
1213                                 goto out;
1214                         }
1215
1216                         memset(params, '\0', param_len);
1217                         send_nt_replies(conn, req, STATUS_INVALID_EA_NAME,
1218                                 params, param_len, NULL, 0);
1219                         goto out;
1220                 }
1221         }
1222
1223         oplock_request = (flags & REQUEST_OPLOCK) ? EXCLUSIVE_OPLOCK : 0;
1224         if (oplock_request) {
1225                 oplock_request |= (flags & REQUEST_BATCH_OPLOCK)
1226                         ? BATCH_OPLOCK : 0;
1227         }
1228
1229         /*
1230          * Bug #6898 - clients using Windows opens should
1231          * never be able to set this attribute into the
1232          * VFS.
1233          */
1234         file_attributes &= ~FILE_FLAG_POSIX_SEMANTICS;
1235
1236         status = SMB_VFS_CREATE_FILE(
1237                 conn,                                   /* conn */
1238                 req,                                    /* req */
1239                 root_dir_fid,                           /* root_dir_fid */
1240                 smb_fname,                              /* fname */
1241                 access_mask,                            /* access_mask */
1242                 share_access,                           /* share_access */
1243                 create_disposition,                     /* create_disposition*/
1244                 create_options,                         /* create_options */
1245                 file_attributes,                        /* file_attributes */
1246                 oplock_request,                         /* oplock_request */
1247                 NULL,                                   /* lease */
1248                 allocation_size,                        /* allocation_size */
1249                 0,                                      /* private_flags */
1250                 sd,                                     /* sd */
1251                 ea_list,                                /* ea_list */
1252                 &fsp,                                   /* result */
1253                 &info,                                  /* pinfo */
1254                 NULL, NULL);                            /* create context */
1255
1256         if(!NT_STATUS_IS_OK(status)) {
1257                 if (open_was_deferred(req->xconn, req->mid)) {
1258                         /* We have re-scheduled this call, no error. */
1259                         return;
1260                 }
1261                 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
1262                         bool ok = defer_smb1_sharing_violation(req);
1263                         if (ok) {
1264                                 return;
1265                         }
1266                 }
1267                 reply_openerror(req, status);
1268                 goto out;
1269         }
1270
1271         /* Ensure we're pointing at the correct stat struct. */
1272         TALLOC_FREE(smb_fname);
1273         smb_fname = fsp->fsp_name;
1274
1275         /*
1276          * If the caller set the extended oplock request bit
1277          * and we granted one (by whatever means) - set the
1278          * correct bit for extended oplock reply.
1279          */
1280
1281         if (oplock_request &&
1282             (lp_fake_oplocks(SNUM(conn))
1283              || EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type))) {
1284
1285                 /*
1286                  * Exclusive oplock granted
1287                  */
1288
1289                 if (flags & REQUEST_BATCH_OPLOCK) {
1290                         oplock_granted = BATCH_OPLOCK_RETURN;
1291                 } else {
1292                         oplock_granted = EXCLUSIVE_OPLOCK_RETURN;
1293                 }
1294         } else if (fsp->oplock_type == LEVEL_II_OPLOCK) {
1295                 oplock_granted = LEVEL_II_OPLOCK_RETURN;
1296         } else {
1297                 oplock_granted = NO_OPLOCK_RETURN;
1298         }
1299
1300         file_len = smb_fname->st.st_ex_size;
1301
1302         /* Realloc the size of parameters and data we will return */
1303         if (flags & EXTENDED_RESPONSE_REQUIRED) {
1304                 /* Extended response is 32 more byyes. */
1305                 param_len = 101;
1306         } else {
1307                 param_len = 69;
1308         }
1309         params = nttrans_realloc(ppparams, param_len);
1310         if(params == NULL) {
1311                 reply_nterror(req, NT_STATUS_NO_MEMORY);
1312                 goto out;
1313         }
1314
1315         p = params;
1316         SCVAL(p, 0, oplock_granted);
1317
1318         p += 2;
1319         SSVAL(p,0,fsp->fnum);
1320         p += 2;
1321         if ((create_disposition == FILE_SUPERSEDE)
1322             && (info == FILE_WAS_OVERWRITTEN)) {
1323                 SIVAL(p,0,FILE_WAS_SUPERSEDED);
1324         } else {
1325                 SIVAL(p,0,info);
1326         }
1327         p += 8;
1328
1329         fattr = dos_mode(conn, smb_fname);
1330         if (fattr == 0) {
1331                 fattr = FILE_ATTRIBUTE_NORMAL;
1332         }
1333
1334         /* Create time. */
1335         create_timespec = get_create_timespec(conn, fsp, smb_fname);
1336         a_timespec = smb_fname->st.st_ex_atime;
1337         m_timespec = smb_fname->st.st_ex_mtime;
1338         c_timespec = get_change_timespec(conn, fsp, smb_fname);
1339
1340         if (lp_dos_filetime_resolution(SNUM(conn))) {
1341                 dos_filetime_timespec(&create_timespec);
1342                 dos_filetime_timespec(&a_timespec);
1343                 dos_filetime_timespec(&m_timespec);
1344                 dos_filetime_timespec(&c_timespec);
1345         }
1346
1347         put_long_date_full_timespec(conn->ts_res, p, &create_timespec); /* create time. */
1348         p += 8;
1349         put_long_date_full_timespec(conn->ts_res, p, &a_timespec); /* access time */
1350         p += 8;
1351         put_long_date_full_timespec(conn->ts_res, p, &m_timespec); /* write time */
1352         p += 8;
1353         put_long_date_full_timespec(conn->ts_res, p, &c_timespec); /* change time */
1354         p += 8;
1355         SIVAL(p,0,fattr); /* File Attributes. */
1356         p += 4;
1357         SOFF_T(p, 0, SMB_VFS_GET_ALLOC_SIZE(conn, fsp, &smb_fname->st));
1358         p += 8;
1359         SOFF_T(p,0,file_len);
1360         p += 8;
1361         if (flags & EXTENDED_RESPONSE_REQUIRED) {
1362                 uint16_t file_status = (NO_EAS|NO_SUBSTREAMS|NO_REPARSETAG);
1363                 unsigned int num_streams = 0;
1364                 struct stream_struct *streams = NULL;
1365
1366                 if (lp_ea_support(SNUM(conn))) {
1367                         size_t num_names = 0;
1368                         /* Do we have any EA's ? */
1369                         status = get_ea_names_from_file(
1370                             ctx, conn, fsp, smb_fname, NULL, &num_names);
1371                         if (NT_STATUS_IS_OK(status) && num_names) {
1372                                 file_status &= ~NO_EAS;
1373                         }
1374                 }
1375
1376                 status = vfs_streaminfo(conn, NULL, smb_fname, ctx,
1377                         &num_streams, &streams);
1378                 /* There is always one stream, ::$DATA. */
1379                 if (NT_STATUS_IS_OK(status) && num_streams > 1) {
1380                         file_status &= ~NO_SUBSTREAMS;
1381                 }
1382                 TALLOC_FREE(streams);
1383                 SSVAL(p,2,file_status);
1384         }
1385         p += 4;
1386         SCVAL(p,0,fsp->fsp_flags.is_directory ? 1 : 0);
1387
1388         if (flags & EXTENDED_RESPONSE_REQUIRED) {
1389                 uint32_t perms = 0;
1390                 p += 25;
1391                 if (fsp->fsp_flags.is_directory ||
1392                     fsp->fsp_flags.can_write ||
1393                     can_write_to_file(conn,
1394                                 smb_fname))
1395                 {
1396                         perms = FILE_GENERIC_ALL;
1397                 } else {
1398                         perms = FILE_GENERIC_READ|FILE_EXECUTE;
1399                 }
1400                 SIVAL(p,0,perms);
1401         }
1402
1403         DEBUG(5,("call_nt_transact_create: open name = %s\n",
1404                  smb_fname_str_dbg(smb_fname)));
1405
1406         /* Send the required number of replies */
1407         send_nt_replies(conn, req, NT_STATUS_OK, params, param_len, *ppdata, 0);
1408  out:
1409         return;
1410 }
1411
1412 /****************************************************************************
1413  Reply to a NT CANCEL request.
1414  conn POINTER CAN BE NULL HERE !
1415 ****************************************************************************/
1416
1417 void reply_ntcancel(struct smb_request *req)
1418 {
1419         struct smbXsrv_connection *xconn = req->xconn;
1420         struct smbd_server_connection *sconn = req->sconn;
1421         bool found;
1422
1423         /*
1424          * Go through and cancel any pending change notifies.
1425          */
1426
1427         START_PROFILE(SMBntcancel);
1428         srv_cancel_sign_response(xconn);
1429         found = remove_pending_change_notify_requests_by_mid(sconn, req->mid);
1430         if (!found) {
1431                 smbd_smb1_brl_finish_by_mid(sconn, req->mid);
1432         }
1433
1434         DEBUG(3,("reply_ntcancel: cancel called on mid = %llu.\n",
1435                 (unsigned long long)req->mid));
1436
1437         END_PROFILE(SMBntcancel);
1438         return;
1439 }
1440
1441 /****************************************************************************
1442  Copy a file.
1443 ****************************************************************************/
1444
1445 static NTSTATUS copy_internals(TALLOC_CTX *ctx,
1446                                 connection_struct *conn,
1447                                 struct smb_request *req,
1448                                 struct smb_filename *smb_fname_src,
1449                                 struct smb_filename *smb_fname_dst,
1450                                 uint32_t attrs)
1451 {
1452         files_struct *fsp1,*fsp2;
1453         uint32_t fattr;
1454         int info;
1455         off_t ret=-1;
1456         NTSTATUS status = NT_STATUS_OK;
1457         struct smb_filename *parent = NULL;
1458         bool ok;
1459
1460         if (!CAN_WRITE(conn)) {
1461                 status = NT_STATUS_MEDIA_WRITE_PROTECTED;
1462                 goto out;
1463         }
1464
1465         /* Source must already exist. */
1466         if (!VALID_STAT(smb_fname_src->st)) {
1467                 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1468                 goto out;
1469         }
1470
1471         /* Ensure attributes match. */
1472         fattr = dos_mode(conn, smb_fname_src);
1473         if ((fattr & ~attrs) & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) {
1474                 status = NT_STATUS_NO_SUCH_FILE;
1475                 goto out;
1476         }
1477
1478         /* Disallow if dst file already exists. */
1479         if (VALID_STAT(smb_fname_dst->st)) {
1480                 status = NT_STATUS_OBJECT_NAME_COLLISION;
1481                 goto out;
1482         }
1483
1484         /* No links from a directory. */
1485         if (S_ISDIR(smb_fname_src->st.st_ex_mode)) {
1486                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
1487                 goto out;
1488         }
1489
1490         DEBUG(10,("copy_internals: doing file copy %s to %s\n",
1491                   smb_fname_str_dbg(smb_fname_src),
1492                   smb_fname_str_dbg(smb_fname_dst)));
1493
1494         status = SMB_VFS_CREATE_FILE(
1495                 conn,                                   /* conn */
1496                 req,                                    /* req */
1497                 0,                                      /* root_dir_fid */
1498                 smb_fname_src,                          /* fname */
1499                 FILE_READ_DATA|FILE_READ_ATTRIBUTES|
1500                         FILE_READ_EA,                   /* access_mask */
1501                 (FILE_SHARE_READ | FILE_SHARE_WRITE |   /* share_access */
1502                     FILE_SHARE_DELETE),
1503                 FILE_OPEN,                              /* create_disposition*/
1504                 0,                                      /* create_options */
1505                 FILE_ATTRIBUTE_NORMAL,                  /* file_attributes */
1506                 NO_OPLOCK,                              /* oplock_request */
1507                 NULL,                                   /* lease */
1508                 0,                                      /* allocation_size */
1509                 0,                                      /* private_flags */
1510                 NULL,                                   /* sd */
1511                 NULL,                                   /* ea_list */
1512                 &fsp1,                                  /* result */
1513                 &info,                                  /* pinfo */
1514                 NULL, NULL);                            /* create context */
1515
1516         if (!NT_STATUS_IS_OK(status)) {
1517                 goto out;
1518         }
1519
1520         status = SMB_VFS_CREATE_FILE(
1521                 conn,                                   /* conn */
1522                 req,                                    /* req */
1523                 0,                                      /* root_dir_fid */
1524                 smb_fname_dst,                          /* fname */
1525                 FILE_WRITE_DATA|FILE_WRITE_ATTRIBUTES|
1526                         FILE_WRITE_EA,                  /* access_mask */
1527                 (FILE_SHARE_READ | FILE_SHARE_WRITE |   /* share_access */
1528                     FILE_SHARE_DELETE),
1529                 FILE_CREATE,                            /* create_disposition*/
1530                 0,                                      /* create_options */
1531                 fattr,                                  /* file_attributes */
1532                 NO_OPLOCK,                              /* oplock_request */
1533                 NULL,                                   /* lease */
1534                 0,                                      /* allocation_size */
1535                 0,                                      /* private_flags */
1536                 NULL,                                   /* sd */
1537                 NULL,                                   /* ea_list */
1538                 &fsp2,                                  /* result */
1539                 &info,                                  /* pinfo */
1540                 NULL, NULL);                            /* create context */
1541
1542         if (!NT_STATUS_IS_OK(status)) {
1543                 close_file(NULL, fsp1, ERROR_CLOSE);
1544                 goto out;
1545         }
1546
1547         if (smb_fname_src->st.st_ex_size) {
1548                 ret = vfs_transfer_file(fsp1, fsp2, smb_fname_src->st.st_ex_size);
1549         }
1550
1551         /*
1552          * As we are opening fsp1 read-only we only expect
1553          * an error on close on fsp2 if we are out of space.
1554          * Thus we don't look at the error return from the
1555          * close of fsp1.
1556          */
1557         close_file(NULL, fsp1, NORMAL_CLOSE);
1558
1559         /* Ensure the modtime is set correctly on the destination file. */
1560         set_close_write_time(fsp2, smb_fname_src->st.st_ex_mtime);
1561
1562         status = close_file(NULL, fsp2, NORMAL_CLOSE);
1563
1564         /* Grrr. We have to do this as open_file_ntcreate adds FILE_ATTRIBUTE_ARCHIVE when it
1565            creates the file. This isn't the correct thing to do in the copy
1566            case. JRA */
1567
1568         ok = parent_smb_fname(talloc_tos(),
1569                               smb_fname_dst,
1570                               &parent,
1571                               NULL);
1572         if (!ok) {
1573                 status = NT_STATUS_NO_MEMORY;
1574                 goto out;
1575         }
1576         file_set_dosmode(conn, smb_fname_dst, fattr, parent, false);
1577         TALLOC_FREE(parent);
1578
1579         if (ret < (off_t)smb_fname_src->st.st_ex_size) {
1580                 status = NT_STATUS_DISK_FULL;
1581                 goto out;
1582         }
1583  out:
1584         if (!NT_STATUS_IS_OK(status)) {
1585                 DEBUG(3,("copy_internals: Error %s copy file %s to %s\n",
1586                         nt_errstr(status), smb_fname_str_dbg(smb_fname_src),
1587                         smb_fname_str_dbg(smb_fname_dst)));
1588         }
1589
1590         return status;
1591 }
1592
1593 /****************************************************************************
1594  Reply to a NT rename request.
1595 ****************************************************************************/
1596
1597 void reply_ntrename(struct smb_request *req)
1598 {
1599         connection_struct *conn = req->conn;
1600         struct smb_filename *smb_fname_old = NULL;
1601         struct smb_filename *smb_fname_new = NULL;
1602         char *oldname = NULL;
1603         char *newname = NULL;
1604         const char *dst_original_lcomp = NULL;
1605         const char *p;
1606         NTSTATUS status;
1607         bool src_has_wcard = False;
1608         bool dest_has_wcard = False;
1609         uint32_t attrs;
1610         uint32_t ucf_flags_src = ucf_flags_from_smb_request(req);
1611         uint32_t ucf_flags_dst = ucf_flags_from_smb_request(req);
1612         uint16_t rename_type;
1613         TALLOC_CTX *ctx = talloc_tos();
1614         bool stream_rename = false;
1615
1616         START_PROFILE(SMBntrename);
1617
1618         if (req->wct < 4) {
1619                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1620                 goto out;
1621         }
1622
1623         attrs = SVAL(req->vwv+0, 0);
1624         rename_type = SVAL(req->vwv+1, 0);
1625
1626         p = (const char *)req->buf + 1;
1627         p += srvstr_get_path_req_wcard(ctx, req, &oldname, p, STR_TERMINATE,
1628                                        &status, &src_has_wcard);
1629         if (!NT_STATUS_IS_OK(status)) {
1630                 reply_nterror(req, status);
1631                 goto out;
1632         }
1633
1634         if (!req->posix_pathnames && ms_has_wild(oldname)) {
1635                 reply_nterror(req, NT_STATUS_OBJECT_PATH_SYNTAX_BAD);
1636                 goto out;
1637         }
1638
1639         p++;
1640         p += srvstr_get_path_req_wcard(ctx, req, &newname, p, STR_TERMINATE,
1641                                        &status, &dest_has_wcard);
1642         if (!NT_STATUS_IS_OK(status)) {
1643                 reply_nterror(req, status);
1644                 goto out;
1645         }
1646
1647         if (!req->posix_pathnames) {
1648                 /* The newname must begin with a ':' if the
1649                    oldname contains a ':'. */
1650                 if (strchr_m(oldname, ':')) {
1651                         if (newname[0] != ':') {
1652                                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1653                                 goto out;
1654                         }
1655                         stream_rename = true;
1656                 }
1657         }
1658
1659         /*
1660          * If this is a rename operation, allow wildcards and save the
1661          * destination's last component.
1662          */
1663         if (rename_type == RENAME_FLAG_RENAME) {
1664                 ucf_flags_src |= UCF_COND_ALLOW_WCARD_LCOMP;
1665                 ucf_flags_dst |= UCF_COND_ALLOW_WCARD_LCOMP;
1666         }
1667
1668         /* rename_internals() calls unix_convert(), so don't call it here. */
1669         status = filename_convert(ctx, conn,
1670                                   oldname,
1671                                   ucf_flags_src,
1672                                   NULL,
1673                                   NULL,
1674                                   &smb_fname_old);
1675         if (!NT_STATUS_IS_OK(status)) {
1676                 if (NT_STATUS_EQUAL(status,
1677                                     NT_STATUS_PATH_NOT_COVERED)) {
1678                         reply_botherror(req,
1679                                         NT_STATUS_PATH_NOT_COVERED,
1680                                         ERRSRV, ERRbadpath);
1681                         goto out;
1682                 }
1683                 reply_nterror(req, status);
1684                 goto out;
1685         }
1686
1687         status = filename_convert(ctx, conn,
1688                                   newname,
1689                                   ucf_flags_dst,
1690                                   NULL,
1691                                   &dest_has_wcard,
1692                                   &smb_fname_new);
1693         if (!NT_STATUS_IS_OK(status)) {
1694                 if (NT_STATUS_EQUAL(status,
1695                                     NT_STATUS_PATH_NOT_COVERED)) {
1696                         reply_botherror(req,
1697                                         NT_STATUS_PATH_NOT_COVERED,
1698                                         ERRSRV, ERRbadpath);
1699                         goto out;
1700                 }
1701                 reply_nterror(req, status);
1702                 goto out;
1703         }
1704
1705         /* Get the last component of the destination for rename_internals(). */
1706         dst_original_lcomp = get_original_lcomp(ctx,
1707                                         conn,
1708                                         newname,
1709                                         ucf_flags_dst);
1710         if (dst_original_lcomp == NULL) {
1711                 reply_nterror(req, NT_STATUS_NO_MEMORY);
1712                 goto out;
1713         }
1714
1715         if (stream_rename) {
1716                 /* smb_fname_new must be the same as smb_fname_old. */
1717                 TALLOC_FREE(smb_fname_new->base_name);
1718                 smb_fname_new->base_name = talloc_strdup(smb_fname_new,
1719                                                 smb_fname_old->base_name);
1720                 if (!smb_fname_new->base_name) {
1721                         reply_nterror(req, NT_STATUS_NO_MEMORY);
1722                         goto out;
1723                 }
1724         }
1725
1726         DEBUG(3,("reply_ntrename: %s -> %s\n",
1727                  smb_fname_str_dbg(smb_fname_old),
1728                  smb_fname_str_dbg(smb_fname_new)));
1729
1730         switch(rename_type) {
1731                 case RENAME_FLAG_RENAME:
1732                         status = rename_internals(ctx,
1733                                                 conn,
1734                                                 req,
1735                                                 smb_fname_old,
1736                                                 smb_fname_new,
1737                                                 dst_original_lcomp,
1738                                                 attrs,
1739                                                 false,
1740                                                 src_has_wcard,
1741                                                 dest_has_wcard,
1742                                                 DELETE_ACCESS);
1743                         break;
1744                 case RENAME_FLAG_HARD_LINK:
1745                         if (src_has_wcard || dest_has_wcard) {
1746                                 /* No wildcards. */
1747                                 status = NT_STATUS_OBJECT_PATH_SYNTAX_BAD;
1748                         } else {
1749                                 status = hardlink_internals(ctx, conn,
1750                                                             req,
1751                                                             false,
1752                                                             smb_fname_old,
1753                                                             smb_fname_new);
1754                         }
1755                         break;
1756                 case RENAME_FLAG_COPY:
1757                         if (src_has_wcard || dest_has_wcard) {
1758                                 /* No wildcards. */
1759                                 status = NT_STATUS_OBJECT_PATH_SYNTAX_BAD;
1760                         } else {
1761                                 status = copy_internals(ctx, conn, req,
1762                                                         smb_fname_old,
1763                                                         smb_fname_new,
1764                                                         attrs);
1765                         }
1766                         break;
1767                 case RENAME_FLAG_MOVE_CLUSTER_INFORMATION:
1768                         status = NT_STATUS_INVALID_PARAMETER;
1769                         break;
1770                 default:
1771                         status = NT_STATUS_ACCESS_DENIED; /* Default error. */
1772                         break;
1773         }
1774
1775         if (!NT_STATUS_IS_OK(status)) {
1776                 if (open_was_deferred(req->xconn, req->mid)) {
1777                         /* We have re-scheduled this call. */
1778                         goto out;
1779                 }
1780                 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
1781                         bool ok = defer_smb1_sharing_violation(req);
1782                         if (ok) {
1783                                 goto out;
1784                         }
1785                 }
1786
1787                 reply_nterror(req, status);
1788                 goto out;
1789         }
1790
1791         reply_outbuf(req, 0, 0);
1792  out:
1793         END_PROFILE(SMBntrename);
1794         return;
1795 }
1796
1797 /****************************************************************************
1798  Reply to a notify change - queue the request and
1799  don't allow a directory to be opened.
1800 ****************************************************************************/
1801
1802 static void smbd_smb1_notify_reply(struct smb_request *req,
1803                                    NTSTATUS error_code,
1804                                    uint8_t *buf, size_t len)
1805 {
1806         send_nt_replies(req->conn, req, error_code, (char *)buf, len, NULL, 0);
1807 }
1808
1809 static void call_nt_transact_notify_change(connection_struct *conn,
1810                                            struct smb_request *req,
1811                                            uint16_t **ppsetup,
1812                                            uint32_t setup_count,
1813                                            char **ppparams,
1814                                            uint32_t parameter_count,
1815                                            char **ppdata, uint32_t data_count,
1816                                            uint32_t max_data_count,
1817                                            uint32_t max_param_count)
1818 {
1819         uint16_t *setup = *ppsetup;
1820         files_struct *fsp;
1821         uint32_t filter;
1822         NTSTATUS status;
1823         bool recursive;
1824
1825         if(setup_count < 6) {
1826                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1827                 return;
1828         }
1829
1830         fsp = file_fsp(req, SVAL(setup,4));
1831         filter = IVAL(setup, 0);
1832         recursive = (SVAL(setup, 6) != 0) ? True : False;
1833
1834         DEBUG(3,("call_nt_transact_notify_change\n"));
1835
1836         if(!fsp) {
1837                 reply_nterror(req, NT_STATUS_INVALID_HANDLE);
1838                 return;
1839         }
1840
1841         {
1842                 char *filter_string;
1843
1844                 if (!(filter_string = notify_filter_string(NULL, filter))) {
1845                         reply_nterror(req,NT_STATUS_NO_MEMORY);
1846                         return;
1847                 }
1848
1849                 DEBUG(3,("call_nt_transact_notify_change: notify change "
1850                          "called on %s, filter = %s, recursive = %d\n",
1851                          fsp_str_dbg(fsp), filter_string, recursive));
1852
1853                 TALLOC_FREE(filter_string);
1854         }
1855
1856         if((!fsp->fsp_flags.is_directory) || (conn != fsp->conn)) {
1857                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1858                 return;
1859         }
1860
1861         if (fsp->notify == NULL) {
1862
1863                 status = change_notify_create(fsp,
1864                                               max_param_count,
1865                                               filter,
1866                                               recursive);
1867                 if (!NT_STATUS_IS_OK(status)) {
1868                         DEBUG(10, ("change_notify_create returned %s\n",
1869                                    nt_errstr(status)));
1870                         reply_nterror(req, status);
1871                         return;
1872                 }
1873         }
1874
1875         if (change_notify_fsp_has_changes(fsp)) {
1876
1877                 /*
1878                  * We've got changes pending, respond immediately
1879                  */
1880
1881                 /*
1882                  * TODO: write a torture test to check the filtering behaviour
1883                  * here.
1884                  */
1885
1886                 change_notify_reply(req,
1887                                     NT_STATUS_OK,
1888                                     max_param_count,
1889                                     fsp->notify,
1890                                     smbd_smb1_notify_reply);
1891
1892                 /*
1893                  * change_notify_reply() above has independently sent its
1894                  * results
1895                  */
1896                 return;
1897         }
1898
1899         /*
1900          * No changes pending, queue the request
1901          */
1902
1903         status = change_notify_add_request(req,
1904                         max_param_count,
1905                         filter,
1906                         recursive, fsp,
1907                         smbd_smb1_notify_reply);
1908         if (!NT_STATUS_IS_OK(status)) {
1909                 reply_nterror(req, status);
1910         }
1911         return;
1912 }
1913
1914 /****************************************************************************
1915  Reply to an NT transact rename command.
1916 ****************************************************************************/
1917
1918 static void call_nt_transact_rename(connection_struct *conn,
1919                                     struct smb_request *req,
1920                                     uint16_t **ppsetup, uint32_t setup_count,
1921                                     char **ppparams, uint32_t parameter_count,
1922                                     char **ppdata, uint32_t data_count,
1923                                     uint32_t max_data_count)
1924 {
1925         char *params = *ppparams;
1926         char *new_name = NULL;
1927         files_struct *fsp = NULL;
1928         bool dest_has_wcard = False;
1929         NTSTATUS status;
1930         TALLOC_CTX *ctx = talloc_tos();
1931
1932         if(parameter_count < 5) {
1933                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1934                 return;
1935         }
1936
1937         fsp = file_fsp(req, SVAL(params, 0));
1938         if (!check_fsp(conn, req, fsp)) {
1939                 return;
1940         }
1941         if (req->posix_pathnames) {
1942                 srvstr_get_path_wcard_posix(ctx,
1943                                 params,
1944                                 req->flags2,
1945                                 &new_name,
1946                                 params+4,
1947                                 parameter_count - 4,
1948                                 STR_TERMINATE,
1949                                 &status,
1950                                 &dest_has_wcard);
1951         } else {
1952                 srvstr_get_path_wcard(ctx,
1953                                 params,
1954                                 req->flags2,
1955                                 &new_name,
1956                                 params+4,
1957                                 parameter_count - 4,
1958                                 STR_TERMINATE,
1959                                 &status,
1960                                 &dest_has_wcard);
1961         }
1962
1963         if (!NT_STATUS_IS_OK(status)) {
1964                 reply_nterror(req, status);
1965                 return;
1966         }
1967
1968         /*
1969          * W2K3 ignores this request as the RAW-RENAME test
1970          * demonstrates, so we do.
1971          */
1972         send_nt_replies(conn, req, NT_STATUS_OK, NULL, 0, NULL, 0);
1973
1974         DEBUG(3,("nt transact rename from = %s, to = %s ignored!\n",
1975                  fsp_str_dbg(fsp), new_name));
1976
1977         return;
1978 }
1979
1980 /******************************************************************************
1981  Fake up a completely empty SD.
1982 *******************************************************************************/
1983
1984 static NTSTATUS get_null_nt_acl(TALLOC_CTX *mem_ctx, struct security_descriptor **ppsd)
1985 {
1986         size_t sd_size;
1987
1988         *ppsd = make_standard_sec_desc( mem_ctx, &global_sid_World, &global_sid_World, NULL, &sd_size);
1989         if(!*ppsd) {
1990                 DEBUG(0,("get_null_nt_acl: Unable to malloc space for security descriptor.\n"));
1991                 return NT_STATUS_NO_MEMORY;
1992         }
1993
1994         return NT_STATUS_OK;
1995 }
1996
1997 /****************************************************************************
1998  Reply to query a security descriptor.
1999  Callable from SMB1 and SMB2.
2000  If it returns NT_STATUS_BUFFER_TOO_SMALL, pdata_size is initialized with
2001  the required size.
2002 ****************************************************************************/
2003
2004 NTSTATUS smbd_do_query_security_desc(connection_struct *conn,
2005                                         TALLOC_CTX *mem_ctx,
2006                                         files_struct *fsp,
2007                                         uint32_t security_info_wanted,
2008                                         uint32_t max_data_count,
2009                                         uint8_t **ppmarshalled_sd,
2010                                         size_t *psd_size)
2011 {
2012         NTSTATUS status;
2013         struct security_descriptor *psd = NULL;
2014         TALLOC_CTX *frame = talloc_stackframe();
2015         bool need_to_read_sd = false;
2016
2017         /*
2018          * Get the permissions to return.
2019          */
2020
2021         if ((security_info_wanted & SECINFO_SACL) &&
2022                         !(fsp->access_mask & SEC_FLAG_SYSTEM_SECURITY)) {
2023                 DEBUG(10, ("Access to SACL denied.\n"));
2024                 TALLOC_FREE(frame);
2025                 return NT_STATUS_ACCESS_DENIED;
2026         }
2027
2028         if ((security_info_wanted & (SECINFO_DACL|SECINFO_OWNER|SECINFO_GROUP)) &&
2029                         !(fsp->access_mask & SEC_STD_READ_CONTROL)) {
2030                 DEBUG(10, ("Access to DACL, OWNER, or GROUP denied.\n"));
2031                 TALLOC_FREE(frame);
2032                 return NT_STATUS_ACCESS_DENIED;
2033         }
2034
2035         if (S_ISLNK(fsp->fsp_name->st.st_ex_mode)) {
2036                 DEBUG(10, ("ACL get on symlink %s denied.\n",
2037                         fsp_str_dbg(fsp)));
2038                 TALLOC_FREE(frame);
2039                 return NT_STATUS_ACCESS_DENIED;
2040         }
2041
2042         if (security_info_wanted & (SECINFO_DACL|SECINFO_OWNER|
2043                         SECINFO_GROUP|SECINFO_SACL)) {
2044                 /* Don't return SECINFO_LABEL if anything else was
2045                    requested. See bug #8458. */
2046                 security_info_wanted &= ~SECINFO_LABEL;
2047
2048                 /*
2049                  * Only query the file system SD if the caller asks
2050                  * for any bits. This allows a caller to open without
2051                  * READ_CONTROL but still issue a query sd. See
2052                  * smb2.sdread test.
2053                  */
2054                 need_to_read_sd = true;
2055         }
2056
2057         if (lp_nt_acl_support(SNUM(conn)) &&
2058             ((security_info_wanted & SECINFO_LABEL) == 0) &&
2059             need_to_read_sd)
2060         {
2061                 status = SMB_VFS_FGET_NT_ACL(
2062                         fsp, security_info_wanted, frame, &psd);
2063         } else {
2064                 status = get_null_nt_acl(frame, &psd);
2065         }
2066
2067         if (!NT_STATUS_IS_OK(status)) {
2068                 TALLOC_FREE(frame);
2069                 return status;
2070         }
2071
2072         if (!(security_info_wanted & SECINFO_OWNER)) {
2073                 psd->owner_sid = NULL;
2074         }
2075         if (!(security_info_wanted & SECINFO_GROUP)) {
2076                 psd->group_sid = NULL;
2077         }
2078         if (!(security_info_wanted & SECINFO_DACL)) {
2079                 psd->type &= ~SEC_DESC_DACL_PRESENT;
2080                 psd->dacl = NULL;
2081         }
2082         if (!(security_info_wanted & SECINFO_SACL)) {
2083                 psd->type &= ~SEC_DESC_SACL_PRESENT;
2084                 psd->sacl = NULL;
2085         }
2086
2087         /* If the SACL/DACL is NULL, but was requested, we mark that it is
2088          * present in the reply to match Windows behavior */
2089         if (psd->sacl == NULL &&
2090             security_info_wanted & SECINFO_SACL)
2091                 psd->type |= SEC_DESC_SACL_PRESENT;
2092         if (psd->dacl == NULL &&
2093             security_info_wanted & SECINFO_DACL)
2094                 psd->type |= SEC_DESC_DACL_PRESENT;
2095
2096         if (security_info_wanted & SECINFO_LABEL) {
2097                 /* Like W2K3 return a null object. */
2098                 psd->owner_sid = NULL;
2099                 psd->group_sid = NULL;
2100                 psd->dacl = NULL;
2101                 psd->sacl = NULL;
2102                 psd->type &= ~(SEC_DESC_DACL_PRESENT|SEC_DESC_SACL_PRESENT);
2103         }
2104
2105         *psd_size = ndr_size_security_descriptor(psd, 0);
2106
2107         DEBUG(3,("smbd_do_query_security_desc: sd_size = %lu.\n",
2108                 (unsigned long)*psd_size));
2109
2110         if (DEBUGLEVEL >= 10) {
2111                 DEBUG(10,("smbd_do_query_security_desc for file %s\n",
2112                           fsp_str_dbg(fsp)));
2113                 NDR_PRINT_DEBUG(security_descriptor, psd);
2114         }
2115
2116         if (max_data_count < *psd_size) {
2117                 TALLOC_FREE(frame);
2118                 return NT_STATUS_BUFFER_TOO_SMALL;
2119         }
2120
2121         status = marshall_sec_desc(mem_ctx, psd,
2122                                    ppmarshalled_sd, psd_size);
2123
2124         if (!NT_STATUS_IS_OK(status)) {
2125                 TALLOC_FREE(frame);
2126                 return status;
2127         }
2128
2129         TALLOC_FREE(frame);
2130         return NT_STATUS_OK;
2131 }
2132
2133 /****************************************************************************
2134  SMB1 reply to query a security descriptor.
2135 ****************************************************************************/
2136
2137 static void call_nt_transact_query_security_desc(connection_struct *conn,
2138                                                  struct smb_request *req,
2139                                                  uint16_t **ppsetup,
2140                                                  uint32_t setup_count,
2141                                                  char **ppparams,
2142                                                  uint32_t parameter_count,
2143                                                  char **ppdata,
2144                                                  uint32_t data_count,
2145                                                  uint32_t max_data_count)
2146 {
2147         char *params = *ppparams;
2148         char *data = *ppdata;
2149         size_t sd_size = 0;
2150         uint32_t security_info_wanted;
2151         files_struct *fsp = NULL;
2152         NTSTATUS status;
2153         uint8_t *marshalled_sd = NULL;
2154
2155         if(parameter_count < 8) {
2156                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2157                 return;
2158         }
2159
2160         fsp = file_fsp(req, SVAL(params,0));
2161         if(!fsp) {
2162                 reply_nterror(req, NT_STATUS_INVALID_HANDLE);
2163                 return;
2164         }
2165
2166         security_info_wanted = IVAL(params,4);
2167
2168         DEBUG(3,("call_nt_transact_query_security_desc: file = %s, "
2169                  "info_wanted = 0x%x\n", fsp_str_dbg(fsp),
2170                  (unsigned int)security_info_wanted));
2171
2172         params = nttrans_realloc(ppparams, 4);
2173         if(params == NULL) {
2174                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2175                 return;
2176         }
2177
2178         /*
2179          * Get the permissions to return.
2180          */
2181
2182         status = smbd_do_query_security_desc(conn,
2183                                         talloc_tos(),
2184                                         fsp,
2185                                         security_info_wanted &
2186                                         SMB_SUPPORTED_SECINFO_FLAGS,
2187                                         max_data_count,
2188                                         &marshalled_sd,
2189                                         &sd_size);
2190
2191         if (NT_STATUS_EQUAL(status, NT_STATUS_BUFFER_TOO_SMALL)) {
2192                 SIVAL(params,0,(uint32_t)sd_size);
2193                 send_nt_replies(conn, req, NT_STATUS_BUFFER_TOO_SMALL,
2194                         params, 4, NULL, 0);
2195                 return;
2196         }
2197
2198         if (!NT_STATUS_IS_OK(status)) {
2199                 reply_nterror(req, status);
2200                 return;
2201         }
2202
2203         SMB_ASSERT(sd_size > 0);
2204
2205         SIVAL(params,0,(uint32_t)sd_size);
2206
2207         if (max_data_count < sd_size) {
2208                 send_nt_replies(conn, req, NT_STATUS_BUFFER_TOO_SMALL,
2209                                 params, 4, NULL, 0);
2210                 return;
2211         }
2212
2213         /*
2214          * Allocate the data we will return.
2215          */
2216
2217         data = nttrans_realloc(ppdata, sd_size);
2218         if(data == NULL) {
2219                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2220                 return;
2221         }
2222
2223         memcpy(data, marshalled_sd, sd_size);
2224
2225         send_nt_replies(conn, req, NT_STATUS_OK, params, 4, data, (int)sd_size);
2226
2227         return;
2228 }
2229
2230 /****************************************************************************
2231  Reply to set a security descriptor. Map to UNIX perms or POSIX ACLs.
2232 ****************************************************************************/
2233
2234 static void call_nt_transact_set_security_desc(connection_struct *conn,
2235                                                struct smb_request *req,
2236                                                uint16_t **ppsetup,
2237                                                uint32_t setup_count,
2238                                                char **ppparams,
2239                                                uint32_t parameter_count,
2240                                                char **ppdata,
2241                                                uint32_t data_count,
2242                                                uint32_t max_data_count)
2243 {
2244         char *params= *ppparams;
2245         char *data = *ppdata;
2246         files_struct *fsp = NULL;
2247         uint32_t security_info_sent = 0;
2248         NTSTATUS status;
2249
2250         if(parameter_count < 8) {
2251                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2252                 return;
2253         }
2254
2255         if((fsp = file_fsp(req, SVAL(params,0))) == NULL) {
2256                 reply_nterror(req, NT_STATUS_INVALID_HANDLE);
2257                 return;
2258         }
2259
2260         if (!CAN_WRITE(fsp->conn)) {
2261                 reply_nterror(req, NT_STATUS_ACCESS_DENIED);
2262                 return;
2263         }
2264
2265         if(!lp_nt_acl_support(SNUM(conn))) {
2266                 goto done;
2267         }
2268
2269         security_info_sent = IVAL(params,4);
2270
2271         DEBUG(3,("call_nt_transact_set_security_desc: file = %s, sent 0x%x\n",
2272                  fsp_str_dbg(fsp), (unsigned int)security_info_sent));
2273
2274         if (data_count == 0) {
2275                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2276                 return;
2277         }
2278
2279         status = set_sd_blob(fsp, (uint8_t *)data, data_count,
2280                              security_info_sent & SMB_SUPPORTED_SECINFO_FLAGS);
2281         if (!NT_STATUS_IS_OK(status)) {
2282                 reply_nterror(req, status);
2283                 return;
2284         }
2285
2286   done:
2287         send_nt_replies(conn, req, NT_STATUS_OK, NULL, 0, NULL, 0);
2288         return;
2289 }
2290
2291 /****************************************************************************
2292  Reply to NT IOCTL
2293 ****************************************************************************/
2294
2295 static void call_nt_transact_ioctl(connection_struct *conn,
2296                                    struct smb_request *req,
2297                                    uint16_t **ppsetup, uint32_t setup_count,
2298                                    char **ppparams, uint32_t parameter_count,
2299                                    char **ppdata, uint32_t data_count,
2300                                    uint32_t max_data_count)
2301 {
2302         NTSTATUS status;
2303         uint32_t function;
2304         uint16_t fidnum;
2305         files_struct *fsp;
2306         uint8_t isFSctl;
2307         uint8_t compfilter;
2308         char *out_data = NULL;
2309         uint32_t out_data_len = 0;
2310         char *pdata = *ppdata;
2311         TALLOC_CTX *ctx = talloc_tos();
2312
2313         if (setup_count != 8) {
2314                 DEBUG(3,("call_nt_transact_ioctl: invalid setup count %d\n", setup_count));
2315                 reply_nterror(req, NT_STATUS_NOT_SUPPORTED);
2316                 return;
2317         }
2318
2319         function = IVAL(*ppsetup, 0);
2320         fidnum = SVAL(*ppsetup, 4);
2321         isFSctl = CVAL(*ppsetup, 6);
2322         compfilter = CVAL(*ppsetup, 7);
2323
2324         DEBUG(10, ("call_nt_transact_ioctl: function[0x%08X] FID[0x%04X] isFSctl[0x%02X] compfilter[0x%02X]\n", 
2325                  function, fidnum, isFSctl, compfilter));
2326
2327         fsp=file_fsp(req, fidnum);
2328
2329         /*
2330          * We don't really implement IOCTLs, especially on files.
2331          */
2332         if (!isFSctl) {
2333                 DEBUG(10, ("isFSctl: 0x%02X indicates IOCTL, not FSCTL!\n",
2334                         isFSctl));
2335                 reply_nterror(req, NT_STATUS_NOT_SUPPORTED);
2336                 return;
2337         }
2338
2339         /* Has to be for an open file! */
2340         if (!check_fsp_open(conn, req, fsp)) {
2341                 return;
2342         }
2343
2344         SMB_PERFCOUNT_SET_IOCTL(&req->pcd, function);
2345
2346         /*
2347          * out_data might be allocated by the VFS module, but talloc should be
2348          * used, and should be cleaned up when the request ends.
2349          */
2350         status = SMB_VFS_FSCTL(fsp, 
2351                                ctx,
2352                                function, 
2353                                req->flags2,
2354                                (uint8_t *)pdata, 
2355                                data_count, 
2356                                (uint8_t **)&out_data,
2357                                max_data_count,
2358                                &out_data_len);
2359         if (!NT_STATUS_IS_OK(status)) {
2360                 reply_nterror(req, status);
2361         } else {
2362                 send_nt_replies(conn, req, NT_STATUS_OK, NULL, 0, out_data, out_data_len);
2363         }
2364 }
2365
2366
2367 #ifdef HAVE_SYS_QUOTAS
2368 static enum ndr_err_code fill_qtlist_from_sids(TALLOC_CTX *mem_ctx,
2369                                                struct files_struct *fsp,
2370                                                SMB_NTQUOTA_HANDLE *qt_handle,
2371                                                struct dom_sid *sids,
2372                                                uint32_t elems)
2373 {
2374         uint32_t i;
2375         TALLOC_CTX *list_ctx = NULL;
2376
2377         list_ctx = talloc_init("quota_sid_list");
2378
2379         if (list_ctx == NULL) {
2380                 DBG_ERR("failed to allocate\n");
2381                 return NDR_ERR_ALLOC;
2382         }
2383
2384         if (qt_handle->quota_list!=NULL) {
2385                 free_ntquota_list(&(qt_handle->quota_list));
2386         }
2387         for (i = 0; i < elems; i++) {
2388                 SMB_NTQUOTA_STRUCT qt;
2389                 SMB_NTQUOTA_LIST *list_item;
2390                 bool ok;
2391
2392                 if (!NT_STATUS_IS_OK(vfs_get_ntquota(fsp,
2393                                                      SMB_USER_QUOTA_TYPE,
2394                                                      &sids[i], &qt))) {
2395                         /* non fatal error, return empty item in result */
2396                         ZERO_STRUCT(qt);
2397                         continue;
2398                 }
2399
2400
2401                 list_item = talloc_zero(list_ctx, SMB_NTQUOTA_LIST);
2402                 if (list_item == NULL) {
2403                         DBG_ERR("failed to allocate\n");
2404                         return NDR_ERR_ALLOC;
2405                 }
2406
2407                 ok = sid_to_uid(&sids[i], &list_item->uid);
2408                 if (!ok) {
2409                         struct dom_sid_buf buf;
2410                         DBG_WARNING("Could not convert SID %s to uid\n",
2411                                     dom_sid_str_buf(&sids[i], &buf));
2412                         /* No idea what to return here... */
2413                         return NDR_ERR_INVALID_POINTER;
2414                 }
2415
2416                 list_item->quotas = talloc_zero(list_item, SMB_NTQUOTA_STRUCT);
2417                 if (list_item->quotas == NULL) {
2418                         DBG_ERR("failed to allocate\n");
2419                         return NDR_ERR_ALLOC;
2420                 }
2421
2422                 *list_item->quotas = qt;
2423                 list_item->mem_ctx = list_ctx;
2424                 DLIST_ADD(qt_handle->quota_list, list_item);
2425         }
2426         qt_handle->tmp_list = qt_handle->quota_list;
2427         return NDR_ERR_SUCCESS;
2428 }
2429
2430 static enum ndr_err_code extract_sids_from_buf(TALLOC_CTX *mem_ctx,
2431                                   uint32_t sidlistlength,
2432                                   DATA_BLOB *sid_buf,
2433                                   struct dom_sid **sids,
2434                                   uint32_t *num)
2435 {
2436         DATA_BLOB blob;
2437         uint32_t i = 0;
2438         enum ndr_err_code err;
2439
2440         struct sid_list_elem {
2441                 struct sid_list_elem *prev, *next;
2442                 struct dom_sid sid;
2443         };
2444
2445         struct sid_list_elem *sid_list = NULL;
2446         struct sid_list_elem *iter = NULL;
2447         TALLOC_CTX *list_ctx = talloc_init("sid_list");
2448         if (!list_ctx) {
2449                 DBG_ERR("OOM\n");
2450                 err = NDR_ERR_ALLOC;
2451                 goto done;
2452         }
2453
2454         *num = 0;
2455         *sids = NULL;
2456
2457         if (sidlistlength) {
2458                 uint32_t offset = 0;
2459                 struct ndr_pull *ndr_pull = NULL;
2460
2461                 if (sidlistlength > sid_buf->length) {
2462                         DBG_ERR("sid_list_length 0x%x exceeds "
2463                                 "available bytes %zx\n",
2464                                 sidlistlength,
2465                                 sid_buf->length);
2466                         err = NDR_ERR_OFFSET;
2467                         goto done;
2468                 }
2469                 while (true) {
2470                         struct file_get_quota_info info;
2471                         struct sid_list_elem *item = NULL;
2472                         uint32_t new_offset = 0;
2473                         blob.data = sid_buf->data + offset;
2474                         blob.length = sidlistlength - offset;
2475                         ndr_pull = ndr_pull_init_blob(&blob, list_ctx);
2476                         if (!ndr_pull) {
2477                                 DBG_ERR("OOM\n");
2478                                 err = NDR_ERR_ALLOC;
2479                                 goto done;
2480                         }
2481                         err = ndr_pull_file_get_quota_info(ndr_pull,
2482                                            NDR_SCALARS | NDR_BUFFERS, &info);
2483                         if (!NDR_ERR_CODE_IS_SUCCESS(err)) {
2484                                 DBG_ERR("Failed to pull file_get_quota_info "
2485                                         "from sidlist buffer\n");
2486                                 goto done;
2487                         }
2488                         item = talloc_zero(list_ctx, struct sid_list_elem);
2489                         if (!item) {
2490                                 DBG_ERR("OOM\n");
2491                                 err = NDR_ERR_ALLOC;
2492                                 goto done;
2493                         }
2494                         item->sid = info.sid;
2495                         DLIST_ADD(sid_list, item);
2496                         i++;
2497                         if (i == UINT32_MAX) {
2498                                 DBG_ERR("Integer overflow\n");
2499                                 err = NDR_ERR_ARRAY_SIZE;
2500                                 goto done;
2501                         }
2502                         new_offset = info.next_entry_offset;
2503
2504                         /* if new_offset == 0 no more sid(s) to read. */
2505                         if (new_offset == 0) {
2506                                 break;
2507                         }
2508
2509                         /* Integer wrap? */
2510                         if ((offset + new_offset) < offset) {
2511                                 DBG_ERR("Integer wrap while adding "
2512                                         "new_offset 0x%x to current "
2513                                         "buffer offset 0x%x\n",
2514                                         new_offset, offset);
2515                                 err = NDR_ERR_OFFSET;
2516                                 goto done;
2517                         }
2518
2519                         offset += new_offset;
2520
2521                         /* check if new offset is outside buffer boundry. */
2522                         if (offset >= sidlistlength) {
2523                                 DBG_ERR("bufsize 0x%x exceeded by "
2524                                         "new offset 0x%x)\n",
2525                                         sidlistlength,
2526                                         offset);
2527                                 err = NDR_ERR_OFFSET;
2528                                 goto done;
2529                         }
2530                 }
2531                 *sids = talloc_zero_array(mem_ctx, struct dom_sid, i);
2532                 if (*sids == NULL) {
2533                         DBG_ERR("OOM\n");
2534                         err = NDR_ERR_ALLOC;
2535                         goto done;
2536                 }
2537
2538                 *num = i;
2539
2540                 for (iter = sid_list, i = 0; iter; iter = iter->next, i++) {
2541                         struct dom_sid_buf buf;
2542                         (*sids)[i] = iter->sid;
2543                         DBG_DEBUG("quota SID[%u] %s\n",
2544                                 (unsigned int)i,
2545                                 dom_sid_str_buf(&iter->sid, &buf));
2546                 }
2547         }
2548         err = NDR_ERR_SUCCESS;
2549 done:
2550         TALLOC_FREE(list_ctx);
2551         return err;
2552 }
2553
2554 NTSTATUS smbd_do_query_getinfo_quota(TALLOC_CTX *mem_ctx,
2555                                      files_struct *fsp,
2556                                      bool restart_scan,
2557                                      bool return_single,
2558                                      uint32_t sid_list_length,
2559                                      DATA_BLOB *sid_buf,
2560                                      uint32_t max_data_count,
2561                                      uint8_t **p_data,
2562                                      uint32_t *p_data_size)
2563 {
2564         NTSTATUS status;
2565         SMB_NTQUOTA_HANDLE *qt_handle = NULL;
2566         SMB_NTQUOTA_LIST *qt_list = NULL;
2567         DATA_BLOB blob = data_blob_null;
2568         enum ndr_err_code err;
2569
2570         qt_handle =
2571                 (SMB_NTQUOTA_HANDLE *)fsp->fake_file_handle->private_data;
2572
2573         if (sid_list_length ) {
2574                 struct dom_sid *sids;
2575                 uint32_t elems = 0;
2576                 /*
2577                  * error check pulled offsets and lengths for wrap and
2578                  * exceeding available bytes.
2579                  */
2580                 if (sid_list_length > sid_buf->length) {
2581                         DBG_ERR("sid_list_length 0x%x exceeds "
2582                                 "available bytes %zx\n",
2583                                 sid_list_length,
2584                                 sid_buf->length);
2585                         return NT_STATUS_INVALID_PARAMETER;
2586                 }
2587
2588                 err = extract_sids_from_buf(mem_ctx, sid_list_length,
2589                                             sid_buf, &sids, &elems);
2590                 if (!NDR_ERR_CODE_IS_SUCCESS(err) || elems == 0) {
2591                         return NT_STATUS_INVALID_PARAMETER;
2592                 }
2593                 err = fill_qtlist_from_sids(mem_ctx,
2594                                             fsp,
2595                                             qt_handle,
2596                                             sids,
2597                                             elems);
2598                 if (!NDR_ERR_CODE_IS_SUCCESS(err)) {
2599                         return NT_STATUS_INVALID_PARAMETER;
2600                 }
2601         } else if (restart_scan) {
2602                 if (vfs_get_user_ntquota_list(fsp,
2603                                               &(qt_handle->quota_list))!=0) {
2604                         return NT_STATUS_INTERNAL_ERROR;
2605                 }
2606         } else {
2607                 if (qt_handle->quota_list!=NULL &&
2608                         qt_handle->tmp_list==NULL) {
2609                         free_ntquota_list(&(qt_handle->quota_list));
2610                 }
2611         }
2612
2613         if (restart_scan !=0 ) {
2614                 qt_list = qt_handle->quota_list;
2615         } else {
2616                 qt_list = qt_handle->tmp_list;
2617         }
2618         status = fill_quota_buffer(mem_ctx, qt_list,
2619                                    return_single != 0,
2620                                    max_data_count,
2621                                    &blob,
2622                                    &qt_handle->tmp_list);
2623         if (!NT_STATUS_IS_OK(status)) {
2624                 return status;
2625         }
2626         if (blob.length > max_data_count) {
2627                 return NT_STATUS_BUFFER_TOO_SMALL;
2628         }
2629
2630         *p_data = blob.data;
2631         *p_data_size = blob.length;
2632         return NT_STATUS_OK;
2633 }
2634
2635 /****************************************************************************
2636  Reply to get user quota
2637 ****************************************************************************/
2638
2639 static void call_nt_transact_get_user_quota(connection_struct *conn,
2640                                             struct smb_request *req,
2641                                             uint16_t **ppsetup,
2642                                             uint32_t setup_count,
2643                                             char **ppparams,
2644                                             uint32_t parameter_count,
2645                                             char **ppdata,
2646                                             uint32_t data_count,
2647                                             uint32_t max_data_count)
2648 {
2649         const struct loadparm_substitution *lp_sub =
2650                 loadparm_s3_global_substitution();
2651         NTSTATUS nt_status = NT_STATUS_OK;
2652         char *params = *ppparams;
2653         char *pdata = *ppdata;
2654         int data_len = 0;
2655         int param_len = 0;
2656         files_struct *fsp = NULL;
2657         DATA_BLOB blob = data_blob_null;
2658         struct nttrans_query_quota_params info = {0};
2659         enum ndr_err_code err;
2660         TALLOC_CTX *tmp_ctx = NULL;
2661         uint32_t resp_len = 0;
2662         uint8_t *resp_data = 0;
2663
2664         tmp_ctx = talloc_init("ntquota_list");
2665         if (!tmp_ctx) {
2666                 nt_status = NT_STATUS_NO_MEMORY;
2667                 goto error;
2668         }
2669
2670         /* access check */
2671         if (get_current_uid(conn) != sec_initial_uid()) {
2672                 DEBUG(1,("get_user_quota: access_denied service [%s] user "
2673                          "[%s]\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn)),
2674                          conn->session_info->unix_info->unix_name));
2675                 nt_status = NT_STATUS_ACCESS_DENIED;
2676                 goto error;
2677         }
2678
2679         blob.data = (uint8_t*)params;
2680         blob.length = parameter_count;
2681
2682         err = ndr_pull_struct_blob(&blob, tmp_ctx, &info,
2683                 (ndr_pull_flags_fn_t)ndr_pull_nttrans_query_quota_params);
2684
2685         if (!NDR_ERR_CODE_IS_SUCCESS(err)) {
2686                 DEBUG(0,("TRANSACT_GET_USER_QUOTA: failed to pull "
2687                          "query_quota_params."));
2688                 nt_status = NT_STATUS_INVALID_PARAMETER;
2689                 goto error;
2690         }
2691         DBG_DEBUG("info.return_single_entry = %u, info.restart_scan = %u, "
2692                   "info.sid_list_length = %u, info.start_sid_length = %u, "
2693                   "info.start_sid_offset = %u\n",
2694                   (unsigned int)info.return_single_entry,
2695                   (unsigned int)info.restart_scan,
2696                   (unsigned int)info.sid_list_length,
2697                   (unsigned int)info.start_sid_length,
2698                   (unsigned int)info.start_sid_offset);
2699
2700         /* set blob to point at data for further parsing */
2701         blob.data = (uint8_t*)pdata;
2702         blob.length = data_count;
2703         /*
2704          * Although MS-SMB ref is ambiguous here, a microsoft client will
2705          * only ever send a start sid (as part of a list) with
2706          * sid_list_length & start_sid_offset both set to the actual list
2707          * length. Note: Only a single result is returned in this case
2708          * In the case where either start_sid_offset or start_sid_length
2709          * are set alone or if both set (but have different values) then
2710          * it seems windows will return a number of entries from the start
2711          * of the list of users with quotas set. This behaviour is undocumented
2712          * and windows clients do not send messages of that type. As such we
2713          * currently will reject these requests.
2714          */
2715         if (info.start_sid_length
2716         || (info.sid_list_length != info.start_sid_offset)) {
2717                 DBG_ERR("TRANSACT_GET_USER_QUOTA: unsupported single or "
2718                         "compound sid format\n");
2719                 nt_status = NT_STATUS_INVALID_PARAMETER;
2720                 goto error;
2721         }
2722
2723         /* maybe we can check the quota_fnum */
2724         fsp = file_fsp(req, info.fid);
2725         if (!check_fsp_ntquota_handle(conn, req, fsp)) {
2726                 DEBUG(3,("TRANSACT_GET_USER_QUOTA: no valid QUOTA HANDLE\n"));
2727                 nt_status = NT_STATUS_INVALID_HANDLE;
2728                 goto error;
2729         }
2730         nt_status = smbd_do_query_getinfo_quota(tmp_ctx,
2731                                   fsp,
2732                                   info.restart_scan,
2733                                   info.return_single_entry,
2734                                   info.sid_list_length,
2735                                   &blob,
2736                                   max_data_count,
2737                                   &resp_data,
2738                                   &resp_len);
2739         if (!NT_STATUS_IS_OK(nt_status)) {
2740                 if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MORE_ENTRIES)) {
2741                         goto error;
2742                 }
2743                 nt_status = NT_STATUS_OK;
2744         }
2745
2746         param_len = 4;
2747         params = nttrans_realloc(ppparams, param_len);
2748         if(params == NULL) {
2749                 nt_status = NT_STATUS_NO_MEMORY;
2750                 goto error;
2751         }
2752
2753         data_len = resp_len;
2754         SIVAL(params, 0, data_len);
2755         pdata = nttrans_realloc(ppdata, data_len);
2756         memcpy(pdata, resp_data, data_len);
2757
2758         TALLOC_FREE(tmp_ctx);
2759         send_nt_replies(conn, req, nt_status, params, param_len,
2760                         pdata, data_len);
2761         return;
2762 error:
2763         TALLOC_FREE(tmp_ctx);
2764         reply_nterror(req, nt_status);
2765 }
2766
2767 /****************************************************************************
2768  Reply to set user quota
2769 ****************************************************************************/
2770
2771 static void call_nt_transact_set_user_quota(connection_struct *conn,
2772                                             struct smb_request *req,
2773                                             uint16_t **ppsetup,
2774                                             uint32_t setup_count,
2775                                             char **ppparams,
2776                                             uint32_t parameter_count,
2777                                             char **ppdata,
2778                                             uint32_t data_count,
2779                                             uint32_t max_data_count)
2780 {
2781         const struct loadparm_substitution *lp_sub =
2782                 loadparm_s3_global_substitution();
2783         char *params = *ppparams;
2784         char *pdata = *ppdata;
2785         int data_len=0,param_len=0;
2786         SMB_NTQUOTA_STRUCT qt;
2787         struct file_quota_information info = {0};
2788         enum ndr_err_code err;
2789         struct dom_sid sid;
2790         DATA_BLOB inblob;
2791         files_struct *fsp = NULL;
2792         TALLOC_CTX *ctx = NULL;
2793         NTSTATUS status = NT_STATUS_OK;
2794         ZERO_STRUCT(qt);
2795
2796         /* access check */
2797         if (get_current_uid(conn) != sec_initial_uid()) {
2798                 DEBUG(1,("set_user_quota: access_denied service [%s] user "
2799                          "[%s]\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn)),
2800                          conn->session_info->unix_info->unix_name));
2801                 status = NT_STATUS_ACCESS_DENIED;
2802                 goto error;
2803         }
2804
2805         /*
2806          * Ensure minimum number of parameters sent.
2807          */
2808
2809         if (parameter_count < 2) {
2810                 DEBUG(0,("TRANSACT_SET_USER_QUOTA: requires %d >= 2 bytes parameters\n",parameter_count));
2811                 status = NT_STATUS_INVALID_PARAMETER;
2812                 goto error;
2813         }
2814
2815         /* maybe we can check the quota_fnum */
2816         fsp = file_fsp(req, SVAL(params,0));
2817         if (!check_fsp_ntquota_handle(conn, req, fsp)) {
2818                 DEBUG(3,("TRANSACT_GET_USER_QUOTA: no valid QUOTA HANDLE\n"));
2819                 status = NT_STATUS_INVALID_HANDLE;
2820                 goto error;
2821         }
2822
2823         ctx = talloc_init("set_user_quota");
2824         if (!ctx) {
2825                 status = NT_STATUS_NO_MEMORY;
2826                 goto error;
2827         }
2828         inblob.data = (uint8_t*)pdata;
2829         inblob.length = data_count;
2830
2831         err = ndr_pull_struct_blob(
2832                         &inblob,
2833                         ctx,
2834                         &info,
2835                         (ndr_pull_flags_fn_t)ndr_pull_file_quota_information);
2836
2837         if (!NDR_ERR_CODE_IS_SUCCESS(err)) {
2838                 DEBUG(0,("TRANSACT_SET_USER_QUOTA: failed to pull "
2839                          "file_quota_information\n"));
2840                 status = NT_STATUS_INVALID_PARAMETER;
2841                 goto error;
2842         }
2843         qt.usedspace = info.quota_used;
2844
2845         qt.softlim = info.quota_threshold;
2846
2847         qt.hardlim = info.quota_limit;
2848
2849         sid = info.sid;
2850
2851         if (vfs_set_ntquota(fsp, SMB_USER_QUOTA_TYPE, &sid, &qt)!=0) {
2852                 status = NT_STATUS_INTERNAL_ERROR;
2853                 goto error;
2854         }
2855
2856         send_nt_replies(conn, req, NT_STATUS_OK, params, param_len,
2857                         pdata, data_len);
2858         TALLOC_FREE(ctx);
2859         return;
2860 error:
2861         TALLOC_FREE(ctx);
2862         reply_nterror(req, status);
2863 }
2864 #endif /* HAVE_SYS_QUOTAS */
2865
2866 static void handle_nttrans(connection_struct *conn,
2867                            struct trans_state *state,
2868                            struct smb_request *req)
2869 {
2870         if (get_Protocol() >= PROTOCOL_NT1) {
2871                 req->flags2 |= 0x40; /* IS_LONG_NAME */
2872                 SSVAL(discard_const_p(uint8_t, req->inbuf),smb_flg2,req->flags2);
2873         }
2874
2875
2876         SMB_PERFCOUNT_SET_SUBOP(&req->pcd, state->call);
2877
2878         /* Now we must call the relevant NT_TRANS function */
2879         switch(state->call) {
2880                 case NT_TRANSACT_CREATE:
2881                 {
2882                         START_PROFILE(NT_transact_create);
2883                         call_nt_transact_create(
2884                                 conn, req,
2885                                 &state->setup, state->setup_count,
2886                                 &state->param, state->total_param,
2887                                 &state->data, state->total_data,
2888                                 state->max_data_return);
2889                         END_PROFILE(NT_transact_create);
2890                         break;
2891                 }
2892
2893                 case NT_TRANSACT_IOCTL:
2894                 {
2895                         START_PROFILE(NT_transact_ioctl);
2896                         call_nt_transact_ioctl(
2897                                 conn, req,
2898                                 &state->setup, state->setup_count,
2899                                 &state->param, state->total_param,
2900                                 &state->data, state->total_data,
2901                                 state->max_data_return);
2902                         END_PROFILE(NT_transact_ioctl);
2903                         break;
2904                 }
2905
2906                 case NT_TRANSACT_SET_SECURITY_DESC:
2907                 {
2908                         START_PROFILE(NT_transact_set_security_desc);
2909                         call_nt_transact_set_security_desc(
2910                                 conn, req,
2911                                 &state->setup, state->setup_count,
2912                                 &state->param, state->total_param,
2913                                 &state->data, state->total_data,
2914                                 state->max_data_return);
2915                         END_PROFILE(NT_transact_set_security_desc);
2916                         break;
2917                 }
2918
2919                 case NT_TRANSACT_NOTIFY_CHANGE:
2920                 {
2921                         START_PROFILE(NT_transact_notify_change);
2922                         call_nt_transact_notify_change(
2923                                 conn, req,
2924                                 &state->setup, state->setup_count,
2925                                 &state->param, state->total_param,
2926                                 &state->data, state->total_data,
2927                                 state->max_data_return,
2928                                 state->max_param_return);
2929                         END_PROFILE(NT_transact_notify_change);
2930                         break;
2931                 }
2932
2933                 case NT_TRANSACT_RENAME:
2934                 {
2935                         START_PROFILE(NT_transact_rename);
2936                         call_nt_transact_rename(
2937                                 conn, req,
2938                                 &state->setup, state->setup_count,
2939                                 &state->param, state->total_param,
2940                                 &state->data, state->total_data,
2941                                 state->max_data_return);
2942                         END_PROFILE(NT_transact_rename);
2943                         break;
2944                 }
2945
2946                 case NT_TRANSACT_QUERY_SECURITY_DESC:
2947                 {
2948                         START_PROFILE(NT_transact_query_security_desc);
2949                         call_nt_transact_query_security_desc(
2950                                 conn, req,
2951                                 &state->setup, state->setup_count,
2952                                 &state->param, state->total_param,
2953                                 &state->data, state->total_data,
2954                                 state->max_data_return);
2955                         END_PROFILE(NT_transact_query_security_desc);
2956                         break;
2957                 }
2958
2959 #ifdef HAVE_SYS_QUOTAS
2960                 case NT_TRANSACT_GET_USER_QUOTA:
2961                 {
2962                         START_PROFILE(NT_transact_get_user_quota);
2963                         call_nt_transact_get_user_quota(
2964                                 conn, req,
2965                                 &state->setup, state->setup_count,
2966                                 &state->param, state->total_param,
2967                                 &state->data, state->total_data,
2968                                 state->max_data_return);
2969                         END_PROFILE(NT_transact_get_user_quota);
2970                         break;
2971                 }
2972
2973                 case NT_TRANSACT_SET_USER_QUOTA:
2974                 {
2975                         START_PROFILE(NT_transact_set_user_quota);
2976                         call_nt_transact_set_user_quota(
2977                                 conn, req,
2978                                 &state->setup, state->setup_count,
2979                                 &state->param, state->total_param,
2980                                 &state->data, state->total_data,
2981                                 state->max_data_return);
2982                         END_PROFILE(NT_transact_set_user_quota);
2983                         break;
2984                 }
2985 #endif /* HAVE_SYS_QUOTAS */
2986
2987                 default:
2988                         /* Error in request */
2989                         DEBUG(0,("handle_nttrans: Unknown request %d in "
2990                                  "nttrans call\n", state->call));
2991                         reply_nterror(req, NT_STATUS_INVALID_LEVEL);
2992                         return;
2993         }
2994         return;
2995 }
2996
2997 /****************************************************************************
2998  Reply to a SMBNTtrans.
2999 ****************************************************************************/
3000
3001 void reply_nttrans(struct smb_request *req)
3002 {
3003         connection_struct *conn = req->conn;
3004         uint32_t pscnt;
3005         uint32_t psoff;
3006         uint32_t dscnt;
3007         uint32_t dsoff;
3008         uint16_t function_code;
3009         NTSTATUS result;
3010         struct trans_state *state;
3011
3012         START_PROFILE(SMBnttrans);
3013
3014         if (req->wct < 19) {
3015                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
3016                 END_PROFILE(SMBnttrans);
3017                 return;
3018         }
3019
3020         pscnt = IVAL(req->vwv+9, 1);
3021         psoff = IVAL(req->vwv+11, 1);
3022         dscnt = IVAL(req->vwv+13, 1);
3023         dsoff = IVAL(req->vwv+15, 1);
3024         function_code = SVAL(req->vwv+18, 0);
3025
3026         if (IS_IPC(conn) && (function_code != NT_TRANSACT_CREATE)) {
3027                 reply_nterror(req, NT_STATUS_ACCESS_DENIED);
3028                 END_PROFILE(SMBnttrans);
3029                 return;
3030         }
3031
3032         result = allow_new_trans(conn->pending_trans, req->mid);
3033         if (!NT_STATUS_IS_OK(result)) {
3034                 DEBUG(2, ("Got invalid nttrans request: %s\n", nt_errstr(result)));
3035                 reply_nterror(req, result);
3036                 END_PROFILE(SMBnttrans);
3037                 return;
3038         }
3039
3040         if ((state = talloc(conn, struct trans_state)) == NULL) {
3041                 reply_nterror(req, NT_STATUS_NO_MEMORY);
3042                 END_PROFILE(SMBnttrans);
3043                 return;
3044         }
3045
3046         state->cmd = SMBnttrans;
3047
3048         state->mid = req->mid;
3049         state->vuid = req->vuid;
3050         state->total_data = IVAL(req->vwv+3, 1);
3051         state->data = NULL;
3052         state->total_param = IVAL(req->vwv+1, 1);
3053         state->param = NULL;
3054         state->max_data_return = IVAL(req->vwv+7, 1);
3055         state->max_param_return = IVAL(req->vwv+5, 1);
3056
3057         /* setup count is in *words* */
3058         state->setup_count = 2*CVAL(req->vwv+17, 1);
3059         state->setup = NULL;
3060         state->call = function_code;
3061
3062         DEBUG(10, ("num_setup=%u, "
3063                    "param_total=%u, this_param=%u, max_param=%u, "
3064                    "data_total=%u, this_data=%u, max_data=%u, "
3065                    "param_offset=%u, data_offset=%u\n",
3066                    (unsigned)state->setup_count,
3067                    (unsigned)state->total_param, (unsigned)pscnt,
3068                    (unsigned)state->max_param_return,
3069                    (unsigned)state->total_data, (unsigned)dscnt,
3070                    (unsigned)state->max_data_return,
3071                    (unsigned)psoff, (unsigned)dsoff));
3072
3073         /*
3074          * All nttrans messages we handle have smb_wct == 19 +
3075          * state->setup_count.  Ensure this is so as a sanity check.
3076          */
3077
3078         if(req->wct != 19 + (state->setup_count/2)) {
3079                 DEBUG(2,("Invalid smb_wct %d in nttrans call (should be %d)\n",
3080                          req->wct, 19 + (state->setup_count/2)));
3081                 goto bad_param;
3082         }
3083
3084         /* Don't allow more than 128mb for each value. */
3085         if ((state->total_data > (1024*1024*128)) ||
3086             (state->total_param > (1024*1024*128))) {
3087                 reply_nterror(req, NT_STATUS_NO_MEMORY);
3088                 END_PROFILE(SMBnttrans);
3089                 return;
3090         }
3091
3092         if ((dscnt > state->total_data) || (pscnt > state->total_param))
3093                 goto bad_param;
3094
3095         if (state->total_data)  {
3096
3097                 if (trans_oob(state->total_data, 0, dscnt)
3098                     || trans_oob(smb_len(req->inbuf), dsoff, dscnt)) {
3099                         goto bad_param;
3100                 }
3101
3102                 /* Can't use talloc here, the core routines do realloc on the
3103                  * params and data. */
3104                 if ((state->data = (char *)SMB_MALLOC(state->total_data)) == NULL) {
3105                         DEBUG(0,("reply_nttrans: data malloc fail for %u "
3106                                  "bytes !\n", (unsigned int)state->total_data));
3107                         TALLOC_FREE(state);
3108                         reply_nterror(req, NT_STATUS_NO_MEMORY);
3109                         END_PROFILE(SMBnttrans);
3110                         return;
3111                 }
3112
3113                 memcpy(state->data,smb_base(req->inbuf)+dsoff,dscnt);
3114         }
3115
3116         if (state->total_param) {
3117
3118                 if (trans_oob(state->total_param, 0, pscnt)
3119                     || trans_oob(smb_len(req->inbuf), psoff, pscnt)) {
3120                         goto bad_param;
3121                 }
3122
3123                 /* Can't use talloc here, the core routines do realloc on the
3124                  * params and data. */
3125                 if ((state->param = (char *)SMB_MALLOC(state->total_param)) == NULL) {
3126                         DEBUG(0,("reply_nttrans: param malloc fail for %u "
3127                                  "bytes !\n", (unsigned int)state->total_param));
3128                         SAFE_FREE(state->data);
3129                         TALLOC_FREE(state);
3130                         reply_nterror(req, NT_STATUS_NO_MEMORY);
3131                         END_PROFILE(SMBnttrans);
3132                         return;
3133                 }
3134
3135                 memcpy(state->param,smb_base(req->inbuf)+psoff,pscnt);
3136         }
3137
3138         state->received_data  = dscnt;
3139         state->received_param = pscnt;
3140
3141         if(state->setup_count > 0) {
3142                 DEBUG(10,("reply_nttrans: state->setup_count = %d\n",
3143                           state->setup_count));
3144
3145                 /*
3146                  * No overflow possible here, state->setup_count is an
3147                  * unsigned int, being filled by a single byte from
3148                  * CVAL(req->vwv+13, 0) above. The cast in the comparison
3149                  * below is not necessary, it's here to clarify things. The
3150                  * validity of req->vwv and req->wct has been checked in
3151                  * init_smb_request already.
3152                  */
3153                 if ((state->setup_count/2) + 19 > (unsigned int)req->wct) {
3154                         goto bad_param;
3155                 }
3156
3157                 state->setup = (uint16_t *)TALLOC(state, state->setup_count);
3158                 if (state->setup == NULL) {
3159                         DEBUG(0,("reply_nttrans : Out of memory\n"));
3160                         SAFE_FREE(state->data);
3161                         SAFE_FREE(state->param);
3162                         TALLOC_FREE(state);
3163                         reply_nterror(req, NT_STATUS_NO_MEMORY);
3164                         END_PROFILE(SMBnttrans);
3165                         return;
3166                 }
3167
3168                 memcpy(state->setup, req->vwv+19, state->setup_count);
3169                 dump_data(10, (uint8_t *)state->setup, state->setup_count);
3170         }
3171
3172         if ((state->received_data == state->total_data) &&
3173             (state->received_param == state->total_param)) {
3174                 handle_nttrans(conn, state, req);
3175                 SAFE_FREE(state->param);
3176                 SAFE_FREE(state->data);
3177                 TALLOC_FREE(state);
3178                 END_PROFILE(SMBnttrans);
3179                 return;
3180         }
3181
3182         DLIST_ADD(conn->pending_trans, state);
3183
3184         /* We need to send an interim response then receive the rest
3185            of the parameter/data bytes */
3186         reply_outbuf(req, 0, 0);
3187         show_msg((char *)req->outbuf);
3188         END_PROFILE(SMBnttrans);
3189         return;
3190
3191   bad_param:
3192
3193         DEBUG(0,("reply_nttrans: invalid trans parameters\n"));
3194         SAFE_FREE(state->data);
3195         SAFE_FREE(state->param);
3196         TALLOC_FREE(state);
3197         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
3198         END_PROFILE(SMBnttrans);
3199         return;
3200 }
3201
3202 /****************************************************************************
3203  Reply to a SMBnttranss
3204  ****************************************************************************/
3205
3206 void reply_nttranss(struct smb_request *req)
3207 {
3208         connection_struct *conn = req->conn;
3209         uint32_t pcnt,poff,dcnt,doff,pdisp,ddisp;
3210         struct trans_state *state;
3211
3212         START_PROFILE(SMBnttranss);
3213
3214         show_msg((const char *)req->inbuf);
3215
3216         /* Windows clients expect all replies to
3217            an NT transact secondary (SMBnttranss 0xA1)
3218            to have a command code of NT transact
3219            (SMBnttrans 0xA0). See bug #8989 for details. */
3220         req->cmd = SMBnttrans;
3221
3222         if (req->wct < 18) {
3223                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);