rpcrt4: Add support for signing, verifying, encrypting and decrypting RPC 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 #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 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   conn->ctx.dwLower = 0;
489   conn->ctx.dwUpper = 0;
490
491   r = InitializeSecurityContextA(&conn->AuthInfo->cred, NULL, NULL,
492         context_req, 0, SECURITY_NETWORK_DREP,
493         NULL, 0, &conn->ctx, &out_desc, &conn->attr, &conn->exp);
494
495   TRACE("r = %08x cbBuffer = %ld attr = %08x\n", r, out->cbBuffer, conn->attr);
496 }
497
498 /***********************************************************************
499  *           RPCRT4_AuthorizeBinding (internal)
500  */
501 static RPC_STATUS RPCRT_AuthorizeConnection(RpcConnection* conn,
502                                             BYTE *challenge, ULONG count)
503 {
504   SecBufferDesc inp_desc, out_desc;
505   SecBuffer inp, out;
506   SECURITY_STATUS r;
507   unsigned char buffer[0x100];
508   RpcPktHdr *resp_hdr;
509   RPC_STATUS status;
510   ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
511                       ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
512
513   TRACE("challenge %s, %d bytes\n", challenge, count);
514
515   if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
516     context_req |= ISC_REQ_INTEGRITY;
517   else if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY)
518     context_req |= ISC_REQ_CONFIDENTIALITY | ISC_REQ_INTEGRITY;
519
520   out.BufferType = SECBUFFER_TOKEN;
521   out.cbBuffer = sizeof buffer;
522   out.pvBuffer = buffer;
523
524   out_desc.ulVersion = 0;
525   out_desc.cBuffers = 1;
526   out_desc.pBuffers = &out;
527
528   inp.BufferType = SECBUFFER_TOKEN;
529   inp.pvBuffer = challenge;
530   inp.cbBuffer = count;
531
532   inp_desc.cBuffers = 1;
533   inp_desc.pBuffers = &inp;
534   inp_desc.ulVersion = 0;
535
536   r = InitializeSecurityContextA(&conn->AuthInfo->cred, &conn->ctx, NULL,
537         context_req, 0, SECURITY_NETWORK_DREP,
538         &inp_desc, 0, &conn->ctx, &out_desc, &conn->attr, &conn->exp);
539   if (r)
540   {
541     WARN("InitializeSecurityContext failed with error 0x%08x\n", r);
542     return ERROR_ACCESS_DENIED;
543   }
544
545   resp_hdr = RPCRT4_BuildAuthHeader(NDR_LOCAL_DATA_REPRESENTATION);
546   if (!resp_hdr)
547     return E_OUTOFMEMORY;
548
549   status = RPCRT4_SendAuth(conn, resp_hdr, NULL, 0, out.pvBuffer, out.cbBuffer);
550
551   RPCRT4_FreeHeader(resp_hdr);
552
553   return status;
554 }
555
556 /***********************************************************************
557  *           RPCRT4_Send (internal)
558  * 
559  * Transmit a packet over connection in acceptable fragments.
560  */
561 RPC_STATUS RPCRT4_Send(RpcConnection *Connection, RpcPktHdr *Header,
562                        void *Buffer, unsigned int BufferLength)
563 {
564   RPC_STATUS r;
565   SecBuffer out;
566
567   if (!Connection->AuthInfo ||
568       Connection->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_DEFAULT ||
569       Connection->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_NONE ||
570       (Connection->ctx.dwUpper || Connection->ctx.dwLower))
571   {
572     return RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, NULL, 0);
573   }
574
575   out.BufferType = SECBUFFER_TOKEN;
576   out.cbBuffer = 0;
577   out.pvBuffer = NULL;
578
579   /* tack on a negotiate packet */
580   RPCRT4_AuthNegotiate(Connection, &out);
581   r = RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, out.pvBuffer, out.cbBuffer);
582   HeapFree(GetProcessHeap(), 0, out.pvBuffer);
583
584   return r;
585 }
586
587 /***********************************************************************
588  *           RPCRT4_Receive (internal)
589  * 
590  * Receive a packet from connection and merge the fragments.
591  */
592 RPC_STATUS RPCRT4_Receive(RpcConnection *Connection, RpcPktHdr **Header,
593                           PRPC_MESSAGE pMsg)
594 {
595   RPC_STATUS status;
596   DWORD hdr_length;
597   LONG dwRead;
598   unsigned short first_flag;
599   unsigned long data_length;
600   unsigned long buffer_length;
601   unsigned long auth_length;
602   unsigned char *auth_data = NULL;
603   RpcPktCommonHdr common_hdr;
604
605   *Header = NULL;
606
607   TRACE("(%p, %p, %p)\n", Connection, Header, pMsg);
608
609   /* read packet common header */
610   dwRead = rpcrt4_conn_read(Connection, &common_hdr, sizeof(common_hdr));
611   if (dwRead != sizeof(common_hdr)) {
612     WARN("Short read of header, %d bytes\n", dwRead);
613     status = RPC_S_PROTOCOL_ERROR;
614     goto fail;
615   }
616
617   /* verify if the header really makes sense */
618   if (common_hdr.rpc_ver != RPC_VER_MAJOR ||
619       common_hdr.rpc_ver_minor != RPC_VER_MINOR) {
620     WARN("unhandled packet version\n");
621     status = RPC_S_PROTOCOL_ERROR;
622     goto fail;
623   }
624
625   hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
626   if (hdr_length == 0) {
627     WARN("header length == 0\n");
628     status = RPC_S_PROTOCOL_ERROR;
629     goto fail;
630   }
631
632   *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
633   memcpy(*Header, &common_hdr, sizeof(common_hdr));
634
635   /* read the rest of packet header */
636   dwRead = rpcrt4_conn_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
637   if (dwRead != hdr_length - sizeof(common_hdr)) {
638     WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
639     status = RPC_S_PROTOCOL_ERROR;
640     goto fail;
641   }
642
643   /* read packet body */
644   switch (common_hdr.ptype) {
645   case PKT_RESPONSE:
646     pMsg->BufferLength = (*Header)->response.alloc_hint;
647     break;
648   case PKT_REQUEST:
649     pMsg->BufferLength = (*Header)->request.alloc_hint;
650     break;
651   default:
652     pMsg->BufferLength = common_hdr.frag_len - hdr_length - RPC_AUTH_VERIFIER_LEN(&common_hdr);
653   }
654
655   TRACE("buffer length = %u\n", pMsg->BufferLength);
656
657   status = I_RpcGetBuffer(pMsg);
658   if (status != RPC_S_OK) goto fail;
659
660   first_flag = RPC_FLG_FIRST;
661   auth_length = common_hdr.auth_len;
662   if (auth_length) {
663     auth_data = HeapAlloc(GetProcessHeap(), 0, RPC_AUTH_VERIFIER_LEN(&common_hdr));
664     if (!auth_data) {
665       status = RPC_S_PROTOCOL_ERROR;
666       goto fail;
667     }
668   }
669   buffer_length = 0;
670   while (TRUE)
671   {
672     unsigned int header_auth_len = RPC_AUTH_VERIFIER_LEN(&(*Header)->common);
673
674     /* verify header fields */
675
676     if (((*Header)->common.frag_len < hdr_length) ||
677         ((*Header)->common.frag_len - hdr_length < header_auth_len)) {
678       WARN("frag_len %d too small for hdr_length %d and auth_len %d\n",
679         common_hdr.frag_len, hdr_length, common_hdr.auth_len);
680       status = RPC_S_PROTOCOL_ERROR;
681       goto fail;
682     }
683
684     if ((*Header)->common.auth_len != auth_length) {
685       WARN("auth_len header field changed from %ld to %d\n",
686         auth_length, (*Header)->common.auth_len);
687       status = RPC_S_PROTOCOL_ERROR;
688       goto fail;
689     }
690
691     if (((*Header)->common.flags & RPC_FLG_FIRST) != first_flag) {
692       TRACE("invalid packet flags\n");
693       status = RPC_S_PROTOCOL_ERROR;
694       goto fail;
695     }
696
697     data_length = (*Header)->common.frag_len - hdr_length - header_auth_len;
698     if (data_length + buffer_length > pMsg->BufferLength) {
699       TRACE("allocation hint exceeded, new buffer length = %ld\n",
700         data_length + buffer_length);
701       pMsg->BufferLength = data_length + buffer_length;
702       status = I_RpcReAllocateBuffer(pMsg);
703       if (status != RPC_S_OK) goto fail;
704     }
705
706     if (data_length == 0) dwRead = 0; else
707     dwRead = rpcrt4_conn_read(Connection,
708         (unsigned char *)pMsg->Buffer + buffer_length, data_length);
709     if (dwRead != data_length) {
710       WARN("bad data length, %d/%ld\n", dwRead, data_length);
711       status = RPC_S_PROTOCOL_ERROR;
712       goto fail;
713     }
714
715     if (header_auth_len) {
716       if (header_auth_len < sizeof(RpcAuthVerifier)) {
717         WARN("bad auth verifier length %d\n", header_auth_len);
718         status = RPC_S_PROTOCOL_ERROR;
719         goto fail;
720       }
721
722       /* FIXME: we should accumulate authentication data for the bind,
723        * bind_ack, alter_context and alter_context_response if necessary.
724        * however, the details of how this is done is very sketchy in the
725        * DCE/RPC spec. for all other packet types that have authentication
726        * verifier data then it is just duplicated in all the fragments */
727       dwRead = rpcrt4_conn_read(Connection, auth_data, header_auth_len);
728       if (dwRead != header_auth_len) {
729         WARN("bad authentication data length, %d/%d\n", dwRead,
730           header_auth_len);
731         status = RPC_S_PROTOCOL_ERROR;
732         goto fail;
733       }
734
735       /* these packets are handled specially, not by the generic SecurePacket
736        * function */
737       if ((common_hdr.ptype != PKT_BIND) &&
738           (common_hdr.ptype != PKT_BIND_ACK) &&
739           (common_hdr.ptype != PKT_AUTH3))
740         status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_RECEIVE,
741             *Header, hdr_length,
742             (unsigned char *)pMsg->Buffer + buffer_length, data_length,
743             (RpcAuthVerifier *)auth_data,
744             (unsigned char *)auth_data + sizeof(RpcAuthVerifier),
745             header_auth_len - sizeof(RpcAuthVerifier));
746     }
747
748     buffer_length += data_length;
749     if (!((*Header)->common.flags & RPC_FLG_LAST)) {
750       TRACE("next header\n");
751
752       /* read the header of next packet */
753       dwRead = rpcrt4_conn_read(Connection, *Header, hdr_length);
754       if (dwRead != hdr_length) {
755         WARN("invalid packet header size (%d)\n", dwRead);
756         status = RPC_S_PROTOCOL_ERROR;
757         goto fail;
758       }
759
760       first_flag = 0;
761     } else {
762       break;
763     }
764   }
765   pMsg->BufferLength = buffer_length;
766
767   /* respond to authorization request */
768   if (common_hdr.ptype == PKT_BIND_ACK && auth_length > sizeof(RpcAuthVerifier))
769   {
770     status = RPCRT_AuthorizeConnection(Connection,
771                                        auth_data + sizeof(RpcAuthVerifier),
772                                        auth_length);
773     if (status)
774         goto fail;
775   }
776
777   /* success */
778   status = RPC_S_OK;
779
780 fail:
781   if (status != RPC_S_OK) {
782     RPCRT4_FreeHeader(*Header);
783     *Header = NULL;
784   }
785   HeapFree(GetProcessHeap(), 0, auth_data);
786   return status;
787 }
788
789 /***********************************************************************
790  *           I_RpcGetBuffer [RPCRT4.@]
791  */
792 RPC_STATUS WINAPI I_RpcGetBuffer(PRPC_MESSAGE pMsg)
793 {
794   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
795   /* FIXME: pfnAllocate? */
796   pMsg->Buffer = HeapAlloc(GetProcessHeap(), 0, pMsg->BufferLength);
797
798   TRACE("Buffer=%p\n", pMsg->Buffer);
799   /* FIXME: which errors to return? */
800   return pMsg->Buffer ? S_OK : E_OUTOFMEMORY;
801 }
802
803 /***********************************************************************
804  *           I_RpcReAllocateBuffer (internal)
805  */
806 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg)
807 {
808   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
809   pMsg->Buffer = HeapReAlloc(GetProcessHeap(), 0, pMsg->Buffer, pMsg->BufferLength);
810
811   TRACE("Buffer=%p\n", pMsg->Buffer);
812   return pMsg->Buffer ? RPC_S_OK : RPC_S_OUT_OF_RESOURCES;
813 }
814
815 /***********************************************************************
816  *           I_RpcFreeBuffer [RPCRT4.@]
817  */
818 RPC_STATUS WINAPI I_RpcFreeBuffer(PRPC_MESSAGE pMsg)
819 {
820   TRACE("(%p) Buffer=%p\n", pMsg, pMsg->Buffer);
821   /* FIXME: pfnFree? */
822   HeapFree(GetProcessHeap(), 0, pMsg->Buffer);
823   pMsg->Buffer = NULL;
824   return S_OK;
825 }
826
827 /***********************************************************************
828  *           I_RpcSend [RPCRT4.@]
829  */
830 RPC_STATUS WINAPI I_RpcSend(PRPC_MESSAGE pMsg)
831 {
832   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
833   RpcConnection* conn;
834   RPC_CLIENT_INTERFACE* cif = NULL;
835   RPC_SERVER_INTERFACE* sif = NULL;
836   RPC_STATUS status;
837   RpcPktHdr *hdr;
838
839   TRACE("(%p)\n", pMsg);
840   if (!bind) return RPC_S_INVALID_BINDING;
841
842   if (bind->server) {
843     sif = pMsg->RpcInterfaceInformation;
844     if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
845     status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
846                                 &sif->InterfaceId);
847   } else {
848     cif = pMsg->RpcInterfaceInformation;
849     if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
850
851     if (!bind->Endpoint || !bind->Endpoint[0])
852     {
853       TRACE("automatically resolving partially bound binding\n");
854       status = RpcEpResolveBinding(bind, cif);
855       if (status != RPC_S_OK) return status;
856     }
857
858     status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
859                                 &cif->InterfaceId);
860   }
861
862   if (status != RPC_S_OK) return status;
863
864   if (bind->server) {
865     if (pMsg->RpcFlags & WINE_RPCFLAG_EXCEPTION) {
866       hdr = RPCRT4_BuildFaultHeader(pMsg->DataRepresentation,
867                                     RPC_S_CALL_FAILED);
868     } else {
869       hdr = RPCRT4_BuildResponseHeader(pMsg->DataRepresentation,
870                                        pMsg->BufferLength);
871     }
872   } else {
873     hdr = RPCRT4_BuildRequestHeader(pMsg->DataRepresentation,
874                                     pMsg->BufferLength, pMsg->ProcNum,
875                                     &bind->ObjectUuid);
876     hdr->common.call_id = conn->NextCallId++;
877   }
878
879   status = RPCRT4_Send(conn, hdr, pMsg->Buffer, pMsg->BufferLength);
880
881   RPCRT4_FreeHeader(hdr);
882
883   /* success */
884   if (!bind->server) {
885     /* save the connection, so the response can be read from it */
886     pMsg->ReservedForRuntime = conn;
887     return status;
888   }
889   RPCRT4_CloseBinding(bind, conn);
890
891   return status;
892 }
893
894 /***********************************************************************
895  *           I_RpcReceive [RPCRT4.@]
896  */
897 RPC_STATUS WINAPI I_RpcReceive(PRPC_MESSAGE pMsg)
898 {
899   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
900   RpcConnection* conn;
901   RPC_CLIENT_INTERFACE* cif = NULL;
902   RPC_SERVER_INTERFACE* sif = NULL;
903   RPC_STATUS status;
904   RpcPktHdr *hdr = NULL;
905
906   TRACE("(%p)\n", pMsg);
907   if (!bind) return RPC_S_INVALID_BINDING;
908
909   if (pMsg->ReservedForRuntime) {
910     conn = pMsg->ReservedForRuntime;
911     pMsg->ReservedForRuntime = NULL;
912   } else {
913     if (bind->server) {
914       sif = pMsg->RpcInterfaceInformation;
915       if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
916       status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
917                                   &sif->InterfaceId);
918     } else {
919       cif = pMsg->RpcInterfaceInformation;
920       if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
921
922       if (!bind->Endpoint || !bind->Endpoint[0])
923       {
924         TRACE("automatically resolving partially bound binding\n");
925         status = RpcEpResolveBinding(bind, cif);
926         if (status != RPC_S_OK) return status;
927       }
928
929       status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
930                                   &cif->InterfaceId);
931     }
932     if (status != RPC_S_OK) return status;
933   }
934
935   status = RPCRT4_Receive(conn, &hdr, pMsg);
936   if (status != RPC_S_OK) {
937     WARN("receive failed with error %lx\n", status);
938     goto fail;
939   }
940
941   status = RPC_S_PROTOCOL_ERROR;
942
943   switch (hdr->common.ptype) {
944   case PKT_RESPONSE:
945     if (bind->server) goto fail;
946     break;
947   case PKT_REQUEST:
948     if (!bind->server) goto fail;
949     break;
950   case PKT_FAULT:
951     pMsg->RpcFlags |= WINE_RPCFLAG_EXCEPTION;
952     ERR ("we got fault packet with status 0x%lx\n", hdr->fault.status);
953     status = hdr->fault.status; /* FIXME: do translation from nca error codes */
954     goto fail;
955   default:
956     WARN("bad packet type %d\n", hdr->common.ptype);
957     goto fail;
958   }
959
960   /* success */
961   status = RPC_S_OK;
962
963 fail:
964   RPCRT4_FreeHeader(hdr);
965   RPCRT4_CloseBinding(bind, conn);
966   return status;
967 }
968
969 /***********************************************************************
970  *           I_RpcSendReceive [RPCRT4.@]
971  */
972 RPC_STATUS WINAPI I_RpcSendReceive(PRPC_MESSAGE pMsg)
973 {
974   RPC_STATUS status;
975
976   TRACE("(%p)\n", pMsg);
977   status = I_RpcSend(pMsg);
978   if (status == RPC_S_OK)
979     status = I_RpcReceive(pMsg);
980   return status;
981 }