rpcrt4: Store the assoc_group_id field returned from the bind_ack packet and use...
[wine/multimedia.git] / dlls / rpcrt4 / rpc_message.c
blobbdd9d124bfb475f47687cc9704e397ba8a2662d2
1 /*
2 * RPC messages
4 * Copyright 2001-2002 Ove Kåven, TransGaming Technologies
5 * Copyright 2004 Filip Navara
6 * Copyright 2006 CodeWeavers
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.
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.
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
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <string.h>
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winerror.h"
31 #include "rpc.h"
32 #include "rpcndr.h"
33 #include "rpcdcep.h"
35 #include "wine/debug.h"
37 #include "rpc_binding.h"
38 #include "rpc_misc.h"
39 #include "rpc_defs.h"
40 #include "rpc_message.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
44 /* note: the DCE/RPC spec says the alignment amount should be 4, but
45 * MS/RPC servers seem to always use 16 */
46 #define AUTH_ALIGNMENT 16
48 /* gets the amount needed to round a value up to the specified alignment */
49 #define ROUND_UP_AMOUNT(value, alignment) \
50 (((alignment) - (((value) % (alignment)))) % (alignment))
51 #define ROUND_UP(value, alignment) (((value) + ((alignment) - 1)) & ~((alignment)-1))
53 enum secure_packet_direction
55 SECURE_PACKET_SEND,
56 SECURE_PACKET_RECEIVE
59 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg);
61 static DWORD RPCRT4_GetHeaderSize(const RpcPktHdr *Header)
63 static const DWORD header_sizes[] = {
64 sizeof(Header->request), 0, sizeof(Header->response),
65 sizeof(Header->fault), 0, 0, 0, 0, 0, 0, 0, sizeof(Header->bind),
66 sizeof(Header->bind_ack), sizeof(Header->bind_nack),
67 0, 0, 0, 0, 0
69 ULONG ret = 0;
71 if (Header->common.ptype < sizeof(header_sizes) / sizeof(header_sizes[0])) {
72 ret = header_sizes[Header->common.ptype];
73 if (ret == 0)
74 FIXME("unhandled packet type\n");
75 if (Header->common.flags & RPC_FLG_OBJECT_UUID)
76 ret += sizeof(UUID);
77 } else {
78 TRACE("invalid packet type\n");
81 return ret;
84 static int packet_has_body(const RpcPktHdr *Header)
86 return (Header->common.ptype == PKT_FAULT) ||
87 (Header->common.ptype == PKT_REQUEST) ||
88 (Header->common.ptype == PKT_RESPONSE);
91 static int packet_has_auth_verifier(const RpcPktHdr *Header)
93 return !(Header->common.ptype == PKT_BIND_NACK) &&
94 !(Header->common.ptype == PKT_SHUTDOWN);
97 static VOID RPCRT4_BuildCommonHeader(RpcPktHdr *Header, unsigned char PacketType,
98 unsigned long DataRepresentation)
100 Header->common.rpc_ver = RPC_VER_MAJOR;
101 Header->common.rpc_ver_minor = RPC_VER_MINOR;
102 Header->common.ptype = PacketType;
103 Header->common.drep[0] = LOBYTE(LOWORD(DataRepresentation));
104 Header->common.drep[1] = HIBYTE(LOWORD(DataRepresentation));
105 Header->common.drep[2] = LOBYTE(HIWORD(DataRepresentation));
106 Header->common.drep[3] = HIBYTE(HIWORD(DataRepresentation));
107 Header->common.auth_len = 0;
108 Header->common.call_id = 1;
109 Header->common.flags = 0;
110 /* Flags and fragment length are computed in RPCRT4_Send. */
113 static RpcPktHdr *RPCRT4_BuildRequestHeader(unsigned long DataRepresentation,
114 unsigned long BufferLength,
115 unsigned short ProcNum,
116 UUID *ObjectUuid)
118 RpcPktHdr *header;
119 BOOL has_object;
120 RPC_STATUS status;
122 has_object = (ObjectUuid != NULL && !UuidIsNil(ObjectUuid, &status));
123 header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
124 sizeof(header->request) + (has_object ? sizeof(UUID) : 0));
125 if (header == NULL) {
126 return NULL;
129 RPCRT4_BuildCommonHeader(header, PKT_REQUEST, DataRepresentation);
130 header->common.frag_len = sizeof(header->request);
131 header->request.alloc_hint = BufferLength;
132 header->request.context_id = 0;
133 header->request.opnum = ProcNum;
134 if (has_object) {
135 header->common.flags |= RPC_FLG_OBJECT_UUID;
136 header->common.frag_len += sizeof(UUID);
137 memcpy(&header->request + 1, ObjectUuid, sizeof(UUID));
140 return header;
143 static RpcPktHdr *RPCRT4_BuildResponseHeader(unsigned long DataRepresentation,
144 unsigned long BufferLength)
146 RpcPktHdr *header;
148 header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->response));
149 if (header == NULL) {
150 return NULL;
153 RPCRT4_BuildCommonHeader(header, PKT_RESPONSE, DataRepresentation);
154 header->common.frag_len = sizeof(header->response);
155 header->response.alloc_hint = BufferLength;
157 return header;
160 RpcPktHdr *RPCRT4_BuildFaultHeader(unsigned long DataRepresentation,
161 RPC_STATUS Status)
163 RpcPktHdr *header;
165 header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->fault));
166 if (header == NULL) {
167 return NULL;
170 RPCRT4_BuildCommonHeader(header, PKT_FAULT, DataRepresentation);
171 header->common.frag_len = sizeof(header->fault);
172 header->fault.status = Status;
174 return header;
177 RpcPktHdr *RPCRT4_BuildBindHeader(unsigned long DataRepresentation,
178 unsigned short MaxTransmissionSize,
179 unsigned short MaxReceiveSize,
180 unsigned long AssocGroupId,
181 RPC_SYNTAX_IDENTIFIER *AbstractId,
182 RPC_SYNTAX_IDENTIFIER *TransferId)
184 RpcPktHdr *header;
186 header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind));
187 if (header == NULL) {
188 return NULL;
191 RPCRT4_BuildCommonHeader(header, PKT_BIND, DataRepresentation);
192 header->common.frag_len = sizeof(header->bind);
193 header->bind.max_tsize = MaxTransmissionSize;
194 header->bind.max_rsize = MaxReceiveSize;
195 header->bind.assoc_gid = AssocGroupId;
196 header->bind.num_elements = 1;
197 header->bind.num_syntaxes = 1;
198 memcpy(&header->bind.abstract, AbstractId, sizeof(RPC_SYNTAX_IDENTIFIER));
199 memcpy(&header->bind.transfer, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
201 return header;
204 static RpcPktHdr *RPCRT4_BuildAuthHeader(unsigned long DataRepresentation)
206 RpcPktHdr *header;
208 header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
209 sizeof(header->common) + 12);
210 if (header == NULL)
211 return NULL;
213 RPCRT4_BuildCommonHeader(header, PKT_AUTH3, DataRepresentation);
214 header->common.frag_len = 0x14;
215 header->common.auth_len = 0;
217 return header;
220 RpcPktHdr *RPCRT4_BuildBindNackHeader(unsigned long DataRepresentation,
221 unsigned char RpcVersion,
222 unsigned char RpcVersionMinor)
224 RpcPktHdr *header;
226 header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind_nack));
227 if (header == NULL) {
228 return NULL;
231 RPCRT4_BuildCommonHeader(header, PKT_BIND_NACK, DataRepresentation);
232 header->common.frag_len = sizeof(header->bind_nack);
233 header->bind_nack.protocols_count = 1;
234 header->bind_nack.protocols[0].rpc_ver = RpcVersion;
235 header->bind_nack.protocols[0].rpc_ver_minor = RpcVersionMinor;
237 return header;
240 RpcPktHdr *RPCRT4_BuildBindAckHeader(unsigned long DataRepresentation,
241 unsigned short MaxTransmissionSize,
242 unsigned short MaxReceiveSize,
243 LPSTR ServerAddress,
244 unsigned long Result,
245 unsigned long Reason,
246 RPC_SYNTAX_IDENTIFIER *TransferId)
248 RpcPktHdr *header;
249 unsigned long header_size;
250 RpcAddressString *server_address;
251 RpcResults *results;
252 RPC_SYNTAX_IDENTIFIER *transfer_id;
254 header_size = sizeof(header->bind_ack) +
255 ROUND_UP(FIELD_OFFSET(RpcAddressString, string[strlen(ServerAddress) + 1]), 4) +
256 sizeof(RpcResults) +
257 sizeof(RPC_SYNTAX_IDENTIFIER);
259 header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, header_size);
260 if (header == NULL) {
261 return NULL;
264 RPCRT4_BuildCommonHeader(header, PKT_BIND_ACK, DataRepresentation);
265 header->common.frag_len = header_size;
266 header->bind_ack.max_tsize = MaxTransmissionSize;
267 header->bind_ack.max_rsize = MaxReceiveSize;
268 server_address = (RpcAddressString*)(&header->bind_ack + 1);
269 server_address->length = strlen(ServerAddress) + 1;
270 strcpy(server_address->string, ServerAddress);
271 /* results is 4-byte aligned */
272 results = (RpcResults*)((ULONG_PTR)server_address + ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4));
273 results->num_results = 1;
274 results->results[0].result = Result;
275 results->results[0].reason = Reason;
276 transfer_id = (RPC_SYNTAX_IDENTIFIER*)(results + 1);
277 memcpy(transfer_id, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
279 return header;
282 VOID RPCRT4_FreeHeader(RpcPktHdr *Header)
284 HeapFree(GetProcessHeap(), 0, Header);
287 static RPC_STATUS RPCRT4_SecurePacket(RpcConnection *Connection,
288 enum secure_packet_direction dir,
289 RpcPktHdr *hdr, unsigned int hdr_size,
290 unsigned char *stub_data, unsigned int stub_data_size,
291 RpcAuthVerifier *auth_hdr,
292 unsigned char *auth_value, unsigned int auth_value_size)
294 SecBufferDesc message;
295 SecBuffer buffers[4];
296 SECURITY_STATUS sec_status;
298 message.ulVersion = SECBUFFER_VERSION;
299 message.cBuffers = sizeof(buffers)/sizeof(buffers[0]);
300 message.pBuffers = buffers;
302 buffers[0].cbBuffer = hdr_size;
303 buffers[0].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
304 buffers[0].pvBuffer = hdr;
305 buffers[1].cbBuffer = stub_data_size;
306 buffers[1].BufferType = SECBUFFER_DATA;
307 buffers[1].pvBuffer = stub_data;
308 buffers[2].cbBuffer = sizeof(*auth_hdr);
309 buffers[2].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
310 buffers[2].pvBuffer = auth_hdr;
311 buffers[3].cbBuffer = auth_value_size;
312 buffers[3].BufferType = SECBUFFER_TOKEN;
313 buffers[3].pvBuffer = auth_value;
315 if (dir == SECURE_PACKET_SEND)
317 if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
319 sec_status = EncryptMessage(&Connection->ctx, 0, &message, 0 /* FIXME */);
320 if (sec_status != SEC_E_OK)
322 ERR("EncryptMessage failed with 0x%08x\n", sec_status);
323 return RPC_S_SEC_PKG_ERROR;
326 else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
328 sec_status = MakeSignature(&Connection->ctx, 0, &message, 0 /* FIXME */);
329 if (sec_status != SEC_E_OK)
331 ERR("MakeSignature failed with 0x%08x\n", sec_status);
332 return RPC_S_SEC_PKG_ERROR;
336 else if (dir == SECURE_PACKET_RECEIVE)
338 if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
340 sec_status = DecryptMessage(&Connection->ctx, &message, 0 /* FIXME */, 0);
341 if (sec_status != SEC_E_OK)
343 ERR("EncryptMessage failed with 0x%08x\n", sec_status);
344 return RPC_S_SEC_PKG_ERROR;
347 else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
349 sec_status = VerifySignature(&Connection->ctx, &message, 0 /* FIXME */, NULL);
350 if (sec_status != SEC_E_OK)
352 ERR("VerifySignature failed with 0x%08x\n", sec_status);
353 return RPC_S_SEC_PKG_ERROR;
358 return RPC_S_OK;
361 /***********************************************************************
362 * RPCRT4_SendAuth (internal)
364 * Transmit a packet with authorization data over connection in acceptable fragments.
366 static RPC_STATUS RPCRT4_SendAuth(RpcConnection *Connection, RpcPktHdr *Header,
367 void *Buffer, unsigned int BufferLength,
368 void *Auth, unsigned int AuthLength)
370 PUCHAR buffer_pos;
371 DWORD hdr_size;
372 LONG count;
373 unsigned char *pkt;
374 LONG alen;
375 RPC_STATUS status;
377 buffer_pos = Buffer;
378 /* The packet building functions save the packet header size, so we can use it. */
379 hdr_size = Header->common.frag_len;
380 if (AuthLength)
381 Header->common.auth_len = AuthLength;
382 else if (Connection->AuthInfo && packet_has_auth_verifier(Header))
384 if ((Connection->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(Header))
385 Header->common.auth_len = Connection->encryption_auth_len;
386 else
387 Header->common.auth_len = Connection->signature_auth_len;
389 else
390 Header->common.auth_len = 0;
391 Header->common.flags |= RPC_FLG_FIRST;
392 Header->common.flags &= ~RPC_FLG_LAST;
394 alen = RPC_AUTH_VERIFIER_LEN(&Header->common);
396 while (!(Header->common.flags & RPC_FLG_LAST)) {
397 unsigned char auth_pad_len = Header->common.auth_len ? ROUND_UP_AMOUNT(BufferLength, AUTH_ALIGNMENT) : 0;
398 unsigned int pkt_size = BufferLength + hdr_size + alen + auth_pad_len;
400 /* decide if we need to split the packet into fragments */
401 if (pkt_size <= Connection->MaxTransmissionSize) {
402 Header->common.flags |= RPC_FLG_LAST;
403 Header->common.frag_len = pkt_size;
404 } else {
405 auth_pad_len = 0;
406 /* make sure packet payload will be a multiple of 16 */
407 Header->common.frag_len =
408 ((Connection->MaxTransmissionSize - hdr_size - alen) & ~(AUTH_ALIGNMENT-1)) +
409 hdr_size + alen;
412 pkt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Header->common.frag_len);
414 memcpy(pkt, Header, hdr_size);
416 /* fragment consisted of header only and is the last one */
417 if (hdr_size == Header->common.frag_len)
418 goto write;
420 memcpy(pkt + hdr_size, buffer_pos, Header->common.frag_len - hdr_size - auth_pad_len - alen);
422 /* add the authorization info */
423 if (Connection->AuthInfo && packet_has_auth_verifier(Header))
425 RpcAuthVerifier *auth_hdr = (RpcAuthVerifier *)&pkt[Header->common.frag_len - alen];
427 auth_hdr->auth_type = Connection->AuthInfo->AuthnSvc;
428 auth_hdr->auth_level = Connection->AuthInfo->AuthnLevel;
429 auth_hdr->auth_pad_length = auth_pad_len;
430 auth_hdr->auth_reserved = 0;
431 /* a unique number... */
432 auth_hdr->auth_context_id = (unsigned long)Connection;
434 if (AuthLength)
435 memcpy(auth_hdr + 1, Auth, AuthLength);
436 else
438 status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_SEND,
439 (RpcPktHdr *)pkt, hdr_size,
440 pkt + hdr_size, Header->common.frag_len - hdr_size - alen,
441 auth_hdr,
442 (unsigned char *)(auth_hdr + 1), Header->common.auth_len);
443 if (status != RPC_S_OK)
445 HeapFree(GetProcessHeap(), 0, pkt);
446 return status;
451 write:
452 count = rpcrt4_conn_write(Connection, pkt, Header->common.frag_len);
453 HeapFree(GetProcessHeap(), 0, pkt);
454 if (count<0) {
455 WARN("rpcrt4_conn_write failed (auth)\n");
456 return RPC_S_PROTOCOL_ERROR;
459 buffer_pos += Header->common.frag_len - hdr_size - alen - auth_pad_len;
460 BufferLength -= Header->common.frag_len - hdr_size - alen - auth_pad_len;
461 Header->common.flags &= ~RPC_FLG_FIRST;
464 return RPC_S_OK;
467 /***********************************************************************
468 * RPCRT4_ClientAuthorize (internal)
470 * Authorize a client connection. A NULL in param signifies a new connection.
472 static RPC_STATUS RPCRT4_ClientAuthorize(RpcConnection *conn, SecBuffer *in,
473 SecBuffer *out)
475 SECURITY_STATUS r;
476 SecBufferDesc out_desc;
477 SecBufferDesc inp_desc;
478 SecPkgContext_Sizes secctx_sizes;
479 BOOL continue_needed;
480 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
481 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
483 if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
484 context_req |= ISC_REQ_INTEGRITY;
485 else if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY)
486 context_req |= ISC_REQ_CONFIDENTIALITY | ISC_REQ_INTEGRITY;
488 out->BufferType = SECBUFFER_TOKEN;
489 out->cbBuffer = conn->AuthInfo->cbMaxToken;
490 out->pvBuffer = HeapAlloc(GetProcessHeap(), 0, out->cbBuffer);
491 if (!out->pvBuffer) return ERROR_OUTOFMEMORY;
493 out_desc.ulVersion = 0;
494 out_desc.cBuffers = 1;
495 out_desc.pBuffers = out;
497 inp_desc.cBuffers = 1;
498 inp_desc.pBuffers = in;
499 inp_desc.ulVersion = 0;
501 r = InitializeSecurityContextA(&conn->AuthInfo->cred, in ? &conn->ctx : NULL,
502 NULL, context_req, 0, SECURITY_NETWORK_DREP,
503 in ? &inp_desc : NULL, 0, &conn->ctx, &out_desc, &conn->attr,
504 &conn->exp);
505 if (FAILED(r))
507 WARN("InitializeSecurityContext failed with error 0x%08x\n", r);
508 goto failed;
511 TRACE("r = 0x%08x, attr = 0x%08x\n", r, conn->attr);
512 continue_needed = ((r == SEC_I_CONTINUE_NEEDED) ||
513 (r == SEC_I_COMPLETE_AND_CONTINUE));
515 if ((r == SEC_I_COMPLETE_NEEDED) || (r == SEC_I_COMPLETE_AND_CONTINUE))
517 TRACE("complete needed\n");
518 r = CompleteAuthToken(&conn->ctx, &out_desc);
519 if (FAILED(r))
521 WARN("CompleteAuthToken failed with error 0x%08x\n", r);
522 goto failed;
526 TRACE("cbBuffer = %ld\n", out->cbBuffer);
528 if (!continue_needed)
530 r = QueryContextAttributesA(&conn->ctx, SECPKG_ATTR_SIZES, &secctx_sizes);
531 if (FAILED(r))
533 WARN("QueryContextAttributes failed with error 0x%08x\n", r);
534 goto failed;
536 conn->signature_auth_len = secctx_sizes.cbMaxSignature;
537 conn->encryption_auth_len = secctx_sizes.cbSecurityTrailer;
540 return RPC_S_OK;
542 failed:
543 HeapFree(GetProcessHeap(), 0, out->pvBuffer);
544 out->pvBuffer = NULL;
545 return ERROR_ACCESS_DENIED; /* FIXME: is this correct? */
548 /***********************************************************************
549 * RPCRT4_AuthorizeBinding (internal)
551 static RPC_STATUS RPCRT_AuthorizeConnection(RpcConnection* conn,
552 BYTE *challenge, ULONG count)
554 SecBuffer inp, out;
555 RpcPktHdr *resp_hdr;
556 RPC_STATUS status;
558 TRACE("challenge %s, %d bytes\n", challenge, count);
560 inp.BufferType = SECBUFFER_TOKEN;
561 inp.pvBuffer = challenge;
562 inp.cbBuffer = count;
564 status = RPCRT4_ClientAuthorize(conn, &inp, &out);
565 if (status) return status;
567 resp_hdr = RPCRT4_BuildAuthHeader(NDR_LOCAL_DATA_REPRESENTATION);
568 if (!resp_hdr)
569 return E_OUTOFMEMORY;
571 status = RPCRT4_SendAuth(conn, resp_hdr, NULL, 0, out.pvBuffer, out.cbBuffer);
573 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
574 RPCRT4_FreeHeader(resp_hdr);
576 return status;
579 /***********************************************************************
580 * RPCRT4_Send (internal)
582 * Transmit a packet over connection in acceptable fragments.
584 RPC_STATUS RPCRT4_Send(RpcConnection *Connection, RpcPktHdr *Header,
585 void *Buffer, unsigned int BufferLength)
587 RPC_STATUS r;
588 SecBuffer out;
590 if (!Connection->AuthInfo || SecIsValidHandle(&Connection->ctx))
592 return RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, NULL, 0);
595 /* tack on a negotiate packet */
596 RPCRT4_ClientAuthorize(Connection, NULL, &out);
597 r = RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, out.pvBuffer, out.cbBuffer);
598 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
600 return r;
603 /***********************************************************************
604 * RPCRT4_Receive (internal)
606 * Receive a packet from connection and merge the fragments.
608 RPC_STATUS RPCRT4_Receive(RpcConnection *Connection, RpcPktHdr **Header,
609 PRPC_MESSAGE pMsg)
611 RPC_STATUS status;
612 DWORD hdr_length;
613 LONG dwRead;
614 unsigned short first_flag;
615 unsigned long data_length;
616 unsigned long buffer_length;
617 unsigned long auth_length;
618 unsigned char *auth_data = NULL;
619 RpcPktCommonHdr common_hdr;
621 *Header = NULL;
623 TRACE("(%p, %p, %p)\n", Connection, Header, pMsg);
625 /* read packet common header */
626 dwRead = rpcrt4_conn_read(Connection, &common_hdr, sizeof(common_hdr));
627 if (dwRead != sizeof(common_hdr)) {
628 WARN("Short read of header, %d bytes\n", dwRead);
629 status = RPC_S_PROTOCOL_ERROR;
630 goto fail;
633 /* verify if the header really makes sense */
634 if (common_hdr.rpc_ver != RPC_VER_MAJOR ||
635 common_hdr.rpc_ver_minor != RPC_VER_MINOR) {
636 WARN("unhandled packet version\n");
637 status = RPC_S_PROTOCOL_ERROR;
638 goto fail;
641 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
642 if (hdr_length == 0) {
643 WARN("header length == 0\n");
644 status = RPC_S_PROTOCOL_ERROR;
645 goto fail;
648 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
649 memcpy(*Header, &common_hdr, sizeof(common_hdr));
651 /* read the rest of packet header */
652 dwRead = rpcrt4_conn_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
653 if (dwRead != hdr_length - sizeof(common_hdr)) {
654 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
655 status = RPC_S_PROTOCOL_ERROR;
656 goto fail;
659 /* read packet body */
660 switch (common_hdr.ptype) {
661 case PKT_RESPONSE:
662 pMsg->BufferLength = (*Header)->response.alloc_hint;
663 break;
664 case PKT_REQUEST:
665 pMsg->BufferLength = (*Header)->request.alloc_hint;
666 break;
667 default:
668 pMsg->BufferLength = common_hdr.frag_len - hdr_length - RPC_AUTH_VERIFIER_LEN(&common_hdr);
671 TRACE("buffer length = %u\n", pMsg->BufferLength);
673 status = I_RpcGetBuffer(pMsg);
674 if (status != RPC_S_OK) goto fail;
676 first_flag = RPC_FLG_FIRST;
677 auth_length = common_hdr.auth_len;
678 if (auth_length) {
679 auth_data = HeapAlloc(GetProcessHeap(), 0, RPC_AUTH_VERIFIER_LEN(&common_hdr));
680 if (!auth_data) {
681 status = RPC_S_PROTOCOL_ERROR;
682 goto fail;
685 buffer_length = 0;
686 while (TRUE)
688 unsigned int header_auth_len = RPC_AUTH_VERIFIER_LEN(&(*Header)->common);
690 /* verify header fields */
692 if (((*Header)->common.frag_len < hdr_length) ||
693 ((*Header)->common.frag_len - hdr_length < header_auth_len)) {
694 WARN("frag_len %d too small for hdr_length %d and auth_len %d\n",
695 (*Header)->common.frag_len, hdr_length, header_auth_len);
696 status = RPC_S_PROTOCOL_ERROR;
697 goto fail;
700 if ((*Header)->common.auth_len != auth_length) {
701 WARN("auth_len header field changed from %ld to %d\n",
702 auth_length, (*Header)->common.auth_len);
703 status = RPC_S_PROTOCOL_ERROR;
704 goto fail;
707 if (((*Header)->common.flags & RPC_FLG_FIRST) != first_flag) {
708 TRACE("invalid packet flags\n");
709 status = RPC_S_PROTOCOL_ERROR;
710 goto fail;
713 data_length = (*Header)->common.frag_len - hdr_length - header_auth_len;
714 if (data_length + buffer_length > pMsg->BufferLength) {
715 TRACE("allocation hint exceeded, new buffer length = %ld\n",
716 data_length + buffer_length);
717 pMsg->BufferLength = data_length + buffer_length;
718 status = I_RpcReAllocateBuffer(pMsg);
719 if (status != RPC_S_OK) goto fail;
722 if (data_length == 0) dwRead = 0; else
723 dwRead = rpcrt4_conn_read(Connection,
724 (unsigned char *)pMsg->Buffer + buffer_length, data_length);
725 if (dwRead != data_length) {
726 WARN("bad data length, %d/%ld\n", dwRead, data_length);
727 status = RPC_S_PROTOCOL_ERROR;
728 goto fail;
731 if (header_auth_len) {
732 if (header_auth_len < sizeof(RpcAuthVerifier)) {
733 WARN("bad auth verifier length %d\n", header_auth_len);
734 status = RPC_S_PROTOCOL_ERROR;
735 goto fail;
738 /* FIXME: we should accumulate authentication data for the bind,
739 * bind_ack, alter_context and alter_context_response if necessary.
740 * however, the details of how this is done is very sketchy in the
741 * DCE/RPC spec. for all other packet types that have authentication
742 * verifier data then it is just duplicated in all the fragments */
743 dwRead = rpcrt4_conn_read(Connection, auth_data, header_auth_len);
744 if (dwRead != header_auth_len) {
745 WARN("bad authentication data length, %d/%d\n", dwRead,
746 header_auth_len);
747 status = RPC_S_PROTOCOL_ERROR;
748 goto fail;
751 /* these packets are handled specially, not by the generic SecurePacket
752 * function */
753 if ((common_hdr.ptype != PKT_BIND) &&
754 (common_hdr.ptype != PKT_BIND_ACK) &&
755 (common_hdr.ptype != PKT_AUTH3))
756 status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_RECEIVE,
757 *Header, hdr_length,
758 (unsigned char *)pMsg->Buffer + buffer_length, data_length,
759 (RpcAuthVerifier *)auth_data,
760 (unsigned char *)auth_data + sizeof(RpcAuthVerifier),
761 header_auth_len - sizeof(RpcAuthVerifier));
764 buffer_length += data_length;
765 if (!((*Header)->common.flags & RPC_FLG_LAST)) {
766 TRACE("next header\n");
768 /* read the header of next packet */
769 dwRead = rpcrt4_conn_read(Connection, *Header, hdr_length);
770 if (dwRead != hdr_length) {
771 WARN("invalid packet header size (%d)\n", dwRead);
772 status = RPC_S_PROTOCOL_ERROR;
773 goto fail;
776 first_flag = 0;
777 } else {
778 break;
781 pMsg->BufferLength = buffer_length;
783 /* respond to authorization request */
784 if (common_hdr.ptype == PKT_BIND_ACK && auth_length > sizeof(RpcAuthVerifier))
786 status = RPCRT_AuthorizeConnection(Connection,
787 auth_data + sizeof(RpcAuthVerifier),
788 auth_length);
789 if (status)
790 goto fail;
793 /* success */
794 status = RPC_S_OK;
796 fail:
797 if (status != RPC_S_OK) {
798 RPCRT4_FreeHeader(*Header);
799 *Header = NULL;
801 HeapFree(GetProcessHeap(), 0, auth_data);
802 return status;
805 /***********************************************************************
806 * I_RpcGetBuffer [RPCRT4.@]
808 * Allocates a buffer for use by I_RpcSend or I_RpcSendReceive and binds to the
809 * server interface.
811 * PARAMS
812 * pMsg [I/O] RPC message information.
814 * RETURNS
815 * Success: RPC_S_OK.
816 * Failure: RPC_S_INVALID_BINDING if pMsg->Handle is invalid.
817 * RPC_S_SERVER_UNAVAILABLE if unable to connect to server.
818 * ERROR_OUTOFMEMORY if buffer allocation failed.
820 * NOTES
821 * The pMsg->BufferLength field determines the size of the buffer to allocate,
822 * in bytes.
824 * Use I_RpcFreeBuffer() to unbind from the server and free the message buffer.
826 * SEE ALSO
827 * I_RpcFreeBuffer(), I_RpcSend(), I_RpcReceive(), I_RpcSendReceive().
829 RPC_STATUS WINAPI I_RpcGetBuffer(PRPC_MESSAGE pMsg)
831 TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
832 /* FIXME: pfnAllocate? */
833 pMsg->Buffer = HeapAlloc(GetProcessHeap(), 0, pMsg->BufferLength);
835 TRACE("Buffer=%p\n", pMsg->Buffer);
836 /* FIXME: which errors to return? */
837 return pMsg->Buffer ? S_OK : E_OUTOFMEMORY;
840 /***********************************************************************
841 * I_RpcReAllocateBuffer (internal)
843 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg)
845 TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
846 pMsg->Buffer = HeapReAlloc(GetProcessHeap(), 0, pMsg->Buffer, pMsg->BufferLength);
848 TRACE("Buffer=%p\n", pMsg->Buffer);
849 return pMsg->Buffer ? RPC_S_OK : RPC_S_OUT_OF_RESOURCES;
852 /***********************************************************************
853 * I_RpcFreeBuffer [RPCRT4.@]
855 * Frees a buffer allocated by I_RpcGetBuffer or I_RpcReceive and unbinds from
856 * the server interface.
858 * PARAMS
859 * pMsg [I/O] RPC message information.
861 * RETURNS
862 * RPC_S_OK.
864 * SEE ALSO
865 * I_RpcGetBuffer(), I_RpcReceive().
867 RPC_STATUS WINAPI I_RpcFreeBuffer(PRPC_MESSAGE pMsg)
869 TRACE("(%p) Buffer=%p\n", pMsg, pMsg->Buffer);
870 /* FIXME: pfnFree? */
871 HeapFree(GetProcessHeap(), 0, pMsg->Buffer);
872 pMsg->Buffer = NULL;
873 return S_OK;
876 /***********************************************************************
877 * I_RpcSend [RPCRT4.@]
879 * Sends a message to the server.
881 * PARAMS
882 * pMsg [I/O] RPC message information.
884 * RETURNS
885 * Unknown.
887 * NOTES
888 * The buffer must have been allocated with I_RpcGetBuffer().
890 * SEE ALSO
891 * I_RpcGetBuffer(), I_RpcReceive(), I_RpcSendReceive().
893 RPC_STATUS WINAPI I_RpcSend(PRPC_MESSAGE pMsg)
895 RpcBinding* bind = (RpcBinding*)pMsg->Handle;
896 RpcConnection* conn;
897 RPC_CLIENT_INTERFACE* cif = NULL;
898 RPC_SERVER_INTERFACE* sif = NULL;
899 RPC_STATUS status;
900 RpcPktHdr *hdr;
902 TRACE("(%p)\n", pMsg);
903 if (!bind) return RPC_S_INVALID_BINDING;
905 if (bind->server) {
906 sif = pMsg->RpcInterfaceInformation;
907 if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
908 status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
909 &sif->InterfaceId);
910 } else {
911 cif = pMsg->RpcInterfaceInformation;
912 if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
914 if (!bind->Endpoint || !bind->Endpoint[0])
916 TRACE("automatically resolving partially bound binding\n");
917 status = RpcEpResolveBinding(bind, cif);
918 if (status != RPC_S_OK) return status;
921 status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
922 &cif->InterfaceId);
925 if (status != RPC_S_OK) return status;
927 if (bind->server) {
928 if (pMsg->RpcFlags & WINE_RPCFLAG_EXCEPTION) {
929 hdr = RPCRT4_BuildFaultHeader(pMsg->DataRepresentation,
930 *(DWORD *)pMsg->Buffer);
931 } else {
932 hdr = RPCRT4_BuildResponseHeader(pMsg->DataRepresentation,
933 pMsg->BufferLength);
935 } else {
936 hdr = RPCRT4_BuildRequestHeader(pMsg->DataRepresentation,
937 pMsg->BufferLength, pMsg->ProcNum,
938 &bind->ObjectUuid);
939 hdr->common.call_id = conn->NextCallId++;
942 status = RPCRT4_Send(conn, hdr, pMsg->Buffer, pMsg->BufferLength);
944 RPCRT4_FreeHeader(hdr);
946 /* success */
947 if (!bind->server) {
948 /* save the connection, so the response can be read from it */
949 pMsg->ReservedForRuntime = conn;
950 return status;
952 RPCRT4_CloseBinding(bind, conn);
954 return status;
957 /* is this status something that the server can't recover from? */
958 static inline BOOL is_hard_error(RPC_STATUS status)
960 switch (status)
962 case 0: /* user-defined fault */
963 case ERROR_ACCESS_DENIED:
964 case ERROR_INVALID_PARAMETER:
965 case RPC_S_PROTOCOL_ERROR:
966 case RPC_S_CALL_FAILED:
967 case RPC_S_CALL_FAILED_DNE:
968 return TRUE;
969 default:
970 return FALSE;
974 /***********************************************************************
975 * I_RpcReceive [RPCRT4.@]
977 RPC_STATUS WINAPI I_RpcReceive(PRPC_MESSAGE pMsg)
979 RpcBinding* bind = (RpcBinding*)pMsg->Handle;
980 RpcConnection* conn;
981 RPC_CLIENT_INTERFACE* cif = NULL;
982 RPC_SERVER_INTERFACE* sif = NULL;
983 RPC_STATUS status;
984 RpcPktHdr *hdr = NULL;
986 TRACE("(%p)\n", pMsg);
987 if (!bind) return RPC_S_INVALID_BINDING;
989 if (pMsg->ReservedForRuntime) {
990 conn = pMsg->ReservedForRuntime;
991 pMsg->ReservedForRuntime = NULL;
992 } else {
993 if (bind->server) {
994 sif = pMsg->RpcInterfaceInformation;
995 if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
996 status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
997 &sif->InterfaceId);
998 } else {
999 cif = pMsg->RpcInterfaceInformation;
1000 if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
1002 if (!bind->Endpoint || !bind->Endpoint[0])
1004 TRACE("automatically resolving partially bound binding\n");
1005 status = RpcEpResolveBinding(bind, cif);
1006 if (status != RPC_S_OK) return status;
1009 status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
1010 &cif->InterfaceId);
1012 if (status != RPC_S_OK) return status;
1015 status = RPCRT4_Receive(conn, &hdr, pMsg);
1016 if (status != RPC_S_OK) {
1017 WARN("receive failed with error %lx\n", status);
1018 goto fail;
1021 switch (hdr->common.ptype) {
1022 case PKT_RESPONSE:
1023 if (bind->server) {
1024 status = RPC_S_PROTOCOL_ERROR;
1025 goto fail;
1027 break;
1028 case PKT_REQUEST:
1029 if (!bind->server) {
1030 status = RPC_S_PROTOCOL_ERROR;
1031 goto fail;
1033 break;
1034 case PKT_FAULT:
1035 pMsg->RpcFlags |= WINE_RPCFLAG_EXCEPTION;
1036 ERR ("we got fault packet with status 0x%lx\n", hdr->fault.status);
1037 status = hdr->fault.status; /* FIXME: do translation from nca error codes */
1038 if (is_hard_error(status))
1039 goto fail;
1040 break;
1041 default:
1042 WARN("bad packet type %d\n", hdr->common.ptype);
1043 status = RPC_S_PROTOCOL_ERROR;
1044 goto fail;
1047 /* success */
1048 RPCRT4_CloseBinding(bind, conn);
1049 RPCRT4_FreeHeader(hdr);
1050 return status;
1052 fail:
1053 RPCRT4_FreeHeader(hdr);
1054 RPCRT4_DestroyConnection(conn);
1055 return status;
1058 /***********************************************************************
1059 * I_RpcSendReceive [RPCRT4.@]
1061 * Sends a message to the server and receives the response.
1063 * PARAMS
1064 * pMsg [I/O] RPC message information.
1066 * RETURNS
1067 * Success: RPC_S_OK.
1068 * Failure: Any error code.
1070 * NOTES
1071 * The buffer must have been allocated with I_RpcGetBuffer().
1073 * SEE ALSO
1074 * I_RpcGetBuffer(), I_RpcSend(), I_RpcReceive().
1076 RPC_STATUS WINAPI I_RpcSendReceive(PRPC_MESSAGE pMsg)
1078 RPC_STATUS status;
1079 RPC_MESSAGE original_message;
1081 TRACE("(%p)\n", pMsg);
1083 original_message = *pMsg;
1084 status = I_RpcSend(pMsg);
1085 if (status == RPC_S_OK)
1086 status = I_RpcReceive(pMsg);
1087 /* free the buffer replaced by a new buffer in I_RpcReceive */
1088 if (status == RPC_S_OK)
1089 I_RpcFreeBuffer(&original_message);
1090 return status;