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