[GLUE] Rsync SAMBA_3_2_0 SVN r25598 in order to create the v3-2-test branch.
[jra/samba/.git] / source3 / rpc_parse / parse_prs.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba memory buffer functions
4    Copyright (C) Andrew Tridgell              1992-1997
5    Copyright (C) Luke Kenneth Casson Leighton 1996-1997
6    Copyright (C) Jeremy Allison               1999
7    Copyright (C) Andrew Bartlett              2003.
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24
25 #undef DBGC_CLASS
26 #define DBGC_CLASS DBGC_RPC_PARSE
27
28 /**
29  * Dump a prs to a file: from the current location through to the end.
30  **/
31 void prs_dump(char *name, int v, prs_struct *ps)
32 {
33         prs_dump_region(name, v, ps, ps->data_offset, ps->buffer_size);
34 }
35
36 /**
37  * Dump from the start of the prs to the current location.
38  **/
39 void prs_dump_before(char *name, int v, prs_struct *ps)
40 {
41         prs_dump_region(name, v, ps, 0, ps->data_offset);
42 }
43
44 /**
45  * Dump everything from the start of the prs up to the current location.
46  **/
47 void prs_dump_region(char *name, int v, prs_struct *ps,
48                      int from_off, int to_off)
49 {
50         int fd, i;
51         pstring fname;
52         ssize_t sz;
53         if (DEBUGLEVEL < 50) return;
54         for (i=1;i<100;i++) {
55                 if (v != -1) {
56                         slprintf(fname,sizeof(fname)-1, "/tmp/%s_%d.%d.prs", name, v, i);
57                 } else {
58                         slprintf(fname,sizeof(fname)-1, "/tmp/%s.%d.prs", name, i);
59                 }
60                 fd = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0644);
61                 if (fd != -1 || errno != EEXIST) break;
62         }
63         if (fd != -1) {
64                 sz = write(fd, ps->data_p + from_off, to_off - from_off);
65                 i = close(fd);
66                 if ( (sz != to_off-from_off) || (i != 0) ) {
67                         DEBUG(0,("Error writing/closing %s: %ld!=%ld %d\n", fname, (unsigned long)sz, (unsigned long)to_off-from_off, i ));
68                 } else {
69                         DEBUG(0,("created %s\n", fname));
70                 }
71         }
72 }
73
74 /*******************************************************************
75  Debug output for parsing info
76
77  XXXX side-effect of this function is to increase the debug depth XXXX.
78
79 ********************************************************************/
80
81 void prs_debug(prs_struct *ps, int depth, const char *desc, const char *fn_name)
82 {
83         DEBUG(5+depth, ("%s%06x %s %s\n", tab_depth(depth), ps->data_offset, fn_name, desc));
84 }
85
86 /**
87  * Initialise an expandable parse structure.
88  *
89  * @param size Initial buffer size.  If >0, a new buffer will be
90  * created with malloc().
91  *
92  * @return False if allocation fails, otherwise True.
93  **/
94
95 BOOL prs_init(prs_struct *ps, uint32 size, TALLOC_CTX *ctx, BOOL io)
96 {
97         ZERO_STRUCTP(ps);
98         ps->io = io;
99         ps->bigendian_data = RPC_LITTLE_ENDIAN;
100         ps->align = RPC_PARSE_ALIGN;
101         ps->is_dynamic = False;
102         ps->data_offset = 0;
103         ps->buffer_size = 0;
104         ps->data_p = NULL;
105         ps->mem_ctx = ctx;
106
107         if (size != 0) {
108                 ps->buffer_size = size;
109                 if((ps->data_p = (char *)SMB_MALLOC((size_t)size)) == NULL) {
110                         DEBUG(0,("prs_init: malloc fail for %u bytes.\n", (unsigned int)size));
111                         return False;
112                 }
113                 memset(ps->data_p, '\0', (size_t)size);
114                 ps->is_dynamic = True; /* We own this memory. */
115         } else if (MARSHALLING(ps)) {
116                 /* If size is zero and we're marshalling we should allocate memory on demand. */
117                 ps->is_dynamic = True;
118         }
119
120         return True;
121 }
122
123 /*******************************************************************
124  Delete the memory in a parse structure - if we own it.
125
126  NOTE: Contrary to the somewhat confusing naming, this function is not
127        intended for freeing memory allocated by prs_alloc_mem().  That memory
128        is attached to the talloc context given by ps->mem_ctx.
129  ********************************************************************/
130
131 void prs_mem_free(prs_struct *ps)
132 {
133         if(ps->is_dynamic)
134                 SAFE_FREE(ps->data_p);
135         ps->is_dynamic = False;
136         ps->buffer_size = 0;
137         ps->data_offset = 0;
138 }
139
140 /*******************************************************************
141  Clear the memory in a parse structure.
142  ********************************************************************/
143
144 void prs_mem_clear(prs_struct *ps)
145 {
146         if (ps->buffer_size)
147                 memset(ps->data_p, '\0', (size_t)ps->buffer_size);
148 }
149
150 /*******************************************************************
151  Allocate memory when unmarshalling... Always zero clears.
152  ********************************************************************/
153
154 #if defined(PARANOID_MALLOC_CHECKER)
155 char *prs_alloc_mem_(prs_struct *ps, size_t size, unsigned int count)
156 #else
157 char *prs_alloc_mem(prs_struct *ps, size_t size, unsigned int count)
158 #endif
159 {
160         char *ret = NULL;
161
162         if (size && count) {
163                 /* We can't call the type-safe version here. */
164                 ret = (char *)_talloc_zero_array(ps->mem_ctx, size, count,
165                                                  "parse_prs");
166         }
167         return ret;
168 }
169
170 /*******************************************************************
171  Return the current talloc context we're using.
172  ********************************************************************/
173
174 TALLOC_CTX *prs_get_mem_context(prs_struct *ps)
175 {
176         return ps->mem_ctx;
177 }
178
179 /*******************************************************************
180  Hand some already allocated memory to a prs_struct.
181  ********************************************************************/
182
183 void prs_give_memory(prs_struct *ps, char *buf, uint32 size, BOOL is_dynamic)
184 {
185         ps->is_dynamic = is_dynamic;
186         ps->data_p = buf;
187         ps->buffer_size = size;
188 }
189
190 /*******************************************************************
191  Take some memory back from a prs_struct.
192  ********************************************************************/
193
194 char *prs_take_memory(prs_struct *ps, uint32 *psize)
195 {
196         char *ret = ps->data_p;
197         if(psize)
198                 *psize = ps->buffer_size;
199         ps->is_dynamic = False;
200         prs_mem_free(ps);
201         return ret;
202 }
203
204 /*******************************************************************
205  Set a prs_struct to exactly a given size. Will grow or tuncate if neccessary.
206  ********************************************************************/
207
208 BOOL prs_set_buffer_size(prs_struct *ps, uint32 newsize)
209 {
210         if (newsize > ps->buffer_size)
211                 return prs_force_grow(ps, newsize - ps->buffer_size);
212
213         if (newsize < ps->buffer_size) {
214                 ps->buffer_size = newsize;
215
216                 /* newsize == 0 acts as a free and set pointer to NULL */
217                 if (newsize == 0) {
218                         SAFE_FREE(ps->data_p);
219                 } else {
220                         ps->data_p = (char *)SMB_REALLOC(ps->data_p, newsize);
221
222                         if (ps->data_p == NULL) {
223                                 DEBUG(0,("prs_set_buffer_size: Realloc failure for size %u.\n",
224                                         (unsigned int)newsize));
225                                 DEBUG(0,("prs_set_buffer_size: Reason %s\n",strerror(errno)));
226                                 return False;
227                         }
228                 }
229         }
230
231         return True;
232 }
233
234 /*******************************************************************
235  Attempt, if needed, to grow a data buffer.
236  Also depends on the data stream mode (io).
237  ********************************************************************/
238
239 BOOL prs_grow(prs_struct *ps, uint32 extra_space)
240 {
241         uint32 new_size;
242
243         ps->grow_size = MAX(ps->grow_size, ps->data_offset + extra_space);
244
245         if(ps->data_offset + extra_space <= ps->buffer_size)
246                 return True;
247
248         /*
249          * We cannot grow the buffer if we're not reading
250          * into the prs_struct, or if we don't own the memory.
251          */
252
253         if(UNMARSHALLING(ps) || !ps->is_dynamic) {
254                 DEBUG(0,("prs_grow: Buffer overflow - unable to expand buffer by %u bytes.\n",
255                                 (unsigned int)extra_space));
256                 return False;
257         }
258         
259         /*
260          * Decide how much extra space we really need.
261          */
262
263         extra_space -= (ps->buffer_size - ps->data_offset);
264         if(ps->buffer_size == 0) {
265                 /*
266                  * Ensure we have at least a PDU's length, or extra_space, whichever
267                  * is greater.
268                  */
269
270                 new_size = MAX(RPC_MAX_PDU_FRAG_LEN,extra_space);
271
272                 if((ps->data_p = (char *)SMB_MALLOC(new_size)) == NULL) {
273                         DEBUG(0,("prs_grow: Malloc failure for size %u.\n", (unsigned int)new_size));
274                         return False;
275                 }
276                 memset(ps->data_p, '\0', (size_t)new_size );
277         } else {
278                 /*
279                  * If the current buffer size is bigger than the space needed, just 
280                  * double it, else add extra_space.
281                  */
282                 new_size = MAX(ps->buffer_size*2, ps->buffer_size + extra_space);               
283
284                 if ((ps->data_p = (char *)SMB_REALLOC(ps->data_p, new_size)) == NULL) {
285                         DEBUG(0,("prs_grow: Realloc failure for size %u.\n",
286                                 (unsigned int)new_size));
287                         return False;
288                 }
289
290                 memset(&ps->data_p[ps->buffer_size], '\0', (size_t)(new_size - ps->buffer_size));
291         }
292         ps->buffer_size = new_size;
293
294         return True;
295 }
296
297 /*******************************************************************
298  Attempt to force a data buffer to grow by len bytes.
299  This is only used when appending more data onto a prs_struct
300  when reading an rpc reply, before unmarshalling it.
301  ********************************************************************/
302
303 BOOL prs_force_grow(prs_struct *ps, uint32 extra_space)
304 {
305         uint32 new_size = ps->buffer_size + extra_space;
306
307         if(!UNMARSHALLING(ps) || !ps->is_dynamic) {
308                 DEBUG(0,("prs_force_grow: Buffer overflow - unable to expand buffer by %u bytes.\n",
309                                 (unsigned int)extra_space));
310                 return False;
311         }
312
313         if((ps->data_p = (char *)SMB_REALLOC(ps->data_p, new_size)) == NULL) {
314                 DEBUG(0,("prs_force_grow: Realloc failure for size %u.\n",
315                         (unsigned int)new_size));
316                 return False;
317         }
318
319         memset(&ps->data_p[ps->buffer_size], '\0', (size_t)(new_size - ps->buffer_size));
320
321         ps->buffer_size = new_size;
322
323         return True;
324 }
325
326 /*******************************************************************
327  Get the data pointer (external interface).
328 ********************************************************************/
329
330 char *prs_data_p(prs_struct *ps)
331 {
332         return ps->data_p;
333 }
334
335 /*******************************************************************
336  Get the current data size (external interface).
337  ********************************************************************/
338
339 uint32 prs_data_size(prs_struct *ps)
340 {
341         return ps->buffer_size;
342 }
343
344 /*******************************************************************
345  Fetch the current offset (external interface).
346  ********************************************************************/
347
348 uint32 prs_offset(prs_struct *ps)
349 {
350         return ps->data_offset;
351 }
352
353 /*******************************************************************
354  Set the current offset (external interface).
355  ********************************************************************/
356
357 BOOL prs_set_offset(prs_struct *ps, uint32 offset)
358 {
359         if(offset <= ps->data_offset) {
360                 ps->data_offset = offset;
361                 return True;
362         }
363
364         if(!prs_grow(ps, offset - ps->data_offset))
365                 return False;
366
367         ps->data_offset = offset;
368         return True;
369 }
370
371 /*******************************************************************
372  Append the data from one parse_struct into another.
373  ********************************************************************/
374
375 BOOL prs_append_prs_data(prs_struct *dst, prs_struct *src)
376 {
377         if (prs_offset(src) == 0)
378                 return True;
379
380         if(!prs_grow(dst, prs_offset(src)))
381                 return False;
382
383         memcpy(&dst->data_p[dst->data_offset], src->data_p, (size_t)prs_offset(src));
384         dst->data_offset += prs_offset(src);
385
386         return True;
387 }
388
389 /*******************************************************************
390  Append some data from one parse_struct into another.
391  ********************************************************************/
392
393 BOOL prs_append_some_prs_data(prs_struct *dst, prs_struct *src, int32 start, uint32 len)
394 {       
395         if (len == 0)
396                 return True;
397
398         if(!prs_grow(dst, len))
399                 return False;
400         
401         memcpy(&dst->data_p[dst->data_offset], src->data_p + start, (size_t)len);
402         dst->data_offset += len;
403
404         return True;
405 }
406
407 /*******************************************************************
408  Append the data from a buffer into a parse_struct.
409  ********************************************************************/
410
411 BOOL prs_copy_data_in(prs_struct *dst, const char *src, uint32 len)
412 {
413         if (len == 0)
414                 return True;
415
416         if(!prs_grow(dst, len))
417                 return False;
418
419         memcpy(&dst->data_p[dst->data_offset], src, (size_t)len);
420         dst->data_offset += len;
421
422         return True;
423 }
424
425 /*******************************************************************
426  Copy some data from a parse_struct into a buffer.
427  ********************************************************************/
428
429 BOOL prs_copy_data_out(char *dst, prs_struct *src, uint32 len)
430 {
431         if (len == 0)
432                 return True;
433
434         if(!prs_mem_get(src, len))
435                 return False;
436
437         memcpy(dst, &src->data_p[src->data_offset], (size_t)len);
438         src->data_offset += len;
439
440         return True;
441 }
442
443 /*******************************************************************
444  Copy all the data from a parse_struct into a buffer.
445  ********************************************************************/
446
447 BOOL prs_copy_all_data_out(char *dst, prs_struct *src)
448 {
449         uint32 len = prs_offset(src);
450
451         if (!len)
452                 return True;
453
454         prs_set_offset(src, 0);
455         return prs_copy_data_out(dst, src, len);
456 }
457
458 /*******************************************************************
459  Set the data as X-endian (external interface).
460  ********************************************************************/
461
462 void prs_set_endian_data(prs_struct *ps, BOOL endian)
463 {
464         ps->bigendian_data = endian;
465 }
466
467 /*******************************************************************
468  Align a the data_len to a multiple of align bytes - filling with
469  zeros.
470  ********************************************************************/
471
472 BOOL prs_align(prs_struct *ps)
473 {
474         uint32 mod = ps->data_offset & (ps->align-1);
475
476         if (ps->align != 0 && mod != 0) {
477                 uint32 extra_space = (ps->align - mod);
478                 if(!prs_grow(ps, extra_space))
479                         return False;
480                 memset(&ps->data_p[ps->data_offset], '\0', (size_t)extra_space);
481                 ps->data_offset += extra_space;
482         }
483
484         return True;
485 }
486
487 /******************************************************************
488  Align on a 2 byte boundary
489  *****************************************************************/
490  
491 BOOL prs_align_uint16(prs_struct *ps)
492 {
493         BOOL ret;
494         uint8 old_align = ps->align;
495
496         ps->align = 2;
497         ret = prs_align(ps);
498         ps->align = old_align;
499         
500         return ret;
501 }
502
503 /******************************************************************
504  Align on a 8 byte boundary
505  *****************************************************************/
506  
507 BOOL prs_align_uint64(prs_struct *ps)
508 {
509         BOOL ret;
510         uint8 old_align = ps->align;
511
512         ps->align = 8;
513         ret = prs_align(ps);
514         ps->align = old_align;
515         
516         return ret;
517 }
518
519 /******************************************************************
520  Align on a specific byte boundary
521  *****************************************************************/
522  
523 BOOL prs_align_custom(prs_struct *ps, uint8 boundary)
524 {
525         BOOL ret;
526         uint8 old_align = ps->align;
527
528         ps->align = boundary;
529         ret = prs_align(ps);
530         ps->align = old_align;
531         
532         return ret;
533 }
534
535
536
537 /*******************************************************************
538  Align only if required (for the unistr2 string mainly)
539  ********************************************************************/
540
541 BOOL prs_align_needed(prs_struct *ps, uint32 needed)
542 {
543         if (needed==0)
544                 return True;
545         else
546                 return prs_align(ps);
547 }
548
549 /*******************************************************************
550  Ensure we can read/write to a given offset.
551  ********************************************************************/
552
553 char *prs_mem_get(prs_struct *ps, uint32 extra_size)
554 {
555         if(UNMARSHALLING(ps)) {
556                 /*
557                  * If reading, ensure that we can read the requested size item.
558                  */
559                 if (ps->data_offset + extra_size > ps->buffer_size) {
560                         DEBUG(0,("prs_mem_get: reading data of size %u would overrun "
561                                 "buffer by %u bytes.\n",
562                                 (unsigned int)extra_size,
563                                 (unsigned int)(ps->data_offset + extra_size - ps->buffer_size) ));
564                         return NULL;
565                 }
566         } else {
567                 /*
568                  * Writing - grow the buffer if needed.
569                  */
570                 if(!prs_grow(ps, extra_size))
571                         return NULL;
572         }
573         return &ps->data_p[ps->data_offset];
574 }
575
576 /*******************************************************************
577  Change the struct type.
578  ********************************************************************/
579
580 void prs_switch_type(prs_struct *ps, BOOL io)
581 {
582         if ((ps->io ^ io) == True)
583                 ps->io=io;
584 }
585
586 /*******************************************************************
587  Force a prs_struct to be dynamic even when it's size is 0.
588  ********************************************************************/
589
590 void prs_force_dynamic(prs_struct *ps)
591 {
592         ps->is_dynamic=True;
593 }
594
595 /*******************************************************************
596  Associate a session key with a parse struct.
597  ********************************************************************/
598
599 void prs_set_session_key(prs_struct *ps, const char sess_key[16])
600 {
601         ps->sess_key = sess_key;
602 }
603
604 /*******************************************************************
605  Stream a uint8.
606  ********************************************************************/
607
608 BOOL prs_uint8(const char *name, prs_struct *ps, int depth, uint8 *data8)
609 {
610         char *q = prs_mem_get(ps, 1);
611         if (q == NULL)
612                 return False;
613
614         if (UNMARSHALLING(ps))
615                 *data8 = CVAL(q,0);
616         else
617                 SCVAL(q,0,*data8);
618
619         DEBUG(5,("%s%04x %s: %02x\n", tab_depth(depth), ps->data_offset, name, *data8));
620
621         ps->data_offset += 1;
622
623         return True;
624 }
625
626 /*******************************************************************
627  Stream a uint16* (allocate memory if unmarshalling)
628  ********************************************************************/
629
630 BOOL prs_pointer( const char *name, prs_struct *ps, int depth, 
631                  void *dta, size_t data_size,
632                  BOOL(*prs_fn)(const char*, prs_struct*, int, void*) )
633 {
634         void ** data = (void **)dta;
635         uint32 data_p;
636
637         /* output f000baaa to stream if the pointer is non-zero. */
638
639         data_p = *data ? 0xf000baaa : 0;
640
641         if ( !prs_uint32("ptr", ps, depth, &data_p ))
642                 return False;
643
644         /* we're done if there is no data */
645
646         if ( !data_p )
647                 return True;
648
649         if (UNMARSHALLING(ps)) {
650                 if (data_size) {
651                         if ( !(*data = PRS_ALLOC_MEM(ps, char, data_size)) )
652                                 return False;
653                 } else {
654                         *data = NULL;
655                 }
656         }
657
658         return prs_fn(name, ps, depth, *data);
659 }
660
661
662 /*******************************************************************
663  Stream a uint16.
664  ********************************************************************/
665
666 BOOL prs_uint16(const char *name, prs_struct *ps, int depth, uint16 *data16)
667 {
668         char *q = prs_mem_get(ps, sizeof(uint16));
669         if (q == NULL)
670                 return False;
671
672         if (UNMARSHALLING(ps)) {
673                 if (ps->bigendian_data)
674                         *data16 = RSVAL(q,0);
675                 else
676                         *data16 = SVAL(q,0);
677         } else {
678                 if (ps->bigendian_data)
679                         RSSVAL(q,0,*data16);
680                 else
681                         SSVAL(q,0,*data16);
682         }
683
684         DEBUG(5,("%s%04x %s: %04x\n", tab_depth(depth), ps->data_offset, name, *data16));
685
686         ps->data_offset += sizeof(uint16);
687
688         return True;
689 }
690
691 /*******************************************************************
692  Stream a uint32.
693  ********************************************************************/
694
695 BOOL prs_uint32(const char *name, prs_struct *ps, int depth, uint32 *data32)
696 {
697         char *q = prs_mem_get(ps, sizeof(uint32));
698         if (q == NULL)
699                 return False;
700
701         if (UNMARSHALLING(ps)) {
702                 if (ps->bigendian_data)
703                         *data32 = RIVAL(q,0);
704                 else
705                         *data32 = IVAL(q,0);
706         } else {
707                 if (ps->bigendian_data)
708                         RSIVAL(q,0,*data32);
709                 else
710                         SIVAL(q,0,*data32);
711         }
712
713         DEBUG(5,("%s%04x %s: %08x\n", tab_depth(depth), ps->data_offset, name, *data32));
714
715         ps->data_offset += sizeof(uint32);
716
717         return True;
718 }
719
720 /*******************************************************************
721  Stream an int32.
722  ********************************************************************/
723
724 BOOL prs_int32(const char *name, prs_struct *ps, int depth, int32 *data32)
725 {
726         char *q = prs_mem_get(ps, sizeof(int32));
727         if (q == NULL)
728                 return False;
729
730         if (UNMARSHALLING(ps)) {
731                 if (ps->bigendian_data)
732                         *data32 = RIVALS(q,0);
733                 else
734                         *data32 = IVALS(q,0);
735         } else {
736                 if (ps->bigendian_data)
737                         RSIVALS(q,0,*data32);
738                 else
739                         SIVALS(q,0,*data32);
740         }
741
742         DEBUG(5,("%s%04x %s: %08x\n", tab_depth(depth), ps->data_offset, name, *data32));
743
744         ps->data_offset += sizeof(int32);
745
746         return True;
747 }
748
749 /*******************************************************************
750  Stream a NTSTATUS
751  ********************************************************************/
752
753 BOOL prs_ntstatus(const char *name, prs_struct *ps, int depth, NTSTATUS *status)
754 {
755         char *q = prs_mem_get(ps, sizeof(uint32));
756         if (q == NULL)
757                 return False;
758
759         if (UNMARSHALLING(ps)) {
760                 if (ps->bigendian_data)
761                         *status = NT_STATUS(RIVAL(q,0));
762                 else
763                         *status = NT_STATUS(IVAL(q,0));
764         } else {
765                 if (ps->bigendian_data)
766                         RSIVAL(q,0,NT_STATUS_V(*status));
767                 else
768                         SIVAL(q,0,NT_STATUS_V(*status));
769         }
770
771         DEBUG(5,("%s%04x %s: %s\n", tab_depth(depth), ps->data_offset, name, 
772                  nt_errstr(*status)));
773
774         ps->data_offset += sizeof(uint32);
775
776         return True;
777 }
778
779 /*******************************************************************
780  Stream a DCE error code
781  ********************************************************************/
782
783 BOOL prs_dcerpc_status(const char *name, prs_struct *ps, int depth, NTSTATUS *status)
784 {
785         char *q = prs_mem_get(ps, sizeof(uint32));
786         if (q == NULL)
787                 return False;
788
789         if (UNMARSHALLING(ps)) {
790                 if (ps->bigendian_data)
791                         *status = NT_STATUS(RIVAL(q,0));
792                 else
793                         *status = NT_STATUS(IVAL(q,0));
794         } else {
795                 if (ps->bigendian_data)
796                         RSIVAL(q,0,NT_STATUS_V(*status));
797                 else
798                         SIVAL(q,0,NT_STATUS_V(*status));
799         }
800
801         DEBUG(5,("%s%04x %s: %s\n", tab_depth(depth), ps->data_offset, name, 
802                  dcerpc_errstr(NT_STATUS_V(*status))));
803
804         ps->data_offset += sizeof(uint32);
805
806         return True;
807 }
808
809
810 /*******************************************************************
811  Stream a WERROR
812  ********************************************************************/
813
814 BOOL prs_werror(const char *name, prs_struct *ps, int depth, WERROR *status)
815 {
816         char *q = prs_mem_get(ps, sizeof(uint32));
817         if (q == NULL)
818                 return False;
819
820         if (UNMARSHALLING(ps)) {
821                 if (ps->bigendian_data)
822                         *status = W_ERROR(RIVAL(q,0));
823                 else
824                         *status = W_ERROR(IVAL(q,0));
825         } else {
826                 if (ps->bigendian_data)
827                         RSIVAL(q,0,W_ERROR_V(*status));
828                 else
829                         SIVAL(q,0,W_ERROR_V(*status));
830         }
831
832         DEBUG(5,("%s%04x %s: %s\n", tab_depth(depth), ps->data_offset, name, 
833                  dos_errstr(*status)));
834
835         ps->data_offset += sizeof(uint32);
836
837         return True;
838 }
839
840
841 /******************************************************************
842  Stream an array of uint8s. Length is number of uint8s.
843  ********************************************************************/
844
845 BOOL prs_uint8s(BOOL charmode, const char *name, prs_struct *ps, int depth, uint8 *data8s, int len)
846 {
847         int i;
848         char *q = prs_mem_get(ps, len);
849         if (q == NULL)
850                 return False;
851
852         if (UNMARSHALLING(ps)) {
853                 for (i = 0; i < len; i++)
854                         data8s[i] = CVAL(q,i);
855         } else {
856                 for (i = 0; i < len; i++)
857                         SCVAL(q, i, data8s[i]);
858         }
859
860         DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset ,name));
861         if (charmode)
862                 print_asc(5, (unsigned char*)data8s, len);
863         else {
864                 for (i = 0; i < len; i++)
865                         DEBUG(5,("%02x ", data8s[i]));
866         }
867         DEBUG(5,("\n"));
868
869         ps->data_offset += len;
870
871         return True;
872 }
873
874 /******************************************************************
875  Stream an array of uint16s. Length is number of uint16s.
876  ********************************************************************/
877
878 BOOL prs_uint16s(BOOL charmode, const char *name, prs_struct *ps, int depth, uint16 *data16s, int len)
879 {
880         int i;
881         char *q = prs_mem_get(ps, len * sizeof(uint16));
882         if (q == NULL)
883                 return False;
884
885         if (UNMARSHALLING(ps)) {
886                 if (ps->bigendian_data) {
887                         for (i = 0; i < len; i++)
888                                 data16s[i] = RSVAL(q, 2*i);
889                 } else {
890                         for (i = 0; i < len; i++)
891                                 data16s[i] = SVAL(q, 2*i);
892                 }
893         } else {
894                 if (ps->bigendian_data) {
895                         for (i = 0; i < len; i++)
896                                 RSSVAL(q, 2*i, data16s[i]);
897                 } else {
898                         for (i = 0; i < len; i++)
899                                 SSVAL(q, 2*i, data16s[i]);
900                 }
901         }
902
903         DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset, name));
904         if (charmode)
905                 print_asc(5, (unsigned char*)data16s, 2*len);
906         else {
907                 for (i = 0; i < len; i++)
908                         DEBUG(5,("%04x ", data16s[i]));
909         }
910         DEBUG(5,("\n"));
911
912         ps->data_offset += (len * sizeof(uint16));
913
914         return True;
915 }
916
917 /******************************************************************
918  Start using a function for streaming unicode chars. If unmarshalling,
919  output must be little-endian, if marshalling, input must be little-endian.
920  ********************************************************************/
921
922 static void dbg_rw_punival(BOOL charmode, const char *name, int depth, prs_struct *ps,
923                                                         char *in_buf, char *out_buf, int len)
924 {
925         int i;
926
927         if (UNMARSHALLING(ps)) {
928                 if (ps->bigendian_data) {
929                         for (i = 0; i < len; i++)
930                                 SSVAL(out_buf,2*i,RSVAL(in_buf, 2*i));
931                 } else {
932                         for (i = 0; i < len; i++)
933                                 SSVAL(out_buf, 2*i, SVAL(in_buf, 2*i));
934                 }
935         } else {
936                 if (ps->bigendian_data) {
937                         for (i = 0; i < len; i++)
938                                 RSSVAL(in_buf, 2*i, SVAL(out_buf,2*i));
939                 } else {
940                         for (i = 0; i < len; i++)
941                                 SSVAL(in_buf, 2*i, SVAL(out_buf,2*i));
942                 }
943         }
944
945         DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset, name));
946         if (charmode)
947                 print_asc(5, (unsigned char*)out_buf, 2*len);
948         else {
949                 for (i = 0; i < len; i++)
950                         DEBUG(5,("%04x ", out_buf[i]));
951         }
952         DEBUG(5,("\n"));
953 }
954
955 /******************************************************************
956  Stream a unistr. Always little endian.
957  ********************************************************************/
958
959 BOOL prs_uint16uni(BOOL charmode, const char *name, prs_struct *ps, int depth, uint16 *data16s, int len)
960 {
961         char *q = prs_mem_get(ps, len * sizeof(uint16));
962         if (q == NULL)
963                 return False;
964
965         dbg_rw_punival(charmode, name, depth, ps, q, (char *)data16s, len);
966         ps->data_offset += (len * sizeof(uint16));
967
968         return True;
969 }
970
971 /******************************************************************
972  Stream an array of uint32s. Length is number of uint32s.
973  ********************************************************************/
974
975 BOOL prs_uint32s(BOOL charmode, const char *name, prs_struct *ps, int depth, uint32 *data32s, int len)
976 {
977         int i;
978         char *q = prs_mem_get(ps, len * sizeof(uint32));
979         if (q == NULL)
980                 return False;
981
982         if (UNMARSHALLING(ps)) {
983                 if (ps->bigendian_data) {
984                         for (i = 0; i < len; i++)
985                                 data32s[i] = RIVAL(q, 4*i);
986                 } else {
987                         for (i = 0; i < len; i++)
988                                 data32s[i] = IVAL(q, 4*i);
989                 }
990         } else {
991                 if (ps->bigendian_data) {
992                         for (i = 0; i < len; i++)
993                                 RSIVAL(q, 4*i, data32s[i]);
994                 } else {
995                         for (i = 0; i < len; i++)
996                                 SIVAL(q, 4*i, data32s[i]);
997                 }
998         }
999
1000         DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset, name));
1001         if (charmode)
1002                 print_asc(5, (unsigned char*)data32s, 4*len);
1003         else {
1004                 for (i = 0; i < len; i++)
1005                         DEBUG(5,("%08x ", data32s[i]));
1006         }
1007         DEBUG(5,("\n"));
1008
1009         ps->data_offset += (len * sizeof(uint32));
1010
1011         return True;
1012 }
1013
1014 /******************************************************************
1015  Stream an array of unicode string, length/buffer specified separately,
1016  in uint16 chars. The unicode string is already in little-endian format.
1017  ********************************************************************/
1018
1019 BOOL prs_buffer5(BOOL charmode, const char *name, prs_struct *ps, int depth, BUFFER5 *str)
1020 {
1021         char *p;
1022         char *q = prs_mem_get(ps, str->buf_len * sizeof(uint16));
1023         if (q == NULL)
1024                 return False;
1025
1026         /* If the string is empty, we don't have anything to stream */
1027         if (str->buf_len==0)
1028                 return True;
1029
1030         if (UNMARSHALLING(ps)) {
1031                 str->buffer = PRS_ALLOC_MEM(ps,uint16,str->buf_len);
1032                 if (str->buffer == NULL)
1033                         return False;
1034         }
1035
1036         p = (char *)str->buffer;
1037
1038         dbg_rw_punival(charmode, name, depth, ps, q, p, str->buf_len);
1039         
1040         ps->data_offset += (str->buf_len * sizeof(uint16));
1041
1042         return True;
1043 }
1044
1045 /******************************************************************
1046  Stream a "not" unicode string, length/buffer specified separately,
1047  in byte chars. String is in little-endian format.
1048  ********************************************************************/
1049
1050 BOOL prs_regval_buffer(BOOL charmode, const char *name, prs_struct *ps, int depth, REGVAL_BUFFER *buf)
1051 {
1052         char *p;
1053         char *q = prs_mem_get(ps, buf->buf_len);
1054         if (q == NULL)
1055                 return False;
1056
1057         if (UNMARSHALLING(ps)) {
1058                 if (buf->buf_len > buf->buf_max_len) {
1059                         return False;
1060                 }
1061                 if ( buf->buf_max_len ) {
1062                         buf->buffer = PRS_ALLOC_MEM(ps, uint16, buf->buf_max_len);
1063                         if ( buf->buffer == NULL )
1064                                 return False;
1065                 } else {
1066                         buf->buffer = NULL;
1067                 }
1068         }
1069
1070         p = (char *)buf->buffer;
1071
1072         dbg_rw_punival(charmode, name, depth, ps, q, p, buf->buf_len/2);
1073         ps->data_offset += buf->buf_len;
1074
1075         return True;
1076 }
1077
1078 /******************************************************************
1079  Stream a string, length/buffer specified separately,
1080  in uint8 chars.
1081  ********************************************************************/
1082
1083 BOOL prs_string2(BOOL charmode, const char *name, prs_struct *ps, int depth, STRING2 *str)
1084 {
1085         unsigned int i;
1086         char *q = prs_mem_get(ps, str->str_str_len);
1087         if (q == NULL)
1088                 return False;
1089
1090         if (UNMARSHALLING(ps)) {
1091                 if (str->str_str_len > str->str_max_len) {
1092                         return False;
1093                 }
1094                 if (str->str_max_len) {
1095                         str->buffer = PRS_ALLOC_MEM(ps,unsigned char, str->str_max_len);
1096                         if (str->buffer == NULL)
1097                                 return False;
1098                 } else {
1099                         str->buffer = NULL;
1100                         /* Return early to ensure Coverity isn't confused. */
1101                         DEBUG(5,("%s%04x %s: \n", tab_depth(depth), ps->data_offset, name));
1102                         return True;
1103                 }
1104         }
1105
1106         if (UNMARSHALLING(ps)) {
1107                 for (i = 0; i < str->str_str_len; i++)
1108                         str->buffer[i] = CVAL(q,i);
1109         } else {
1110                 for (i = 0; i < str->str_str_len; i++)
1111                         SCVAL(q, i, str->buffer[i]);
1112         }
1113
1114         DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset, name));
1115         if (charmode)
1116                 print_asc(5, (unsigned char*)str->buffer, str->str_str_len);
1117         else {
1118                 for (i = 0; i < str->str_str_len; i++)
1119                         DEBUG(5,("%02x ", str->buffer[i]));
1120         }
1121         DEBUG(5,("\n"));
1122
1123         ps->data_offset += str->str_str_len;
1124
1125         return True;
1126 }
1127
1128 /******************************************************************
1129  Stream a unicode string, length/buffer specified separately,
1130  in uint16 chars. The unicode string is already in little-endian format.
1131  ********************************************************************/
1132
1133 BOOL prs_unistr2(BOOL charmode, const char *name, prs_struct *ps, int depth, UNISTR2 *str)
1134 {
1135         char *p;
1136         char *q = prs_mem_get(ps, str->uni_str_len * sizeof(uint16));
1137         if (q == NULL)
1138                 return False;
1139
1140         /* If the string is empty, we don't have anything to stream */
1141         if (str->uni_str_len==0)
1142                 return True;
1143
1144         if (UNMARSHALLING(ps)) {
1145                 if (str->uni_str_len > str->uni_max_len) {
1146                         return False;
1147                 }
1148                 if (str->uni_max_len) {
1149                         str->buffer = PRS_ALLOC_MEM(ps,uint16,str->uni_max_len);
1150                         if (str->buffer == NULL)
1151                                 return False;
1152                 } else {
1153                         str->buffer = NULL;
1154                 }
1155         }
1156
1157         p = (char *)str->buffer;
1158
1159         dbg_rw_punival(charmode, name, depth, ps, q, p, str->uni_str_len);
1160         
1161         ps->data_offset += (str->uni_str_len * sizeof(uint16));
1162
1163         return True;
1164 }
1165
1166 /******************************************************************
1167  Stream a unicode string, length/buffer specified separately,
1168  in uint16 chars. The unicode string is already in little-endian format.
1169  ********************************************************************/
1170
1171 BOOL prs_unistr3(BOOL charmode, const char *name, UNISTR3 *str, prs_struct *ps, int depth)
1172 {
1173         char *p;
1174         char *q = prs_mem_get(ps, str->uni_str_len * sizeof(uint16));
1175         if (q == NULL)
1176                 return False;
1177
1178         if (UNMARSHALLING(ps)) {
1179                 if (str->uni_str_len) {
1180                         str->str.buffer = PRS_ALLOC_MEM(ps,uint16,str->uni_str_len);
1181                         if (str->str.buffer == NULL)
1182                                 return False;
1183                 } else {
1184                         str->str.buffer = NULL;
1185                 }
1186         }
1187
1188         p = (char *)str->str.buffer;
1189
1190         dbg_rw_punival(charmode, name, depth, ps, q, p, str->uni_str_len);
1191         ps->data_offset += (str->uni_str_len * sizeof(uint16));
1192
1193         return True;
1194 }
1195
1196 /*******************************************************************
1197  Stream a unicode  null-terminated string. As the string is already
1198  in little-endian format then do it as a stream of bytes.
1199  ********************************************************************/
1200
1201 BOOL prs_unistr(const char *name, prs_struct *ps, int depth, UNISTR *str)
1202 {
1203         unsigned int len = 0;
1204         unsigned char *p = (unsigned char *)str->buffer;
1205         uint8 *start;
1206         char *q;
1207         uint32 max_len;
1208         uint16* ptr;
1209
1210         if (MARSHALLING(ps)) {
1211
1212                 for(len = 0; str->buffer[len] != 0; len++)
1213                         ;
1214
1215                 q = prs_mem_get(ps, (len+1)*2);
1216                 if (q == NULL)
1217                         return False;
1218
1219                 start = (uint8*)q;
1220
1221                 for(len = 0; str->buffer[len] != 0; len++) {
1222                         if(ps->bigendian_data) {
1223                                 /* swap bytes - p is little endian, q is big endian. */
1224                                 q[0] = (char)p[1];
1225                                 q[1] = (char)p[0];
1226                                 p += 2;
1227                                 q += 2;
1228                         } 
1229                         else 
1230                         {
1231                                 q[0] = (char)p[0];
1232                                 q[1] = (char)p[1];
1233                                 p += 2;
1234                                 q += 2;
1235                         }
1236                 }
1237
1238                 /*
1239                  * even if the string is 'empty' (only an \0 char)
1240                  * at this point the leading \0 hasn't been parsed.
1241                  * so parse it now
1242                  */
1243
1244                 q[0] = 0;
1245                 q[1] = 0;
1246                 q += 2;
1247
1248                 len++;
1249
1250                 DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset, name));
1251                 print_asc(5, (unsigned char*)start, 2*len);     
1252                 DEBUG(5, ("\n"));
1253         }
1254         else { /* unmarshalling */
1255         
1256                 uint32 alloc_len = 0;
1257                 q = ps->data_p + prs_offset(ps);
1258
1259                 /*
1260                  * Work out how much space we need and talloc it.
1261                  */
1262                 max_len = (ps->buffer_size - ps->data_offset)/sizeof(uint16);
1263
1264                 /* the test of the value of *ptr helps to catch the circumstance
1265                    where we have an emtpty (non-existent) string in the buffer */
1266                 for ( ptr = (uint16 *)q; *ptr++ && (alloc_len <= max_len); alloc_len++)
1267                         /* do nothing */ 
1268                         ;
1269
1270                 if (alloc_len < max_len)
1271                         alloc_len += 1;
1272
1273                 /* should we allocate anything at all? */
1274                 str->buffer = PRS_ALLOC_MEM(ps,uint16,alloc_len);
1275                 if ((str->buffer == NULL) && (alloc_len > 0))
1276                         return False;
1277
1278                 p = (unsigned char *)str->buffer;
1279
1280                 len = 0;
1281                 /* the (len < alloc_len) test is to prevent us from overwriting
1282                    memory that is not ours...if we get that far, we have a non-null
1283                    terminated string in the buffer and have messed up somewhere */
1284                 while ((len < alloc_len) && (*(uint16 *)q != 0)) {
1285                         if(ps->bigendian_data) 
1286                         {
1287                                 /* swap bytes - q is big endian, p is little endian. */
1288                                 p[0] = (unsigned char)q[1];
1289                                 p[1] = (unsigned char)q[0];
1290                                 p += 2;
1291                                 q += 2;
1292                         } else {
1293
1294                                 p[0] = (unsigned char)q[0];
1295                                 p[1] = (unsigned char)q[1];
1296                                 p += 2;
1297                                 q += 2;
1298                         }
1299
1300                         len++;
1301                 } 
1302                 if (len < alloc_len) {
1303                         /* NULL terminate the UNISTR */
1304                         str->buffer[len++] = '\0';
1305                 }
1306
1307                 DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset, name));
1308                 print_asc(5, (unsigned char*)str->buffer, 2*len);       
1309                 DEBUG(5, ("\n"));
1310         }
1311
1312         /* set the offset in the prs_struct; 'len' points to the
1313            terminiating NULL in the UNISTR so we need to go one more
1314            uint16 */
1315         ps->data_offset += (len)*2;
1316         
1317         return True;
1318 }
1319
1320
1321 /*******************************************************************
1322  Stream a null-terminated string.  len is strlen, and therefore does
1323  not include the null-termination character.
1324  ********************************************************************/
1325
1326 BOOL prs_string(const char *name, prs_struct *ps, int depth, char *str, int max_buf_size)
1327 {
1328         char *q;
1329         int i;
1330         int len;
1331
1332         if (UNMARSHALLING(ps))
1333                 len = strlen(&ps->data_p[ps->data_offset]);
1334         else
1335                 len = strlen(str);
1336
1337         len = MIN(len, (max_buf_size-1));
1338
1339         q = prs_mem_get(ps, len+1);
1340         if (q == NULL)
1341                 return False;
1342
1343         for(i = 0; i < len; i++) {
1344                 if (UNMARSHALLING(ps))
1345                         str[i] = q[i];
1346                 else
1347                         q[i] = str[i];
1348         }
1349
1350         /* The terminating null. */
1351         str[i] = '\0';
1352
1353         if (MARSHALLING(ps)) {
1354                 q[i] = '\0';
1355         }
1356
1357         ps->data_offset += len+1;
1358
1359         dump_data(5+depth, (uint8 *)q, len);
1360
1361         return True;
1362 }
1363
1364 BOOL prs_string_alloc(const char *name, prs_struct *ps, int depth, const char **str)
1365 {
1366         size_t len;
1367         char *tmp_str;
1368
1369         if (UNMARSHALLING(ps)) {
1370                 len = strlen(&ps->data_p[ps->data_offset]);
1371         } else {
1372                 len = strlen(*str);
1373         }
1374
1375         tmp_str = PRS_ALLOC_MEM(ps, char, len+1);
1376
1377         if (tmp_str == NULL) {
1378                 return False;
1379         }
1380
1381         if (MARSHALLING(ps)) {
1382                 strncpy(tmp_str, *str, len);
1383         }
1384
1385         if (!prs_string(name, ps, depth, tmp_str, len+1)) {
1386                 return False;
1387         }
1388
1389         *str = tmp_str;
1390         return True;
1391 }
1392
1393 /*******************************************************************
1394  prs_uint16 wrapper. Call this and it sets up a pointer to where the
1395  uint16 should be stored, or gets the size if reading.
1396  ********************************************************************/
1397
1398 BOOL prs_uint16_pre(const char *name, prs_struct *ps, int depth, uint16 *data16, uint32 *offset)
1399 {
1400         *offset = ps->data_offset;
1401         if (UNMARSHALLING(ps)) {
1402                 /* reading. */
1403                 return prs_uint16(name, ps, depth, data16);
1404         } else {
1405                 char *q = prs_mem_get(ps, sizeof(uint16));
1406                 if(q ==NULL)
1407                         return False;
1408                 ps->data_offset += sizeof(uint16);
1409         }
1410         return True;
1411 }
1412
1413 /*******************************************************************
1414  prs_uint16 wrapper.  call this and it retrospectively stores the size.
1415  does nothing on reading, as that is already handled by ...._pre()
1416  ********************************************************************/
1417
1418 BOOL prs_uint16_post(const char *name, prs_struct *ps, int depth, uint16 *data16,
1419                                 uint32 ptr_uint16, uint32 start_offset)
1420 {
1421         if (MARSHALLING(ps)) {
1422                 /* 
1423                  * Writing - temporarily move the offset pointer.
1424                  */
1425                 uint16 data_size = ps->data_offset - start_offset;
1426                 uint32 old_offset = ps->data_offset;
1427
1428                 ps->data_offset = ptr_uint16;
1429                 if(!prs_uint16(name, ps, depth, &data_size)) {
1430                         ps->data_offset = old_offset;
1431                         return False;
1432                 }
1433                 ps->data_offset = old_offset;
1434         } else {
1435                 ps->data_offset = start_offset + (uint32)(*data16);
1436         }
1437         return True;
1438 }
1439
1440 /*******************************************************************
1441  prs_uint32 wrapper. Call this and it sets up a pointer to where the
1442  uint32 should be stored, or gets the size if reading.
1443  ********************************************************************/
1444
1445 BOOL prs_uint32_pre(const char *name, prs_struct *ps, int depth, uint32 *data32, uint32 *offset)
1446 {
1447         *offset = ps->data_offset;
1448         if (UNMARSHALLING(ps) && (data32 != NULL)) {
1449                 /* reading. */
1450                 return prs_uint32(name, ps, depth, data32);
1451         } else {
1452                 ps->data_offset += sizeof(uint32);
1453         }
1454         return True;
1455 }
1456
1457 /*******************************************************************
1458  prs_uint32 wrapper.  call this and it retrospectively stores the size.
1459  does nothing on reading, as that is already handled by ...._pre()
1460  ********************************************************************/
1461
1462 BOOL prs_uint32_post(const char *name, prs_struct *ps, int depth, uint32 *data32,
1463                                 uint32 ptr_uint32, uint32 data_size)
1464 {
1465         if (MARSHALLING(ps)) {
1466                 /* 
1467                  * Writing - temporarily move the offset pointer.
1468                  */
1469                 uint32 old_offset = ps->data_offset;
1470                 ps->data_offset = ptr_uint32;
1471                 if(!prs_uint32(name, ps, depth, &data_size)) {
1472                         ps->data_offset = old_offset;
1473                         return False;
1474                 }
1475                 ps->data_offset = old_offset;
1476         }
1477         return True;
1478 }
1479
1480 /* useful function to store a structure in rpc wire format */
1481 int tdb_prs_store(TDB_CONTEXT *tdb, TDB_DATA kbuf, prs_struct *ps)
1482 {
1483         TDB_DATA dbuf;
1484         dbuf.dptr = (uint8 *)ps->data_p;
1485         dbuf.dsize = prs_offset(ps);
1486         return tdb_trans_store(tdb, kbuf, dbuf, TDB_REPLACE);
1487 }
1488
1489 /* useful function to fetch a structure into rpc wire format */
1490 int tdb_prs_fetch(TDB_CONTEXT *tdb, TDB_DATA kbuf, prs_struct *ps, TALLOC_CTX *mem_ctx)
1491 {
1492         TDB_DATA dbuf;
1493
1494         prs_init(ps, 0, mem_ctx, UNMARSHALL);
1495
1496         dbuf = tdb_fetch(tdb, kbuf);
1497         if (!dbuf.dptr)
1498                 return -1;
1499
1500         prs_give_memory(ps, (char *)dbuf.dptr, dbuf.dsize, True);
1501
1502         return 0;
1503 }
1504
1505 /*******************************************************************
1506  hash a stream.
1507  ********************************************************************/
1508
1509 BOOL prs_hash1(prs_struct *ps, uint32 offset, int len)
1510 {
1511         char *q;
1512
1513         q = ps->data_p;
1514         q = &q[offset];
1515
1516 #ifdef DEBUG_PASSWORD
1517         DEBUG(100, ("prs_hash1\n"));
1518         dump_data(100, (uint8 *)ps->sess_key, 16);
1519         dump_data(100, (uint8 *)q, len);
1520 #endif
1521         SamOEMhash((uchar *) q, (const unsigned char *)ps->sess_key, len);
1522
1523 #ifdef DEBUG_PASSWORD
1524         dump_data(100, (uint8 *)q, len);
1525 #endif
1526
1527         return True;
1528 }
1529
1530 /*******************************************************************
1531  Create a digest over the entire packet (including the data), and 
1532  MD5 it with the session key.
1533  ********************************************************************/
1534
1535 static void schannel_digest(struct schannel_auth_struct *a,
1536                           enum pipe_auth_level auth_level,
1537                           RPC_AUTH_SCHANNEL_CHK * verf,
1538                           char *data, size_t data_len,
1539                           uchar digest_final[16]) 
1540 {
1541         uchar whole_packet_digest[16];
1542         static const uchar zeros[4] = { 0, };
1543         struct MD5Context ctx3;
1544         
1545         /* verfiy the signature on the packet by MD5 over various bits */
1546         MD5Init(&ctx3);
1547         /* use our sequence number, which ensures the packet is not
1548            out of order */
1549         MD5Update(&ctx3, zeros, sizeof(zeros));
1550         MD5Update(&ctx3, verf->sig, sizeof(verf->sig));
1551         if (auth_level == PIPE_AUTH_LEVEL_PRIVACY) {
1552                 MD5Update(&ctx3, verf->confounder, sizeof(verf->confounder));
1553         }
1554         MD5Update(&ctx3, (const unsigned char *)data, data_len);
1555         MD5Final(whole_packet_digest, &ctx3);
1556         dump_data_pw("whole_packet_digest:\n", whole_packet_digest, sizeof(whole_packet_digest));
1557         
1558         /* MD5 this result and the session key, to prove that
1559            only a valid client could had produced this */
1560         hmac_md5(a->sess_key, whole_packet_digest, sizeof(whole_packet_digest), digest_final);
1561 }
1562
1563 /*******************************************************************
1564  Calculate the key with which to encode the data payload 
1565  ********************************************************************/
1566
1567 static void schannel_get_sealing_key(struct schannel_auth_struct *a,
1568                                    RPC_AUTH_SCHANNEL_CHK *verf,
1569                                    uchar sealing_key[16]) 
1570 {
1571         static const uchar zeros[4] = { 0, };
1572         uchar digest2[16];
1573         uchar sess_kf0[16];
1574         int i;
1575
1576         for (i = 0; i < sizeof(sess_kf0); i++) {
1577                 sess_kf0[i] = a->sess_key[i] ^ 0xf0;
1578         }
1579         
1580         dump_data_pw("sess_kf0:\n", sess_kf0, sizeof(sess_kf0));
1581         
1582         /* MD5 of sess_kf0 and 4 zero bytes */
1583         hmac_md5(sess_kf0, zeros, 0x4, digest2);
1584         dump_data_pw("digest2:\n", digest2, sizeof(digest2));
1585         
1586         /* MD5 of the above result, plus 8 bytes of sequence number */
1587         hmac_md5(digest2, verf->seq_num, sizeof(verf->seq_num), sealing_key);
1588         dump_data_pw("sealing_key:\n", sealing_key, 16);
1589 }
1590
1591 /*******************************************************************
1592  Encode or Decode the sequence number (which is symmetric)
1593  ********************************************************************/
1594
1595 static void schannel_deal_with_seq_num(struct schannel_auth_struct *a,
1596                                      RPC_AUTH_SCHANNEL_CHK *verf)
1597 {
1598         static const uchar zeros[4] = { 0, };
1599         uchar sequence_key[16];
1600         uchar digest1[16];
1601
1602         hmac_md5(a->sess_key, zeros, sizeof(zeros), digest1);
1603         dump_data_pw("(sequence key) digest1:\n", digest1, sizeof(digest1));
1604
1605         hmac_md5(digest1, verf->packet_digest, 8, sequence_key);
1606
1607         dump_data_pw("sequence_key:\n", sequence_key, sizeof(sequence_key));
1608
1609         dump_data_pw("seq_num (before):\n", verf->seq_num, sizeof(verf->seq_num));
1610         SamOEMhash(verf->seq_num, sequence_key, 8);
1611         dump_data_pw("seq_num (after):\n", verf->seq_num, sizeof(verf->seq_num));
1612 }
1613
1614 /*******************************************************************
1615 creates an RPC_AUTH_SCHANNEL_CHK structure.
1616 ********************************************************************/
1617
1618 static BOOL init_rpc_auth_schannel_chk(RPC_AUTH_SCHANNEL_CHK * chk,
1619                               const uchar sig[8],
1620                               const uchar packet_digest[8],
1621                               const uchar seq_num[8], const uchar confounder[8])
1622 {
1623         if (chk == NULL)
1624                 return False;
1625
1626         memcpy(chk->sig, sig, sizeof(chk->sig));
1627         memcpy(chk->packet_digest, packet_digest, sizeof(chk->packet_digest));
1628         memcpy(chk->seq_num, seq_num, sizeof(chk->seq_num));
1629         memcpy(chk->confounder, confounder, sizeof(chk->confounder));
1630
1631         return True;
1632 }
1633
1634 /*******************************************************************
1635  Encode a blob of data using the schannel alogrithm, also produceing
1636  a checksum over the original data.  We currently only support
1637  signing and sealing togeather - the signing-only code is close, but not
1638  quite compatible with what MS does.
1639  ********************************************************************/
1640
1641 void schannel_encode(struct schannel_auth_struct *a, enum pipe_auth_level auth_level,
1642                    enum schannel_direction direction,
1643                    RPC_AUTH_SCHANNEL_CHK * verf,
1644                    char *data, size_t data_len)
1645 {
1646         uchar digest_final[16];
1647         uchar confounder[8];
1648         uchar seq_num[8];
1649         static const uchar nullbytes[8] = { 0, };
1650
1651         static const uchar schannel_seal_sig[8] = SCHANNEL_SEAL_SIGNATURE;
1652         static const uchar schannel_sign_sig[8] = SCHANNEL_SIGN_SIGNATURE;
1653         const uchar *schannel_sig = NULL;
1654
1655         DEBUG(10,("SCHANNEL: schannel_encode seq_num=%d data_len=%lu\n", a->seq_num, (unsigned long)data_len));
1656         
1657         if (auth_level == PIPE_AUTH_LEVEL_PRIVACY) {
1658                 schannel_sig = schannel_seal_sig;
1659         } else {
1660                 schannel_sig = schannel_sign_sig;
1661         }
1662
1663         /* fill the 'confounder' with random data */
1664         generate_random_buffer(confounder, sizeof(confounder));
1665
1666         dump_data_pw("a->sess_key:\n", a->sess_key, sizeof(a->sess_key));
1667
1668         RSIVAL(seq_num, 0, a->seq_num);
1669
1670         switch (direction) {
1671         case SENDER_IS_INITIATOR:
1672                 SIVAL(seq_num, 4, 0x80);
1673                 break;
1674         case SENDER_IS_ACCEPTOR:
1675                 SIVAL(seq_num, 4, 0x0);
1676                 break;
1677         }
1678
1679         dump_data_pw("verf->seq_num:\n", seq_num, sizeof(verf->seq_num));
1680
1681         init_rpc_auth_schannel_chk(verf, schannel_sig, nullbytes,
1682                                  seq_num, confounder);
1683                                 
1684         /* produce a digest of the packet to prove it's legit (before we seal it) */
1685         schannel_digest(a, auth_level, verf, data, data_len, digest_final);
1686         memcpy(verf->packet_digest, digest_final, sizeof(verf->packet_digest));
1687
1688         if (auth_level == PIPE_AUTH_LEVEL_PRIVACY) {
1689                 uchar sealing_key[16];
1690
1691                 /* get the key to encode the data with */
1692                 schannel_get_sealing_key(a, verf, sealing_key);
1693
1694                 /* encode the verification data */
1695                 dump_data_pw("verf->confounder:\n", verf->confounder, sizeof(verf->confounder));
1696                 SamOEMhash(verf->confounder, sealing_key, 8);
1697
1698                 dump_data_pw("verf->confounder_enc:\n", verf->confounder, sizeof(verf->confounder));
1699                 
1700                 /* encode the packet payload */
1701                 dump_data_pw("data:\n", (const unsigned char *)data, data_len);
1702                 SamOEMhash((unsigned char *)data, sealing_key, data_len);
1703                 dump_data_pw("data_enc:\n", (const unsigned char *)data, data_len);
1704         }
1705
1706         /* encode the sequence number (key based on packet digest) */
1707         /* needs to be done after the sealing, as the original version 
1708            is used in the sealing stuff... */
1709         schannel_deal_with_seq_num(a, verf);
1710
1711         return;
1712 }
1713
1714 /*******************************************************************
1715  Decode a blob of data using the schannel alogrithm, also verifiying
1716  a checksum over the original data.  We currently can verify signed messages,
1717  as well as decode sealed messages
1718  ********************************************************************/
1719
1720 BOOL schannel_decode(struct schannel_auth_struct *a, enum pipe_auth_level auth_level,
1721                    enum schannel_direction direction, 
1722                    RPC_AUTH_SCHANNEL_CHK * verf, char *data, size_t data_len)
1723 {
1724         uchar digest_final[16];
1725
1726         static const uchar schannel_seal_sig[8] = SCHANNEL_SEAL_SIGNATURE;
1727         static const uchar schannel_sign_sig[8] = SCHANNEL_SIGN_SIGNATURE;
1728         const uchar *schannel_sig = NULL;
1729
1730         uchar seq_num[8];
1731
1732         DEBUG(10,("SCHANNEL: schannel_decode seq_num=%d data_len=%lu\n", a->seq_num, (unsigned long)data_len));
1733         
1734         if (auth_level == PIPE_AUTH_LEVEL_PRIVACY) {
1735                 schannel_sig = schannel_seal_sig;
1736         } else {
1737                 schannel_sig = schannel_sign_sig;
1738         }
1739
1740         /* Create the expected sequence number for comparison */
1741         RSIVAL(seq_num, 0, a->seq_num);
1742
1743         switch (direction) {
1744         case SENDER_IS_INITIATOR:
1745                 SIVAL(seq_num, 4, 0x80);
1746                 break;
1747         case SENDER_IS_ACCEPTOR:
1748                 SIVAL(seq_num, 4, 0x0);
1749                 break;
1750         }
1751
1752         DEBUG(10,("SCHANNEL: schannel_decode seq_num=%d data_len=%lu\n", a->seq_num, (unsigned long)data_len));
1753         dump_data_pw("a->sess_key:\n", a->sess_key, sizeof(a->sess_key));
1754
1755         dump_data_pw("seq_num:\n", seq_num, sizeof(seq_num));
1756
1757         /* extract the sequence number (key based on supplied packet digest) */
1758         /* needs to be done before the sealing, as the original version 
1759            is used in the sealing stuff... */
1760         schannel_deal_with_seq_num(a, verf);
1761
1762         if (memcmp(verf->seq_num, seq_num, sizeof(seq_num))) {
1763                 /* don't even bother with the below if the sequence number is out */
1764                 /* The sequence number is MD5'ed with a key based on the whole-packet
1765                    digest, as supplied by the client.  We check that it's a valid 
1766                    checksum after the decode, below
1767                 */
1768                 DEBUG(2, ("schannel_decode: FAILED: packet sequence number:\n"));
1769                 dump_data(2, verf->seq_num, sizeof(verf->seq_num));
1770                 DEBUG(2, ("should be:\n"));
1771                 dump_data(2, seq_num, sizeof(seq_num));
1772
1773                 return False;
1774         }
1775
1776         if (memcmp(verf->sig, schannel_sig, sizeof(verf->sig))) {
1777                 /* Validate that the other end sent the expected header */
1778                 DEBUG(2, ("schannel_decode: FAILED: packet header:\n"));
1779                 dump_data(2, verf->sig, sizeof(verf->sig));
1780                 DEBUG(2, ("should be:\n"));
1781                 dump_data(2, schannel_sig, sizeof(schannel_sig));
1782                 return False;
1783         }
1784
1785         if (auth_level == PIPE_AUTH_LEVEL_PRIVACY) {
1786                 uchar sealing_key[16];
1787                 
1788                 /* get the key to extract the data with */
1789                 schannel_get_sealing_key(a, verf, sealing_key);
1790
1791                 /* extract the verification data */
1792                 dump_data_pw("verf->confounder:\n", verf->confounder, 
1793                              sizeof(verf->confounder));
1794                 SamOEMhash(verf->confounder, sealing_key, 8);
1795
1796                 dump_data_pw("verf->confounder_dec:\n", verf->confounder, 
1797                              sizeof(verf->confounder));
1798                 
1799                 /* extract the packet payload */
1800                 dump_data_pw("data   :\n", (const unsigned char *)data, data_len);
1801                 SamOEMhash((unsigned char *)data, sealing_key, data_len);
1802                 dump_data_pw("datadec:\n", (const unsigned char *)data, data_len);      
1803         }
1804
1805         /* digest includes 'data' after unsealing */
1806         schannel_digest(a, auth_level, verf, data, data_len, digest_final);
1807
1808         dump_data_pw("Calculated digest:\n", digest_final, 
1809                      sizeof(digest_final));
1810         dump_data_pw("verf->packet_digest:\n", verf->packet_digest, 
1811                      sizeof(verf->packet_digest));
1812         
1813         /* compare - if the client got the same result as us, then
1814            it must know the session key */
1815         return (memcmp(digest_final, verf->packet_digest, 
1816                        sizeof(verf->packet_digest)) == 0);
1817 }
1818
1819 /*******************************************************************
1820 creates a new prs_struct containing a DATA_BLOB
1821 ********************************************************************/
1822 BOOL prs_init_data_blob(prs_struct *prs, DATA_BLOB *blob, TALLOC_CTX *mem_ctx)
1823 {
1824         if (!prs_init( prs, RPC_MAX_PDU_FRAG_LEN, mem_ctx, MARSHALL ))
1825                 return False;
1826
1827
1828         if (!prs_copy_data_in(prs, (char *)blob->data, blob->length))
1829                 return False;
1830
1831         return True;
1832 }
1833
1834 /*******************************************************************
1835 return the contents of a prs_struct in a DATA_BLOB
1836 ********************************************************************/
1837 BOOL prs_data_blob(prs_struct *prs, DATA_BLOB *blob, TALLOC_CTX *mem_ctx)
1838 {
1839         blob->length = prs_data_size(prs);
1840         blob->data = (uint8 *)TALLOC_ZERO_SIZE(mem_ctx, blob->length);
1841         
1842         /* set the pointer at the end of the buffer */
1843         prs_set_offset( prs, prs_data_size(prs) );
1844
1845         if (!prs_copy_all_data_out((char *)blob->data, prs))
1846                 return False;
1847         
1848         return True;
1849 }