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