Add missing '\n's in traces.
[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 #define ROUND_UP(value, alignment) (((value) + ((alignment) - 1)) & ~((alignment)-1))
53
54 enum secure_packet_direction
55 {
56   SECURE_PACKET_SEND,
57   SECURE_PACKET_RECEIVE
58 };
59
60 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg);
61
62 static DWORD RPCRT4_GetHeaderSize(RpcPktHdr *Header)
63 {
64   static const DWORD header_sizes[] = {
65     sizeof(Header->request), 0, sizeof(Header->response),
66     sizeof(Header->fault), 0, 0, 0, 0, 0, 0, 0, sizeof(Header->bind),
67     sizeof(Header->bind_ack), sizeof(Header->bind_nack),
68     0, 0, 0, 0, 0
69   };
70   ULONG ret = 0;
71   
72   if (Header->common.ptype < sizeof(header_sizes) / sizeof(header_sizes[0])) {
73     ret = header_sizes[Header->common.ptype];
74     if (ret == 0)
75       FIXME("unhandled packet type\n");
76     if (Header->common.flags & RPC_FLG_OBJECT_UUID)
77       ret += sizeof(UUID);
78   } else {
79     TRACE("invalid packet type\n");
80   }
81
82   return ret;
83 }
84
85 static int packet_has_body(RpcPktHdr *Header)
86 {
87     return (Header->common.ptype == PKT_FAULT) ||
88            (Header->common.ptype == PKT_REQUEST) ||
89            (Header->common.ptype == PKT_RESPONSE);
90 }
91
92 static int packet_has_auth_verifier(RpcPktHdr *Header)
93 {
94     return !(Header->common.ptype == PKT_BIND_NACK) &&
95            !(Header->common.ptype == PKT_SHUTDOWN);
96 }
97
98 static VOID RPCRT4_BuildCommonHeader(RpcPktHdr *Header, unsigned char PacketType,
99                               unsigned long DataRepresentation)
100 {
101   Header->common.rpc_ver = RPC_VER_MAJOR;
102   Header->common.rpc_ver_minor = RPC_VER_MINOR;
103   Header->common.ptype = PacketType;
104   Header->common.drep[0] = LOBYTE(LOWORD(DataRepresentation));
105   Header->common.drep[1] = HIBYTE(LOWORD(DataRepresentation));
106   Header->common.drep[2] = LOBYTE(HIWORD(DataRepresentation));
107   Header->common.drep[3] = HIBYTE(HIWORD(DataRepresentation));
108   Header->common.auth_len = 0;
109   Header->common.call_id = 1;
110   Header->common.flags = 0;
111   /* Flags and fragment length are computed in RPCRT4_Send. */
112 }                              
113
114 static RpcPktHdr *RPCRT4_BuildRequestHeader(unsigned long DataRepresentation,
115                                      unsigned long BufferLength,
116                                      unsigned short ProcNum,
117                                      UUID *ObjectUuid)
118 {
119   RpcPktHdr *header;
120   BOOL has_object;
121   RPC_STATUS status;
122
123   has_object = (ObjectUuid != NULL && !UuidIsNil(ObjectUuid, &status));
124   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
125                      sizeof(header->request) + (has_object ? sizeof(UUID) : 0));
126   if (header == NULL) {
127     return NULL;
128   }
129
130   RPCRT4_BuildCommonHeader(header, PKT_REQUEST, DataRepresentation);
131   header->common.frag_len = sizeof(header->request);
132   header->request.alloc_hint = BufferLength;
133   header->request.context_id = 0;
134   header->request.opnum = ProcNum;
135   if (has_object) {
136     header->common.flags |= RPC_FLG_OBJECT_UUID;
137     header->common.frag_len += sizeof(UUID);
138     memcpy(&header->request + 1, ObjectUuid, sizeof(UUID));
139   }
140
141   return header;
142 }
143
144 static RpcPktHdr *RPCRT4_BuildResponseHeader(unsigned long DataRepresentation,
145                                       unsigned long BufferLength)
146 {
147   RpcPktHdr *header;
148
149   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->response));
150   if (header == NULL) {
151     return NULL;
152   }
153
154   RPCRT4_BuildCommonHeader(header, PKT_RESPONSE, DataRepresentation);
155   header->common.frag_len = sizeof(header->response);
156   header->response.alloc_hint = BufferLength;
157
158   return header;
159 }
160
161 RpcPktHdr *RPCRT4_BuildFaultHeader(unsigned long DataRepresentation,
162                                    RPC_STATUS Status)
163 {
164   RpcPktHdr *header;
165
166   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->fault));
167   if (header == NULL) {
168     return NULL;
169   }
170
171   RPCRT4_BuildCommonHeader(header, PKT_FAULT, DataRepresentation);
172   header->common.frag_len = sizeof(header->fault);
173   header->fault.status = Status;
174
175   return header;
176 }
177
178 RpcPktHdr *RPCRT4_BuildBindHeader(unsigned long DataRepresentation,
179                                   unsigned short MaxTransmissionSize,
180                                   unsigned short MaxReceiveSize,
181                                   RPC_SYNTAX_IDENTIFIER *AbstractId,
182                                   RPC_SYNTAX_IDENTIFIER *TransferId)
183 {
184   RpcPktHdr *header;
185
186   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind));
187   if (header == NULL) {
188     return NULL;
189   }
190
191   RPCRT4_BuildCommonHeader(header, PKT_BIND, DataRepresentation);
192   header->common.frag_len = sizeof(header->bind);
193   header->bind.max_tsize = MaxTransmissionSize;
194   header->bind.max_rsize = MaxReceiveSize;
195   header->bind.num_elements = 1;
196   header->bind.num_syntaxes = 1;
197   memcpy(&header->bind.abstract, AbstractId, sizeof(RPC_SYNTAX_IDENTIFIER));
198   memcpy(&header->bind.transfer, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
199
200   return header;
201 }
202
203 static RpcPktHdr *RPCRT4_BuildAuthHeader(unsigned long DataRepresentation)
204 {
205   RpcPktHdr *header;
206
207   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
208                      sizeof(header->common) + 12);
209   if (header == NULL)
210     return NULL;
211
212   RPCRT4_BuildCommonHeader(header, PKT_AUTH3, DataRepresentation);
213   header->common.frag_len = 0x14;
214   header->common.auth_len = 0;
215
216   return header;
217 }
218
219 RpcPktHdr *RPCRT4_BuildBindNackHeader(unsigned long DataRepresentation,
220                                       unsigned char RpcVersion,
221                                       unsigned char RpcVersionMinor)
222 {
223   RpcPktHdr *header;
224
225   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind_nack));
226   if (header == NULL) {
227     return NULL;
228   }
229
230   RPCRT4_BuildCommonHeader(header, PKT_BIND_NACK, DataRepresentation);
231   header->common.frag_len = sizeof(header->bind_nack);
232   header->bind_nack.protocols_count = 1;
233   header->bind_nack.protocols[0].rpc_ver = RpcVersion;
234   header->bind_nack.protocols[0].rpc_ver_minor = RpcVersionMinor;
235
236   return header;
237 }
238
239 RpcPktHdr *RPCRT4_BuildBindAckHeader(unsigned long DataRepresentation,
240                                      unsigned short MaxTransmissionSize,
241                                      unsigned short MaxReceiveSize,
242                                      LPSTR ServerAddress,
243                                      unsigned long Result,
244                                      unsigned long Reason,
245                                      RPC_SYNTAX_IDENTIFIER *TransferId)
246 {
247   RpcPktHdr *header;
248   unsigned long header_size;
249   RpcAddressString *server_address;
250   RpcResults *results;
251   RPC_SYNTAX_IDENTIFIER *transfer_id;
252
253   header_size = sizeof(header->bind_ack) +
254                 ROUND_UP(FIELD_OFFSET(RpcAddressString, string[strlen(ServerAddress) + 1]), 4) +
255                 sizeof(RpcResults) +
256                 sizeof(RPC_SYNTAX_IDENTIFIER);
257
258   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, header_size);
259   if (header == NULL) {
260     return NULL;
261   }
262
263   RPCRT4_BuildCommonHeader(header, PKT_BIND_ACK, DataRepresentation);
264   header->common.frag_len = header_size;
265   header->bind_ack.max_tsize = MaxTransmissionSize;
266   header->bind_ack.max_rsize = MaxReceiveSize;
267   server_address = (RpcAddressString*)(&header->bind_ack + 1);
268   server_address->length = strlen(ServerAddress) + 1;
269   strcpy(server_address->string, ServerAddress);
270   /* results is 4-byte aligned */
271   results = (RpcResults*)((ULONG_PTR)server_address + ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4));
272   results->num_results = 1;
273   results->results[0].result = Result;
274   results->results[0].reason = Reason;
275   transfer_id = (RPC_SYNTAX_IDENTIFIER*)(results + 1);
276   memcpy(transfer_id, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
277
278   return header;
279 }
280
281 VOID RPCRT4_FreeHeader(RpcPktHdr *Header)
282 {
283   HeapFree(GetProcessHeap(), 0, Header);
284 }
285
286 static RPC_STATUS RPCRT4_SecurePacket(RpcConnection *Connection,
287     enum secure_packet_direction dir,
288     RpcPktHdr *hdr, unsigned int hdr_size,
289     unsigned char *stub_data, unsigned int stub_data_size,
290     RpcAuthVerifier *auth_hdr,
291     unsigned char *auth_value, unsigned int auth_value_size)
292 {
293     SecBufferDesc message;
294     SecBuffer buffers[4];
295     SECURITY_STATUS sec_status;
296
297     message.ulVersion = SECBUFFER_VERSION;
298     message.cBuffers = sizeof(buffers)/sizeof(buffers[0]);
299     message.pBuffers = buffers;
300
301     buffers[0].cbBuffer = hdr_size;
302     buffers[0].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
303     buffers[0].pvBuffer = hdr;
304     buffers[1].cbBuffer = stub_data_size;
305     buffers[1].BufferType = SECBUFFER_DATA;
306     buffers[1].pvBuffer = stub_data;
307     buffers[2].cbBuffer = sizeof(*auth_hdr);
308     buffers[2].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
309     buffers[2].pvBuffer = auth_hdr;
310     buffers[3].cbBuffer = auth_value_size;
311     buffers[3].BufferType = SECBUFFER_TOKEN;
312     buffers[3].pvBuffer = auth_value;
313
314     if (dir == SECURE_PACKET_SEND)
315     {
316         if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
317         {
318             sec_status = EncryptMessage(&Connection->ctx, 0, &message, 0 /* FIXME */);
319             if (sec_status != SEC_E_OK)
320             {
321                 ERR("EncryptMessage failed with 0x%08x\n", sec_status);
322                 return RPC_S_SEC_PKG_ERROR;
323             }
324         }
325         else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
326         {
327             sec_status = MakeSignature(&Connection->ctx, 0, &message, 0 /* FIXME */);
328             if (sec_status != SEC_E_OK)
329             {
330                 ERR("MakeSignature failed with 0x%08x\n", sec_status);
331                 return RPC_S_SEC_PKG_ERROR;
332             }
333         }
334     }
335     else if (dir == SECURE_PACKET_RECEIVE)
336     {
337         if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
338         {
339             sec_status = DecryptMessage(&Connection->ctx, &message, 0 /* FIXME */, 0);
340             if (sec_status != SEC_E_OK)
341             {
342                 ERR("EncryptMessage failed with 0x%08x\n", sec_status);
343                 return RPC_S_SEC_PKG_ERROR;
344             }
345         }
346         else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
347         {
348             sec_status = VerifySignature(&Connection->ctx, &message, 0 /* FIXME */, NULL);
349             if (sec_status != SEC_E_OK)
350             {
351                 ERR("VerifySignature failed with 0x%08x\n", sec_status);
352                 return RPC_S_SEC_PKG_ERROR;
353             }
354         }
355     }
356
357     return RPC_S_OK;
358 }
359          
360 /***********************************************************************
361  *           RPCRT4_SendAuth (internal)
362  * 
363  * Transmit a packet with authorization data over connection in acceptable fragments.
364  */
365 static RPC_STATUS RPCRT4_SendAuth(RpcConnection *Connection, RpcPktHdr *Header,
366                                   void *Buffer, unsigned int BufferLength,
367                                   void *Auth, unsigned int AuthLength)
368 {
369   PUCHAR buffer_pos;
370   DWORD hdr_size;
371   LONG count;
372   unsigned char *pkt;
373   LONG alen;
374   RPC_STATUS status;
375
376   buffer_pos = Buffer;
377   /* The packet building functions save the packet header size, so we can use it. */
378   hdr_size = Header->common.frag_len;
379   if (AuthLength)
380     Header->common.auth_len = AuthLength;
381   else if (Connection->AuthInfo && packet_has_auth_verifier(Header))
382     Header->common.auth_len = 16 /* FIXME */;
383   else
384     Header->common.auth_len = 0;
385   Header->common.flags |= RPC_FLG_FIRST;
386   Header->common.flags &= ~RPC_FLG_LAST;
387
388   alen = RPC_AUTH_VERIFIER_LEN(&Header->common);
389
390   while (!(Header->common.flags & RPC_FLG_LAST)) {
391     unsigned char auth_pad_len = Header->common.auth_len ? ROUND_UP_AMOUNT(BufferLength, AUTH_ALIGNMENT) : 0;
392     unsigned int pkt_size = BufferLength + hdr_size + alen + auth_pad_len;
393
394     /* decide if we need to split the packet into fragments */
395    if (pkt_size <= Connection->MaxTransmissionSize) {
396      Header->common.flags |= RPC_FLG_LAST;
397      Header->common.frag_len = pkt_size;
398     } else {
399       auth_pad_len = 0;
400       /* make sure packet payload will be a multiple of 16 */
401       Header->common.frag_len =
402         ((Connection->MaxTransmissionSize - hdr_size - alen) & ~(AUTH_ALIGNMENT-1)) +
403         hdr_size + alen;
404     }
405
406     pkt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Header->common.frag_len);
407
408     memcpy(pkt, Header, hdr_size);
409
410     /* fragment consisted of header only and is the last one */
411     if (hdr_size == Header->common.frag_len)
412       goto write;
413
414     memcpy(pkt + hdr_size, buffer_pos, Header->common.frag_len - hdr_size - auth_pad_len - alen);
415
416     /* add the authorization info */
417     if (Connection->AuthInfo && packet_has_auth_verifier(Header))
418     {
419       RpcAuthVerifier *auth_hdr = (RpcAuthVerifier *)&pkt[Header->common.frag_len - alen];
420
421       auth_hdr->auth_type = Connection->AuthInfo->AuthnSvc;
422       auth_hdr->auth_level = Connection->AuthInfo->AuthnLevel;
423       auth_hdr->auth_pad_length = auth_pad_len;
424       auth_hdr->auth_reserved = 0;
425       /* a unique number... */
426       auth_hdr->auth_context_id = (unsigned long)Connection;
427
428       if (AuthLength)
429         memcpy(auth_hdr + 1, Auth, AuthLength);
430       else
431       {
432         status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_SEND,
433             (RpcPktHdr *)pkt, hdr_size,
434             pkt + hdr_size, Header->common.frag_len - hdr_size - alen,
435             auth_hdr,
436             (unsigned char *)(auth_hdr + 1), Header->common.auth_len);
437         if (status != RPC_S_OK)
438         {
439           HeapFree(GetProcessHeap(), 0, pkt);
440           return status;
441         }
442       }
443     }
444
445 write:
446     count = rpcrt4_conn_write(Connection, pkt, Header->common.frag_len);
447     HeapFree(GetProcessHeap(), 0, pkt);
448     if (count<0) {
449       WARN("rpcrt4_conn_write failed (auth)\n");
450       return RPC_S_PROTOCOL_ERROR;
451     }
452
453     buffer_pos += Header->common.frag_len - hdr_size - alen - auth_pad_len;
454     BufferLength -= Header->common.frag_len - hdr_size - alen - auth_pad_len;
455     Header->common.flags &= ~RPC_FLG_FIRST;
456   }
457
458   return RPC_S_OK;
459 }
460
461 /***********************************************************************
462  *           RPCRT4_AuthNegotiate (internal)
463  */
464 static void RPCRT4_AuthNegotiate(RpcConnection *conn, SecBuffer *out)
465 {
466   SECURITY_STATUS r;
467   SecBufferDesc out_desc;
468   unsigned char *buffer;
469   ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
470                       ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
471
472   if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
473     context_req |= ISC_REQ_INTEGRITY;
474   else if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY)
475     context_req |= ISC_REQ_CONFIDENTIALITY | ISC_REQ_INTEGRITY;
476
477   buffer = HeapAlloc(GetProcessHeap(), 0, 0x100);
478
479   out->BufferType = SECBUFFER_TOKEN;
480   out->cbBuffer = 0x100;
481   out->pvBuffer = buffer;
482
483   out_desc.ulVersion = 0;
484   out_desc.cBuffers = 1;
485   out_desc.pBuffers = out;
486
487   conn->attr = 0;
488   SecInvalidateHandle(&conn->ctx);
489
490   r = InitializeSecurityContextA(&conn->AuthInfo->cred, NULL, NULL,
491         context_req, 0, SECURITY_NETWORK_DREP,
492         NULL, 0, &conn->ctx, &out_desc, &conn->attr, &conn->exp);
493
494   TRACE("r = %08x cbBuffer = %ld attr = %08x\n", r, out->cbBuffer, conn->attr);
495 }
496
497 /***********************************************************************
498  *           RPCRT4_AuthorizeBinding (internal)
499  */
500 static RPC_STATUS RPCRT_AuthorizeConnection(RpcConnection* conn,
501                                             BYTE *challenge, ULONG count)
502 {
503   SecBufferDesc inp_desc, out_desc;
504   SecBuffer inp, out;
505   SECURITY_STATUS r;
506   unsigned char buffer[0x100];
507   RpcPktHdr *resp_hdr;
508   RPC_STATUS status;
509   ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
510                       ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
511
512   TRACE("challenge %s, %d bytes\n", challenge, count);
513
514   if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
515     context_req |= ISC_REQ_INTEGRITY;
516   else if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY)
517     context_req |= ISC_REQ_CONFIDENTIALITY | ISC_REQ_INTEGRITY;
518
519   out.BufferType = SECBUFFER_TOKEN;
520   out.cbBuffer = sizeof buffer;
521   out.pvBuffer = buffer;
522
523   out_desc.ulVersion = 0;
524   out_desc.cBuffers = 1;
525   out_desc.pBuffers = &out;
526
527   inp.BufferType = SECBUFFER_TOKEN;
528   inp.pvBuffer = challenge;
529   inp.cbBuffer = count;
530
531   inp_desc.cBuffers = 1;
532   inp_desc.pBuffers = &inp;
533   inp_desc.ulVersion = 0;
534
535   r = InitializeSecurityContextA(&conn->AuthInfo->cred, &conn->ctx, NULL,
536         context_req, 0, SECURITY_NETWORK_DREP,
537         &inp_desc, 0, &conn->ctx, &out_desc, &conn->attr, &conn->exp);
538   if (r)
539   {
540     WARN("InitializeSecurityContext failed with error 0x%08x\n", r);
541     return ERROR_ACCESS_DENIED;
542   }
543
544   resp_hdr = RPCRT4_BuildAuthHeader(NDR_LOCAL_DATA_REPRESENTATION);
545   if (!resp_hdr)
546     return E_OUTOFMEMORY;
547
548   status = RPCRT4_SendAuth(conn, resp_hdr, NULL, 0, out.pvBuffer, out.cbBuffer);
549
550   RPCRT4_FreeHeader(resp_hdr);
551
552   return status;
553 }
554
555 /***********************************************************************
556  *           RPCRT4_Send (internal)
557  * 
558  * Transmit a packet over connection in acceptable fragments.
559  */
560 RPC_STATUS RPCRT4_Send(RpcConnection *Connection, RpcPktHdr *Header,
561                        void *Buffer, unsigned int BufferLength)
562 {
563   RPC_STATUS r;
564   SecBuffer out;
565
566   if (!Connection->AuthInfo || SecIsValidHandle(&Connection->ctx))
567   {
568     return RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, NULL, 0);
569   }
570
571   out.BufferType = SECBUFFER_TOKEN;
572   out.cbBuffer = 0;
573   out.pvBuffer = NULL;
574
575   /* tack on a negotiate packet */
576   RPCRT4_AuthNegotiate(Connection, &out);
577   r = RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, out.pvBuffer, out.cbBuffer);
578   HeapFree(GetProcessHeap(), 0, out.pvBuffer);
579
580   return r;
581 }
582
583 /***********************************************************************
584  *           RPCRT4_Receive (internal)
585  * 
586  * Receive a packet from connection and merge the fragments.
587  */
588 RPC_STATUS RPCRT4_Receive(RpcConnection *Connection, RpcPktHdr **Header,
589                           PRPC_MESSAGE pMsg)
590 {
591   RPC_STATUS status;
592   DWORD hdr_length;
593   LONG dwRead;
594   unsigned short first_flag;
595   unsigned long data_length;
596   unsigned long buffer_length;
597   unsigned long auth_length;
598   unsigned char *auth_data = NULL;
599   RpcPktCommonHdr common_hdr;
600
601   *Header = NULL;
602
603   TRACE("(%p, %p, %p)\n", Connection, Header, pMsg);
604
605   /* read packet common header */
606   dwRead = rpcrt4_conn_read(Connection, &common_hdr, sizeof(common_hdr));
607   if (dwRead != sizeof(common_hdr)) {
608     WARN("Short read of header, %d bytes\n", dwRead);
609     status = RPC_S_PROTOCOL_ERROR;
610     goto fail;
611   }
612
613   /* verify if the header really makes sense */
614   if (common_hdr.rpc_ver != RPC_VER_MAJOR ||
615       common_hdr.rpc_ver_minor != RPC_VER_MINOR) {
616     WARN("unhandled packet version\n");
617     status = RPC_S_PROTOCOL_ERROR;
618     goto fail;
619   }
620
621   hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
622   if (hdr_length == 0) {
623     WARN("header length == 0\n");
624     status = RPC_S_PROTOCOL_ERROR;
625     goto fail;
626   }
627
628   *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
629   memcpy(*Header, &common_hdr, sizeof(common_hdr));
630
631   /* read the rest of packet header */
632   dwRead = rpcrt4_conn_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
633   if (dwRead != hdr_length - sizeof(common_hdr)) {
634     WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
635     status = RPC_S_PROTOCOL_ERROR;
636     goto fail;
637   }
638
639   /* read packet body */
640   switch (common_hdr.ptype) {
641   case PKT_RESPONSE:
642     pMsg->BufferLength = (*Header)->response.alloc_hint;
643     break;
644   case PKT_REQUEST:
645     pMsg->BufferLength = (*Header)->request.alloc_hint;
646     break;
647   default:
648     pMsg->BufferLength = common_hdr.frag_len - hdr_length - RPC_AUTH_VERIFIER_LEN(&common_hdr);
649   }
650
651   TRACE("buffer length = %u\n", pMsg->BufferLength);
652
653   status = I_RpcGetBuffer(pMsg);
654   if (status != RPC_S_OK) goto fail;
655
656   first_flag = RPC_FLG_FIRST;
657   auth_length = common_hdr.auth_len;
658   if (auth_length) {
659     auth_data = HeapAlloc(GetProcessHeap(), 0, RPC_AUTH_VERIFIER_LEN(&common_hdr));
660     if (!auth_data) {
661       status = RPC_S_PROTOCOL_ERROR;
662       goto fail;
663     }
664   }
665   buffer_length = 0;
666   while (TRUE)
667   {
668     unsigned int header_auth_len = RPC_AUTH_VERIFIER_LEN(&(*Header)->common);
669
670     /* verify header fields */
671
672     if (((*Header)->common.frag_len < hdr_length) ||
673         ((*Header)->common.frag_len - hdr_length < header_auth_len)) {
674       WARN("frag_len %d too small for hdr_length %d and auth_len %d\n",
675         common_hdr.frag_len, hdr_length, common_hdr.auth_len);
676       status = RPC_S_PROTOCOL_ERROR;
677       goto fail;
678     }
679
680     if ((*Header)->common.auth_len != auth_length) {
681       WARN("auth_len header field changed from %ld to %d\n",
682         auth_length, (*Header)->common.auth_len);
683       status = RPC_S_PROTOCOL_ERROR;
684       goto fail;
685     }
686
687     if (((*Header)->common.flags & RPC_FLG_FIRST) != first_flag) {
688       TRACE("invalid packet flags\n");
689       status = RPC_S_PROTOCOL_ERROR;
690       goto fail;
691     }
692
693     data_length = (*Header)->common.frag_len - hdr_length - header_auth_len;
694     if (data_length + buffer_length > pMsg->BufferLength) {
695       TRACE("allocation hint exceeded, new buffer length = %ld\n",
696         data_length + buffer_length);
697       pMsg->BufferLength = data_length + buffer_length;
698       status = I_RpcReAllocateBuffer(pMsg);
699       if (status != RPC_S_OK) goto fail;
700     }
701
702     if (data_length == 0) dwRead = 0; else
703     dwRead = rpcrt4_conn_read(Connection,
704         (unsigned char *)pMsg->Buffer + buffer_length, data_length);
705     if (dwRead != data_length) {
706       WARN("bad data length, %d/%ld\n", dwRead, data_length);
707       status = RPC_S_PROTOCOL_ERROR;
708       goto fail;
709     }
710
711     if (header_auth_len) {
712       if (header_auth_len < sizeof(RpcAuthVerifier)) {
713         WARN("bad auth verifier length %d\n", header_auth_len);
714         status = RPC_S_PROTOCOL_ERROR;
715         goto fail;
716       }
717
718       /* FIXME: we should accumulate authentication data for the bind,
719        * bind_ack, alter_context and alter_context_response if necessary.
720        * however, the details of how this is done is very sketchy in the
721        * DCE/RPC spec. for all other packet types that have authentication
722        * verifier data then it is just duplicated in all the fragments */
723       dwRead = rpcrt4_conn_read(Connection, auth_data, header_auth_len);
724       if (dwRead != header_auth_len) {
725         WARN("bad authentication data length, %d/%d\n", dwRead,
726           header_auth_len);
727         status = RPC_S_PROTOCOL_ERROR;
728         goto fail;
729       }
730
731       /* these packets are handled specially, not by the generic SecurePacket
732        * function */
733       if ((common_hdr.ptype != PKT_BIND) &&
734           (common_hdr.ptype != PKT_BIND_ACK) &&
735           (common_hdr.ptype != PKT_AUTH3))
736         status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_RECEIVE,
737             *Header, hdr_length,
738             (unsigned char *)pMsg->Buffer + buffer_length, data_length,
739             (RpcAuthVerifier *)auth_data,
740             (unsigned char *)auth_data + sizeof(RpcAuthVerifier),
741             header_auth_len - sizeof(RpcAuthVerifier));
742     }
743
744     buffer_length += data_length;
745     if (!((*Header)->common.flags & RPC_FLG_LAST)) {
746       TRACE("next header\n");
747
748       /* read the header of next packet */
749       dwRead = rpcrt4_conn_read(Connection, *Header, hdr_length);
750       if (dwRead != hdr_length) {
751         WARN("invalid packet header size (%d)\n", dwRead);
752         status = RPC_S_PROTOCOL_ERROR;
753         goto fail;
754       }
755
756       first_flag = 0;
757     } else {
758       break;
759     }
760   }
761   pMsg->BufferLength = buffer_length;
762
763   /* respond to authorization request */
764   if (common_hdr.ptype == PKT_BIND_ACK && auth_length > sizeof(RpcAuthVerifier))
765   {
766     status = RPCRT_AuthorizeConnection(Connection,
767                                        auth_data + sizeof(RpcAuthVerifier),
768                                        auth_length);
769     if (status)
770         goto fail;
771   }
772
773   /* success */
774   status = RPC_S_OK;
775
776 fail:
777   if (status != RPC_S_OK) {
778     RPCRT4_FreeHeader(*Header);
779     *Header = NULL;
780   }
781   HeapFree(GetProcessHeap(), 0, auth_data);
782   return status;
783 }
784
785 /***********************************************************************
786  *           I_RpcGetBuffer [RPCRT4.@]
787  */
788 RPC_STATUS WINAPI I_RpcGetBuffer(PRPC_MESSAGE pMsg)
789 {
790   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
791   /* FIXME: pfnAllocate? */
792   pMsg->Buffer = HeapAlloc(GetProcessHeap(), 0, pMsg->BufferLength);
793
794   TRACE("Buffer=%p\n", pMsg->Buffer);
795   /* FIXME: which errors to return? */
796   return pMsg->Buffer ? S_OK : E_OUTOFMEMORY;
797 }
798
799 /***********************************************************************
800  *           I_RpcReAllocateBuffer (internal)
801  */
802 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg)
803 {
804   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
805   pMsg->Buffer = HeapReAlloc(GetProcessHeap(), 0, pMsg->Buffer, pMsg->BufferLength);
806
807   TRACE("Buffer=%p\n", pMsg->Buffer);
808   return pMsg->Buffer ? RPC_S_OK : RPC_S_OUT_OF_RESOURCES;
809 }
810
811 /***********************************************************************
812  *           I_RpcFreeBuffer [RPCRT4.@]
813  */
814 RPC_STATUS WINAPI I_RpcFreeBuffer(PRPC_MESSAGE pMsg)
815 {
816   TRACE("(%p) Buffer=%p\n", pMsg, pMsg->Buffer);
817   /* FIXME: pfnFree? */
818   HeapFree(GetProcessHeap(), 0, pMsg->Buffer);
819   pMsg->Buffer = NULL;
820   return S_OK;
821 }
822
823 /***********************************************************************
824  *           I_RpcSend [RPCRT4.@]
825  */
826 RPC_STATUS WINAPI I_RpcSend(PRPC_MESSAGE pMsg)
827 {
828   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
829   RpcConnection* conn;
830   RPC_CLIENT_INTERFACE* cif = NULL;
831   RPC_SERVER_INTERFACE* sif = NULL;
832   RPC_STATUS status;
833   RpcPktHdr *hdr;
834
835   TRACE("(%p)\n", pMsg);
836   if (!bind) return RPC_S_INVALID_BINDING;
837
838   if (bind->server) {
839     sif = pMsg->RpcInterfaceInformation;
840     if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
841     status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
842                                 &sif->InterfaceId);
843   } else {
844     cif = pMsg->RpcInterfaceInformation;
845     if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
846
847     if (!bind->Endpoint || !bind->Endpoint[0])
848     {
849       TRACE("automatically resolving partially bound binding\n");
850       status = RpcEpResolveBinding(bind, cif);
851       if (status != RPC_S_OK) return status;
852     }
853
854     status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
855                                 &cif->InterfaceId);
856   }
857
858   if (status != RPC_S_OK) return status;
859
860   if (bind->server) {
861     if (pMsg->RpcFlags & WINE_RPCFLAG_EXCEPTION) {
862       hdr = RPCRT4_BuildFaultHeader(pMsg->DataRepresentation,
863                                     RPC_S_CALL_FAILED);
864     } else {
865       hdr = RPCRT4_BuildResponseHeader(pMsg->DataRepresentation,
866                                        pMsg->BufferLength);
867     }
868   } else {
869     hdr = RPCRT4_BuildRequestHeader(pMsg->DataRepresentation,
870                                     pMsg->BufferLength, pMsg->ProcNum,
871                                     &bind->ObjectUuid);
872     hdr->common.call_id = conn->NextCallId++;
873   }
874
875   status = RPCRT4_Send(conn, hdr, pMsg->Buffer, pMsg->BufferLength);
876
877   RPCRT4_FreeHeader(hdr);
878
879   /* success */
880   if (!bind->server) {
881     /* save the connection, so the response can be read from it */
882     pMsg->ReservedForRuntime = conn;
883     return status;
884   }
885   RPCRT4_CloseBinding(bind, conn);
886
887   return status;
888 }
889
890 /***********************************************************************
891  *           I_RpcReceive [RPCRT4.@]
892  */
893 RPC_STATUS WINAPI I_RpcReceive(PRPC_MESSAGE pMsg)
894 {
895   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
896   RpcConnection* conn;
897   RPC_CLIENT_INTERFACE* cif = NULL;
898   RPC_SERVER_INTERFACE* sif = NULL;
899   RPC_STATUS status;
900   RpcPktHdr *hdr = NULL;
901
902   TRACE("(%p)\n", pMsg);
903   if (!bind) return RPC_S_INVALID_BINDING;
904
905   if (pMsg->ReservedForRuntime) {
906     conn = pMsg->ReservedForRuntime;
907     pMsg->ReservedForRuntime = NULL;
908   } else {
909     if (bind->server) {
910       sif = pMsg->RpcInterfaceInformation;
911       if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
912       status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
913                                   &sif->InterfaceId);
914     } else {
915       cif = pMsg->RpcInterfaceInformation;
916       if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
917
918       if (!bind->Endpoint || !bind->Endpoint[0])
919       {
920         TRACE("automatically resolving partially bound binding\n");
921         status = RpcEpResolveBinding(bind, cif);
922         if (status != RPC_S_OK) return status;
923       }
924
925       status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
926                                   &cif->InterfaceId);
927     }
928     if (status != RPC_S_OK) return status;
929   }
930
931   status = RPCRT4_Receive(conn, &hdr, pMsg);
932   if (status != RPC_S_OK) {
933     WARN("receive failed with error %lx\n", status);
934     goto fail;
935   }
936
937   status = RPC_S_PROTOCOL_ERROR;
938
939   switch (hdr->common.ptype) {
940   case PKT_RESPONSE:
941     if (bind->server) goto fail;
942     break;
943   case PKT_REQUEST:
944     if (!bind->server) goto fail;
945     break;
946   case PKT_FAULT:
947     pMsg->RpcFlags |= WINE_RPCFLAG_EXCEPTION;
948     ERR ("we got fault packet with status 0x%lx\n", hdr->fault.status);
949     status = hdr->fault.status; /* FIXME: do translation from nca error codes */
950     goto fail;
951   default:
952     WARN("bad packet type %d\n", hdr->common.ptype);
953     goto fail;
954   }
955
956   /* success */
957   status = RPC_S_OK;
958
959 fail:
960   RPCRT4_FreeHeader(hdr);
961   RPCRT4_CloseBinding(bind, conn);
962   return status;
963 }
964
965 /***********************************************************************
966  *           I_RpcSendReceive [RPCRT4.@]
967  */
968 RPC_STATUS WINAPI I_RpcSendReceive(PRPC_MESSAGE pMsg)
969 {
970   RPC_STATUS status;
971
972   TRACE("(%p)\n", pMsg);
973   status = I_RpcSend(pMsg);
974   if (status == RPC_S_OK)
975     status = I_RpcReceive(pMsg);
976   return status;
977 }