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