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