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