rpcrt4: Fix RPCRT4_Receive to accept authentication verifier data on any packets...
[wine] / dlls / rpcrt4 / rpc_message.c
1 /*
2  * RPC messages
3  *
4  * Copyright 2001-2002 Ove Kåven, TransGaming Technologies
5  * Copyright 2004 Filip Navara
6  * Copyright 2006 CodeWeavers
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <string.h>
26
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winerror.h"
30 #include "winreg.h"
31
32 #include "rpc.h"
33 #include "rpcndr.h"
34 #include "rpcdcep.h"
35
36 #include "wine/debug.h"
37
38 #include "rpc_binding.h"
39 #include "rpc_misc.h"
40 #include "rpc_defs.h"
41 #include "rpc_message.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
44
45 /* note: the DCE/RPC spec says the alignment amount should be 4, but
46  * MS/RPC servers seem to always use 16 */
47 #define AUTH_ALIGNMENT 16
48
49 /* gets the amount needed to round a value up to the specified alignment */
50 #define ROUND_UP_AMOUNT(value, alignment) \
51     (((alignment) - (((value) % (alignment)))) % (alignment))
52
53 static DWORD RPCRT4_GetHeaderSize(RpcPktHdr *Header)
54 {
55   static const DWORD header_sizes[] = {
56     sizeof(Header->request), 0, sizeof(Header->response),
57     sizeof(Header->fault), 0, 0, 0, 0, 0, 0, 0, sizeof(Header->bind),
58     sizeof(Header->bind_ack), sizeof(Header->bind_nack),
59     0, 0, 0, 0, 0
60   };
61   ULONG ret = 0;
62   
63   if (Header->common.ptype < sizeof(header_sizes) / sizeof(header_sizes[0])) {
64     ret = header_sizes[Header->common.ptype];
65     if (ret == 0)
66       FIXME("unhandled packet type\n");
67     if (Header->common.flags & RPC_FLG_OBJECT_UUID)
68       ret += sizeof(UUID);
69   } else {
70     TRACE("invalid packet type\n");
71   }
72
73   return ret;
74 }
75
76 static VOID RPCRT4_BuildCommonHeader(RpcPktHdr *Header, unsigned char PacketType,
77                               unsigned long DataRepresentation)
78 {
79   Header->common.rpc_ver = RPC_VER_MAJOR;
80   Header->common.rpc_ver_minor = RPC_VER_MINOR;
81   Header->common.ptype = PacketType;
82   Header->common.drep[0] = LOBYTE(LOWORD(DataRepresentation));
83   Header->common.drep[1] = HIBYTE(LOWORD(DataRepresentation));
84   Header->common.drep[2] = LOBYTE(HIWORD(DataRepresentation));
85   Header->common.drep[3] = HIBYTE(HIWORD(DataRepresentation));
86   Header->common.auth_len = 0;
87   Header->common.call_id = 1;
88   Header->common.flags = 0;
89   /* Flags and fragment length are computed in RPCRT4_Send. */
90 }                              
91
92 static RpcPktHdr *RPCRT4_BuildRequestHeader(unsigned long DataRepresentation,
93                                      unsigned long BufferLength,
94                                      unsigned short ProcNum,
95                                      UUID *ObjectUuid)
96 {
97   RpcPktHdr *header;
98   BOOL has_object;
99   RPC_STATUS status;
100
101   has_object = (ObjectUuid != NULL && !UuidIsNil(ObjectUuid, &status));
102   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
103                      sizeof(header->request) + (has_object ? sizeof(UUID) : 0));
104   if (header == NULL) {
105     return NULL;
106   }
107
108   RPCRT4_BuildCommonHeader(header, PKT_REQUEST, DataRepresentation);
109   header->common.frag_len = sizeof(header->request);
110   header->request.alloc_hint = BufferLength;
111   header->request.context_id = 0;
112   header->request.opnum = ProcNum;
113   if (has_object) {
114     header->common.flags |= RPC_FLG_OBJECT_UUID;
115     header->common.frag_len += sizeof(UUID);
116     memcpy(&header->request + 1, ObjectUuid, sizeof(UUID));
117   }
118
119   return header;
120 }
121
122 static RpcPktHdr *RPCRT4_BuildResponseHeader(unsigned long DataRepresentation,
123                                       unsigned long BufferLength)
124 {
125   RpcPktHdr *header;
126
127   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->response));
128   if (header == NULL) {
129     return NULL;
130   }
131
132   RPCRT4_BuildCommonHeader(header, PKT_RESPONSE, DataRepresentation);
133   header->common.frag_len = sizeof(header->response);
134   header->response.alloc_hint = BufferLength;
135
136   return header;
137 }
138
139 RpcPktHdr *RPCRT4_BuildFaultHeader(unsigned long DataRepresentation,
140                                    RPC_STATUS Status)
141 {
142   RpcPktHdr *header;
143
144   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->fault));
145   if (header == NULL) {
146     return NULL;
147   }
148
149   RPCRT4_BuildCommonHeader(header, PKT_FAULT, DataRepresentation);
150   header->common.frag_len = sizeof(header->fault);
151   header->fault.status = Status;
152
153   return header;
154 }
155
156 RpcPktHdr *RPCRT4_BuildBindHeader(unsigned long DataRepresentation,
157                                   unsigned short MaxTransmissionSize,
158                                   unsigned short MaxReceiveSize,
159                                   RPC_SYNTAX_IDENTIFIER *AbstractId,
160                                   RPC_SYNTAX_IDENTIFIER *TransferId)
161 {
162   RpcPktHdr *header;
163
164   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind));
165   if (header == NULL) {
166     return NULL;
167   }
168
169   RPCRT4_BuildCommonHeader(header, PKT_BIND, DataRepresentation);
170   header->common.frag_len = sizeof(header->bind);
171   header->bind.max_tsize = MaxTransmissionSize;
172   header->bind.max_rsize = MaxReceiveSize;
173   header->bind.num_elements = 1;
174   header->bind.num_syntaxes = 1;
175   memcpy(&header->bind.abstract, AbstractId, sizeof(RPC_SYNTAX_IDENTIFIER));
176   memcpy(&header->bind.transfer, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
177
178   return header;
179 }
180
181 RpcPktHdr *RPCRT4_BuildAuthHeader(unsigned long DataRepresentation)
182 {
183   RpcPktHdr *header;
184
185   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
186                      sizeof(header->common) + 12);
187   if (header == NULL)
188     return NULL;
189
190   RPCRT4_BuildCommonHeader(header, PKT_AUTH3, DataRepresentation);
191   header->common.frag_len = 0x14;
192   header->common.auth_len = 0;
193
194   return header;
195 }
196
197 RpcPktHdr *RPCRT4_BuildBindNackHeader(unsigned long DataRepresentation,
198                                       unsigned char RpcVersion,
199                                       unsigned char RpcVersionMinor)
200 {
201   RpcPktHdr *header;
202
203   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind_nack));
204   if (header == NULL) {
205     return NULL;
206   }
207
208   RPCRT4_BuildCommonHeader(header, PKT_BIND_NACK, DataRepresentation);
209   header->common.frag_len = sizeof(header->bind_nack);
210   header->bind_nack.protocols_count = 1;
211   header->bind_nack.protocols[0].rpc_ver = RpcVersion;
212   header->bind_nack.protocols[0].rpc_ver_minor = RpcVersionMinor;
213
214   return header;
215 }
216
217 RpcPktHdr *RPCRT4_BuildBindAckHeader(unsigned long DataRepresentation,
218                                      unsigned short MaxTransmissionSize,
219                                      unsigned short MaxReceiveSize,
220                                      LPSTR ServerAddress,
221                                      unsigned long Result,
222                                      unsigned long Reason,
223                                      RPC_SYNTAX_IDENTIFIER *TransferId)
224 {
225   RpcPktHdr *header;
226   unsigned long header_size;
227   RpcAddressString *server_address;
228   RpcResults *results;
229   RPC_SYNTAX_IDENTIFIER *transfer_id;
230
231   header_size = sizeof(header->bind_ack) + sizeof(RpcResults) +
232                 sizeof(RPC_SYNTAX_IDENTIFIER) + sizeof(RpcAddressString) +
233                 strlen(ServerAddress);
234
235   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, header_size);
236   if (header == NULL) {
237     return NULL;
238   }
239
240   RPCRT4_BuildCommonHeader(header, PKT_BIND_ACK, DataRepresentation);
241   header->common.frag_len = header_size;
242   header->bind_ack.max_tsize = MaxTransmissionSize;
243   header->bind_ack.max_rsize = MaxReceiveSize;
244   server_address = (RpcAddressString*)(&header->bind_ack + 1);
245   server_address->length = strlen(ServerAddress) + 1;
246   strcpy(server_address->string, ServerAddress);
247   results = (RpcResults*)((ULONG_PTR)server_address + sizeof(RpcAddressString) + server_address->length - 1);
248   results->num_results = 1;
249   results->results[0].result = Result;
250   results->results[0].reason = Reason;
251   transfer_id = (RPC_SYNTAX_IDENTIFIER*)(results + 1);
252   memcpy(transfer_id, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
253
254   return header;
255 }
256
257 VOID RPCRT4_FreeHeader(RpcPktHdr *Header)
258 {
259   HeapFree(GetProcessHeap(), 0, Header);
260 }
261
262 /***********************************************************************
263  *           RPCRT4_SendAuth (internal)
264  * 
265  * Transmit a packet with authorization data over connection in acceptable fragments.
266  */
267 static RPC_STATUS RPCRT4_SendAuth(RpcConnection *Connection, RpcPktHdr *Header,
268                                   void *Buffer, unsigned int BufferLength,
269                                   void *Auth, unsigned int AuthLength)
270 {
271   PUCHAR buffer_pos;
272   DWORD hdr_size;
273   LONG count;
274   unsigned char *pkt;
275   LONG alen = AuthLength ? (AuthLength + sizeof(RpcAuthVerifier)) : 0;
276
277   buffer_pos = Buffer;
278   /* The packet building functions save the packet header size, so we can use it. */
279   hdr_size = Header->common.frag_len;
280   Header->common.auth_len = AuthLength;
281   Header->common.flags |= RPC_FLG_FIRST;
282   Header->common.flags &= ~RPC_FLG_LAST;
283   while (!(Header->common.flags & RPC_FLG_LAST)) {
284     unsigned char auth_pad_len = AuthLength ? ROUND_UP_AMOUNT(BufferLength, AUTH_ALIGNMENT) : 0;
285     unsigned int pkt_size = BufferLength + hdr_size + alen + auth_pad_len;
286
287     /* decide if we need to split the packet into fragments */
288    if (pkt_size <= Connection->MaxTransmissionSize) {
289      Header->common.flags |= RPC_FLG_LAST;
290      Header->common.frag_len = pkt_size;
291     } else {
292       auth_pad_len = 0;
293       /* make sure packet payload will be a multiple of 16 */
294       Header->common.frag_len =
295         ((Connection->MaxTransmissionSize - hdr_size - alen) & ~(AUTH_ALIGNMENT-1)) +
296         hdr_size + alen;
297     }
298
299     pkt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Header->common.frag_len);
300
301     memcpy(pkt, Header, hdr_size);
302
303     /* fragment consisted of header only and is the last one */
304     if (hdr_size == Header->common.frag_len)
305       goto write;
306
307     memcpy(pkt + hdr_size, buffer_pos, Header->common.frag_len - hdr_size - auth_pad_len - alen);
308
309     /* add the authorization info */
310     if (Connection->AuthInfo && AuthLength)
311     {
312       RpcAuthVerifier *auth_hdr = (RpcAuthVerifier *)&pkt[Header->common.frag_len - alen];
313
314       auth_hdr->auth_type = Connection->AuthInfo->AuthnSvc;
315       auth_hdr->auth_level = Connection->AuthInfo->AuthnLevel;
316       auth_hdr->auth_pad_length = auth_pad_len;
317       auth_hdr->auth_reserved = 0;
318       /* a unique number... */
319       auth_hdr->auth_context_id = (unsigned long)Connection;
320
321       memcpy(auth_hdr + 1, Auth, AuthLength);
322     }
323
324 write:
325     count = rpcrt4_conn_write(Connection, pkt, Header->common.frag_len);
326     HeapFree(GetProcessHeap(), 0, pkt);
327     if (count<0) {
328       WARN("rpcrt4_conn_write failed (auth)\n");
329       return RPC_S_PROTOCOL_ERROR;
330     }
331
332     buffer_pos += Header->common.frag_len - hdr_size - alen - auth_pad_len;
333     BufferLength -= Header->common.frag_len - hdr_size - alen - auth_pad_len;
334     Header->common.flags &= ~RPC_FLG_FIRST;
335   }
336
337   return RPC_S_OK;
338 }
339
340 /***********************************************************************
341  *           RPCRT4_AuthNegotiate (internal)
342  */
343 static void RPCRT4_AuthNegotiate(RpcConnection *conn, SecBuffer *out)
344 {
345   SECURITY_STATUS r;
346   SecBufferDesc out_desc;
347   unsigned char *buffer;
348
349   buffer = HeapAlloc(GetProcessHeap(), 0, 0x100);
350
351   out->BufferType = SECBUFFER_TOKEN;
352   out->cbBuffer = 0x100;
353   out->pvBuffer = buffer;
354
355   out_desc.ulVersion = 0;
356   out_desc.cBuffers = 1;
357   out_desc.pBuffers = out;
358
359   conn->attr = 0;
360   conn->ctx.dwLower = 0;
361   conn->ctx.dwUpper = 0;
362
363   r = InitializeSecurityContextA(&conn->AuthInfo->cred, NULL, NULL,
364         ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE | ISC_REQ_MUTUAL_AUTH |
365         ISC_REQ_DELEGATE, 0, SECURITY_NETWORK_DREP,
366         NULL, 0, &conn->ctx, &out_desc, &conn->attr, &conn->exp);
367
368   TRACE("r = %08lx cbBuffer = %ld attr = %08lx\n", r, out->cbBuffer, conn->attr);
369 }
370
371 /***********************************************************************
372  *           RPCRT4_AuthorizeBinding (internal)
373  */
374 static RPC_STATUS RPCRT_AuthorizeConnection(RpcConnection* conn,
375                                             BYTE *challenge, ULONG count)
376 {
377   SecBufferDesc inp_desc, out_desc;
378   SecBuffer inp, out;
379   SECURITY_STATUS r;
380   unsigned char buffer[0x100];
381   RpcPktHdr *resp_hdr;
382   RPC_STATUS status;
383
384   TRACE("challenge %s, %ld bytes\n", challenge, count);
385
386   out.BufferType = SECBUFFER_TOKEN;
387   out.cbBuffer = sizeof buffer;
388   out.pvBuffer = buffer;
389
390   out_desc.ulVersion = 0;
391   out_desc.cBuffers = 1;
392   out_desc.pBuffers = &out;
393
394   inp.BufferType = SECBUFFER_TOKEN;
395   inp.pvBuffer = challenge;
396   inp.cbBuffer = count;
397
398   inp_desc.cBuffers = 1;
399   inp_desc.pBuffers = &inp;
400   inp_desc.ulVersion = 0;
401
402   r = InitializeSecurityContextA(&conn->AuthInfo->cred, &conn->ctx, NULL,
403         ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE | ISC_REQ_MUTUAL_AUTH |
404         ISC_REQ_DELEGATE, 0, SECURITY_NETWORK_DREP,
405         &inp_desc, 0, &conn->ctx, &out_desc, &conn->attr, &conn->exp);
406   if (r)
407   {
408     WARN("InitializeSecurityContext failed with error 0x%08lx\n", r);
409     return ERROR_ACCESS_DENIED;
410   }
411
412   resp_hdr = RPCRT4_BuildAuthHeader(NDR_LOCAL_DATA_REPRESENTATION);
413   if (!resp_hdr)
414     return E_OUTOFMEMORY;
415
416   status = RPCRT4_SendAuth(conn, resp_hdr, NULL, 0, out.pvBuffer, out.cbBuffer);
417
418   RPCRT4_FreeHeader(resp_hdr);
419
420   return status;
421 }
422
423 /***********************************************************************
424  *           RPCRT4_Send (internal)
425  * 
426  * Transmit a packet over connection in acceptable fragments.
427  */
428 RPC_STATUS RPCRT4_Send(RpcConnection *Connection, RpcPktHdr *Header,
429                        void *Buffer, unsigned int BufferLength)
430 {
431   RPC_STATUS r;
432   SecBuffer out;
433
434   /* if we've already authenticated, just send the context */
435   if (Connection->ctx.dwUpper || Connection->ctx.dwLower)
436   {
437     unsigned char buffer[0x10];
438
439     memset(buffer, 0, sizeof buffer);
440     buffer[0] = 1; /* version number lsb */
441
442     return RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, buffer, sizeof buffer);
443   }
444
445   if (!Connection->AuthInfo ||
446       Connection->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_DEFAULT ||
447       Connection->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_NONE)
448   {
449     return RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, NULL, 0);
450   }
451
452   out.BufferType = SECBUFFER_TOKEN;
453   out.cbBuffer = 0;
454   out.pvBuffer = NULL;
455
456   /* tack on a negotiate packet */
457   RPCRT4_AuthNegotiate(Connection, &out);
458   r = RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, out.pvBuffer, out.cbBuffer);
459   HeapFree(GetProcessHeap(), 0, out.pvBuffer);
460
461   return r;
462 }
463
464 /***********************************************************************
465  *           RPCRT4_Receive (internal)
466  * 
467  * Receive a packet from connection and merge the fragments.
468  */
469 RPC_STATUS RPCRT4_Receive(RpcConnection *Connection, RpcPktHdr **Header,
470                           PRPC_MESSAGE pMsg)
471 {
472   RPC_STATUS status;
473   DWORD hdr_length;
474   LONG dwRead;
475   unsigned short first_flag;
476   unsigned long data_length;
477   unsigned long buffer_length;
478   unsigned long auth_length;
479   unsigned char *buffer_ptr;
480   unsigned char *auth_data = NULL;
481   RpcPktCommonHdr common_hdr;
482
483   *Header = NULL;
484
485   TRACE("(%p, %p, %p)\n", Connection, Header, pMsg);
486
487   /* read packet common header */
488   dwRead = rpcrt4_conn_read(Connection, &common_hdr, sizeof(common_hdr));
489   if (dwRead != sizeof(common_hdr)) {
490     WARN("Short read of header, %ld bytes\n", dwRead);
491     status = RPC_S_PROTOCOL_ERROR;
492     goto fail;
493   }
494
495   /* verify if the header really makes sense */
496   if (common_hdr.rpc_ver != RPC_VER_MAJOR ||
497       common_hdr.rpc_ver_minor != RPC_VER_MINOR) {
498     WARN("unhandled packet version\n");
499     status = RPC_S_PROTOCOL_ERROR;
500     goto fail;
501   }
502
503   hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
504   if (hdr_length == 0) {
505     WARN("header length == 0\n");
506     status = RPC_S_PROTOCOL_ERROR;
507     goto fail;
508   }
509
510   *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
511   memcpy(*Header, &common_hdr, sizeof(common_hdr));
512
513   /* read the rest of packet header */
514   dwRead = rpcrt4_conn_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
515   if (dwRead != hdr_length - sizeof(common_hdr)) {
516     WARN("bad header length, %ld/%ld bytes\n", dwRead, hdr_length - sizeof(common_hdr));
517     status = RPC_S_PROTOCOL_ERROR;
518     goto fail;
519   }
520
521   /* read packet body */
522   switch (common_hdr.ptype) {
523   case PKT_RESPONSE:
524     pMsg->BufferLength = (*Header)->response.alloc_hint;
525     break;
526   case PKT_REQUEST:
527     pMsg->BufferLength = (*Header)->request.alloc_hint;
528     break;
529   default:
530     pMsg->BufferLength = common_hdr.frag_len - hdr_length - RPC_AUTH_VERIFIER_LEN(&common_hdr);
531   }
532
533   TRACE("buffer length = %u\n", pMsg->BufferLength);
534
535   status = I_RpcGetBuffer(pMsg);
536   if (status != RPC_S_OK) goto fail;
537
538   first_flag = RPC_FLG_FIRST;
539   auth_length = common_hdr.auth_len;
540   if (auth_length) {
541     auth_data = HeapAlloc(GetProcessHeap(), 0, RPC_AUTH_VERIFIER_LEN(&common_hdr));
542     if (!auth_data) {
543       status = RPC_S_PROTOCOL_ERROR;
544       goto fail;
545     }
546   }
547   buffer_length = 0;
548   buffer_ptr = pMsg->Buffer;
549   while (buffer_length < pMsg->BufferLength)
550   {
551     unsigned int header_auth_len = RPC_AUTH_VERIFIER_LEN(&(*Header)->common);
552
553     /* verify header fields */
554
555     if (((*Header)->common.frag_len < hdr_length) ||
556         ((*Header)->common.frag_len - hdr_length < header_auth_len)) {
557       WARN("frag_len %d too small for hdr_length %ld and auth_len %d\n",
558         common_hdr.frag_len, hdr_length, common_hdr.auth_len);
559       status = RPC_S_PROTOCOL_ERROR;
560       goto fail;
561     }
562
563     if ((*Header)->common.auth_len != auth_length) {
564       WARN("auth_len header field changed from %ld to %d\n",
565         auth_length, (*Header)->common.auth_len);
566       status = RPC_S_PROTOCOL_ERROR;
567       goto fail;
568     }
569
570     data_length = (*Header)->common.frag_len - hdr_length - header_auth_len;
571     if (((*Header)->common.flags & RPC_FLG_FIRST) != first_flag ||
572         data_length + buffer_length > pMsg->BufferLength) {
573       TRACE("invalid packet flags or buffer length\n");
574       status = RPC_S_PROTOCOL_ERROR;
575       goto fail;
576     }
577
578     if (data_length == 0) dwRead = 0; else
579     dwRead = rpcrt4_conn_read(Connection, buffer_ptr, data_length);
580     if (dwRead != data_length) {
581       WARN("bad data length, %ld/%ld\n", dwRead, data_length);
582       status = RPC_S_PROTOCOL_ERROR;
583       goto fail;
584     }
585
586     if (header_auth_len) {
587       /* FIXME: we should accumulate authentication data for the bind,
588        * bind_ack, alter_context and alter_context_response if necessary.
589        * however, the details of how this is done is very sketchy in the
590        * DCE/RPC spec. for all other packet types that have authentication
591        * verifier data then it is just duplicated in all the fragments */
592       dwRead = rpcrt4_conn_read(Connection, auth_data, header_auth_len);
593       if (dwRead != header_auth_len) {
594         WARN("bad authentication data length, %ld/%d\n", dwRead,
595           header_auth_len);
596         status = RPC_S_PROTOCOL_ERROR;
597         goto fail;
598       }
599     }
600
601     /* when there is no more data left, it should be the last packet */
602     if (buffer_length == pMsg->BufferLength &&
603         ((*Header)->common.flags & RPC_FLG_LAST) == 0) {
604       WARN("no more data left, but not last packet\n");
605       status = RPC_S_PROTOCOL_ERROR;
606       goto fail;
607     }
608
609     buffer_length += data_length;
610     if (buffer_length < pMsg->BufferLength) {
611       TRACE("next header\n");
612
613       /* read the header of next packet */
614       dwRead = rpcrt4_conn_read(Connection, *Header, hdr_length);
615       if (dwRead != hdr_length) {
616         WARN("invalid packet header size (%ld)\n", dwRead);
617         status = RPC_S_PROTOCOL_ERROR;
618         goto fail;
619       }
620
621       buffer_ptr += data_length;
622       first_flag = 0;
623     }
624   }
625
626   /* respond to authorization request */
627   if (common_hdr.ptype == PKT_BIND_ACK && auth_length > sizeof(RpcAuthVerifier))
628   {
629     status = RPCRT_AuthorizeConnection(Connection,
630                                        auth_data + sizeof(RpcAuthVerifier),
631                                        auth_length);
632     if (status)
633         goto fail;
634   }
635
636   /* success */
637   status = RPC_S_OK;
638
639 fail:
640   if (status != RPC_S_OK) {
641     RPCRT4_FreeHeader(*Header);
642     *Header = NULL;
643   }
644   HeapFree(GetProcessHeap(), 0, auth_data);
645   return status;
646 }
647
648 /***********************************************************************
649  *           I_RpcGetBuffer [RPCRT4.@]
650  */
651 RPC_STATUS WINAPI I_RpcGetBuffer(PRPC_MESSAGE pMsg)
652 {
653   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
654   /* FIXME: pfnAllocate? */
655   pMsg->Buffer = HeapAlloc(GetProcessHeap(), 0, pMsg->BufferLength);
656
657   TRACE("Buffer=%p\n", pMsg->Buffer);
658   /* FIXME: which errors to return? */
659   return pMsg->Buffer ? S_OK : E_OUTOFMEMORY;
660 }
661
662 /***********************************************************************
663  *           I_RpcFreeBuffer [RPCRT4.@]
664  */
665 RPC_STATUS WINAPI I_RpcFreeBuffer(PRPC_MESSAGE pMsg)
666 {
667   TRACE("(%p) Buffer=%p\n", pMsg, pMsg->Buffer);
668   /* FIXME: pfnFree? */
669   HeapFree(GetProcessHeap(), 0, pMsg->Buffer);
670   pMsg->Buffer = NULL;
671   return S_OK;
672 }
673
674 /***********************************************************************
675  *           I_RpcSend [RPCRT4.@]
676  */
677 RPC_STATUS WINAPI I_RpcSend(PRPC_MESSAGE pMsg)
678 {
679   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
680   RpcConnection* conn;
681   RPC_CLIENT_INTERFACE* cif = NULL;
682   RPC_SERVER_INTERFACE* sif = NULL;
683   RPC_STATUS status;
684   RpcPktHdr *hdr;
685
686   TRACE("(%p)\n", pMsg);
687   if (!bind) return RPC_S_INVALID_BINDING;
688
689   if (bind->server) {
690     sif = pMsg->RpcInterfaceInformation;
691     if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
692     status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
693                                 &sif->InterfaceId);
694   } else {
695     cif = pMsg->RpcInterfaceInformation;
696     if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
697
698     if (!bind->Endpoint || !bind->Endpoint[0])
699     {
700       TRACE("automatically resolving partially bound binding\n");
701       status = RpcEpResolveBinding(bind, cif);
702       if (status != RPC_S_OK) return status;
703     }
704
705     status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
706                                 &cif->InterfaceId);
707   }
708
709   if (status != RPC_S_OK) return status;
710
711   if (bind->server) {
712     if (pMsg->RpcFlags & WINE_RPCFLAG_EXCEPTION) {
713       hdr = RPCRT4_BuildFaultHeader(pMsg->DataRepresentation,
714                                     RPC_S_CALL_FAILED);
715     } else {
716       hdr = RPCRT4_BuildResponseHeader(pMsg->DataRepresentation,
717                                        pMsg->BufferLength);
718     }
719   } else {
720     hdr = RPCRT4_BuildRequestHeader(pMsg->DataRepresentation,
721                                     pMsg->BufferLength, pMsg->ProcNum,
722                                     &bind->ObjectUuid);
723     hdr->common.call_id = conn->NextCallId++;
724   }
725
726   status = RPCRT4_Send(conn, hdr, pMsg->Buffer, pMsg->BufferLength);
727
728   RPCRT4_FreeHeader(hdr);
729
730   /* success */
731   if (!bind->server) {
732     /* save the connection, so the response can be read from it */
733     pMsg->ReservedForRuntime = conn;
734     return status;
735   }
736   RPCRT4_CloseBinding(bind, conn);
737
738   return status;
739 }
740
741 /***********************************************************************
742  *           I_RpcReceive [RPCRT4.@]
743  */
744 RPC_STATUS WINAPI I_RpcReceive(PRPC_MESSAGE pMsg)
745 {
746   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
747   RpcConnection* conn;
748   RPC_CLIENT_INTERFACE* cif = NULL;
749   RPC_SERVER_INTERFACE* sif = NULL;
750   RPC_STATUS status;
751   RpcPktHdr *hdr = NULL;
752
753   TRACE("(%p)\n", pMsg);
754   if (!bind) return RPC_S_INVALID_BINDING;
755
756   if (pMsg->ReservedForRuntime) {
757     conn = pMsg->ReservedForRuntime;
758     pMsg->ReservedForRuntime = NULL;
759   } else {
760     if (bind->server) {
761       sif = pMsg->RpcInterfaceInformation;
762       if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
763       status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
764                                   &sif->InterfaceId);
765     } else {
766       cif = pMsg->RpcInterfaceInformation;
767       if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
768
769       if (!bind->Endpoint || !bind->Endpoint[0])
770       {
771         TRACE("automatically resolving partially bound binding\n");
772         status = RpcEpResolveBinding(bind, cif);
773         if (status != RPC_S_OK) return status;
774       }
775
776       status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
777                                   &cif->InterfaceId);
778     }
779     if (status != RPC_S_OK) return status;
780   }
781
782   status = RPCRT4_Receive(conn, &hdr, pMsg);
783   if (status != RPC_S_OK) {
784     WARN("receive failed with error %lx\n", status);
785     goto fail;
786   }
787
788   status = RPC_S_PROTOCOL_ERROR;
789
790   switch (hdr->common.ptype) {
791   case PKT_RESPONSE:
792     if (bind->server) goto fail;
793     break;
794   case PKT_REQUEST:
795     if (!bind->server) goto fail;
796     break;
797   case PKT_FAULT:
798     pMsg->RpcFlags |= WINE_RPCFLAG_EXCEPTION;
799     ERR ("we got fault packet with status 0x%lx\n", hdr->fault.status);
800     status = hdr->fault.status; /* FIXME: do translation from nca error codes */
801     goto fail;
802   default:
803     WARN("bad packet type %d\n", hdr->common.ptype);
804     goto fail;
805   }
806
807   /* success */
808   status = RPC_S_OK;
809
810 fail:
811   RPCRT4_FreeHeader(hdr);
812   RPCRT4_CloseBinding(bind, conn);
813   return status;
814 }
815
816 /***********************************************************************
817  *           I_RpcSendReceive [RPCRT4.@]
818  */
819 RPC_STATUS WINAPI I_RpcSendReceive(PRPC_MESSAGE pMsg)
820 {
821   RPC_STATUS status;
822
823   TRACE("(%p)\n", pMsg);
824   status = I_RpcSend(pMsg);
825   if (status == RPC_S_OK)
826     status = I_RpcReceive(pMsg);
827   return status;
828 }