s3: only include smb profiling where needed.
[nivanova/samba-autobuild/.git] / source3 / smbd / trans2.c
1 /*
2    Unix SMB/CIFS implementation.
3    SMB transaction2 handling
4    Copyright (C) Jeremy Allison                 1994-2007
5    Copyright (C) Stefan (metze) Metzmacher      2003
6    Copyright (C) Volker Lendecke                2005-2007
7    Copyright (C) Steve French                   2005
8    Copyright (C) James Peach                    2006-2007
9
10    Extensively modified by Andrew Tridgell, 1995
11
12    This program is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3 of the License, or
15    (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 */
25
26 #include "includes.h"
27 #include "system/filesys.h"
28 #include "version.h"
29 #include "smbd/smbd.h"
30 #include "smbd/globals.h"
31 #include "../libcli/auth/libcli_auth.h"
32 #include "../librpc/gen_ndr/xattr.h"
33 #include "../librpc/gen_ndr/ndr_security.h"
34 #include "libcli/security/security.h"
35 #include "trans2.h"
36 #include "auth.h"
37 #include "smbprofile.h"
38
39 #define DIR_ENTRY_SAFETY_MARGIN 4096
40
41 static char *store_file_unix_basic(connection_struct *conn,
42                                 char *pdata,
43                                 files_struct *fsp,
44                                 const SMB_STRUCT_STAT *psbuf);
45
46 static char *store_file_unix_basic_info2(connection_struct *conn,
47                                 char *pdata,
48                                 files_struct *fsp,
49                                 const SMB_STRUCT_STAT *psbuf);
50
51 /********************************************************************
52  Roundup a value to the nearest allocation roundup size boundary.
53  Only do this for Windows clients.
54 ********************************************************************/
55
56 uint64_t smb_roundup(connection_struct *conn, uint64_t val)
57 {
58         uint64_t rval = lp_allocation_roundup_size(SNUM(conn));
59
60         /* Only roundup for Windows clients. */
61         enum remote_arch_types ra_type = get_remote_arch();
62         if (rval && (ra_type != RA_SAMBA) && (ra_type != RA_CIFSFS)) {
63                 val = SMB_ROUNDUP(val,rval);
64         }
65         return val;
66 }
67
68 /********************************************************************
69  Create a 64 bit FileIndex. If the file is on the same device as
70  the root of the share, just return the 64-bit inode. If it isn't,
71  mangle as we used to do.
72 ********************************************************************/
73
74 uint64_t get_FileIndex(connection_struct *conn, const SMB_STRUCT_STAT *psbuf)
75 {
76         uint64_t file_index;
77         if (conn->base_share_dev == psbuf->st_ex_dev) {
78                 return (uint64_t)psbuf->st_ex_ino;
79         }
80         file_index = ((psbuf->st_ex_ino) & UINT32_MAX); /* FileIndexLow */
81         file_index |= ((uint64_t)((psbuf->st_ex_dev) & UINT32_MAX)) << 32; /* FileIndexHigh */
82         return file_index;
83 }
84
85 /****************************************************************************
86  Utility functions for dealing with extended attributes.
87 ****************************************************************************/
88
89 /****************************************************************************
90  Refuse to allow clients to overwrite our private xattrs.
91 ****************************************************************************/
92
93 static bool samba_private_attr_name(const char *unix_ea_name)
94 {
95         static const char * const prohibited_ea_names[] = {
96                 SAMBA_POSIX_INHERITANCE_EA_NAME,
97                 SAMBA_XATTR_DOS_ATTRIB,
98                 SAMBA_XATTR_MARKER,
99                 XATTR_NTACL_NAME,
100                 NULL
101         };
102
103         int i;
104
105         for (i = 0; prohibited_ea_names[i]; i++) {
106                 if (strequal( prohibited_ea_names[i], unix_ea_name))
107                         return true;
108         }
109         if (StrnCaseCmp(unix_ea_name, SAMBA_XATTR_DOSSTREAM_PREFIX,
110                         strlen(SAMBA_XATTR_DOSSTREAM_PREFIX)) == 0) {
111                 return true;
112         }
113         return false;
114 }
115
116 /****************************************************************************
117  Get one EA value. Fill in a struct ea_struct.
118 ****************************************************************************/
119
120 NTSTATUS get_ea_value(TALLOC_CTX *mem_ctx, connection_struct *conn,
121                       files_struct *fsp, const char *fname,
122                       const char *ea_name, struct ea_struct *pea)
123 {
124         /* Get the value of this xattr. Max size is 64k. */
125         size_t attr_size = 256;
126         char *val = NULL;
127         ssize_t sizeret;
128
129  again:
130
131         val = TALLOC_REALLOC_ARRAY(mem_ctx, val, char, attr_size);
132         if (!val) {
133                 return NT_STATUS_NO_MEMORY;
134         }
135
136         if (fsp && fsp->fh->fd != -1) {
137                 sizeret = SMB_VFS_FGETXATTR(fsp, ea_name, val, attr_size);
138         } else {
139                 sizeret = SMB_VFS_GETXATTR(conn, fname, ea_name, val, attr_size);
140         }
141
142         if (sizeret == -1 && errno == ERANGE && attr_size != 65536) {
143                 attr_size = 65536;
144                 goto again;
145         }
146
147         if (sizeret == -1) {
148                 return map_nt_error_from_unix(errno);
149         }
150
151         DEBUG(10,("get_ea_value: EA %s is of length %u\n", ea_name, (unsigned int)sizeret));
152         dump_data(10, (uint8 *)val, sizeret);
153
154         pea->flags = 0;
155         if (strnequal(ea_name, "user.", 5)) {
156                 pea->name = talloc_strdup(mem_ctx, &ea_name[5]);
157         } else {
158                 pea->name = talloc_strdup(mem_ctx, ea_name);
159         }
160         if (pea->name == NULL) {
161                 TALLOC_FREE(val);
162                 return NT_STATUS_NO_MEMORY;
163         }
164         pea->value.data = (unsigned char *)val;
165         pea->value.length = (size_t)sizeret;
166         return NT_STATUS_OK;
167 }
168
169 NTSTATUS get_ea_names_from_file(TALLOC_CTX *mem_ctx, connection_struct *conn,
170                                 files_struct *fsp, const char *fname,
171                                 char ***pnames, size_t *pnum_names)
172 {
173         /* Get a list of all xattrs. Max namesize is 64k. */
174         size_t ea_namelist_size = 1024;
175         char *ea_namelist = NULL;
176
177         char *p;
178         char **names, **tmp;
179         size_t num_names;
180         ssize_t sizeret = -1;
181
182         if (!lp_ea_support(SNUM(conn))) {
183                 if (pnames) {
184                         *pnames = NULL;
185                 }
186                 *pnum_names = 0;
187                 return NT_STATUS_OK;
188         }
189
190         /*
191          * TALLOC the result early to get the talloc hierarchy right.
192          */
193
194         names = TALLOC_ARRAY(mem_ctx, char *, 1);
195         if (names == NULL) {
196                 DEBUG(0, ("talloc failed\n"));
197                 return NT_STATUS_NO_MEMORY;
198         }
199
200         while (ea_namelist_size <= 65536) {
201
202                 ea_namelist = TALLOC_REALLOC_ARRAY(
203                         names, ea_namelist, char, ea_namelist_size);
204                 if (ea_namelist == NULL) {
205                         DEBUG(0, ("talloc failed\n"));
206                         TALLOC_FREE(names);
207                         return NT_STATUS_NO_MEMORY;
208                 }
209
210                 if (fsp && fsp->fh->fd != -1) {
211                         sizeret = SMB_VFS_FLISTXATTR(fsp, ea_namelist,
212                                                      ea_namelist_size);
213                 } else {
214                         sizeret = SMB_VFS_LISTXATTR(conn, fname, ea_namelist,
215                                                     ea_namelist_size);
216                 }
217
218                 if ((sizeret == -1) && (errno == ERANGE)) {
219                         ea_namelist_size *= 2;
220                 }
221                 else {
222                         break;
223                 }
224         }
225
226         if (sizeret == -1) {
227                 TALLOC_FREE(names);
228                 return map_nt_error_from_unix(errno);
229         }
230
231         DEBUG(10, ("get_ea_list_from_file: ea_namelist size = %u\n",
232                    (unsigned int)sizeret));
233
234         if (sizeret == 0) {
235                 TALLOC_FREE(names);
236                 if (pnames) {
237                         *pnames = NULL;
238                 }
239                 *pnum_names = 0;
240                 return NT_STATUS_OK;
241         }
242
243         /*
244          * Ensure the result is 0-terminated
245          */
246
247         if (ea_namelist[sizeret-1] != '\0') {
248                 TALLOC_FREE(names);
249                 return NT_STATUS_INTERNAL_ERROR;
250         }
251
252         /*
253          * count the names
254          */
255         num_names = 0;
256
257         for (p = ea_namelist; p - ea_namelist < sizeret; p += strlen(p)+1) {
258                 num_names += 1;
259         }
260
261         tmp = TALLOC_REALLOC_ARRAY(mem_ctx, names, char *, num_names);
262         if (tmp == NULL) {
263                 DEBUG(0, ("talloc failed\n"));
264                 TALLOC_FREE(names);
265                 return NT_STATUS_NO_MEMORY;
266         }
267
268         names = tmp;
269         num_names = 0;
270
271         for (p = ea_namelist; p - ea_namelist < sizeret; p += strlen(p)+1) {
272                 names[num_names++] = p;
273         }
274
275         if (pnames) {
276                 *pnames = names;
277         } else {
278                 TALLOC_FREE(names);
279         }
280         *pnum_names = num_names;
281         return NT_STATUS_OK;
282 }
283
284 /****************************************************************************
285  Return a linked list of the total EA's. Plus the total size
286 ****************************************************************************/
287
288 static struct ea_list *get_ea_list_from_file(TALLOC_CTX *mem_ctx, connection_struct *conn, files_struct *fsp,
289                                         const char *fname, size_t *pea_total_len)
290 {
291         /* Get a list of all xattrs. Max namesize is 64k. */
292         size_t i, num_names;
293         char **names;
294         struct ea_list *ea_list_head = NULL;
295         NTSTATUS status;
296
297         *pea_total_len = 0;
298
299         if (!lp_ea_support(SNUM(conn))) {
300                 return NULL;
301         }
302
303         status = get_ea_names_from_file(talloc_tos(), conn, fsp, fname,
304                                         &names, &num_names);
305
306         if (!NT_STATUS_IS_OK(status) || (num_names == 0)) {
307                 return NULL;
308         }
309
310         for (i=0; i<num_names; i++) {
311                 struct ea_list *listp;
312                 fstring dos_ea_name;
313
314                 if (strnequal(names[i], "system.", 7)
315                     || samba_private_attr_name(names[i]))
316                         continue;
317
318                 listp = TALLOC_P(mem_ctx, struct ea_list);
319                 if (listp == NULL) {
320                         return NULL;
321                 }
322
323                 if (!NT_STATUS_IS_OK(get_ea_value(mem_ctx, conn, fsp,
324                                                   fname, names[i],
325                                                   &listp->ea))) {
326                         return NULL;
327                 }
328
329                 push_ascii_fstring(dos_ea_name, listp->ea.name);
330
331                 *pea_total_len +=
332                         4 + strlen(dos_ea_name) + 1 + listp->ea.value.length;
333
334                 DEBUG(10,("get_ea_list_from_file: total_len = %u, %s, val len "
335                           "= %u\n", (unsigned int)*pea_total_len, dos_ea_name,
336                           (unsigned int)listp->ea.value.length));
337
338                 DLIST_ADD_END(ea_list_head, listp, struct ea_list *);
339
340         }
341
342         /* Add on 4 for total length. */
343         if (*pea_total_len) {
344                 *pea_total_len += 4;
345         }
346
347         DEBUG(10, ("get_ea_list_from_file: total_len = %u\n",
348                    (unsigned int)*pea_total_len));
349
350         return ea_list_head;
351 }
352
353 /****************************************************************************
354  Fill a qfilepathinfo buffer with EA's. Returns the length of the buffer
355  that was filled.
356 ****************************************************************************/
357
358 static unsigned int fill_ea_buffer(TALLOC_CTX *mem_ctx, char *pdata, unsigned int total_data_size,
359         connection_struct *conn, struct ea_list *ea_list)
360 {
361         unsigned int ret_data_size = 4;
362         char *p = pdata;
363
364         SMB_ASSERT(total_data_size >= 4);
365
366         if (!lp_ea_support(SNUM(conn))) {
367                 SIVAL(pdata,4,0);
368                 return 4;
369         }
370
371         for (p = pdata + 4; ea_list; ea_list = ea_list->next) {
372                 size_t dos_namelen;
373                 fstring dos_ea_name;
374                 push_ascii_fstring(dos_ea_name, ea_list->ea.name);
375                 dos_namelen = strlen(dos_ea_name);
376                 if (dos_namelen > 255 || dos_namelen == 0) {
377                         break;
378                 }
379                 if (ea_list->ea.value.length > 65535) {
380                         break;
381                 }
382                 if (4 + dos_namelen + 1 + ea_list->ea.value.length > total_data_size) {
383                         break;
384                 }
385
386                 /* We know we have room. */
387                 SCVAL(p,0,ea_list->ea.flags);
388                 SCVAL(p,1,dos_namelen);
389                 SSVAL(p,2,ea_list->ea.value.length);
390                 fstrcpy(p+4, dos_ea_name);
391                 memcpy( p + 4 + dos_namelen + 1, ea_list->ea.value.data, ea_list->ea.value.length);
392
393                 total_data_size -= 4 + dos_namelen + 1 + ea_list->ea.value.length;
394                 p += 4 + dos_namelen + 1 + ea_list->ea.value.length;
395         }
396
397         ret_data_size = PTR_DIFF(p, pdata);
398         DEBUG(10,("fill_ea_buffer: data_size = %u\n", ret_data_size ));
399         SIVAL(pdata,0,ret_data_size);
400         return ret_data_size;
401 }
402
403 static NTSTATUS fill_ea_chained_buffer(TALLOC_CTX *mem_ctx,
404                                        char *pdata,
405                                        unsigned int total_data_size,
406                                        unsigned int *ret_data_size,
407                                        connection_struct *conn,
408                                        struct ea_list *ea_list)
409 {
410         uint8_t *p = (uint8_t *)pdata;
411         uint8_t *last_start = NULL;
412
413         *ret_data_size = 0;
414
415         if (!lp_ea_support(SNUM(conn))) {
416                 return NT_STATUS_NO_EAS_ON_FILE;
417         }
418
419         for (; ea_list; ea_list = ea_list->next) {
420                 size_t dos_namelen;
421                 fstring dos_ea_name;
422                 size_t this_size;
423
424                 if (last_start) {
425                         SIVAL(last_start, 0, PTR_DIFF(p, last_start));
426                 }
427                 last_start = p;
428
429                 push_ascii_fstring(dos_ea_name, ea_list->ea.name);
430                 dos_namelen = strlen(dos_ea_name);
431                 if (dos_namelen > 255 || dos_namelen == 0) {
432                         return NT_STATUS_INTERNAL_ERROR;
433                 }
434                 if (ea_list->ea.value.length > 65535) {
435                         return NT_STATUS_INTERNAL_ERROR;
436                 }
437
438                 this_size = 0x08 + dos_namelen + 1 + ea_list->ea.value.length;
439
440                 if (ea_list->next) {
441                         size_t pad = 4 - (this_size % 4);
442                         this_size += pad;
443                 }
444
445                 if (this_size > total_data_size) {
446                         return NT_STATUS_INFO_LENGTH_MISMATCH;
447                 }
448
449                 /* We know we have room. */
450                 SIVAL(p, 0x00, 0); /* next offset */
451                 SCVAL(p, 0x04, ea_list->ea.flags);
452                 SCVAL(p, 0x05, dos_namelen);
453                 SSVAL(p, 0x06, ea_list->ea.value.length);
454                 fstrcpy((char *)(p+0x08), dos_ea_name);
455                 memcpy(p + 0x08 + dos_namelen + 1, ea_list->ea.value.data, ea_list->ea.value.length);
456
457                 total_data_size -= this_size;
458                 p += this_size;
459         }
460
461         *ret_data_size = PTR_DIFF(p, pdata);
462         DEBUG(10,("fill_ea_chained_buffer: data_size = %u\n", *ret_data_size));
463         return NT_STATUS_OK;
464 }
465
466 static unsigned int estimate_ea_size(connection_struct *conn, files_struct *fsp, const char *fname)
467 {
468         size_t total_ea_len = 0;
469         TALLOC_CTX *mem_ctx = NULL;
470
471         if (!lp_ea_support(SNUM(conn))) {
472                 return 0;
473         }
474         mem_ctx = talloc_tos();
475         (void)get_ea_list_from_file(mem_ctx, conn, fsp, fname, &total_ea_len);
476         return total_ea_len;
477 }
478
479 /****************************************************************************
480  Ensure the EA name is case insensitive by matching any existing EA name.
481 ****************************************************************************/
482
483 static void canonicalize_ea_name(connection_struct *conn, files_struct *fsp, const char *fname, fstring unix_ea_name)
484 {
485         size_t total_ea_len;
486         TALLOC_CTX *mem_ctx = talloc_tos();
487         struct ea_list *ea_list = get_ea_list_from_file(mem_ctx, conn, fsp, fname, &total_ea_len);
488
489         for (; ea_list; ea_list = ea_list->next) {
490                 if (strequal(&unix_ea_name[5], ea_list->ea.name)) {
491                         DEBUG(10,("canonicalize_ea_name: %s -> %s\n",
492                                 &unix_ea_name[5], ea_list->ea.name));
493                         safe_strcpy(&unix_ea_name[5], ea_list->ea.name, sizeof(fstring)-6);
494                         break;
495                 }
496         }
497 }
498
499 /****************************************************************************
500  Set or delete an extended attribute.
501 ****************************************************************************/
502
503 NTSTATUS set_ea(connection_struct *conn, files_struct *fsp,
504                 const struct smb_filename *smb_fname, struct ea_list *ea_list)
505 {
506         char *fname = NULL;
507
508         if (!lp_ea_support(SNUM(conn))) {
509                 return NT_STATUS_EAS_NOT_SUPPORTED;
510         }
511
512         if (fsp && !(fsp->access_mask & FILE_WRITE_EA)) {
513                 return NT_STATUS_ACCESS_DENIED;
514         }
515
516         /* For now setting EAs on streams isn't supported. */
517         fname = smb_fname->base_name;
518
519         for (;ea_list; ea_list = ea_list->next) {
520                 int ret;
521                 fstring unix_ea_name;
522
523                 fstrcpy(unix_ea_name, "user."); /* All EA's must start with user. */
524                 fstrcat(unix_ea_name, ea_list->ea.name);
525
526                 canonicalize_ea_name(conn, fsp, fname, unix_ea_name);
527
528                 DEBUG(10,("set_ea: ea_name %s ealen = %u\n", unix_ea_name, (unsigned int)ea_list->ea.value.length));
529
530                 if (samba_private_attr_name(unix_ea_name)) {
531                         DEBUG(10,("set_ea: ea name %s is a private Samba name.\n", unix_ea_name));
532                         return NT_STATUS_ACCESS_DENIED;
533                 }
534
535                 if (ea_list->ea.value.length == 0) {
536                         /* Remove the attribute. */
537                         if (fsp && (fsp->fh->fd != -1)) {
538                                 DEBUG(10,("set_ea: deleting ea name %s on "
539                                           "file %s by file descriptor.\n",
540                                           unix_ea_name, fsp_str_dbg(fsp)));
541                                 ret = SMB_VFS_FREMOVEXATTR(fsp, unix_ea_name);
542                         } else {
543                                 DEBUG(10,("set_ea: deleting ea name %s on file %s.\n",
544                                         unix_ea_name, fname));
545                                 ret = SMB_VFS_REMOVEXATTR(conn, fname, unix_ea_name);
546                         }
547 #ifdef ENOATTR
548                         /* Removing a non existent attribute always succeeds. */
549                         if (ret == -1 && errno == ENOATTR) {
550                                 DEBUG(10,("set_ea: deleting ea name %s didn't exist - succeeding by default.\n",
551                                                 unix_ea_name));
552                                 ret = 0;
553                         }
554 #endif
555                 } else {
556                         if (fsp && (fsp->fh->fd != -1)) {
557                                 DEBUG(10,("set_ea: setting ea name %s on file "
558                                           "%s by file descriptor.\n",
559                                           unix_ea_name, fsp_str_dbg(fsp)));
560                                 ret = SMB_VFS_FSETXATTR(fsp, unix_ea_name,
561                                                         ea_list->ea.value.data, ea_list->ea.value.length, 0);
562                         } else {
563                                 DEBUG(10,("set_ea: setting ea name %s on file %s.\n",
564                                         unix_ea_name, fname));
565                                 ret = SMB_VFS_SETXATTR(conn, fname, unix_ea_name,
566                                                         ea_list->ea.value.data, ea_list->ea.value.length, 0);
567                         }
568                 }
569
570                 if (ret == -1) {
571 #ifdef ENOTSUP
572                         if (errno == ENOTSUP) {
573                                 return NT_STATUS_EAS_NOT_SUPPORTED;
574                         }
575 #endif
576                         return map_nt_error_from_unix(errno);
577                 }
578
579         }
580         return NT_STATUS_OK;
581 }
582 /****************************************************************************
583  Read a list of EA names from an incoming data buffer. Create an ea_list with them.
584 ****************************************************************************/
585
586 static struct ea_list *read_ea_name_list(TALLOC_CTX *ctx, const char *pdata, size_t data_size)
587 {
588         struct ea_list *ea_list_head = NULL;
589         size_t converted_size, offset = 0;
590
591         while (offset + 2 < data_size) {
592                 struct ea_list *eal = TALLOC_ZERO_P(ctx, struct ea_list);
593                 unsigned int namelen = CVAL(pdata,offset);
594
595                 offset++; /* Go past the namelen byte. */
596
597                 /* integer wrap paranioa. */
598                 if ((offset + namelen < offset) || (offset + namelen < namelen) ||
599                                 (offset > data_size) || (namelen > data_size) ||
600                                 (offset + namelen >= data_size)) {
601                         break;
602                 }
603                 /* Ensure the name is null terminated. */
604                 if (pdata[offset + namelen] != '\0') {
605                         return NULL;
606                 }
607                 if (!pull_ascii_talloc(ctx, &eal->ea.name, &pdata[offset],
608                                        &converted_size)) {
609                         DEBUG(0,("read_ea_name_list: pull_ascii_talloc "
610                                  "failed: %s", strerror(errno)));
611                 }
612                 if (!eal->ea.name) {
613                         return NULL;
614                 }
615
616                 offset += (namelen + 1); /* Go past the name + terminating zero. */
617                 DLIST_ADD_END(ea_list_head, eal, struct ea_list *);
618                 DEBUG(10,("read_ea_name_list: read ea name %s\n", eal->ea.name));
619         }
620
621         return ea_list_head;
622 }
623
624 /****************************************************************************
625  Read one EA list entry from the buffer.
626 ****************************************************************************/
627
628 struct ea_list *read_ea_list_entry(TALLOC_CTX *ctx, const char *pdata, size_t data_size, size_t *pbytes_used)
629 {
630         struct ea_list *eal = TALLOC_ZERO_P(ctx, struct ea_list);
631         uint16 val_len;
632         unsigned int namelen;
633         size_t converted_size;
634
635         if (!eal) {
636                 return NULL;
637         }
638
639         if (data_size < 6) {
640                 return NULL;
641         }
642
643         eal->ea.flags = CVAL(pdata,0);
644         namelen = CVAL(pdata,1);
645         val_len = SVAL(pdata,2);
646
647         if (4 + namelen + 1 + val_len > data_size) {
648                 return NULL;
649         }
650
651         /* Ensure the name is null terminated. */
652         if (pdata[namelen + 4] != '\0') {
653                 return NULL;
654         }
655         if (!pull_ascii_talloc(ctx, &eal->ea.name, pdata + 4, &converted_size)) {
656                 DEBUG(0,("read_ea_list_entry: pull_ascii_talloc failed: %s",
657                          strerror(errno)));
658         }
659         if (!eal->ea.name) {
660                 return NULL;
661         }
662
663         eal->ea.value = data_blob_talloc(eal, NULL, (size_t)val_len + 1);
664         if (!eal->ea.value.data) {
665                 return NULL;
666         }
667
668         memcpy(eal->ea.value.data, pdata + 4 + namelen + 1, val_len);
669
670         /* Ensure we're null terminated just in case we print the value. */
671         eal->ea.value.data[val_len] = '\0';
672         /* But don't count the null. */
673         eal->ea.value.length--;
674
675         if (pbytes_used) {
676                 *pbytes_used = 4 + namelen + 1 + val_len;
677         }
678
679         DEBUG(10,("read_ea_list_entry: read ea name %s\n", eal->ea.name));
680         dump_data(10, eal->ea.value.data, eal->ea.value.length);
681
682         return eal;
683 }
684
685 /****************************************************************************
686  Read a list of EA names and data from an incoming data buffer. Create an ea_list with them.
687 ****************************************************************************/
688
689 static struct ea_list *read_ea_list(TALLOC_CTX *ctx, const char *pdata, size_t data_size)
690 {
691         struct ea_list *ea_list_head = NULL;
692         size_t offset = 0;
693         size_t bytes_used = 0;
694
695         while (offset < data_size) {
696                 struct ea_list *eal = read_ea_list_entry(ctx, pdata + offset, data_size - offset, &bytes_used);
697
698                 if (!eal) {
699                         return NULL;
700                 }
701
702                 DLIST_ADD_END(ea_list_head, eal, struct ea_list *);
703                 offset += bytes_used;
704         }
705
706         return ea_list_head;
707 }
708
709 /****************************************************************************
710  Count the total EA size needed.
711 ****************************************************************************/
712
713 static size_t ea_list_size(struct ea_list *ealist)
714 {
715         fstring dos_ea_name;
716         struct ea_list *listp;
717         size_t ret = 0;
718
719         for (listp = ealist; listp; listp = listp->next) {
720                 push_ascii_fstring(dos_ea_name, listp->ea.name);
721                 ret += 4 + strlen(dos_ea_name) + 1 + listp->ea.value.length;
722         }
723         /* Add on 4 for total length. */
724         if (ret) {
725                 ret += 4;
726         }
727
728         return ret;
729 }
730
731 /****************************************************************************
732  Return a union of EA's from a file list and a list of names.
733  The TALLOC context for the two lists *MUST* be identical as we steal
734  memory from one list to add to another. JRA.
735 ****************************************************************************/
736
737 static struct ea_list *ea_list_union(struct ea_list *name_list, struct ea_list *file_list, size_t *total_ea_len)
738 {
739         struct ea_list *nlistp, *flistp;
740
741         for (nlistp = name_list; nlistp; nlistp = nlistp->next) {
742                 for (flistp = file_list; flistp; flistp = flistp->next) {
743                         if (strequal(nlistp->ea.name, flistp->ea.name)) {
744                                 break;
745                         }
746                 }
747
748                 if (flistp) {
749                         /* Copy the data from this entry. */
750                         nlistp->ea.flags = flistp->ea.flags;
751                         nlistp->ea.value = flistp->ea.value;
752                 } else {
753                         /* Null entry. */
754                         nlistp->ea.flags = 0;
755                         ZERO_STRUCT(nlistp->ea.value);
756                 }
757         }
758
759         *total_ea_len = ea_list_size(name_list);
760         return name_list;
761 }
762
763 /****************************************************************************
764   Send the required number of replies back.
765   We assume all fields other than the data fields are
766   set correctly for the type of call.
767   HACK ! Always assumes smb_setup field is zero.
768 ****************************************************************************/
769
770 void send_trans2_replies(connection_struct *conn,
771                         struct smb_request *req,
772                          const char *params,
773                          int paramsize,
774                          const char *pdata,
775                          int datasize,
776                          int max_data_bytes)
777 {
778         /* As we are using a protocol > LANMAN1 then the max_send
779          variable must have been set in the sessetupX call.
780          This takes precedence over the max_xmit field in the
781          global struct. These different max_xmit variables should
782          be merged as this is now too confusing */
783
784         int data_to_send = datasize;
785         int params_to_send = paramsize;
786         int useable_space;
787         const char *pp = params;
788         const char *pd = pdata;
789         int params_sent_thistime, data_sent_thistime, total_sent_thistime;
790         int alignment_offset = 1; /* JRA. This used to be 3. Set to 1 to make netmon parse ok. */
791         int data_alignment_offset = 0;
792         bool overflow = False;
793         struct smbd_server_connection *sconn = req->sconn;
794         int max_send = sconn->smb1.sessions.max_send;
795
796         /* Modify the data_to_send and datasize and set the error if
797            we're trying to send more than max_data_bytes. We still send
798            the part of the packet(s) that fit. Strange, but needed
799            for OS/2. */
800
801         if (max_data_bytes > 0 && datasize > max_data_bytes) {
802                 DEBUG(5,("send_trans2_replies: max_data_bytes %d exceeded by data %d\n",
803                         max_data_bytes, datasize ));
804                 datasize = data_to_send = max_data_bytes;
805                 overflow = True;
806         }
807
808         /* If there genuinely are no parameters or data to send just send the empty packet */
809
810         if(params_to_send == 0 && data_to_send == 0) {
811                 reply_outbuf(req, 10, 0);
812                 show_msg((char *)req->outbuf);
813                 if (!srv_send_smb(sconn,
814                                 (char *)req->outbuf,
815                                 true, req->seqnum+1,
816                                 IS_CONN_ENCRYPTED(conn),
817                                 &req->pcd)) {
818                         exit_server_cleanly("send_trans2_replies: srv_send_smb failed.");
819                 }
820                 TALLOC_FREE(req->outbuf);
821                 return;
822         }
823
824         /* When sending params and data ensure that both are nicely aligned */
825         /* Only do this alignment when there is also data to send - else
826                 can cause NT redirector problems. */
827
828         if (((params_to_send % 4) != 0) && (data_to_send != 0))
829                 data_alignment_offset = 4 - (params_to_send % 4);
830
831         /* Space is bufsize minus Netbios over TCP header minus SMB header */
832         /* The alignment_offset is to align the param bytes on an even byte
833                 boundary. NT 4.0 Beta needs this to work correctly. */
834
835         useable_space = max_send - (smb_size
836                                     + 2 * 10 /* wct */
837                                     + alignment_offset
838                                     + data_alignment_offset);
839
840         if (useable_space < 0) {
841                 DEBUG(0, ("send_trans2_replies failed sanity useable_space "
842                           "= %d!!!", useable_space));
843                 exit_server_cleanly("send_trans2_replies: Not enough space");
844         }
845
846         while (params_to_send || data_to_send) {
847                 /* Calculate whether we will totally or partially fill this packet */
848
849                 total_sent_thistime = params_to_send + data_to_send;
850
851                 /* We can never send more than useable_space */
852                 /*
853                  * Note that 'useable_space' does not include the alignment offsets,
854                  * but we must include the alignment offsets in the calculation of
855                  * the length of the data we send over the wire, as the alignment offsets
856                  * are sent here. Fix from Marc_Jacobsen@hp.com.
857                  */
858
859                 total_sent_thistime = MIN(total_sent_thistime, useable_space);
860
861                 reply_outbuf(req, 10, total_sent_thistime + alignment_offset
862                              + data_alignment_offset);
863
864                 /*
865                  * We might have SMBtrans2s in req which was transferred to
866                  * the outbuf, fix that.
867                  */
868                 SCVAL(req->outbuf, smb_com, SMBtrans2);
869
870                 /* Set total params and data to be sent */
871                 SSVAL(req->outbuf,smb_tprcnt,paramsize);
872                 SSVAL(req->outbuf,smb_tdrcnt,datasize);
873
874                 /* Calculate how many parameters and data we can fit into
875                  * this packet. Parameters get precedence
876                  */
877
878                 params_sent_thistime = MIN(params_to_send,useable_space);
879                 data_sent_thistime = useable_space - params_sent_thistime;
880                 data_sent_thistime = MIN(data_sent_thistime,data_to_send);
881
882                 SSVAL(req->outbuf,smb_prcnt, params_sent_thistime);
883
884                 /* smb_proff is the offset from the start of the SMB header to the
885                         parameter bytes, however the first 4 bytes of outbuf are
886                         the Netbios over TCP header. Thus use smb_base() to subtract
887                         them from the calculation */
888
889                 SSVAL(req->outbuf,smb_proff,
890                       ((smb_buf(req->outbuf)+alignment_offset)
891                        - smb_base(req->outbuf)));
892
893                 if(params_sent_thistime == 0)
894                         SSVAL(req->outbuf,smb_prdisp,0);
895                 else
896                         /* Absolute displacement of param bytes sent in this packet */
897                         SSVAL(req->outbuf,smb_prdisp,pp - params);
898
899                 SSVAL(req->outbuf,smb_drcnt, data_sent_thistime);
900                 if(data_sent_thistime == 0) {
901                         SSVAL(req->outbuf,smb_droff,0);
902                         SSVAL(req->outbuf,smb_drdisp, 0);
903                 } else {
904                         /* The offset of the data bytes is the offset of the
905                                 parameter bytes plus the number of parameters being sent this time */
906                         SSVAL(req->outbuf, smb_droff,
907                               ((smb_buf(req->outbuf)+alignment_offset)
908                                - smb_base(req->outbuf))
909                               + params_sent_thistime + data_alignment_offset);
910                         SSVAL(req->outbuf,smb_drdisp, pd - pdata);
911                 }
912
913                 /* Initialize the padding for alignment */
914
915                 if (alignment_offset != 0) {
916                         memset(smb_buf(req->outbuf), 0, alignment_offset);
917                 }
918
919                 /* Copy the param bytes into the packet */
920
921                 if(params_sent_thistime) {
922                         memcpy((smb_buf(req->outbuf)+alignment_offset), pp,
923                                params_sent_thistime);
924                 }
925
926                 /* Copy in the data bytes */
927                 if(data_sent_thistime) {
928                         if (data_alignment_offset != 0) {
929                                 memset((smb_buf(req->outbuf)+alignment_offset+
930                                         params_sent_thistime), 0,
931                                        data_alignment_offset);
932                         }
933                         memcpy(smb_buf(req->outbuf)+alignment_offset
934                                +params_sent_thistime+data_alignment_offset,
935                                pd,data_sent_thistime);
936                 }
937
938                 DEBUG(9,("t2_rep: params_sent_thistime = %d, data_sent_thistime = %d, useable_space = %d\n",
939                         params_sent_thistime, data_sent_thistime, useable_space));
940                 DEBUG(9,("t2_rep: params_to_send = %d, data_to_send = %d, paramsize = %d, datasize = %d\n",
941                         params_to_send, data_to_send, paramsize, datasize));
942
943                 if (overflow) {
944                         error_packet_set((char *)req->outbuf,
945                                          ERRDOS,ERRbufferoverflow,
946                                          STATUS_BUFFER_OVERFLOW,
947                                          __LINE__,__FILE__);
948                 }
949
950                 /* Send the packet */
951                 show_msg((char *)req->outbuf);
952                 if (!srv_send_smb(sconn,
953                                 (char *)req->outbuf,
954                                 true, req->seqnum+1,
955                                 IS_CONN_ENCRYPTED(conn),
956                                 &req->pcd))
957                         exit_server_cleanly("send_trans2_replies: srv_send_smb failed.");
958
959                 TALLOC_FREE(req->outbuf);
960
961                 pp += params_sent_thistime;
962                 pd += data_sent_thistime;
963
964                 params_to_send -= params_sent_thistime;
965                 data_to_send -= data_sent_thistime;
966
967                 /* Sanity check */
968                 if(params_to_send < 0 || data_to_send < 0) {
969                         DEBUG(0,("send_trans2_replies failed sanity check pts = %d, dts = %d\n!!!",
970                                 params_to_send, data_to_send));
971                         return;
972                 }
973         }
974
975         return;
976 }
977
978 /****************************************************************************
979  Reply to a TRANSACT2_OPEN.
980 ****************************************************************************/
981
982 static void call_trans2open(connection_struct *conn,
983                             struct smb_request *req,
984                             char **pparams, int total_params,
985                             char **ppdata, int total_data,
986                             unsigned int max_data_bytes)
987 {
988         struct smb_filename *smb_fname = NULL;
989         char *params = *pparams;
990         char *pdata = *ppdata;
991         int deny_mode;
992         int32 open_attr;
993         bool oplock_request;
994 #if 0
995         bool return_additional_info;
996         int16 open_sattr;
997         time_t open_time;
998 #endif
999         int open_ofun;
1000         uint32 open_size;
1001         char *pname;
1002         char *fname = NULL;
1003         SMB_OFF_T size=0;
1004         int fattr=0,mtime=0;
1005         SMB_INO_T inode = 0;
1006         int smb_action = 0;
1007         files_struct *fsp;
1008         struct ea_list *ea_list = NULL;
1009         uint16 flags = 0;
1010         NTSTATUS status;
1011         uint32 access_mask;
1012         uint32 share_mode;
1013         uint32 create_disposition;
1014         uint32 create_options = 0;
1015         uint32_t private_flags = 0;
1016         TALLOC_CTX *ctx = talloc_tos();
1017
1018         /*
1019          * Ensure we have enough parameters to perform the operation.
1020          */
1021
1022         if (total_params < 29) {
1023                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1024                 goto out;
1025         }
1026
1027         flags = SVAL(params, 0);
1028         deny_mode = SVAL(params, 2);
1029         open_attr = SVAL(params,6);
1030         oplock_request = (flags & REQUEST_OPLOCK) ? EXCLUSIVE_OPLOCK : 0;
1031         if (oplock_request) {
1032                 oplock_request |= (flags & REQUEST_BATCH_OPLOCK) ? BATCH_OPLOCK : 0;
1033         }
1034
1035 #if 0
1036         return_additional_info = BITSETW(params,0);
1037         open_sattr = SVAL(params, 4);
1038         open_time = make_unix_date3(params+8);
1039 #endif
1040         open_ofun = SVAL(params,12);
1041         open_size = IVAL(params,14);
1042         pname = &params[28];
1043
1044         if (IS_IPC(conn)) {
1045                 reply_nterror(req, NT_STATUS_NETWORK_ACCESS_DENIED);
1046                 goto out;
1047         }
1048
1049         srvstr_get_path(ctx, params, req->flags2, &fname, pname,
1050                         total_params - 28, STR_TERMINATE,
1051                         &status);
1052         if (!NT_STATUS_IS_OK(status)) {
1053                 reply_nterror(req, status);
1054                 goto out;
1055         }
1056
1057         DEBUG(3,("call_trans2open %s deny_mode=0x%x attr=%d ofun=0x%x size=%d\n",
1058                 fname, (unsigned int)deny_mode, (unsigned int)open_attr,
1059                 (unsigned int)open_ofun, open_size));
1060
1061         status = filename_convert(ctx,
1062                                 conn,
1063                                 req->flags2 & FLAGS2_DFS_PATHNAMES,
1064                                 fname,
1065                                 0,
1066                                 NULL,
1067                                 &smb_fname);
1068         if (!NT_STATUS_IS_OK(status)) {
1069                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
1070                         reply_botherror(req,
1071                                 NT_STATUS_PATH_NOT_COVERED,
1072                                 ERRSRV, ERRbadpath);
1073                         goto out;
1074                 }
1075                 reply_nterror(req, status);
1076                 goto out;
1077         }
1078
1079         if (open_ofun == 0) {
1080                 reply_nterror(req, NT_STATUS_OBJECT_NAME_COLLISION);
1081                 goto out;
1082         }
1083
1084         if (!map_open_params_to_ntcreate(smb_fname, deny_mode, open_ofun,
1085                                          &access_mask, &share_mode,
1086                                          &create_disposition,
1087                                          &create_options,
1088                                          &private_flags)) {
1089                 reply_nterror(req, NT_STATUS_ACCESS_DENIED);
1090                 goto out;
1091         }
1092
1093         /* Any data in this call is an EA list. */
1094         if (total_data && (total_data != 4)) {
1095                 if (total_data < 10) {
1096                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1097                         goto out;
1098                 }
1099
1100                 if (IVAL(pdata,0) > total_data) {
1101                         DEBUG(10,("call_trans2open: bad total data size (%u) > %u\n",
1102                                 IVAL(pdata,0), (unsigned int)total_data));
1103                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1104                         goto out;
1105                 }
1106
1107                 ea_list = read_ea_list(talloc_tos(), pdata + 4,
1108                                        total_data - 4);
1109                 if (!ea_list) {
1110                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1111                         goto out;
1112                 }
1113
1114                 if (!lp_ea_support(SNUM(conn))) {
1115                         reply_nterror(req, NT_STATUS_EAS_NOT_SUPPORTED);
1116                         goto out;
1117                 }
1118         }
1119
1120         status = SMB_VFS_CREATE_FILE(
1121                 conn,                                   /* conn */
1122                 req,                                    /* req */
1123                 0,                                      /* root_dir_fid */
1124                 smb_fname,                              /* fname */
1125                 access_mask,                            /* access_mask */
1126                 share_mode,                             /* share_access */
1127                 create_disposition,                     /* create_disposition*/
1128                 create_options,                         /* create_options */
1129                 open_attr,                              /* file_attributes */
1130                 oplock_request,                         /* oplock_request */
1131                 open_size,                              /* allocation_size */
1132                 private_flags,
1133                 NULL,                                   /* sd */
1134                 ea_list,                                /* ea_list */
1135                 &fsp,                                   /* result */
1136                 &smb_action);                           /* psbuf */
1137
1138         if (!NT_STATUS_IS_OK(status)) {
1139                 if (open_was_deferred(req->mid)) {
1140                         /* We have re-scheduled this call. */
1141                         goto out;
1142                 }
1143                 reply_openerror(req, status);
1144                 goto out;
1145         }
1146
1147         size = get_file_size_stat(&smb_fname->st);
1148         fattr = dos_mode(conn, smb_fname);
1149         mtime = convert_timespec_to_time_t(smb_fname->st.st_ex_mtime);
1150         inode = smb_fname->st.st_ex_ino;
1151         if (fattr & aDIR) {
1152                 close_file(req, fsp, ERROR_CLOSE);
1153                 reply_nterror(req, NT_STATUS_ACCESS_DENIED);
1154                 goto out;
1155         }
1156
1157         /* Realloc the size of parameters and data we will return */
1158         *pparams = (char *)SMB_REALLOC(*pparams, 30);
1159         if(*pparams == NULL ) {
1160                 reply_nterror(req, NT_STATUS_NO_MEMORY);
1161                 goto out;
1162         }
1163         params = *pparams;
1164
1165         SSVAL(params,0,fsp->fnum);
1166         SSVAL(params,2,fattr);
1167         srv_put_dos_date2(params,4, mtime);
1168         SIVAL(params,8, (uint32)size);
1169         SSVAL(params,12,deny_mode);
1170         SSVAL(params,14,0); /* open_type - file or directory. */
1171         SSVAL(params,16,0); /* open_state - only valid for IPC device. */
1172
1173         if (oplock_request && lp_fake_oplocks(SNUM(conn))) {
1174                 smb_action |= EXTENDED_OPLOCK_GRANTED;
1175         }
1176
1177         SSVAL(params,18,smb_action);
1178
1179         /*
1180          * WARNING - this may need to be changed if SMB_INO_T <> 4 bytes.
1181          */
1182         SIVAL(params,20,inode);
1183         SSVAL(params,24,0); /* Padding. */
1184         if (flags & 8) {
1185                 uint32 ea_size = estimate_ea_size(conn, fsp,
1186                                                   fsp->fsp_name->base_name);
1187                 SIVAL(params, 26, ea_size);
1188         } else {
1189                 SIVAL(params, 26, 0);
1190         }
1191
1192         /* Send the required number of replies */
1193         send_trans2_replies(conn, req, params, 30, *ppdata, 0, max_data_bytes);
1194  out:
1195         TALLOC_FREE(smb_fname);
1196 }
1197
1198 /*********************************************************
1199  Routine to check if a given string matches exactly.
1200  as a special case a mask of "." does NOT match. That
1201  is required for correct wildcard semantics
1202  Case can be significant or not.
1203 **********************************************************/
1204
1205 static bool exact_match(bool has_wild,
1206                         bool case_sensitive,
1207                         const char *str,
1208                         const char *mask)
1209 {
1210         if (mask[0] == '.' && mask[1] == 0) {
1211                 return false;
1212         }
1213
1214         if (has_wild) {
1215                 return false;
1216         }
1217
1218         if (case_sensitive) {
1219                 return strcmp(str,mask)==0;
1220         } else {
1221                 return StrCaseCmp(str,mask) == 0;
1222         }
1223 }
1224
1225 /****************************************************************************
1226  Return the filetype for UNIX extensions.
1227 ****************************************************************************/
1228
1229 static uint32 unix_filetype(mode_t mode)
1230 {
1231         if(S_ISREG(mode))
1232                 return UNIX_TYPE_FILE;
1233         else if(S_ISDIR(mode))
1234                 return UNIX_TYPE_DIR;
1235 #ifdef S_ISLNK
1236         else if(S_ISLNK(mode))
1237                 return UNIX_TYPE_SYMLINK;
1238 #endif
1239 #ifdef S_ISCHR
1240         else if(S_ISCHR(mode))
1241                 return UNIX_TYPE_CHARDEV;
1242 #endif
1243 #ifdef S_ISBLK
1244         else if(S_ISBLK(mode))
1245                 return UNIX_TYPE_BLKDEV;
1246 #endif
1247 #ifdef S_ISFIFO
1248         else if(S_ISFIFO(mode))
1249                 return UNIX_TYPE_FIFO;
1250 #endif
1251 #ifdef S_ISSOCK
1252         else if(S_ISSOCK(mode))
1253                 return UNIX_TYPE_SOCKET;
1254 #endif
1255
1256         DEBUG(0,("unix_filetype: unknown filetype %u\n", (unsigned)mode));
1257         return UNIX_TYPE_UNKNOWN;
1258 }
1259
1260 /****************************************************************************
1261  Map wire perms onto standard UNIX permissions. Obey share restrictions.
1262 ****************************************************************************/
1263
1264 enum perm_type { PERM_NEW_FILE, PERM_NEW_DIR, PERM_EXISTING_FILE, PERM_EXISTING_DIR};
1265
1266 static NTSTATUS unix_perms_from_wire( connection_struct *conn,
1267                                 const SMB_STRUCT_STAT *psbuf,
1268                                 uint32 perms,
1269                                 enum perm_type ptype,
1270                                 mode_t *ret_perms)
1271 {
1272         mode_t ret = 0;
1273
1274         if (perms == SMB_MODE_NO_CHANGE) {
1275                 if (!VALID_STAT(*psbuf)) {
1276                         return NT_STATUS_INVALID_PARAMETER;
1277                 } else {
1278                         *ret_perms = psbuf->st_ex_mode;
1279                         return NT_STATUS_OK;
1280                 }
1281         }
1282
1283         ret |= ((perms & UNIX_X_OTH ) ? S_IXOTH : 0);
1284         ret |= ((perms & UNIX_W_OTH ) ? S_IWOTH : 0);
1285         ret |= ((perms & UNIX_R_OTH ) ? S_IROTH : 0);
1286         ret |= ((perms & UNIX_X_GRP ) ? S_IXGRP : 0);
1287         ret |= ((perms & UNIX_W_GRP ) ? S_IWGRP : 0);
1288         ret |= ((perms & UNIX_R_GRP ) ? S_IRGRP : 0);
1289         ret |= ((perms & UNIX_X_USR ) ? S_IXUSR : 0);
1290         ret |= ((perms & UNIX_W_USR ) ? S_IWUSR : 0);
1291         ret |= ((perms & UNIX_R_USR ) ? S_IRUSR : 0);
1292 #ifdef S_ISVTX
1293         ret |= ((perms & UNIX_STICKY ) ? S_ISVTX : 0);
1294 #endif
1295 #ifdef S_ISGID
1296         ret |= ((perms & UNIX_SET_GID ) ? S_ISGID : 0);
1297 #endif
1298 #ifdef S_ISUID
1299         ret |= ((perms & UNIX_SET_UID ) ? S_ISUID : 0);
1300 #endif
1301
1302         switch (ptype) {
1303         case PERM_NEW_FILE:
1304                 /* Apply mode mask */
1305                 ret &= lp_create_mask(SNUM(conn));
1306                 /* Add in force bits */
1307                 ret |= lp_force_create_mode(SNUM(conn));
1308                 break;
1309         case PERM_NEW_DIR:
1310                 ret &= lp_dir_mask(SNUM(conn));
1311                 /* Add in force bits */
1312                 ret |= lp_force_dir_mode(SNUM(conn));
1313                 break;
1314         case PERM_EXISTING_FILE:
1315                 /* Apply mode mask */
1316                 ret &= lp_security_mask(SNUM(conn));
1317                 /* Add in force bits */
1318                 ret |= lp_force_security_mode(SNUM(conn));
1319                 break;
1320         case PERM_EXISTING_DIR:
1321                 /* Apply mode mask */
1322                 ret &= lp_dir_security_mask(SNUM(conn));
1323                 /* Add in force bits */
1324                 ret |= lp_force_dir_security_mode(SNUM(conn));
1325                 break;
1326         }
1327
1328         *ret_perms = ret;
1329         return NT_STATUS_OK;
1330 }
1331
1332 /****************************************************************************
1333  Needed to show the msdfs symlinks as directories. Modifies psbuf
1334  to be a directory if it's a msdfs link.
1335 ****************************************************************************/
1336
1337 static bool check_msdfs_link(connection_struct *conn,
1338                                 const char *pathname,
1339                                 SMB_STRUCT_STAT *psbuf)
1340 {
1341         int saved_errno = errno;
1342         if(lp_host_msdfs() &&
1343                 lp_msdfs_root(SNUM(conn)) &&
1344                 is_msdfs_link(conn, pathname, psbuf)) {
1345
1346                 DEBUG(5,("check_msdfs_link: Masquerading msdfs link %s "
1347                         "as a directory\n",
1348                         pathname));
1349                 psbuf->st_ex_mode = (psbuf->st_ex_mode & 0xFFF) | S_IFDIR;
1350                 errno = saved_errno;
1351                 return true;
1352         }
1353         errno = saved_errno;
1354         return false;
1355 }
1356
1357
1358 /****************************************************************************
1359  Get a level dependent lanman2 dir entry.
1360 ****************************************************************************/
1361
1362 struct smbd_dirptr_lanman2_state {
1363         connection_struct *conn;
1364         uint32_t info_level;
1365         bool check_mangled_names;
1366         bool has_wild;
1367         bool got_exact_match;
1368 };
1369
1370 static bool smbd_dirptr_lanman2_match_fn(TALLOC_CTX *ctx,
1371                                          void *private_data,
1372                                          const char *dname,
1373                                          const char *mask,
1374                                          char **_fname)
1375 {
1376         struct smbd_dirptr_lanman2_state *state =
1377                 (struct smbd_dirptr_lanman2_state *)private_data;
1378         bool ok;
1379         char mangled_name[13]; /* mangled 8.3 name. */
1380         bool got_match;
1381         const char *fname;
1382
1383         /* Mangle fname if it's an illegal name. */
1384         if (mangle_must_mangle(dname, state->conn->params)) {
1385                 ok = name_to_8_3(dname, mangled_name,
1386                                  true, state->conn->params);
1387                 if (!ok) {
1388                         return false;
1389                 }
1390                 fname = mangled_name;
1391         } else {
1392                 fname = dname;
1393         }
1394
1395         got_match = exact_match(state->has_wild,
1396                                 state->conn->case_sensitive,
1397                                 fname, mask);
1398         state->got_exact_match = got_match;
1399         if (!got_match) {
1400                 got_match = mask_match(fname, mask,
1401                                        state->conn->case_sensitive);
1402         }
1403
1404         if(!got_match && state->check_mangled_names &&
1405            !mangle_is_8_3(fname, false, state->conn->params)) {
1406                 /*
1407                  * It turns out that NT matches wildcards against
1408                  * both long *and* short names. This may explain some
1409                  * of the wildcard wierdness from old DOS clients
1410                  * that some people have been seeing.... JRA.
1411                  */
1412                 /* Force the mangling into 8.3. */
1413                 ok = name_to_8_3(fname, mangled_name,
1414                                  false, state->conn->params);
1415                 if (!ok) {
1416                         return false;
1417                 }
1418
1419                 got_match = exact_match(state->has_wild,
1420                                         state->conn->case_sensitive,
1421                                         mangled_name, mask);
1422                 state->got_exact_match = got_match;
1423                 if (!got_match) {
1424                         got_match = mask_match(mangled_name, mask,
1425                                                state->conn->case_sensitive);
1426                 }
1427         }
1428
1429         if (!got_match) {
1430                 return false;
1431         }
1432
1433         *_fname = talloc_strdup(ctx, fname);
1434         if (*_fname == NULL) {
1435                 return false;
1436         }
1437
1438         return true;
1439 }
1440
1441 static bool smbd_dirptr_lanman2_mode_fn(TALLOC_CTX *ctx,
1442                                         void *private_data,
1443                                         struct smb_filename *smb_fname,
1444                                         uint32_t *_mode)
1445 {
1446         struct smbd_dirptr_lanman2_state *state =
1447                 (struct smbd_dirptr_lanman2_state *)private_data;
1448         bool ms_dfs_link = false;
1449         uint32_t mode = 0;
1450
1451         if (INFO_LEVEL_IS_UNIX(state->info_level)) {
1452                 if (SMB_VFS_LSTAT(state->conn, smb_fname) != 0) {
1453                         DEBUG(5,("smbd_dirptr_lanman2_mode_fn: "
1454                                  "Couldn't lstat [%s] (%s)\n",
1455                                  smb_fname_str_dbg(smb_fname),
1456                                  strerror(errno)));
1457                         return false;
1458                 }
1459         } else if (!VALID_STAT(smb_fname->st) &&
1460                    SMB_VFS_STAT(state->conn, smb_fname) != 0) {
1461                 /* Needed to show the msdfs symlinks as
1462                  * directories */
1463
1464                 ms_dfs_link = check_msdfs_link(state->conn,
1465                                                smb_fname->base_name,
1466                                                &smb_fname->st);
1467                 if (!ms_dfs_link) {
1468                         DEBUG(5,("smbd_dirptr_lanman2_mode_fn: "
1469                                  "Couldn't stat [%s] (%s)\n",
1470                                  smb_fname_str_dbg(smb_fname),
1471                                  strerror(errno)));
1472                         return false;
1473                 }
1474         }
1475
1476         if (ms_dfs_link) {
1477                 mode = dos_mode_msdfs(state->conn, smb_fname);
1478         } else {
1479                 mode = dos_mode(state->conn, smb_fname);
1480         }
1481
1482         *_mode = mode;
1483         return true;
1484 }
1485
1486 static bool smbd_marshall_dir_entry(TALLOC_CTX *ctx,
1487                                     connection_struct *conn,
1488                                     uint16_t flags2,
1489                                     uint32_t info_level,
1490                                     struct ea_list *name_list,
1491                                     bool check_mangled_names,
1492                                     bool requires_resume_key,
1493                                     uint32_t mode,
1494                                     const char *fname,
1495                                     const struct smb_filename *smb_fname,
1496                                     int space_remaining,
1497                                     uint8_t align,
1498                                     bool do_pad,
1499                                     char *base_data,
1500                                     char **ppdata,
1501                                     char *end_data,
1502                                     bool *out_of_space,
1503                                     uint64_t *last_entry_off)
1504 {
1505         char *p, *q, *pdata = *ppdata;
1506         uint32_t reskey=0;
1507         uint64_t file_size = 0;
1508         uint64_t allocation_size = 0;
1509         uint64_t file_index = 0;
1510         uint32_t len;
1511         struct timespec mdate_ts, adate_ts, cdate_ts, create_date_ts;
1512         time_t mdate = (time_t)0, adate = (time_t)0, create_date = (time_t)0;
1513         time_t c_date = (time_t)0;
1514         char *nameptr;
1515         char *last_entry_ptr;
1516         bool was_8_3;
1517         int off;
1518         int pad = 0;
1519
1520         *out_of_space = false;
1521
1522         ZERO_STRUCT(mdate_ts);
1523         ZERO_STRUCT(adate_ts);
1524         ZERO_STRUCT(create_date_ts);
1525         ZERO_STRUCT(cdate_ts);
1526
1527         if (!(mode & aDIR)) {
1528                 file_size = get_file_size_stat(&smb_fname->st);
1529         }
1530         allocation_size = SMB_VFS_GET_ALLOC_SIZE(conn, NULL, &smb_fname->st);
1531
1532         file_index = get_FileIndex(conn, &smb_fname->st);
1533
1534         mdate_ts = smb_fname->st.st_ex_mtime;
1535         adate_ts = smb_fname->st.st_ex_atime;
1536         create_date_ts = get_create_timespec(conn, NULL, smb_fname);
1537         cdate_ts = get_change_timespec(conn, NULL, smb_fname);
1538
1539         if (lp_dos_filetime_resolution(SNUM(conn))) {
1540                 dos_filetime_timespec(&create_date_ts);
1541                 dos_filetime_timespec(&mdate_ts);
1542                 dos_filetime_timespec(&adate_ts);
1543                 dos_filetime_timespec(&cdate_ts);
1544         }
1545
1546         create_date = convert_timespec_to_time_t(create_date_ts);
1547         mdate = convert_timespec_to_time_t(mdate_ts);
1548         adate = convert_timespec_to_time_t(adate_ts);
1549         c_date = convert_timespec_to_time_t(cdate_ts);
1550
1551         /* align the record */
1552         SMB_ASSERT(align >= 1);
1553
1554         off = (int)PTR_DIFF(pdata, base_data);
1555         pad = (off + (align-1)) & ~(align-1);
1556         pad -= off;
1557
1558         if (pad && pad > space_remaining) {
1559                 *out_of_space = true;
1560                 DEBUG(9,("smbd_marshall_dir_entry: out of space "
1561                         "for padding (wanted %u, had %d)\n",
1562                         (unsigned int)pad,
1563                         space_remaining ));
1564                 return false; /* Not finished - just out of space */
1565         }
1566
1567         off += pad;
1568         /* initialize padding to 0 */
1569         if (pad) {
1570                 memset(pdata, 0, pad);
1571         }
1572         space_remaining -= pad;
1573
1574         DEBUG(10,("smbd_marshall_dir_entry: space_remaining = %d\n",
1575                 space_remaining ));
1576
1577         pdata += pad;
1578         p = pdata;
1579         last_entry_ptr = p;
1580
1581         pad = 0;
1582         off = 0;
1583
1584         switch (info_level) {
1585         case SMB_FIND_INFO_STANDARD:
1586                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_INFO_STANDARD\n"));
1587                 if(requires_resume_key) {
1588                         SIVAL(p,0,reskey);
1589                         p += 4;
1590                 }
1591                 srv_put_dos_date2(p,0,create_date);
1592                 srv_put_dos_date2(p,4,adate);
1593                 srv_put_dos_date2(p,8,mdate);
1594                 SIVAL(p,12,(uint32)file_size);
1595                 SIVAL(p,16,(uint32)allocation_size);
1596                 SSVAL(p,20,mode);
1597                 p += 23;
1598                 nameptr = p;
1599                 if (flags2 & FLAGS2_UNICODE_STRINGS) {
1600                         p += ucs2_align(base_data, p, 0);
1601                 }
1602                 len = srvstr_push(base_data, flags2, p,
1603                                   fname, PTR_DIFF(end_data, p),
1604                                   STR_TERMINATE);
1605                 if (flags2 & FLAGS2_UNICODE_STRINGS) {
1606                         if (len > 2) {
1607                                 SCVAL(nameptr, -1, len - 2);
1608                         } else {
1609                                 SCVAL(nameptr, -1, 0);
1610                         }
1611                 } else {
1612                         if (len > 1) {
1613                                 SCVAL(nameptr, -1, len - 1);
1614                         } else {
1615                                 SCVAL(nameptr, -1, 0);
1616                         }
1617                 }
1618                 p += len;
1619                 break;
1620
1621         case SMB_FIND_EA_SIZE:
1622                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_EA_SIZE\n"));
1623                 if (requires_resume_key) {
1624                         SIVAL(p,0,reskey);
1625                         p += 4;
1626                 }
1627                 srv_put_dos_date2(p,0,create_date);
1628                 srv_put_dos_date2(p,4,adate);
1629                 srv_put_dos_date2(p,8,mdate);
1630                 SIVAL(p,12,(uint32)file_size);
1631                 SIVAL(p,16,(uint32)allocation_size);
1632                 SSVAL(p,20,mode);
1633                 {
1634                         unsigned int ea_size = estimate_ea_size(conn, NULL,
1635                                                                 smb_fname->base_name);
1636                         SIVAL(p,22,ea_size); /* Extended attributes */
1637                 }
1638                 p += 27;
1639                 nameptr = p - 1;
1640                 len = srvstr_push(base_data, flags2,
1641                                   p, fname, PTR_DIFF(end_data, p),
1642                                   STR_TERMINATE | STR_NOALIGN);
1643                 if (flags2 & FLAGS2_UNICODE_STRINGS) {
1644                         if (len > 2) {
1645                                 len -= 2;
1646                         } else {
1647                                 len = 0;
1648                         }
1649                 } else {
1650                         if (len > 1) {
1651                                 len -= 1;
1652                         } else {
1653                                 len = 0;
1654                         }
1655                 }
1656                 SCVAL(nameptr,0,len);
1657                 p += len;
1658                 SCVAL(p,0,0); p += 1; /* Extra zero byte ? - why.. */
1659                 break;
1660
1661         case SMB_FIND_EA_LIST:
1662         {
1663                 struct ea_list *file_list = NULL;
1664                 size_t ea_len = 0;
1665
1666                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_EA_LIST\n"));
1667                 if (!name_list) {
1668                         return false;
1669                 }
1670                 if (requires_resume_key) {
1671                         SIVAL(p,0,reskey);
1672                         p += 4;
1673                 }
1674                 srv_put_dos_date2(p,0,create_date);
1675                 srv_put_dos_date2(p,4,adate);
1676                 srv_put_dos_date2(p,8,mdate);
1677                 SIVAL(p,12,(uint32)file_size);
1678                 SIVAL(p,16,(uint32)allocation_size);
1679                 SSVAL(p,20,mode);
1680                 p += 22; /* p now points to the EA area. */
1681
1682                 file_list = get_ea_list_from_file(ctx, conn, NULL,
1683                                                   smb_fname->base_name,
1684                                                   &ea_len);
1685                 name_list = ea_list_union(name_list, file_list, &ea_len);
1686
1687                 /* We need to determine if this entry will fit in the space available. */
1688                 /* Max string size is 255 bytes. */
1689                 if (PTR_DIFF(p + 255 + ea_len,pdata) > space_remaining) {
1690                         *out_of_space = true;
1691                         DEBUG(9,("smbd_marshall_dir_entry: out of space "
1692                                 "(wanted %u, had %d)\n",
1693                                 (unsigned int)PTR_DIFF(p + 255 + ea_len,pdata),
1694                                 space_remaining ));
1695                         return False; /* Not finished - just out of space */
1696                 }
1697
1698                 /* Push the ea_data followed by the name. */
1699                 p += fill_ea_buffer(ctx, p, space_remaining, conn, name_list);
1700                 nameptr = p;
1701                 len = srvstr_push(base_data, flags2,
1702                                   p + 1, fname, PTR_DIFF(end_data, p+1),
1703                                   STR_TERMINATE | STR_NOALIGN);
1704                 if (flags2 & FLAGS2_UNICODE_STRINGS) {
1705                         if (len > 2) {
1706                                 len -= 2;
1707                         } else {
1708                                 len = 0;
1709                         }
1710                 } else {
1711                         if (len > 1) {
1712                                 len -= 1;
1713                         } else {
1714                                 len = 0;
1715                         }
1716                 }
1717                 SCVAL(nameptr,0,len);
1718                 p += len + 1;
1719                 SCVAL(p,0,0); p += 1; /* Extra zero byte ? - why.. */
1720                 break;
1721         }
1722
1723         case SMB_FIND_FILE_BOTH_DIRECTORY_INFO:
1724                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_FILE_BOTH_DIRECTORY_INFO\n"));
1725                 was_8_3 = mangle_is_8_3(fname, True, conn->params);
1726                 p += 4;
1727                 SIVAL(p,0,reskey); p += 4;
1728                 put_long_date_timespec(conn->ts_res,p,create_date_ts); p += 8;
1729                 put_long_date_timespec(conn->ts_res,p,adate_ts); p += 8;
1730                 put_long_date_timespec(conn->ts_res,p,mdate_ts); p += 8;
1731                 put_long_date_timespec(conn->ts_res,p,cdate_ts); p += 8;
1732                 SOFF_T(p,0,file_size); p += 8;
1733                 SOFF_T(p,0,allocation_size); p += 8;
1734                 SIVAL(p,0,mode); p += 4;
1735                 q = p; p += 4; /* q is placeholder for name length. */
1736                 {
1737                         unsigned int ea_size = estimate_ea_size(conn, NULL,
1738                                                                 smb_fname->base_name);
1739                         SIVAL(p,0,ea_size); /* Extended attributes */
1740                         p += 4;
1741                 }
1742                 /* Clear the short name buffer. This is
1743                  * IMPORTANT as not doing so will trigger
1744                  * a Win2k client bug. JRA.
1745                  */
1746                 if (!was_8_3 && check_mangled_names) {
1747                         char mangled_name[13]; /* mangled 8.3 name. */
1748                         if (!name_to_8_3(fname,mangled_name,True,
1749                                            conn->params)) {
1750                                 /* Error - mangle failed ! */
1751                                 memset(mangled_name,'\0',12);
1752                         }
1753                         mangled_name[12] = 0;
1754                         len = srvstr_push(base_data, flags2,
1755                                           p+2, mangled_name, 24,
1756                                           STR_UPPER|STR_UNICODE);
1757                         if (len < 24) {
1758                                 memset(p + 2 + len,'\0',24 - len);
1759                         }
1760                         SSVAL(p, 0, len);
1761                 } else {
1762                         memset(p,'\0',26);
1763                 }
1764                 p += 2 + 24;
1765                 len = srvstr_push(base_data, flags2, p,
1766                                   fname, PTR_DIFF(end_data, p),
1767                                   STR_TERMINATE_ASCII);
1768                 SIVAL(q,0,len);
1769                 p += len;
1770
1771                 len = PTR_DIFF(p, pdata);
1772                 pad = (len + (align-1)) & ~(align-1);
1773                 /*
1774                  * offset to the next entry, the caller
1775                  * will overwrite it for the last entry
1776                  * that's why we always include the padding
1777                  */
1778                 SIVAL(pdata,0,pad);
1779                 /*
1780                  * set padding to zero
1781                  */
1782                 if (do_pad) {
1783                         memset(p, 0, pad - len);
1784                         p = pdata + pad;
1785                 } else {
1786                         p = pdata + len;
1787                 }
1788                 break;
1789
1790         case SMB_FIND_FILE_DIRECTORY_INFO:
1791                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_FILE_DIRECTORY_INFO\n"));
1792                 p += 4;
1793                 SIVAL(p,0,reskey); p += 4;
1794                 put_long_date_timespec(conn->ts_res,p,create_date_ts); p += 8;
1795                 put_long_date_timespec(conn->ts_res,p,adate_ts); p += 8;
1796                 put_long_date_timespec(conn->ts_res,p,mdate_ts); p += 8;
1797                 put_long_date_timespec(conn->ts_res,p,cdate_ts); p += 8;
1798                 SOFF_T(p,0,file_size); p += 8;
1799                 SOFF_T(p,0,allocation_size); p += 8;
1800                 SIVAL(p,0,mode); p += 4;
1801                 len = srvstr_push(base_data, flags2,
1802                                   p + 4, fname, PTR_DIFF(end_data, p+4),
1803                                   STR_TERMINATE_ASCII);
1804                 SIVAL(p,0,len);
1805                 p += 4 + len;
1806
1807                 len = PTR_DIFF(p, pdata);
1808                 pad = (len + (align-1)) & ~(align-1);
1809                 /*
1810                  * offset to the next entry, the caller
1811                  * will overwrite it for the last entry
1812                  * that's why we always include the padding
1813                  */
1814                 SIVAL(pdata,0,pad);
1815                 /*
1816                  * set padding to zero
1817                  */
1818                 if (do_pad) {
1819                         memset(p, 0, pad - len);
1820                         p = pdata + pad;
1821                 } else {
1822                         p = pdata + len;
1823                 }
1824                 break;
1825
1826         case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
1827                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_FILE_FULL_DIRECTORY_INFO\n"));
1828                 p += 4;
1829                 SIVAL(p,0,reskey); p += 4;
1830                 put_long_date_timespec(conn->ts_res,p,create_date_ts); p += 8;
1831                 put_long_date_timespec(conn->ts_res,p,adate_ts); p += 8;
1832                 put_long_date_timespec(conn->ts_res,p,mdate_ts); p += 8;
1833                 put_long_date_timespec(conn->ts_res,p,cdate_ts); p += 8;
1834                 SOFF_T(p,0,file_size); p += 8;
1835                 SOFF_T(p,0,allocation_size); p += 8;
1836                 SIVAL(p,0,mode); p += 4;
1837                 q = p; p += 4; /* q is placeholder for name length. */
1838                 {
1839                         unsigned int ea_size = estimate_ea_size(conn, NULL,
1840                                                                 smb_fname->base_name);
1841                         SIVAL(p,0,ea_size); /* Extended attributes */
1842                         p +=4;
1843                 }
1844                 len = srvstr_push(base_data, flags2, p,
1845                                   fname, PTR_DIFF(end_data, p),
1846                                   STR_TERMINATE_ASCII);
1847                 SIVAL(q, 0, len);
1848                 p += len;
1849
1850                 len = PTR_DIFF(p, pdata);
1851                 pad = (len + (align-1)) & ~(align-1);
1852                 /*
1853                  * offset to the next entry, the caller
1854                  * will overwrite it for the last entry
1855                  * that's why we always include the padding
1856                  */
1857                 SIVAL(pdata,0,pad);
1858                 /*
1859                  * set padding to zero
1860                  */
1861                 if (do_pad) {
1862                         memset(p, 0, pad - len);
1863                         p = pdata + pad;
1864                 } else {
1865                         p = pdata + len;
1866                 }
1867                 break;
1868
1869         case SMB_FIND_FILE_NAMES_INFO:
1870                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_FILE_NAMES_INFO\n"));
1871                 p += 4;
1872                 SIVAL(p,0,reskey); p += 4;
1873                 p += 4;
1874                 /* this must *not* be null terminated or w2k gets in a loop trying to set an
1875                    acl on a dir (tridge) */
1876                 len = srvstr_push(base_data, flags2, p,
1877                                   fname, PTR_DIFF(end_data, p),
1878                                   STR_TERMINATE_ASCII);
1879                 SIVAL(p, -4, len);
1880                 p += len;
1881
1882                 len = PTR_DIFF(p, pdata);
1883                 pad = (len + (align-1)) & ~(align-1);
1884                 /*
1885                  * offset to the next entry, the caller
1886                  * will overwrite it for the last entry
1887                  * that's why we always include the padding
1888                  */
1889                 SIVAL(pdata,0,pad);
1890                 /*
1891                  * set padding to zero
1892                  */
1893                 if (do_pad) {
1894                         memset(p, 0, pad - len);
1895                         p = pdata + pad;
1896                 } else {
1897                         p = pdata + len;
1898                 }
1899                 break;
1900
1901         case SMB_FIND_ID_FULL_DIRECTORY_INFO:
1902                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_ID_FULL_DIRECTORY_INFO\n"));
1903                 p += 4;
1904                 SIVAL(p,0,reskey); p += 4;
1905                 put_long_date_timespec(conn->ts_res,p,create_date_ts); p += 8;
1906                 put_long_date_timespec(conn->ts_res,p,adate_ts); p += 8;
1907                 put_long_date_timespec(conn->ts_res,p,mdate_ts); p += 8;
1908                 put_long_date_timespec(conn->ts_res,p,cdate_ts); p += 8;
1909                 SOFF_T(p,0,file_size); p += 8;
1910                 SOFF_T(p,0,allocation_size); p += 8;
1911                 SIVAL(p,0,mode); p += 4;
1912                 q = p; p += 4; /* q is placeholder for name length. */
1913                 {
1914                         unsigned int ea_size = estimate_ea_size(conn, NULL,
1915                                                                 smb_fname->base_name);
1916                         SIVAL(p,0,ea_size); /* Extended attributes */
1917                         p +=4;
1918                 }
1919                 SIVAL(p,0,0); p += 4; /* Unknown - reserved ? */
1920                 SBVAL(p,0,file_index); p += 8;
1921                 len = srvstr_push(base_data, flags2, p,
1922                                   fname, PTR_DIFF(end_data, p),
1923                                   STR_TERMINATE_ASCII);
1924                 SIVAL(q, 0, len);
1925                 p += len;
1926
1927                 len = PTR_DIFF(p, pdata);
1928                 pad = (len + (align-1)) & ~(align-1);
1929                 /*
1930                  * offset to the next entry, the caller
1931                  * will overwrite it for the last entry
1932                  * that's why we always include the padding
1933                  */
1934                 SIVAL(pdata,0,pad);
1935                 /*
1936                  * set padding to zero
1937                  */
1938                 if (do_pad) {
1939                         memset(p, 0, pad - len);
1940                         p = pdata + pad;
1941                 } else {
1942                         p = pdata + len;
1943                 }
1944                 break;
1945
1946         case SMB_FIND_ID_BOTH_DIRECTORY_INFO:
1947                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_ID_BOTH_DIRECTORY_INFO\n"));
1948                 was_8_3 = mangle_is_8_3(fname, True, conn->params);
1949                 p += 4;
1950                 SIVAL(p,0,reskey); p += 4;
1951                 put_long_date_timespec(conn->ts_res,p,create_date_ts); p += 8;
1952                 put_long_date_timespec(conn->ts_res,p,adate_ts); p += 8;
1953                 put_long_date_timespec(conn->ts_res,p,mdate_ts); p += 8;
1954                 put_long_date_timespec(conn->ts_res,p,cdate_ts); p += 8;
1955                 SOFF_T(p,0,file_size); p += 8;
1956                 SOFF_T(p,0,allocation_size); p += 8;
1957                 SIVAL(p,0,mode); p += 4;
1958                 q = p; p += 4; /* q is placeholder for name length */
1959                 {
1960                         unsigned int ea_size = estimate_ea_size(conn, NULL,
1961                                                                 smb_fname->base_name);
1962                         SIVAL(p,0,ea_size); /* Extended attributes */
1963                         p +=4;
1964                 }
1965                 /* Clear the short name buffer. This is
1966                  * IMPORTANT as not doing so will trigger
1967                  * a Win2k client bug. JRA.
1968                  */
1969                 if (!was_8_3 && check_mangled_names) {
1970                         char mangled_name[13]; /* mangled 8.3 name. */
1971                         if (!name_to_8_3(fname,mangled_name,True,
1972                                         conn->params)) {
1973                                 /* Error - mangle failed ! */
1974                                 memset(mangled_name,'\0',12);
1975                         }
1976                         mangled_name[12] = 0;
1977                         len = srvstr_push(base_data, flags2,
1978                                           p+2, mangled_name, 24,
1979                                           STR_UPPER|STR_UNICODE);
1980                         SSVAL(p, 0, len);
1981                         if (len < 24) {
1982                                 memset(p + 2 + len,'\0',24 - len);
1983                         }
1984                         SSVAL(p, 0, len);
1985                 } else {
1986                         memset(p,'\0',26);
1987                 }
1988                 p += 26;
1989                 SSVAL(p,0,0); p += 2; /* Reserved ? */
1990                 SBVAL(p,0,file_index); p += 8;
1991                 len = srvstr_push(base_data, flags2, p,
1992                                   fname, PTR_DIFF(end_data, p),
1993                                   STR_TERMINATE_ASCII);
1994                 SIVAL(q,0,len);
1995                 p += len;
1996
1997                 len = PTR_DIFF(p, pdata);
1998                 pad = (len + (align-1)) & ~(align-1);
1999                 /*
2000                  * offset to the next entry, the caller
2001                  * will overwrite it for the last entry
2002                  * that's why we always include the padding
2003                  */
2004                 SIVAL(pdata,0,pad);
2005                 /*
2006                  * set padding to zero
2007                  */
2008                 if (do_pad) {
2009                         memset(p, 0, pad - len);
2010                         p = pdata + pad;
2011                 } else {
2012                         p = pdata + len;
2013                 }
2014                 break;
2015
2016         /* CIFS UNIX Extension. */
2017
2018         case SMB_FIND_FILE_UNIX:
2019         case SMB_FIND_FILE_UNIX_INFO2:
2020                 p+= 4;
2021                 SIVAL(p,0,reskey); p+= 4;    /* Used for continuing search. */
2022
2023                 /* Begin of SMB_QUERY_FILE_UNIX_BASIC */
2024
2025                 if (info_level == SMB_FIND_FILE_UNIX) {
2026                         DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_FILE_UNIX\n"));
2027                         p = store_file_unix_basic(conn, p,
2028                                                 NULL, &smb_fname->st);
2029                         len = srvstr_push(base_data, flags2, p,
2030                                           fname, PTR_DIFF(end_data, p),
2031                                           STR_TERMINATE);
2032                 } else {
2033                         DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_FILE_UNIX_INFO2\n"));
2034                         p = store_file_unix_basic_info2(conn, p,
2035                                                 NULL, &smb_fname->st);
2036                         nameptr = p;
2037                         p += 4;
2038                         len = srvstr_push(base_data, flags2, p, fname,
2039                                           PTR_DIFF(end_data, p), 0);
2040                         SIVAL(nameptr, 0, len);
2041                 }
2042
2043                 p += len;
2044
2045                 len = PTR_DIFF(p, pdata);
2046                 pad = (len + (align-1)) & ~(align-1);
2047                 /*
2048                  * offset to the next entry, the caller
2049                  * will overwrite it for the last entry
2050                  * that's why we always include the padding
2051                  */
2052                 SIVAL(pdata,0,pad);
2053                 /*
2054                  * set padding to zero
2055                  */
2056                 if (do_pad) {
2057                         memset(p, 0, pad - len);
2058                         p = pdata + pad;
2059                 } else {
2060                         p = pdata + len;
2061                 }
2062                 /* End of SMB_QUERY_FILE_UNIX_BASIC */
2063
2064                 break;
2065
2066         default:
2067                 return false;
2068         }
2069
2070         if (PTR_DIFF(p,pdata) > space_remaining) {
2071                 *out_of_space = true;
2072                 DEBUG(9,("smbd_marshall_dir_entry: out of space "
2073                         "(wanted %u, had %d)\n",
2074                         (unsigned int)PTR_DIFF(p,pdata),
2075                         space_remaining ));
2076                 return false; /* Not finished - just out of space */
2077         }
2078
2079         /* Setup the last entry pointer, as an offset from base_data */
2080         *last_entry_off = PTR_DIFF(last_entry_ptr,base_data);
2081         /* Advance the data pointer to the next slot */
2082         *ppdata = p;
2083
2084         return true;
2085 }
2086
2087 bool smbd_dirptr_lanman2_entry(TALLOC_CTX *ctx,
2088                                connection_struct *conn,
2089                                struct dptr_struct *dirptr,
2090                                uint16 flags2,
2091                                const char *path_mask,
2092                                uint32 dirtype,
2093                                int info_level,
2094                                int requires_resume_key,
2095                                bool dont_descend,
2096                                bool ask_sharemode,
2097                                uint8_t align,
2098                                bool do_pad,
2099                                char **ppdata,
2100                                char *base_data,
2101                                char *end_data,
2102                                int space_remaining,
2103                                bool *out_of_space,
2104                                bool *got_exact_match,
2105                                int *_last_entry_off,
2106                                struct ea_list *name_list)
2107 {
2108         const char *p;
2109         const char *mask = NULL;
2110         long prev_dirpos = 0;
2111         uint32_t mode = 0;
2112         char *fname = NULL;
2113         struct smb_filename *smb_fname = NULL;
2114         struct smbd_dirptr_lanman2_state state;
2115         bool ok;
2116         uint64_t last_entry_off = 0;
2117
2118         ZERO_STRUCT(state);
2119         state.conn = conn;
2120         state.info_level = info_level;
2121         state.check_mangled_names = lp_manglednames(conn->params);
2122         state.has_wild = dptr_has_wild(dirptr);
2123         state.got_exact_match = false;
2124
2125         *out_of_space = false;
2126         *got_exact_match = false;
2127
2128         p = strrchr_m(path_mask,'/');
2129         if(p != NULL) {
2130                 if(p[1] == '\0') {
2131                         mask = "*.*";
2132                 } else {
2133                         mask = p+1;
2134                 }
2135         } else {
2136                 mask = path_mask;
2137         }
2138
2139         ok = smbd_dirptr_get_entry(ctx,
2140                                    dirptr,
2141                                    mask,
2142                                    dirtype,
2143                                    dont_descend,
2144                                    ask_sharemode,
2145                                    smbd_dirptr_lanman2_match_fn,
2146                                    smbd_dirptr_lanman2_mode_fn,
2147                                    &state,
2148                                    &fname,
2149                                    &smb_fname,
2150                                    &mode,
2151                                    &prev_dirpos);
2152         if (!ok) {
2153                 return false;
2154         }
2155
2156         *got_exact_match = state.got_exact_match;
2157
2158         ok = smbd_marshall_dir_entry(ctx,
2159                                      conn,
2160                                      flags2,
2161                                      info_level,
2162                                      name_list,
2163                                      state.check_mangled_names,
2164                                      requires_resume_key,
2165                                      mode,
2166                                      fname,
2167                                      smb_fname,
2168                                      space_remaining,
2169                                      align,
2170                                      do_pad,
2171                                      base_data,
2172                                      ppdata,
2173                                      end_data,
2174                                      out_of_space,
2175                                      &last_entry_off);
2176         TALLOC_FREE(fname);
2177         TALLOC_FREE(smb_fname);
2178         if (*out_of_space) {
2179                 dptr_SeekDir(dirptr, prev_dirpos);
2180                 return false;
2181         }
2182         if (!ok) {
2183                 return false;
2184         }
2185
2186         *_last_entry_off = last_entry_off;
2187         return true;
2188 }
2189
2190 static bool get_lanman2_dir_entry(TALLOC_CTX *ctx,
2191                                 connection_struct *conn,
2192                                 struct dptr_struct *dirptr,
2193                                 uint16 flags2,
2194                                 const char *path_mask,
2195                                 uint32 dirtype,
2196                                 int info_level,
2197                                 bool requires_resume_key,
2198                                 bool dont_descend,
2199                                 bool ask_sharemode,
2200                                 char **ppdata,
2201                                 char *base_data,
2202                                 char *end_data,
2203                                 int space_remaining,
2204                                 bool *out_of_space,
2205                                 bool *got_exact_match,
2206                                 int *last_entry_off,
2207                                 struct ea_list *name_list)
2208 {
2209         uint8_t align = 4;
2210         const bool do_pad = true;
2211
2212         if (info_level >= 1 && info_level <= 3) {
2213                 /* No alignment on earlier info levels. */
2214                 align = 1;
2215         }
2216
2217         return smbd_dirptr_lanman2_entry(ctx, conn, dirptr, flags2,
2218                                          path_mask, dirtype, info_level,
2219                                          requires_resume_key, dont_descend, ask_sharemode,
2220                                          align, do_pad,
2221                                          ppdata, base_data, end_data,
2222                                          space_remaining,
2223                                          out_of_space, got_exact_match,
2224                                          last_entry_off, name_list);
2225 }
2226
2227 /****************************************************************************
2228  Reply to a TRANS2_FINDFIRST.
2229 ****************************************************************************/
2230
2231 static void call_trans2findfirst(connection_struct *conn,
2232                                  struct smb_request *req,
2233                                  char **pparams, int total_params,
2234                                  char **ppdata, int total_data,
2235                                  unsigned int max_data_bytes)
2236 {
2237         /* We must be careful here that we don't return more than the
2238                 allowed number of data bytes. If this means returning fewer than
2239                 maxentries then so be it. We assume that the redirector has
2240                 enough room for the fixed number of parameter bytes it has
2241                 requested. */
2242         struct smb_filename *smb_dname = NULL;
2243         char *params = *pparams;
2244         char *pdata = *ppdata;
2245         char *data_end;
2246         uint32 dirtype;
2247         int maxentries;
2248         uint16 findfirst_flags;
2249         bool close_after_first;
2250         bool close_if_end;
2251         bool requires_resume_key;
2252         int info_level;
2253         char *directory = NULL;
2254         char *mask = NULL;
2255         char *p;
2256         int last_entry_off=0;
2257         int dptr_num = -1;
2258         int numentries = 0;
2259         int i;
2260         bool finished = False;
2261         bool dont_descend = False;
2262         bool out_of_space = False;
2263         int space_remaining;
2264         bool mask_contains_wcard = False;
2265         struct ea_list *ea_list = NULL;
2266         NTSTATUS ntstatus = NT_STATUS_OK;
2267         bool ask_sharemode = lp_parm_bool(SNUM(conn), "smbd", "search ask sharemode", true);
2268         TALLOC_CTX *ctx = talloc_tos();
2269         struct dptr_struct *dirptr = NULL;
2270         struct smbd_server_connection *sconn = req->sconn;
2271
2272         if (total_params < 13) {
2273                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2274                 goto out;
2275         }
2276
2277         dirtype = SVAL(params,0);
2278         maxentries = SVAL(params,2);
2279         findfirst_flags = SVAL(params,4);
2280         close_after_first = (findfirst_flags & FLAG_TRANS2_FIND_CLOSE);
2281         close_if_end = (findfirst_flags & FLAG_TRANS2_FIND_CLOSE_IF_END);
2282         requires_resume_key = (findfirst_flags & FLAG_TRANS2_FIND_REQUIRE_RESUME);
2283         info_level = SVAL(params,6);
2284
2285         DEBUG(3,("call_trans2findfirst: dirtype = %x, maxentries = %d, close_after_first=%d, \
2286 close_if_end = %d requires_resume_key = %d level = 0x%x, max_data_bytes = %d\n",
2287                 (unsigned int)dirtype, maxentries, close_after_first, close_if_end, requires_resume_key,
2288                 info_level, max_data_bytes));
2289
2290         if (!maxentries) {
2291                 /* W2K3 seems to treat zero as 1. */
2292                 maxentries = 1;
2293         }
2294
2295         switch (info_level) {
2296                 case SMB_FIND_INFO_STANDARD:
2297                 case SMB_FIND_EA_SIZE:
2298                 case SMB_FIND_EA_LIST:
2299                 case SMB_FIND_FILE_DIRECTORY_INFO:
2300                 case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
2301                 case SMB_FIND_FILE_NAMES_INFO:
2302                 case SMB_FIND_FILE_BOTH_DIRECTORY_INFO:
2303                 case SMB_FIND_ID_FULL_DIRECTORY_INFO:
2304                 case SMB_FIND_ID_BOTH_DIRECTORY_INFO:
2305                         break;
2306                 case SMB_FIND_FILE_UNIX:
2307                 case SMB_FIND_FILE_UNIX_INFO2:
2308                         /* Always use filesystem for UNIX mtime query. */
2309                         ask_sharemode = false;
2310                         if (!lp_unix_extensions()) {
2311                                 reply_nterror(req, NT_STATUS_INVALID_LEVEL);
2312                                 goto out;
2313                         }
2314                         break;
2315                 default:
2316                         reply_nterror(req, NT_STATUS_INVALID_LEVEL);
2317                         goto out;
2318         }
2319
2320         srvstr_get_path_wcard(ctx, params, req->flags2, &directory,
2321                               params+12, total_params - 12,
2322                               STR_TERMINATE, &ntstatus, &mask_contains_wcard);
2323         if (!NT_STATUS_IS_OK(ntstatus)) {
2324                 reply_nterror(req, ntstatus);
2325                 goto out;
2326         }
2327
2328         ntstatus = filename_convert(ctx, conn,
2329                                     req->flags2 & FLAGS2_DFS_PATHNAMES,
2330                                     directory,
2331                                     (UCF_SAVE_LCOMP |
2332                                         UCF_ALWAYS_ALLOW_WCARD_LCOMP),
2333                                     &mask_contains_wcard,
2334                                     &smb_dname);
2335         if (!NT_STATUS_IS_OK(ntstatus)) {
2336                 if (NT_STATUS_EQUAL(ntstatus,NT_STATUS_PATH_NOT_COVERED)) {
2337                         reply_botherror(req, NT_STATUS_PATH_NOT_COVERED,
2338                                         ERRSRV, ERRbadpath);
2339                         goto out;
2340                 }
2341                 reply_nterror(req, ntstatus);
2342                 goto out;
2343         }
2344
2345         mask = smb_dname->original_lcomp;
2346
2347         directory = smb_dname->base_name;
2348
2349         p = strrchr_m(directory,'/');
2350         if(p == NULL) {
2351                 /* Windows and OS/2 systems treat search on the root '\' as if it were '\*' */
2352                 if((directory[0] == '.') && (directory[1] == '\0')) {
2353                         mask = talloc_strdup(ctx,"*");
2354                         if (!mask) {
2355                                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2356                                 goto out;
2357                         }
2358                         mask_contains_wcard = True;
2359                 }
2360         } else {
2361                 *p = 0;
2362         }
2363
2364         if (p == NULL || p == directory) {
2365                 /* Ensure we don't have a directory name of "". */
2366                 directory = talloc_strdup(talloc_tos(), ".");
2367                 if (!directory) {
2368                         reply_nterror(req, NT_STATUS_NO_MEMORY);
2369                         goto out;
2370                 }
2371         }
2372
2373         DEBUG(5,("dir=%s, mask = %s\n",directory, mask));
2374
2375         if (info_level == SMB_FIND_EA_LIST) {
2376                 uint32 ea_size;
2377
2378                 if (total_data < 4) {
2379                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2380                         goto out;
2381                 }
2382
2383                 ea_size = IVAL(pdata,0);
2384                 if (ea_size != total_data) {
2385                         DEBUG(4,("call_trans2findfirst: Rejecting EA request with incorrect \
2386 total_data=%u (should be %u)\n", (unsigned int)total_data, (unsigned int)IVAL(pdata,0) ));
2387                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2388                         goto out;
2389                 }
2390
2391                 if (!lp_ea_support(SNUM(conn))) {
2392                         reply_nterror(req, NT_STATUS_EAS_NOT_SUPPORTED);
2393                         goto out;
2394                 }
2395
2396                 /* Pull out the list of names. */
2397                 ea_list = read_ea_name_list(ctx, pdata + 4, ea_size - 4);
2398                 if (!ea_list) {
2399                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2400                         goto out;
2401                 }
2402         }
2403
2404         *ppdata = (char *)SMB_REALLOC(
2405                 *ppdata, max_data_bytes + DIR_ENTRY_SAFETY_MARGIN);
2406         if(*ppdata == NULL ) {
2407                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2408                 goto out;
2409         }
2410         pdata = *ppdata;
2411         data_end = pdata + max_data_bytes + DIR_ENTRY_SAFETY_MARGIN - 1;
2412
2413         /* Realloc the params space */
2414         *pparams = (char *)SMB_REALLOC(*pparams, 10);
2415         if (*pparams == NULL) {
2416                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2417                 goto out;
2418         }
2419         params = *pparams;
2420
2421         /* Save the wildcard match and attribs we are using on this directory -
2422                 needed as lanman2 assumes these are being saved between calls */
2423
2424         ntstatus = dptr_create(conn,
2425                                 NULL, /* fsp */
2426                                 directory,
2427                                 False,
2428                                 True,
2429                                 req->smbpid,
2430                                 mask,
2431                                 mask_contains_wcard,
2432                                 dirtype,
2433                                 &dirptr);
2434
2435         if (!NT_STATUS_IS_OK(ntstatus)) {
2436                 reply_nterror(req, ntstatus);
2437                 goto out;
2438         }
2439
2440         dptr_num = dptr_dnum(dirptr);
2441         DEBUG(4,("dptr_num is %d, wcard = %s, attr = %d\n", dptr_num, mask, dirtype));
2442
2443         /* Initialize per TRANS2_FIND_FIRST operation data */
2444         dptr_init_search_op(dirptr);
2445
2446         /* We don't need to check for VOL here as this is returned by
2447                 a different TRANS2 call. */
2448
2449         DEBUG(8,("dirpath=<%s> dontdescend=<%s>\n",
2450                 directory,lp_dontdescend(SNUM(conn))));
2451         if (in_list(directory,lp_dontdescend(SNUM(conn)),conn->case_sensitive))
2452                 dont_descend = True;
2453
2454         p = pdata;
2455         space_remaining = max_data_bytes;
2456         out_of_space = False;
2457
2458         for (i=0;(i<maxentries) && !finished && !out_of_space;i++) {
2459                 bool got_exact_match = False;
2460
2461                 /* this is a heuristic to avoid seeking the dirptr except when
2462                         absolutely necessary. It allows for a filename of about 40 chars */
2463                 if (space_remaining < DIRLEN_GUESS && numentries > 0) {
2464                         out_of_space = True;
2465                         finished = False;
2466                 } else {
2467                         finished = !get_lanman2_dir_entry(ctx,
2468                                         conn,
2469                                         dirptr,
2470                                         req->flags2,
2471                                         mask,dirtype,info_level,
2472                                         requires_resume_key,dont_descend,
2473                                         ask_sharemode,
2474                                         &p,pdata,data_end,
2475                                         space_remaining, &out_of_space,
2476                                         &got_exact_match,
2477                                         &last_entry_off, ea_list);
2478                 }
2479
2480                 if (finished && out_of_space)
2481                         finished = False;
2482
2483                 if (!finished && !out_of_space)
2484                         numentries++;
2485
2486                 /*
2487                  * As an optimisation if we know we aren't looking
2488                  * for a wildcard name (ie. the name matches the wildcard exactly)
2489                  * then we can finish on any (first) match.
2490                  * This speeds up large directory searches. JRA.
2491                  */
2492
2493                 if(got_exact_match)
2494                         finished = True;
2495
2496                 /* Ensure space_remaining never goes -ve. */
2497                 if (PTR_DIFF(p,pdata) > max_data_bytes) {
2498                         space_remaining = 0;
2499                         out_of_space = true;
2500                 } else {
2501                         space_remaining = max_data_bytes - PTR_DIFF(p,pdata);
2502                 }
2503         }
2504
2505         /* Check if we can close the dirptr */
2506         if(close_after_first || (finished && close_if_end)) {
2507                 DEBUG(5,("call_trans2findfirst - (2) closing dptr_num %d\n", dptr_num));
2508                 dptr_close(sconn, &dptr_num);
2509         }
2510
2511         /*
2512          * If there are no matching entries we must return ERRDOS/ERRbadfile -
2513          * from observation of NT. NB. This changes to ERRDOS,ERRnofiles if
2514          * the protocol level is less than NT1. Tested with smbclient. JRA.
2515          * This should fix the OS/2 client bug #2335.
2516          */
2517
2518         if(numentries == 0) {
2519                 dptr_close(sconn, &dptr_num);
2520                 if (get_Protocol() < PROTOCOL_NT1) {
2521                         reply_force_doserror(req, ERRDOS, ERRnofiles);
2522                         goto out;
2523                 } else {
2524                         reply_botherror(req, NT_STATUS_NO_SUCH_FILE,
2525                                         ERRDOS, ERRbadfile);
2526                         goto out;
2527                 }
2528         }
2529
2530         /* At this point pdata points to numentries directory entries. */
2531
2532         /* Set up the return parameter block */
2533         SSVAL(params,0,dptr_num);
2534         SSVAL(params,2,numentries);
2535         SSVAL(params,4,finished);
2536         SSVAL(params,6,0); /* Never an EA error */
2537         SSVAL(params,8,last_entry_off);
2538
2539         send_trans2_replies(conn, req, params, 10, pdata, PTR_DIFF(p,pdata),
2540                             max_data_bytes);
2541
2542         if ((! *directory) && dptr_path(sconn, dptr_num)) {
2543                 directory = talloc_strdup(talloc_tos(),dptr_path(sconn, dptr_num));
2544                 if (!directory) {
2545                         reply_nterror(req, NT_STATUS_NO_MEMORY);
2546                 }
2547         }
2548
2549         DEBUG( 4, ( "%s mask=%s directory=%s dirtype=%d numentries=%d\n",
2550                 smb_fn_name(req->cmd),
2551                 mask, directory, dirtype, numentries ) );
2552
2553         /*
2554          * Force a name mangle here to ensure that the
2555          * mask as an 8.3 name is top of the mangled cache.
2556          * The reasons for this are subtle. Don't remove
2557          * this code unless you know what you are doing
2558          * (see PR#13758). JRA.
2559          */
2560
2561         if(!mangle_is_8_3_wildcards( mask, False, conn->params)) {
2562                 char mangled_name[13];
2563                 name_to_8_3(mask, mangled_name, True, conn->params);
2564         }
2565  out:
2566         TALLOC_FREE(smb_dname);
2567         return;
2568 }
2569
2570 /****************************************************************************
2571  Reply to a TRANS2_FINDNEXT.
2572 ****************************************************************************/
2573
2574 static void call_trans2findnext(connection_struct *conn,
2575                                 struct smb_request *req,
2576                                 char **pparams, int total_params,
2577                                 char **ppdata, int total_data,
2578                                 unsigned int max_data_bytes)
2579 {
2580         /* We must be careful here that we don't return more than the
2581                 allowed number of data bytes. If this means returning fewer than
2582                 maxentries then so be it. We assume that the redirector has
2583                 enough room for the fixed number of parameter bytes it has
2584                 requested. */
2585         char *params = *pparams;
2586         char *pdata = *ppdata;
2587         char *data_end;
2588         int dptr_num;
2589         int maxentries;
2590         uint16 info_level;
2591         uint32 resume_key;
2592         uint16 findnext_flags;
2593         bool close_after_request;
2594         bool close_if_end;
2595         bool requires_resume_key;
2596         bool continue_bit;
2597         bool mask_contains_wcard = False;
2598         char *resume_name = NULL;
2599         const char *mask = NULL;
2600         const char *directory = NULL;
2601         char *p = NULL;
2602         uint16 dirtype;
2603         int numentries = 0;
2604         int i, last_entry_off=0;
2605         bool finished = False;
2606         bool dont_descend = False;
2607         bool out_of_space = False;
2608         int space_remaining;
2609         struct ea_list *ea_list = NULL;
2610         NTSTATUS ntstatus = NT_STATUS_OK;
2611         bool ask_sharemode = lp_parm_bool(SNUM(conn), "smbd", "search ask sharemode", true);
2612         TALLOC_CTX *ctx = talloc_tos();
2613         struct dptr_struct *dirptr;
2614         struct smbd_server_connection *sconn = req->sconn;
2615
2616         if (total_params < 13) {
2617                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2618                 return;
2619         }
2620
2621         dptr_num = SVAL(params,0);
2622         maxentries = SVAL(params,2);
2623         info_level = SVAL(params,4);
2624         resume_key = IVAL(params,6);
2625         findnext_flags = SVAL(params,10);
2626         close_after_request = (findnext_flags & FLAG_TRANS2_FIND_CLOSE);
2627         close_if_end = (findnext_flags & FLAG_TRANS2_FIND_CLOSE_IF_END);
2628         requires_resume_key = (findnext_flags & FLAG_TRANS2_FIND_REQUIRE_RESUME);
2629         continue_bit = (findnext_flags & FLAG_TRANS2_FIND_CONTINUE);
2630
2631         if (!continue_bit) {
2632                 /* We only need resume_name if continue_bit is zero. */
2633                 srvstr_get_path_wcard(ctx, params, req->flags2, &resume_name,
2634                               params+12,
2635                               total_params - 12, STR_TERMINATE, &ntstatus,
2636                               &mask_contains_wcard);
2637                 if (!NT_STATUS_IS_OK(ntstatus)) {
2638                         /* Win9x or OS/2 can send a resume name of ".." or ".". This will cause the parser to
2639                            complain (it thinks we're asking for the directory above the shared
2640                            path or an invalid name). Catch this as the resume name is only compared, never used in
2641                            a file access. JRA. */
2642                         srvstr_pull_talloc(ctx, params, req->flags2,
2643                                 &resume_name, params+12,
2644                                 total_params - 12,
2645                                 STR_TERMINATE);
2646
2647                         if (!resume_name || !(ISDOT(resume_name) || ISDOTDOT(resume_name))) {
2648                                 reply_nterror(req, ntstatus);
2649                                 return;
2650                         }
2651                 }
2652         }
2653
2654         DEBUG(3,("call_trans2findnext: dirhandle = %d, max_data_bytes = %d, maxentries = %d, \
2655 close_after_request=%d, close_if_end = %d requires_resume_key = %d \
2656 resume_key = %d resume name = %s continue=%d level = %d\n",
2657                 dptr_num, max_data_bytes, maxentries, close_after_request, close_if_end, 
2658                 requires_resume_key, resume_key,
2659                 resume_name ? resume_name : "(NULL)", continue_bit, info_level));
2660
2661         if (!maxentries) {
2662                 /* W2K3 seems to treat zero as 1. */
2663                 maxentries = 1;
2664         }
2665
2666         switch (info_level) {
2667                 case SMB_FIND_INFO_STANDARD:
2668                 case SMB_FIND_EA_SIZE:
2669                 case SMB_FIND_EA_LIST:
2670                 case SMB_FIND_FILE_DIRECTORY_INFO:
2671                 case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
2672                 case SMB_FIND_FILE_NAMES_INFO:
2673                 case SMB_FIND_FILE_BOTH_DIRECTORY_INFO:
2674                 case SMB_FIND_ID_FULL_DIRECTORY_INFO:
2675                 case SMB_FIND_ID_BOTH_DIRECTORY_INFO:
2676                         break;
2677                 case SMB_FIND_FILE_UNIX:
2678                 case SMB_FIND_FILE_UNIX_INFO2:
2679                         /* Always use filesystem for UNIX mtime query. */
2680                         ask_sharemode = false;
2681                         if (!lp_unix_extensions()) {
2682                                 reply_nterror(req, NT_STATUS_INVALID_LEVEL);
2683                                 return;
2684                         }
2685                         break;
2686                 default:
2687                         reply_nterror(req, NT_STATUS_INVALID_LEVEL);
2688                         return;
2689         }
2690
2691         if (info_level == SMB_FIND_EA_LIST) {
2692                 uint32 ea_size;
2693
2694                 if (total_data < 4) {
2695                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2696                         return;
2697                 }
2698
2699                 ea_size = IVAL(pdata,0);
2700                 if (ea_size != total_data) {
2701                         DEBUG(4,("call_trans2findnext: Rejecting EA request with incorrect \
2702 total_data=%u (should be %u)\n", (unsigned int)total_data, (unsigned int)IVAL(pdata,0) ));
2703                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2704                         return;
2705                 }
2706
2707                 if (!lp_ea_support(SNUM(conn))) {
2708                         reply_nterror(req, NT_STATUS_EAS_NOT_SUPPORTED);
2709                         return;
2710                 }
2711
2712                 /* Pull out the list of names. */
2713                 ea_list = read_ea_name_list(ctx, pdata + 4, ea_size - 4);
2714                 if (!ea_list) {
2715                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2716                         return;
2717                 }
2718         }
2719
2720         *ppdata = (char *)SMB_REALLOC(
2721                 *ppdata, max_data_bytes + DIR_ENTRY_SAFETY_MARGIN);
2722         if(*ppdata == NULL) {
2723                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2724                 return;
2725         }
2726
2727         pdata = *ppdata;
2728         data_end = pdata + max_data_bytes + DIR_ENTRY_SAFETY_MARGIN - 1;
2729
2730         /* Realloc the params space */
2731         *pparams = (char *)SMB_REALLOC(*pparams, 6*SIZEOFWORD);
2732         if(*pparams == NULL ) {
2733                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2734                 return;
2735         }
2736
2737         params = *pparams;
2738
2739         /* Check that the dptr is valid */
2740         if(!(dirptr = dptr_fetch_lanman2(sconn, dptr_num))) {
2741                 reply_nterror(req, STATUS_NO_MORE_FILES);
2742                 return;
2743         }
2744
2745         directory = dptr_path(sconn, dptr_num);
2746
2747         /* Get the wildcard mask from the dptr */
2748         if((p = dptr_wcard(sconn, dptr_num))== NULL) {
2749                 DEBUG(2,("dptr_num %d has no wildcard\n", dptr_num));
2750                 reply_nterror(req, STATUS_NO_MORE_FILES);
2751                 return;
2752         }
2753
2754         mask = p;
2755
2756         /* Get the attr mask from the dptr */
2757         dirtype = dptr_attr(sconn, dptr_num);
2758
2759         DEBUG(3,("dptr_num is %d, mask = %s, attr = %x, dirptr=(0x%lX,%ld)\n",
2760                 dptr_num, mask, dirtype,
2761                 (long)dirptr,
2762                 dptr_TellDir(dirptr)));
2763
2764         /* Initialize per TRANS2_FIND_NEXT operation data */
2765         dptr_init_search_op(dirptr);
2766
2767         /* We don't need to check for VOL here as this is returned by
2768                 a different TRANS2 call. */
2769
2770         DEBUG(8,("dirpath=<%s> dontdescend=<%s>\n",
2771                  directory,lp_dontdescend(SNUM(conn))));
2772         if (in_list(directory,lp_dontdescend(SNUM(conn)),conn->case_sensitive))
2773                 dont_descend = True;
2774
2775         p = pdata;
2776         space_remaining = max_data_bytes;
2777         out_of_space = False;
2778
2779         /*
2780          * Seek to the correct position. We no longer use the resume key but
2781          * depend on the last file name instead.
2782          */
2783
2784         if(!continue_bit && resume_name && *resume_name) {
2785                 SMB_STRUCT_STAT st;
2786
2787                 long current_pos = 0;
2788                 /*
2789                  * Remember, name_to_8_3 is called by
2790                  * get_lanman2_dir_entry(), so the resume name
2791                  * could be mangled. Ensure we check the unmangled name.
2792                  */
2793
2794                 if (mangle_is_mangled(resume_name, conn->params)) {
2795                         char *new_resume_name = NULL;
2796                         mangle_lookup_name_from_8_3(ctx,
2797                                                 resume_name,
2798                                                 &new_resume_name,
2799                                                 conn->params);
2800                         if (new_resume_name) {
2801                                 resume_name = new_resume_name;
2802                         }
2803                 }
2804
2805                 /*
2806                  * Fix for NT redirector problem triggered by resume key indexes
2807                  * changing between directory scans. We now return a resume key of 0
2808                  * and instead look for the filename to continue from (also given
2809                  * to us by NT/95/smbfs/smbclient). If no other scans have been done between the
2810                  * findfirst/findnext (as is usual) then the directory pointer
2811                  * should already be at the correct place.
2812                  */
2813
2814                 finished = !dptr_SearchDir(dirptr, resume_name, &current_pos, &st);
2815         } /* end if resume_name && !continue_bit */
2816
2817         for (i=0;(i<(int)maxentries) && !finished && !out_of_space ;i++) {
2818                 bool got_exact_match = False;
2819
2820                 /* this is a heuristic to avoid seeking the dirptr except when 
2821                         absolutely necessary. It allows for a filename of about 40 chars */
2822                 if (space_remaining < DIRLEN_GUESS && numentries > 0) {
2823                         out_of_space = True;
2824                         finished = False;
2825                 } else {
2826                         finished = !get_lanman2_dir_entry(ctx,
2827                                                 conn,
2828                                                 dirptr,
2829                                                 req->flags2,
2830                                                 mask,dirtype,info_level,
2831                                                 requires_resume_key,dont_descend,
2832                                                 ask_sharemode,
2833                                                 &p,pdata,data_end,
2834                                                 space_remaining, &out_of_space,
2835                                                 &got_exact_match,
2836                                                 &last_entry_off, ea_list);
2837                 }
2838
2839                 if (finished && out_of_space)
2840                         finished = False;
2841
2842                 if (!finished && !out_of_space)
2843                         numentries++;
2844
2845                 /*
2846                  * As an optimisation if we know we aren't looking
2847                  * for a wildcard name (ie. the name matches the wildcard exactly)
2848                  * then we can finish on any (first) match.
2849                  * This speeds up large directory searches. JRA.
2850                  */
2851
2852                 if(got_exact_match)
2853                         finished = True;
2854
2855                 space_remaining = max_data_bytes - PTR_DIFF(p,pdata);
2856         }
2857
2858         DEBUG( 3, ( "%s mask=%s directory=%s dirtype=%d numentries=%d\n",
2859                 smb_fn_name(req->cmd),
2860                 mask, directory, dirtype, numentries ) );
2861
2862         /* Check if we can close the dirptr */
2863         if(close_after_request || (finished && close_if_end)) {
2864                 DEBUG(5,("call_trans2findnext: closing dptr_num = %d\n", dptr_num));
2865                 dptr_close(sconn, &dptr_num); /* This frees up the saved mask */
2866         }
2867
2868         /* Set up the return parameter block */
2869         SSVAL(params,0,numentries);
2870         SSVAL(params,2,finished);
2871         SSVAL(params,4,0); /* Never an EA error */
2872         SSVAL(params,6,last_entry_off);
2873
2874         send_trans2_replies(conn, req, params, 8, pdata, PTR_DIFF(p,pdata),
2875                             max_data_bytes);
2876
2877         return;
2878 }
2879
2880 unsigned char *create_volume_objectid(connection_struct *conn, unsigned char objid[16])
2881 {
2882         E_md4hash(lp_servicename(SNUM(conn)),objid);
2883         return objid;
2884 }
2885
2886 static void samba_extended_info_version(struct smb_extended_info *extended_info)
2887 {
2888         SMB_ASSERT(extended_info != NULL);
2889
2890         extended_info->samba_magic = SAMBA_EXTENDED_INFO_MAGIC;
2891         extended_info->samba_version = ((SAMBA_VERSION_MAJOR & 0xff) << 24)
2892                                        | ((SAMBA_VERSION_MINOR & 0xff) << 16)
2893                                        | ((SAMBA_VERSION_RELEASE & 0xff) << 8);
2894 #ifdef SAMBA_VERSION_REVISION
2895         extended_info->samba_version |= (tolower(*SAMBA_VERSION_REVISION) - 'a' + 1) & 0xff;
2896 #endif
2897         extended_info->samba_subversion = 0;
2898 #ifdef SAMBA_VERSION_RC_RELEASE
2899         extended_info->samba_subversion |= (SAMBA_VERSION_RC_RELEASE & 0xff) << 24;
2900 #else
2901 #ifdef SAMBA_VERSION_PRE_RELEASE
2902         extended_info->samba_subversion |= (SAMBA_VERSION_PRE_RELEASE & 0xff) << 16;
2903 #endif
2904 #endif
2905 #ifdef SAMBA_VERSION_VENDOR_PATCH
2906         extended_info->samba_subversion |= (SAMBA_VERSION_VENDOR_PATCH & 0xffff);
2907 #endif
2908         extended_info->samba_gitcommitdate = 0;
2909 #ifdef SAMBA_VERSION_COMMIT_TIME
2910         unix_to_nt_time(&extended_info->samba_gitcommitdate, SAMBA_VERSION_COMMIT_TIME);
2911 #endif
2912
2913         memset(extended_info->samba_version_string, 0,
2914                sizeof(extended_info->samba_version_string));
2915
2916         snprintf (extended_info->samba_version_string,
2917                   sizeof(extended_info->samba_version_string),
2918                   "%s", samba_version_string());
2919 }
2920
2921 NTSTATUS smbd_do_qfsinfo(connection_struct *conn,
2922                          TALLOC_CTX *mem_ctx,
2923                          uint16_t info_level,
2924                          uint16_t flags2,
2925                          unsigned int max_data_bytes,
2926                          char **ppdata,
2927                          int *ret_data_len)
2928 {
2929         char *pdata, *end_data;
2930         int data_len = 0, len;
2931         const char *vname = volume_label(SNUM(conn));
2932         int snum = SNUM(conn);
2933         char *fstype = lp_fstype(SNUM(conn));
2934         uint32 additional_flags = 0;
2935         struct smb_filename smb_fname_dot;
2936         SMB_STRUCT_STAT st;
2937