s3-secdesc: remove "typedef struct security_descriptor SEC_DESC".
[kai/samba.git] / source3 / registry / regfio.c
1 /*
2  * Unix SMB/CIFS implementation.
3  * Windows NT registry I/O library
4  * Copyright (c) Gerald (Jerry) Carter               2005
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <http://www.gnu.org/licenses/>.  
18  */
19
20 #include "includes.h"
21 #include "regfio.h"
22 #include "reg_objects.h"
23
24 #undef DBGC_CLASS
25 #define DBGC_CLASS DBGC_REGISTRY
26
27 /*******************************************************************
28  *
29  * TODO : Right now this code basically ignores classnames.
30  *
31  ******************************************************************/
32
33
34 /*******************************************************************
35 *******************************************************************/
36
37 static int write_block( REGF_FILE *file, prs_struct *ps, uint32 offset )
38 {
39         int bytes_written, returned;
40         char *buffer = prs_data_p( ps );
41         uint32 buffer_size = prs_data_size( ps );
42         SMB_STRUCT_STAT sbuf;
43
44         if ( file->fd == -1 )
45                 return -1;
46
47         /* check for end of file */
48
49         if (sys_fstat(file->fd, &sbuf, false)) {
50                 DEBUG(0,("write_block: stat() failed! (%s)\n", strerror(errno)));
51                 return -1;
52         }
53
54         if ( lseek( file->fd, offset, SEEK_SET ) == -1 ) {
55                 DEBUG(0,("write_block: lseek() failed! (%s)\n", strerror(errno) ));
56                 return -1;
57         }
58         
59         bytes_written = returned = 0;
60         while ( bytes_written < buffer_size ) {
61                 if ( (returned = write( file->fd, buffer+bytes_written, buffer_size-bytes_written )) == -1 ) {
62                         DEBUG(0,("write_block: write() failed! (%s)\n", strerror(errno) ));
63                         return False;
64                 }
65                                 
66                 bytes_written += returned;
67         }
68         
69         return bytes_written;
70 }
71
72 /*******************************************************************
73 *******************************************************************/
74
75 static int read_block( REGF_FILE *file, prs_struct *ps, uint32 file_offset, uint32 block_size )
76 {
77         int bytes_read, returned;
78         char *buffer;
79         SMB_STRUCT_STAT sbuf;
80
81         /* check for end of file */
82
83         if (sys_fstat(file->fd, &sbuf, false)) {
84                 DEBUG(0,("read_block: stat() failed! (%s)\n", strerror(errno)));
85                 return -1;
86         }
87
88         if ( (size_t)file_offset >= sbuf.st_ex_size )
89                 return -1;
90         
91         /* if block_size == 0, we are parsing HBIN records and need 
92            to read some of the header to get the block_size from there */
93            
94         if ( block_size == 0 ) {
95                 char hdr[0x20];
96
97                 if ( lseek( file->fd, file_offset, SEEK_SET ) == -1 ) {
98                         DEBUG(0,("read_block: lseek() failed! (%s)\n", strerror(errno) ));
99                         return -1;
100                 }
101
102                 returned = read( file->fd, hdr, 0x20 );
103                 if ( (returned == -1) || (returned < 0x20) ) {
104                         DEBUG(0,("read_block: failed to read in HBIN header. Is the file corrupt?\n"));
105                         return -1;
106                 }
107
108                 /* make sure this is an hbin header */
109
110                 if ( strncmp( hdr, "hbin", HBIN_HDR_SIZE ) != 0 ) {
111                         DEBUG(0,("read_block: invalid block header!\n"));
112                         return -1;
113                 }
114
115                 block_size = IVAL( hdr, 0x08 );
116         }
117
118         DEBUG(10,("read_block: block_size == 0x%x\n", block_size ));
119
120         /* set the offset, initialize the buffer, and read the block from disk */
121
122         if ( lseek( file->fd, file_offset, SEEK_SET ) == -1 ) {
123                 DEBUG(0,("read_block: lseek() failed! (%s)\n", strerror(errno) ));
124                 return -1;
125         }
126         
127         if (!prs_init( ps, block_size, file->mem_ctx, UNMARSHALL )) {
128                 DEBUG(0,("read_block: prs_init() failed! (%s)\n", strerror(errno) ));
129                 return -1;
130         }
131         buffer = prs_data_p( ps );
132         bytes_read = returned = 0;
133
134         while ( bytes_read < block_size ) {
135                 if ( (returned = read( file->fd, buffer+bytes_read, block_size-bytes_read )) == -1 ) {
136                         DEBUG(0,("read_block: read() failed (%s)\n", strerror(errno) ));
137                         return False;
138                 }
139                 if ( (returned == 0) && (bytes_read < block_size) ) {
140                         DEBUG(0,("read_block: not a vald registry file ?\n" ));
141                         return False;
142                 }       
143                 
144                 bytes_read += returned;
145         }
146         
147         return bytes_read;
148 }
149
150 /*******************************************************************
151 *******************************************************************/
152
153 static bool write_hbin_block( REGF_FILE *file, REGF_HBIN *hbin )
154 {
155         if ( !hbin->dirty )
156                 return True;
157
158         /* write free space record if any is available */
159
160         if ( hbin->free_off != REGF_OFFSET_NONE ) {
161                 uint32 header = 0xffffffff;
162
163                 if ( !prs_set_offset( &hbin->ps, hbin->free_off-sizeof(uint32) ) )
164                         return False;
165                 if ( !prs_uint32( "free_size", &hbin->ps, 0, &hbin->free_size ) )
166                         return False;
167                 if ( !prs_uint32( "free_header", &hbin->ps, 0, &header ) )
168                         return False;
169         }
170
171         hbin->dirty = (write_block( file, &hbin->ps, hbin->file_off ) != -1);
172
173         return hbin->dirty;
174 }
175
176 /*******************************************************************
177 *******************************************************************/
178
179 static bool hbin_block_close( REGF_FILE *file, REGF_HBIN *hbin )
180 {
181         REGF_HBIN *p;
182
183         /* remove the block from the open list and flush it to disk */
184
185         for ( p=file->block_list; p && p!=hbin; p=p->next )
186                 ;;
187
188         if ( p == hbin ) {
189                 DLIST_REMOVE( file->block_list, hbin );
190         }
191         else
192                 DEBUG(0,("hbin_block_close: block not in open list!\n"));
193
194         if ( !write_hbin_block( file, hbin ) )
195                 return False;
196
197         return True;
198 }
199
200 /*******************************************************************
201 *******************************************************************/
202
203 static bool prs_regf_block( const char *desc, prs_struct *ps, int depth, REGF_FILE *file )
204 {
205         prs_debug(ps, depth, desc, "prs_regf_block");
206         depth++;
207         
208         if ( !prs_uint8s( True, "header", ps, depth, (uint8*)file->header, sizeof( file->header )) )
209                 return False;
210         
211         /* yes, these values are always identical so store them only once */
212         
213         if ( !prs_uint32( "unknown1", ps, depth, &file->unknown1 ))
214                 return False;
215         if ( !prs_uint32( "unknown1 (again)", ps, depth, &file->unknown1 ))
216                 return False;
217
218         /* get the modtime */
219         
220         if ( !prs_set_offset( ps, 0x0c ) )
221                 return False;
222         if ( !smb_io_time( "modtime", &file->mtime, ps, depth ) )
223                 return False;
224
225         /* constants */
226         
227         if ( !prs_uint32( "unknown2", ps, depth, &file->unknown2 ))
228                 return False;
229         if ( !prs_uint32( "unknown3", ps, depth, &file->unknown3 ))
230                 return False;
231         if ( !prs_uint32( "unknown4", ps, depth, &file->unknown4 ))
232                 return False;
233         if ( !prs_uint32( "unknown5", ps, depth, &file->unknown5 ))
234                 return False;
235
236         /* get file offsets */
237         
238         if ( !prs_set_offset( ps, 0x24 ) )
239                 return False;
240         if ( !prs_uint32( "data_offset", ps, depth, &file->data_offset ))
241                 return False;
242         if ( !prs_uint32( "last_block", ps, depth, &file->last_block ))
243                 return False;
244                 
245         /* one more constant */
246         
247         if ( !prs_uint32( "unknown6", ps, depth, &file->unknown6 ))
248                 return False;
249                 
250         /* get the checksum */
251         
252         if ( !prs_set_offset( ps, 0x01fc ) )
253                 return False;
254         if ( !prs_uint32( "checksum", ps, depth, &file->checksum ))
255                 return False;
256         
257         return True;
258 }
259
260 /*******************************************************************
261 *******************************************************************/
262
263 static bool prs_hbin_block( const char *desc, prs_struct *ps, int depth, REGF_HBIN *hbin )
264 {
265         uint32 block_size2;
266
267         prs_debug(ps, depth, desc, "prs_regf_block");
268         depth++;
269         
270         if ( !prs_uint8s( True, "header", ps, depth, (uint8*)hbin->header, sizeof( hbin->header )) )
271                 return False;
272
273         if ( !prs_uint32( "first_hbin_off", ps, depth, &hbin->first_hbin_off ))
274                 return False;
275
276         /* The dosreg.cpp comments say that the block size is at 0x1c.
277            According to a WINXP NTUSER.dat file, this is wrong.  The block_size
278            is at 0x08 */
279
280         if ( !prs_uint32( "block_size", ps, depth, &hbin->block_size ))
281                 return False;
282
283         block_size2 = hbin->block_size;
284         prs_set_offset( ps, 0x1c );
285         if ( !prs_uint32( "block_size2", ps, depth, &block_size2 ))
286                 return False;
287
288         if ( MARSHALLING(ps) )
289                 hbin->dirty = True;
290         
291
292         return True;
293 }
294
295 /*******************************************************************
296 *******************************************************************/
297
298 static bool prs_nk_rec( const char *desc, prs_struct *ps, int depth, REGF_NK_REC *nk )
299 {
300         uint16 class_length, name_length;
301         uint32 start;
302         uint32 data_size, start_off, end_off;
303         uint32 unknown_off = REGF_OFFSET_NONE;
304
305         nk->hbin_off = prs_offset( ps );
306         start = nk->hbin_off;
307         
308         prs_debug(ps, depth, desc, "prs_nk_rec");
309         depth++;
310         
311         /* back up and get the data_size */
312         
313         if ( !prs_set_offset( ps, prs_offset(ps)-sizeof(uint32)) )
314                 return False;
315         start_off = prs_offset( ps );
316         if ( !prs_uint32( "rec_size", ps, depth, &nk->rec_size ))
317                 return False;
318         
319         if ( !prs_uint8s( True, "header", ps, depth, (uint8*)nk->header, sizeof( nk->header )) )
320                 return False;
321                 
322         if ( !prs_uint16( "key_type", ps, depth, &nk->key_type ))
323                 return False;
324         if ( !smb_io_time( "mtime", &nk->mtime, ps, depth ))
325                 return False;
326                 
327         if ( !prs_set_offset( ps, start+0x0010 ) )
328                 return False;
329         if ( !prs_uint32( "parent_off", ps, depth, &nk->parent_off ))
330                 return False;
331         if ( !prs_uint32( "num_subkeys", ps, depth, &nk->num_subkeys ))
332                 return False;
333                 
334         if ( !prs_set_offset( ps, start+0x001c ) )
335                 return False;
336         if ( !prs_uint32( "subkeys_off", ps, depth, &nk->subkeys_off ))
337                 return False;
338         if ( !prs_uint32( "unknown_off", ps, depth, &unknown_off) )
339                 return False;
340                 
341         if ( !prs_set_offset( ps, start+0x0024 ) )
342                 return False;
343         if ( !prs_uint32( "num_values", ps, depth, &nk->num_values ))
344                 return False;
345         if ( !prs_uint32( "values_off", ps, depth, &nk->values_off ))
346                 return False;
347         if ( !prs_uint32( "sk_off", ps, depth, &nk->sk_off ))
348                 return False;
349         if ( !prs_uint32( "classname_off", ps, depth, &nk->classname_off ))
350                 return False;
351
352         if ( !prs_uint32( "max_bytes_subkeyname", ps, depth, &nk->max_bytes_subkeyname))
353                 return False;
354         if ( !prs_uint32( "max_bytes_subkeyclassname", ps, depth, &nk->max_bytes_subkeyclassname))
355                 return False;
356         if ( !prs_uint32( "max_bytes_valuename", ps, depth, &nk->max_bytes_valuename))
357                 return False;
358         if ( !prs_uint32( "max_bytes_value", ps, depth, &nk->max_bytes_value))
359                 return False;
360         if ( !prs_uint32( "unknown index", ps, depth, &nk->unk_index))
361                 return False;
362
363         name_length = nk->keyname ? strlen(nk->keyname) : 0 ;
364         class_length = nk->classname ? strlen(nk->classname) : 0 ;
365         if ( !prs_uint16( "name_length", ps, depth, &name_length ))
366                 return False;
367         if ( !prs_uint16( "class_length", ps, depth, &class_length ))
368                 return False;   
369                 
370         if ( class_length ) {
371                 ;;
372         }
373         
374         if ( name_length ) {
375                 if ( UNMARSHALLING(ps) ) {
376                         if ( !(nk->keyname = PRS_ALLOC_MEM( ps, char, name_length+1 )) )
377                                 return False;
378                 }
379
380                 if ( !prs_uint8s( True, "name", ps, depth, (uint8*)nk->keyname, name_length) )
381                         return False;
382
383                 if ( UNMARSHALLING(ps) ) 
384                         nk->keyname[name_length] = '\0';
385         }
386
387         end_off = prs_offset( ps );
388
389         /* data_size must be divisible by 8 and large enough to hold the original record */
390
391         data_size = ((start_off - end_off) & 0xfffffff8 );
392         if ( data_size > nk->rec_size )
393                 DEBUG(10,("Encountered reused record (0x%x < 0x%x)\n", data_size, nk->rec_size));
394
395         if ( MARSHALLING(ps) )
396                 nk->hbin->dirty = True;
397
398         return True;
399 }
400
401 /*******************************************************************
402 *******************************************************************/
403
404 static uint32 regf_block_checksum( prs_struct *ps )
405 {
406         char *buffer = prs_data_p( ps );
407         uint32 checksum, x;
408         int i;
409
410         /* XOR of all bytes 0x0000 - 0x01FB */
411                 
412         checksum = x = 0;
413         
414         for ( i=0; i<0x01FB; i+=4 ) {
415                 x = IVAL(buffer, i );
416                 checksum ^= x;
417         }
418         
419         return checksum;
420 }
421
422 /*******************************************************************
423 *******************************************************************/
424
425 static bool read_regf_block( REGF_FILE *file )
426 {
427         prs_struct ps;
428         uint32 checksum;
429         
430         /* grab the first block from the file */
431                 
432         if ( read_block( file, &ps, 0, REGF_BLOCKSIZE ) == -1 )
433                 return False;
434         
435         /* parse the block and verify the checksum */
436         
437         if ( !prs_regf_block( "regf_header", &ps, 0, file ) )
438                 return False;   
439                 
440         checksum = regf_block_checksum( &ps );
441         
442         prs_mem_free( &ps );
443         
444         if ( file->checksum !=  checksum ) {
445                 DEBUG(0,("read_regf_block: invalid checksum\n" ));
446                 return False;
447         }
448
449         return True;
450 }
451
452 /*******************************************************************
453 *******************************************************************/
454
455 static REGF_HBIN* read_hbin_block( REGF_FILE *file, off_t offset )
456 {
457         REGF_HBIN *hbin;
458         uint32 record_size, curr_off, block_size, header;
459         
460         if ( !(hbin = TALLOC_ZERO_P(file->mem_ctx, REGF_HBIN)) ) 
461                 return NULL;
462         hbin->file_off = offset;
463         hbin->free_off = -1;
464                 
465         if ( read_block( file, &hbin->ps, offset, 0 ) == -1 )
466                 return NULL;
467         
468         if ( !prs_hbin_block( "hbin", &hbin->ps, 0, hbin ) )
469                 return NULL;    
470
471         /* this should be the same thing as hbin->block_size but just in case */
472
473         block_size = prs_data_size( &hbin->ps );        
474
475         /* Find the available free space offset.  Always at the end,
476            so walk the record list and stop when you get to the end.
477            The end is defined by a record header of 0xffffffff.  The 
478            previous 4 bytes contains the amount of free space remaining 
479            in the hbin block. */
480
481         /* remember that the record_size is in the 4 bytes preceeding the record itself */
482
483         if ( !prs_set_offset( &hbin->ps, file->data_offset+HBIN_HDR_SIZE-sizeof(uint32) ) )
484                 return False;
485
486         record_size = 0;
487         header = 0;
488         curr_off = prs_offset( &hbin->ps );
489         while ( header != 0xffffffff ) {
490                 /* not done yet so reset the current offset to the 
491                    next record_size field */
492
493                 curr_off = curr_off+record_size;
494
495                 /* for some reason the record_size of the last record in
496                    an hbin block can extend past the end of the block
497                    even though the record fits within the remaining 
498                    space....aaarrrgggghhhhhh */
499
500                 if ( curr_off >= block_size ) {
501                         record_size = -1;
502                         curr_off = -1;
503                         break;
504                 }
505
506                 if ( !prs_set_offset( &hbin->ps, curr_off) )
507                         return False;
508
509                 if ( !prs_uint32( "rec_size", &hbin->ps, 0, &record_size ) )
510                         return False;
511                 if ( !prs_uint32( "header", &hbin->ps, 0, &header ) )
512                         return False;
513                 
514                 SMB_ASSERT( record_size != 0 );
515
516                 if ( record_size & 0x80000000 ) {
517                         /* absolute_value(record_size) */
518                         record_size = (record_size ^ 0xffffffff) + 1;
519                 }
520         }
521
522         /* save the free space offset */
523
524         if ( header == 0xffffffff ) {
525
526                 /* account for the fact that the curr_off is 4 bytes behind the actual 
527                    record header */
528
529                 hbin->free_off = curr_off + sizeof(uint32);
530                 hbin->free_size = record_size;
531         }
532
533         DEBUG(10,("read_hbin_block: free space offset == 0x%x\n", hbin->free_off));
534
535         if ( !prs_set_offset( &hbin->ps, file->data_offset+HBIN_HDR_SIZE )  )
536                 return False;
537         
538         return hbin;
539 }
540
541 /*******************************************************************
542  Input a random offset and receive the corresponding HBIN 
543  block for it
544 *******************************************************************/
545
546 static bool hbin_contains_offset( REGF_HBIN *hbin, uint32 offset )
547 {
548         if ( !hbin )
549                 return False;
550         
551         if ( (offset > hbin->first_hbin_off) && (offset < (hbin->first_hbin_off+hbin->block_size)) )
552                 return True;
553                 
554         return False;
555 }
556
557 /*******************************************************************
558  Input a random offset and receive the corresponding HBIN 
559  block for it
560 *******************************************************************/
561
562 static REGF_HBIN* lookup_hbin_block( REGF_FILE *file, uint32 offset )
563 {
564         REGF_HBIN *hbin = NULL;
565         uint32 block_off;
566
567         /* start with the open list */
568
569         for ( hbin=file->block_list; hbin; hbin=hbin->next ) {
570                 DEBUG(10,("lookup_hbin_block: address = 0x%x [0x%lx]\n", hbin->file_off, (unsigned long)hbin ));
571                 if ( hbin_contains_offset( hbin, offset ) )
572                         return hbin;
573         }
574         
575         if ( !hbin ) {
576                 /* start at the beginning */
577
578                 block_off = REGF_BLOCKSIZE;
579                 do {
580                         /* cleanup before the next round */
581                         if ( hbin )
582                                 prs_mem_free( &hbin->ps );
583
584                         hbin = read_hbin_block( file, block_off );
585
586                         if ( hbin ) 
587                                 block_off = hbin->file_off + hbin->block_size;
588
589                 } while ( hbin && !hbin_contains_offset( hbin, offset ) );
590         }
591
592         if ( hbin )
593                 DLIST_ADD( file->block_list, hbin );
594
595         return hbin;
596 }
597
598 /*******************************************************************
599 *******************************************************************/
600
601 static bool prs_hash_rec( const char *desc, prs_struct *ps, int depth, REGF_HASH_REC *hash )
602 {
603         prs_debug(ps, depth, desc, "prs_hash_rec");
604         depth++;
605
606         if ( !prs_uint32( "nk_off", ps, depth, &hash->nk_off ))
607                 return False;
608         if ( !prs_uint8s( True, "keycheck", ps, depth, hash->keycheck, sizeof( hash->keycheck )) )
609                 return False;
610         
611         return True;
612 }
613
614 /*******************************************************************
615 *******************************************************************/
616
617 static bool hbin_prs_lf_records( const char *desc, REGF_HBIN *hbin, int depth, REGF_NK_REC *nk )
618 {
619         int i;
620         REGF_LF_REC *lf = &nk->subkeys;
621         uint32 data_size, start_off, end_off;
622
623         prs_debug(&hbin->ps, depth, desc, "prs_lf_records");
624         depth++;
625
626         /* check if we have anything to do first */
627         
628         if ( nk->num_subkeys == 0 )
629                 return True;
630
631         /* move to the LF record */
632
633         if ( !prs_set_offset( &hbin->ps, nk->subkeys_off + HBIN_HDR_SIZE - hbin->first_hbin_off ) )
634                 return False;
635
636         /* backup and get the data_size */
637         
638         if ( !prs_set_offset( &hbin->ps, prs_offset(&hbin->ps)-sizeof(uint32)) )
639                 return False;
640         start_off = prs_offset( &hbin->ps );
641         if ( !prs_uint32( "rec_size", &hbin->ps, depth, &lf->rec_size ))
642                 return False;
643
644         if ( !prs_uint8s( True, "header", &hbin->ps, depth, (uint8*)lf->header, sizeof( lf->header )) )
645                 return False;
646                 
647         if ( !prs_uint16( "num_keys", &hbin->ps, depth, &lf->num_keys))
648                 return False;
649
650         if ( UNMARSHALLING(&hbin->ps) ) {
651                 if (lf->num_keys) {
652                         if ( !(lf->hashes = PRS_ALLOC_MEM( &hbin->ps, REGF_HASH_REC, lf->num_keys )) )
653                                 return False;
654                 } else {
655                         lf->hashes = NULL;
656                 }
657         }
658
659         for ( i=0; i<lf->num_keys; i++ ) {
660                 if ( !prs_hash_rec( "hash_rec", &hbin->ps, depth, &lf->hashes[i] ) )
661                         return False;
662         }
663
664         end_off = prs_offset( &hbin->ps );
665
666         /* data_size must be divisible by 8 and large enough to hold the original record */
667
668         data_size = ((start_off - end_off) & 0xfffffff8 );
669         if ( data_size > lf->rec_size )
670                 DEBUG(10,("Encountered reused record (0x%x < 0x%x)\n", data_size, lf->rec_size));
671
672         if ( MARSHALLING(&hbin->ps) )
673                 hbin->dirty = True;
674
675         return True;
676 }
677
678 /*******************************************************************
679 *******************************************************************/
680
681 static bool hbin_prs_sk_rec( const char *desc, REGF_HBIN *hbin, int depth, REGF_SK_REC *sk )
682 {
683         prs_struct *ps = &hbin->ps;
684         uint16 tag = 0xFFFF;
685         uint32 data_size, start_off, end_off;
686
687
688         prs_debug(ps, depth, desc, "hbin_prs_sk_rec");
689         depth++;
690
691         if ( !prs_set_offset( &hbin->ps, sk->sk_off + HBIN_HDR_SIZE - hbin->first_hbin_off ) )
692                 return False;
693
694         /* backup and get the data_size */
695         
696         if ( !prs_set_offset( &hbin->ps, prs_offset(&hbin->ps)-sizeof(uint32)) )
697                 return False;
698         start_off = prs_offset( &hbin->ps );
699         if ( !prs_uint32( "rec_size", &hbin->ps, depth, &sk->rec_size ))
700                 return False;
701
702         if ( !prs_uint8s( True, "header", ps, depth, (uint8*)sk->header, sizeof( sk->header )) )
703                 return False;
704         if ( !prs_uint16( "tag", ps, depth, &tag))
705                 return False;
706
707         if ( !prs_uint32( "prev_sk_off", ps, depth, &sk->prev_sk_off))
708                 return False;
709         if ( !prs_uint32( "next_sk_off", ps, depth, &sk->next_sk_off))
710                 return False;
711         if ( !prs_uint32( "ref_count", ps, depth, &sk->ref_count))
712                 return False;
713         if ( !prs_uint32( "size", ps, depth, &sk->size))
714                 return False;
715
716         {
717                 NTSTATUS status;
718                 TALLOC_CTX *mem_ctx = prs_get_mem_context(&hbin->ps);
719                 DATA_BLOB blob;
720
721                 if (MARSHALLING(&hbin->ps)) {
722                         status = marshall_sec_desc(mem_ctx,
723                                                    sk->sec_desc,
724                                                    &blob.data, &blob.length);
725                         if (!NT_STATUS_IS_OK(status))
726                                 return False;
727                         if (!prs_copy_data_in(&hbin->ps, (const char *)blob.data, blob.length))
728                                 return False;
729                 } else {
730                         blob = data_blob_const(prs_data_p(&hbin->ps),
731                                                prs_data_size(&hbin->ps));
732                         status = unmarshall_sec_desc(mem_ctx,
733                                                      blob.data, blob.length,
734                                                      &sk->sec_desc);
735                         if (!NT_STATUS_IS_OK(status))
736                                 return False;
737                         prs_set_offset(&hbin->ps, blob.length);
738                 }
739         }
740
741         end_off = prs_offset( &hbin->ps );
742
743         /* data_size must be divisible by 8 and large enough to hold the original record */
744
745         data_size = ((start_off - end_off) & 0xfffffff8 );
746         if ( data_size > sk->rec_size )
747                 DEBUG(10,("Encountered reused record (0x%x < 0x%x)\n", data_size, sk->rec_size));
748
749         if ( MARSHALLING(&hbin->ps) )
750                 hbin->dirty = True;
751
752         return True;
753 }
754
755 /*******************************************************************
756 *******************************************************************/
757
758 static bool hbin_prs_vk_rec( const char *desc, REGF_HBIN *hbin, int depth, REGF_VK_REC *vk, REGF_FILE *file )
759 {
760         uint32 offset;
761         uint16 name_length;
762         prs_struct *ps = &hbin->ps;
763         uint32 data_size, start_off, end_off;
764
765         prs_debug(ps, depth, desc, "prs_vk_rec");
766         depth++;
767
768         /* backup and get the data_size */
769         
770         if ( !prs_set_offset( &hbin->ps, prs_offset(&hbin->ps)-sizeof(uint32)) )
771                 return False;
772         start_off = prs_offset( &hbin->ps );
773         if ( !prs_uint32( "rec_size", &hbin->ps, depth, &vk->rec_size ))
774                 return False;
775
776         if ( !prs_uint8s( True, "header", ps, depth, (uint8*)vk->header, sizeof( vk->header )) )
777                 return False;
778
779         if ( MARSHALLING(&hbin->ps) )
780                 name_length = strlen(vk->valuename);
781
782         if ( !prs_uint16( "name_length", ps, depth, &name_length ))
783                 return False;
784         if ( !prs_uint32( "data_size", ps, depth, &vk->data_size ))
785                 return False;
786         if ( !prs_uint32( "data_off", ps, depth, &vk->data_off ))
787                 return False;
788         if ( !prs_uint32( "type", ps, depth, &vk->type))
789                 return False;
790         if ( !prs_uint16( "flag", ps, depth, &vk->flag))
791                 return False;
792
793         offset = prs_offset( ps );
794         offset += 2;    /* skip 2 bytes */
795         prs_set_offset( ps, offset );
796
797         /* get the name */
798
799         if ( vk->flag&VK_FLAG_NAME_PRESENT ) {
800
801                 if ( UNMARSHALLING(&hbin->ps) ) {
802                         if ( !(vk->valuename = PRS_ALLOC_MEM( ps, char, name_length+1 )))
803                                 return False;
804                 }
805                 if ( !prs_uint8s( True, "name", ps, depth, (uint8*)vk->valuename, name_length ) )
806                         return False;
807         }
808
809         end_off = prs_offset( &hbin->ps );
810
811         /* get the data if necessary */
812
813         if ( vk->data_size != 0 ) {
814                 bool charmode = False;
815
816                 if ( (vk->type == REG_SZ) || (vk->type == REG_MULTI_SZ) )
817                         charmode = True;
818
819                 /* the data is stored in the offset if the size <= 4 */
820
821                 if ( !(vk->data_size & VK_DATA_IN_OFFSET) ) {
822                         REGF_HBIN *hblock = hbin;
823                         uint32 data_rec_size;
824
825                         if ( UNMARSHALLING(&hbin->ps) ) {
826                                 if ( !(vk->data = PRS_ALLOC_MEM( ps, uint8, vk->data_size) ) )
827                                         return False;
828                         }
829
830                         /* this data can be in another hbin */
831                         if ( !hbin_contains_offset( hbin, vk->data_off ) ) {
832                                 if ( !(hblock = lookup_hbin_block( file, vk->data_off )) )
833                                         return False;
834                         }
835                         if ( !(prs_set_offset( &hblock->ps, (vk->data_off+HBIN_HDR_SIZE-hblock->first_hbin_off)-sizeof(uint32) )) )
836                                 return False;
837
838                         if ( MARSHALLING(&hblock->ps) ) {
839                                 data_rec_size = ( (vk->data_size+sizeof(uint32)) & 0xfffffff8 ) + 8;
840                                 data_rec_size = ( data_rec_size - 1 ) ^ 0xFFFFFFFF;
841                         }
842                         if ( !prs_uint32( "data_rec_size", &hblock->ps, depth, &data_rec_size ))
843                                 return False;
844                         if ( !prs_uint8s( charmode, "data", &hblock->ps, depth, vk->data, vk->data_size) )
845                                 return False;
846
847                         if ( MARSHALLING(&hblock->ps) )
848                                 hblock->dirty = True;
849                 }
850                 else {
851                         if ( !(vk->data = PRS_ALLOC_MEM( ps, uint8, 4 ) ) )
852                                 return False;
853                         SIVAL( vk->data, 0, vk->data_off );
854                 }
855                 
856         }
857
858         /* data_size must be divisible by 8 and large enough to hold the original record */
859
860         data_size = ((start_off - end_off ) & 0xfffffff8 );
861         if ( data_size !=  vk->rec_size )
862                 DEBUG(10,("prs_vk_rec: data_size check failed (0x%x < 0x%x)\n", data_size, vk->rec_size));
863
864         if ( MARSHALLING(&hbin->ps) )
865                 hbin->dirty = True;
866
867         return True;
868 }
869
870 /*******************************************************************
871  read a VK record which is contained in the HBIN block stored 
872  in the prs_struct *ps.
873 *******************************************************************/
874
875 static bool hbin_prs_vk_records( const char *desc, REGF_HBIN *hbin, int depth, REGF_NK_REC *nk, REGF_FILE *file )
876 {
877         int i;
878         uint32 record_size;
879
880         prs_debug(&hbin->ps, depth, desc, "prs_vk_records");
881         depth++;
882         
883         /* check if we have anything to do first */
884         
885         if ( nk->num_values == 0 )
886                 return True;
887                 
888         if ( UNMARSHALLING(&hbin->ps) ) {
889                 if ( !(nk->values = PRS_ALLOC_MEM( &hbin->ps, REGF_VK_REC, nk->num_values ) ) )
890                         return False;
891         }
892         
893         /* convert the offset to something relative to this HBIN block */
894         
895         if ( !prs_set_offset( &hbin->ps, nk->values_off+HBIN_HDR_SIZE-hbin->first_hbin_off-sizeof(uint32)) )
896                 return False;
897
898         if ( MARSHALLING( &hbin->ps) ) { 
899                 record_size = ( ( nk->num_values * sizeof(uint32) ) & 0xfffffff8 ) + 8;
900                 record_size = (record_size - 1) ^ 0xFFFFFFFF;
901         }
902
903         if ( !prs_uint32( "record_size", &hbin->ps, depth, &record_size ) )
904                 return False;
905                 
906         for ( i=0; i<nk->num_values; i++ ) {
907                 if ( !prs_uint32( "vk_off", &hbin->ps, depth, &nk->values[i].rec_off ) )
908                         return False;
909         }
910
911         for ( i=0; i<nk->num_values; i++ ) {
912                 REGF_HBIN *sub_hbin = hbin;
913                 uint32 new_offset;
914         
915                 if ( !hbin_contains_offset( hbin, nk->values[i].rec_off ) ) {
916                         sub_hbin = lookup_hbin_block( file, nk->values[i].rec_off );
917                         if ( !sub_hbin ) {
918                                 DEBUG(0,("hbin_prs_vk_records: Failed to find HBIN block containing offset [0x%x]\n", 
919                                         nk->values[i].hbin_off));
920                                 return False;
921                         }
922                 }
923                 
924                 new_offset = nk->values[i].rec_off + HBIN_HDR_SIZE - sub_hbin->first_hbin_off;
925                 if ( !prs_set_offset( &sub_hbin->ps, new_offset ) )
926                         return False;
927                 if ( !hbin_prs_vk_rec( "vk_rec", sub_hbin, depth, &nk->values[i], file ) )
928                         return False;
929         }
930
931         if ( MARSHALLING(&hbin->ps) )
932                 hbin->dirty = True;
933
934
935         return True;
936 }
937
938
939 /*******************************************************************
940 *******************************************************************/
941
942 static REGF_SK_REC* find_sk_record_by_offset( REGF_FILE *file, uint32 offset )
943 {
944         REGF_SK_REC *p_sk;
945         
946         for ( p_sk=file->sec_desc_list; p_sk; p_sk=p_sk->next ) {
947                 if ( p_sk->sk_off == offset ) 
948                         return p_sk;
949         }
950         
951         return NULL;
952 }
953
954 /*******************************************************************
955 *******************************************************************/
956
957 static REGF_SK_REC* find_sk_record_by_sec_desc( REGF_FILE *file, struct security_descriptor *sd )
958 {
959         REGF_SK_REC *p;
960
961         for ( p=file->sec_desc_list; p; p=p->next ) {
962                 if ( security_descriptor_equal( p->sec_desc, sd ) )
963                         return p;
964         }
965
966         /* failure */
967
968         return NULL;
969 }
970
971 /*******************************************************************
972 *******************************************************************/
973
974 static bool hbin_prs_key( REGF_FILE *file, REGF_HBIN *hbin, REGF_NK_REC *nk )
975 {
976         int depth = 0;
977         REGF_HBIN *sub_hbin;
978         
979         prs_debug(&hbin->ps, depth, "", "fetch_key");
980         depth++;
981
982         /* get the initial nk record */
983         
984         if ( !prs_nk_rec( "nk_rec", &hbin->ps, depth, nk ))
985                 return False;
986
987         /* fill in values */
988         
989         if ( nk->num_values && (nk->values_off!=REGF_OFFSET_NONE) ) {
990                 sub_hbin = hbin;
991                 if ( !hbin_contains_offset( hbin, nk->values_off ) ) {
992                         sub_hbin = lookup_hbin_block( file, nk->values_off );
993                         if ( !sub_hbin ) {
994                                 DEBUG(0,("hbin_prs_key: Failed to find HBIN block containing value_list_offset [0x%x]\n", 
995                                         nk->values_off));
996                                 return False;
997                         }
998                 }
999                 
1000                 if ( !hbin_prs_vk_records( "vk_rec", sub_hbin, depth, nk, file ))
1001                         return False;
1002         }
1003                 
1004         /* now get subkeys */
1005         
1006         if ( nk->num_subkeys && (nk->subkeys_off!=REGF_OFFSET_NONE) ) {
1007                 sub_hbin = hbin;
1008                 if ( !hbin_contains_offset( hbin, nk->subkeys_off ) ) {
1009                         sub_hbin = lookup_hbin_block( file, nk->subkeys_off );
1010                         if ( !sub_hbin ) {
1011                                 DEBUG(0,("hbin_prs_key: Failed to find HBIN block containing subkey_offset [0x%x]\n", 
1012                                         nk->subkeys_off));
1013                                 return False;
1014                         }
1015                 }
1016                 
1017                 if ( !hbin_prs_lf_records( "lf_rec", sub_hbin, depth, nk ))
1018                         return False;
1019         }
1020
1021         /* get the to the security descriptor.  First look if we have already parsed it */
1022         
1023         if ( (nk->sk_off!=REGF_OFFSET_NONE) && !( nk->sec_desc = find_sk_record_by_offset( file, nk->sk_off )) ) {
1024
1025                 sub_hbin = hbin;
1026                 if ( !hbin_contains_offset( hbin, nk->sk_off ) ) {
1027                         sub_hbin = lookup_hbin_block( file, nk->sk_off );
1028                         if ( !sub_hbin ) {
1029                                 DEBUG(0,("hbin_prs_key: Failed to find HBIN block containing sk_offset [0x%x]\n", 
1030                                         nk->subkeys_off));
1031                                 return False;
1032                         }
1033                 }
1034                 
1035                 if ( !(nk->sec_desc = TALLOC_ZERO_P( file->mem_ctx, REGF_SK_REC )) )
1036                         return False;
1037                 nk->sec_desc->sk_off = nk->sk_off;
1038                 if ( !hbin_prs_sk_rec( "sk_rec", sub_hbin, depth, nk->sec_desc ))
1039                         return False;
1040                         
1041                 /* add to the list of security descriptors (ref_count has been read from the files) */
1042
1043                 nk->sec_desc->sk_off = nk->sk_off;
1044                 DLIST_ADD( file->sec_desc_list, nk->sec_desc );
1045         }
1046                 
1047         return True;
1048 }
1049
1050 /*******************************************************************
1051 *******************************************************************/
1052
1053 static bool next_record( REGF_HBIN *hbin, const char *hdr, bool *eob )
1054 {
1055         uint8 header[REC_HDR_SIZE];
1056         uint32 record_size;
1057         uint32 curr_off, block_size;
1058         bool found = False;
1059         prs_struct *ps = &hbin->ps;
1060         
1061         curr_off = prs_offset( ps );
1062         if ( curr_off == 0 )
1063                 prs_set_offset( ps, HBIN_HEADER_REC_SIZE );
1064
1065         /* assume that the current offset is at the record header 
1066            and we need to backup to read the record size */
1067
1068         curr_off -= sizeof(uint32);
1069
1070         block_size = prs_data_size( ps );
1071         record_size = 0;
1072         memset( header, 0x0, sizeof(uint8)*REC_HDR_SIZE );
1073         while ( !found ) {
1074
1075                 curr_off = curr_off+record_size;
1076                 if ( curr_off >= block_size ) 
1077                         break;
1078
1079                 if ( !prs_set_offset( &hbin->ps, curr_off) )
1080                         return False;
1081
1082                 if ( !prs_uint32( "record_size", ps, 0, &record_size ) )
1083                         return False;
1084                 if ( !prs_uint8s( True, "header", ps, 0, header, REC_HDR_SIZE ) )
1085                         return False;
1086
1087                 if ( record_size & 0x80000000 ) {
1088                         /* absolute_value(record_size) */
1089                         record_size = (record_size ^ 0xffffffff) + 1;
1090                 }
1091
1092                 if ( memcmp( header, hdr, REC_HDR_SIZE ) == 0 ) {
1093                         found = True;
1094                         curr_off += sizeof(uint32);
1095                 }
1096         } 
1097
1098         /* mark prs_struct as done ( at end ) if no more SK records */
1099         /* mark end-of-block as True */
1100         
1101         if ( !found ) {
1102                 prs_set_offset( &hbin->ps, prs_data_size(&hbin->ps) );
1103                 *eob = True;
1104                 return False;
1105         }
1106                 
1107         if ( !prs_set_offset( ps, curr_off ) )
1108                 return False;
1109
1110         return True;
1111 }
1112
1113 /*******************************************************************
1114 *******************************************************************/
1115
1116 static bool next_nk_record( REGF_FILE *file, REGF_HBIN *hbin, REGF_NK_REC *nk, bool *eob )
1117 {
1118         if ( next_record( hbin, "nk", eob ) && hbin_prs_key( file, hbin, nk ) )
1119                 return True;
1120         
1121         return False;
1122 }
1123
1124 /*******************************************************************
1125  Intialize the newly created REGF_BLOCK in *file and write the 
1126  block header to disk 
1127 *******************************************************************/
1128
1129 static bool init_regf_block( REGF_FILE *file )
1130 {       
1131         prs_struct ps;
1132         bool result = True;
1133         
1134         if ( !prs_init( &ps, REGF_BLOCKSIZE, file->mem_ctx, MARSHALL ) )
1135                 return False;
1136                 
1137         memcpy( file->header, "regf", REGF_HDR_SIZE );
1138         file->data_offset = 0x20;
1139         file->last_block  = 0x1000;
1140         
1141         /* set mod time */
1142         
1143         unix_to_nt_time( &file->mtime, time(NULL) );
1144         
1145         /* hard coded values...no diea what these are ... maybe in time */
1146         
1147         file->unknown1 = 0x2;
1148         file->unknown2 = 0x1;
1149         file->unknown3 = 0x3;
1150         file->unknown4 = 0x0;
1151         file->unknown5 = 0x1;
1152         file->unknown6 = 0x1;
1153         
1154         /* write header to the buffer */
1155         
1156         if ( !prs_regf_block( "regf_header", &ps, 0, file ) ) {
1157                 result = False;
1158                 goto out;
1159         }
1160         
1161         /* calculate the checksum, re-marshall data (to include the checksum) 
1162            and write to disk */
1163         
1164         file->checksum = regf_block_checksum( &ps );
1165         prs_set_offset( &ps, 0 );
1166         if ( !prs_regf_block( "regf_header", &ps, 0, file ) ) {
1167                 result = False;
1168                 goto out;
1169         }
1170                 
1171         if ( write_block( file, &ps, 0 ) == -1 ) {
1172                 DEBUG(0,("init_regf_block: Failed to initialize registry header block!\n"));
1173                 result = False;
1174                 goto out;
1175         }
1176         
1177 out:
1178         prs_mem_free( &ps );
1179
1180         return result;
1181 }
1182 /*******************************************************************
1183  Open the registry file and then read in the REGF block to get the 
1184  first hbin offset.
1185 *******************************************************************/
1186
1187  REGF_FILE* regfio_open( const char *filename, int flags, int mode )
1188 {
1189         REGF_FILE *rb;
1190         
1191         if ( !(rb = SMB_MALLOC_P(REGF_FILE)) ) {
1192                 DEBUG(0,("ERROR allocating memory\n"));
1193                 return NULL;
1194         }
1195         ZERO_STRUCTP( rb );
1196         rb->fd = -1;
1197         
1198         if ( !(rb->mem_ctx = talloc_init( "read_regf_block" )) ) {
1199                 regfio_close( rb );
1200                 return NULL;
1201         }
1202
1203         rb->open_flags = flags;
1204         
1205         /* open and existing file */
1206
1207         if ( (rb->fd = open(filename, flags, mode)) == -1 ) {
1208                 DEBUG(0,("regfio_open: failure to open %s (%s)\n", filename, strerror(errno)));
1209                 regfio_close( rb );
1210                 return NULL;
1211         }
1212         
1213         /* check if we are creating a new file or overwriting an existing one */
1214                 
1215         if ( flags & (O_CREAT|O_TRUNC) ) {
1216                 if ( !init_regf_block( rb ) ) {
1217                         DEBUG(0,("regfio_open: Failed to read initial REGF block\n"));
1218                         regfio_close( rb );
1219                         return NULL;
1220                 }
1221                 
1222                 /* success */
1223                 return rb;
1224         }
1225         
1226         /* read in an existing file */
1227         
1228         if ( !read_regf_block( rb ) ) {
1229                 DEBUG(0,("regfio_open: Failed to read initial REGF block\n"));
1230                 regfio_close( rb );
1231                 return NULL;
1232         }
1233         
1234         /* success */
1235         
1236         return rb;
1237 }
1238
1239 /*******************************************************************
1240 *******************************************************************/
1241
1242 static void regfio_mem_free( REGF_FILE *file )
1243 {
1244         /* free any talloc()'d memory */
1245         
1246         if ( file && file->mem_ctx )
1247                 talloc_destroy( file->mem_ctx );        
1248 }
1249
1250 /*******************************************************************
1251 *******************************************************************/
1252
1253  int regfio_close( REGF_FILE *file )
1254 {
1255         int fd;
1256
1257         /* cleanup for a file opened for write */
1258
1259         if ((file->fd != -1) && (file->open_flags & (O_WRONLY|O_RDWR))) {
1260                 prs_struct ps;
1261                 REGF_SK_REC *sk;
1262
1263                 /* write of sd list */
1264
1265                 for ( sk=file->sec_desc_list; sk; sk=sk->next ) {
1266                         hbin_prs_sk_rec( "sk_rec", sk->hbin, 0, sk );
1267                 }
1268
1269                 /* flush any dirty blocks */
1270
1271                 while ( file->block_list ) {
1272                         hbin_block_close( file, file->block_list );
1273                 } 
1274
1275                 ZERO_STRUCT( ps );
1276
1277                 unix_to_nt_time( &file->mtime, time(NULL) );
1278
1279                 if ( read_block( file, &ps, 0, REGF_BLOCKSIZE ) != -1 ) {
1280                         /* now use for writing */
1281                         prs_switch_type( &ps, MARSHALL );
1282
1283                         /* stream the block once, generate the checksum, 
1284                            and stream it again */
1285                         prs_set_offset( &ps, 0 );
1286                         prs_regf_block( "regf_blocK", &ps, 0, file );
1287                         file->checksum = regf_block_checksum( &ps );
1288                         prs_set_offset( &ps, 0 );
1289                         prs_regf_block( "regf_blocK", &ps, 0, file );
1290
1291                         /* now we are ready to write it to disk */
1292                         if ( write_block( file, &ps, 0 ) == -1 )
1293                                 DEBUG(0,("regfio_close: failed to update the regf header block!\n"));
1294                 }
1295
1296                 prs_mem_free( &ps );
1297         }
1298         
1299         regfio_mem_free( file );
1300
1301         /* nothing tdo do if there is no open file */
1302
1303         if (file->fd == -1)
1304                 return 0;
1305                 
1306         fd = file->fd;
1307         file->fd = -1;
1308         SAFE_FREE( file );
1309
1310         return close( fd );
1311 }
1312
1313 /*******************************************************************
1314 *******************************************************************/
1315
1316 static void regfio_flush( REGF_FILE *file )
1317 {
1318         REGF_HBIN *hbin;
1319
1320         for ( hbin=file->block_list; hbin; hbin=hbin->next ) {
1321                 write_hbin_block( file, hbin );
1322         }
1323 }
1324
1325 /*******************************************************************
1326  There should be only *one* root key in the registry file based 
1327  on my experience.  --jerry
1328 *******************************************************************/
1329
1330 REGF_NK_REC* regfio_rootkey( REGF_FILE *file )
1331 {
1332         REGF_NK_REC *nk;
1333         REGF_HBIN   *hbin;
1334         uint32      offset = REGF_BLOCKSIZE;
1335         bool        found = False;
1336         bool        eob;
1337         
1338         if ( !file )
1339                 return NULL;
1340                 
1341         if ( !(nk = TALLOC_ZERO_P( file->mem_ctx, REGF_NK_REC )) ) {
1342                 DEBUG(0,("regfio_rootkey: talloc() failed!\n"));
1343                 return NULL;
1344         }
1345         
1346         /* scan through the file on HBIN block at a time looking 
1347            for an NK record with a type == 0x002c.
1348            Normally this is the first nk record in the first hbin 
1349            block (but I'm not assuming that for now) */
1350         
1351         while ( (hbin = read_hbin_block( file, offset )) ) {
1352                 eob = False;
1353
1354                 while ( !eob) {
1355                         if ( next_nk_record( file, hbin, nk, &eob ) ) {
1356                                 if ( nk->key_type == NK_TYPE_ROOTKEY ) {
1357                                         found = True;
1358                                         break;
1359                                 }
1360                         }
1361                         prs_mem_free( &hbin->ps );
1362                 }
1363                 
1364                 if ( found ) 
1365                         break;
1366
1367                 offset += hbin->block_size;
1368         }
1369         
1370         if ( !found ) {
1371                 DEBUG(0,("regfio_rootkey: corrupt registry file ?  No root key record located\n"));
1372                 return NULL;
1373         }
1374
1375         DLIST_ADD( file->block_list, hbin );
1376
1377         return nk;              
1378 }
1379
1380 /*******************************************************************
1381  This acts as an interator over the subkeys defined for a given 
1382  NK record.  Remember that offsets are from the *first* HBIN block.
1383 *******************************************************************/
1384
1385  REGF_NK_REC* regfio_fetch_subkey( REGF_FILE *file, REGF_NK_REC *nk )
1386 {
1387         REGF_NK_REC *subkey;
1388         REGF_HBIN   *hbin;
1389         uint32      nk_offset;
1390
1391         /* see if there is anything left to report */
1392         
1393         if ( !nk || (nk->subkeys_off==REGF_OFFSET_NONE) || (nk->subkey_index >= nk->num_subkeys) )
1394                 return NULL;
1395
1396         /* find the HBIN block which should contain the nk record */
1397         
1398         if ( !(hbin = lookup_hbin_block( file, nk->subkeys.hashes[nk->subkey_index].nk_off )) ) {
1399                 DEBUG(0,("hbin_prs_key: Failed to find HBIN block containing offset [0x%x]\n", 
1400                         nk->subkeys.hashes[nk->subkey_index].nk_off));
1401                 return NULL;
1402         }
1403         
1404         nk_offset = nk->subkeys.hashes[nk->subkey_index].nk_off;
1405         if ( !prs_set_offset( &hbin->ps, (HBIN_HDR_SIZE + nk_offset - hbin->first_hbin_off) ) )
1406                 return NULL;
1407                 
1408         nk->subkey_index++;
1409         if ( !(subkey = TALLOC_ZERO_P( file->mem_ctx, REGF_NK_REC )) )
1410                 return NULL;
1411                 
1412         if ( !hbin_prs_key( file, hbin, subkey ) )
1413                 return NULL;
1414         
1415         return subkey;
1416 }
1417
1418
1419 /*******************************************************************
1420 *******************************************************************/
1421
1422 static REGF_HBIN* regf_hbin_allocate( REGF_FILE *file, uint32 block_size )
1423 {
1424         REGF_HBIN *hbin;
1425         SMB_STRUCT_STAT sbuf;
1426
1427         if ( !(hbin = TALLOC_ZERO_P( file->mem_ctx, REGF_HBIN )) )
1428                 return NULL;
1429
1430         memcpy( hbin->header, "hbin", sizeof(HBIN_HDR_SIZE) );
1431
1432
1433         if (sys_fstat(file->fd, &sbuf, false)) {
1434                 DEBUG(0,("regf_hbin_allocate: stat() failed! (%s)\n", strerror(errno)));
1435                 return NULL;
1436         }
1437
1438         hbin->file_off       = sbuf.st_ex_size;
1439
1440         hbin->free_off       = HBIN_HEADER_REC_SIZE;
1441         hbin->free_size      = block_size - hbin->free_off + sizeof(uint32);;
1442
1443         hbin->block_size     = block_size;
1444         hbin->first_hbin_off = hbin->file_off - REGF_BLOCKSIZE;
1445
1446         if ( !prs_init( &hbin->ps, block_size, file->mem_ctx, MARSHALL ) )
1447                 return NULL;
1448
1449         if ( !prs_hbin_block( "new_hbin", &hbin->ps, 0, hbin ) )
1450                 return NULL;
1451
1452         if ( !write_hbin_block( file, hbin ) )
1453                 return NULL;
1454
1455         file->last_block = hbin->file_off;
1456
1457         return hbin;
1458 }
1459
1460 /*******************************************************************
1461 *******************************************************************/
1462
1463 static void update_free_space( REGF_HBIN *hbin, uint32 size_used )
1464 {
1465         hbin->free_off  += size_used;
1466         hbin->free_size -= size_used;
1467
1468         if ( hbin->free_off >= hbin->block_size ) {
1469                 hbin->free_off = REGF_OFFSET_NONE;
1470         }
1471
1472         return;
1473 }
1474
1475 /*******************************************************************
1476 *******************************************************************/
1477
1478 static REGF_HBIN* find_free_space( REGF_FILE *file, uint32 size )
1479 {
1480         REGF_HBIN *hbin, *p_hbin;
1481         uint32 block_off;
1482         bool cached;
1483
1484         /* check open block list */
1485
1486         for ( hbin=file->block_list; hbin!=NULL; hbin=hbin->next ) {
1487                 /* only check blocks that actually have available space */
1488
1489                 if ( hbin->free_off == REGF_OFFSET_NONE )
1490                         continue;
1491
1492                 /* check for a large enough available chunk */
1493
1494                 if ( (hbin->block_size - hbin->free_off) >= size ) {
1495                         DLIST_PROMOTE( file->block_list, hbin );
1496                         goto done;                      
1497                 }
1498         }
1499
1500         /* parse the file until we find a block with 
1501            enough free space; save the last non-filled hbin */
1502
1503         block_off = REGF_BLOCKSIZE;
1504         do {
1505                 /* cleanup before the next round */
1506                 cached = False;
1507                 if ( hbin )
1508                         prs_mem_free( &hbin->ps );
1509
1510                 hbin = read_hbin_block( file, block_off );
1511
1512                 if ( hbin ) {
1513
1514                         /* make sure that we don't already have this block in memory */
1515
1516                         for ( p_hbin=file->block_list; p_hbin!=NULL; p_hbin=p_hbin->next ) {
1517                                 if ( p_hbin->file_off == hbin->file_off ) {
1518                                         cached = True;  
1519                                         break;
1520                                 }
1521                         }
1522
1523                         block_off = hbin->file_off + hbin->block_size;
1524
1525                         if ( cached ) {
1526                                 prs_mem_free( &hbin->ps );
1527                                 hbin = NULL;
1528                                 continue;
1529                         }
1530                 }
1531         /* if (cached block or (new block and not enough free space)) then continue looping */
1532         } while ( cached || (hbin && (hbin->free_size < size)) );
1533         
1534         /* no free space; allocate a new one */
1535
1536         if ( !hbin ) {
1537                 uint32 alloc_size;
1538
1539                 /* allocate in multiples of REGF_ALLOC_BLOCK; make sure (size + hbin_header) fits */
1540
1541                 alloc_size = (((size+HBIN_HEADER_REC_SIZE) / REGF_ALLOC_BLOCK ) + 1 ) * REGF_ALLOC_BLOCK;
1542
1543                 if ( !(hbin = regf_hbin_allocate( file, alloc_size )) ) {
1544                         DEBUG(0,("find_free_space: regf_hbin_allocate() failed!\n"));
1545                         return NULL;
1546                 }
1547                 DLIST_ADD( file->block_list, hbin );
1548         }
1549
1550 done:
1551         /* set the offset to be ready to write */
1552
1553         if ( !prs_set_offset( &hbin->ps, hbin->free_off-sizeof(uint32) ) )
1554                 return NULL;
1555
1556         /* write the record size as a placeholder for now, it should be
1557            probably updated by the caller once it all of the data necessary 
1558            for the record */
1559
1560         if ( !prs_uint32("allocated_size", &hbin->ps, 0, &size) )
1561                 return False;
1562
1563         update_free_space( hbin, size );
1564         
1565         return hbin;
1566 }
1567
1568 /*******************************************************************
1569 *******************************************************************/
1570
1571 static uint32 sk_record_data_size( struct security_descriptor * sd )
1572 {
1573         uint32 size, size_mod8;
1574
1575         size_mod8 = 0;
1576
1577         /* the record size is sizeof(hdr) + name + static members + data_size_field */
1578
1579         size = sizeof(uint32)*5 + ndr_size_security_descriptor(sd, 0) + sizeof(uint32);
1580
1581         /* multiple of 8 */
1582         size_mod8 = size & 0xfffffff8;
1583         if ( size_mod8 < size )
1584                 size_mod8 += 8;
1585
1586         return size_mod8;
1587 }
1588
1589 /*******************************************************************
1590 *******************************************************************/
1591
1592 static uint32 vk_record_data_size( REGF_VK_REC *vk )
1593 {
1594         uint32 size, size_mod8;
1595
1596         size_mod8 = 0;
1597
1598         /* the record size is sizeof(hdr) + name + static members + data_size_field */
1599
1600         size = REC_HDR_SIZE + (sizeof(uint16)*3) + (sizeof(uint32)*3) + sizeof(uint32);
1601
1602         if ( vk->valuename )
1603                 size += strlen(vk->valuename);
1604
1605         /* multiple of 8 */
1606         size_mod8 = size & 0xfffffff8;
1607         if ( size_mod8 < size )
1608                 size_mod8 += 8;
1609
1610         return size_mod8;
1611 }
1612
1613 /*******************************************************************
1614 *******************************************************************/
1615
1616 static uint32 lf_record_data_size( uint32 num_keys )
1617 {
1618         uint32 size, size_mod8;
1619
1620         size_mod8 = 0;
1621
1622         /* the record size is sizeof(hdr) + num_keys + sizeof of hash_array + data_size_uint32 */
1623
1624         size = REC_HDR_SIZE + sizeof(uint16) + (sizeof(REGF_HASH_REC) * num_keys) + sizeof(uint32);
1625
1626         /* multiple of 8 */
1627         size_mod8 = size & 0xfffffff8;
1628         if ( size_mod8 < size )
1629                 size_mod8 += 8;
1630
1631         return size_mod8;
1632 }
1633
1634 /*******************************************************************
1635 *******************************************************************/
1636
1637 static uint32 nk_record_data_size( REGF_NK_REC *nk )
1638 {
1639         uint32 size, size_mod8;
1640
1641         size_mod8 = 0;
1642
1643         /* the record size is static + length_of_keyname + length_of_classname + data_size_uint32 */
1644
1645         size = 0x4c + strlen(nk->keyname) + sizeof(uint32);
1646
1647         if ( nk->classname )
1648                 size += strlen( nk->classname );
1649
1650         /* multiple of 8 */
1651         size_mod8 = size & 0xfffffff8;
1652         if ( size_mod8 < size )
1653                 size_mod8 += 8;
1654
1655         return size_mod8;
1656 }
1657
1658 /*******************************************************************
1659 *******************************************************************/
1660
1661 static bool create_vk_record(REGF_FILE *file, REGF_VK_REC *vk,
1662                              struct regval_blob *value)
1663 {
1664         char *name = regval_name(value);
1665         REGF_HBIN *data_hbin;
1666
1667         ZERO_STRUCTP( vk );
1668
1669         memcpy( vk->header, "vk", REC_HDR_SIZE );
1670
1671         if ( name ) {
1672                 vk->valuename = talloc_strdup( file->mem_ctx, regval_name(value) );
1673                 vk->flag = VK_FLAG_NAME_PRESENT;
1674         }
1675
1676         vk->data_size = regval_size( value );
1677         vk->type      = regval_type( value );
1678
1679         if ( vk->data_size > sizeof(uint32) ) {
1680                 uint32 data_size = ( (vk->data_size+sizeof(uint32)) & 0xfffffff8 ) + 8;
1681
1682                 vk->data = (uint8 *)TALLOC_MEMDUP( file->mem_ctx,
1683                                                    regval_data_p(value),
1684                                                    vk->data_size );
1685                 if (vk->data == NULL) {
1686                         return False;
1687                 }
1688
1689                 /* go ahead and store the offset....we'll pick this hbin block back up when 
1690                    we stream the data */
1691
1692                 if ((data_hbin = find_free_space(file, data_size )) == NULL) {
1693                         return False;
1694                 }
1695                 vk->data_off = prs_offset( &data_hbin->ps ) + data_hbin->first_hbin_off - HBIN_HDR_SIZE;
1696         }
1697         else {
1698                 /* make sure we don't try to copy from a NULL value pointer */
1699
1700                 if ( vk->data_size != 0 ) 
1701                         memcpy( &vk->data_off, regval_data_p(value), sizeof(uint32) );
1702                 vk->data_size |= VK_DATA_IN_OFFSET;             
1703         }
1704
1705         return True;
1706 }
1707
1708 /*******************************************************************
1709 *******************************************************************/
1710
1711 static int hashrec_cmp( REGF_HASH_REC *h1, REGF_HASH_REC *h2 )
1712 {
1713         return StrCaseCmp( h1->fullname, h2->fullname );
1714 }
1715
1716 /*******************************************************************
1717 *******************************************************************/
1718
1719  REGF_NK_REC* regfio_write_key( REGF_FILE *file, const char *name,
1720                                struct regval_ctr *values, struct regsubkey_ctr *subkeys,
1721                                struct security_descriptor *sec_desc, REGF_NK_REC *parent )
1722 {
1723         REGF_NK_REC *nk;
1724         REGF_HBIN *vlist_hbin = NULL;
1725         uint32 size;
1726
1727         if ( !(nk = TALLOC_ZERO_P( file->mem_ctx, REGF_NK_REC )) )
1728                 return NULL;
1729
1730         memcpy( nk->header, "nk", REC_HDR_SIZE );
1731
1732         if ( !parent )
1733                 nk->key_type = NK_TYPE_ROOTKEY;
1734         else
1735                 nk->key_type = NK_TYPE_NORMALKEY;
1736
1737         /* store the parent offset (or -1 if a the root key */
1738
1739         nk->parent_off = parent ? (parent->hbin_off + parent->hbin->file_off - REGF_BLOCKSIZE - HBIN_HDR_SIZE ) : REGF_OFFSET_NONE;
1740
1741         /* no classname currently */
1742
1743         nk->classname_off = REGF_OFFSET_NONE;
1744         nk->classname = NULL;
1745         nk->keyname = talloc_strdup( file->mem_ctx, name );
1746
1747         /* current modification time */
1748
1749         unix_to_nt_time( &nk->mtime, time(NULL) );
1750
1751         /* allocate the record on disk */
1752
1753         size = nk_record_data_size( nk );
1754         nk->rec_size = ( size - 1 ) ^ 0XFFFFFFFF;
1755         if ((nk->hbin = find_free_space( file, size )) == NULL) {
1756                 return NULL;
1757         }
1758         nk->hbin_off = prs_offset( &nk->hbin->ps );
1759
1760         /* Update the hash record in the parent */
1761         
1762         if ( parent ) {
1763                 REGF_HASH_REC *hash = &parent->subkeys.hashes[parent->subkey_index];
1764
1765                 hash->nk_off = prs_offset( &nk->hbin->ps ) + nk->hbin->first_hbin_off - HBIN_HDR_SIZE;
1766                 memcpy( hash->keycheck, name, sizeof(uint32) );
1767                 hash->fullname = talloc_strdup( file->mem_ctx, name );
1768                 parent->subkey_index++;
1769
1770                 /* sort the list by keyname */
1771                 TYPESAFE_QSORT(parent->subkeys.hashes, parent->subkey_index, hashrec_cmp);
1772
1773                 if ( !hbin_prs_lf_records( "lf_rec", parent->subkeys.hbin, 0, parent ) )
1774                         return False;
1775         }
1776
1777         /* write the security descriptor */
1778
1779         nk->sk_off = REGF_OFFSET_NONE;
1780         if ( sec_desc ) {
1781                 uint32 sk_size = sk_record_data_size( sec_desc );
1782                 REGF_HBIN *sk_hbin;
1783
1784                 /* search for it in the existing list of sd's */
1785
1786                 if ( (nk->sec_desc = find_sk_record_by_sec_desc( file, sec_desc )) == NULL ) {
1787                         /* not found so add it to the list */
1788
1789                         if (!(sk_hbin = find_free_space( file, sk_size ))) {
1790                                 return NULL;
1791                         }
1792
1793                         if ( !(nk->sec_desc = TALLOC_ZERO_P( file->mem_ctx, REGF_SK_REC )) )
1794                                 return NULL;
1795         
1796                         /* now we have to store the security descriptor in the list and 
1797                            update the offsets */
1798
1799                         memcpy( nk->sec_desc->header, "sk", REC_HDR_SIZE );
1800                         nk->sec_desc->hbin      = sk_hbin;
1801                         nk->sec_desc->hbin_off  = prs_offset( &sk_hbin->ps );
1802                         nk->sec_desc->sk_off    = prs_offset( &sk_hbin->ps ) + sk_hbin->first_hbin_off - HBIN_HDR_SIZE;
1803                         nk->sec_desc->rec_size  = (sk_size-1)  ^ 0xFFFFFFFF;
1804
1805                         nk->sec_desc->sec_desc  = sec_desc;
1806                         nk->sec_desc->ref_count = 0;
1807                         
1808                         /* size value must be self-inclusive */
1809                         nk->sec_desc->size      = ndr_size_security_descriptor(sec_desc, 0)
1810                                 + sizeof(uint32);
1811
1812                         DLIST_ADD_END( file->sec_desc_list, nk->sec_desc, REGF_SK_REC *);
1813
1814                         /* update the offsets for us and the previous sd in the list.
1815                            if this is the first record, then just set the next and prev
1816                            offsets to ourself. */
1817
1818                         if ( DLIST_PREV(nk->sec_desc) ) {
1819                                 REGF_SK_REC *prev = DLIST_PREV(nk->sec_desc);
1820
1821                                 nk->sec_desc->prev_sk_off = prev->hbin_off + prev->hbin->first_hbin_off - HBIN_HDR_SIZE;
1822                                 prev->next_sk_off = nk->sec_desc->sk_off;
1823
1824                                 /* the end must loop around to the front */
1825                                 nk->sec_desc->next_sk_off = file->sec_desc_list->sk_off;
1826
1827                                 /* and first must loop around to the tail */
1828                                 file->sec_desc_list->prev_sk_off = nk->sec_desc->sk_off;
1829                         } else {
1830                                 nk->sec_desc->prev_sk_off = nk->sec_desc->sk_off;
1831                                 nk->sec_desc->next_sk_off = nk->sec_desc->sk_off;
1832                         }
1833                 }
1834
1835                 /* bump the reference count +1 */
1836
1837                 nk->sk_off = nk->sec_desc->sk_off;
1838                 nk->sec_desc->ref_count++;
1839         }
1840
1841         /* write the subkeys */
1842
1843         nk->subkeys_off = REGF_OFFSET_NONE;
1844         if ( (nk->num_subkeys = regsubkey_ctr_numkeys( subkeys )) != 0 ) {
1845                 uint32 lf_size = lf_record_data_size( nk->num_subkeys );
1846                 uint32 namelen;
1847                 int i;
1848                 
1849                 if (!(nk->subkeys.hbin = find_free_space( file, lf_size ))) {
1850                         return NULL;
1851                 }
1852                 nk->subkeys.hbin_off = prs_offset( &nk->subkeys.hbin->ps );
1853                 nk->subkeys.rec_size = (lf_size-1) ^ 0xFFFFFFFF;
1854                 nk->subkeys_off = prs_offset( &nk->subkeys.hbin->ps ) + nk->subkeys.hbin->first_hbin_off - HBIN_HDR_SIZE;
1855
1856                 memcpy( nk->subkeys.header, "lf", REC_HDR_SIZE );
1857                 
1858                 nk->subkeys.num_keys = nk->num_subkeys;
1859                 if (nk->subkeys.num_keys) {
1860                         if ( !(nk->subkeys.hashes = TALLOC_ZERO_ARRAY( file->mem_ctx, REGF_HASH_REC, nk->subkeys.num_keys )) )
1861                                 return NULL;
1862                 } else {
1863                         nk->subkeys.hashes = NULL;
1864                 }
1865                 nk->subkey_index = 0;
1866
1867                 /* update the max_bytes_subkey{name,classname} fields */
1868                 for ( i=0; i<nk->num_subkeys; i++ ) {
1869                         namelen = strlen( regsubkey_ctr_specific_key(subkeys, i) );
1870                         if ( namelen*2 > nk->max_bytes_subkeyname )
1871                                 nk->max_bytes_subkeyname = namelen * 2;
1872                 }
1873         }
1874
1875         /* write the values */
1876
1877         nk->values_off = REGF_OFFSET_NONE;
1878         if ( (nk->num_values = regval_ctr_numvals( values )) != 0 ) {
1879                 uint32 vlist_size = ( ( nk->num_values * sizeof(uint32) ) & 0xfffffff8 ) + 8;
1880                 int i;
1881                 
1882                 if (!(vlist_hbin = find_free_space( file, vlist_size ))) {
1883                         return NULL;
1884                 }
1885                 nk->values_off = prs_offset( &vlist_hbin->ps ) + vlist_hbin->first_hbin_off - HBIN_HDR_SIZE;
1886         
1887                 if (nk->num_values) {
1888                         if ( !(nk->values = TALLOC_ARRAY( file->mem_ctx, REGF_VK_REC, nk->num_values )) )
1889                                 return NULL;
1890                 } else {
1891                         nk->values = NULL;
1892                 }
1893
1894                 /* create the vk records */
1895
1896                 for ( i=0; i<nk->num_values; i++ ) {
1897                         uint32 vk_size, namelen, datalen;
1898                         struct regval_blob *r;
1899
1900                         r = regval_ctr_specific_value( values, i );
1901                         create_vk_record( file, &nk->values[i], r );
1902                         vk_size = vk_record_data_size( &nk->values[i] );
1903                         nk->values[i].hbin = find_free_space( file, vk_size );
1904                         nk->values[i].hbin_off = prs_offset( &nk->values[i].hbin->ps );
1905                         nk->values[i].rec_size = ( vk_size - 1 ) ^ 0xFFFFFFFF;
1906                         nk->values[i].rec_off = prs_offset( &nk->values[i].hbin->ps ) 
1907                                 + nk->values[i].hbin->first_hbin_off 
1908                                 - HBIN_HDR_SIZE;
1909
1910                         /* update the max bytes fields if necessary */
1911
1912                         namelen = strlen( regval_name(r) );
1913                         if ( namelen*2 > nk->max_bytes_valuename )
1914                                 nk->max_bytes_valuename = namelen * 2;
1915
1916                         datalen = regval_size( r );
1917                         if ( datalen > nk->max_bytes_value )
1918                                 nk->max_bytes_value = datalen;
1919                 }
1920         }
1921
1922         /* stream the records */        
1923         
1924         prs_set_offset( &nk->hbin->ps, nk->hbin_off );
1925         if ( !prs_nk_rec( "nk_rec", &nk->hbin->ps, 0, nk ) )
1926                 return False;
1927
1928         if ( nk->num_values ) {
1929                 if ( !hbin_prs_vk_records( "vk_records", vlist_hbin, 0, nk, file ) )
1930                         return False;
1931         }
1932
1933
1934         regfio_flush( file );
1935
1936         return nk;
1937 }
1938