d3d9: Hold the lock in stateblock methods.
[wine.git] / dlls / rpcrt4 / rpc_message.c
blobdd37f33538d74b6dfc2c2e788fa628964d00d675
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 RPC_SYNTAX_IDENTIFIER *AbstractId,
181 RPC_SYNTAX_IDENTIFIER *TransferId)
183 RpcPktHdr *header;
185 header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind));
186 if (header == NULL) {
187 return NULL;
190 RPCRT4_BuildCommonHeader(header, PKT_BIND, DataRepresentation);
191 header->common.frag_len = sizeof(header->bind);
192 header->bind.max_tsize = MaxTransmissionSize;
193 header->bind.max_rsize = MaxReceiveSize;
194 header->bind.num_elements = 1;
195 header->bind.num_syntaxes = 1;
196 memcpy(&header->bind.abstract, AbstractId, sizeof(RPC_SYNTAX_IDENTIFIER));
197 memcpy(&header->bind.transfer, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
199 return header;
202 static RpcPktHdr *RPCRT4_BuildAuthHeader(unsigned long DataRepresentation)
204 RpcPktHdr *header;
206 header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
207 sizeof(header->common) + 12);
208 if (header == NULL)
209 return NULL;
211 RPCRT4_BuildCommonHeader(header, PKT_AUTH3, DataRepresentation);
212 header->common.frag_len = 0x14;
213 header->common.auth_len = 0;
215 return header;
218 RpcPktHdr *RPCRT4_BuildBindNackHeader(unsigned long DataRepresentation,
219 unsigned char RpcVersion,
220 unsigned char RpcVersionMinor)
222 RpcPktHdr *header;
224 header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind_nack));
225 if (header == NULL) {
226 return NULL;
229 RPCRT4_BuildCommonHeader(header, PKT_BIND_NACK, DataRepresentation);
230 header->common.frag_len = sizeof(header->bind_nack);
231 header->bind_nack.protocols_count = 1;
232 header->bind_nack.protocols[0].rpc_ver = RpcVersion;
233 header->bind_nack.protocols[0].rpc_ver_minor = RpcVersionMinor;
235 return header;
238 RpcPktHdr *RPCRT4_BuildBindAckHeader(unsigned long DataRepresentation,
239 unsigned short MaxTransmissionSize,
240 unsigned short MaxReceiveSize,
241 LPSTR ServerAddress,
242 unsigned long Result,
243 unsigned long Reason,
244 RPC_SYNTAX_IDENTIFIER *TransferId)
246 RpcPktHdr *header;
247 unsigned long header_size;
248 RpcAddressString *server_address;
249 RpcResults *results;
250 RPC_SYNTAX_IDENTIFIER *transfer_id;
252 header_size = sizeof(header->bind_ack) +
253 ROUND_UP(FIELD_OFFSET(RpcAddressString, string[strlen(ServerAddress) + 1]), 4) +
254 sizeof(RpcResults) +
255 sizeof(RPC_SYNTAX_IDENTIFIER);
257 header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, header_size);
258 if (header == NULL) {
259 return NULL;
262 RPCRT4_BuildCommonHeader(header, PKT_BIND_ACK, DataRepresentation);
263 header->common.frag_len = header_size;
264 header->bind_ack.max_tsize = MaxTransmissionSize;
265 header->bind_ack.max_rsize = MaxReceiveSize;
266 server_address = (RpcAddressString*)(&header->bind_ack + 1);
267 server_address->length = strlen(ServerAddress) + 1;
268 strcpy(server_address->string, ServerAddress);
269 /* results is 4-byte aligned */
270 results = (RpcResults*)((ULONG_PTR)server_address + ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4));
271 results->num_results = 1;
272 results->results[0].result = Result;
273 results->results[0].reason = Reason;
274 transfer_id = (RPC_SYNTAX_IDENTIFIER*)(results + 1);
275 memcpy(transfer_id, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
277 return header;
280 VOID RPCRT4_FreeHeader(RpcPktHdr *Header)
282 HeapFree(GetProcessHeap(), 0, Header);
285 static RPC_STATUS RPCRT4_SecurePacket(RpcConnection *Connection,
286 enum secure_packet_direction dir,
287 RpcPktHdr *hdr, unsigned int hdr_size,
288 unsigned char *stub_data, unsigned int stub_data_size,
289 RpcAuthVerifier *auth_hdr,
290 unsigned char *auth_value, unsigned int auth_value_size)
292 SecBufferDesc message;
293 SecBuffer buffers[4];
294 SECURITY_STATUS sec_status;
296 message.ulVersion = SECBUFFER_VERSION;
297 message.cBuffers = sizeof(buffers)/sizeof(buffers[0]);
298 message.pBuffers = buffers;
300 buffers[0].cbBuffer = hdr_size;
301 buffers[0].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
302 buffers[0].pvBuffer = hdr;
303 buffers[1].cbBuffer = stub_data_size;
304 buffers[1].BufferType = SECBUFFER_DATA;
305 buffers[1].pvBuffer = stub_data;
306 buffers[2].cbBuffer = sizeof(*auth_hdr);
307 buffers[2].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
308 buffers[2].pvBuffer = auth_hdr;
309 buffers[3].cbBuffer = auth_value_size;
310 buffers[3].BufferType = SECBUFFER_TOKEN;
311 buffers[3].pvBuffer = auth_value;
313 if (dir == SECURE_PACKET_SEND)
315 if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
317 sec_status = EncryptMessage(&Connection->ctx, 0, &message, 0 /* FIXME */);
318 if (sec_status != SEC_E_OK)
320 ERR("EncryptMessage failed with 0x%08x\n", sec_status);
321 return RPC_S_SEC_PKG_ERROR;
324 else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
326 sec_status = MakeSignature(&Connection->ctx, 0, &message, 0 /* FIXME */);
327 if (sec_status != SEC_E_OK)
329 ERR("MakeSignature failed with 0x%08x\n", sec_status);
330 return RPC_S_SEC_PKG_ERROR;
334 else if (dir == SECURE_PACKET_RECEIVE)
336 if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
338 sec_status = DecryptMessage(&Connection->ctx, &message, 0 /* FIXME */, 0);
339 if (sec_status != SEC_E_OK)
341 ERR("EncryptMessage failed with 0x%08x\n", sec_status);
342 return RPC_S_SEC_PKG_ERROR;
345 else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
347 sec_status = VerifySignature(&Connection->ctx, &message, 0 /* FIXME */, NULL);
348 if (sec_status != SEC_E_OK)
350 ERR("VerifySignature failed with 0x%08x\n", sec_status);
351 return RPC_S_SEC_PKG_ERROR;
356 return RPC_S_OK;
359 /***********************************************************************
360 * RPCRT4_SendAuth (internal)
362 * Transmit a packet with authorization data over connection in acceptable fragments.
364 static RPC_STATUS RPCRT4_SendAuth(RpcConnection *Connection, RpcPktHdr *Header,
365 void *Buffer, unsigned int BufferLength,
366 void *Auth, unsigned int AuthLength)
368 PUCHAR buffer_pos;
369 DWORD hdr_size;
370 LONG count;
371 unsigned char *pkt;
372 LONG alen;
373 RPC_STATUS status;
375 buffer_pos = Buffer;
376 /* The packet building functions save the packet header size, so we can use it. */
377 hdr_size = Header->common.frag_len;
378 if (AuthLength)
379 Header->common.auth_len = AuthLength;
380 else if (Connection->AuthInfo && packet_has_auth_verifier(Header))
382 if ((Connection->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(Header))
383 Header->common.auth_len = Connection->encryption_auth_len;
384 else
385 Header->common.auth_len = Connection->signature_auth_len;
387 else
388 Header->common.auth_len = 0;
389 Header->common.flags |= RPC_FLG_FIRST;
390 Header->common.flags &= ~RPC_FLG_LAST;
392 alen = RPC_AUTH_VERIFIER_LEN(&Header->common);
394 while (!(Header->common.flags & RPC_FLG_LAST)) {
395 unsigned char auth_pad_len = Header->common.auth_len ? ROUND_UP_AMOUNT(BufferLength, AUTH_ALIGNMENT) : 0;
396 unsigned int pkt_size = BufferLength + hdr_size + alen + auth_pad_len;
398 /* decide if we need to split the packet into fragments */
399 if (pkt_size <= Connection->MaxTransmissionSize) {
400 Header->common.flags |= RPC_FLG_LAST;
401 Header->common.frag_len = pkt_size;
402 } else {
403 auth_pad_len = 0;
404 /* make sure packet payload will be a multiple of 16 */
405 Header->common.frag_len =
406 ((Connection->MaxTransmissionSize - hdr_size - alen) & ~(AUTH_ALIGNMENT-1)) +
407 hdr_size + alen;
410 pkt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Header->common.frag_len);
412 memcpy(pkt, Header, hdr_size);
414 /* fragment consisted of header only and is the last one */
415 if (hdr_size == Header->common.frag_len)
416 goto write;
418 memcpy(pkt + hdr_size, buffer_pos, Header->common.frag_len - hdr_size - auth_pad_len - alen);
420 /* add the authorization info */
421 if (Connection->AuthInfo && packet_has_auth_verifier(Header))
423 RpcAuthVerifier *auth_hdr = (RpcAuthVerifier *)&pkt[Header->common.frag_len - alen];
425 auth_hdr->auth_type = Connection->AuthInfo->AuthnSvc;
426 auth_hdr->auth_level = Connection->AuthInfo->AuthnLevel;
427 auth_hdr->auth_pad_length = auth_pad_len;
428 auth_hdr->auth_reserved = 0;
429 /* a unique number... */
430 auth_hdr->auth_context_id = (unsigned long)Connection;
432 if (AuthLength)
433 memcpy(auth_hdr + 1, Auth, AuthLength);
434 else
436 status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_SEND,
437 (RpcPktHdr *)pkt, hdr_size,
438 pkt + hdr_size, Header->common.frag_len - hdr_size - alen,
439 auth_hdr,
440 (unsigned char *)(auth_hdr + 1), Header->common.auth_len);
441 if (status != RPC_S_OK)
443 HeapFree(GetProcessHeap(), 0, pkt);
444 return status;
449 write:
450 count = rpcrt4_conn_write(Connection, pkt, Header->common.frag_len);
451 HeapFree(GetProcessHeap(), 0, pkt);
452 if (count<0) {
453 WARN("rpcrt4_conn_write failed (auth)\n");
454 return RPC_S_PROTOCOL_ERROR;
457 buffer_pos += Header->common.frag_len - hdr_size - alen - auth_pad_len;
458 BufferLength -= Header->common.frag_len - hdr_size - alen - auth_pad_len;
459 Header->common.flags &= ~RPC_FLG_FIRST;
462 return RPC_S_OK;
465 /***********************************************************************
466 * RPCRT4_ClientAuthorize (internal)
468 * Authorize a client connection. A NULL in param signifies a new connection.
470 static RPC_STATUS RPCRT4_ClientAuthorize(RpcConnection *conn, SecBuffer *in,
471 SecBuffer *out)
473 SECURITY_STATUS r;
474 SecBufferDesc out_desc;
475 SecBufferDesc inp_desc;
476 SecPkgContext_Sizes secctx_sizes;
477 BOOL continue_needed;
478 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
479 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
481 if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
482 context_req |= ISC_REQ_INTEGRITY;
483 else if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY)
484 context_req |= ISC_REQ_CONFIDENTIALITY | ISC_REQ_INTEGRITY;
486 out->BufferType = SECBUFFER_TOKEN;
487 out->cbBuffer = conn->AuthInfo->cbMaxToken;
488 out->pvBuffer = HeapAlloc(GetProcessHeap(), 0, out->cbBuffer);
489 if (!out->pvBuffer) return ERROR_OUTOFMEMORY;
491 out_desc.ulVersion = 0;
492 out_desc.cBuffers = 1;
493 out_desc.pBuffers = out;
495 inp_desc.cBuffers = 1;
496 inp_desc.pBuffers = in;
497 inp_desc.ulVersion = 0;
499 r = InitializeSecurityContextA(&conn->AuthInfo->cred, in ? &conn->ctx : NULL,
500 NULL, context_req, 0, SECURITY_NETWORK_DREP,
501 in ? &inp_desc : NULL, 0, &conn->ctx, &out_desc, &conn->attr,
502 &conn->exp);
503 if (FAILED(r))
505 WARN("InitializeSecurityContext failed with error 0x%08x\n", r);
506 goto failed;
509 TRACE("r = 0x%08x, attr = 0x%08x\n", r, conn->attr);
510 continue_needed = ((r == SEC_I_CONTINUE_NEEDED) ||
511 (r == SEC_I_COMPLETE_AND_CONTINUE));
513 if ((r == SEC_I_COMPLETE_NEEDED) || (r == SEC_I_COMPLETE_AND_CONTINUE))
515 TRACE("complete needed\n");
516 r = CompleteAuthToken(&conn->ctx, &out_desc);
517 if (FAILED(r))
519 WARN("CompleteAuthToken failed with error 0x%08x\n", r);
520 goto failed;
524 TRACE("cbBuffer = %ld\n", out->cbBuffer);
526 if (!continue_needed)
528 r = QueryContextAttributesA(&conn->ctx, SECPKG_ATTR_SIZES, &secctx_sizes);
529 if (FAILED(r))
531 WARN("QueryContextAttributes failed with error 0x%08x\n", r);
532 goto failed;
534 conn->signature_auth_len = secctx_sizes.cbMaxSignature;
535 conn->encryption_auth_len = secctx_sizes.cbSecurityTrailer;
538 return RPC_S_OK;
540 failed:
541 HeapFree(GetProcessHeap(), 0, out->pvBuffer);
542 out->pvBuffer = NULL;
543 return ERROR_ACCESS_DENIED; /* FIXME: is this correct? */
546 /***********************************************************************
547 * RPCRT4_AuthorizeBinding (internal)
549 static RPC_STATUS RPCRT_AuthorizeConnection(RpcConnection* conn,
550 BYTE *challenge, ULONG count)
552 SecBuffer inp, out;
553 RpcPktHdr *resp_hdr;
554 RPC_STATUS status;
556 TRACE("challenge %s, %d bytes\n", challenge, count);
558 inp.BufferType = SECBUFFER_TOKEN;
559 inp.pvBuffer = challenge;
560 inp.cbBuffer = count;
562 status = RPCRT4_ClientAuthorize(conn, &inp, &out);
563 if (status) return status;
565 resp_hdr = RPCRT4_BuildAuthHeader(NDR_LOCAL_DATA_REPRESENTATION);
566 if (!resp_hdr)
567 return E_OUTOFMEMORY;
569 status = RPCRT4_SendAuth(conn, resp_hdr, NULL, 0, out.pvBuffer, out.cbBuffer);
571 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
572 RPCRT4_FreeHeader(resp_hdr);
574 return status;
577 /***********************************************************************
578 * RPCRT4_Send (internal)
580 * Transmit a packet over connection in acceptable fragments.
582 RPC_STATUS RPCRT4_Send(RpcConnection *Connection, RpcPktHdr *Header,
583 void *Buffer, unsigned int BufferLength)
585 RPC_STATUS r;
586 SecBuffer out;
588 if (!Connection->AuthInfo || SecIsValidHandle(&Connection->ctx))
590 return RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, NULL, 0);
593 /* tack on a negotiate packet */
594 RPCRT4_ClientAuthorize(Connection, NULL, &out);
595 r = RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, out.pvBuffer, out.cbBuffer);
596 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
598 return r;
601 /***********************************************************************
602 * RPCRT4_Receive (internal)
604 * Receive a packet from connection and merge the fragments.
606 RPC_STATUS RPCRT4_Receive(RpcConnection *Connection, RpcPktHdr **Header,
607 PRPC_MESSAGE pMsg)
609 RPC_STATUS status;
610 DWORD hdr_length;
611 LONG dwRead;
612 unsigned short first_flag;
613 unsigned long data_length;
614 unsigned long buffer_length;
615 unsigned long auth_length;
616 unsigned char *auth_data = NULL;
617 RpcPktCommonHdr common_hdr;
619 *Header = NULL;
621 TRACE("(%p, %p, %p)\n", Connection, Header, pMsg);
623 /* read packet common header */
624 dwRead = rpcrt4_conn_read(Connection, &common_hdr, sizeof(common_hdr));
625 if (dwRead != sizeof(common_hdr)) {
626 WARN("Short read of header, %d bytes\n", dwRead);
627 status = RPC_S_PROTOCOL_ERROR;
628 goto fail;
631 /* verify if the header really makes sense */
632 if (common_hdr.rpc_ver != RPC_VER_MAJOR ||
633 common_hdr.rpc_ver_minor != RPC_VER_MINOR) {
634 WARN("unhandled packet version\n");
635 status = RPC_S_PROTOCOL_ERROR;
636 goto fail;
639 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
640 if (hdr_length == 0) {
641 WARN("header length == 0\n");
642 status = RPC_S_PROTOCOL_ERROR;
643 goto fail;
646 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
647 memcpy(*Header, &common_hdr, sizeof(common_hdr));
649 /* read the rest of packet header */
650 dwRead = rpcrt4_conn_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
651 if (dwRead != hdr_length - sizeof(common_hdr)) {
652 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
653 status = RPC_S_PROTOCOL_ERROR;
654 goto fail;
657 /* read packet body */
658 switch (common_hdr.ptype) {
659 case PKT_RESPONSE:
660 pMsg->BufferLength = (*Header)->response.alloc_hint;
661 break;
662 case PKT_REQUEST:
663 pMsg->BufferLength = (*Header)->request.alloc_hint;
664 break;
665 default:
666 pMsg->BufferLength = common_hdr.frag_len - hdr_length - RPC_AUTH_VERIFIER_LEN(&common_hdr);
669 TRACE("buffer length = %u\n", pMsg->BufferLength);
671 status = I_RpcGetBuffer(pMsg);
672 if (status != RPC_S_OK) goto fail;
674 first_flag = RPC_FLG_FIRST;
675 auth_length = common_hdr.auth_len;
676 if (auth_length) {
677 auth_data = HeapAlloc(GetProcessHeap(), 0, RPC_AUTH_VERIFIER_LEN(&common_hdr));
678 if (!auth_data) {
679 status = RPC_S_PROTOCOL_ERROR;
680 goto fail;
683 buffer_length = 0;
684 while (TRUE)
686 unsigned int header_auth_len = RPC_AUTH_VERIFIER_LEN(&(*Header)->common);
688 /* verify header fields */
690 if (((*Header)->common.frag_len < hdr_length) ||
691 ((*Header)->common.frag_len - hdr_length < header_auth_len)) {
692 WARN("frag_len %d too small for hdr_length %d and auth_len %d\n",
693 (*Header)->common.frag_len, hdr_length, header_auth_len);
694 status = RPC_S_PROTOCOL_ERROR;
695 goto fail;
698 if ((*Header)->common.auth_len != auth_length) {
699 WARN("auth_len header field changed from %ld to %d\n",
700 auth_length, (*Header)->common.auth_len);
701 status = RPC_S_PROTOCOL_ERROR;
702 goto fail;
705 if (((*Header)->common.flags & RPC_FLG_FIRST) != first_flag) {
706 TRACE("invalid packet flags\n");
707 status = RPC_S_PROTOCOL_ERROR;
708 goto fail;
711 data_length = (*Header)->common.frag_len - hdr_length - header_auth_len;
712 if (data_length + buffer_length > pMsg->BufferLength) {
713 TRACE("allocation hint exceeded, new buffer length = %ld\n",
714 data_length + buffer_length);
715 pMsg->BufferLength = data_length + buffer_length;
716 status = I_RpcReAllocateBuffer(pMsg);
717 if (status != RPC_S_OK) goto fail;
720 if (data_length == 0) dwRead = 0; else
721 dwRead = rpcrt4_conn_read(Connection,
722 (unsigned char *)pMsg->Buffer + buffer_length, data_length);
723 if (dwRead != data_length) {
724 WARN("bad data length, %d/%ld\n", dwRead, data_length);
725 status = RPC_S_PROTOCOL_ERROR;
726 goto fail;
729 if (header_auth_len) {
730 if (header_auth_len < sizeof(RpcAuthVerifier)) {
731 WARN("bad auth verifier length %d\n", header_auth_len);
732 status = RPC_S_PROTOCOL_ERROR;
733 goto fail;
736 /* FIXME: we should accumulate authentication data for the bind,
737 * bind_ack, alter_context and alter_context_response if necessary.
738 * however, the details of how this is done is very sketchy in the
739 * DCE/RPC spec. for all other packet types that have authentication
740 * verifier data then it is just duplicated in all the fragments */
741 dwRead = rpcrt4_conn_read(Connection, auth_data, header_auth_len);
742 if (dwRead != header_auth_len) {
743 WARN("bad authentication data length, %d/%d\n", dwRead,
744 header_auth_len);
745 status = RPC_S_PROTOCOL_ERROR;
746 goto fail;
749 /* these packets are handled specially, not by the generic SecurePacket
750 * function */
751 if ((common_hdr.ptype != PKT_BIND) &&
752 (common_hdr.ptype != PKT_BIND_ACK) &&
753 (common_hdr.ptype != PKT_AUTH3))
754 status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_RECEIVE,
755 *Header, hdr_length,
756 (unsigned char *)pMsg->Buffer + buffer_length, data_length,
757 (RpcAuthVerifier *)auth_data,
758 (unsigned char *)auth_data + sizeof(RpcAuthVerifier),
759 header_auth_len - sizeof(RpcAuthVerifier));
762 buffer_length += data_length;
763 if (!((*Header)->common.flags & RPC_FLG_LAST)) {
764 TRACE("next header\n");
766 /* read the header of next packet */
767 dwRead = rpcrt4_conn_read(Connection, *Header, hdr_length);
768 if (dwRead != hdr_length) {
769 WARN("invalid packet header size (%d)\n", dwRead);
770 status = RPC_S_PROTOCOL_ERROR;
771 goto fail;
774 first_flag = 0;
775 } else {
776 break;
779 pMsg->BufferLength = buffer_length;
781 /* respond to authorization request */
782 if (common_hdr.ptype == PKT_BIND_ACK && auth_length > sizeof(RpcAuthVerifier))
784 status = RPCRT_AuthorizeConnection(Connection,
785 auth_data + sizeof(RpcAuthVerifier),
786 auth_length);
787 if (status)
788 goto fail;
791 /* success */
792 status = RPC_S_OK;
794 fail:
795 if (status != RPC_S_OK) {
796 RPCRT4_FreeHeader(*Header);
797 *Header = NULL;
799 HeapFree(GetProcessHeap(), 0, auth_data);
800 return status;
803 /***********************************************************************
804 * I_RpcGetBuffer [RPCRT4.@]
806 * Allocates a buffer for use by I_RpcSend or I_RpcSendReceive and binds to the
807 * server interface.
809 * PARAMS
810 * pMsg [I/O] RPC message information.
812 * RETURNS
813 * Success: RPC_S_OK.
814 * Failure: RPC_S_INVALID_BINDING if pMsg->Handle is invalid.
815 * RPC_S_SERVER_UNAVAILABLE if unable to connect to server.
816 * ERROR_OUTOFMEMORY if buffer allocation failed.
818 * NOTES
819 * The pMsg->BufferLength field determines the size of the buffer to allocate,
820 * in bytes.
822 * Use I_RpcFreeBuffer() to unbind from the server and free the message buffer.
824 * SEE ALSO
825 * I_RpcFreeBuffer(), I_RpcSend(), I_RpcReceive(), I_RpcSendReceive().
827 RPC_STATUS WINAPI I_RpcGetBuffer(PRPC_MESSAGE pMsg)
829 TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
830 /* FIXME: pfnAllocate? */
831 pMsg->Buffer = HeapAlloc(GetProcessHeap(), 0, pMsg->BufferLength);
833 TRACE("Buffer=%p\n", pMsg->Buffer);
834 /* FIXME: which errors to return? */
835 return pMsg->Buffer ? S_OK : E_OUTOFMEMORY;
838 /***********************************************************************
839 * I_RpcReAllocateBuffer (internal)
841 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg)
843 TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
844 pMsg->Buffer = HeapReAlloc(GetProcessHeap(), 0, pMsg->Buffer, pMsg->BufferLength);
846 TRACE("Buffer=%p\n", pMsg->Buffer);
847 return pMsg->Buffer ? RPC_S_OK : RPC_S_OUT_OF_RESOURCES;
850 /***********************************************************************
851 * I_RpcFreeBuffer [RPCRT4.@]
853 * Frees a buffer allocated by I_RpcGetBuffer or I_RpcReceive and unbinds from
854 * the server interface.
856 * PARAMS
857 * pMsg [I/O] RPC message information.
859 * RETURNS
860 * RPC_S_OK.
862 * SEE ALSO
863 * I_RpcGetBuffer(), I_RpcReceive().
865 RPC_STATUS WINAPI I_RpcFreeBuffer(PRPC_MESSAGE pMsg)
867 TRACE("(%p) Buffer=%p\n", pMsg, pMsg->Buffer);
868 /* FIXME: pfnFree? */
869 HeapFree(GetProcessHeap(), 0, pMsg->Buffer);
870 pMsg->Buffer = NULL;
871 return S_OK;
874 /***********************************************************************
875 * I_RpcSend [RPCRT4.@]
877 * Sends a message to the server.
879 * PARAMS
880 * pMsg [I/O] RPC message information.
882 * RETURNS
883 * Unknown.
885 * NOTES
886 * The buffer must have been allocated with I_RpcGetBuffer().
888 * SEE ALSO
889 * I_RpcGetBuffer(), I_RpcReceive(), I_RpcSendReceive().
891 RPC_STATUS WINAPI I_RpcSend(PRPC_MESSAGE pMsg)
893 RpcBinding* bind = (RpcBinding*)pMsg->Handle;
894 RpcConnection* conn;
895 RPC_CLIENT_INTERFACE* cif = NULL;
896 RPC_SERVER_INTERFACE* sif = NULL;
897 RPC_STATUS status;
898 RpcPktHdr *hdr;
900 TRACE("(%p)\n", pMsg);
901 if (!bind) return RPC_S_INVALID_BINDING;
903 if (bind->server) {
904 sif = pMsg->RpcInterfaceInformation;
905 if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
906 status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
907 &sif->InterfaceId);
908 } else {
909 cif = pMsg->RpcInterfaceInformation;
910 if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
912 if (!bind->Endpoint || !bind->Endpoint[0])
914 TRACE("automatically resolving partially bound binding\n");
915 status = RpcEpResolveBinding(bind, cif);
916 if (status != RPC_S_OK) return status;
919 status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
920 &cif->InterfaceId);
923 if (status != RPC_S_OK) return status;
925 if (bind->server) {
926 if (pMsg->RpcFlags & WINE_RPCFLAG_EXCEPTION) {
927 hdr = RPCRT4_BuildFaultHeader(pMsg->DataRepresentation,
928 RPC_S_CALL_FAILED);
929 } else {
930 hdr = RPCRT4_BuildResponseHeader(pMsg->DataRepresentation,
931 pMsg->BufferLength);
933 } else {
934 hdr = RPCRT4_BuildRequestHeader(pMsg->DataRepresentation,
935 pMsg->BufferLength, pMsg->ProcNum,
936 &bind->ObjectUuid);
937 hdr->common.call_id = conn->NextCallId++;
940 status = RPCRT4_Send(conn, hdr, pMsg->Buffer, pMsg->BufferLength);
942 RPCRT4_FreeHeader(hdr);
944 /* success */
945 if (!bind->server) {
946 /* save the connection, so the response can be read from it */
947 pMsg->ReservedForRuntime = conn;
948 return status;
950 RPCRT4_CloseBinding(bind, conn);
952 return status;
955 /***********************************************************************
956 * I_RpcReceive [RPCRT4.@]
958 RPC_STATUS WINAPI I_RpcReceive(PRPC_MESSAGE pMsg)
960 RpcBinding* bind = (RpcBinding*)pMsg->Handle;
961 RpcConnection* conn;
962 RPC_CLIENT_INTERFACE* cif = NULL;
963 RPC_SERVER_INTERFACE* sif = NULL;
964 RPC_STATUS status;
965 RpcPktHdr *hdr = NULL;
967 TRACE("(%p)\n", pMsg);
968 if (!bind) return RPC_S_INVALID_BINDING;
970 if (pMsg->ReservedForRuntime) {
971 conn = pMsg->ReservedForRuntime;
972 pMsg->ReservedForRuntime = NULL;
973 } else {
974 if (bind->server) {
975 sif = pMsg->RpcInterfaceInformation;
976 if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
977 status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
978 &sif->InterfaceId);
979 } else {
980 cif = pMsg->RpcInterfaceInformation;
981 if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
983 if (!bind->Endpoint || !bind->Endpoint[0])
985 TRACE("automatically resolving partially bound binding\n");
986 status = RpcEpResolveBinding(bind, cif);
987 if (status != RPC_S_OK) return status;
990 status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
991 &cif->InterfaceId);
993 if (status != RPC_S_OK) return status;
996 status = RPCRT4_Receive(conn, &hdr, pMsg);
997 if (status != RPC_S_OK) {
998 WARN("receive failed with error %lx\n", status);
999 goto fail;
1002 status = RPC_S_PROTOCOL_ERROR;
1004 switch (hdr->common.ptype) {
1005 case PKT_RESPONSE:
1006 if (bind->server) goto fail;
1007 break;
1008 case PKT_REQUEST:
1009 if (!bind->server) goto fail;
1010 break;
1011 case PKT_FAULT:
1012 pMsg->RpcFlags |= WINE_RPCFLAG_EXCEPTION;
1013 ERR ("we got fault packet with status 0x%lx\n", hdr->fault.status);
1014 status = hdr->fault.status; /* FIXME: do translation from nca error codes */
1015 goto fail;
1016 default:
1017 WARN("bad packet type %d\n", hdr->common.ptype);
1018 goto fail;
1021 /* success */
1022 status = RPC_S_OK;
1024 fail:
1025 RPCRT4_FreeHeader(hdr);
1026 RPCRT4_CloseBinding(bind, conn);
1027 return status;
1030 /***********************************************************************
1031 * I_RpcSendReceive [RPCRT4.@]
1033 * Sends a message to the server and receives the response.
1035 * PARAMS
1036 * pMsg [I/O] RPC message information.
1038 * RETURNS
1039 * Success: RPC_S_OK.
1040 * Failure: Any error code.
1042 * NOTES
1043 * The buffer must have been allocated with I_RpcGetBuffer().
1045 * SEE ALSO
1046 * I_RpcGetBuffer(), I_RpcSend(), I_RpcReceive().
1048 RPC_STATUS WINAPI I_RpcSendReceive(PRPC_MESSAGE pMsg)
1050 RPC_STATUS status;
1051 RPC_MESSAGE original_message;
1053 TRACE("(%p)\n", pMsg);
1055 original_message = *pMsg;
1056 status = I_RpcSend(pMsg);
1057 if (status == RPC_S_OK)
1058 status = I_RpcReceive(pMsg);
1059 /* free the buffer replaced by a new buffer in I_RpcReceive */
1060 if (status == RPC_S_OK)
1061 I_RpcFreeBuffer(&original_message);
1062 return status;