rpcrt4: Add structure definition for RPC AUTH3 packet and use the size of this on...
[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 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg);
55
56 DWORD RPCRT4_GetHeaderSize(const RpcPktHdr *Header)
57 {
58   static const DWORD header_sizes[] = {
59     sizeof(Header->request), 0, sizeof(Header->response),
60     sizeof(Header->fault), 0, 0, 0, 0, 0, 0, 0, sizeof(Header->bind),
61     sizeof(Header->bind_ack), sizeof(Header->bind_nack),
62     0, 0, sizeof(Header->auth3), 0, 0, 0, sizeof(Header->http)
63   };
64   ULONG ret = 0;
65   
66   if (Header->common.ptype < sizeof(header_sizes) / sizeof(header_sizes[0])) {
67     ret = header_sizes[Header->common.ptype];
68     if (ret == 0)
69       FIXME("unhandled packet type %u\n", Header->common.ptype);
70     if (Header->common.flags & RPC_FLG_OBJECT_UUID)
71       ret += sizeof(UUID);
72   } else {
73     WARN("invalid packet type %u\n", Header->common.ptype);
74   }
75
76   return ret;
77 }
78
79 static int packet_has_body(const RpcPktHdr *Header)
80 {
81     return (Header->common.ptype == PKT_FAULT) ||
82            (Header->common.ptype == PKT_REQUEST) ||
83            (Header->common.ptype == PKT_RESPONSE);
84 }
85
86 static int packet_has_auth_verifier(const RpcPktHdr *Header)
87 {
88     return !(Header->common.ptype == PKT_BIND_NACK) &&
89            !(Header->common.ptype == PKT_SHUTDOWN);
90 }
91
92 static int packet_does_auth_negotiation(const RpcPktHdr *Header)
93 {
94     switch (Header->common.ptype)
95     {
96     case PKT_BIND:
97     case PKT_BIND_ACK:
98     case PKT_AUTH3:
99     case PKT_ALTER_CONTEXT:
100     case PKT_ALTER_CONTEXT_RESP:
101         return TRUE;
102     default:
103         return FALSE;
104     }
105 }
106
107 static VOID RPCRT4_BuildCommonHeader(RpcPktHdr *Header, unsigned char PacketType,
108                                      ULONG DataRepresentation)
109 {
110   Header->common.rpc_ver = RPC_VER_MAJOR;
111   Header->common.rpc_ver_minor = RPC_VER_MINOR;
112   Header->common.ptype = PacketType;
113   Header->common.drep[0] = LOBYTE(LOWORD(DataRepresentation));
114   Header->common.drep[1] = HIBYTE(LOWORD(DataRepresentation));
115   Header->common.drep[2] = LOBYTE(HIWORD(DataRepresentation));
116   Header->common.drep[3] = HIBYTE(HIWORD(DataRepresentation));
117   Header->common.auth_len = 0;
118   Header->common.call_id = 1;
119   Header->common.flags = 0;
120   /* Flags and fragment length are computed in RPCRT4_Send. */
121 }                              
122
123 static RpcPktHdr *RPCRT4_BuildRequestHeader(ULONG DataRepresentation,
124                                      ULONG BufferLength,
125                                      unsigned short ProcNum,
126                                      UUID *ObjectUuid)
127 {
128   RpcPktHdr *header;
129   BOOL has_object;
130   RPC_STATUS status;
131
132   has_object = (ObjectUuid != NULL && !UuidIsNil(ObjectUuid, &status));
133   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
134                      sizeof(header->request) + (has_object ? sizeof(UUID) : 0));
135   if (header == NULL) {
136     return NULL;
137   }
138
139   RPCRT4_BuildCommonHeader(header, PKT_REQUEST, DataRepresentation);
140   header->common.frag_len = sizeof(header->request);
141   header->request.alloc_hint = BufferLength;
142   header->request.context_id = 0;
143   header->request.opnum = ProcNum;
144   if (has_object) {
145     header->common.flags |= RPC_FLG_OBJECT_UUID;
146     header->common.frag_len += sizeof(UUID);
147     memcpy(&header->request + 1, ObjectUuid, sizeof(UUID));
148   }
149
150   return header;
151 }
152
153 RpcPktHdr *RPCRT4_BuildResponseHeader(ULONG DataRepresentation, ULONG BufferLength)
154 {
155   RpcPktHdr *header;
156
157   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->response));
158   if (header == NULL) {
159     return NULL;
160   }
161
162   RPCRT4_BuildCommonHeader(header, PKT_RESPONSE, DataRepresentation);
163   header->common.frag_len = sizeof(header->response);
164   header->response.alloc_hint = BufferLength;
165
166   return header;
167 }
168
169 RpcPktHdr *RPCRT4_BuildFaultHeader(ULONG DataRepresentation, RPC_STATUS Status)
170 {
171   RpcPktHdr *header;
172
173   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->fault));
174   if (header == NULL) {
175     return NULL;
176   }
177
178   RPCRT4_BuildCommonHeader(header, PKT_FAULT, DataRepresentation);
179   header->common.frag_len = sizeof(header->fault);
180   header->fault.status = Status;
181
182   return header;
183 }
184
185 RpcPktHdr *RPCRT4_BuildBindHeader(ULONG DataRepresentation,
186                                   unsigned short MaxTransmissionSize,
187                                   unsigned short MaxReceiveSize,
188                                   ULONG  AssocGroupId,
189                                   const RPC_SYNTAX_IDENTIFIER *AbstractId,
190                                   const RPC_SYNTAX_IDENTIFIER *TransferId)
191 {
192   RpcPktHdr *header;
193   RpcContextElement *ctxt_elem;
194
195   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
196                      sizeof(header->bind) + FIELD_OFFSET(RpcContextElement, transfer_syntaxes[1]));
197   if (header == NULL) {
198     return NULL;
199   }
200   ctxt_elem = (RpcContextElement *)(&header->bind + 1);
201
202   RPCRT4_BuildCommonHeader(header, PKT_BIND, DataRepresentation);
203   header->common.frag_len = sizeof(header->bind) + FIELD_OFFSET(RpcContextElement, transfer_syntaxes[1]);
204   header->bind.max_tsize = MaxTransmissionSize;
205   header->bind.max_rsize = MaxReceiveSize;
206   header->bind.assoc_gid = AssocGroupId;
207   header->bind.num_elements = 1;
208   ctxt_elem->num_syntaxes = 1;
209   ctxt_elem->abstract_syntax = *AbstractId;
210   ctxt_elem->transfer_syntaxes[0] = *TransferId;
211
212   return header;
213 }
214
215 static RpcPktHdr *RPCRT4_BuildAuthHeader(ULONG DataRepresentation)
216 {
217   RpcPktHdr *header;
218
219   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
220                      sizeof(header->auth3));
221   if (header == NULL)
222     return NULL;
223
224   RPCRT4_BuildCommonHeader(header, PKT_AUTH3, DataRepresentation);
225   header->common.frag_len = sizeof(header->auth3);
226
227   return header;
228 }
229
230 RpcPktHdr *RPCRT4_BuildBindNackHeader(ULONG DataRepresentation,
231                                       unsigned char RpcVersion,
232                                       unsigned char RpcVersionMinor,
233                                       unsigned short RejectReason)
234 {
235   RpcPktHdr *header;
236
237   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, FIELD_OFFSET(RpcPktHdr, bind_nack.protocols[1]));
238   if (header == NULL) {
239     return NULL;
240   }
241
242   RPCRT4_BuildCommonHeader(header, PKT_BIND_NACK, DataRepresentation);
243   header->common.frag_len = FIELD_OFFSET(RpcPktHdr, bind_nack.protocols[1]);
244   header->bind_nack.reject_reason = RejectReason;
245   header->bind_nack.protocols_count = 1;
246   header->bind_nack.protocols[0].rpc_ver = RpcVersion;
247   header->bind_nack.protocols[0].rpc_ver_minor = RpcVersionMinor;
248
249   return header;
250 }
251
252 RpcPktHdr *RPCRT4_BuildBindAckHeader(ULONG DataRepresentation,
253                                      unsigned short MaxTransmissionSize,
254                                      unsigned short MaxReceiveSize,
255                                      ULONG AssocGroupId,
256                                      LPCSTR ServerAddress,
257                                      unsigned char ResultCount,
258                                      const RpcResult *Results)
259 {
260   RpcPktHdr *header;
261   ULONG header_size;
262   RpcAddressString *server_address;
263   RpcResultList *results;
264
265   header_size = sizeof(header->bind_ack) +
266                 ROUND_UP(FIELD_OFFSET(RpcAddressString, string[strlen(ServerAddress) + 1]), 4) +
267                 FIELD_OFFSET(RpcResultList, results[ResultCount]);
268
269   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, header_size);
270   if (header == NULL) {
271     return NULL;
272   }
273
274   RPCRT4_BuildCommonHeader(header, PKT_BIND_ACK, DataRepresentation);
275   header->common.frag_len = header_size;
276   header->bind_ack.max_tsize = MaxTransmissionSize;
277   header->bind_ack.max_rsize = MaxReceiveSize;
278   header->bind_ack.assoc_gid = AssocGroupId;
279   server_address = (RpcAddressString*)(&header->bind_ack + 1);
280   server_address->length = strlen(ServerAddress) + 1;
281   strcpy(server_address->string, ServerAddress);
282   /* results is 4-byte aligned */
283   results = (RpcResultList*)((ULONG_PTR)server_address + ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4));
284   results->num_results = ResultCount;
285   memcpy(&results->results[0], Results, ResultCount * sizeof(*Results));
286
287   return header;
288 }
289
290 RpcPktHdr *RPCRT4_BuildHttpHeader(ULONG DataRepresentation,
291                                   unsigned short flags,
292                                   unsigned short num_data_items,
293                                   unsigned int payload_size)
294 {
295   RpcPktHdr *header;
296
297   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->http) + payload_size);
298   if (header == NULL) {
299       ERR("failed to allocate memory\n");
300     return NULL;
301   }
302
303   RPCRT4_BuildCommonHeader(header, PKT_HTTP, DataRepresentation);
304   /* since the packet isn't current sent using RPCRT4_Send, set the flags
305    * manually here */
306   header->common.flags = RPC_FLG_FIRST|RPC_FLG_LAST;
307   header->common.call_id = 0;
308   header->common.frag_len = sizeof(header->http) + payload_size;
309   header->http.flags = flags;
310   header->http.num_data_items = num_data_items;
311
312   return header;
313 }
314
315 #define WRITE_HTTP_PAYLOAD_FIELD_UINT32(payload, type, value) \
316     do { \
317         *(unsigned int *)(payload) = (type); \
318         (payload) += 4; \
319         *(unsigned int *)(payload) = (value); \
320         (payload) += 4; \
321     } while (0)
322
323 #define WRITE_HTTP_PAYLOAD_FIELD_UUID(payload, type, uuid) \
324     do { \
325         *(unsigned int *)(payload) = (type); \
326         (payload) += 4; \
327         *(UUID *)(payload) = (uuid); \
328         (payload) += sizeof(UUID); \
329     } while (0)
330
331 #define WRITE_HTTP_PAYLOAD_FIELD_FLOW_CONTROL(payload, bytes_transmitted, flow_control_increment, uuid) \
332     do { \
333         *(unsigned int *)(payload) = 0x00000001; \
334         (payload) += 4; \
335         *(unsigned int *)(payload) = (bytes_transmitted); \
336         (payload) += 4; \
337         *(unsigned int *)(payload) = (flow_control_increment); \
338         (payload) += 4; \
339         *(UUID *)(payload) = (uuid); \
340         (payload) += sizeof(UUID); \
341     } while (0)
342
343 RpcPktHdr *RPCRT4_BuildHttpConnectHeader(unsigned short flags, int out_pipe,
344                                          const UUID *connection_uuid,
345                                          const UUID *pipe_uuid,
346                                          const UUID *association_uuid)
347 {
348   RpcPktHdr *header;
349   unsigned int size;
350   char *payload;
351
352   size = 8 + 4 + sizeof(UUID) + 4 + sizeof(UUID) + 8;
353   if (!out_pipe)
354     size += 8 + 4 + sizeof(UUID);
355
356   header = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, flags,
357                                   out_pipe ? 4 : 6, size);
358   if (!header) return NULL;
359   payload = (char *)(&header->http+1);
360
361   /* FIXME: what does this part of the payload do? */
362   WRITE_HTTP_PAYLOAD_FIELD_UINT32(payload, 0x00000006, 0x00000001);
363
364   WRITE_HTTP_PAYLOAD_FIELD_UUID(payload, 0x00000003, *connection_uuid);
365   WRITE_HTTP_PAYLOAD_FIELD_UUID(payload, 0x00000003, *pipe_uuid);
366
367   if (out_pipe)
368     /* FIXME: what does this part of the payload do? */
369     WRITE_HTTP_PAYLOAD_FIELD_UINT32(payload, 0x00000000, 0x00010000);
370   else
371   {
372     /* FIXME: what does this part of the payload do? */
373     WRITE_HTTP_PAYLOAD_FIELD_UINT32(payload, 0x00000004, 0x40000000);
374     /* FIXME: what does this part of the payload do? */
375     WRITE_HTTP_PAYLOAD_FIELD_UINT32(payload, 0x00000005, 0x000493e0);
376
377     WRITE_HTTP_PAYLOAD_FIELD_UUID(payload, 0x0000000c, *association_uuid);
378   }
379
380   return header;
381 }
382
383 RpcPktHdr *RPCRT4_BuildHttpFlowControlHeader(BOOL server, ULONG bytes_transmitted,
384                                              ULONG flow_control_increment,
385                                              const UUID *pipe_uuid)
386 {
387   RpcPktHdr *header;
388   char *payload;
389
390   header = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x2, 2,
391                                   5 * sizeof(ULONG) + sizeof(UUID));
392   if (!header) return NULL;
393   payload = (char *)(&header->http+1);
394
395   WRITE_HTTP_PAYLOAD_FIELD_UINT32(payload, 0x0000000d, (server ? 0x0 : 0x3));
396
397   WRITE_HTTP_PAYLOAD_FIELD_FLOW_CONTROL(payload, bytes_transmitted,
398                                         flow_control_increment, *pipe_uuid);
399   return header;
400 }
401
402 VOID RPCRT4_FreeHeader(RpcPktHdr *Header)
403 {
404   HeapFree(GetProcessHeap(), 0, Header);
405 }
406
407 NCA_STATUS RPC2NCA_STATUS(RPC_STATUS status)
408 {
409     switch (status)
410     {
411     case ERROR_INVALID_HANDLE:              return NCA_S_FAULT_CONTEXT_MISMATCH;
412     case ERROR_OUTOFMEMORY:                 return NCA_S_FAULT_REMOTE_NO_MEMORY;
413     case RPC_S_NOT_LISTENING:               return NCA_S_SERVER_TOO_BUSY;
414     case RPC_S_UNKNOWN_IF:                  return NCA_S_UNK_IF;
415     case RPC_S_SERVER_TOO_BUSY:             return NCA_S_SERVER_TOO_BUSY;
416     case RPC_S_CALL_FAILED:                 return NCA_S_FAULT_UNSPEC;
417     case RPC_S_CALL_FAILED_DNE:             return NCA_S_MANAGER_NOT_ENTERED;
418     case RPC_S_PROTOCOL_ERROR:              return NCA_S_PROTO_ERROR;
419     case RPC_S_UNSUPPORTED_TYPE:            return NCA_S_UNSUPPORTED_TYPE;
420     case RPC_S_INVALID_TAG:                 return NCA_S_FAULT_INVALID_TAG;
421     case RPC_S_INVALID_BOUND:               return NCA_S_FAULT_INVALID_BOUND;
422     case RPC_S_PROCNUM_OUT_OF_RANGE:        return NCA_S_OP_RNG_ERROR;
423     case RPC_X_SS_HANDLES_MISMATCH:         return NCA_S_FAULT_CONTEXT_MISMATCH;
424     case RPC_S_CALL_CANCELLED:              return NCA_S_FAULT_CANCEL;
425     case RPC_S_COMM_FAILURE:                return NCA_S_COMM_FAILURE;
426     case RPC_X_WRONG_PIPE_ORDER:            return NCA_S_FAULT_PIPE_ORDER;
427     case RPC_X_PIPE_CLOSED:                 return NCA_S_FAULT_PIPE_CLOSED;
428     case RPC_X_PIPE_DISCIPLINE_ERROR:       return NCA_S_FAULT_PIPE_DISCIPLINE;
429     case RPC_X_PIPE_EMPTY:                  return NCA_S_FAULT_PIPE_EMPTY;
430     case STATUS_FLOAT_DIVIDE_BY_ZERO:       return NCA_S_FAULT_FP_DIV_ZERO;
431     case STATUS_FLOAT_INVALID_OPERATION:    return NCA_S_FAULT_FP_ERROR;
432     case STATUS_FLOAT_OVERFLOW:             return NCA_S_FAULT_FP_OVERFLOW;
433     case STATUS_FLOAT_UNDERFLOW:            return NCA_S_FAULT_FP_UNDERFLOW;
434     case STATUS_INTEGER_DIVIDE_BY_ZERO:     return NCA_S_FAULT_INT_DIV_BY_ZERO;
435     case STATUS_INTEGER_OVERFLOW:           return NCA_S_FAULT_INT_OVERFLOW;
436     default:                                return status;
437     }
438 }
439
440 static RPC_STATUS NCA2RPC_STATUS(NCA_STATUS status)
441 {
442     switch (status)
443     {
444     case NCA_S_COMM_FAILURE:            return RPC_S_COMM_FAILURE;
445     case NCA_S_OP_RNG_ERROR:            return RPC_S_PROCNUM_OUT_OF_RANGE;
446     case NCA_S_UNK_IF:                  return RPC_S_UNKNOWN_IF;
447     case NCA_S_YOU_CRASHED:             return RPC_S_CALL_FAILED;
448     case NCA_S_PROTO_ERROR:             return RPC_S_PROTOCOL_ERROR;
449     case NCA_S_OUT_ARGS_TOO_BIG:        return ERROR_NOT_ENOUGH_SERVER_MEMORY;
450     case NCA_S_SERVER_TOO_BUSY:         return RPC_S_SERVER_TOO_BUSY;
451     case NCA_S_UNSUPPORTED_TYPE:        return RPC_S_UNSUPPORTED_TYPE;
452     case NCA_S_FAULT_INT_DIV_BY_ZERO:   return RPC_S_ZERO_DIVIDE;
453     case NCA_S_FAULT_ADDR_ERROR:        return RPC_S_ADDRESS_ERROR;
454     case NCA_S_FAULT_FP_DIV_ZERO:       return RPC_S_FP_DIV_ZERO;
455     case NCA_S_FAULT_FP_UNDERFLOW:      return RPC_S_FP_UNDERFLOW;
456     case NCA_S_FAULT_FP_OVERFLOW:       return RPC_S_FP_OVERFLOW;
457     case NCA_S_FAULT_INVALID_TAG:       return RPC_S_INVALID_TAG;
458     case NCA_S_FAULT_INVALID_BOUND:     return RPC_S_INVALID_BOUND;
459     case NCA_S_RPC_VERSION_MISMATCH:    return RPC_S_PROTOCOL_ERROR;
460     case NCA_S_UNSPEC_REJECT:           return RPC_S_CALL_FAILED_DNE;
461     case NCA_S_BAD_ACTID:               return RPC_S_CALL_FAILED_DNE;
462     case NCA_S_WHO_ARE_YOU_FAILED:      return RPC_S_CALL_FAILED;
463     case NCA_S_MANAGER_NOT_ENTERED:     return RPC_S_CALL_FAILED_DNE;
464     case NCA_S_FAULT_CANCEL:            return RPC_S_CALL_CANCELLED;
465     case NCA_S_FAULT_ILL_INST:          return RPC_S_ADDRESS_ERROR;
466     case NCA_S_FAULT_FP_ERROR:          return RPC_S_FP_OVERFLOW;
467     case NCA_S_FAULT_INT_OVERFLOW:      return RPC_S_ADDRESS_ERROR;
468     case NCA_S_FAULT_UNSPEC:            return RPC_S_CALL_FAILED;
469     case NCA_S_FAULT_PIPE_EMPTY:        return RPC_X_PIPE_EMPTY;
470     case NCA_S_FAULT_PIPE_CLOSED:       return RPC_X_PIPE_CLOSED;
471     case NCA_S_FAULT_PIPE_ORDER:        return RPC_X_WRONG_PIPE_ORDER;
472     case NCA_S_FAULT_PIPE_DISCIPLINE:   return RPC_X_PIPE_DISCIPLINE_ERROR;
473     case NCA_S_FAULT_PIPE_COMM_ERROR:   return RPC_S_COMM_FAILURE;
474     case NCA_S_FAULT_PIPE_MEMORY:       return ERROR_OUTOFMEMORY;
475     case NCA_S_FAULT_CONTEXT_MISMATCH:  return ERROR_INVALID_HANDLE;
476     case NCA_S_FAULT_REMOTE_NO_MEMORY:  return ERROR_NOT_ENOUGH_SERVER_MEMORY;
477     default:                            return status;
478     }
479 }
480
481 /* assumes the common header fields have already been validated */
482 BOOL RPCRT4_IsValidHttpPacket(RpcPktHdr *hdr, unsigned char *data,
483                               unsigned short data_len)
484 {
485   unsigned short i;
486   BYTE *p = data;
487
488   for (i = 0; i < hdr->http.num_data_items; i++)
489   {
490     ULONG type;
491
492     if (data_len < sizeof(ULONG))
493       return FALSE;
494
495     type = *(ULONG *)p;
496     p += sizeof(ULONG);
497     data_len -= sizeof(ULONG);
498
499     switch (type)
500     {
501       case 0x3:
502       case 0xc:
503         if (data_len < sizeof(GUID))
504           return FALSE;
505         p += sizeof(GUID);
506         data_len -= sizeof(GUID);
507         break;
508       case 0x0:
509       case 0x2:
510       case 0x4:
511       case 0x5:
512       case 0x6:
513       case 0xd:
514         if (data_len < sizeof(ULONG))
515           return FALSE;
516         p += sizeof(ULONG);
517         data_len -= sizeof(ULONG);
518         break;
519       case 0x1:
520         if (data_len < 24)
521           return FALSE;
522         p += 24;
523         data_len -= 24;
524         break;
525       default:
526         FIXME("unimplemented type 0x%x\n", type);
527         break;
528     }
529   }
530   return TRUE;
531 }
532
533 /* assumes the HTTP packet has been validated */
534 static unsigned char *RPCRT4_NextHttpHeaderField(unsigned char *data)
535 {
536   ULONG type;
537
538   type = *(ULONG *)data;
539   data += sizeof(ULONG);
540
541   switch (type)
542   {
543     case 0x3:
544     case 0xc:
545       return data + sizeof(GUID);
546     case 0x0:
547     case 0x2:
548     case 0x4:
549     case 0x5:
550     case 0x6:
551     case 0xd:
552       return data + sizeof(ULONG);
553     case 0x1:
554       return data + 24;
555     default:
556       FIXME("unimplemented type 0x%x\n", type);
557       return data;
558   }
559 }
560
561 #define READ_HTTP_PAYLOAD_FIELD_TYPE(data) *(ULONG *)(data)
562 #define GET_HTTP_PAYLOAD_FIELD_DATA(data) ((data) + sizeof(ULONG))
563
564 /* assumes the HTTP packet has been validated */
565 RPC_STATUS RPCRT4_ParseHttpPrepareHeader1(RpcPktHdr *header,
566                                           unsigned char *data, ULONG *field1)
567 {
568   ULONG type;
569   if (header->http.flags != 0x0)
570   {
571     ERR("invalid flags 0x%x\n", header->http.flags);
572     return RPC_S_PROTOCOL_ERROR;
573   }
574   if (header->http.num_data_items != 1)
575   {
576     ERR("invalid number of data items %d\n", header->http.num_data_items);
577     return RPC_S_PROTOCOL_ERROR;
578   }
579   type = READ_HTTP_PAYLOAD_FIELD_TYPE(data);
580   if (type != 0x00000002)
581   {
582     ERR("invalid type 0x%08x\n", type);
583     return RPC_S_PROTOCOL_ERROR;
584   }
585   *field1 = *(ULONG *)GET_HTTP_PAYLOAD_FIELD_DATA(data);
586   return RPC_S_OK;
587 }
588
589 /* assumes the HTTP packet has been validated */
590 RPC_STATUS RPCRT4_ParseHttpPrepareHeader2(RpcPktHdr *header,
591                                           unsigned char *data, ULONG *field1,
592                                           ULONG *bytes_until_next_packet,
593                                           ULONG *field3)
594 {
595   ULONG type;
596   if (header->http.flags != 0x0)
597   {
598     ERR("invalid flags 0x%x\n", header->http.flags);
599     return RPC_S_PROTOCOL_ERROR;
600   }
601   if (header->http.num_data_items != 3)
602   {
603     ERR("invalid number of data items %d\n", header->http.num_data_items);
604     return RPC_S_PROTOCOL_ERROR;
605   }
606
607   type = READ_HTTP_PAYLOAD_FIELD_TYPE(data);
608   if (type != 0x00000006)
609   {
610     ERR("invalid type for field 1: 0x%08x\n", type);
611     return RPC_S_PROTOCOL_ERROR;
612   }
613   *field1 = *(ULONG *)GET_HTTP_PAYLOAD_FIELD_DATA(data);
614   data = RPCRT4_NextHttpHeaderField(data);
615
616   type = READ_HTTP_PAYLOAD_FIELD_TYPE(data);
617   if (type != 0x00000000)
618   {
619     ERR("invalid type for field 2: 0x%08x\n", type);
620     return RPC_S_PROTOCOL_ERROR;
621   }
622   *bytes_until_next_packet = *(ULONG *)GET_HTTP_PAYLOAD_FIELD_DATA(data);
623   data = RPCRT4_NextHttpHeaderField(data);
624
625   type = READ_HTTP_PAYLOAD_FIELD_TYPE(data);
626   if (type != 0x00000002)
627   {
628     ERR("invalid type for field 3: 0x%08x\n", type);
629     return RPC_S_PROTOCOL_ERROR;
630   }
631   *field3 = *(ULONG *)GET_HTTP_PAYLOAD_FIELD_DATA(data);
632
633   return RPC_S_OK;
634 }
635
636 RPC_STATUS RPCRT4_ParseHttpFlowControlHeader(RpcPktHdr *header,
637                                              unsigned char *data, BOOL server,
638                                              ULONG *bytes_transmitted,
639                                              ULONG *flow_control_increment,
640                                              UUID *pipe_uuid)
641 {
642   ULONG type;
643   if (header->http.flags != 0x2)
644   {
645     ERR("invalid flags 0x%x\n", header->http.flags);
646     return RPC_S_PROTOCOL_ERROR;
647   }
648   if (header->http.num_data_items != 2)
649   {
650     ERR("invalid number of data items %d\n", header->http.num_data_items);
651     return RPC_S_PROTOCOL_ERROR;
652   }
653
654   type = READ_HTTP_PAYLOAD_FIELD_TYPE(data);
655   if (type != 0x0000000d)
656   {
657     ERR("invalid type for field 1: 0x%08x\n", type);
658     return RPC_S_PROTOCOL_ERROR;
659   }
660   if (*(ULONG *)GET_HTTP_PAYLOAD_FIELD_DATA(data) != (server ? 0x3 : 0x0))
661   {
662     ERR("invalid type for 0xd field data: 0x%08x\n", *(ULONG *)GET_HTTP_PAYLOAD_FIELD_DATA(data));
663     return RPC_S_PROTOCOL_ERROR;
664   }
665   data = RPCRT4_NextHttpHeaderField(data);
666
667   type = READ_HTTP_PAYLOAD_FIELD_TYPE(data);
668   if (type != 0x00000001)
669   {
670     ERR("invalid type for field 2: 0x%08x\n", type);
671     return RPC_S_PROTOCOL_ERROR;
672   }
673   *bytes_transmitted = *(ULONG *)GET_HTTP_PAYLOAD_FIELD_DATA(data);
674   *flow_control_increment = *(ULONG *)(GET_HTTP_PAYLOAD_FIELD_DATA(data) + 4);
675   *pipe_uuid = *(UUID *)(GET_HTTP_PAYLOAD_FIELD_DATA(data) + 8);
676
677   return RPC_S_OK;
678 }
679
680
681 RPC_STATUS RPCRT4_default_secure_packet(RpcConnection *Connection,
682     enum secure_packet_direction dir,
683     RpcPktHdr *hdr, unsigned int hdr_size,
684     unsigned char *stub_data, unsigned int stub_data_size,
685     RpcAuthVerifier *auth_hdr,
686     unsigned char *auth_value, unsigned int auth_value_size)
687 {
688     SecBufferDesc message;
689     SecBuffer buffers[4];
690     SECURITY_STATUS sec_status;
691
692     message.ulVersion = SECBUFFER_VERSION;
693     message.cBuffers = sizeof(buffers)/sizeof(buffers[0]);
694     message.pBuffers = buffers;
695
696     buffers[0].cbBuffer = hdr_size;
697     buffers[0].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
698     buffers[0].pvBuffer = hdr;
699     buffers[1].cbBuffer = stub_data_size;
700     buffers[1].BufferType = SECBUFFER_DATA;
701     buffers[1].pvBuffer = stub_data;
702     buffers[2].cbBuffer = sizeof(*auth_hdr);
703     buffers[2].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
704     buffers[2].pvBuffer = auth_hdr;
705     buffers[3].cbBuffer = auth_value_size;
706     buffers[3].BufferType = SECBUFFER_TOKEN;
707     buffers[3].pvBuffer = auth_value;
708
709     if (dir == SECURE_PACKET_SEND)
710     {
711         if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
712         {
713             sec_status = EncryptMessage(&Connection->ctx, 0, &message, 0 /* FIXME */);
714             if (sec_status != SEC_E_OK)
715             {
716                 ERR("EncryptMessage failed with 0x%08x\n", sec_status);
717                 return RPC_S_SEC_PKG_ERROR;
718             }
719         }
720         else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
721         {
722             sec_status = MakeSignature(&Connection->ctx, 0, &message, 0 /* FIXME */);
723             if (sec_status != SEC_E_OK)
724             {
725                 ERR("MakeSignature failed with 0x%08x\n", sec_status);
726                 return RPC_S_SEC_PKG_ERROR;
727             }
728         }
729     }
730     else if (dir == SECURE_PACKET_RECEIVE)
731     {
732         if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
733         {
734             sec_status = DecryptMessage(&Connection->ctx, &message, 0 /* FIXME */, 0);
735             if (sec_status != SEC_E_OK)
736             {
737                 ERR("DecryptMessage failed with 0x%08x\n", sec_status);
738                 return RPC_S_SEC_PKG_ERROR;
739             }
740         }
741         else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
742         {
743             sec_status = VerifySignature(&Connection->ctx, &message, 0 /* FIXME */, NULL);
744             if (sec_status != SEC_E_OK)
745             {
746                 ERR("VerifySignature failed with 0x%08x\n", sec_status);
747                 return RPC_S_SEC_PKG_ERROR;
748             }
749         }
750     }
751
752     return RPC_S_OK;
753 }
754          
755 /***********************************************************************
756  *           RPCRT4_SendWithAuth (internal)
757  * 
758  * Transmit a packet with authorization data over connection in acceptable fragments.
759  */
760 RPC_STATUS RPCRT4_SendWithAuth(RpcConnection *Connection, RpcPktHdr *Header,
761                                void *Buffer, unsigned int BufferLength,
762                                const void *Auth, unsigned int AuthLength)
763 {
764   PUCHAR buffer_pos;
765   DWORD hdr_size;
766   LONG count;
767   unsigned char *pkt;
768   LONG alen;
769   RPC_STATUS status;
770
771   RPCRT4_SetThreadCurrentConnection(Connection);
772
773   buffer_pos = Buffer;
774   /* The packet building functions save the packet header size, so we can use it. */
775   hdr_size = Header->common.frag_len;
776   if (AuthLength)
777     Header->common.auth_len = AuthLength;
778   else if (Connection->AuthInfo && packet_has_auth_verifier(Header))
779   {
780     if ((Connection->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(Header))
781       Header->common.auth_len = Connection->encryption_auth_len;
782     else
783       Header->common.auth_len = Connection->signature_auth_len;
784   }
785   else
786     Header->common.auth_len = 0;
787   Header->common.flags |= RPC_FLG_FIRST;
788   Header->common.flags &= ~RPC_FLG_LAST;
789
790   alen = RPC_AUTH_VERIFIER_LEN(&Header->common);
791
792   while (!(Header->common.flags & RPC_FLG_LAST)) {
793     unsigned char auth_pad_len = Header->common.auth_len ? ROUND_UP_AMOUNT(BufferLength, AUTH_ALIGNMENT) : 0;
794     unsigned int pkt_size = BufferLength + hdr_size + alen + auth_pad_len;
795
796     /* decide if we need to split the packet into fragments */
797    if (pkt_size <= Connection->MaxTransmissionSize) {
798      Header->common.flags |= RPC_FLG_LAST;
799      Header->common.frag_len = pkt_size;
800     } else {
801       auth_pad_len = 0;
802       /* make sure packet payload will be a multiple of 16 */
803       Header->common.frag_len =
804         ((Connection->MaxTransmissionSize - hdr_size - alen) & ~(AUTH_ALIGNMENT-1)) +
805         hdr_size + alen;
806     }
807
808     pkt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Header->common.frag_len);
809
810     memcpy(pkt, Header, hdr_size);
811
812     /* fragment consisted of header only and is the last one */
813     if (hdr_size == Header->common.frag_len)
814       goto write;
815
816     memcpy(pkt + hdr_size, buffer_pos, Header->common.frag_len - hdr_size - auth_pad_len - alen);
817
818     /* add the authorization info */
819     if (Header->common.auth_len)
820     {
821       RpcAuthVerifier *auth_hdr = (RpcAuthVerifier *)&pkt[Header->common.frag_len - alen];
822
823       auth_hdr->auth_type = Connection->AuthInfo->AuthnSvc;
824       auth_hdr->auth_level = Connection->AuthInfo->AuthnLevel;
825       auth_hdr->auth_pad_length = auth_pad_len;
826       auth_hdr->auth_reserved = 0;
827       /* a unique number... */
828       auth_hdr->auth_context_id = Connection->auth_context_id;
829
830       if (AuthLength)
831         memcpy(auth_hdr + 1, Auth, AuthLength);
832       else
833       {
834         status = rpcrt4_conn_secure_packet(Connection, SECURE_PACKET_SEND,
835             (RpcPktHdr *)pkt, hdr_size,
836             pkt + hdr_size, Header->common.frag_len - hdr_size - alen,
837             auth_hdr,
838             (unsigned char *)(auth_hdr + 1), Header->common.auth_len);
839         if (status != RPC_S_OK)
840         {
841           HeapFree(GetProcessHeap(), 0, pkt);
842           RPCRT4_SetThreadCurrentConnection(NULL);
843           return status;
844         }
845       }
846     }
847
848 write:
849     count = rpcrt4_conn_write(Connection, pkt, Header->common.frag_len);
850     HeapFree(GetProcessHeap(), 0, pkt);
851     if (count<0) {
852       WARN("rpcrt4_conn_write failed (auth)\n");
853       RPCRT4_SetThreadCurrentConnection(NULL);
854       return RPC_S_CALL_FAILED;
855     }
856
857     buffer_pos += Header->common.frag_len - hdr_size - alen - auth_pad_len;
858     BufferLength -= Header->common.frag_len - hdr_size - alen - auth_pad_len;
859     Header->common.flags &= ~RPC_FLG_FIRST;
860   }
861
862   RPCRT4_SetThreadCurrentConnection(NULL);
863   return RPC_S_OK;
864 }
865
866 /***********************************************************************
867  *           RPCRT4_default_authorize (internal)
868  *
869  * Authorize a client connection.
870  */
871 RPC_STATUS RPCRT4_default_authorize(RpcConnection *conn, BOOL first_time,
872                                     unsigned char *in_buffer,
873                                     unsigned int in_size,
874                                     unsigned char *out_buffer,
875                                     unsigned int *out_size)
876 {
877   SECURITY_STATUS r;
878   SecBufferDesc out_desc;
879   SecBufferDesc inp_desc;
880   SecPkgContext_Sizes secctx_sizes;
881   BOOL continue_needed;
882   ULONG context_req;
883   SecBuffer in, out;
884
885   if (!out_buffer)
886   {
887     *out_size = conn->AuthInfo->cbMaxToken;
888     return RPC_S_OK;
889   }
890
891   in.BufferType = SECBUFFER_TOKEN;
892   in.pvBuffer = in_buffer;
893   in.cbBuffer = in_size;
894
895   out.BufferType = SECBUFFER_TOKEN;
896   out.pvBuffer = out_buffer;
897   out.cbBuffer = *out_size;
898
899   out_desc.ulVersion = 0;
900   out_desc.cBuffers = 1;
901   out_desc.pBuffers = &out;
902
903   inp_desc.ulVersion = 0;
904   inp_desc.cBuffers = 1;
905   inp_desc.pBuffers = &in;
906
907   if (conn->server)
908   {
909       context_req = ASC_REQ_CONNECTION | ASC_REQ_USE_DCE_STYLE |
910                     ASC_REQ_DELEGATE;
911
912       if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
913           context_req |= ASC_REQ_INTEGRITY;
914       else if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY)
915           context_req |= ASC_REQ_CONFIDENTIALITY | ASC_REQ_INTEGRITY;
916
917       r = AcceptSecurityContext(&conn->AuthInfo->cred,
918                                 first_time ? NULL : &conn->ctx,
919                                 &inp_desc, context_req, SECURITY_NETWORK_DREP,
920                                 &conn->ctx,
921                                 &out_desc, &conn->attr, &conn->exp);
922       if (r == SEC_E_OK || r == SEC_I_COMPLETE_NEEDED)
923       {
924           /* authorisation done, so nothing more to send */
925           out.cbBuffer = 0;
926       }
927   }
928   else
929   {
930       context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
931                     ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
932
933       if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
934           context_req |= ISC_REQ_INTEGRITY;
935       else if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY)
936           context_req |= ISC_REQ_CONFIDENTIALITY | ISC_REQ_INTEGRITY;
937
938       r = InitializeSecurityContextW(&conn->AuthInfo->cred,
939                                      first_time ? NULL: &conn->ctx,
940                                      first_time ? conn->AuthInfo->server_principal_name : NULL,
941                                      context_req, 0, SECURITY_NETWORK_DREP,
942                                      first_time ? NULL : &inp_desc, 0, &conn->ctx,
943                                      &out_desc, &conn->attr, &conn->exp);
944   }
945   if (FAILED(r))
946   {
947       WARN("InitializeSecurityContext failed with error 0x%08x\n", r);
948       goto failed;
949   }
950
951   TRACE("r = 0x%08x, attr = 0x%08x\n", r, conn->attr);
952   continue_needed = ((r == SEC_I_CONTINUE_NEEDED) ||
953                      (r == SEC_I_COMPLETE_AND_CONTINUE));
954
955   if ((r == SEC_I_COMPLETE_NEEDED) || (r == SEC_I_COMPLETE_AND_CONTINUE))
956   {
957       TRACE("complete needed\n");
958       r = CompleteAuthToken(&conn->ctx, &out_desc);
959       if (FAILED(r))
960       {
961           WARN("CompleteAuthToken failed with error 0x%08x\n", r);
962           goto failed;
963       }
964   }
965
966   TRACE("cbBuffer = %d\n", out.cbBuffer);
967
968   if (!continue_needed)
969   {
970       r = QueryContextAttributesA(&conn->ctx, SECPKG_ATTR_SIZES, &secctx_sizes);
971       if (FAILED(r))
972       {
973           WARN("QueryContextAttributes failed with error 0x%08x\n", r);
974           goto failed;
975       }
976       conn->signature_auth_len = secctx_sizes.cbMaxSignature;
977       conn->encryption_auth_len = secctx_sizes.cbSecurityTrailer;
978   }
979
980   *out_size = out.cbBuffer;
981   return RPC_S_OK;
982
983 failed:
984   *out_size = 0;
985   return ERROR_ACCESS_DENIED; /* FIXME: is this correct? */
986 }
987
988 /***********************************************************************
989  *           RPCRT4_ClientConnectionAuth (internal)
990  */
991 RPC_STATUS RPCRT4_ClientConnectionAuth(RpcConnection* conn, BYTE *challenge,
992                                        ULONG count)
993 {
994   RpcPktHdr *resp_hdr;
995   RPC_STATUS status;
996   unsigned char *out_buffer;
997   unsigned int out_len = 0;
998
999   TRACE("challenge %s, %d bytes\n", challenge, count);
1000
1001   status = rpcrt4_conn_authorize(conn, FALSE, challenge, count, NULL, &out_len);
1002   if (status) return status;
1003   out_buffer = HeapAlloc(GetProcessHeap(), 0, out_len);
1004   if (!out_buffer) return RPC_S_OUT_OF_RESOURCES;
1005   status = rpcrt4_conn_authorize(conn, FALSE, challenge, count, out_buffer, &out_len);
1006   if (status) return status;
1007
1008   resp_hdr = RPCRT4_BuildAuthHeader(NDR_LOCAL_DATA_REPRESENTATION);
1009
1010   if (resp_hdr)
1011     status = RPCRT4_SendWithAuth(conn, resp_hdr, NULL, 0, out_buffer, out_len);
1012   else
1013     status = RPC_S_OUT_OF_RESOURCES;
1014
1015   HeapFree(GetProcessHeap(), 0, out_buffer);
1016   RPCRT4_FreeHeader(resp_hdr);
1017
1018   return status;
1019 }
1020
1021 /***********************************************************************
1022  *           RPCRT4_ServerConnectionAuth (internal)
1023  */
1024 RPC_STATUS RPCRT4_ServerConnectionAuth(RpcConnection* conn,
1025                                        BOOL start,
1026                                        RpcAuthVerifier *auth_data_in,
1027                                        ULONG auth_length_in,
1028                                        unsigned char **auth_data_out,
1029                                        ULONG *auth_length_out)
1030 {
1031     unsigned char *out_buffer;
1032     unsigned int out_size;
1033     RPC_STATUS status;
1034
1035     if (start)
1036     {
1037         /* remove any existing authentication information */
1038         if (conn->AuthInfo)
1039         {
1040             RpcAuthInfo_Release(conn->AuthInfo);
1041             conn->AuthInfo = NULL;
1042         }
1043         if (SecIsValidHandle(&conn->ctx))
1044         {
1045             DeleteSecurityContext(&conn->ctx);
1046             SecInvalidateHandle(&conn->ctx);
1047         }
1048         if (auth_length_in >= sizeof(RpcAuthVerifier))
1049         {
1050             CredHandle cred;
1051             TimeStamp exp;
1052             ULONG max_token;
1053
1054             status = RPCRT4_ServerGetRegisteredAuthInfo(
1055                 auth_data_in->auth_type, &cred, &exp, &max_token);
1056             if (status != RPC_S_OK)
1057             {
1058                 ERR("unknown authentication service %u\n", auth_data_in->auth_type);
1059                 return status;
1060             }
1061
1062             status = RpcAuthInfo_Create(auth_data_in->auth_level,
1063                                         auth_data_in->auth_type, cred, exp,
1064                                         max_token, NULL, &conn->AuthInfo);
1065             if (status != RPC_S_OK)
1066                 return status;
1067
1068             /* FIXME: should auth_data_in->auth_context_id be checked in the !start case? */
1069             conn->auth_context_id = auth_data_in->auth_context_id;
1070         }
1071     }
1072
1073     if (auth_length_in < sizeof(RpcAuthVerifier))
1074         return RPC_S_OK;
1075
1076     if (!conn->AuthInfo)
1077         /* should have filled in authentication info by now */
1078         return RPC_S_PROTOCOL_ERROR;
1079
1080     status = rpcrt4_conn_authorize(
1081         conn, start, (unsigned char *)(auth_data_in + 1),
1082         auth_length_in - sizeof(RpcAuthVerifier), NULL, &out_size);
1083     if (status) return status;
1084
1085     out_buffer = HeapAlloc(GetProcessHeap(), 0, out_size);
1086     if (!out_buffer) return RPC_S_OUT_OF_RESOURCES;
1087
1088     status = rpcrt4_conn_authorize(
1089         conn, start, (unsigned char *)(auth_data_in + 1),
1090         auth_length_in - sizeof(RpcAuthVerifier), out_buffer, &out_size);
1091     if (status != RPC_S_OK)
1092     {
1093         HeapFree(GetProcessHeap(), 0, out_buffer);
1094         return status;
1095     }
1096
1097     if (out_size && !auth_length_out)
1098     {
1099         ERR("expected authentication to be complete but SSP returned data of "
1100             "%u bytes to be sent back to client\n", out_size);
1101         HeapFree(GetProcessHeap(), 0, out_buffer);
1102         return RPC_S_SEC_PKG_ERROR;
1103     }
1104     else
1105     {
1106         *auth_data_out = out_buffer;
1107         *auth_length_out = out_size;
1108     }
1109
1110     return status;
1111 }
1112
1113 /***********************************************************************
1114  *           RPCRT4_default_is_authorized (internal)
1115  *
1116  * Has a connection started the process of authorizing with the server?
1117  */
1118 BOOL RPCRT4_default_is_authorized(RpcConnection *Connection)
1119 {
1120     return Connection->AuthInfo && SecIsValidHandle(&Connection->ctx);
1121 }
1122
1123 /***********************************************************************
1124  *           RPCRT4_default_impersonate_client (internal)
1125  *
1126  */
1127 RPC_STATUS RPCRT4_default_impersonate_client(RpcConnection *conn)
1128 {
1129     SECURITY_STATUS sec_status;
1130
1131     TRACE("(%p)\n", conn);
1132
1133     if (!conn->AuthInfo || !SecIsValidHandle(&conn->ctx))
1134         return RPC_S_NO_CONTEXT_AVAILABLE;
1135     sec_status = ImpersonateSecurityContext(&conn->ctx);
1136     if (sec_status != SEC_E_OK)
1137         WARN("ImpersonateSecurityContext returned 0x%08x\n", sec_status);
1138     switch (sec_status)
1139     {
1140     case SEC_E_UNSUPPORTED_FUNCTION:
1141         return RPC_S_CANNOT_SUPPORT;
1142     case SEC_E_NO_IMPERSONATION:
1143         return RPC_S_NO_CONTEXT_AVAILABLE;
1144     case SEC_E_OK:
1145         return RPC_S_OK;
1146     default:
1147         return RPC_S_SEC_PKG_ERROR;
1148     }
1149 }
1150
1151 /***********************************************************************
1152  *           RPCRT4_default_revert_to_self (internal)
1153  *
1154  */
1155 RPC_STATUS RPCRT4_default_revert_to_self(RpcConnection *conn)
1156 {
1157     SECURITY_STATUS sec_status;
1158
1159     TRACE("(%p)\n", conn);
1160
1161     if (!conn->AuthInfo || !SecIsValidHandle(&conn->ctx))
1162         return RPC_S_NO_CONTEXT_AVAILABLE;
1163     sec_status = RevertSecurityContext(&conn->ctx);
1164     if (sec_status != SEC_E_OK)
1165         WARN("RevertSecurityContext returned 0x%08x\n", sec_status);
1166     switch (sec_status)
1167     {
1168     case SEC_E_UNSUPPORTED_FUNCTION:
1169         return RPC_S_CANNOT_SUPPORT;
1170     case SEC_E_NO_IMPERSONATION:
1171         return RPC_S_NO_CONTEXT_AVAILABLE;
1172     case SEC_E_OK:
1173         return RPC_S_OK;
1174     default:
1175         return RPC_S_SEC_PKG_ERROR;
1176     }
1177 }
1178
1179 /***********************************************************************
1180  *           RPCRT4_default_inquire_auth_client (internal)
1181  *
1182  * Default function to retrieve the authentication details that the client
1183  * is using to call the server.
1184  */
1185 RPC_STATUS RPCRT4_default_inquire_auth_client(
1186     RpcConnection *conn, RPC_AUTHZ_HANDLE *privs, RPC_WSTR *server_princ_name,
1187     ULONG *authn_level, ULONG *authn_svc, ULONG *authz_svc, ULONG flags)
1188 {
1189     if (!conn->AuthInfo) return RPC_S_BINDING_HAS_NO_AUTH;
1190
1191     if (privs)
1192     {
1193         FIXME("privs not implemented\n");
1194         *privs = NULL;
1195     }
1196     if (server_princ_name)
1197     {
1198         *server_princ_name = RPCRT4_strdupW(conn->AuthInfo->server_principal_name);
1199         if (!*server_princ_name) return ERROR_OUTOFMEMORY;
1200     }
1201     if (authn_level) *authn_level = conn->AuthInfo->AuthnLevel;
1202     if (authn_svc) *authn_svc = conn->AuthInfo->AuthnSvc;
1203     if (authz_svc)
1204     {
1205         FIXME("authorization service not implemented\n");
1206         *authz_svc = RPC_C_AUTHZ_NONE;
1207     }
1208     if (flags)
1209         FIXME("flags 0x%x not implemented\n", flags);
1210
1211     return RPC_S_OK;
1212 }
1213
1214 /***********************************************************************
1215  *           RPCRT4_Send (internal)
1216  * 
1217  * Transmit a packet over connection in acceptable fragments.
1218  */
1219 RPC_STATUS RPCRT4_Send(RpcConnection *Connection, RpcPktHdr *Header,
1220                        void *Buffer, unsigned int BufferLength)
1221 {
1222   RPC_STATUS r;
1223
1224   if (packet_does_auth_negotiation(Header) &&
1225       Connection->AuthInfo &&
1226       !rpcrt4_conn_is_authorized(Connection))
1227   {
1228       unsigned int out_size = 0;
1229       unsigned char *out_buffer;
1230
1231       r = rpcrt4_conn_authorize(Connection, TRUE, NULL, 0, NULL, &out_size);
1232       if (r != RPC_S_OK) return r;
1233
1234       out_buffer = HeapAlloc(GetProcessHeap(), 0, out_size);
1235       if (!out_buffer) return RPC_S_OUT_OF_RESOURCES;
1236
1237       /* tack on a negotiate packet */
1238       r = rpcrt4_conn_authorize(Connection, TRUE, NULL, 0, out_buffer, &out_size);
1239       if (r == RPC_S_OK)
1240           r = RPCRT4_SendWithAuth(Connection, Header, Buffer, BufferLength, out_buffer, out_size);
1241
1242       HeapFree(GetProcessHeap(), 0, out_buffer);
1243   }
1244   else
1245     r = RPCRT4_SendWithAuth(Connection, Header, Buffer, BufferLength, NULL, 0);
1246
1247   return r;
1248 }
1249
1250 /* validates version and frag_len fields */
1251 RPC_STATUS RPCRT4_ValidateCommonHeader(const RpcPktCommonHdr *hdr)
1252 {
1253   DWORD hdr_length;
1254
1255   /* verify if the header really makes sense */
1256   if (hdr->rpc_ver != RPC_VER_MAJOR ||
1257       hdr->rpc_ver_minor != RPC_VER_MINOR)
1258   {
1259     WARN("unhandled packet version\n");
1260     return RPC_S_PROTOCOL_ERROR;
1261   }
1262
1263   hdr_length = RPCRT4_GetHeaderSize((const RpcPktHdr*)hdr);
1264   if (hdr_length == 0)
1265   {
1266     WARN("header length == 0\n");
1267     return RPC_S_PROTOCOL_ERROR;
1268   }
1269
1270   if (hdr->frag_len < hdr_length)
1271   {
1272     WARN("bad frag length %d\n", hdr->frag_len);
1273     return RPC_S_PROTOCOL_ERROR;
1274   }
1275
1276   return RPC_S_OK;
1277 }
1278
1279 /***********************************************************************
1280  *           RPCRT4_default_receive_fragment (internal)
1281  * 
1282  * Receive a fragment from a connection.
1283  */
1284 static RPC_STATUS RPCRT4_default_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
1285 {
1286   RPC_STATUS status;
1287   DWORD hdr_length;
1288   LONG dwRead;
1289   RpcPktCommonHdr common_hdr;
1290
1291   *Header = NULL;
1292   *Payload = NULL;
1293
1294   TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
1295
1296   /* read packet common header */
1297   dwRead = rpcrt4_conn_read(Connection, &common_hdr, sizeof(common_hdr));
1298   if (dwRead != sizeof(common_hdr)) {
1299     WARN("Short read of header, %d bytes\n", dwRead);
1300     status = RPC_S_CALL_FAILED;
1301     goto fail;
1302   }
1303
1304   status = RPCRT4_ValidateCommonHeader(&common_hdr);
1305   if (status != RPC_S_OK) goto fail;
1306
1307   hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
1308   if (hdr_length == 0) {
1309     WARN("header length == 0\n");
1310     status = RPC_S_PROTOCOL_ERROR;
1311     goto fail;
1312   }
1313
1314   *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
1315   memcpy(*Header, &common_hdr, sizeof(common_hdr));
1316
1317   /* read the rest of packet header */
1318   dwRead = rpcrt4_conn_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
1319   if (dwRead != hdr_length - sizeof(common_hdr)) {
1320     WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
1321     status = RPC_S_CALL_FAILED;
1322     goto fail;
1323   }
1324
1325   if (common_hdr.frag_len - hdr_length)
1326   {
1327     *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
1328     if (!*Payload)
1329     {
1330       status = RPC_S_OUT_OF_RESOURCES;
1331       goto fail;
1332     }
1333
1334     dwRead = rpcrt4_conn_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
1335     if (dwRead != common_hdr.frag_len - hdr_length)
1336     {
1337       WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
1338       status = RPC_S_CALL_FAILED;
1339       goto fail;
1340     }
1341   }
1342   else
1343     *Payload = NULL;
1344
1345   /* success */
1346   status = RPC_S_OK;
1347
1348 fail:
1349   if (status != RPC_S_OK) {
1350     RPCRT4_FreeHeader(*Header);
1351     *Header = NULL;
1352     HeapFree(GetProcessHeap(), 0, *Payload);
1353     *Payload = NULL;
1354   }
1355   return status;
1356 }
1357
1358 static RPC_STATUS RPCRT4_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
1359 {
1360     if (Connection->ops->receive_fragment)
1361         return Connection->ops->receive_fragment(Connection, Header, Payload);
1362     else
1363         return RPCRT4_default_receive_fragment(Connection, Header, Payload);
1364 }
1365
1366 /***********************************************************************
1367  *           RPCRT4_ReceiveWithAuth (internal)
1368  *
1369  * Receive a packet from connection, merge the fragments and return the auth
1370  * data.
1371  */
1372 RPC_STATUS RPCRT4_ReceiveWithAuth(RpcConnection *Connection, RpcPktHdr **Header,
1373                                   PRPC_MESSAGE pMsg,
1374                                   unsigned char **auth_data_out,
1375                                   ULONG *auth_length_out)
1376 {
1377   RPC_STATUS status;
1378   DWORD hdr_length;
1379   unsigned short first_flag;
1380   ULONG data_length;
1381   ULONG buffer_length;
1382   ULONG auth_length = 0;
1383   unsigned char *auth_data = NULL;
1384   RpcPktHdr *CurrentHeader = NULL;
1385   void *payload = NULL;
1386
1387   *Header = NULL;
1388   pMsg->Buffer = NULL;
1389   if (auth_data_out) *auth_data_out = NULL;
1390   if (auth_length_out) *auth_length_out = 0;
1391
1392   TRACE("(%p, %p, %p, %p)\n", Connection, Header, pMsg, auth_data_out);
1393
1394   RPCRT4_SetThreadCurrentConnection(Connection);
1395
1396   status = RPCRT4_receive_fragment(Connection, Header, &payload);
1397   if (status != RPC_S_OK) goto fail;
1398
1399   hdr_length = RPCRT4_GetHeaderSize(*Header);
1400
1401   /* read packet body */
1402   switch ((*Header)->common.ptype) {
1403   case PKT_RESPONSE:
1404     pMsg->BufferLength = (*Header)->response.alloc_hint;
1405     break;
1406   case PKT_REQUEST:
1407     pMsg->BufferLength = (*Header)->request.alloc_hint;
1408     break;
1409   default:
1410     pMsg->BufferLength = (*Header)->common.frag_len - hdr_length - RPC_AUTH_VERIFIER_LEN(&(*Header)->common);
1411   }
1412
1413   TRACE("buffer length = %u\n", pMsg->BufferLength);
1414
1415   pMsg->Buffer = I_RpcAllocate(pMsg->BufferLength);
1416   if (!pMsg->Buffer)
1417   {
1418     status = ERROR_OUTOFMEMORY;
1419     goto fail;
1420   }
1421
1422   first_flag = RPC_FLG_FIRST;
1423   auth_length = (*Header)->common.auth_len;
1424   if (auth_length) {
1425     auth_data = HeapAlloc(GetProcessHeap(), 0, RPC_AUTH_VERIFIER_LEN(&(*Header)->common));
1426     if (!auth_data) {
1427       status = RPC_S_OUT_OF_RESOURCES;
1428       goto fail;
1429     }
1430   }
1431   CurrentHeader = *Header;
1432   buffer_length = 0;
1433   while (TRUE)
1434   {
1435     unsigned int header_auth_len = RPC_AUTH_VERIFIER_LEN(&CurrentHeader->common);
1436
1437     /* verify header fields */
1438
1439     if ((CurrentHeader->common.frag_len < hdr_length) ||
1440         (CurrentHeader->common.frag_len - hdr_length < header_auth_len)) {
1441       WARN("frag_len %d too small for hdr_length %d and auth_len %d\n",
1442         CurrentHeader->common.frag_len, hdr_length, CurrentHeader->common.auth_len);
1443       status = RPC_S_PROTOCOL_ERROR;
1444       goto fail;
1445     }
1446
1447     if (CurrentHeader->common.auth_len != auth_length) {
1448       WARN("auth_len header field changed from %d to %d\n",
1449         auth_length, CurrentHeader->common.auth_len);
1450       status = RPC_S_PROTOCOL_ERROR;
1451       goto fail;
1452     }
1453
1454     if ((CurrentHeader->common.flags & RPC_FLG_FIRST) != first_flag) {
1455       TRACE("invalid packet flags\n");
1456       status = RPC_S_PROTOCOL_ERROR;
1457       goto fail;
1458     }
1459
1460     data_length = CurrentHeader->common.frag_len - hdr_length - header_auth_len;
1461     if (data_length + buffer_length > pMsg->BufferLength) {
1462       TRACE("allocation hint exceeded, new buffer length = %d\n",
1463         data_length + buffer_length);
1464       pMsg->BufferLength = data_length + buffer_length;
1465       status = I_RpcReAllocateBuffer(pMsg);
1466       if (status != RPC_S_OK) goto fail;
1467     }
1468
1469     memcpy((unsigned char *)pMsg->Buffer + buffer_length, payload, data_length);
1470
1471     if (header_auth_len) {
1472       if (header_auth_len < sizeof(RpcAuthVerifier) ||
1473           header_auth_len > RPC_AUTH_VERIFIER_LEN(&(*Header)->common)) {
1474         WARN("bad auth verifier length %d\n", header_auth_len);
1475         status = RPC_S_PROTOCOL_ERROR;
1476         goto fail;
1477       }
1478
1479       /* FIXME: we should accumulate authentication data for the bind,
1480        * bind_ack, alter_context and alter_context_response if necessary.
1481        * however, the details of how this is done is very sketchy in the
1482        * DCE/RPC spec. for all other packet types that have authentication
1483        * verifier data then it is just duplicated in all the fragments */
1484       memcpy(auth_data, (unsigned char *)payload + data_length, header_auth_len);
1485
1486       /* these packets are handled specially, not by the generic SecurePacket
1487        * function */
1488       if (!packet_does_auth_negotiation(*Header) && rpcrt4_conn_is_authorized(Connection))
1489       {
1490         status = rpcrt4_conn_secure_packet(Connection, SECURE_PACKET_RECEIVE,
1491             CurrentHeader, hdr_length,
1492             (unsigned char *)pMsg->Buffer + buffer_length, data_length,
1493             (RpcAuthVerifier *)auth_data,
1494             auth_data + sizeof(RpcAuthVerifier),
1495             header_auth_len - sizeof(RpcAuthVerifier));
1496         if (status != RPC_S_OK) goto fail;
1497       }
1498     }
1499
1500     buffer_length += data_length;
1501     if (!(CurrentHeader->common.flags & RPC_FLG_LAST)) {
1502       TRACE("next header\n");
1503
1504       if (*Header != CurrentHeader)
1505       {
1506           RPCRT4_FreeHeader(CurrentHeader);
1507           CurrentHeader = NULL;
1508       }
1509       HeapFree(GetProcessHeap(), 0, payload);
1510       payload = NULL;
1511
1512       status = RPCRT4_receive_fragment(Connection, &CurrentHeader, &payload);
1513       if (status != RPC_S_OK) goto fail;
1514
1515       first_flag = 0;
1516     } else {
1517       break;
1518     }
1519   }
1520   pMsg->BufferLength = buffer_length;
1521
1522   /* success */
1523   status = RPC_S_OK;
1524
1525 fail:
1526   RPCRT4_SetThreadCurrentConnection(NULL);
1527   if (CurrentHeader != *Header)
1528     RPCRT4_FreeHeader(CurrentHeader);
1529   if (status != RPC_S_OK) {
1530     I_RpcFree(pMsg->Buffer);
1531     pMsg->Buffer = NULL;
1532     RPCRT4_FreeHeader(*Header);
1533     *Header = NULL;
1534   }
1535   if (auth_data_out && status == RPC_S_OK) {
1536     *auth_length_out = auth_length;
1537     *auth_data_out = auth_data;
1538   }
1539   else
1540     HeapFree(GetProcessHeap(), 0, auth_data);
1541   HeapFree(GetProcessHeap(), 0, payload);
1542   return status;
1543 }
1544
1545 /***********************************************************************
1546  *           RPCRT4_Receive (internal)
1547  *
1548  * Receive a packet from connection and merge the fragments.
1549  */
1550 RPC_STATUS RPCRT4_Receive(RpcConnection *Connection, RpcPktHdr **Header,
1551                           PRPC_MESSAGE pMsg)
1552 {
1553     return RPCRT4_ReceiveWithAuth(Connection, Header, pMsg, NULL, NULL);
1554 }
1555
1556 /***********************************************************************
1557  *           I_RpcNegotiateTransferSyntax [RPCRT4.@]
1558  *
1559  * Negotiates the transfer syntax used by a client connection by connecting
1560  * to the server.
1561  *
1562  * PARAMS
1563  *  pMsg   [I] RPC Message structure.
1564  *  pAsync [I] Asynchronous state to set.
1565  *
1566  * RETURNS
1567  *  Success: RPC_S_OK.
1568  *  Failure: Any error code.
1569  */
1570 RPC_STATUS WINAPI I_RpcNegotiateTransferSyntax(PRPC_MESSAGE pMsg)
1571 {
1572   RpcBinding* bind = pMsg->Handle;
1573   RpcConnection* conn;
1574   RPC_STATUS status = RPC_S_OK;
1575
1576   TRACE("(%p)\n", pMsg);
1577
1578   if (!bind || bind->server)
1579   {
1580     ERR("no binding\n");
1581     return RPC_S_INVALID_BINDING;
1582   }
1583
1584   /* if we already have a connection, we don't need to negotiate again */
1585   if (!pMsg->ReservedForRuntime)
1586   {
1587     RPC_CLIENT_INTERFACE *cif = pMsg->RpcInterfaceInformation;
1588     if (!cif) return RPC_S_INTERFACE_NOT_FOUND;
1589
1590     if (!bind->Endpoint || !bind->Endpoint[0])
1591     {
1592       TRACE("automatically resolving partially bound binding\n");
1593       status = RpcEpResolveBinding(bind, cif);
1594       if (status != RPC_S_OK) return status;
1595     }
1596
1597     status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
1598                                 &cif->InterfaceId);
1599
1600     if (status == RPC_S_OK)
1601     {
1602       pMsg->ReservedForRuntime = conn;
1603       RPCRT4_AddRefBinding(bind);
1604     }
1605   }
1606
1607   return status;
1608 }
1609
1610 /***********************************************************************
1611  *           I_RpcGetBuffer [RPCRT4.@]
1612  *
1613  * Allocates a buffer for use by I_RpcSend or I_RpcSendReceive and binds to the
1614  * server interface.
1615  *
1616  * PARAMS
1617  *  pMsg [I/O] RPC message information.
1618  *
1619  * RETURNS
1620  *  Success: RPC_S_OK.
1621  *  Failure: RPC_S_INVALID_BINDING if pMsg->Handle is invalid.
1622  *           RPC_S_SERVER_UNAVAILABLE if unable to connect to server.
1623  *           ERROR_OUTOFMEMORY if buffer allocation failed.
1624  *
1625  * NOTES
1626  *  The pMsg->BufferLength field determines the size of the buffer to allocate,
1627  *  in bytes.
1628  *
1629  *  Use I_RpcFreeBuffer() to unbind from the server and free the message buffer.
1630  *
1631  * SEE ALSO
1632  *  I_RpcFreeBuffer(), I_RpcSend(), I_RpcReceive(), I_RpcSendReceive().
1633  */
1634 RPC_STATUS WINAPI I_RpcGetBuffer(PRPC_MESSAGE pMsg)
1635 {
1636   RPC_STATUS status;
1637   RpcBinding* bind = pMsg->Handle;
1638
1639   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
1640
1641   if (!bind)
1642   {
1643     ERR("no binding\n");
1644     return RPC_S_INVALID_BINDING;
1645   }
1646
1647   pMsg->Buffer = I_RpcAllocate(pMsg->BufferLength);
1648   TRACE("Buffer=%p\n", pMsg->Buffer);
1649
1650   if (!pMsg->Buffer)
1651     return ERROR_OUTOFMEMORY;
1652
1653   if (!bind->server)
1654   {
1655     status = I_RpcNegotiateTransferSyntax(pMsg);
1656     if (status != RPC_S_OK)
1657       I_RpcFree(pMsg->Buffer);
1658   }
1659   else
1660     status = RPC_S_OK;
1661
1662   return status;
1663 }
1664
1665 /***********************************************************************
1666  *           I_RpcReAllocateBuffer (internal)
1667  */
1668 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg)
1669 {
1670   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
1671   pMsg->Buffer = HeapReAlloc(GetProcessHeap(), 0, pMsg->Buffer, pMsg->BufferLength);
1672
1673   TRACE("Buffer=%p\n", pMsg->Buffer);
1674   return pMsg->Buffer ? RPC_S_OK : ERROR_OUTOFMEMORY;
1675 }
1676
1677 /***********************************************************************
1678  *           I_RpcFreeBuffer [RPCRT4.@]
1679  *
1680  * Frees a buffer allocated by I_RpcGetBuffer or I_RpcReceive and unbinds from
1681  * the server interface.
1682  *
1683  * PARAMS
1684  *  pMsg [I/O] RPC message information.
1685  *
1686  * RETURNS
1687  *  RPC_S_OK.
1688  *
1689  * SEE ALSO
1690  *  I_RpcGetBuffer(), I_RpcReceive().
1691  */
1692 RPC_STATUS WINAPI I_RpcFreeBuffer(PRPC_MESSAGE pMsg)
1693 {
1694   RpcBinding* bind = pMsg->Handle;
1695
1696   TRACE("(%p) Buffer=%p\n", pMsg, pMsg->Buffer);
1697
1698   if (!bind)
1699   {
1700     ERR("no binding\n");
1701     return RPC_S_INVALID_BINDING;
1702   }
1703
1704   if (pMsg->ReservedForRuntime)
1705   {
1706     RpcConnection *conn = pMsg->ReservedForRuntime;
1707     RPCRT4_CloseBinding(bind, conn);
1708     RPCRT4_ReleaseBinding(bind);
1709     pMsg->ReservedForRuntime = NULL;
1710   }
1711   I_RpcFree(pMsg->Buffer);
1712   return RPC_S_OK;
1713 }
1714
1715 static void CALLBACK async_apc_notifier_proc(ULONG_PTR ulParam)
1716 {
1717     RPC_ASYNC_STATE *state = (RPC_ASYNC_STATE *)ulParam;
1718     state->u.APC.NotificationRoutine(state, NULL, state->Event);
1719 }
1720
1721 static DWORD WINAPI async_notifier_proc(LPVOID p)
1722 {
1723     RpcConnection *conn = p;
1724     RPC_ASYNC_STATE *state = conn->async_state;
1725
1726     if (state && conn->ops->wait_for_incoming_data(conn) != -1)
1727     {
1728         state->Event = RpcCallComplete;
1729         switch (state->NotificationType)
1730         {
1731         case RpcNotificationTypeEvent:
1732             TRACE("RpcNotificationTypeEvent %p\n", state->u.hEvent);
1733             SetEvent(state->u.hEvent);
1734             break;
1735         case RpcNotificationTypeApc:
1736             TRACE("RpcNotificationTypeApc %p\n", state->u.APC.hThread);
1737             QueueUserAPC(async_apc_notifier_proc, state->u.APC.hThread, (ULONG_PTR)state);
1738             break;
1739         case RpcNotificationTypeIoc:
1740             TRACE("RpcNotificationTypeIoc %p, 0x%x, 0x%lx, %p\n",
1741                 state->u.IOC.hIOPort, state->u.IOC.dwNumberOfBytesTransferred,
1742                 state->u.IOC.dwCompletionKey, state->u.IOC.lpOverlapped);
1743             PostQueuedCompletionStatus(state->u.IOC.hIOPort,
1744                 state->u.IOC.dwNumberOfBytesTransferred,
1745                 state->u.IOC.dwCompletionKey,
1746                 state->u.IOC.lpOverlapped);
1747             break;
1748         case RpcNotificationTypeHwnd:
1749             TRACE("RpcNotificationTypeHwnd %p 0x%x\n", state->u.HWND.hWnd,
1750                 state->u.HWND.Msg);
1751             PostMessageW(state->u.HWND.hWnd, state->u.HWND.Msg, 0, 0);
1752             break;
1753         case RpcNotificationTypeCallback:
1754             TRACE("RpcNotificationTypeCallback %p\n", state->u.NotificationRoutine);
1755             state->u.NotificationRoutine(state, NULL, state->Event);
1756             break;
1757         case RpcNotificationTypeNone:
1758             TRACE("RpcNotificationTypeNone\n");
1759             break;
1760         default:
1761             FIXME("unknown NotificationType: %d/0x%x\n", state->NotificationType, state->NotificationType);
1762             break;
1763         }
1764     }
1765
1766     return 0;
1767 }
1768
1769 /***********************************************************************
1770  *           I_RpcSend [RPCRT4.@]
1771  *
1772  * Sends a message to the server.
1773  *
1774  * PARAMS
1775  *  pMsg [I/O] RPC message information.
1776  *
1777  * RETURNS
1778  *  Unknown.
1779  *
1780  * NOTES
1781  *  The buffer must have been allocated with I_RpcGetBuffer().
1782  *
1783  * SEE ALSO
1784  *  I_RpcGetBuffer(), I_RpcReceive(), I_RpcSendReceive().
1785  */
1786 RPC_STATUS WINAPI I_RpcSend(PRPC_MESSAGE pMsg)
1787 {
1788   RpcBinding* bind = pMsg->Handle;
1789   RpcConnection* conn;
1790   RPC_STATUS status;
1791   RpcPktHdr *hdr;
1792
1793   TRACE("(%p)\n", pMsg);
1794   if (!bind || bind->server || !pMsg->ReservedForRuntime) return RPC_S_INVALID_BINDING;
1795
1796   conn = pMsg->ReservedForRuntime;
1797
1798   hdr = RPCRT4_BuildRequestHeader(pMsg->DataRepresentation,
1799                                   pMsg->BufferLength,
1800                                   pMsg->ProcNum & ~RPC_FLAGS_VALID_BIT,
1801                                   &bind->ObjectUuid);
1802   if (!hdr)
1803     return ERROR_OUTOFMEMORY;
1804   hdr->common.call_id = conn->NextCallId++;
1805
1806   status = RPCRT4_Send(conn, hdr, pMsg->Buffer, pMsg->BufferLength);
1807
1808   RPCRT4_FreeHeader(hdr);
1809
1810   if (status == RPC_S_OK && pMsg->RpcFlags & RPC_BUFFER_ASYNC)
1811   {
1812     if (!QueueUserWorkItem(async_notifier_proc, conn, WT_EXECUTEDEFAULT | WT_EXECUTELONGFUNCTION))
1813         status = RPC_S_OUT_OF_RESOURCES;
1814   }
1815
1816   return status;
1817 }
1818
1819 /* is this status something that the server can't recover from? */
1820 static inline BOOL is_hard_error(RPC_STATUS status)
1821 {
1822     switch (status)
1823     {
1824     case 0: /* user-defined fault */
1825     case ERROR_ACCESS_DENIED:
1826     case ERROR_INVALID_PARAMETER:
1827     case RPC_S_PROTOCOL_ERROR:
1828     case RPC_S_CALL_FAILED:
1829     case RPC_S_CALL_FAILED_DNE:
1830     case RPC_S_SEC_PKG_ERROR:
1831         return TRUE;
1832     default:
1833         return FALSE;
1834     }
1835 }
1836
1837 /***********************************************************************
1838  *           I_RpcReceive [RPCRT4.@]
1839  */
1840 RPC_STATUS WINAPI I_RpcReceive(PRPC_MESSAGE pMsg)
1841 {
1842   RpcBinding* bind = pMsg->Handle;
1843   RPC_STATUS status;
1844   RpcPktHdr *hdr = NULL;
1845   RpcConnection *conn;
1846
1847   TRACE("(%p)\n", pMsg);
1848   if (!bind || bind->server || !pMsg->ReservedForRuntime) return RPC_S_INVALID_BINDING;
1849
1850   conn = pMsg->ReservedForRuntime;
1851   status = RPCRT4_Receive(conn, &hdr, pMsg);
1852   if (status != RPC_S_OK) {
1853     WARN("receive failed with error %x\n", status);
1854     goto fail;
1855   }
1856
1857   switch (hdr->common.ptype) {
1858   case PKT_RESPONSE:
1859     break;
1860   case PKT_FAULT:
1861     ERR ("we got fault packet with status 0x%x\n", hdr->fault.status);
1862     status = NCA2RPC_STATUS(hdr->fault.status);
1863     if (is_hard_error(status))
1864         goto fail;
1865     break;
1866   default:
1867     WARN("bad packet type %d\n", hdr->common.ptype);
1868     status = RPC_S_PROTOCOL_ERROR;
1869     goto fail;
1870   }
1871
1872   /* success */
1873   RPCRT4_FreeHeader(hdr);
1874   return status;
1875
1876 fail:
1877   RPCRT4_FreeHeader(hdr);
1878   RPCRT4_DestroyConnection(conn);
1879   pMsg->ReservedForRuntime = NULL;
1880   return status;
1881 }
1882
1883 /***********************************************************************
1884  *           I_RpcSendReceive [RPCRT4.@]
1885  *
1886  * Sends a message to the server and receives the response.
1887  *
1888  * PARAMS
1889  *  pMsg [I/O] RPC message information.
1890  *
1891  * RETURNS
1892  *  Success: RPC_S_OK.
1893  *  Failure: Any error code.
1894  *
1895  * NOTES
1896  *  The buffer must have been allocated with I_RpcGetBuffer().
1897  *
1898  * SEE ALSO
1899  *  I_RpcGetBuffer(), I_RpcSend(), I_RpcReceive().
1900  */
1901 RPC_STATUS WINAPI I_RpcSendReceive(PRPC_MESSAGE pMsg)
1902 {
1903   RPC_STATUS status;
1904   void *original_buffer;
1905
1906   TRACE("(%p)\n", pMsg);
1907
1908   original_buffer = pMsg->Buffer;
1909   status = I_RpcSend(pMsg);
1910   if (status == RPC_S_OK)
1911     status = I_RpcReceive(pMsg);
1912   /* free the buffer replaced by a new buffer in I_RpcReceive */
1913   if (status == RPC_S_OK)
1914     I_RpcFree(original_buffer);
1915   return status;
1916 }
1917
1918 /***********************************************************************
1919  *           I_RpcAsyncSetHandle [RPCRT4.@]
1920  *
1921  * Sets the asynchronous state of the handle contained in the RPC message
1922  * structure.
1923  *
1924  * PARAMS
1925  *  pMsg   [I] RPC Message structure.
1926  *  pAsync [I] Asynchronous state to set.
1927  *
1928  * RETURNS
1929  *  Success: RPC_S_OK.
1930  *  Failure: Any error code.
1931  */
1932 RPC_STATUS WINAPI I_RpcAsyncSetHandle(PRPC_MESSAGE pMsg, PRPC_ASYNC_STATE pAsync)
1933 {
1934     RpcBinding* bind = pMsg->Handle;
1935     RpcConnection *conn;
1936
1937     TRACE("(%p, %p)\n", pMsg, pAsync);
1938
1939     if (!bind || bind->server || !pMsg->ReservedForRuntime) return RPC_S_INVALID_BINDING;
1940
1941     conn = pMsg->ReservedForRuntime;
1942     conn->async_state = pAsync;
1943
1944     return RPC_S_OK;
1945 }
1946
1947 /***********************************************************************
1948  *           I_RpcAsyncAbortCall [RPCRT4.@]
1949  *
1950  * Aborts an asynchronous call.
1951  *
1952  * PARAMS
1953  *  pAsync        [I] Asynchronous state.
1954  *  ExceptionCode [I] Exception code.
1955  *
1956  * RETURNS
1957  *  Success: RPC_S_OK.
1958  *  Failure: Any error code.
1959  */
1960 RPC_STATUS WINAPI I_RpcAsyncAbortCall(PRPC_ASYNC_STATE pAsync, ULONG ExceptionCode)
1961 {
1962     FIXME("(%p, %d): stub\n", pAsync, ExceptionCode);
1963     return RPC_S_INVALID_ASYNC_HANDLE;
1964 }