msi: Release the record when loading the hash data.
[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                                      LPCSTR ServerAddress,
245                                      unsigned long Result,
246                                      unsigned long Reason,
247                                      const RPC_SYNTAX_IDENTIFIER *TransferId)
248 {
249   RpcPktHdr *header;
250   unsigned long header_size;
251   RpcAddressString *server_address;
252   RpcResults *results;
253   RPC_SYNTAX_IDENTIFIER *transfer_id;
254
255   header_size = sizeof(header->bind_ack) +
256                 ROUND_UP(FIELD_OFFSET(RpcAddressString, string[strlen(ServerAddress) + 1]), 4) +
257                 sizeof(RpcResults) +
258                 sizeof(RPC_SYNTAX_IDENTIFIER);
259
260   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, header_size);
261   if (header == NULL) {
262     return NULL;
263   }
264
265   RPCRT4_BuildCommonHeader(header, PKT_BIND_ACK, DataRepresentation);
266   header->common.frag_len = header_size;
267   header->bind_ack.max_tsize = MaxTransmissionSize;
268   header->bind_ack.max_rsize = MaxReceiveSize;
269   server_address = (RpcAddressString*)(&header->bind_ack + 1);
270   server_address->length = strlen(ServerAddress) + 1;
271   strcpy(server_address->string, ServerAddress);
272   /* results is 4-byte aligned */
273   results = (RpcResults*)((ULONG_PTR)server_address + ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4));
274   results->num_results = 1;
275   results->results[0].result = Result;
276   results->results[0].reason = Reason;
277   transfer_id = (RPC_SYNTAX_IDENTIFIER*)(results + 1);
278   memcpy(transfer_id, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
279
280   return header;
281 }
282
283 VOID RPCRT4_FreeHeader(RpcPktHdr *Header)
284 {
285   HeapFree(GetProcessHeap(), 0, Header);
286 }
287
288 NCA_STATUS RPC2NCA_STATUS(RPC_STATUS status)
289 {
290     switch (status)
291     {
292     case ERROR_INVALID_HANDLE:              return NCA_S_FAULT_CONTEXT_MISMATCH;
293     case ERROR_OUTOFMEMORY:                 return NCA_S_FAULT_REMOTE_NO_MEMORY;
294     case RPC_S_NOT_LISTENING:               return NCA_S_SERVER_TOO_BUSY;
295     case RPC_S_UNKNOWN_IF:                  return NCA_S_UNK_IF;
296     case RPC_S_SERVER_TOO_BUSY:             return NCA_S_SERVER_TOO_BUSY;
297     case RPC_S_CALL_FAILED:                 return NCA_S_FAULT_UNSPEC;
298     case RPC_S_CALL_FAILED_DNE:             return NCA_S_MANAGER_NOT_ENTERED;
299     case RPC_S_PROTOCOL_ERROR:              return NCA_S_PROTO_ERROR;
300     case RPC_S_UNSUPPORTED_TYPE:            return NCA_S_UNSUPPORTED_TYPE;
301     case RPC_S_INVALID_TAG:                 return NCA_S_FAULT_INVALID_TAG;
302     case RPC_S_INVALID_BOUND:               return NCA_S_FAULT_INVALID_BOUND;
303     case RPC_S_PROCNUM_OUT_OF_RANGE:        return NCA_S_OP_RNG_ERROR;
304     case RPC_X_SS_HANDLES_MISMATCH:         return NCA_S_FAULT_CONTEXT_MISMATCH;
305     case RPC_S_CALL_CANCELLED:              return NCA_S_FAULT_CANCEL;
306     case RPC_S_COMM_FAILURE:                return NCA_S_COMM_FAILURE;
307     case RPC_X_WRONG_PIPE_ORDER:            return NCA_S_FAULT_PIPE_ORDER;
308     case RPC_X_PIPE_CLOSED:                 return NCA_S_FAULT_PIPE_CLOSED;
309     case RPC_X_PIPE_DISCIPLINE_ERROR:       return NCA_S_FAULT_PIPE_DISCIPLINE;
310     case RPC_X_PIPE_EMPTY:                  return NCA_S_FAULT_PIPE_EMPTY;
311     case STATUS_FLOAT_DIVIDE_BY_ZERO:       return NCA_S_FAULT_FP_DIV_ZERO;
312     case STATUS_FLOAT_INVALID_OPERATION:    return NCA_S_FAULT_FP_ERROR;
313     case STATUS_FLOAT_OVERFLOW:             return NCA_S_FAULT_FP_OVERFLOW;
314     case STATUS_FLOAT_UNDERFLOW:            return NCA_S_FAULT_FP_UNDERFLOW;
315     case STATUS_INTEGER_DIVIDE_BY_ZERO:     return NCA_S_FAULT_INT_DIV_BY_ZERO;
316     case STATUS_INTEGER_OVERFLOW:           return NCA_S_FAULT_INT_OVERFLOW;
317     default:                                return status;
318     }
319 }
320
321 RPC_STATUS NCA2RPC_STATUS(NCA_STATUS status)
322 {
323     switch (status)
324     {
325     case NCA_S_COMM_FAILURE:            return RPC_S_COMM_FAILURE;
326     case NCA_S_OP_RNG_ERROR:            return RPC_S_PROCNUM_OUT_OF_RANGE;
327     case NCA_S_UNK_IF:                  return RPC_S_UNKNOWN_IF;
328     case NCA_S_YOU_CRASHED:             return RPC_S_CALL_FAILED;
329     case NCA_S_PROTO_ERROR:             return RPC_S_PROTOCOL_ERROR;
330     case NCA_S_OUT_ARGS_TOO_BIG:        return ERROR_NOT_ENOUGH_SERVER_MEMORY;
331     case NCA_S_SERVER_TOO_BUSY:         return RPC_S_SERVER_TOO_BUSY;
332     case NCA_S_UNSUPPORTED_TYPE:        return RPC_S_UNSUPPORTED_TYPE;
333     case NCA_S_FAULT_INT_DIV_BY_ZERO:   return RPC_S_ZERO_DIVIDE;
334     case NCA_S_FAULT_ADDR_ERROR:        return RPC_S_ADDRESS_ERROR;
335     case NCA_S_FAULT_FP_DIV_ZERO:       return RPC_S_FP_DIV_ZERO;
336     case NCA_S_FAULT_FP_UNDERFLOW:      return RPC_S_FP_UNDERFLOW;
337     case NCA_S_FAULT_FP_OVERFLOW:       return RPC_S_FP_OVERFLOW;
338     case NCA_S_FAULT_INVALID_TAG:       return RPC_S_INVALID_TAG;
339     case NCA_S_FAULT_INVALID_BOUND:     return RPC_S_INVALID_BOUND;
340     case NCA_S_RPC_VERSION_MISMATCH:    return RPC_S_PROTOCOL_ERROR;
341     case NCA_S_UNSPEC_REJECT:           return RPC_S_CALL_FAILED_DNE;
342     case NCA_S_BAD_ACTID:               return RPC_S_CALL_FAILED_DNE;
343     case NCA_S_WHO_ARE_YOU_FAILED:      return RPC_S_CALL_FAILED;
344     case NCA_S_MANAGER_NOT_ENTERED:     return RPC_S_CALL_FAILED_DNE;
345     case NCA_S_FAULT_CANCEL:            return RPC_S_CALL_CANCELLED;
346     case NCA_S_FAULT_ILL_INST:          return RPC_S_ADDRESS_ERROR;
347     case NCA_S_FAULT_FP_ERROR:          return RPC_S_FP_OVERFLOW;
348     case NCA_S_FAULT_INT_OVERFLOW:      return RPC_S_ADDRESS_ERROR;
349     case NCA_S_FAULT_UNSPEC:            return RPC_S_CALL_FAILED;
350     case NCA_S_FAULT_PIPE_EMPTY:        return RPC_X_PIPE_EMPTY;
351     case NCA_S_FAULT_PIPE_CLOSED:       return RPC_X_PIPE_CLOSED;
352     case NCA_S_FAULT_PIPE_ORDER:        return RPC_X_WRONG_PIPE_ORDER;
353     case NCA_S_FAULT_PIPE_DISCIPLINE:   return RPC_X_PIPE_DISCIPLINE_ERROR;
354     case NCA_S_FAULT_PIPE_COMM_ERROR:   return RPC_S_COMM_FAILURE;
355     case NCA_S_FAULT_PIPE_MEMORY:       return ERROR_OUTOFMEMORY;
356     case NCA_S_FAULT_CONTEXT_MISMATCH:  return ERROR_INVALID_HANDLE;
357     case NCA_S_FAULT_REMOTE_NO_MEMORY:  return ERROR_NOT_ENOUGH_SERVER_MEMORY;
358     default:                            return status;
359     }
360 }
361
362 static RPC_STATUS RPCRT4_SecurePacket(RpcConnection *Connection,
363     enum secure_packet_direction dir,
364     RpcPktHdr *hdr, unsigned int hdr_size,
365     unsigned char *stub_data, unsigned int stub_data_size,
366     RpcAuthVerifier *auth_hdr,
367     unsigned char *auth_value, unsigned int auth_value_size)
368 {
369     SecBufferDesc message;
370     SecBuffer buffers[4];
371     SECURITY_STATUS sec_status;
372
373     message.ulVersion = SECBUFFER_VERSION;
374     message.cBuffers = sizeof(buffers)/sizeof(buffers[0]);
375     message.pBuffers = buffers;
376
377     buffers[0].cbBuffer = hdr_size;
378     buffers[0].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
379     buffers[0].pvBuffer = hdr;
380     buffers[1].cbBuffer = stub_data_size;
381     buffers[1].BufferType = SECBUFFER_DATA;
382     buffers[1].pvBuffer = stub_data;
383     buffers[2].cbBuffer = sizeof(*auth_hdr);
384     buffers[2].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
385     buffers[2].pvBuffer = auth_hdr;
386     buffers[3].cbBuffer = auth_value_size;
387     buffers[3].BufferType = SECBUFFER_TOKEN;
388     buffers[3].pvBuffer = auth_value;
389
390     if (dir == SECURE_PACKET_SEND)
391     {
392         if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
393         {
394             sec_status = EncryptMessage(&Connection->ctx, 0, &message, 0 /* FIXME */);
395             if (sec_status != SEC_E_OK)
396             {
397                 ERR("EncryptMessage failed with 0x%08x\n", sec_status);
398                 return RPC_S_SEC_PKG_ERROR;
399             }
400         }
401         else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
402         {
403             sec_status = MakeSignature(&Connection->ctx, 0, &message, 0 /* FIXME */);
404             if (sec_status != SEC_E_OK)
405             {
406                 ERR("MakeSignature failed with 0x%08x\n", sec_status);
407                 return RPC_S_SEC_PKG_ERROR;
408             }
409         }
410     }
411     else if (dir == SECURE_PACKET_RECEIVE)
412     {
413         if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
414         {
415             sec_status = DecryptMessage(&Connection->ctx, &message, 0 /* FIXME */, 0);
416             if (sec_status != SEC_E_OK)
417             {
418                 ERR("DecryptMessage failed with 0x%08x\n", sec_status);
419                 return RPC_S_SEC_PKG_ERROR;
420             }
421         }
422         else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
423         {
424             sec_status = VerifySignature(&Connection->ctx, &message, 0 /* FIXME */, NULL);
425             if (sec_status != SEC_E_OK)
426             {
427                 ERR("VerifySignature failed with 0x%08x\n", sec_status);
428                 return RPC_S_SEC_PKG_ERROR;
429             }
430         }
431     }
432
433     return RPC_S_OK;
434 }
435          
436 /***********************************************************************
437  *           RPCRT4_SendAuth (internal)
438  * 
439  * Transmit a packet with authorization data over connection in acceptable fragments.
440  */
441 static RPC_STATUS RPCRT4_SendAuth(RpcConnection *Connection, RpcPktHdr *Header,
442                                   void *Buffer, unsigned int BufferLength,
443                                   const void *Auth, unsigned int AuthLength)
444 {
445   PUCHAR buffer_pos;
446   DWORD hdr_size;
447   LONG count;
448   unsigned char *pkt;
449   LONG alen;
450   RPC_STATUS status;
451
452   RPCRT4_SetThreadCurrentConnection(Connection);
453
454   buffer_pos = Buffer;
455   /* The packet building functions save the packet header size, so we can use it. */
456   hdr_size = Header->common.frag_len;
457   if (AuthLength)
458     Header->common.auth_len = AuthLength;
459   else if (Connection->AuthInfo && packet_has_auth_verifier(Header))
460   {
461     if ((Connection->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(Header))
462       Header->common.auth_len = Connection->encryption_auth_len;
463     else
464       Header->common.auth_len = Connection->signature_auth_len;
465   }
466   else
467     Header->common.auth_len = 0;
468   Header->common.flags |= RPC_FLG_FIRST;
469   Header->common.flags &= ~RPC_FLG_LAST;
470
471   alen = RPC_AUTH_VERIFIER_LEN(&Header->common);
472
473   while (!(Header->common.flags & RPC_FLG_LAST)) {
474     unsigned char auth_pad_len = Header->common.auth_len ? ROUND_UP_AMOUNT(BufferLength, AUTH_ALIGNMENT) : 0;
475     unsigned int pkt_size = BufferLength + hdr_size + alen + auth_pad_len;
476
477     /* decide if we need to split the packet into fragments */
478    if (pkt_size <= Connection->MaxTransmissionSize) {
479      Header->common.flags |= RPC_FLG_LAST;
480      Header->common.frag_len = pkt_size;
481     } else {
482       auth_pad_len = 0;
483       /* make sure packet payload will be a multiple of 16 */
484       Header->common.frag_len =
485         ((Connection->MaxTransmissionSize - hdr_size - alen) & ~(AUTH_ALIGNMENT-1)) +
486         hdr_size + alen;
487     }
488
489     pkt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Header->common.frag_len);
490
491     memcpy(pkt, Header, hdr_size);
492
493     /* fragment consisted of header only and is the last one */
494     if (hdr_size == Header->common.frag_len)
495       goto write;
496
497     memcpy(pkt + hdr_size, buffer_pos, Header->common.frag_len - hdr_size - auth_pad_len - alen);
498
499     /* add the authorization info */
500     if (Connection->AuthInfo && packet_has_auth_verifier(Header))
501     {
502       RpcAuthVerifier *auth_hdr = (RpcAuthVerifier *)&pkt[Header->common.frag_len - alen];
503
504       auth_hdr->auth_type = Connection->AuthInfo->AuthnSvc;
505       auth_hdr->auth_level = Connection->AuthInfo->AuthnLevel;
506       auth_hdr->auth_pad_length = auth_pad_len;
507       auth_hdr->auth_reserved = 0;
508       /* a unique number... */
509       auth_hdr->auth_context_id = (unsigned long)Connection;
510
511       if (AuthLength)
512         memcpy(auth_hdr + 1, Auth, AuthLength);
513       else
514       {
515         status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_SEND,
516             (RpcPktHdr *)pkt, hdr_size,
517             pkt + hdr_size, Header->common.frag_len - hdr_size - alen,
518             auth_hdr,
519             (unsigned char *)(auth_hdr + 1), Header->common.auth_len);
520         if (status != RPC_S_OK)
521         {
522           HeapFree(GetProcessHeap(), 0, pkt);
523           RPCRT4_SetThreadCurrentConnection(NULL);
524           return status;
525         }
526       }
527     }
528
529 write:
530     count = rpcrt4_conn_write(Connection, pkt, Header->common.frag_len);
531     HeapFree(GetProcessHeap(), 0, pkt);
532     if (count<0) {
533       WARN("rpcrt4_conn_write failed (auth)\n");
534       RPCRT4_SetThreadCurrentConnection(NULL);
535       return RPC_S_CALL_FAILED;
536     }
537
538     buffer_pos += Header->common.frag_len - hdr_size - alen - auth_pad_len;
539     BufferLength -= Header->common.frag_len - hdr_size - alen - auth_pad_len;
540     Header->common.flags &= ~RPC_FLG_FIRST;
541   }
542
543   RPCRT4_SetThreadCurrentConnection(NULL);
544   return RPC_S_OK;
545 }
546
547 /***********************************************************************
548  *           RPCRT4_ClientAuthorize (internal)
549  *
550  * Authorize a client connection. A NULL in param signifies a new connection.
551  */
552 static RPC_STATUS RPCRT4_ClientAuthorize(RpcConnection *conn, SecBuffer *in,
553                                          SecBuffer *out)
554 {
555   SECURITY_STATUS r;
556   SecBufferDesc out_desc;
557   SecBufferDesc inp_desc;
558   SecPkgContext_Sizes secctx_sizes;
559   BOOL continue_needed;
560   ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
561                       ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
562
563   if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
564     context_req |= ISC_REQ_INTEGRITY;
565   else if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY)
566     context_req |= ISC_REQ_CONFIDENTIALITY | ISC_REQ_INTEGRITY;
567
568   out->BufferType = SECBUFFER_TOKEN;
569   out->cbBuffer = conn->AuthInfo->cbMaxToken;
570   out->pvBuffer = HeapAlloc(GetProcessHeap(), 0, out->cbBuffer);
571   if (!out->pvBuffer) return ERROR_OUTOFMEMORY;
572
573   out_desc.ulVersion = 0;
574   out_desc.cBuffers = 1;
575   out_desc.pBuffers = out;
576
577   inp_desc.cBuffers = 1;
578   inp_desc.pBuffers = in;
579   inp_desc.ulVersion = 0;
580
581   r = InitializeSecurityContextA(&conn->AuthInfo->cred, in ? &conn->ctx : NULL,
582         NULL, context_req, 0, SECURITY_NETWORK_DREP,
583         in ? &inp_desc : NULL, 0, &conn->ctx, &out_desc, &conn->attr,
584         &conn->exp);
585   if (FAILED(r))
586   {
587       WARN("InitializeSecurityContext failed with error 0x%08x\n", r);
588       goto failed;
589   }
590
591   TRACE("r = 0x%08x, attr = 0x%08x\n", r, conn->attr);
592   continue_needed = ((r == SEC_I_CONTINUE_NEEDED) ||
593                      (r == SEC_I_COMPLETE_AND_CONTINUE));
594
595   if ((r == SEC_I_COMPLETE_NEEDED) || (r == SEC_I_COMPLETE_AND_CONTINUE))
596   {
597       TRACE("complete needed\n");
598       r = CompleteAuthToken(&conn->ctx, &out_desc);
599       if (FAILED(r))
600       {
601           WARN("CompleteAuthToken failed with error 0x%08x\n", r);
602           goto failed;
603       }
604   }
605
606   TRACE("cbBuffer = %ld\n", out->cbBuffer);
607
608   if (!continue_needed)
609   {
610       r = QueryContextAttributesA(&conn->ctx, SECPKG_ATTR_SIZES, &secctx_sizes);
611       if (FAILED(r))
612       {
613           WARN("QueryContextAttributes failed with error 0x%08x\n", r);
614           goto failed;
615       }
616       conn->signature_auth_len = secctx_sizes.cbMaxSignature;
617       conn->encryption_auth_len = secctx_sizes.cbSecurityTrailer;
618   }
619
620   return RPC_S_OK;
621
622 failed:
623   HeapFree(GetProcessHeap(), 0, out->pvBuffer);
624   out->pvBuffer = NULL;
625   return ERROR_ACCESS_DENIED; /* FIXME: is this correct? */
626 }
627
628 /***********************************************************************
629  *           RPCRT4_AuthorizeBinding (internal)
630  */
631 static RPC_STATUS RPCRT_AuthorizeConnection(RpcConnection* conn,
632                                             BYTE *challenge, ULONG count)
633 {
634   SecBuffer inp, out;
635   RpcPktHdr *resp_hdr;
636   RPC_STATUS status;
637
638   TRACE("challenge %s, %d bytes\n", challenge, count);
639
640   inp.BufferType = SECBUFFER_TOKEN;
641   inp.pvBuffer = challenge;
642   inp.cbBuffer = count;
643
644   status = RPCRT4_ClientAuthorize(conn, &inp, &out);
645   if (status) return status;
646
647   resp_hdr = RPCRT4_BuildAuthHeader(NDR_LOCAL_DATA_REPRESENTATION);
648   if (!resp_hdr)
649     return E_OUTOFMEMORY;
650
651   status = RPCRT4_SendAuth(conn, resp_hdr, NULL, 0, out.pvBuffer, out.cbBuffer);
652
653   HeapFree(GetProcessHeap(), 0, out.pvBuffer);
654   RPCRT4_FreeHeader(resp_hdr);
655
656   return status;
657 }
658
659 /***********************************************************************
660  *           RPCRT4_Send (internal)
661  * 
662  * Transmit a packet over connection in acceptable fragments.
663  */
664 RPC_STATUS RPCRT4_Send(RpcConnection *Connection, RpcPktHdr *Header,
665                        void *Buffer, unsigned int BufferLength)
666 {
667   RPC_STATUS r;
668   SecBuffer out;
669
670   if (!Connection->AuthInfo || SecIsValidHandle(&Connection->ctx))
671   {
672     return RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, NULL, 0);
673   }
674
675   /* tack on a negotiate packet */
676   RPCRT4_ClientAuthorize(Connection, NULL, &out);
677   r = RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, out.pvBuffer, out.cbBuffer);
678   HeapFree(GetProcessHeap(), 0, out.pvBuffer);
679
680   return r;
681 }
682
683 /***********************************************************************
684  *           RPCRT4_Receive (internal)
685  * 
686  * Receive a packet from connection and merge the fragments.
687  */
688 RPC_STATUS RPCRT4_Receive(RpcConnection *Connection, RpcPktHdr **Header,
689                           PRPC_MESSAGE pMsg)
690 {
691   RPC_STATUS status;
692   DWORD hdr_length;
693   LONG dwRead;
694   unsigned short first_flag;
695   unsigned long data_length;
696   unsigned long buffer_length;
697   unsigned long auth_length;
698   unsigned char *auth_data = NULL;
699   RpcPktCommonHdr common_hdr;
700
701   *Header = NULL;
702
703   TRACE("(%p, %p, %p)\n", Connection, Header, pMsg);
704
705   RPCRT4_SetThreadCurrentConnection(Connection);
706
707   /* read packet common header */
708   dwRead = rpcrt4_conn_read(Connection, &common_hdr, sizeof(common_hdr));
709   if (dwRead != sizeof(common_hdr)) {
710     WARN("Short read of header, %d bytes\n", dwRead);
711     status = RPC_S_CALL_FAILED;
712     goto fail;
713   }
714
715   /* verify if the header really makes sense */
716   if (common_hdr.rpc_ver != RPC_VER_MAJOR ||
717       common_hdr.rpc_ver_minor != RPC_VER_MINOR) {
718     WARN("unhandled packet version\n");
719     status = RPC_S_PROTOCOL_ERROR;
720     goto fail;
721   }
722
723   hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
724   if (hdr_length == 0) {
725     WARN("header length == 0\n");
726     status = RPC_S_PROTOCOL_ERROR;
727     goto fail;
728   }
729
730   *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
731   memcpy(*Header, &common_hdr, sizeof(common_hdr));
732
733   /* read the rest of packet header */
734   dwRead = rpcrt4_conn_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
735   if (dwRead != hdr_length - sizeof(common_hdr)) {
736     WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
737     status = RPC_S_CALL_FAILED;
738     goto fail;
739   }
740
741   /* read packet body */
742   switch (common_hdr.ptype) {
743   case PKT_RESPONSE:
744     pMsg->BufferLength = (*Header)->response.alloc_hint;
745     break;
746   case PKT_REQUEST:
747     pMsg->BufferLength = (*Header)->request.alloc_hint;
748     break;
749   default:
750     pMsg->BufferLength = common_hdr.frag_len - hdr_length - RPC_AUTH_VERIFIER_LEN(&common_hdr);
751   }
752
753   TRACE("buffer length = %u\n", pMsg->BufferLength);
754
755   status = I_RpcGetBuffer(pMsg);
756   if (status != RPC_S_OK) goto fail;
757
758   first_flag = RPC_FLG_FIRST;
759   auth_length = common_hdr.auth_len;
760   if (auth_length) {
761     auth_data = HeapAlloc(GetProcessHeap(), 0, RPC_AUTH_VERIFIER_LEN(&common_hdr));
762     if (!auth_data) {
763       status = RPC_S_OUT_OF_RESOURCES;
764       goto fail;
765     }
766   }
767   buffer_length = 0;
768   while (TRUE)
769   {
770     unsigned int header_auth_len = RPC_AUTH_VERIFIER_LEN(&(*Header)->common);
771
772     /* verify header fields */
773
774     if (((*Header)->common.frag_len < hdr_length) ||
775         ((*Header)->common.frag_len - hdr_length < header_auth_len)) {
776       WARN("frag_len %d too small for hdr_length %d and auth_len %d\n",
777         (*Header)->common.frag_len, hdr_length, header_auth_len);
778       status = RPC_S_PROTOCOL_ERROR;
779       goto fail;
780     }
781
782     if ((*Header)->common.auth_len != auth_length) {
783       WARN("auth_len header field changed from %ld to %d\n",
784         auth_length, (*Header)->common.auth_len);
785       status = RPC_S_PROTOCOL_ERROR;
786       goto fail;
787     }
788
789     if (((*Header)->common.flags & RPC_FLG_FIRST) != first_flag) {
790       TRACE("invalid packet flags\n");
791       status = RPC_S_PROTOCOL_ERROR;
792       goto fail;
793     }
794
795     data_length = (*Header)->common.frag_len - hdr_length - header_auth_len;
796     if (data_length + buffer_length > pMsg->BufferLength) {
797       TRACE("allocation hint exceeded, new buffer length = %ld\n",
798         data_length + buffer_length);
799       pMsg->BufferLength = data_length + buffer_length;
800       status = I_RpcReAllocateBuffer(pMsg);
801       if (status != RPC_S_OK) goto fail;
802     }
803
804     if (data_length == 0) dwRead = 0; else
805     dwRead = rpcrt4_conn_read(Connection,
806         (unsigned char *)pMsg->Buffer + buffer_length, data_length);
807     if (dwRead != data_length) {
808       WARN("bad data length, %d/%ld\n", dwRead, data_length);
809       status = RPC_S_CALL_FAILED;
810       goto fail;
811     }
812
813     if (header_auth_len) {
814       if (header_auth_len < sizeof(RpcAuthVerifier)) {
815         WARN("bad auth verifier length %d\n", header_auth_len);
816         status = RPC_S_PROTOCOL_ERROR;
817         goto fail;
818       }
819
820       /* FIXME: we should accumulate authentication data for the bind,
821        * bind_ack, alter_context and alter_context_response if necessary.
822        * however, the details of how this is done is very sketchy in the
823        * DCE/RPC spec. for all other packet types that have authentication
824        * verifier data then it is just duplicated in all the fragments */
825       dwRead = rpcrt4_conn_read(Connection, auth_data, header_auth_len);
826       if (dwRead != header_auth_len) {
827         WARN("bad authentication data length, %d/%d\n", dwRead,
828           header_auth_len);
829         status = RPC_S_CALL_FAILED;
830         goto fail;
831       }
832
833       /* these packets are handled specially, not by the generic SecurePacket
834        * function */
835       if ((common_hdr.ptype != PKT_BIND) &&
836           (common_hdr.ptype != PKT_BIND_ACK) &&
837           (common_hdr.ptype != PKT_AUTH3))
838       {
839         status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_RECEIVE,
840             *Header, hdr_length,
841             (unsigned char *)pMsg->Buffer + buffer_length, data_length,
842             (RpcAuthVerifier *)auth_data,
843             (unsigned char *)auth_data + sizeof(RpcAuthVerifier),
844             header_auth_len - sizeof(RpcAuthVerifier));
845         if (status != RPC_S_OK) goto fail;
846       }
847     }
848
849     buffer_length += data_length;
850     if (!((*Header)->common.flags & RPC_FLG_LAST)) {
851       TRACE("next header\n");
852
853       /* read the header of next packet */
854       dwRead = rpcrt4_conn_read(Connection, *Header, hdr_length);
855       if (dwRead != hdr_length) {
856         WARN("invalid packet header size (%d)\n", dwRead);
857         status = RPC_S_CALL_FAILED;
858         goto fail;
859       }
860
861       first_flag = 0;
862     } else {
863       break;
864     }
865   }
866   pMsg->BufferLength = buffer_length;
867
868   /* respond to authorization request */
869   if (common_hdr.ptype == PKT_BIND_ACK && auth_length > sizeof(RpcAuthVerifier))
870   {
871     status = RPCRT_AuthorizeConnection(Connection,
872                                        auth_data + sizeof(RpcAuthVerifier),
873                                        auth_length);
874     if (status)
875         goto fail;
876   }
877
878   /* success */
879   status = RPC_S_OK;
880
881 fail:
882   RPCRT4_SetThreadCurrentConnection(NULL);
883   if (status != RPC_S_OK) {
884     RPCRT4_FreeHeader(*Header);
885     *Header = NULL;
886   }
887   HeapFree(GetProcessHeap(), 0, auth_data);
888   return status;
889 }
890
891 /***********************************************************************
892  *           I_RpcGetBuffer [RPCRT4.@]
893  *
894  * Allocates a buffer for use by I_RpcSend or I_RpcSendReceive and binds to the
895  * server interface.
896  *
897  * PARAMS
898  *  pMsg [I/O] RPC message information.
899  *
900  * RETURNS
901  *  Success: RPC_S_OK.
902  *  Failure: RPC_S_INVALID_BINDING if pMsg->Handle is invalid.
903  *           RPC_S_SERVER_UNAVAILABLE if unable to connect to server.
904  *           ERROR_OUTOFMEMORY if buffer allocation failed.
905  *
906  * NOTES
907  *  The pMsg->BufferLength field determines the size of the buffer to allocate,
908  *  in bytes.
909  *
910  *  Use I_RpcFreeBuffer() to unbind from the server and free the message buffer.
911  *
912  * SEE ALSO
913  *  I_RpcFreeBuffer(), I_RpcSend(), I_RpcReceive(), I_RpcSendReceive().
914  */
915 RPC_STATUS WINAPI I_RpcGetBuffer(PRPC_MESSAGE pMsg)
916 {
917   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
918   /* FIXME: pfnAllocate? */
919   pMsg->Buffer = HeapAlloc(GetProcessHeap(), 0, pMsg->BufferLength);
920
921   TRACE("Buffer=%p\n", pMsg->Buffer);
922   /* FIXME: which errors to return? */
923   return pMsg->Buffer ? S_OK : E_OUTOFMEMORY;
924 }
925
926 /***********************************************************************
927  *           I_RpcReAllocateBuffer (internal)
928  */
929 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg)
930 {
931   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
932   pMsg->Buffer = HeapReAlloc(GetProcessHeap(), 0, pMsg->Buffer, pMsg->BufferLength);
933
934   TRACE("Buffer=%p\n", pMsg->Buffer);
935   return pMsg->Buffer ? RPC_S_OK : RPC_S_OUT_OF_RESOURCES;
936 }
937
938 /***********************************************************************
939  *           I_RpcFreeBuffer [RPCRT4.@]
940  *
941  * Frees a buffer allocated by I_RpcGetBuffer or I_RpcReceive and unbinds from
942  * the server interface.
943  *
944  * PARAMS
945  *  pMsg [I/O] RPC message information.
946  *
947  * RETURNS
948  *  RPC_S_OK.
949  *
950  * SEE ALSO
951  *  I_RpcGetBuffer(), I_RpcReceive().
952  */
953 RPC_STATUS WINAPI I_RpcFreeBuffer(PRPC_MESSAGE pMsg)
954 {
955   TRACE("(%p) Buffer=%p\n", pMsg, pMsg->Buffer);
956   /* FIXME: pfnFree? */
957   HeapFree(GetProcessHeap(), 0, pMsg->Buffer);
958   pMsg->Buffer = NULL;
959   return S_OK;
960 }
961
962 /***********************************************************************
963  *           I_RpcSend [RPCRT4.@]
964  *
965  * Sends a message to the server.
966  *
967  * PARAMS
968  *  pMsg [I/O] RPC message information.
969  *
970  * RETURNS
971  *  Unknown.
972  *
973  * NOTES
974  *  The buffer must have been allocated with I_RpcGetBuffer().
975  *
976  * SEE ALSO
977  *  I_RpcGetBuffer(), I_RpcReceive(), I_RpcSendReceive().
978  */
979 RPC_STATUS WINAPI I_RpcSend(PRPC_MESSAGE pMsg)
980 {
981   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
982   RpcConnection* conn;
983   RPC_CLIENT_INTERFACE* cif = NULL;
984   RPC_STATUS status;
985   RpcPktHdr *hdr;
986
987   TRACE("(%p)\n", pMsg);
988   if (!bind || bind->server) return RPC_S_INVALID_BINDING;
989
990   cif = pMsg->RpcInterfaceInformation;
991   if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
992
993   if (!bind->Endpoint || !bind->Endpoint[0])
994   {
995     TRACE("automatically resolving partially bound binding\n");
996     status = RpcEpResolveBinding(bind, cif);
997     if (status != RPC_S_OK) return status;
998   }
999
1000   status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
1001                               &cif->InterfaceId);
1002   if (status != RPC_S_OK) return status;
1003
1004   hdr = RPCRT4_BuildRequestHeader(pMsg->DataRepresentation,
1005                                   pMsg->BufferLength, pMsg->ProcNum,
1006                                   &bind->ObjectUuid);
1007   if (!hdr)
1008   {
1009     RPCRT4_CloseBinding(bind, conn);
1010     return ERROR_OUTOFMEMORY;
1011   }
1012   hdr->common.call_id = conn->NextCallId++;
1013
1014   status = RPCRT4_Send(conn, hdr, pMsg->Buffer, pMsg->BufferLength);
1015
1016   RPCRT4_FreeHeader(hdr);
1017
1018   /* save the connection, so the response can be read from it */
1019   pMsg->ReservedForRuntime = conn;
1020   return status;
1021 }
1022
1023 /* is this status something that the server can't recover from? */
1024 static inline BOOL is_hard_error(RPC_STATUS status)
1025 {
1026     switch (status)
1027     {
1028     case 0: /* user-defined fault */
1029     case ERROR_ACCESS_DENIED:
1030     case ERROR_INVALID_PARAMETER:
1031     case RPC_S_PROTOCOL_ERROR:
1032     case RPC_S_CALL_FAILED:
1033     case RPC_S_CALL_FAILED_DNE:
1034     case RPC_S_SEC_PKG_ERROR:
1035         return TRUE;
1036     default:
1037         return FALSE;
1038     }
1039 }
1040
1041 /***********************************************************************
1042  *           I_RpcReceive [RPCRT4.@]
1043  */
1044 RPC_STATUS WINAPI I_RpcReceive(PRPC_MESSAGE pMsg)
1045 {
1046   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
1047   RpcConnection* conn;
1048   RPC_CLIENT_INTERFACE* cif = NULL;
1049   RPC_SERVER_INTERFACE* sif = NULL;
1050   RPC_STATUS status;
1051   RpcPktHdr *hdr = NULL;
1052
1053   TRACE("(%p)\n", pMsg);
1054   if (!bind) return RPC_S_INVALID_BINDING;
1055
1056   if (pMsg->ReservedForRuntime) {
1057     conn = pMsg->ReservedForRuntime;
1058     pMsg->ReservedForRuntime = NULL;
1059   } else {
1060     if (bind->server) {
1061       sif = pMsg->RpcInterfaceInformation;
1062       if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
1063       status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
1064                                   &sif->InterfaceId);
1065     } else {
1066       cif = pMsg->RpcInterfaceInformation;
1067       if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
1068
1069       if (!bind->Endpoint || !bind->Endpoint[0])
1070       {
1071         TRACE("automatically resolving partially bound binding\n");
1072         status = RpcEpResolveBinding(bind, cif);
1073         if (status != RPC_S_OK) return status;
1074       }
1075
1076       status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
1077                                   &cif->InterfaceId);
1078     }
1079     if (status != RPC_S_OK) return status;
1080   }
1081
1082   status = RPCRT4_Receive(conn, &hdr, pMsg);
1083   if (status != RPC_S_OK) {
1084     WARN("receive failed with error %lx\n", status);
1085     goto fail;
1086   }
1087
1088   switch (hdr->common.ptype) {
1089   case PKT_RESPONSE:
1090     if (bind->server) {
1091         status = RPC_S_PROTOCOL_ERROR;
1092         goto fail;
1093     }
1094     break;
1095   case PKT_REQUEST:
1096     if (!bind->server) {
1097         status = RPC_S_PROTOCOL_ERROR;
1098         goto fail;
1099     }
1100     break;
1101   case PKT_FAULT:
1102     ERR ("we got fault packet with status 0x%lx\n", hdr->fault.status);
1103     status = NCA2RPC_STATUS(hdr->fault.status);
1104     if (is_hard_error(status))
1105         goto fail;
1106     break;
1107   default:
1108     WARN("bad packet type %d\n", hdr->common.ptype);
1109     status = RPC_S_PROTOCOL_ERROR;
1110     goto fail;
1111   }
1112
1113   /* success */
1114   RPCRT4_CloseBinding(bind, conn);
1115   RPCRT4_FreeHeader(hdr);
1116   return status;
1117
1118 fail:
1119   RPCRT4_FreeHeader(hdr);
1120   RPCRT4_DestroyConnection(conn);
1121   return status;
1122 }
1123
1124 /***********************************************************************
1125  *           I_RpcSendReceive [RPCRT4.@]
1126  *
1127  * Sends a message to the server and receives the response.
1128  *
1129  * PARAMS
1130  *  pMsg [I/O] RPC message information.
1131  *
1132  * RETURNS
1133  *  Success: RPC_S_OK.
1134  *  Failure: Any error code.
1135  *
1136  * NOTES
1137  *  The buffer must have been allocated with I_RpcGetBuffer().
1138  *
1139  * SEE ALSO
1140  *  I_RpcGetBuffer(), I_RpcSend(), I_RpcReceive().
1141  */
1142 RPC_STATUS WINAPI I_RpcSendReceive(PRPC_MESSAGE pMsg)
1143 {
1144   RPC_STATUS status;
1145   RPC_MESSAGE original_message;
1146
1147   TRACE("(%p)\n", pMsg);
1148
1149   original_message = *pMsg;
1150   status = I_RpcSend(pMsg);
1151   if (status == RPC_S_OK)
1152     status = I_RpcReceive(pMsg);
1153   /* free the buffer replaced by a new buffer in I_RpcReceive */
1154   if (status == RPC_S_OK)
1155     I_RpcFreeBuffer(&original_message);
1156   return status;
1157 }