rpcrt4: Implement client impersonation.
[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->common), 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->common));
221   if (header == NULL)
222     return NULL;
223
224   RPCRT4_BuildCommonHeader(header, PKT_AUTH3, DataRepresentation);
225   header->common.frag_len = sizeof(header->common);
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_Send (internal)
1181  * 
1182  * Transmit a packet over connection in acceptable fragments.
1183  */
1184 RPC_STATUS RPCRT4_Send(RpcConnection *Connection, RpcPktHdr *Header,
1185                        void *Buffer, unsigned int BufferLength)
1186 {
1187   RPC_STATUS r;
1188
1189   if (packet_does_auth_negotiation(Header) &&
1190       Connection->AuthInfo &&
1191       !rpcrt4_conn_is_authorized(Connection))
1192   {
1193       unsigned int out_size = 0;
1194       unsigned char *out_buffer;
1195
1196       r = rpcrt4_conn_authorize(Connection, TRUE, NULL, 0, NULL, &out_size);
1197       if (r != RPC_S_OK) return r;
1198
1199       out_buffer = HeapAlloc(GetProcessHeap(), 0, out_size);
1200       if (!out_buffer) return RPC_S_OUT_OF_RESOURCES;
1201
1202       /* tack on a negotiate packet */
1203       r = rpcrt4_conn_authorize(Connection, TRUE, NULL, 0, out_buffer, &out_size);
1204       if (r == RPC_S_OK)
1205           r = RPCRT4_SendWithAuth(Connection, Header, Buffer, BufferLength, out_buffer, out_size);
1206
1207       HeapFree(GetProcessHeap(), 0, out_buffer);
1208   }
1209   else
1210     r = RPCRT4_SendWithAuth(Connection, Header, Buffer, BufferLength, NULL, 0);
1211
1212   return r;
1213 }
1214
1215 /* validates version and frag_len fields */
1216 RPC_STATUS RPCRT4_ValidateCommonHeader(const RpcPktCommonHdr *hdr)
1217 {
1218   DWORD hdr_length;
1219
1220   /* verify if the header really makes sense */
1221   if (hdr->rpc_ver != RPC_VER_MAJOR ||
1222       hdr->rpc_ver_minor != RPC_VER_MINOR)
1223   {
1224     WARN("unhandled packet version\n");
1225     return RPC_S_PROTOCOL_ERROR;
1226   }
1227
1228   hdr_length = RPCRT4_GetHeaderSize((const RpcPktHdr*)hdr);
1229   if (hdr_length == 0)
1230   {
1231     WARN("header length == 0\n");
1232     return RPC_S_PROTOCOL_ERROR;
1233   }
1234
1235   if (hdr->frag_len < hdr_length)
1236   {
1237     WARN("bad frag length %d\n", hdr->frag_len);
1238     return RPC_S_PROTOCOL_ERROR;
1239   }
1240
1241   return RPC_S_OK;
1242 }
1243
1244 /***********************************************************************
1245  *           RPCRT4_default_receive_fragment (internal)
1246  * 
1247  * Receive a fragment from a connection.
1248  */
1249 static RPC_STATUS RPCRT4_default_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
1250 {
1251   RPC_STATUS status;
1252   DWORD hdr_length;
1253   LONG dwRead;
1254   RpcPktCommonHdr common_hdr;
1255
1256   *Header = NULL;
1257   *Payload = NULL;
1258
1259   TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
1260
1261   /* read packet common header */
1262   dwRead = rpcrt4_conn_read(Connection, &common_hdr, sizeof(common_hdr));
1263   if (dwRead != sizeof(common_hdr)) {
1264     WARN("Short read of header, %d bytes\n", dwRead);
1265     status = RPC_S_CALL_FAILED;
1266     goto fail;
1267   }
1268
1269   status = RPCRT4_ValidateCommonHeader(&common_hdr);
1270   if (status != RPC_S_OK) goto fail;
1271
1272   hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
1273   if (hdr_length == 0) {
1274     WARN("header length == 0\n");
1275     status = RPC_S_PROTOCOL_ERROR;
1276     goto fail;
1277   }
1278
1279   *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
1280   memcpy(*Header, &common_hdr, sizeof(common_hdr));
1281
1282   /* read the rest of packet header */
1283   dwRead = rpcrt4_conn_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
1284   if (dwRead != hdr_length - sizeof(common_hdr)) {
1285     WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
1286     status = RPC_S_CALL_FAILED;
1287     goto fail;
1288   }
1289
1290   if (common_hdr.frag_len - hdr_length)
1291   {
1292     *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
1293     if (!*Payload)
1294     {
1295       status = RPC_S_OUT_OF_RESOURCES;
1296       goto fail;
1297     }
1298
1299     dwRead = rpcrt4_conn_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
1300     if (dwRead != common_hdr.frag_len - hdr_length)
1301     {
1302       WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
1303       status = RPC_S_CALL_FAILED;
1304       goto fail;
1305     }
1306   }
1307   else
1308     *Payload = NULL;
1309
1310   /* success */
1311   status = RPC_S_OK;
1312
1313 fail:
1314   if (status != RPC_S_OK) {
1315     RPCRT4_FreeHeader(*Header);
1316     *Header = NULL;
1317     HeapFree(GetProcessHeap(), 0, *Payload);
1318     *Payload = NULL;
1319   }
1320   return status;
1321 }
1322
1323 static RPC_STATUS RPCRT4_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
1324 {
1325     if (Connection->ops->receive_fragment)
1326         return Connection->ops->receive_fragment(Connection, Header, Payload);
1327     else
1328         return RPCRT4_default_receive_fragment(Connection, Header, Payload);
1329 }
1330
1331 /***********************************************************************
1332  *           RPCRT4_ReceiveWithAuth (internal)
1333  *
1334  * Receive a packet from connection, merge the fragments and return the auth
1335  * data.
1336  */
1337 RPC_STATUS RPCRT4_ReceiveWithAuth(RpcConnection *Connection, RpcPktHdr **Header,
1338                                   PRPC_MESSAGE pMsg,
1339                                   unsigned char **auth_data_out,
1340                                   ULONG *auth_length_out)
1341 {
1342   RPC_STATUS status;
1343   DWORD hdr_length;
1344   unsigned short first_flag;
1345   ULONG data_length;
1346   ULONG buffer_length;
1347   ULONG auth_length = 0;
1348   unsigned char *auth_data = NULL;
1349   RpcPktHdr *CurrentHeader = NULL;
1350   void *payload = NULL;
1351
1352   *Header = NULL;
1353   pMsg->Buffer = NULL;
1354   if (auth_data_out) *auth_data_out = NULL;
1355   if (auth_length_out) *auth_length_out = 0;
1356
1357   TRACE("(%p, %p, %p, %p)\n", Connection, Header, pMsg, auth_data_out);
1358
1359   RPCRT4_SetThreadCurrentConnection(Connection);
1360
1361   status = RPCRT4_receive_fragment(Connection, Header, &payload);
1362   if (status != RPC_S_OK) goto fail;
1363
1364   hdr_length = RPCRT4_GetHeaderSize(*Header);
1365
1366   /* read packet body */
1367   switch ((*Header)->common.ptype) {
1368   case PKT_RESPONSE:
1369     pMsg->BufferLength = (*Header)->response.alloc_hint;
1370     break;
1371   case PKT_REQUEST:
1372     pMsg->BufferLength = (*Header)->request.alloc_hint;
1373     break;
1374   default:
1375     pMsg->BufferLength = (*Header)->common.frag_len - hdr_length - RPC_AUTH_VERIFIER_LEN(&(*Header)->common);
1376   }
1377
1378   TRACE("buffer length = %u\n", pMsg->BufferLength);
1379
1380   pMsg->Buffer = I_RpcAllocate(pMsg->BufferLength);
1381   if (!pMsg->Buffer)
1382   {
1383     status = ERROR_OUTOFMEMORY;
1384     goto fail;
1385   }
1386
1387   first_flag = RPC_FLG_FIRST;
1388   auth_length = (*Header)->common.auth_len;
1389   if (auth_length) {
1390     auth_data = HeapAlloc(GetProcessHeap(), 0, RPC_AUTH_VERIFIER_LEN(&(*Header)->common));
1391     if (!auth_data) {
1392       status = RPC_S_OUT_OF_RESOURCES;
1393       goto fail;
1394     }
1395   }
1396   CurrentHeader = *Header;
1397   buffer_length = 0;
1398   while (TRUE)
1399   {
1400     unsigned int header_auth_len = RPC_AUTH_VERIFIER_LEN(&CurrentHeader->common);
1401
1402     /* verify header fields */
1403
1404     if ((CurrentHeader->common.frag_len < hdr_length) ||
1405         (CurrentHeader->common.frag_len - hdr_length < header_auth_len)) {
1406       WARN("frag_len %d too small for hdr_length %d and auth_len %d\n",
1407         CurrentHeader->common.frag_len, hdr_length, CurrentHeader->common.auth_len);
1408       status = RPC_S_PROTOCOL_ERROR;
1409       goto fail;
1410     }
1411
1412     if (CurrentHeader->common.auth_len != auth_length) {
1413       WARN("auth_len header field changed from %d to %d\n",
1414         auth_length, CurrentHeader->common.auth_len);
1415       status = RPC_S_PROTOCOL_ERROR;
1416       goto fail;
1417     }
1418
1419     if ((CurrentHeader->common.flags & RPC_FLG_FIRST) != first_flag) {
1420       TRACE("invalid packet flags\n");
1421       status = RPC_S_PROTOCOL_ERROR;
1422       goto fail;
1423     }
1424
1425     data_length = CurrentHeader->common.frag_len - hdr_length - header_auth_len;
1426     if (data_length + buffer_length > pMsg->BufferLength) {
1427       TRACE("allocation hint exceeded, new buffer length = %d\n",
1428         data_length + buffer_length);
1429       pMsg->BufferLength = data_length + buffer_length;
1430       status = I_RpcReAllocateBuffer(pMsg);
1431       if (status != RPC_S_OK) goto fail;
1432     }
1433
1434     memcpy((unsigned char *)pMsg->Buffer + buffer_length, payload, data_length);
1435
1436     if (header_auth_len) {
1437       if (header_auth_len < sizeof(RpcAuthVerifier) ||
1438           header_auth_len > RPC_AUTH_VERIFIER_LEN(&(*Header)->common)) {
1439         WARN("bad auth verifier length %d\n", header_auth_len);
1440         status = RPC_S_PROTOCOL_ERROR;
1441         goto fail;
1442       }
1443
1444       /* FIXME: we should accumulate authentication data for the bind,
1445        * bind_ack, alter_context and alter_context_response if necessary.
1446        * however, the details of how this is done is very sketchy in the
1447        * DCE/RPC spec. for all other packet types that have authentication
1448        * verifier data then it is just duplicated in all the fragments */
1449       memcpy(auth_data, (unsigned char *)payload + data_length, header_auth_len);
1450
1451       /* these packets are handled specially, not by the generic SecurePacket
1452        * function */
1453       if (!packet_does_auth_negotiation(*Header) && rpcrt4_conn_is_authorized(Connection))
1454       {
1455         status = rpcrt4_conn_secure_packet(Connection, SECURE_PACKET_RECEIVE,
1456             CurrentHeader, hdr_length,
1457             (unsigned char *)pMsg->Buffer + buffer_length, data_length,
1458             (RpcAuthVerifier *)auth_data,
1459             auth_data + sizeof(RpcAuthVerifier),
1460             header_auth_len - sizeof(RpcAuthVerifier));
1461         if (status != RPC_S_OK) goto fail;
1462       }
1463     }
1464
1465     buffer_length += data_length;
1466     if (!(CurrentHeader->common.flags & RPC_FLG_LAST)) {
1467       TRACE("next header\n");
1468
1469       if (*Header != CurrentHeader)
1470       {
1471           RPCRT4_FreeHeader(CurrentHeader);
1472           CurrentHeader = NULL;
1473       }
1474       HeapFree(GetProcessHeap(), 0, payload);
1475       payload = NULL;
1476
1477       status = RPCRT4_receive_fragment(Connection, &CurrentHeader, &payload);
1478       if (status != RPC_S_OK) goto fail;
1479
1480       first_flag = 0;
1481     } else {
1482       break;
1483     }
1484   }
1485   pMsg->BufferLength = buffer_length;
1486
1487   /* success */
1488   status = RPC_S_OK;
1489
1490 fail:
1491   RPCRT4_SetThreadCurrentConnection(NULL);
1492   if (CurrentHeader != *Header)
1493     RPCRT4_FreeHeader(CurrentHeader);
1494   if (status != RPC_S_OK) {
1495     I_RpcFree(pMsg->Buffer);
1496     pMsg->Buffer = NULL;
1497     RPCRT4_FreeHeader(*Header);
1498     *Header = NULL;
1499   }
1500   if (auth_data_out && status == RPC_S_OK) {
1501     *auth_length_out = auth_length;
1502     *auth_data_out = auth_data;
1503   }
1504   else
1505     HeapFree(GetProcessHeap(), 0, auth_data);
1506   HeapFree(GetProcessHeap(), 0, payload);
1507   return status;
1508 }
1509
1510 /***********************************************************************
1511  *           RPCRT4_Receive (internal)
1512  *
1513  * Receive a packet from connection and merge the fragments.
1514  */
1515 RPC_STATUS RPCRT4_Receive(RpcConnection *Connection, RpcPktHdr **Header,
1516                           PRPC_MESSAGE pMsg)
1517 {
1518     return RPCRT4_ReceiveWithAuth(Connection, Header, pMsg, NULL, NULL);
1519 }
1520
1521 /***********************************************************************
1522  *           I_RpcNegotiateTransferSyntax [RPCRT4.@]
1523  *
1524  * Negotiates the transfer syntax used by a client connection by connecting
1525  * to the server.
1526  *
1527  * PARAMS
1528  *  pMsg   [I] RPC Message structure.
1529  *  pAsync [I] Asynchronous state to set.
1530  *
1531  * RETURNS
1532  *  Success: RPC_S_OK.
1533  *  Failure: Any error code.
1534  */
1535 RPC_STATUS WINAPI I_RpcNegotiateTransferSyntax(PRPC_MESSAGE pMsg)
1536 {
1537   RpcBinding* bind = pMsg->Handle;
1538   RpcConnection* conn;
1539   RPC_STATUS status = RPC_S_OK;
1540
1541   TRACE("(%p)\n", pMsg);
1542
1543   if (!bind || bind->server)
1544   {
1545     ERR("no binding\n");
1546     return RPC_S_INVALID_BINDING;
1547   }
1548
1549   /* if we already have a connection, we don't need to negotiate again */
1550   if (!pMsg->ReservedForRuntime)
1551   {
1552     RPC_CLIENT_INTERFACE *cif = pMsg->RpcInterfaceInformation;
1553     if (!cif) return RPC_S_INTERFACE_NOT_FOUND;
1554
1555     if (!bind->Endpoint || !bind->Endpoint[0])
1556     {
1557       TRACE("automatically resolving partially bound binding\n");
1558       status = RpcEpResolveBinding(bind, cif);
1559       if (status != RPC_S_OK) return status;
1560     }
1561
1562     status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
1563                                 &cif->InterfaceId);
1564
1565     if (status == RPC_S_OK)
1566     {
1567       pMsg->ReservedForRuntime = conn;
1568       RPCRT4_AddRefBinding(bind);
1569     }
1570   }
1571
1572   return status;
1573 }
1574
1575 /***********************************************************************
1576  *           I_RpcGetBuffer [RPCRT4.@]
1577  *
1578  * Allocates a buffer for use by I_RpcSend or I_RpcSendReceive and binds to the
1579  * server interface.
1580  *
1581  * PARAMS
1582  *  pMsg [I/O] RPC message information.
1583  *
1584  * RETURNS
1585  *  Success: RPC_S_OK.
1586  *  Failure: RPC_S_INVALID_BINDING if pMsg->Handle is invalid.
1587  *           RPC_S_SERVER_UNAVAILABLE if unable to connect to server.
1588  *           ERROR_OUTOFMEMORY if buffer allocation failed.
1589  *
1590  * NOTES
1591  *  The pMsg->BufferLength field determines the size of the buffer to allocate,
1592  *  in bytes.
1593  *
1594  *  Use I_RpcFreeBuffer() to unbind from the server and free the message buffer.
1595  *
1596  * SEE ALSO
1597  *  I_RpcFreeBuffer(), I_RpcSend(), I_RpcReceive(), I_RpcSendReceive().
1598  */
1599 RPC_STATUS WINAPI I_RpcGetBuffer(PRPC_MESSAGE pMsg)
1600 {
1601   RPC_STATUS status;
1602   RpcBinding* bind = pMsg->Handle;
1603
1604   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
1605
1606   if (!bind)
1607   {
1608     ERR("no binding\n");
1609     return RPC_S_INVALID_BINDING;
1610   }
1611
1612   pMsg->Buffer = I_RpcAllocate(pMsg->BufferLength);
1613   TRACE("Buffer=%p\n", pMsg->Buffer);
1614
1615   if (!pMsg->Buffer)
1616     return ERROR_OUTOFMEMORY;
1617
1618   if (!bind->server)
1619   {
1620     status = I_RpcNegotiateTransferSyntax(pMsg);
1621     if (status != RPC_S_OK)
1622       I_RpcFree(pMsg->Buffer);
1623   }
1624   else
1625     status = RPC_S_OK;
1626
1627   return status;
1628 }
1629
1630 /***********************************************************************
1631  *           I_RpcReAllocateBuffer (internal)
1632  */
1633 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg)
1634 {
1635   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
1636   pMsg->Buffer = HeapReAlloc(GetProcessHeap(), 0, pMsg->Buffer, pMsg->BufferLength);
1637
1638   TRACE("Buffer=%p\n", pMsg->Buffer);
1639   return pMsg->Buffer ? RPC_S_OK : ERROR_OUTOFMEMORY;
1640 }
1641
1642 /***********************************************************************
1643  *           I_RpcFreeBuffer [RPCRT4.@]
1644  *
1645  * Frees a buffer allocated by I_RpcGetBuffer or I_RpcReceive and unbinds from
1646  * the server interface.
1647  *
1648  * PARAMS
1649  *  pMsg [I/O] RPC message information.
1650  *
1651  * RETURNS
1652  *  RPC_S_OK.
1653  *
1654  * SEE ALSO
1655  *  I_RpcGetBuffer(), I_RpcReceive().
1656  */
1657 RPC_STATUS WINAPI I_RpcFreeBuffer(PRPC_MESSAGE pMsg)
1658 {
1659   RpcBinding* bind = pMsg->Handle;
1660
1661   TRACE("(%p) Buffer=%p\n", pMsg, pMsg->Buffer);
1662
1663   if (!bind)
1664   {
1665     ERR("no binding\n");
1666     return RPC_S_INVALID_BINDING;
1667   }
1668
1669   if (pMsg->ReservedForRuntime)
1670   {
1671     RpcConnection *conn = pMsg->ReservedForRuntime;
1672     RPCRT4_CloseBinding(bind, conn);
1673     RPCRT4_ReleaseBinding(bind);
1674     pMsg->ReservedForRuntime = NULL;
1675   }
1676   I_RpcFree(pMsg->Buffer);
1677   return RPC_S_OK;
1678 }
1679
1680 static void CALLBACK async_apc_notifier_proc(ULONG_PTR ulParam)
1681 {
1682     RPC_ASYNC_STATE *state = (RPC_ASYNC_STATE *)ulParam;
1683     state->u.APC.NotificationRoutine(state, NULL, state->Event);
1684 }
1685
1686 static DWORD WINAPI async_notifier_proc(LPVOID p)
1687 {
1688     RpcConnection *conn = p;
1689     RPC_ASYNC_STATE *state = conn->async_state;
1690
1691     if (state && conn->ops->wait_for_incoming_data(conn) != -1)
1692     {
1693         state->Event = RpcCallComplete;
1694         switch (state->NotificationType)
1695         {
1696         case RpcNotificationTypeEvent:
1697             TRACE("RpcNotificationTypeEvent %p\n", state->u.hEvent);
1698             SetEvent(state->u.hEvent);
1699             break;
1700         case RpcNotificationTypeApc:
1701             TRACE("RpcNotificationTypeApc %p\n", state->u.APC.hThread);
1702             QueueUserAPC(async_apc_notifier_proc, state->u.APC.hThread, (ULONG_PTR)state);
1703             break;
1704         case RpcNotificationTypeIoc:
1705             TRACE("RpcNotificationTypeIoc %p, 0x%x, 0x%lx, %p\n",
1706                 state->u.IOC.hIOPort, state->u.IOC.dwNumberOfBytesTransferred,
1707                 state->u.IOC.dwCompletionKey, state->u.IOC.lpOverlapped);
1708             PostQueuedCompletionStatus(state->u.IOC.hIOPort,
1709                 state->u.IOC.dwNumberOfBytesTransferred,
1710                 state->u.IOC.dwCompletionKey,
1711                 state->u.IOC.lpOverlapped);
1712             break;
1713         case RpcNotificationTypeHwnd:
1714             TRACE("RpcNotificationTypeHwnd %p 0x%x\n", state->u.HWND.hWnd,
1715                 state->u.HWND.Msg);
1716             PostMessageW(state->u.HWND.hWnd, state->u.HWND.Msg, 0, 0);
1717             break;
1718         case RpcNotificationTypeCallback:
1719             TRACE("RpcNotificationTypeCallback %p\n", state->u.NotificationRoutine);
1720             state->u.NotificationRoutine(state, NULL, state->Event);
1721             break;
1722         case RpcNotificationTypeNone:
1723             TRACE("RpcNotificationTypeNone\n");
1724             break;
1725         default:
1726             FIXME("unknown NotificationType: %d/0x%x\n", state->NotificationType, state->NotificationType);
1727             break;
1728         }
1729     }
1730
1731     return 0;
1732 }
1733
1734 /***********************************************************************
1735  *           I_RpcSend [RPCRT4.@]
1736  *
1737  * Sends a message to the server.
1738  *
1739  * PARAMS
1740  *  pMsg [I/O] RPC message information.
1741  *
1742  * RETURNS
1743  *  Unknown.
1744  *
1745  * NOTES
1746  *  The buffer must have been allocated with I_RpcGetBuffer().
1747  *
1748  * SEE ALSO
1749  *  I_RpcGetBuffer(), I_RpcReceive(), I_RpcSendReceive().
1750  */
1751 RPC_STATUS WINAPI I_RpcSend(PRPC_MESSAGE pMsg)
1752 {
1753   RpcBinding* bind = pMsg->Handle;
1754   RpcConnection* conn;
1755   RPC_STATUS status;
1756   RpcPktHdr *hdr;
1757
1758   TRACE("(%p)\n", pMsg);
1759   if (!bind || bind->server || !pMsg->ReservedForRuntime) return RPC_S_INVALID_BINDING;
1760
1761   conn = pMsg->ReservedForRuntime;
1762
1763   hdr = RPCRT4_BuildRequestHeader(pMsg->DataRepresentation,
1764                                   pMsg->BufferLength,
1765                                   pMsg->ProcNum & ~RPC_FLAGS_VALID_BIT,
1766                                   &bind->ObjectUuid);
1767   if (!hdr)
1768     return ERROR_OUTOFMEMORY;
1769   hdr->common.call_id = conn->NextCallId++;
1770
1771   status = RPCRT4_Send(conn, hdr, pMsg->Buffer, pMsg->BufferLength);
1772
1773   RPCRT4_FreeHeader(hdr);
1774
1775   if (status == RPC_S_OK && pMsg->RpcFlags & RPC_BUFFER_ASYNC)
1776   {
1777     if (!QueueUserWorkItem(async_notifier_proc, conn, WT_EXECUTEDEFAULT | WT_EXECUTELONGFUNCTION))
1778         status = RPC_S_OUT_OF_RESOURCES;
1779   }
1780
1781   return status;
1782 }
1783
1784 /* is this status something that the server can't recover from? */
1785 static inline BOOL is_hard_error(RPC_STATUS status)
1786 {
1787     switch (status)
1788     {
1789     case 0: /* user-defined fault */
1790     case ERROR_ACCESS_DENIED:
1791     case ERROR_INVALID_PARAMETER:
1792     case RPC_S_PROTOCOL_ERROR:
1793     case RPC_S_CALL_FAILED:
1794     case RPC_S_CALL_FAILED_DNE:
1795     case RPC_S_SEC_PKG_ERROR:
1796         return TRUE;
1797     default:
1798         return FALSE;
1799     }
1800 }
1801
1802 /***********************************************************************
1803  *           I_RpcReceive [RPCRT4.@]
1804  */
1805 RPC_STATUS WINAPI I_RpcReceive(PRPC_MESSAGE pMsg)
1806 {
1807   RpcBinding* bind = pMsg->Handle;
1808   RPC_STATUS status;
1809   RpcPktHdr *hdr = NULL;
1810   RpcConnection *conn;
1811
1812   TRACE("(%p)\n", pMsg);
1813   if (!bind || bind->server || !pMsg->ReservedForRuntime) return RPC_S_INVALID_BINDING;
1814
1815   conn = pMsg->ReservedForRuntime;
1816   status = RPCRT4_Receive(conn, &hdr, pMsg);
1817   if (status != RPC_S_OK) {
1818     WARN("receive failed with error %x\n", status);
1819     goto fail;
1820   }
1821
1822   switch (hdr->common.ptype) {
1823   case PKT_RESPONSE:
1824     break;
1825   case PKT_FAULT:
1826     ERR ("we got fault packet with status 0x%x\n", hdr->fault.status);
1827     status = NCA2RPC_STATUS(hdr->fault.status);
1828     if (is_hard_error(status))
1829         goto fail;
1830     break;
1831   default:
1832     WARN("bad packet type %d\n", hdr->common.ptype);
1833     status = RPC_S_PROTOCOL_ERROR;
1834     goto fail;
1835   }
1836
1837   /* success */
1838   RPCRT4_FreeHeader(hdr);
1839   return status;
1840
1841 fail:
1842   RPCRT4_FreeHeader(hdr);
1843   RPCRT4_DestroyConnection(conn);
1844   pMsg->ReservedForRuntime = NULL;
1845   return status;
1846 }
1847
1848 /***********************************************************************
1849  *           I_RpcSendReceive [RPCRT4.@]
1850  *
1851  * Sends a message to the server and receives the response.
1852  *
1853  * PARAMS
1854  *  pMsg [I/O] RPC message information.
1855  *
1856  * RETURNS
1857  *  Success: RPC_S_OK.
1858  *  Failure: Any error code.
1859  *
1860  * NOTES
1861  *  The buffer must have been allocated with I_RpcGetBuffer().
1862  *
1863  * SEE ALSO
1864  *  I_RpcGetBuffer(), I_RpcSend(), I_RpcReceive().
1865  */
1866 RPC_STATUS WINAPI I_RpcSendReceive(PRPC_MESSAGE pMsg)
1867 {
1868   RPC_STATUS status;
1869   void *original_buffer;
1870
1871   TRACE("(%p)\n", pMsg);
1872
1873   original_buffer = pMsg->Buffer;
1874   status = I_RpcSend(pMsg);
1875   if (status == RPC_S_OK)
1876     status = I_RpcReceive(pMsg);
1877   /* free the buffer replaced by a new buffer in I_RpcReceive */
1878   if (status == RPC_S_OK)
1879     I_RpcFree(original_buffer);
1880   return status;
1881 }
1882
1883 /***********************************************************************
1884  *           I_RpcAsyncSetHandle [RPCRT4.@]
1885  *
1886  * Sets the asynchronous state of the handle contained in the RPC message
1887  * structure.
1888  *
1889  * PARAMS
1890  *  pMsg   [I] RPC Message structure.
1891  *  pAsync [I] Asynchronous state to set.
1892  *
1893  * RETURNS
1894  *  Success: RPC_S_OK.
1895  *  Failure: Any error code.
1896  */
1897 RPC_STATUS WINAPI I_RpcAsyncSetHandle(PRPC_MESSAGE pMsg, PRPC_ASYNC_STATE pAsync)
1898 {
1899     RpcBinding* bind = pMsg->Handle;
1900     RpcConnection *conn;
1901
1902     TRACE("(%p, %p)\n", pMsg, pAsync);
1903
1904     if (!bind || bind->server || !pMsg->ReservedForRuntime) return RPC_S_INVALID_BINDING;
1905
1906     conn = pMsg->ReservedForRuntime;
1907     conn->async_state = pAsync;
1908
1909     return RPC_S_OK;
1910 }
1911
1912 /***********************************************************************
1913  *           I_RpcAsyncAbortCall [RPCRT4.@]
1914  *
1915  * Aborts an asynchronous call.
1916  *
1917  * PARAMS
1918  *  pAsync        [I] Asynchronous state.
1919  *  ExceptionCode [I] Exception code.
1920  *
1921  * RETURNS
1922  *  Success: RPC_S_OK.
1923  *  Failure: Any error code.
1924  */
1925 RPC_STATUS WINAPI I_RpcAsyncAbortCall(PRPC_ASYNC_STATE pAsync, ULONG ExceptionCode)
1926 {
1927     FIXME("(%p, %d): stub\n", pAsync, ExceptionCode);
1928     return RPC_S_INVALID_ASYNC_HANDLE;
1929 }