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