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