advapi32/tests: Make sure NT4 and W2K tests don't fail.
[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 #define ROUND_UP(value, alignment) (((value) + ((alignment) - 1)) & ~((alignment)-1))
53
54 enum secure_packet_direction
55 {
56   SECURE_PACKET_SEND,
57   SECURE_PACKET_RECEIVE
58 };
59
60 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg);
61
62 static DWORD RPCRT4_GetHeaderSize(const RpcPktHdr *Header)
63 {
64   static const DWORD header_sizes[] = {
65     sizeof(Header->request), 0, sizeof(Header->response),
66     sizeof(Header->fault), 0, 0, 0, 0, 0, 0, 0, sizeof(Header->bind),
67     sizeof(Header->bind_ack), sizeof(Header->bind_nack),
68     0, 0, 0, 0, 0
69   };
70   ULONG ret = 0;
71   
72   if (Header->common.ptype < sizeof(header_sizes) / sizeof(header_sizes[0])) {
73     ret = header_sizes[Header->common.ptype];
74     if (ret == 0)
75       FIXME("unhandled packet type\n");
76     if (Header->common.flags & RPC_FLG_OBJECT_UUID)
77       ret += sizeof(UUID);
78   } else {
79     TRACE("invalid packet type\n");
80   }
81
82   return ret;
83 }
84
85 static int packet_has_body(const RpcPktHdr *Header)
86 {
87     return (Header->common.ptype == PKT_FAULT) ||
88            (Header->common.ptype == PKT_REQUEST) ||
89            (Header->common.ptype == PKT_RESPONSE);
90 }
91
92 static int packet_has_auth_verifier(const RpcPktHdr *Header)
93 {
94     return !(Header->common.ptype == PKT_BIND_NACK) &&
95            !(Header->common.ptype == PKT_SHUTDOWN);
96 }
97
98 static VOID RPCRT4_BuildCommonHeader(RpcPktHdr *Header, unsigned char PacketType,
99                               unsigned long DataRepresentation)
100 {
101   Header->common.rpc_ver = RPC_VER_MAJOR;
102   Header->common.rpc_ver_minor = RPC_VER_MINOR;
103   Header->common.ptype = PacketType;
104   Header->common.drep[0] = LOBYTE(LOWORD(DataRepresentation));
105   Header->common.drep[1] = HIBYTE(LOWORD(DataRepresentation));
106   Header->common.drep[2] = LOBYTE(HIWORD(DataRepresentation));
107   Header->common.drep[3] = HIBYTE(HIWORD(DataRepresentation));
108   Header->common.auth_len = 0;
109   Header->common.call_id = 1;
110   Header->common.flags = 0;
111   /* Flags and fragment length are computed in RPCRT4_Send. */
112 }                              
113
114 static RpcPktHdr *RPCRT4_BuildRequestHeader(unsigned long DataRepresentation,
115                                      unsigned long BufferLength,
116                                      unsigned short ProcNum,
117                                      UUID *ObjectUuid)
118 {
119   RpcPktHdr *header;
120   BOOL has_object;
121   RPC_STATUS status;
122
123   has_object = (ObjectUuid != NULL && !UuidIsNil(ObjectUuid, &status));
124   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
125                      sizeof(header->request) + (has_object ? sizeof(UUID) : 0));
126   if (header == NULL) {
127     return NULL;
128   }
129
130   RPCRT4_BuildCommonHeader(header, PKT_REQUEST, DataRepresentation);
131   header->common.frag_len = sizeof(header->request);
132   header->request.alloc_hint = BufferLength;
133   header->request.context_id = 0;
134   header->request.opnum = ProcNum;
135   if (has_object) {
136     header->common.flags |= RPC_FLG_OBJECT_UUID;
137     header->common.frag_len += sizeof(UUID);
138     memcpy(&header->request + 1, ObjectUuid, sizeof(UUID));
139   }
140
141   return header;
142 }
143
144 static RpcPktHdr *RPCRT4_BuildResponseHeader(unsigned long DataRepresentation,
145                                       unsigned long BufferLength)
146 {
147   RpcPktHdr *header;
148
149   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->response));
150   if (header == NULL) {
151     return NULL;
152   }
153
154   RPCRT4_BuildCommonHeader(header, PKT_RESPONSE, DataRepresentation);
155   header->common.frag_len = sizeof(header->response);
156   header->response.alloc_hint = BufferLength;
157
158   return header;
159 }
160
161 RpcPktHdr *RPCRT4_BuildFaultHeader(unsigned long DataRepresentation,
162                                    RPC_STATUS Status)
163 {
164   RpcPktHdr *header;
165
166   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->fault));
167   if (header == NULL) {
168     return NULL;
169   }
170
171   RPCRT4_BuildCommonHeader(header, PKT_FAULT, DataRepresentation);
172   header->common.frag_len = sizeof(header->fault);
173   header->fault.status = Status;
174
175   return header;
176 }
177
178 RpcPktHdr *RPCRT4_BuildBindHeader(unsigned long DataRepresentation,
179                                   unsigned short MaxTransmissionSize,
180                                   unsigned short MaxReceiveSize,
181                                   RPC_SYNTAX_IDENTIFIER *AbstractId,
182                                   RPC_SYNTAX_IDENTIFIER *TransferId)
183 {
184   RpcPktHdr *header;
185
186   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind));
187   if (header == NULL) {
188     return NULL;
189   }
190
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.num_elements = 1;
196   header->bind.num_syntaxes = 1;
197   memcpy(&header->bind.abstract, AbstractId, sizeof(RPC_SYNTAX_IDENTIFIER));
198   memcpy(&header->bind.transfer, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
199
200   return header;
201 }
202
203 static RpcPktHdr *RPCRT4_BuildAuthHeader(unsigned long DataRepresentation)
204 {
205   RpcPktHdr *header;
206
207   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
208                      sizeof(header->common) + 12);
209   if (header == NULL)
210     return NULL;
211
212   RPCRT4_BuildCommonHeader(header, PKT_AUTH3, DataRepresentation);
213   header->common.frag_len = 0x14;
214   header->common.auth_len = 0;
215
216   return header;
217 }
218
219 RpcPktHdr *RPCRT4_BuildBindNackHeader(unsigned long DataRepresentation,
220                                       unsigned char RpcVersion,
221                                       unsigned char RpcVersionMinor)
222 {
223   RpcPktHdr *header;
224
225   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind_nack));
226   if (header == NULL) {
227     return NULL;
228   }
229
230   RPCRT4_BuildCommonHeader(header, PKT_BIND_NACK, DataRepresentation);
231   header->common.frag_len = sizeof(header->bind_nack);
232   header->bind_nack.protocols_count = 1;
233   header->bind_nack.protocols[0].rpc_ver = RpcVersion;
234   header->bind_nack.protocols[0].rpc_ver_minor = RpcVersionMinor;
235
236   return header;
237 }
238
239 RpcPktHdr *RPCRT4_BuildBindAckHeader(unsigned long DataRepresentation,
240                                      unsigned short MaxTransmissionSize,
241                                      unsigned short MaxReceiveSize,
242                                      LPSTR ServerAddress,
243                                      unsigned long Result,
244                                      unsigned long Reason,
245                                      RPC_SYNTAX_IDENTIFIER *TransferId)
246 {
247   RpcPktHdr *header;
248   unsigned long header_size;
249   RpcAddressString *server_address;
250   RpcResults *results;
251   RPC_SYNTAX_IDENTIFIER *transfer_id;
252
253   header_size = sizeof(header->bind_ack) +
254                 ROUND_UP(FIELD_OFFSET(RpcAddressString, string[strlen(ServerAddress) + 1]), 4) +
255                 sizeof(RpcResults) +
256                 sizeof(RPC_SYNTAX_IDENTIFIER);
257
258   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, header_size);
259   if (header == NULL) {
260     return NULL;
261   }
262
263   RPCRT4_BuildCommonHeader(header, PKT_BIND_ACK, DataRepresentation);
264   header->common.frag_len = header_size;
265   header->bind_ack.max_tsize = MaxTransmissionSize;
266   header->bind_ack.max_rsize = MaxReceiveSize;
267   server_address = (RpcAddressString*)(&header->bind_ack + 1);
268   server_address->length = strlen(ServerAddress) + 1;
269   strcpy(server_address->string, ServerAddress);
270   /* results is 4-byte aligned */
271   results = (RpcResults*)((ULONG_PTR)server_address + ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4));
272   results->num_results = 1;
273   results->results[0].result = Result;
274   results->results[0].reason = Reason;
275   transfer_id = (RPC_SYNTAX_IDENTIFIER*)(results + 1);
276   memcpy(transfer_id, TransferId, sizeof(RPC_SYNTAX_IDENTIFIER));
277
278   return header;
279 }
280
281 VOID RPCRT4_FreeHeader(RpcPktHdr *Header)
282 {
283   HeapFree(GetProcessHeap(), 0, Header);
284 }
285
286 static RPC_STATUS RPCRT4_SecurePacket(RpcConnection *Connection,
287     enum secure_packet_direction dir,
288     RpcPktHdr *hdr, unsigned int hdr_size,
289     unsigned char *stub_data, unsigned int stub_data_size,
290     RpcAuthVerifier *auth_hdr,
291     unsigned char *auth_value, unsigned int auth_value_size)
292 {
293     SecBufferDesc message;
294     SecBuffer buffers[4];
295     SECURITY_STATUS sec_status;
296
297     message.ulVersion = SECBUFFER_VERSION;
298     message.cBuffers = sizeof(buffers)/sizeof(buffers[0]);
299     message.pBuffers = buffers;
300
301     buffers[0].cbBuffer = hdr_size;
302     buffers[0].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
303     buffers[0].pvBuffer = hdr;
304     buffers[1].cbBuffer = stub_data_size;
305     buffers[1].BufferType = SECBUFFER_DATA;
306     buffers[1].pvBuffer = stub_data;
307     buffers[2].cbBuffer = sizeof(*auth_hdr);
308     buffers[2].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
309     buffers[2].pvBuffer = auth_hdr;
310     buffers[3].cbBuffer = auth_value_size;
311     buffers[3].BufferType = SECBUFFER_TOKEN;
312     buffers[3].pvBuffer = auth_value;
313
314     if (dir == SECURE_PACKET_SEND)
315     {
316         if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
317         {
318             sec_status = EncryptMessage(&Connection->ctx, 0, &message, 0 /* FIXME */);
319             if (sec_status != SEC_E_OK)
320             {
321                 ERR("EncryptMessage failed with 0x%08x\n", sec_status);
322                 return RPC_S_SEC_PKG_ERROR;
323             }
324         }
325         else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
326         {
327             sec_status = MakeSignature(&Connection->ctx, 0, &message, 0 /* FIXME */);
328             if (sec_status != SEC_E_OK)
329             {
330                 ERR("MakeSignature failed with 0x%08x\n", sec_status);
331                 return RPC_S_SEC_PKG_ERROR;
332             }
333         }
334     }
335     else if (dir == SECURE_PACKET_RECEIVE)
336     {
337         if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
338         {
339             sec_status = DecryptMessage(&Connection->ctx, &message, 0 /* FIXME */, 0);
340             if (sec_status != SEC_E_OK)
341             {
342                 ERR("EncryptMessage failed with 0x%08x\n", sec_status);
343                 return RPC_S_SEC_PKG_ERROR;
344             }
345         }
346         else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
347         {
348             sec_status = VerifySignature(&Connection->ctx, &message, 0 /* FIXME */, NULL);
349             if (sec_status != SEC_E_OK)
350             {
351                 ERR("VerifySignature failed with 0x%08x\n", sec_status);
352                 return RPC_S_SEC_PKG_ERROR;
353             }
354         }
355     }
356
357     return RPC_S_OK;
358 }
359          
360 /***********************************************************************
361  *           RPCRT4_SendAuth (internal)
362  * 
363  * Transmit a packet with authorization data over connection in acceptable fragments.
364  */
365 static RPC_STATUS RPCRT4_SendAuth(RpcConnection *Connection, RpcPktHdr *Header,
366                                   void *Buffer, unsigned int BufferLength,
367                                   void *Auth, unsigned int AuthLength)
368 {
369   PUCHAR buffer_pos;
370   DWORD hdr_size;
371   LONG count;
372   unsigned char *pkt;
373   LONG alen;
374   RPC_STATUS status;
375
376   buffer_pos = Buffer;
377   /* The packet building functions save the packet header size, so we can use it. */
378   hdr_size = Header->common.frag_len;
379   if (AuthLength)
380     Header->common.auth_len = AuthLength;
381   else if (Connection->AuthInfo && packet_has_auth_verifier(Header))
382   {
383     if ((Connection->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(Header))
384       Header->common.auth_len = Connection->encryption_auth_len;
385     else
386       Header->common.auth_len = Connection->signature_auth_len;
387   }
388   else
389     Header->common.auth_len = 0;
390   Header->common.flags |= RPC_FLG_FIRST;
391   Header->common.flags &= ~RPC_FLG_LAST;
392
393   alen = RPC_AUTH_VERIFIER_LEN(&Header->common);
394
395   while (!(Header->common.flags & RPC_FLG_LAST)) {
396     unsigned char auth_pad_len = Header->common.auth_len ? ROUND_UP_AMOUNT(BufferLength, AUTH_ALIGNMENT) : 0;
397     unsigned int pkt_size = BufferLength + hdr_size + alen + auth_pad_len;
398
399     /* decide if we need to split the packet into fragments */
400    if (pkt_size <= Connection->MaxTransmissionSize) {
401      Header->common.flags |= RPC_FLG_LAST;
402      Header->common.frag_len = pkt_size;
403     } else {
404       auth_pad_len = 0;
405       /* make sure packet payload will be a multiple of 16 */
406       Header->common.frag_len =
407         ((Connection->MaxTransmissionSize - hdr_size - alen) & ~(AUTH_ALIGNMENT-1)) +
408         hdr_size + alen;
409     }
410
411     pkt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Header->common.frag_len);
412
413     memcpy(pkt, Header, hdr_size);
414
415     /* fragment consisted of header only and is the last one */
416     if (hdr_size == Header->common.frag_len)
417       goto write;
418
419     memcpy(pkt + hdr_size, buffer_pos, Header->common.frag_len - hdr_size - auth_pad_len - alen);
420
421     /* add the authorization info */
422     if (Connection->AuthInfo && packet_has_auth_verifier(Header))
423     {
424       RpcAuthVerifier *auth_hdr = (RpcAuthVerifier *)&pkt[Header->common.frag_len - alen];
425
426       auth_hdr->auth_type = Connection->AuthInfo->AuthnSvc;
427       auth_hdr->auth_level = Connection->AuthInfo->AuthnLevel;
428       auth_hdr->auth_pad_length = auth_pad_len;
429       auth_hdr->auth_reserved = 0;
430       /* a unique number... */
431       auth_hdr->auth_context_id = (unsigned long)Connection;
432
433       if (AuthLength)
434         memcpy(auth_hdr + 1, Auth, AuthLength);
435       else
436       {
437         status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_SEND,
438             (RpcPktHdr *)pkt, hdr_size,
439             pkt + hdr_size, Header->common.frag_len - hdr_size - alen,
440             auth_hdr,
441             (unsigned char *)(auth_hdr + 1), Header->common.auth_len);
442         if (status != RPC_S_OK)
443         {
444           HeapFree(GetProcessHeap(), 0, pkt);
445           return status;
446         }
447       }
448     }
449
450 write:
451     count = rpcrt4_conn_write(Connection, pkt, Header->common.frag_len);
452     HeapFree(GetProcessHeap(), 0, pkt);
453     if (count<0) {
454       WARN("rpcrt4_conn_write failed (auth)\n");
455       return RPC_S_PROTOCOL_ERROR;
456     }
457
458     buffer_pos += Header->common.frag_len - hdr_size - alen - auth_pad_len;
459     BufferLength -= Header->common.frag_len - hdr_size - alen - auth_pad_len;
460     Header->common.flags &= ~RPC_FLG_FIRST;
461   }
462
463   return RPC_S_OK;
464 }
465
466 /***********************************************************************
467  *           RPCRT4_ClientAuthorize (internal)
468  *
469  * Authorize a client connection. A NULL in param signifies a new connection.
470  */
471 static RPC_STATUS RPCRT4_ClientAuthorize(RpcConnection *conn, SecBuffer *in,
472                                          SecBuffer *out)
473 {
474   SECURITY_STATUS r;
475   SecBufferDesc out_desc;
476   SecBufferDesc inp_desc;
477   SecPkgContext_Sizes secctx_sizes;
478   BOOL continue_needed;
479   ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
480                       ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
481
482   if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
483     context_req |= ISC_REQ_INTEGRITY;
484   else if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY)
485     context_req |= ISC_REQ_CONFIDENTIALITY | ISC_REQ_INTEGRITY;
486
487   out->BufferType = SECBUFFER_TOKEN;
488   out->cbBuffer = conn->AuthInfo->cbMaxToken;
489   out->pvBuffer = HeapAlloc(GetProcessHeap(), 0, out->cbBuffer);
490   if (!out->pvBuffer) return ERROR_OUTOFMEMORY;
491
492   out_desc.ulVersion = 0;
493   out_desc.cBuffers = 1;
494   out_desc.pBuffers = out;
495
496   inp_desc.cBuffers = 1;
497   inp_desc.pBuffers = in;
498   inp_desc.ulVersion = 0;
499
500   r = InitializeSecurityContextA(&conn->AuthInfo->cred, in ? &conn->ctx : NULL,
501         NULL, context_req, 0, SECURITY_NETWORK_DREP,
502         in ? &inp_desc : NULL, 0, &conn->ctx, &out_desc, &conn->attr,
503         &conn->exp);
504   if (FAILED(r))
505   {
506       WARN("InitializeSecurityContext failed with error 0x%08x\n", r);
507       goto failed;
508   }
509
510   TRACE("r = 0x%08x, attr = 0x%08x\n", r, conn->attr);
511   continue_needed = ((r == SEC_I_CONTINUE_NEEDED) ||
512                      (r == SEC_I_COMPLETE_AND_CONTINUE));
513
514   if ((r == SEC_I_COMPLETE_NEEDED) || (r == SEC_I_COMPLETE_AND_CONTINUE))
515   {
516       TRACE("complete needed\n");
517       r = CompleteAuthToken(&conn->ctx, &out_desc);
518       if (FAILED(r))
519       {
520           WARN("CompleteAuthToken failed with error 0x%08x\n", r);
521           goto failed;
522       }
523   }
524
525   TRACE("cbBuffer = %ld\n", out->cbBuffer);
526
527   if (!continue_needed)
528   {
529       r = QueryContextAttributesA(&conn->ctx, SECPKG_ATTR_SIZES, &secctx_sizes);
530       if (FAILED(r))
531       {
532           WARN("QueryContextAttributes failed with error 0x%08x\n", r);
533           goto failed;
534       }
535       conn->signature_auth_len = secctx_sizes.cbMaxSignature;
536       conn->encryption_auth_len = secctx_sizes.cbSecurityTrailer;
537   }
538
539   return RPC_S_OK;
540
541 failed:
542   HeapFree(GetProcessHeap(), 0, out->pvBuffer);
543   out->pvBuffer = NULL;
544   return ERROR_ACCESS_DENIED; /* FIXME: is this correct? */
545 }
546
547 /***********************************************************************
548  *           RPCRT4_AuthorizeBinding (internal)
549  */
550 static RPC_STATUS RPCRT_AuthorizeConnection(RpcConnection* conn,
551                                             BYTE *challenge, ULONG count)
552 {
553   SecBuffer inp, out;
554   RpcPktHdr *resp_hdr;
555   RPC_STATUS status;
556
557   TRACE("challenge %s, %d bytes\n", challenge, count);
558
559   inp.BufferType = SECBUFFER_TOKEN;
560   inp.pvBuffer = challenge;
561   inp.cbBuffer = count;
562
563   status = RPCRT4_ClientAuthorize(conn, &inp, &out);
564   if (status) return status;
565
566   resp_hdr = RPCRT4_BuildAuthHeader(NDR_LOCAL_DATA_REPRESENTATION);
567   if (!resp_hdr)
568     return E_OUTOFMEMORY;
569
570   status = RPCRT4_SendAuth(conn, resp_hdr, NULL, 0, out.pvBuffer, out.cbBuffer);
571
572   HeapFree(GetProcessHeap(), 0, out.pvBuffer);
573   RPCRT4_FreeHeader(resp_hdr);
574
575   return status;
576 }
577
578 /***********************************************************************
579  *           RPCRT4_Send (internal)
580  * 
581  * Transmit a packet over connection in acceptable fragments.
582  */
583 RPC_STATUS RPCRT4_Send(RpcConnection *Connection, RpcPktHdr *Header,
584                        void *Buffer, unsigned int BufferLength)
585 {
586   RPC_STATUS r;
587   SecBuffer out;
588
589   if (!Connection->AuthInfo || SecIsValidHandle(&Connection->ctx))
590   {
591     return RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, NULL, 0);
592   }
593
594   /* tack on a negotiate packet */
595   RPCRT4_ClientAuthorize(Connection, NULL, &out);
596   r = RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, out.pvBuffer, out.cbBuffer);
597   HeapFree(GetProcessHeap(), 0, out.pvBuffer);
598
599   return r;
600 }
601
602 /***********************************************************************
603  *           RPCRT4_Receive (internal)
604  * 
605  * Receive a packet from connection and merge the fragments.
606  */
607 RPC_STATUS RPCRT4_Receive(RpcConnection *Connection, RpcPktHdr **Header,
608                           PRPC_MESSAGE pMsg)
609 {
610   RPC_STATUS status;
611   DWORD hdr_length;
612   LONG dwRead;
613   unsigned short first_flag;
614   unsigned long data_length;
615   unsigned long buffer_length;
616   unsigned long auth_length;
617   unsigned char *auth_data = NULL;
618   RpcPktCommonHdr common_hdr;
619
620   *Header = NULL;
621
622   TRACE("(%p, %p, %p)\n", Connection, Header, pMsg);
623
624   /* read packet common header */
625   dwRead = rpcrt4_conn_read(Connection, &common_hdr, sizeof(common_hdr));
626   if (dwRead != sizeof(common_hdr)) {
627     WARN("Short read of header, %d bytes\n", dwRead);
628     status = RPC_S_PROTOCOL_ERROR;
629     goto fail;
630   }
631
632   /* verify if the header really makes sense */
633   if (common_hdr.rpc_ver != RPC_VER_MAJOR ||
634       common_hdr.rpc_ver_minor != RPC_VER_MINOR) {
635     WARN("unhandled packet version\n");
636     status = RPC_S_PROTOCOL_ERROR;
637     goto fail;
638   }
639
640   hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
641   if (hdr_length == 0) {
642     WARN("header length == 0\n");
643     status = RPC_S_PROTOCOL_ERROR;
644     goto fail;
645   }
646
647   *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
648   memcpy(*Header, &common_hdr, sizeof(common_hdr));
649
650   /* read the rest of packet header */
651   dwRead = rpcrt4_conn_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
652   if (dwRead != hdr_length - sizeof(common_hdr)) {
653     WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
654     status = RPC_S_PROTOCOL_ERROR;
655     goto fail;
656   }
657
658   /* read packet body */
659   switch (common_hdr.ptype) {
660   case PKT_RESPONSE:
661     pMsg->BufferLength = (*Header)->response.alloc_hint;
662     break;
663   case PKT_REQUEST:
664     pMsg->BufferLength = (*Header)->request.alloc_hint;
665     break;
666   default:
667     pMsg->BufferLength = common_hdr.frag_len - hdr_length - RPC_AUTH_VERIFIER_LEN(&common_hdr);
668   }
669
670   TRACE("buffer length = %u\n", pMsg->BufferLength);
671
672   status = I_RpcGetBuffer(pMsg);
673   if (status != RPC_S_OK) goto fail;
674
675   first_flag = RPC_FLG_FIRST;
676   auth_length = common_hdr.auth_len;
677   if (auth_length) {
678     auth_data = HeapAlloc(GetProcessHeap(), 0, RPC_AUTH_VERIFIER_LEN(&common_hdr));
679     if (!auth_data) {
680       status = RPC_S_PROTOCOL_ERROR;
681       goto fail;
682     }
683   }
684   buffer_length = 0;
685   while (TRUE)
686   {
687     unsigned int header_auth_len = RPC_AUTH_VERIFIER_LEN(&(*Header)->common);
688
689     /* verify header fields */
690
691     if (((*Header)->common.frag_len < hdr_length) ||
692         ((*Header)->common.frag_len - hdr_length < header_auth_len)) {
693       WARN("frag_len %d too small for hdr_length %d and auth_len %d\n",
694         common_hdr.frag_len, hdr_length, common_hdr.auth_len);
695       status = RPC_S_PROTOCOL_ERROR;
696       goto fail;
697     }
698
699     if ((*Header)->common.auth_len != auth_length) {
700       WARN("auth_len header field changed from %ld to %d\n",
701         auth_length, (*Header)->common.auth_len);
702       status = RPC_S_PROTOCOL_ERROR;
703       goto fail;
704     }
705
706     if (((*Header)->common.flags & RPC_FLG_FIRST) != first_flag) {
707       TRACE("invalid packet flags\n");
708       status = RPC_S_PROTOCOL_ERROR;
709       goto fail;
710     }
711
712     data_length = (*Header)->common.frag_len - hdr_length - header_auth_len;
713     if (data_length + buffer_length > pMsg->BufferLength) {
714       TRACE("allocation hint exceeded, new buffer length = %ld\n",
715         data_length + buffer_length);
716       pMsg->BufferLength = data_length + buffer_length;
717       status = I_RpcReAllocateBuffer(pMsg);
718       if (status != RPC_S_OK) goto fail;
719     }
720
721     if (data_length == 0) dwRead = 0; else
722     dwRead = rpcrt4_conn_read(Connection,
723         (unsigned char *)pMsg->Buffer + buffer_length, data_length);
724     if (dwRead != data_length) {
725       WARN("bad data length, %d/%ld\n", dwRead, data_length);
726       status = RPC_S_PROTOCOL_ERROR;
727       goto fail;
728     }
729
730     if (header_auth_len) {
731       if (header_auth_len < sizeof(RpcAuthVerifier)) {
732         WARN("bad auth verifier length %d\n", header_auth_len);
733         status = RPC_S_PROTOCOL_ERROR;
734         goto fail;
735       }
736
737       /* FIXME: we should accumulate authentication data for the bind,
738        * bind_ack, alter_context and alter_context_response if necessary.
739        * however, the details of how this is done is very sketchy in the
740        * DCE/RPC spec. for all other packet types that have authentication
741        * verifier data then it is just duplicated in all the fragments */
742       dwRead = rpcrt4_conn_read(Connection, auth_data, header_auth_len);
743       if (dwRead != header_auth_len) {
744         WARN("bad authentication data length, %d/%d\n", dwRead,
745           header_auth_len);
746         status = RPC_S_PROTOCOL_ERROR;
747         goto fail;
748       }
749
750       /* these packets are handled specially, not by the generic SecurePacket
751        * function */
752       if ((common_hdr.ptype != PKT_BIND) &&
753           (common_hdr.ptype != PKT_BIND_ACK) &&
754           (common_hdr.ptype != PKT_AUTH3))
755         status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_RECEIVE,
756             *Header, hdr_length,
757             (unsigned char *)pMsg->Buffer + buffer_length, data_length,
758             (RpcAuthVerifier *)auth_data,
759             (unsigned char *)auth_data + sizeof(RpcAuthVerifier),
760             header_auth_len - sizeof(RpcAuthVerifier));
761     }
762
763     buffer_length += data_length;
764     if (!((*Header)->common.flags & RPC_FLG_LAST)) {
765       TRACE("next header\n");
766
767       /* read the header of next packet */
768       dwRead = rpcrt4_conn_read(Connection, *Header, hdr_length);
769       if (dwRead != hdr_length) {
770         WARN("invalid packet header size (%d)\n", dwRead);
771         status = RPC_S_PROTOCOL_ERROR;
772         goto fail;
773       }
774
775       first_flag = 0;
776     } else {
777       break;
778     }
779   }
780   pMsg->BufferLength = buffer_length;
781
782   /* respond to authorization request */
783   if (common_hdr.ptype == PKT_BIND_ACK && auth_length > sizeof(RpcAuthVerifier))
784   {
785     status = RPCRT_AuthorizeConnection(Connection,
786                                        auth_data + sizeof(RpcAuthVerifier),
787                                        auth_length);
788     if (status)
789         goto fail;
790   }
791
792   /* success */
793   status = RPC_S_OK;
794
795 fail:
796   if (status != RPC_S_OK) {
797     RPCRT4_FreeHeader(*Header);
798     *Header = NULL;
799   }
800   HeapFree(GetProcessHeap(), 0, auth_data);
801   return status;
802 }
803
804 /***********************************************************************
805  *           I_RpcGetBuffer [RPCRT4.@]
806  *
807  * Allocates a buffer for use by I_RpcSend or I_RpcSendReceive and binds to the
808  * server interface.
809  *
810  * PARAMS
811  *  pMsg [I/O] RPC message information.
812  *
813  * RETURNS
814  *  Success: RPC_S_OK.
815  *  Failure: RPC_S_INVALID_BINDING if pMsg->Handle is invalid.
816  *           RPC_S_SERVER_UNAVAILABLE if unable to connect to server.
817  *           ERROR_OUTOFMEMORY if buffer allocation failed.
818  *
819  * NOTES
820  *  The pMsg->BufferLength field determines the size of the buffer to allocate,
821  *  in bytes.
822  *
823  *  Use I_RpcFreeBuffer() to unbind from the server and free the message buffer.
824  *
825  * SEE ALSO
826  *  I_RpcFreeBuffer(), I_RpcSend(), I_RpcReceive(), I_RpcSendReceive().
827  */
828 RPC_STATUS WINAPI I_RpcGetBuffer(PRPC_MESSAGE pMsg)
829 {
830   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
831   /* FIXME: pfnAllocate? */
832   pMsg->Buffer = HeapAlloc(GetProcessHeap(), 0, pMsg->BufferLength);
833
834   TRACE("Buffer=%p\n", pMsg->Buffer);
835   /* FIXME: which errors to return? */
836   return pMsg->Buffer ? S_OK : E_OUTOFMEMORY;
837 }
838
839 /***********************************************************************
840  *           I_RpcReAllocateBuffer (internal)
841  */
842 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg)
843 {
844   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
845   pMsg->Buffer = HeapReAlloc(GetProcessHeap(), 0, pMsg->Buffer, pMsg->BufferLength);
846
847   TRACE("Buffer=%p\n", pMsg->Buffer);
848   return pMsg->Buffer ? RPC_S_OK : RPC_S_OUT_OF_RESOURCES;
849 }
850
851 /***********************************************************************
852  *           I_RpcFreeBuffer [RPCRT4.@]
853  *
854  * Frees a buffer allocated by I_RpcGetBuffer or I_RpcReceive and unbinds from
855  * the server interface.
856  *
857  * PARAMS
858  *  pMsg [I/O] RPC message information.
859  *
860  * RETURNS
861  *  RPC_S_OK.
862  *
863  * SEE ALSO
864  *  I_RpcGetBuffer(), I_RpcReceive().
865  */
866 RPC_STATUS WINAPI I_RpcFreeBuffer(PRPC_MESSAGE pMsg)
867 {
868   TRACE("(%p) Buffer=%p\n", pMsg, pMsg->Buffer);
869   /* FIXME: pfnFree? */
870   HeapFree(GetProcessHeap(), 0, pMsg->Buffer);
871   pMsg->Buffer = NULL;
872   return S_OK;
873 }
874
875 /***********************************************************************
876  *           I_RpcSend [RPCRT4.@]
877  *
878  * Sends a message to the server.
879  *
880  * PARAMS
881  *  pMsg [I/O] RPC message information.
882  *
883  * RETURNS
884  *  Unknown.
885  *
886  * NOTES
887  *  The buffer must have been allocated with I_RpcGetBuffer().
888  *
889  * SEE ALSO
890  *  I_RpcGetBuffer(), I_RpcReceive(), I_RpcSendReceive().
891  */
892 RPC_STATUS WINAPI I_RpcSend(PRPC_MESSAGE pMsg)
893 {
894   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
895   RpcConnection* conn;
896   RPC_CLIENT_INTERFACE* cif = NULL;
897   RPC_SERVER_INTERFACE* sif = NULL;
898   RPC_STATUS status;
899   RpcPktHdr *hdr;
900
901   TRACE("(%p)\n", pMsg);
902   if (!bind) return RPC_S_INVALID_BINDING;
903
904   if (bind->server) {
905     sif = pMsg->RpcInterfaceInformation;
906     if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
907     status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
908                                 &sif->InterfaceId);
909   } else {
910     cif = pMsg->RpcInterfaceInformation;
911     if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
912
913     if (!bind->Endpoint || !bind->Endpoint[0])
914     {
915       TRACE("automatically resolving partially bound binding\n");
916       status = RpcEpResolveBinding(bind, cif);
917       if (status != RPC_S_OK) return status;
918     }
919
920     status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
921                                 &cif->InterfaceId);
922   }
923
924   if (status != RPC_S_OK) return status;
925
926   if (bind->server) {
927     if (pMsg->RpcFlags & WINE_RPCFLAG_EXCEPTION) {
928       hdr = RPCRT4_BuildFaultHeader(pMsg->DataRepresentation,
929                                     RPC_S_CALL_FAILED);
930     } else {
931       hdr = RPCRT4_BuildResponseHeader(pMsg->DataRepresentation,
932                                        pMsg->BufferLength);
933     }
934   } else {
935     hdr = RPCRT4_BuildRequestHeader(pMsg->DataRepresentation,
936                                     pMsg->BufferLength, pMsg->ProcNum,
937                                     &bind->ObjectUuid);
938     hdr->common.call_id = conn->NextCallId++;
939   }
940
941   status = RPCRT4_Send(conn, hdr, pMsg->Buffer, pMsg->BufferLength);
942
943   RPCRT4_FreeHeader(hdr);
944
945   /* success */
946   if (!bind->server) {
947     /* save the connection, so the response can be read from it */
948     pMsg->ReservedForRuntime = conn;
949     return status;
950   }
951   RPCRT4_CloseBinding(bind, conn);
952
953   return status;
954 }
955
956 /***********************************************************************
957  *           I_RpcReceive [RPCRT4.@]
958  */
959 RPC_STATUS WINAPI I_RpcReceive(PRPC_MESSAGE pMsg)
960 {
961   RpcBinding* bind = (RpcBinding*)pMsg->Handle;
962   RpcConnection* conn;
963   RPC_CLIENT_INTERFACE* cif = NULL;
964   RPC_SERVER_INTERFACE* sif = NULL;
965   RPC_STATUS status;
966   RpcPktHdr *hdr = NULL;
967
968   TRACE("(%p)\n", pMsg);
969   if (!bind) return RPC_S_INVALID_BINDING;
970
971   if (pMsg->ReservedForRuntime) {
972     conn = pMsg->ReservedForRuntime;
973     pMsg->ReservedForRuntime = NULL;
974   } else {
975     if (bind->server) {
976       sif = pMsg->RpcInterfaceInformation;
977       if (!sif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
978       status = RPCRT4_OpenBinding(bind, &conn, &sif->TransferSyntax,
979                                   &sif->InterfaceId);
980     } else {
981       cif = pMsg->RpcInterfaceInformation;
982       if (!cif) return RPC_S_INTERFACE_NOT_FOUND; /* ? */
983
984       if (!bind->Endpoint || !bind->Endpoint[0])
985       {
986         TRACE("automatically resolving partially bound binding\n");
987         status = RpcEpResolveBinding(bind, cif);
988         if (status != RPC_S_OK) return status;
989       }
990
991       status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
992                                   &cif->InterfaceId);
993     }
994     if (status != RPC_S_OK) return status;
995   }
996
997   status = RPCRT4_Receive(conn, &hdr, pMsg);
998   if (status != RPC_S_OK) {
999     WARN("receive failed with error %lx\n", status);
1000     goto fail;
1001   }
1002
1003   status = RPC_S_PROTOCOL_ERROR;
1004
1005   switch (hdr->common.ptype) {
1006   case PKT_RESPONSE:
1007     if (bind->server) goto fail;
1008     break;
1009   case PKT_REQUEST:
1010     if (!bind->server) goto fail;
1011     break;
1012   case PKT_FAULT:
1013     pMsg->RpcFlags |= WINE_RPCFLAG_EXCEPTION;
1014     ERR ("we got fault packet with status 0x%lx\n", hdr->fault.status);
1015     status = hdr->fault.status; /* FIXME: do translation from nca error codes */
1016     goto fail;
1017   default:
1018     WARN("bad packet type %d\n", hdr->common.ptype);
1019     goto fail;
1020   }
1021
1022   /* success */
1023   status = RPC_S_OK;
1024
1025 fail:
1026   RPCRT4_FreeHeader(hdr);
1027   RPCRT4_CloseBinding(bind, conn);
1028   return status;
1029 }
1030
1031 /***********************************************************************
1032  *           I_RpcSendReceive [RPCRT4.@]
1033  *
1034  * Sends a message to the server and receives the response.
1035  *
1036  * PARAMS
1037  *  pMsg [I/O] RPC message information.
1038  *
1039  * RETURNS
1040  *  Success: RPC_S_OK.
1041  *  Failure: Any error code.
1042  *
1043  * NOTES
1044  *  The buffer must have been allocated with I_RpcGetBuffer().
1045  *
1046  * SEE ALSO
1047  *  I_RpcGetBuffer(), I_RpcSend(), I_RpcReceive().
1048  */
1049 RPC_STATUS WINAPI I_RpcSendReceive(PRPC_MESSAGE pMsg)
1050 {
1051   RPC_STATUS status;
1052   RPC_MESSAGE original_message;
1053
1054   TRACE("(%p)\n", pMsg);
1055
1056   original_message = *pMsg;
1057   status = I_RpcSend(pMsg);
1058   if (status == RPC_S_OK)
1059     status = I_RpcReceive(pMsg);
1060   /* free the buffer replaced by a new buffer in I_RpcReceive */
1061   if (status == RPC_S_OK)
1062     I_RpcFreeBuffer(&original_message);
1063   return status;
1064 }