rpcrt4: Bind to the server interface in I_RpcGetBuffer, not I_RpcSendReceive.
[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
31 #include "rpc.h"
32 #include "rpcndr.h"
33 #include "rpcdcep.h"
34
35 #include "wine/debug.h"
36
37 #include "rpc_binding.h"
38 #include "rpc_defs.h"
39 #include "rpc_message.h"
40 #include "ncastatus.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
43
44 /* note: the DCE/RPC spec says the alignment amount should be 4, but
45  * MS/RPC servers seem to always use 16 */
46 #define AUTH_ALIGNMENT 16
47
48 /* gets the amount needed to round a value up to the specified alignment */
49 #define ROUND_UP_AMOUNT(value, alignment) \
50     (((alignment) - (((value) % (alignment)))) % (alignment))
51 #define ROUND_UP(value, alignment) (((value) + ((alignment) - 1)) & ~((alignment)-1))
52
53 enum secure_packet_direction
54 {
55   SECURE_PACKET_SEND,
56   SECURE_PACKET_RECEIVE
57 };
58
59 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg);
60
61 static DWORD RPCRT4_GetHeaderSize(const RpcPktHdr *Header)
62 {
63   static const DWORD header_sizes[] = {
64     sizeof(Header->request), 0, sizeof(Header->response),
65     sizeof(Header->fault), 0, 0, 0, 0, 0, 0, 0, sizeof(Header->bind),
66     sizeof(Header->bind_ack), sizeof(Header->bind_nack),
67     0, 0, 0, 0, 0
68   };
69   ULONG ret = 0;
70   
71   if (Header->common.ptype < sizeof(header_sizes) / sizeof(header_sizes[0])) {
72     ret = header_sizes[Header->common.ptype];
73     if (ret == 0)
74       FIXME("unhandled packet type\n");
75     if (Header->common.flags & RPC_FLG_OBJECT_UUID)
76       ret += sizeof(UUID);
77   } else {
78     TRACE("invalid packet type\n");
79   }
80
81   return ret;
82 }
83
84 static int packet_has_body(const RpcPktHdr *Header)
85 {
86     return (Header->common.ptype == PKT_FAULT) ||
87            (Header->common.ptype == PKT_REQUEST) ||
88            (Header->common.ptype == PKT_RESPONSE);
89 }
90
91 static int packet_has_auth_verifier(const RpcPktHdr *Header)
92 {
93     return !(Header->common.ptype == PKT_BIND_NACK) &&
94            !(Header->common.ptype == PKT_SHUTDOWN);
95 }
96
97 static VOID RPCRT4_BuildCommonHeader(RpcPktHdr *Header, unsigned char PacketType,
98                               unsigned long DataRepresentation)
99 {
100   Header->common.rpc_ver = RPC_VER_MAJOR;
101   Header->common.rpc_ver_minor = RPC_VER_MINOR;
102   Header->common.ptype = PacketType;
103   Header->common.drep[0] = LOBYTE(LOWORD(DataRepresentation));
104   Header->common.drep[1] = HIBYTE(LOWORD(DataRepresentation));
105   Header->common.drep[2] = LOBYTE(HIWORD(DataRepresentation));
106   Header->common.drep[3] = HIBYTE(HIWORD(DataRepresentation));
107   Header->common.auth_len = 0;
108   Header->common.call_id = 1;
109   Header->common.flags = 0;
110   /* Flags and fragment length are computed in RPCRT4_Send. */
111 }                              
112
113 static RpcPktHdr *RPCRT4_BuildRequestHeader(unsigned long DataRepresentation,
114                                      unsigned long BufferLength,
115                                      unsigned short ProcNum,
116                                      UUID *ObjectUuid)
117 {
118   RpcPktHdr *header;
119   BOOL has_object;
120   RPC_STATUS status;
121
122   has_object = (ObjectUuid != NULL && !UuidIsNil(ObjectUuid, &status));
123   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
124                      sizeof(header->request) + (has_object ? sizeof(UUID) : 0));
125   if (header == NULL) {
126     return NULL;
127   }
128
129   RPCRT4_BuildCommonHeader(header, PKT_REQUEST, DataRepresentation);
130   header->common.frag_len = sizeof(header->request);
131   header->request.alloc_hint = BufferLength;
132   header->request.context_id = 0;
133   header->request.opnum = ProcNum;
134   if (has_object) {
135     header->common.flags |= RPC_FLG_OBJECT_UUID;
136     header->common.frag_len += sizeof(UUID);
137     memcpy(&header->request + 1, ObjectUuid, sizeof(UUID));
138   }
139
140   return header;
141 }
142
143 RpcPktHdr *RPCRT4_BuildResponseHeader(unsigned long DataRepresentation,
144                                       unsigned long BufferLength)
145 {
146   RpcPktHdr *header;
147
148   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->response));
149   if (header == NULL) {
150     return NULL;
151   }
152
153   RPCRT4_BuildCommonHeader(header, PKT_RESPONSE, DataRepresentation);
154   header->common.frag_len = sizeof(header->response);
155   header->response.alloc_hint = BufferLength;
156
157   return header;
158 }
159
160 RpcPktHdr *RPCRT4_BuildFaultHeader(unsigned long DataRepresentation,
161                                    RPC_STATUS Status)
162 {
163   RpcPktHdr *header;
164
165   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->fault));
166   if (header == NULL) {
167     return NULL;
168   }
169
170   RPCRT4_BuildCommonHeader(header, PKT_FAULT, DataRepresentation);
171   header->common.frag_len = sizeof(header->fault);
172   header->fault.status = Status;
173
174   return header;
175 }
176
177 RpcPktHdr *RPCRT4_BuildBindHeader(unsigned long DataRepresentation,
178                                   unsigned short MaxTransmissionSize,
179                                   unsigned short MaxReceiveSize,
180                                   unsigned long  AssocGroupId,
181                                   const RPC_SYNTAX_IDENTIFIER *AbstractId,
182                                   const 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.assoc_gid = AssocGroupId;
196   header->bind.num_elements = 1;
197   header->bind.num_syntaxes = 1;
198   memcpy(&header->bind.abstract, AbstractId, sizeof(RPC_SYNTAX_IDENTIFIER));
199   memcpy(&header->bind.transfer, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
200
201   return header;
202 }
203
204 static RpcPktHdr *RPCRT4_BuildAuthHeader(unsigned long DataRepresentation)
205 {
206   RpcPktHdr *header;
207
208   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
209                      sizeof(header->common) + 12);
210   if (header == NULL)
211     return NULL;
212
213   RPCRT4_BuildCommonHeader(header, PKT_AUTH3, DataRepresentation);
214   header->common.frag_len = 0x14;
215   header->common.auth_len = 0;
216
217   return header;
218 }
219
220 RpcPktHdr *RPCRT4_BuildBindNackHeader(unsigned long DataRepresentation,
221                                       unsigned char RpcVersion,
222                                       unsigned char RpcVersionMinor)
223 {
224   RpcPktHdr *header;
225
226   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind_nack));
227   if (header == NULL) {
228     return NULL;
229   }
230
231   RPCRT4_BuildCommonHeader(header, PKT_BIND_NACK, DataRepresentation);
232   header->common.frag_len = sizeof(header->bind_nack);
233   header->bind_nack.reject_reason = REJECT_REASON_NOT_SPECIFIED;
234   header->bind_nack.protocols_count = 1;
235   header->bind_nack.protocols[0].rpc_ver = RpcVersion;
236   header->bind_nack.protocols[0].rpc_ver_minor = RpcVersionMinor;
237
238   return header;
239 }
240
241 RpcPktHdr *RPCRT4_BuildBindAckHeader(unsigned long DataRepresentation,
242                                      unsigned short MaxTransmissionSize,
243                                      unsigned short MaxReceiveSize,
244                                      unsigned long AssocGroupId,
245                                      LPCSTR ServerAddress,
246                                      unsigned long Result,
247                                      unsigned long Reason,
248                                      const RPC_SYNTAX_IDENTIFIER *TransferId)
249 {
250   RpcPktHdr *header;
251   unsigned long header_size;
252   RpcAddressString *server_address;
253   RpcResults *results;
254   RPC_SYNTAX_IDENTIFIER *transfer_id;
255
256   header_size = sizeof(header->bind_ack) +
257                 ROUND_UP(FIELD_OFFSET(RpcAddressString, string[strlen(ServerAddress) + 1]), 4) +
258                 sizeof(RpcResults) +
259                 sizeof(RPC_SYNTAX_IDENTIFIER);
260
261   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, header_size);
262   if (header == NULL) {
263     return NULL;
264   }
265
266   RPCRT4_BuildCommonHeader(header, PKT_BIND_ACK, DataRepresentation);
267   header->common.frag_len = header_size;
268   header->bind_ack.max_tsize = MaxTransmissionSize;
269   header->bind_ack.max_rsize = MaxReceiveSize;
270   header->bind_ack.assoc_gid = AssocGroupId;
271   server_address = (RpcAddressString*)(&header->bind_ack + 1);
272   server_address->length = strlen(ServerAddress) + 1;
273   strcpy(server_address->string, ServerAddress);
274   /* results is 4-byte aligned */
275   results = (RpcResults*)((ULONG_PTR)server_address + ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4));
276   results->num_results = 1;
277   results->results[0].result = Result;
278   results->results[0].reason = Reason;
279   transfer_id = (RPC_SYNTAX_IDENTIFIER*)(results + 1);
280   memcpy(transfer_id, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
281
282   return header;
283 }
284
285 VOID RPCRT4_FreeHeader(RpcPktHdr *Header)
286 {
287   HeapFree(GetProcessHeap(), 0, Header);
288 }
289
290 NCA_STATUS RPC2NCA_STATUS(RPC_STATUS status)
291 {
292     switch (status)
293     {
294     case ERROR_INVALID_HANDLE:              return NCA_S_FAULT_CONTEXT_MISMATCH;
295     case ERROR_OUTOFMEMORY:                 return NCA_S_FAULT_REMOTE_NO_MEMORY;
296     case RPC_S_NOT_LISTENING:               return NCA_S_SERVER_TOO_BUSY;
297     case RPC_S_UNKNOWN_IF:                  return NCA_S_UNK_IF;
298     case RPC_S_SERVER_TOO_BUSY:             return NCA_S_SERVER_TOO_BUSY;
299     case RPC_S_CALL_FAILED:                 return NCA_S_FAULT_UNSPEC;
300     case RPC_S_CALL_FAILED_DNE:             return NCA_S_MANAGER_NOT_ENTERED;
301     case RPC_S_PROTOCOL_ERROR:              return NCA_S_PROTO_ERROR;
302     case RPC_S_UNSUPPORTED_TYPE:            return NCA_S_UNSUPPORTED_TYPE;
303     case RPC_S_INVALID_TAG:                 return NCA_S_FAULT_INVALID_TAG;
304     case RPC_S_INVALID_BOUND:               return NCA_S_FAULT_INVALID_BOUND;
305     case RPC_S_PROCNUM_OUT_OF_RANGE:        return NCA_S_OP_RNG_ERROR;
306     case RPC_X_SS_HANDLES_MISMATCH:         return NCA_S_FAULT_CONTEXT_MISMATCH;
307     case RPC_S_CALL_CANCELLED:              return NCA_S_FAULT_CANCEL;
308     case RPC_S_COMM_FAILURE:                return NCA_S_COMM_FAILURE;
309     case RPC_X_WRONG_PIPE_ORDER:            return NCA_S_FAULT_PIPE_ORDER;
310     case RPC_X_PIPE_CLOSED:                 return NCA_S_FAULT_PIPE_CLOSED;
311     case RPC_X_PIPE_DISCIPLINE_ERROR:       return NCA_S_FAULT_PIPE_DISCIPLINE;
312     case RPC_X_PIPE_EMPTY:                  return NCA_S_FAULT_PIPE_EMPTY;
313     case STATUS_FLOAT_DIVIDE_BY_ZERO:       return NCA_S_FAULT_FP_DIV_ZERO;
314     case STATUS_FLOAT_INVALID_OPERATION:    return NCA_S_FAULT_FP_ERROR;
315     case STATUS_FLOAT_OVERFLOW:             return NCA_S_FAULT_FP_OVERFLOW;
316     case STATUS_FLOAT_UNDERFLOW:            return NCA_S_FAULT_FP_UNDERFLOW;
317     case STATUS_INTEGER_DIVIDE_BY_ZERO:     return NCA_S_FAULT_INT_DIV_BY_ZERO;
318     case STATUS_INTEGER_OVERFLOW:           return NCA_S_FAULT_INT_OVERFLOW;
319     default:                                return status;
320     }
321 }
322
323 RPC_STATUS NCA2RPC_STATUS(NCA_STATUS status)
324 {
325     switch (status)
326     {
327     case NCA_S_COMM_FAILURE:            return RPC_S_COMM_FAILURE;
328     case NCA_S_OP_RNG_ERROR:            return RPC_S_PROCNUM_OUT_OF_RANGE;
329     case NCA_S_UNK_IF:                  return RPC_S_UNKNOWN_IF;
330     case NCA_S_YOU_CRASHED:             return RPC_S_CALL_FAILED;
331     case NCA_S_PROTO_ERROR:             return RPC_S_PROTOCOL_ERROR;
332     case NCA_S_OUT_ARGS_TOO_BIG:        return ERROR_NOT_ENOUGH_SERVER_MEMORY;
333     case NCA_S_SERVER_TOO_BUSY:         return RPC_S_SERVER_TOO_BUSY;
334     case NCA_S_UNSUPPORTED_TYPE:        return RPC_S_UNSUPPORTED_TYPE;
335     case NCA_S_FAULT_INT_DIV_BY_ZERO:   return RPC_S_ZERO_DIVIDE;
336     case NCA_S_FAULT_ADDR_ERROR:        return RPC_S_ADDRESS_ERROR;
337     case NCA_S_FAULT_FP_DIV_ZERO:       return RPC_S_FP_DIV_ZERO;
338     case NCA_S_FAULT_FP_UNDERFLOW:      return RPC_S_FP_UNDERFLOW;
339     case NCA_S_FAULT_FP_OVERFLOW:       return RPC_S_FP_OVERFLOW;
340     case NCA_S_FAULT_INVALID_TAG:       return RPC_S_INVALID_TAG;
341     case NCA_S_FAULT_INVALID_BOUND:     return RPC_S_INVALID_BOUND;
342     case NCA_S_RPC_VERSION_MISMATCH:    return RPC_S_PROTOCOL_ERROR;
343     case NCA_S_UNSPEC_REJECT:           return RPC_S_CALL_FAILED_DNE;
344     case NCA_S_BAD_ACTID:               return RPC_S_CALL_FAILED_DNE;
345     case NCA_S_WHO_ARE_YOU_FAILED:      return RPC_S_CALL_FAILED;
346     case NCA_S_MANAGER_NOT_ENTERED:     return RPC_S_CALL_FAILED_DNE;
347     case NCA_S_FAULT_CANCEL:            return RPC_S_CALL_CANCELLED;
348     case NCA_S_FAULT_ILL_INST:          return RPC_S_ADDRESS_ERROR;
349     case NCA_S_FAULT_FP_ERROR:          return RPC_S_FP_OVERFLOW;
350     case NCA_S_FAULT_INT_OVERFLOW:      return RPC_S_ADDRESS_ERROR;
351     case NCA_S_FAULT_UNSPEC:            return RPC_S_CALL_FAILED;
352     case NCA_S_FAULT_PIPE_EMPTY:        return RPC_X_PIPE_EMPTY;
353     case NCA_S_FAULT_PIPE_CLOSED:       return RPC_X_PIPE_CLOSED;
354     case NCA_S_FAULT_PIPE_ORDER:        return RPC_X_WRONG_PIPE_ORDER;
355     case NCA_S_FAULT_PIPE_DISCIPLINE:   return RPC_X_PIPE_DISCIPLINE_ERROR;
356     case NCA_S_FAULT_PIPE_COMM_ERROR:   return RPC_S_COMM_FAILURE;
357     case NCA_S_FAULT_PIPE_MEMORY:       return ERROR_OUTOFMEMORY;
358     case NCA_S_FAULT_CONTEXT_MISMATCH:  return ERROR_INVALID_HANDLE;
359     case NCA_S_FAULT_REMOTE_NO_MEMORY:  return ERROR_NOT_ENOUGH_SERVER_MEMORY;
360     default:                            return status;
361     }
362 }
363
364 static RPC_STATUS RPCRT4_SecurePacket(RpcConnection *Connection,
365     enum secure_packet_direction dir,
366     RpcPktHdr *hdr, unsigned int hdr_size,
367     unsigned char *stub_data, unsigned int stub_data_size,
368     RpcAuthVerifier *auth_hdr,
369     unsigned char *auth_value, unsigned int auth_value_size)
370 {
371     SecBufferDesc message;
372     SecBuffer buffers[4];
373     SECURITY_STATUS sec_status;
374
375     message.ulVersion = SECBUFFER_VERSION;
376     message.cBuffers = sizeof(buffers)/sizeof(buffers[0]);
377     message.pBuffers = buffers;
378
379     buffers[0].cbBuffer = hdr_size;
380     buffers[0].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
381     buffers[0].pvBuffer = hdr;
382     buffers[1].cbBuffer = stub_data_size;
383     buffers[1].BufferType = SECBUFFER_DATA;
384     buffers[1].pvBuffer = stub_data;
385     buffers[2].cbBuffer = sizeof(*auth_hdr);
386     buffers[2].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
387     buffers[2].pvBuffer = auth_hdr;
388     buffers[3].cbBuffer = auth_value_size;
389     buffers[3].BufferType = SECBUFFER_TOKEN;
390     buffers[3].pvBuffer = auth_value;
391
392     if (dir == SECURE_PACKET_SEND)
393     {
394         if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
395         {
396             sec_status = EncryptMessage(&Connection->ctx, 0, &message, 0 /* FIXME */);
397             if (sec_status != SEC_E_OK)
398             {
399                 ERR("EncryptMessage failed with 0x%08x\n", sec_status);
400                 return RPC_S_SEC_PKG_ERROR;
401             }
402         }
403         else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
404         {
405             sec_status = MakeSignature(&Connection->ctx, 0, &message, 0 /* FIXME */);
406             if (sec_status != SEC_E_OK)
407             {
408                 ERR("MakeSignature failed with 0x%08x\n", sec_status);
409                 return RPC_S_SEC_PKG_ERROR;
410             }
411         }
412     }
413     else if (dir == SECURE_PACKET_RECEIVE)
414     {
415         if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
416         {
417             sec_status = DecryptMessage(&Connection->ctx, &message, 0 /* FIXME */, 0);
418             if (sec_status != SEC_E_OK)
419             {
420                 ERR("DecryptMessage failed with 0x%08x\n", sec_status);
421                 return RPC_S_SEC_PKG_ERROR;
422             }
423         }
424         else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
425         {
426             sec_status = VerifySignature(&Connection->ctx, &message, 0 /* FIXME */, NULL);
427             if (sec_status != SEC_E_OK)
428             {
429                 ERR("VerifySignature failed with 0x%08x\n", sec_status);
430                 return RPC_S_SEC_PKG_ERROR;
431             }
432         }
433     }
434
435     return RPC_S_OK;
436 }
437          
438 /***********************************************************************
439  *           RPCRT4_SendAuth (internal)
440  * 
441  * Transmit a packet with authorization data over connection in acceptable fragments.
442  */
443 static RPC_STATUS RPCRT4_SendAuth(RpcConnection *Connection, RpcPktHdr *Header,
444                                   void *Buffer, unsigned int BufferLength,
445                                   const void *Auth, unsigned int AuthLength)
446 {
447   PUCHAR buffer_pos;
448   DWORD hdr_size;
449   LONG count;
450   unsigned char *pkt;
451   LONG alen;
452   RPC_STATUS status;
453
454   RPCRT4_SetThreadCurrentConnection(Connection);
455
456   buffer_pos = Buffer;
457   /* The packet building functions save the packet header size, so we can use it. */
458   hdr_size = Header->common.frag_len;
459   if (AuthLength)
460     Header->common.auth_len = AuthLength;
461   else if (Connection->AuthInfo && packet_has_auth_verifier(Header))
462   {
463     if ((Connection->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(Header))
464       Header->common.auth_len = Connection->encryption_auth_len;
465     else
466       Header->common.auth_len = Connection->signature_auth_len;
467   }
468   else
469     Header->common.auth_len = 0;
470   Header->common.flags |= RPC_FLG_FIRST;
471   Header->common.flags &= ~RPC_FLG_LAST;
472
473   alen = RPC_AUTH_VERIFIER_LEN(&Header->common);
474
475   while (!(Header->common.flags & RPC_FLG_LAST)) {
476     unsigned char auth_pad_len = Header->common.auth_len ? ROUND_UP_AMOUNT(BufferLength, AUTH_ALIGNMENT) : 0;
477     unsigned int pkt_size = BufferLength + hdr_size + alen + auth_pad_len;
478
479     /* decide if we need to split the packet into fragments */
480    if (pkt_size <= Connection->MaxTransmissionSize) {
481      Header->common.flags |= RPC_FLG_LAST;
482      Header->common.frag_len = pkt_size;
483     } else {
484       auth_pad_len = 0;
485       /* make sure packet payload will be a multiple of 16 */
486       Header->common.frag_len =
487         ((Connection->MaxTransmissionSize - hdr_size - alen) & ~(AUTH_ALIGNMENT-1)) +
488         hdr_size + alen;
489     }
490
491     pkt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Header->common.frag_len);
492
493     memcpy(pkt, Header, hdr_size);
494
495     /* fragment consisted of header only and is the last one */
496     if (hdr_size == Header->common.frag_len)
497       goto write;
498
499     memcpy(pkt + hdr_size, buffer_pos, Header->common.frag_len - hdr_size - auth_pad_len - alen);
500
501     /* add the authorization info */
502     if (Connection->AuthInfo && packet_has_auth_verifier(Header))
503     {
504       RpcAuthVerifier *auth_hdr = (RpcAuthVerifier *)&pkt[Header->common.frag_len - alen];
505
506       auth_hdr->auth_type = Connection->AuthInfo->AuthnSvc;
507       auth_hdr->auth_level = Connection->AuthInfo->AuthnLevel;
508       auth_hdr->auth_pad_length = auth_pad_len;
509       auth_hdr->auth_reserved = 0;
510       /* a unique number... */
511       auth_hdr->auth_context_id = (unsigned long)Connection;
512
513       if (AuthLength)
514         memcpy(auth_hdr + 1, Auth, AuthLength);
515       else
516       {
517         status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_SEND,
518             (RpcPktHdr *)pkt, hdr_size,
519             pkt + hdr_size, Header->common.frag_len - hdr_size - alen,
520             auth_hdr,
521             (unsigned char *)(auth_hdr + 1), Header->common.auth_len);
522         if (status != RPC_S_OK)
523         {
524           HeapFree(GetProcessHeap(), 0, pkt);
525           RPCRT4_SetThreadCurrentConnection(NULL);
526           return status;
527         }
528       }
529     }
530
531 write:
532     count = rpcrt4_conn_write(Connection, pkt, Header->common.frag_len);
533     HeapFree(GetProcessHeap(), 0, pkt);
534     if (count<0) {
535       WARN("rpcrt4_conn_write failed (auth)\n");
536       RPCRT4_SetThreadCurrentConnection(NULL);
537       return RPC_S_CALL_FAILED;
538     }
539
540     buffer_pos += Header->common.frag_len - hdr_size - alen - auth_pad_len;
541     BufferLength -= Header->common.frag_len - hdr_size - alen - auth_pad_len;
542     Header->common.flags &= ~RPC_FLG_FIRST;
543   }
544
545   RPCRT4_SetThreadCurrentConnection(NULL);
546   return RPC_S_OK;
547 }
548
549 /***********************************************************************
550  *           RPCRT4_ClientAuthorize (internal)
551  *
552  * Authorize a client connection. A NULL in param signifies a new connection.
553  */
554 static RPC_STATUS RPCRT4_ClientAuthorize(RpcConnection *conn, SecBuffer *in,
555                                          SecBuffer *out)
556 {
557   SECURITY_STATUS r;
558   SecBufferDesc out_desc;
559   SecBufferDesc inp_desc;
560   SecPkgContext_Sizes secctx_sizes;
561   BOOL continue_needed;
562   ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
563                       ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
564
565   if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
566     context_req |= ISC_REQ_INTEGRITY;
567   else if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY)
568     context_req |= ISC_REQ_CONFIDENTIALITY | ISC_REQ_INTEGRITY;
569
570   out->BufferType = SECBUFFER_TOKEN;
571   out->cbBuffer = conn->AuthInfo->cbMaxToken;
572   out->pvBuffer = HeapAlloc(GetProcessHeap(), 0, out->cbBuffer);
573   if (!out->pvBuffer) return ERROR_OUTOFMEMORY;
574
575   out_desc.ulVersion = 0;
576   out_desc.cBuffers = 1;
577   out_desc.pBuffers = out;
578
579   inp_desc.cBuffers = 1;
580   inp_desc.pBuffers = in;
581   inp_desc.ulVersion = 0;
582
583   r = InitializeSecurityContextA(&conn->AuthInfo->cred, in ? &conn->ctx : NULL,
584         NULL, context_req, 0, SECURITY_NETWORK_DREP,
585         in ? &inp_desc : NULL, 0, &conn->ctx, &out_desc, &conn->attr,
586         &conn->exp);
587   if (FAILED(r))
588   {
589       WARN("InitializeSecurityContext failed with error 0x%08x\n", r);
590       goto failed;
591   }
592
593   TRACE("r = 0x%08x, attr = 0x%08x\n", r, conn->attr);
594   continue_needed = ((r == SEC_I_CONTINUE_NEEDED) ||
595                      (r == SEC_I_COMPLETE_AND_CONTINUE));
596
597   if ((r == SEC_I_COMPLETE_NEEDED) || (r == SEC_I_COMPLETE_AND_CONTINUE))
598   {
599       TRACE("complete needed\n");
600       r = CompleteAuthToken(&conn->ctx, &out_desc);
601       if (FAILED(r))
602       {
603           WARN("CompleteAuthToken failed with error 0x%08x\n", r);
604           goto failed;
605       }
606   }
607
608   TRACE("cbBuffer = %ld\n", out->cbBuffer);
609
610   if (!continue_needed)
611   {
612       r = QueryContextAttributesA(&conn->ctx, SECPKG_ATTR_SIZES, &secctx_sizes);
613       if (FAILED(r))
614       {
615           WARN("QueryContextAttributes failed with error 0x%08x\n", r);
616           goto failed;
617       }
618       conn->signature_auth_len = secctx_sizes.cbMaxSignature;
619       conn->encryption_auth_len = secctx_sizes.cbSecurityTrailer;
620   }
621
622   return RPC_S_OK;
623
624 failed:
625   HeapFree(GetProcessHeap(), 0, out->pvBuffer);
626   out->pvBuffer = NULL;
627   return ERROR_ACCESS_DENIED; /* FIXME: is this correct? */
628 }
629
630 /***********************************************************************
631  *           RPCRT4_AuthorizeBinding (internal)
632  */
633 static RPC_STATUS RPCRT_AuthorizeConnection(RpcConnection* conn,
634                                             BYTE *challenge, ULONG count)
635 {
636   SecBuffer inp, out;
637   RpcPktHdr *resp_hdr;
638   RPC_STATUS status;
639
640   TRACE("challenge %s, %d bytes\n", challenge, count);
641
642   inp.BufferType = SECBUFFER_TOKEN;
643   inp.pvBuffer = challenge;
644   inp.cbBuffer = count;
645
646   status = RPCRT4_ClientAuthorize(conn, &inp, &out);
647   if (status) return status;
648
649   resp_hdr = RPCRT4_BuildAuthHeader(NDR_LOCAL_DATA_REPRESENTATION);
650   if (!resp_hdr)
651     return E_OUTOFMEMORY;
652
653   status = RPCRT4_SendAuth(conn, resp_hdr, NULL, 0, out.pvBuffer, out.cbBuffer);
654
655   HeapFree(GetProcessHeap(), 0, out.pvBuffer);
656   RPCRT4_FreeHeader(resp_hdr);
657
658   return status;
659 }
660
661 /***********************************************************************
662  *           RPCRT4_Send (internal)
663  * 
664  * Transmit a packet over connection in acceptable fragments.
665  */
666 RPC_STATUS RPCRT4_Send(RpcConnection *Connection, RpcPktHdr *Header,
667                        void *Buffer, unsigned int BufferLength)
668 {
669   RPC_STATUS r;
670   SecBuffer out;
671
672   if (!Connection->AuthInfo || SecIsValidHandle(&Connection->ctx))
673   {
674     return RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, NULL, 0);
675   }
676
677   /* tack on a negotiate packet */
678   RPCRT4_ClientAuthorize(Connection, NULL, &out);
679   r = RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, out.pvBuffer, out.cbBuffer);
680   HeapFree(GetProcessHeap(), 0, out.pvBuffer);
681
682   return r;
683 }
684
685 /***********************************************************************
686  *           RPCRT4_Receive (internal)
687  * 
688  * Receive a packet from connection and merge the fragments.
689  */
690 RPC_STATUS RPCRT4_Receive(RpcConnection *Connection, RpcPktHdr **Header,
691                           PRPC_MESSAGE pMsg)
692 {
693   RPC_STATUS status;
694   DWORD hdr_length;
695   LONG dwRead;
696   unsigned short first_flag;
697   unsigned long data_length;
698   unsigned long buffer_length;
699   unsigned long auth_length;
700   unsigned char *auth_data = NULL;
701   RpcPktCommonHdr common_hdr;
702
703   *Header = NULL;
704
705   TRACE("(%p, %p, %p)\n", Connection, Header, pMsg);
706
707   RPCRT4_SetThreadCurrentConnection(Connection);
708
709   /* read packet common header */
710   dwRead = rpcrt4_conn_read(Connection, &common_hdr, sizeof(common_hdr));
711   if (dwRead != sizeof(common_hdr)) {
712     WARN("Short read of header, %d bytes\n", dwRead);
713     status = RPC_S_CALL_FAILED;
714     goto fail;
715   }
716
717   /* verify if the header really makes sense */
718   if (common_hdr.rpc_ver != RPC_VER_MAJOR ||
719       common_hdr.rpc_ver_minor != RPC_VER_MINOR) {
720     WARN("unhandled packet version\n");
721     status = RPC_S_PROTOCOL_ERROR;
722     goto fail;
723   }
724
725   hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
726   if (hdr_length == 0) {
727     WARN("header length == 0\n");
728     status = RPC_S_PROTOCOL_ERROR;
729     goto fail;
730   }
731
732   *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
733   memcpy(*Header, &common_hdr, sizeof(common_hdr));
734
735   /* read the rest of packet header */
736   dwRead = rpcrt4_conn_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
737   if (dwRead != hdr_length - sizeof(common_hdr)) {
738     WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
739     status = RPC_S_CALL_FAILED;
740     goto fail;
741   }
742
743   /* read packet body */
744   switch (common_hdr.ptype) {
745   case PKT_RESPONSE:
746     pMsg->BufferLength = (*Header)->response.alloc_hint;
747     break;
748   case PKT_REQUEST:
749     pMsg->BufferLength = (*Header)->request.alloc_hint;
750     break;
751   default:
752     pMsg->BufferLength = common_hdr.frag_len - hdr_length - RPC_AUTH_VERIFIER_LEN(&common_hdr);
753   }
754
755   TRACE("buffer length = %u\n", pMsg->BufferLength);
756
757   pMsg->Buffer = I_RpcAllocate(pMsg->BufferLength);
758   if (!pMsg->Buffer)
759   {
760     status = ERROR_OUTOFMEMORY;
761     goto fail;
762   }
763
764   first_flag = RPC_FLG_FIRST;
765   auth_length = common_hdr.auth_len;
766   if (auth_length) {
767     auth_data = HeapAlloc(GetProcessHeap(), 0, RPC_AUTH_VERIFIER_LEN(&common_hdr));
768     if (!auth_data) {
769       status = RPC_S_OUT_OF_RESOURCES;
770       goto fail;
771     }
772   }
773   buffer_length = 0;
774   while (TRUE)
775   {
776     unsigned int header_auth_len = RPC_AUTH_VERIFIER_LEN(&(*Header)->common);
777
778     /* verify header fields */
779
780     if (((*Header)->common.frag_len < hdr_length) ||
781         ((*Header)->common.frag_len - hdr_length < header_auth_len)) {
782       WARN("frag_len %d too small for hdr_length %d and auth_len %d\n",
783         (*Header)->common.frag_len, hdr_length, header_auth_len);
784       status = RPC_S_PROTOCOL_ERROR;
785       goto fail;
786     }
787
788     if ((*Header)->common.auth_len != auth_length) {
789       WARN("auth_len header field changed from %ld to %d\n",
790         auth_length, (*Header)->common.auth_len);
791       status = RPC_S_PROTOCOL_ERROR;
792       goto fail;
793     }
794
795     if (((*Header)->common.flags & RPC_FLG_FIRST) != first_flag) {
796       TRACE("invalid packet flags\n");
797       status = RPC_S_PROTOCOL_ERROR;
798       goto fail;
799     }
800
801     data_length = (*Header)->common.frag_len - hdr_length - header_auth_len;
802     if (data_length + buffer_length > pMsg->BufferLength) {
803       TRACE("allocation hint exceeded, new buffer length = %ld\n",
804         data_length + buffer_length);
805       pMsg->BufferLength = data_length + buffer_length;
806       status = I_RpcReAllocateBuffer(pMsg);
807       if (status != RPC_S_OK) goto fail;
808     }
809
810     if (data_length == 0) dwRead = 0; else
811     dwRead = rpcrt4_conn_read(Connection,
812         (unsigned char *)pMsg->Buffer + buffer_length, data_length);
813     if (dwRead != data_length) {
814       WARN("bad data length, %d/%ld\n", dwRead, data_length);
815       status = RPC_S_CALL_FAILED;
816       goto fail;
817     }
818
819     if (header_auth_len) {
820       if (header_auth_len < sizeof(RpcAuthVerifier)) {
821         WARN("bad auth verifier length %d\n", header_auth_len);
822         status = RPC_S_PROTOCOL_ERROR;
823         goto fail;
824       }
825
826       /* FIXME: we should accumulate authentication data for the bind,
827        * bind_ack, alter_context and alter_context_response if necessary.
828        * however, the details of how this is done is very sketchy in the
829        * DCE/RPC spec. for all other packet types that have authentication
830        * verifier data then it is just duplicated in all the fragments */
831       dwRead = rpcrt4_conn_read(Connection, auth_data, header_auth_len);
832       if (dwRead != header_auth_len) {
833         WARN("bad authentication data length, %d/%d\n", dwRead,
834           header_auth_len);
835         status = RPC_S_CALL_FAILED;
836         goto fail;
837       }
838
839       /* these packets are handled specially, not by the generic SecurePacket
840        * function */
841       if ((common_hdr.ptype != PKT_BIND) &&
842           (common_hdr.ptype != PKT_BIND_ACK) &&
843           (common_hdr.ptype != PKT_AUTH3))
844       {
845         status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_RECEIVE,
846             *Header, hdr_length,
847             (unsigned char *)pMsg->Buffer + buffer_length, data_length,
848             (RpcAuthVerifier *)auth_data,
849             (unsigned char *)auth_data + sizeof(RpcAuthVerifier),
850             header_auth_len - sizeof(RpcAuthVerifier));
851         if (status != RPC_S_OK) goto fail;
852       }
853     }
854
855     buffer_length += data_length;
856     if (!((*Header)->common.flags & RPC_FLG_LAST)) {
857       TRACE("next header\n");
858
859       /* read the header of next packet */
860       dwRead = rpcrt4_conn_read(Connection, *Header, hdr_length);
861       if (dwRead != hdr_length) {
862         WARN("invalid packet header size (%d)\n", dwRead);
863         status = RPC_S_CALL_FAILED;
864         goto fail;
865       }
866
867       first_flag = 0;
868     } else {
869       break;
870     }
871   }
872   pMsg->BufferLength = buffer_length;
873
874   /* respond to authorization request */
875   if (common_hdr.ptype == PKT_BIND_ACK && auth_length > sizeof(RpcAuthVerifier))
876   {
877     status = RPCRT_AuthorizeConnection(Connection,
878                                        auth_data + sizeof(RpcAuthVerifier),
879                                        auth_length);
880     if (status)
881         goto fail;
882   }
883
884   /* success */
885   status = RPC_S_OK;
886
887 fail:
888   RPCRT4_SetThreadCurrentConnection(NULL);
889   if (status != RPC_S_OK) {
890     RPCRT4_FreeHeader(*Header);
891     *Header = NULL;
892   }
893   HeapFree(GetProcessHeap(), 0, auth_data);
894   return status;
895 }
896
897 /***********************************************************************
898  *           I_RpcNegotiateTransferSyntax [RPCRT4.@]
899  *
900  * Negotiates the transfer syntax used by a client connection by connecting
901  * to the server.
902  *
903  * PARAMS
904  *  pMsg   [I] RPC Message structure.
905  *  pAsync [I] Asynchronous state to set.
906  *
907  * RETURNS
908  *  Success: RPC_S_OK.
909  *  Failure: Any error code.
910  */
911 RPC_STATUS WINAPI I_RpcNegotiateTransferSyntax(PRPC_MESSAGE pMsg)
912 {
913   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
914   RpcConnection* conn;
915   RPC_STATUS status = RPC_S_OK;
916
917   TRACE("(%p)\n", pMsg);
918
919   if (!bind || bind->server)
920     return RPC_S_INVALID_BINDING;
921
922   /* if we already have a connection, we don't need to negotiate again */
923   if (!pMsg->ReservedForRuntime)
924   {
925     RPC_CLIENT_INTERFACE *cif = pMsg->RpcInterfaceInformation;
926     if (!cif) return RPC_S_INTERFACE_NOT_FOUND;
927
928     if (!bind->Endpoint || !bind->Endpoint[0])
929     {
930       TRACE("automatically resolving partially bound binding\n");
931       status = RpcEpResolveBinding(bind, cif);
932       if (status != RPC_S_OK) return status;
933     }
934
935     status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
936                                 &cif->InterfaceId);
937
938     if (status == RPC_S_OK)
939       pMsg->ReservedForRuntime = conn;
940   }
941
942   return status;
943 }
944
945 /***********************************************************************
946  *           I_RpcGetBuffer [RPCRT4.@]
947  *
948  * Allocates a buffer for use by I_RpcSend or I_RpcSendReceive and binds to the
949  * server interface.
950  *
951  * PARAMS
952  *  pMsg [I/O] RPC message information.
953  *
954  * RETURNS
955  *  Success: RPC_S_OK.
956  *  Failure: RPC_S_INVALID_BINDING if pMsg->Handle is invalid.
957  *           RPC_S_SERVER_UNAVAILABLE if unable to connect to server.
958  *           ERROR_OUTOFMEMORY if buffer allocation failed.
959  *
960  * NOTES
961  *  The pMsg->BufferLength field determines the size of the buffer to allocate,
962  *  in bytes.
963  *
964  *  Use I_RpcFreeBuffer() to unbind from the server and free the message buffer.
965  *
966  * SEE ALSO
967  *  I_RpcFreeBuffer(), I_RpcSend(), I_RpcReceive(), I_RpcSendReceive().
968  */
969 RPC_STATUS WINAPI I_RpcGetBuffer(PRPC_MESSAGE pMsg)
970 {
971   RPC_STATUS status;
972   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
973
974   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
975
976   if (!bind)
977     return RPC_S_INVALID_BINDING;
978
979   pMsg->Buffer = I_RpcAllocate(pMsg->BufferLength);
980   TRACE("Buffer=%p\n", pMsg->Buffer);
981
982   if (!pMsg->Buffer)
983     return ERROR_OUTOFMEMORY;
984
985   if (!bind->server)
986   {
987     status = I_RpcNegotiateTransferSyntax(pMsg);
988     if (status != RPC_S_OK)
989       I_RpcFree(pMsg->Buffer);
990   }
991   else
992     status = RPC_S_OK;
993
994   return status;
995 }
996
997 /***********************************************************************
998  *           I_RpcReAllocateBuffer (internal)
999  */
1000 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg)
1001 {
1002   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
1003   pMsg->Buffer = HeapReAlloc(GetProcessHeap(), 0, pMsg->Buffer, pMsg->BufferLength);
1004
1005   TRACE("Buffer=%p\n", pMsg->Buffer);
1006   return pMsg->Buffer ? RPC_S_OK : ERROR_OUTOFMEMORY;
1007 }
1008
1009 /***********************************************************************
1010  *           I_RpcFreeBuffer [RPCRT4.@]
1011  *
1012  * Frees a buffer allocated by I_RpcGetBuffer or I_RpcReceive and unbinds from
1013  * the server interface.
1014  *
1015  * PARAMS
1016  *  pMsg [I/O] RPC message information.
1017  *
1018  * RETURNS
1019  *  RPC_S_OK.
1020  *
1021  * SEE ALSO
1022  *  I_RpcGetBuffer(), I_RpcReceive().
1023  */
1024 RPC_STATUS WINAPI I_RpcFreeBuffer(PRPC_MESSAGE pMsg)
1025 {
1026   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
1027
1028   TRACE("(%p) Buffer=%p\n", pMsg, pMsg->Buffer);
1029
1030   if (!bind) return RPC_S_INVALID_BINDING;
1031
1032   if (pMsg->ReservedForRuntime)
1033   {
1034     RpcConnection *conn = pMsg->ReservedForRuntime;
1035     RPCRT4_CloseBinding(bind, conn);
1036     pMsg->ReservedForRuntime = NULL;
1037   }
1038   I_RpcFree(pMsg->Buffer);
1039   return RPC_S_OK;
1040 }
1041
1042 /***********************************************************************
1043  *           I_RpcSend [RPCRT4.@]
1044  *
1045  * Sends a message to the server.
1046  *
1047  * PARAMS
1048  *  pMsg [I/O] RPC message information.
1049  *
1050  * RETURNS
1051  *  Unknown.
1052  *
1053  * NOTES
1054  *  The buffer must have been allocated with I_RpcGetBuffer().
1055  *
1056  * SEE ALSO
1057  *  I_RpcGetBuffer(), I_RpcReceive(), I_RpcSendReceive().
1058  */
1059 RPC_STATUS WINAPI I_RpcSend(PRPC_MESSAGE pMsg)
1060 {
1061   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
1062   RpcConnection* conn;
1063   RPC_STATUS status;
1064   RpcPktHdr *hdr;
1065
1066   TRACE("(%p)\n", pMsg);
1067   if (!bind || bind->server || !pMsg->ReservedForRuntime) return RPC_S_INVALID_BINDING;
1068
1069   conn = pMsg->ReservedForRuntime;
1070
1071   hdr = RPCRT4_BuildRequestHeader(pMsg->DataRepresentation,
1072                                   pMsg->BufferLength,
1073                                   pMsg->ProcNum & ~RPC_FLAGS_VALID_BIT,
1074                                   &bind->ObjectUuid);
1075   if (!hdr)
1076     return ERROR_OUTOFMEMORY;
1077   hdr->common.call_id = conn->NextCallId++;
1078
1079   status = RPCRT4_Send(conn, hdr, pMsg->Buffer, pMsg->BufferLength);
1080
1081   RPCRT4_FreeHeader(hdr);
1082
1083   return status;
1084 }
1085
1086 /* is this status something that the server can't recover from? */
1087 static inline BOOL is_hard_error(RPC_STATUS status)
1088 {
1089     switch (status)
1090     {
1091     case 0: /* user-defined fault */
1092     case ERROR_ACCESS_DENIED:
1093     case ERROR_INVALID_PARAMETER:
1094     case RPC_S_PROTOCOL_ERROR:
1095     case RPC_S_CALL_FAILED:
1096     case RPC_S_CALL_FAILED_DNE:
1097     case RPC_S_SEC_PKG_ERROR:
1098         return TRUE;
1099     default:
1100         return FALSE;
1101     }
1102 }
1103
1104 /***********************************************************************
1105  *           I_RpcReceive [RPCRT4.@]
1106  */
1107 RPC_STATUS WINAPI I_RpcReceive(PRPC_MESSAGE pMsg)
1108 {
1109   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
1110   RPC_STATUS status;
1111   RpcPktHdr *hdr = NULL;
1112   RpcConnection *conn;
1113
1114   TRACE("(%p)\n", pMsg);
1115   if (!bind || bind->server || !pMsg->ReservedForRuntime) return RPC_S_INVALID_BINDING;
1116
1117   conn = pMsg->ReservedForRuntime;
1118   status = RPCRT4_Receive(conn, &hdr, pMsg);
1119   if (status != RPC_S_OK) {
1120     WARN("receive failed with error %lx\n", status);
1121     goto fail;
1122   }
1123
1124   switch (hdr->common.ptype) {
1125   case PKT_RESPONSE:
1126     break;
1127   case PKT_FAULT:
1128     ERR ("we got fault packet with status 0x%lx\n", hdr->fault.status);
1129     status = NCA2RPC_STATUS(hdr->fault.status);
1130     if (is_hard_error(status))
1131         goto fail;
1132     break;
1133   default:
1134     WARN("bad packet type %d\n", hdr->common.ptype);
1135     status = RPC_S_PROTOCOL_ERROR;
1136     goto fail;
1137   }
1138
1139   /* success */
1140   RPCRT4_FreeHeader(hdr);
1141   return status;
1142
1143 fail:
1144   RPCRT4_FreeHeader(hdr);
1145   RPCRT4_DestroyConnection(conn);
1146   pMsg->ReservedForRuntime = NULL;
1147   return status;
1148 }
1149
1150 /***********************************************************************
1151  *           I_RpcSendReceive [RPCRT4.@]
1152  *
1153  * Sends a message to the server and receives the response.
1154  *
1155  * PARAMS
1156  *  pMsg [I/O] RPC message information.
1157  *
1158  * RETURNS
1159  *  Success: RPC_S_OK.
1160  *  Failure: Any error code.
1161  *
1162  * NOTES
1163  *  The buffer must have been allocated with I_RpcGetBuffer().
1164  *
1165  * SEE ALSO
1166  *  I_RpcGetBuffer(), I_RpcSend(), I_RpcReceive().
1167  */
1168 RPC_STATUS WINAPI I_RpcSendReceive(PRPC_MESSAGE pMsg)
1169 {
1170   RPC_STATUS status;
1171   void *original_buffer;
1172
1173   TRACE("(%p)\n", pMsg);
1174
1175   original_buffer = pMsg->Buffer;
1176   status = I_RpcSend(pMsg);
1177   if (status == RPC_S_OK)
1178     status = I_RpcReceive(pMsg);
1179   /* free the buffer replaced by a new buffer in I_RpcReceive */
1180   if (status == RPC_S_OK)
1181     I_RpcFree(original_buffer);
1182   return status;
1183 }
1184
1185 /***********************************************************************
1186  *           I_RpcAsyncSetHandle [RPCRT4.@]
1187  *
1188  * Sets the asynchronous state of the handle contained in the RPC message
1189  * structure.
1190  *
1191  * PARAMS
1192  *  pMsg   [I] RPC Message structure.
1193  *  pAsync [I] Asynchronous state to set.
1194  *
1195  * RETURNS
1196  *  Success: RPC_S_OK.
1197  *  Failure: Any error code.
1198  */
1199 RPC_STATUS WINAPI I_RpcAsyncSetHandle(PRPC_MESSAGE pMsg, PRPC_ASYNC_STATE pAsync)
1200 {
1201     FIXME("(%p, %p): stub\n", pMsg, pAsync);
1202     return RPC_S_INVALID_BINDING;
1203 }
1204
1205 /***********************************************************************
1206  *           I_RpcAsyncAbortCall [RPCRT4.@]
1207  *
1208  * Aborts an asynchronous call.
1209  *
1210  * PARAMS
1211  *  pAsync        [I] Asynchronous state.
1212  *  ExceptionCode [I] Exception code.
1213  *
1214  * RETURNS
1215  *  Success: RPC_S_OK.
1216  *  Failure: Any error code.
1217  */
1218 RPC_STATUS WINAPI I_RpcAsyncAbortCall(PRPC_ASYNC_STATE pAsync, ULONG ExceptionCode)
1219 {
1220     FIXME("(%p, %d): stub\n", pAsync, ExceptionCode);
1221     return RPC_S_INVALID_ASYNC_HANDLE;
1222 }