user: Added fast 16->32 mapping for WM_COPYDATA, WM_GETDLGCODE and WM_NEXTMENU.
[wine] / dlls / rpcrt4 / rpc_message.c
1 /*
2  * RPC messages
3  *
4  * Copyright 2001-2002 Ove Kåven, TransGaming Technologies
5  * Copyright 2004 Filip Navara
6  * Copyright 2006 CodeWeavers
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <string.h>
26
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winerror.h"
30 #include "winreg.h"
31
32 #include "rpc.h"
33 #include "rpcndr.h"
34 #include "rpcdcep.h"
35
36 #include "wine/debug.h"
37
38 #include "rpc_binding.h"
39 #include "rpc_misc.h"
40 #include "rpc_defs.h"
41 #include "rpc_message.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
44
45 /* note: the DCE/RPC spec says the alignment amount should be 4, but
46  * MS/RPC servers seem to always use 16 */
47 #define AUTH_ALIGNMENT 16
48
49 /* gets the amount needed to round a value up to the specified alignment */
50 #define ROUND_UP_AMOUNT(value, alignment) \
51     (((alignment) - (((value) % (alignment)))) % (alignment))
52
53 static DWORD RPCRT4_GetHeaderSize(RpcPktHdr *Header)
54 {
55   static const DWORD header_sizes[] = {
56     sizeof(Header->request), 0, sizeof(Header->response),
57     sizeof(Header->fault), 0, 0, 0, 0, 0, 0, 0, sizeof(Header->bind),
58     sizeof(Header->bind_ack), sizeof(Header->bind_nack),
59     0, 0, 0, 0, 0
60   };
61   ULONG ret = 0;
62   
63   if (Header->common.ptype < sizeof(header_sizes) / sizeof(header_sizes[0])) {
64     ret = header_sizes[Header->common.ptype];
65     if (ret == 0)
66       FIXME("unhandled packet type\n");
67     if (Header->common.flags & RPC_FLG_OBJECT_UUID)
68       ret += sizeof(UUID);
69   } else {
70     TRACE("invalid packet type\n");
71   }
72
73   return ret;
74 }
75
76 static VOID RPCRT4_BuildCommonHeader(RpcPktHdr *Header, unsigned char PacketType,
77                               unsigned long DataRepresentation)
78 {
79   Header->common.rpc_ver = RPC_VER_MAJOR;
80   Header->common.rpc_ver_minor = RPC_VER_MINOR;
81   Header->common.ptype = PacketType;
82   Header->common.drep[0] = LOBYTE(LOWORD(DataRepresentation));
83   Header->common.drep[1] = HIBYTE(LOWORD(DataRepresentation));
84   Header->common.drep[2] = LOBYTE(HIWORD(DataRepresentation));
85   Header->common.drep[3] = HIBYTE(HIWORD(DataRepresentation));
86   Header->common.auth_len = 0;
87   Header->common.call_id = 1;
88   Header->common.flags = 0;
89   /* Flags and fragment length are computed in RPCRT4_Send. */
90 }                              
91
92 static RpcPktHdr *RPCRT4_BuildRequestHeader(unsigned long DataRepresentation,
93                                      unsigned long BufferLength,
94                                      unsigned short ProcNum,
95                                      UUID *ObjectUuid)
96 {
97   RpcPktHdr *header;
98   BOOL has_object;
99   RPC_STATUS status;
100
101   has_object = (ObjectUuid != NULL && !UuidIsNil(ObjectUuid, &status));
102   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
103                      sizeof(header->request) + (has_object ? sizeof(UUID) : 0));
104   if (header == NULL) {
105     return NULL;
106   }
107
108   RPCRT4_BuildCommonHeader(header, PKT_REQUEST, DataRepresentation);
109   header->common.frag_len = sizeof(header->request);
110   header->request.alloc_hint = BufferLength;
111   header->request.context_id = 0;
112   header->request.opnum = ProcNum;
113   if (has_object) {
114     header->common.flags |= RPC_FLG_OBJECT_UUID;
115     header->common.frag_len += sizeof(UUID);
116     memcpy(&header->request + 1, ObjectUuid, sizeof(UUID));
117   }
118
119   return header;
120 }
121
122 static RpcPktHdr *RPCRT4_BuildResponseHeader(unsigned long DataRepresentation,
123                                       unsigned long BufferLength)
124 {
125   RpcPktHdr *header;
126
127   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->response));
128   if (header == NULL) {
129     return NULL;
130   }
131
132   RPCRT4_BuildCommonHeader(header, PKT_RESPONSE, DataRepresentation);
133   header->common.frag_len = sizeof(header->response);
134   header->response.alloc_hint = BufferLength;
135
136   return header;
137 }
138
139 RpcPktHdr *RPCRT4_BuildFaultHeader(unsigned long DataRepresentation,
140                                    RPC_STATUS Status)
141 {
142   RpcPktHdr *header;
143
144   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->fault));
145   if (header == NULL) {
146     return NULL;
147   }
148
149   RPCRT4_BuildCommonHeader(header, PKT_FAULT, DataRepresentation);
150   header->common.frag_len = sizeof(header->fault);
151   header->fault.status = Status;
152
153   return header;
154 }
155
156 RpcPktHdr *RPCRT4_BuildBindHeader(unsigned long DataRepresentation,
157                                   unsigned short MaxTransmissionSize,
158                                   unsigned short MaxReceiveSize,
159                                   RPC_SYNTAX_IDENTIFIER *AbstractId,
160                                   RPC_SYNTAX_IDENTIFIER *TransferId)
161 {
162   RpcPktHdr *header;
163
164   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind));
165   if (header == NULL) {
166     return NULL;
167   }
168
169   RPCRT4_BuildCommonHeader(header, PKT_BIND, DataRepresentation);
170   header->common.frag_len = sizeof(header->bind);
171   header->bind.max_tsize = MaxTransmissionSize;
172   header->bind.max_rsize = MaxReceiveSize;
173   header->bind.num_elements = 1;
174   header->bind.num_syntaxes = 1;
175   memcpy(&header->bind.abstract, AbstractId, sizeof(RPC_SYNTAX_IDENTIFIER));
176   memcpy(&header->bind.transfer, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
177
178   return header;
179 }
180
181 RpcPktHdr *RPCRT4_BuildAuthHeader(unsigned long DataRepresentation)
182 {
183   RpcPktHdr *header;
184
185   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
186                      sizeof(header->common) + 12);
187   if (header == NULL)
188     return NULL;
189
190   RPCRT4_BuildCommonHeader(header, PKT_AUTH3, DataRepresentation);
191   header->common.frag_len = 0x14;
192   header->common.auth_len = 0;
193
194   return header;
195 }
196
197 RpcPktHdr *RPCRT4_BuildBindNackHeader(unsigned long DataRepresentation,
198                                       unsigned char RpcVersion,
199                                       unsigned char RpcVersionMinor)
200 {
201   RpcPktHdr *header;
202
203   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind_nack));
204   if (header == NULL) {
205     return NULL;
206   }
207
208   RPCRT4_BuildCommonHeader(header, PKT_BIND_NACK, DataRepresentation);
209   header->common.frag_len = sizeof(header->bind_nack);
210   header->bind_nack.protocols_count = 1;
211   header->bind_nack.protocols[0].rpc_ver = RpcVersion;
212   header->bind_nack.protocols[0].rpc_ver_minor = RpcVersionMinor;
213
214   return header;
215 }
216
217 RpcPktHdr *RPCRT4_BuildBindAckHeader(unsigned long DataRepresentation,
218                                      unsigned short MaxTransmissionSize,
219                                      unsigned short MaxReceiveSize,
220                                      LPSTR ServerAddress,
221                                      unsigned long Result,
222                                      unsigned long Reason,
223                                      RPC_SYNTAX_IDENTIFIER *TransferId)
224 {
225   RpcPktHdr *header;
226   unsigned long header_size;
227   RpcAddressString *server_address;
228   RpcResults *results;
229   RPC_SYNTAX_IDENTIFIER *transfer_id;
230
231   header_size = sizeof(header->bind_ack) + sizeof(RpcResults) +
232                 sizeof(RPC_SYNTAX_IDENTIFIER) + sizeof(RpcAddressString) +
233                 strlen(ServerAddress);
234
235   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, header_size);
236   if (header == NULL) {
237     return NULL;
238   }
239
240   RPCRT4_BuildCommonHeader(header, PKT_BIND_ACK, DataRepresentation);
241   header->common.frag_len = header_size;
242   header->bind_ack.max_tsize = MaxTransmissionSize;
243   header->bind_ack.max_rsize = MaxReceiveSize;
244   server_address = (RpcAddressString*)(&header->bind_ack + 1);
245   server_address->length = strlen(ServerAddress) + 1;
246   strcpy(server_address->string, ServerAddress);
247   results = (RpcResults*)((ULONG_PTR)server_address + sizeof(RpcAddressString) + server_address->length - 1);
248   results->num_results = 1;
249   results->results[0].result = Result;
250   results->results[0].reason = Reason;
251   transfer_id = (RPC_SYNTAX_IDENTIFIER*)(results + 1);
252   memcpy(transfer_id, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
253
254   return header;
255 }
256
257 VOID RPCRT4_FreeHeader(RpcPktHdr *Header)
258 {
259   HeapFree(GetProcessHeap(), 0, Header);
260 }
261
262 /***********************************************************************
263  *           RPCRT4_SendAuth (internal)
264  * 
265  * Transmit a packet with authorization data over connection in acceptable fragments.
266  */
267 static RPC_STATUS RPCRT4_SendAuth(RpcConnection *Connection, RpcPktHdr *Header,
268                                   void *Buffer, unsigned int BufferLength,
269                                   void *Auth, unsigned int AuthLength)
270 {
271   PUCHAR buffer_pos;
272   DWORD hdr_size;
273   LONG count;
274   unsigned char *pkt;
275   LONG alen = AuthLength ? (AuthLength + sizeof(RpcAuthVerifier)) : 0;
276
277   buffer_pos = Buffer;
278   /* The packet building functions save the packet header size, so we can use it. */
279   hdr_size = Header->common.frag_len;
280   Header->common.auth_len = AuthLength;
281   Header->common.flags |= RPC_FLG_FIRST;
282   Header->common.flags &= ~RPC_FLG_LAST;
283   while (!(Header->common.flags & RPC_FLG_LAST)) {
284     unsigned char auth_pad_len = AuthLength ? ROUND_UP_AMOUNT(BufferLength, AUTH_ALIGNMENT) : 0;
285     unsigned short pkt_size = BufferLength + hdr_size + alen + auth_pad_len;
286
287     /* decide if we need to split the packet into fragments */
288    if (pkt_size <= Connection->MaxTransmissionSize) {
289      Header->common.flags |= RPC_FLG_LAST;
290      Header->common.frag_len = pkt_size;
291     } else {
292       auth_pad_len = 0;
293       /* make sure packet payload will be a multiple of 16 */
294       Header->common.frag_len =
295         ((Connection->MaxTransmissionSize - hdr_size - alen) & ~(AUTH_ALIGNMENT-1)) +
296         hdr_size + alen;
297     }
298
299     pkt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Header->common.frag_len);
300
301     memcpy(pkt, Header, hdr_size);
302
303     /* fragment consisted of header only and is the last one */
304     if (hdr_size == Header->common.frag_len)
305       goto write;
306
307     memcpy(pkt + hdr_size, buffer_pos, Header->common.frag_len - hdr_size - auth_pad_len - alen);
308
309     /* add the authorization info */
310     if (Connection->AuthInfo && AuthLength)
311     {
312       RpcAuthVerifier *auth_hdr = (RpcAuthVerifier *)&pkt[Header->common.frag_len - alen];
313
314       auth_hdr->auth_type = Connection->AuthInfo->AuthnSvc;
315       auth_hdr->auth_level = Connection->AuthInfo->AuthnLevel;
316       auth_hdr->auth_pad_length = auth_pad_len;
317       auth_hdr->auth_reserved = 0;
318       /* a unique number... */
319       auth_hdr->auth_context_id = (unsigned long)Connection;
320
321       memcpy(auth_hdr + 1, Auth, AuthLength);
322     }
323
324 write:
325     count = rpcrt4_conn_write(Connection, pkt, Header->common.frag_len);
326     HeapFree(GetProcessHeap(), 0, pkt);
327     if (count<0) {
328       WARN("rpcrt4_conn_write failed (auth)\n");
329       return RPC_S_PROTOCOL_ERROR;
330     }
331
332     buffer_pos += Header->common.frag_len - hdr_size - alen - auth_pad_len;
333     BufferLength -= Header->common.frag_len - hdr_size - alen - auth_pad_len;
334     Header->common.flags &= ~RPC_FLG_FIRST;
335   }
336
337   return RPC_S_OK;
338 }
339
340 /***********************************************************************
341  *           RPCRT4_AuthNegotiate (internal)
342  */
343 static void RPCRT4_AuthNegotiate(RpcConnection *conn, SecBuffer *out)
344 {
345   SECURITY_STATUS r;
346   SecBufferDesc out_desc;
347   unsigned char *buffer;
348
349   buffer = HeapAlloc(GetProcessHeap(), 0, 0x100);
350
351   out->BufferType = SECBUFFER_TOKEN;
352   out->cbBuffer = 0x100;
353   out->pvBuffer = buffer;
354
355   out_desc.ulVersion = 0;
356   out_desc.cBuffers = 1;
357   out_desc.pBuffers = out;
358
359   conn->attr = 0;
360   conn->ctx.dwLower = 0;
361   conn->ctx.dwUpper = 0;
362
363   r = InitializeSecurityContextA(&conn->AuthInfo->cred, NULL, NULL,
364         ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE | ISC_REQ_MUTUAL_AUTH |
365         ISC_REQ_DELEGATE, 0, SECURITY_NETWORK_DREP,
366         NULL, 0, &conn->ctx, &out_desc, &conn->attr, &conn->exp);
367
368   TRACE("r = %08lx cbBuffer = %ld attr = %08lx\n", r, out->cbBuffer, conn->attr);
369 }
370
371 /***********************************************************************
372  *           RPCRT4_AuthorizeBinding (internal)
373  */
374 static RPC_STATUS RPCRT_AuthorizeConnection(RpcConnection* conn,
375                                             BYTE *challenge, ULONG count)
376 {
377   SecBufferDesc inp_desc, out_desc;
378   SecBuffer inp, out;
379   SECURITY_STATUS r;
380   unsigned char buffer[0x100];
381   RpcPktHdr *resp_hdr;
382   RPC_STATUS status;
383
384   TRACE("challenge %s, %ld bytes\n", challenge, count);
385
386   out.BufferType = SECBUFFER_TOKEN;
387   out.cbBuffer = sizeof buffer;
388   out.pvBuffer = buffer;
389
390   out_desc.ulVersion = 0;
391   out_desc.cBuffers = 1;
392   out_desc.pBuffers = &out;
393
394   inp.BufferType = SECBUFFER_TOKEN;
395   inp.pvBuffer = challenge;
396   inp.cbBuffer = count;
397
398   inp_desc.cBuffers = 1;
399   inp_desc.pBuffers = &inp;
400   inp_desc.ulVersion = 0;
401
402   r = InitializeSecurityContextA(&conn->AuthInfo->cred, &conn->ctx, NULL,
403         ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE | ISC_REQ_MUTUAL_AUTH |
404         ISC_REQ_DELEGATE, 0, SECURITY_NETWORK_DREP,
405         &inp_desc, 0, &conn->ctx, &out_desc, &conn->attr, &conn->exp);
406   if (r)
407   {
408     WARN("InitializeSecurityContext failed with error 0x%08lx\n", r);
409     return ERROR_ACCESS_DENIED;
410   }
411
412   resp_hdr = RPCRT4_BuildAuthHeader(NDR_LOCAL_DATA_REPRESENTATION);
413   if (!resp_hdr)
414     return E_OUTOFMEMORY;
415
416   status = RPCRT4_SendAuth(conn, resp_hdr, NULL, 0, out.pvBuffer, out.cbBuffer);
417
418   RPCRT4_FreeHeader(resp_hdr);
419
420   return status;
421 }
422
423 /***********************************************************************
424  *           RPCRT4_Send (internal)
425  * 
426  * Transmit a packet over connection in acceptable fragments.
427  */
428 RPC_STATUS RPCRT4_Send(RpcConnection *Connection, RpcPktHdr *Header,
429                        void *Buffer, unsigned int BufferLength)
430 {
431   RPC_STATUS r;
432   SecBuffer out;
433
434   /* if we've already authenticated, just send the context */
435   if (Connection->ctx.dwUpper || Connection->ctx.dwLower)
436   {
437     unsigned char buffer[0x10];
438
439     memset(buffer, 0, sizeof buffer);
440     buffer[0] = 1; /* version number lsb */
441
442     return RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, buffer, sizeof buffer);
443   }
444
445   if (!Connection->AuthInfo ||
446       Connection->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_DEFAULT ||
447       Connection->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_NONE)
448   {
449     return RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, NULL, 0);
450   }
451
452   out.BufferType = SECBUFFER_TOKEN;
453   out.cbBuffer = 0;
454   out.pvBuffer = NULL;
455
456   /* tack on a negotiate packet */
457   RPCRT4_AuthNegotiate(Connection, &out);
458   r = RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, out.pvBuffer, out.cbBuffer);
459   HeapFree(GetProcessHeap(), 0, out.pvBuffer);
460
461   return r;
462 }
463
464 /***********************************************************************
465  *           RPCRT4_Receive (internal)
466  * 
467  * Receive a packet from connection and merge the fragments.
468  */
469 RPC_STATUS RPCRT4_Receive(RpcConnection *Connection, RpcPktHdr **Header,
470                           PRPC_MESSAGE pMsg)
471 {
472   RPC_STATUS status;
473   DWORD hdr_length;
474   LONG dwRead;
475   unsigned short first_flag;
476   unsigned long data_length;
477   unsigned long buffer_length;
478   unsigned char *buffer_ptr;
479   RpcPktCommonHdr common_hdr;
480
481   *Header = NULL;
482
483   TRACE("(%p, %p, %p)\n", Connection, Header, pMsg);
484
485   /* read packet common header */
486   dwRead = rpcrt4_conn_read(Connection, &common_hdr, sizeof(common_hdr));
487   if (dwRead != sizeof(common_hdr)) {
488     WARN("Short read of header, %ld/%d bytes\n", dwRead, sizeof(common_hdr));
489     status = RPC_S_PROTOCOL_ERROR;
490     goto fail;
491   }
492
493   /* verify if the header really makes sense */
494   if (common_hdr.rpc_ver != RPC_VER_MAJOR ||
495       common_hdr.rpc_ver_minor != RPC_VER_MINOR) {
496     WARN("unhandled packet version\n");
497     status = RPC_S_PROTOCOL_ERROR;
498     goto fail;
499   }
500
501   hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
502   if (hdr_length == 0) {
503     WARN("header length == 0\n");
504     status = RPC_S_PROTOCOL_ERROR;
505     goto fail;
506   }
507
508   *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
509   memcpy(*Header, &common_hdr, sizeof(common_hdr));
510
511   /* read the rest of packet header */
512   dwRead = rpcrt4_conn_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
513   if (dwRead != hdr_length - sizeof(common_hdr)) {
514     WARN("bad header length, %ld/%ld bytes\n", dwRead, hdr_length - sizeof(common_hdr));
515     status = RPC_S_PROTOCOL_ERROR;
516     goto fail;
517   }
518
519   /* read packet body */
520   switch (common_hdr.ptype) {
521   case PKT_RESPONSE:
522     pMsg->BufferLength = (*Header)->response.alloc_hint;
523     break;
524   case PKT_REQUEST:
525     pMsg->BufferLength = (*Header)->request.alloc_hint;
526     break;
527   default:
528     pMsg->BufferLength = common_hdr.frag_len - hdr_length;
529   }
530
531   TRACE("buffer length = %u\n", pMsg->BufferLength);
532
533   status = I_RpcGetBuffer(pMsg);
534   if (status != RPC_S_OK) goto fail;
535
536   first_flag = RPC_FLG_FIRST;
537   buffer_length = 0;
538   buffer_ptr = pMsg->Buffer;
539   while (buffer_length < pMsg->BufferLength)
540   {
541     data_length = (*Header)->common.frag_len - hdr_length;
542     if (((*Header)->common.flags & RPC_FLG_FIRST) != first_flag ||
543         data_length + buffer_length > pMsg->BufferLength) {
544       TRACE("invalid packet flags or buffer length\n");
545       status = RPC_S_PROTOCOL_ERROR;
546       goto fail;
547     }
548
549     if (data_length == 0) dwRead = 0; else
550     dwRead = rpcrt4_conn_read(Connection, buffer_ptr, data_length);
551     if (dwRead != data_length) {
552       WARN("bad data length, %ld/%ld\n", dwRead, data_length);
553       status = RPC_S_PROTOCOL_ERROR;
554       goto fail;
555     }
556
557     /* when there is no more data left, it should be the last packet */
558     if (buffer_length == pMsg->BufferLength &&
559         ((*Header)->common.flags & RPC_FLG_LAST) == 0) {
560       WARN("no more data left, but not last packet\n");
561       status = RPC_S_PROTOCOL_ERROR;
562       goto fail;
563     }
564
565     buffer_length += data_length;
566     if (buffer_length < pMsg->BufferLength) {
567       TRACE("next header\n");
568
569       /* read the header of next packet */
570       dwRead = rpcrt4_conn_read(Connection, *Header, hdr_length);
571       if (dwRead != hdr_length) {
572         WARN("invalid packet header size (%ld)\n", dwRead);
573         status = RPC_S_PROTOCOL_ERROR;
574         goto fail;
575       }
576
577       buffer_ptr += data_length;
578       first_flag = 0;
579     }
580   }
581
582   /* respond to authorization request */
583   if (common_hdr.ptype == PKT_BIND_ACK && common_hdr.auth_len > 8)
584   {
585     unsigned int offset;
586
587     offset = common_hdr.frag_len - hdr_length - common_hdr.auth_len;
588     status = RPCRT_AuthorizeConnection(Connection, (LPBYTE)pMsg->Buffer + offset,
589                                        common_hdr.auth_len);
590     if (status)
591         goto fail;
592   }
593
594   /* success */
595   status = RPC_S_OK;
596
597 fail:
598   if (status != RPC_S_OK && *Header) {
599     RPCRT4_FreeHeader(*Header);
600     *Header = NULL;
601   }
602   return status;
603 }
604
605 /***********************************************************************
606  *           I_RpcGetBuffer [RPCRT4.@]
607  */
608 RPC_STATUS WINAPI I_RpcGetBuffer(PRPC_MESSAGE pMsg)
609 {
610   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
611   /* FIXME: pfnAllocate? */
612   pMsg->Buffer = HeapAlloc(GetProcessHeap(), 0, pMsg->BufferLength);
613
614   TRACE("Buffer=%p\n", pMsg->Buffer);
615   /* FIXME: which errors to return? */
616   return pMsg->Buffer ? S_OK : E_OUTOFMEMORY;
617 }
618
619 /***********************************************************************
620  *           I_RpcFreeBuffer [RPCRT4.@]
621  */
622 RPC_STATUS WINAPI I_RpcFreeBuffer(PRPC_MESSAGE pMsg)
623 {
624   TRACE("(%p) Buffer=%p\n", pMsg, pMsg->Buffer);
625   /* FIXME: pfnFree? */
626   HeapFree(GetProcessHeap(), 0, pMsg->Buffer);
627   pMsg->Buffer = NULL;
628   return S_OK;
629 }
630
631 /***********************************************************************
632  *           I_RpcSend [RPCRT4.@]
633  */
634 RPC_STATUS WINAPI I_RpcSend(PRPC_MESSAGE pMsg)
635 {
636   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
637   RpcConnection* conn;
638   RPC_CLIENT_INTERFACE* cif = NULL;
639   RPC_SERVER_INTERFACE* sif = NULL;
640   RPC_STATUS status;
641   RpcPktHdr *hdr;
642
643   TRACE("(%p)\n", pMsg);
644   if (!bind) return RPC_S_INVALID_BINDING;
645
646   if (bind->server) {
647     sif = pMsg->RpcInterfaceInformation;
648     if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
649     status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
650                                 &sif->InterfaceId);
651   } else {
652     cif = pMsg->RpcInterfaceInformation;
653     if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
654
655     if (!bind->Endpoint || !bind->Endpoint[0])
656     {
657       TRACE("automatically resolving partially bound binding\n");
658       status = RpcEpResolveBinding(bind, cif);
659       if (status != RPC_S_OK) return status;
660     }
661
662     status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
663                                 &cif->InterfaceId);
664   }
665
666   if (status != RPC_S_OK) return status;
667
668   if (bind->server) {
669     if (pMsg->RpcFlags & WINE_RPCFLAG_EXCEPTION) {
670       hdr = RPCRT4_BuildFaultHeader(pMsg->DataRepresentation,
671                                     RPC_S_CALL_FAILED);
672     } else {
673       hdr = RPCRT4_BuildResponseHeader(pMsg->DataRepresentation,
674                                        pMsg->BufferLength);
675     }
676   } else {
677     hdr = RPCRT4_BuildRequestHeader(pMsg->DataRepresentation,
678                                     pMsg->BufferLength, pMsg->ProcNum,
679                                     &bind->ObjectUuid);
680     hdr->common.call_id = conn->NextCallId++;
681   }
682
683   status = RPCRT4_Send(conn, hdr, pMsg->Buffer, pMsg->BufferLength);
684
685   RPCRT4_FreeHeader(hdr);
686
687   /* success */
688   if (!bind->server) {
689     /* save the connection, so the response can be read from it */
690     pMsg->ReservedForRuntime = conn;
691     return RPC_S_OK;
692   }
693   RPCRT4_CloseBinding(bind, conn);
694   status = RPC_S_OK;
695
696   return status;
697 }
698
699 /***********************************************************************
700  *           I_RpcReceive [RPCRT4.@]
701  */
702 RPC_STATUS WINAPI I_RpcReceive(PRPC_MESSAGE pMsg)
703 {
704   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
705   RpcConnection* conn;
706   RPC_CLIENT_INTERFACE* cif = NULL;
707   RPC_SERVER_INTERFACE* sif = NULL;
708   RPC_STATUS status;
709   RpcPktHdr *hdr = NULL;
710
711   TRACE("(%p)\n", pMsg);
712   if (!bind) return RPC_S_INVALID_BINDING;
713
714   if (pMsg->ReservedForRuntime) {
715     conn = pMsg->ReservedForRuntime;
716     pMsg->ReservedForRuntime = NULL;
717   } else {
718     if (bind->server) {
719       sif = pMsg->RpcInterfaceInformation;
720       if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
721       status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
722                                   &sif->InterfaceId);
723     } else {
724       cif = pMsg->RpcInterfaceInformation;
725       if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
726
727       if (!bind->Endpoint || !bind->Endpoint[0])
728       {
729         TRACE("automatically resolving partially bound binding\n");
730         status = RpcEpResolveBinding(bind, cif);
731         if (status != RPC_S_OK) return status;
732       }
733
734       status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
735                                   &cif->InterfaceId);
736     }
737     if (status != RPC_S_OK) return status;
738   }
739
740   status = RPCRT4_Receive(conn, &hdr, pMsg);
741   if (status != RPC_S_OK) {
742     WARN("receive failed with error %lx\n", status);
743     goto fail;
744   }
745
746   status = RPC_S_PROTOCOL_ERROR;
747
748   switch (hdr->common.ptype) {
749   case PKT_RESPONSE:
750     if (bind->server) goto fail;
751     break;
752   case PKT_REQUEST:
753     if (!bind->server) goto fail;
754     break;
755   case PKT_FAULT:
756     pMsg->RpcFlags |= WINE_RPCFLAG_EXCEPTION;
757     ERR ("we got fault packet with status %lx\n", hdr->fault.status);
758     status = RPC_S_CALL_FAILED; /* ? */
759     goto fail;
760   default:
761     WARN("bad packet type %d\n", hdr->common.ptype);
762     goto fail;
763   }
764
765   /* success */
766   status = RPC_S_OK;
767
768 fail:
769   if (hdr) {
770     RPCRT4_FreeHeader(hdr);
771   }
772   RPCRT4_CloseBinding(bind, conn);
773   return status;
774 }
775
776 /***********************************************************************
777  *           I_RpcSendReceive [RPCRT4.@]
778  */
779 RPC_STATUS WINAPI I_RpcSendReceive(PRPC_MESSAGE pMsg)
780 {
781   RPC_STATUS status;
782
783   TRACE("(%p)\n", pMsg);
784   status = I_RpcSend(pMsg);
785   if (status == RPC_S_OK)
786     status = I_RpcReceive(pMsg);
787   return status;
788 }