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