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