ntoskrnl.exe: Add a stub implementation of KeInitializeTimer.
[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
31 #include "rpc.h"
32 #include "rpcndr.h"
33 #include "rpcdcep.h"
34
35 #include "wine/debug.h"
36
37 #include "rpc_binding.h"
38 #include "rpc_misc.h"
39 #include "rpc_defs.h"
40 #include "rpc_message.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
43
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
47
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))
52
53 enum secure_packet_direction
54 {
55   SECURE_PACKET_SEND,
56   SECURE_PACKET_RECEIVE
57 };
58
59 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg);
60
61 static DWORD RPCRT4_GetHeaderSize(const RpcPktHdr *Header)
62 {
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
68   };
69   ULONG ret = 0;
70   
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");
79   }
80
81   return ret;
82 }
83
84 static int packet_has_body(const RpcPktHdr *Header)
85 {
86     return (Header->common.ptype == PKT_FAULT) ||
87            (Header->common.ptype == PKT_REQUEST) ||
88            (Header->common.ptype == PKT_RESPONSE);
89 }
90
91 static int packet_has_auth_verifier(const RpcPktHdr *Header)
92 {
93     return !(Header->common.ptype == PKT_BIND_NACK) &&
94            !(Header->common.ptype == PKT_SHUTDOWN);
95 }
96
97 static VOID RPCRT4_BuildCommonHeader(RpcPktHdr *Header, unsigned char PacketType,
98                               unsigned long DataRepresentation)
99 {
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. */
111 }                              
112
113 static RpcPktHdr *RPCRT4_BuildRequestHeader(unsigned long DataRepresentation,
114                                      unsigned long BufferLength,
115                                      unsigned short ProcNum,
116                                      UUID *ObjectUuid)
117 {
118   RpcPktHdr *header;
119   BOOL has_object;
120   RPC_STATUS status;
121
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;
127   }
128
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));
138   }
139
140   return header;
141 }
142
143 static RpcPktHdr *RPCRT4_BuildResponseHeader(unsigned long DataRepresentation,
144                                       unsigned long BufferLength)
145 {
146   RpcPktHdr *header;
147
148   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->response));
149   if (header == NULL) {
150     return NULL;
151   }
152
153   RPCRT4_BuildCommonHeader(header, PKT_RESPONSE, DataRepresentation);
154   header->common.frag_len = sizeof(header->response);
155   header->response.alloc_hint = BufferLength;
156
157   return header;
158 }
159
160 RpcPktHdr *RPCRT4_BuildFaultHeader(unsigned long DataRepresentation,
161                                    RPC_STATUS Status)
162 {
163   RpcPktHdr *header;
164
165   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->fault));
166   if (header == NULL) {
167     return NULL;
168   }
169
170   RPCRT4_BuildCommonHeader(header, PKT_FAULT, DataRepresentation);
171   header->common.frag_len = sizeof(header->fault);
172   header->fault.status = Status;
173
174   return header;
175 }
176
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)
182 {
183   RpcPktHdr *header;
184
185   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind));
186   if (header == NULL) {
187     return NULL;
188   }
189
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));
198
199   return header;
200 }
201
202 static RpcPktHdr *RPCRT4_BuildAuthHeader(unsigned long DataRepresentation)
203 {
204   RpcPktHdr *header;
205
206   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
207                      sizeof(header->common) + 12);
208   if (header == NULL)
209     return NULL;
210
211   RPCRT4_BuildCommonHeader(header, PKT_AUTH3, DataRepresentation);
212   header->common.frag_len = 0x14;
213   header->common.auth_len = 0;
214
215   return header;
216 }
217
218 RpcPktHdr *RPCRT4_BuildBindNackHeader(unsigned long DataRepresentation,
219                                       unsigned char RpcVersion,
220                                       unsigned char RpcVersionMinor)
221 {
222   RpcPktHdr *header;
223
224   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind_nack));
225   if (header == NULL) {
226     return NULL;
227   }
228
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;
234
235   return header;
236 }
237
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)
245 {
246   RpcPktHdr *header;
247   unsigned long header_size;
248   RpcAddressString *server_address;
249   RpcResults *results;
250   RPC_SYNTAX_IDENTIFIER *transfer_id;
251
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);
256
257   header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, header_size);
258   if (header == NULL) {
259     return NULL;
260   }
261
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));
276
277   return header;
278 }
279
280 VOID RPCRT4_FreeHeader(RpcPktHdr *Header)
281 {
282   HeapFree(GetProcessHeap(), 0, Header);
283 }
284
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)
291 {
292     SecBufferDesc message;
293     SecBuffer buffers[4];
294     SECURITY_STATUS sec_status;
295
296     message.ulVersion = SECBUFFER_VERSION;
297     message.cBuffers = sizeof(buffers)/sizeof(buffers[0]);
298     message.pBuffers = buffers;
299
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;
312
313     if (dir == SECURE_PACKET_SEND)
314     {
315         if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
316         {
317             sec_status = EncryptMessage(&Connection->ctx, 0, &message, 0 /* FIXME */);
318             if (sec_status != SEC_E_OK)
319             {
320                 ERR("EncryptMessage failed with 0x%08x\n", sec_status);
321                 return RPC_S_SEC_PKG_ERROR;
322             }
323         }
324         else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
325         {
326             sec_status = MakeSignature(&Connection->ctx, 0, &message, 0 /* FIXME */);
327             if (sec_status != SEC_E_OK)
328             {
329                 ERR("MakeSignature failed with 0x%08x\n", sec_status);
330                 return RPC_S_SEC_PKG_ERROR;
331             }
332         }
333     }
334     else if (dir == SECURE_PACKET_RECEIVE)
335     {
336         if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
337         {
338             sec_status = DecryptMessage(&Connection->ctx, &message, 0 /* FIXME */, 0);
339             if (sec_status != SEC_E_OK)
340             {
341                 ERR("EncryptMessage failed with 0x%08x\n", sec_status);
342                 return RPC_S_SEC_PKG_ERROR;
343             }
344         }
345         else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
346         {
347             sec_status = VerifySignature(&Connection->ctx, &message, 0 /* FIXME */, NULL);
348             if (sec_status != SEC_E_OK)
349             {
350                 ERR("VerifySignature failed with 0x%08x\n", sec_status);
351                 return RPC_S_SEC_PKG_ERROR;
352             }
353         }
354     }
355
356     return RPC_S_OK;
357 }
358          
359 /***********************************************************************
360  *           RPCRT4_SendAuth (internal)
361  * 
362  * Transmit a packet with authorization data over connection in acceptable fragments.
363  */
364 static RPC_STATUS RPCRT4_SendAuth(RpcConnection *Connection, RpcPktHdr *Header,
365                                   void *Buffer, unsigned int BufferLength,
366                                   void *Auth, unsigned int AuthLength)
367 {
368   PUCHAR buffer_pos;
369   DWORD hdr_size;
370   LONG count;
371   unsigned char *pkt;
372   LONG alen;
373   RPC_STATUS status;
374
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))
381   {
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;
386   }
387   else
388     Header->common.auth_len = 0;
389   Header->common.flags |= RPC_FLG_FIRST;
390   Header->common.flags &= ~RPC_FLG_LAST;
391
392   alen = RPC_AUTH_VERIFIER_LEN(&Header->common);
393
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;
397
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;
408     }
409
410     pkt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Header->common.frag_len);
411
412     memcpy(pkt, Header, hdr_size);
413
414     /* fragment consisted of header only and is the last one */
415     if (hdr_size == Header->common.frag_len)
416       goto write;
417
418     memcpy(pkt + hdr_size, buffer_pos, Header->common.frag_len - hdr_size - auth_pad_len - alen);
419
420     /* add the authorization info */
421     if (Connection->AuthInfo && packet_has_auth_verifier(Header))
422     {
423       RpcAuthVerifier *auth_hdr = (RpcAuthVerifier *)&pkt[Header->common.frag_len - alen];
424
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;
431
432       if (AuthLength)
433         memcpy(auth_hdr + 1, Auth, AuthLength);
434       else
435       {
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)
442         {
443           HeapFree(GetProcessHeap(), 0, pkt);
444           return status;
445         }
446       }
447     }
448
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;
455     }
456
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;
460   }
461
462   return RPC_S_OK;
463 }
464
465 /***********************************************************************
466  *           RPCRT4_ClientAuthorize (internal)
467  *
468  * Authorize a client connection. A NULL in param signifies a new connection.
469  */
470 static RPC_STATUS RPCRT4_ClientAuthorize(RpcConnection *conn, SecBuffer *in,
471                                          SecBuffer *out)
472 {
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;
480
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;
485
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;
490
491   out_desc.ulVersion = 0;
492   out_desc.cBuffers = 1;
493   out_desc.pBuffers = out;
494
495   inp_desc.cBuffers = 1;
496   inp_desc.pBuffers = in;
497   inp_desc.ulVersion = 0;
498
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))
504   {
505       WARN("InitializeSecurityContext failed with error 0x%08x\n", r);
506       goto failed;
507   }
508
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));
512
513   if ((r == SEC_I_COMPLETE_NEEDED) || (r == SEC_I_COMPLETE_AND_CONTINUE))
514   {
515       TRACE("complete needed\n");
516       r = CompleteAuthToken(&conn->ctx, &out_desc);
517       if (FAILED(r))
518       {
519           WARN("CompleteAuthToken failed with error 0x%08x\n", r);
520           goto failed;
521       }
522   }
523
524   TRACE("cbBuffer = %ld\n", out->cbBuffer);
525
526   if (!continue_needed)
527   {
528       r = QueryContextAttributesA(&conn->ctx, SECPKG_ATTR_SIZES, &secctx_sizes);
529       if (FAILED(r))
530       {
531           WARN("QueryContextAttributes failed with error 0x%08x\n", r);
532           goto failed;
533       }
534       conn->signature_auth_len = secctx_sizes.cbMaxSignature;
535       conn->encryption_auth_len = secctx_sizes.cbSecurityTrailer;
536   }
537
538   return RPC_S_OK;
539
540 failed:
541   HeapFree(GetProcessHeap(), 0, out->pvBuffer);
542   out->pvBuffer = NULL;
543   return ERROR_ACCESS_DENIED; /* FIXME: is this correct? */
544 }
545
546 /***********************************************************************
547  *           RPCRT4_AuthorizeBinding (internal)
548  */
549 static RPC_STATUS RPCRT_AuthorizeConnection(RpcConnection* conn,
550                                             BYTE *challenge, ULONG count)
551 {
552   SecBuffer inp, out;
553   RpcPktHdr *resp_hdr;
554   RPC_STATUS status;
555
556   TRACE("challenge %s, %d bytes\n", challenge, count);
557
558   inp.BufferType = SECBUFFER_TOKEN;
559   inp.pvBuffer = challenge;
560   inp.cbBuffer = count;
561
562   status = RPCRT4_ClientAuthorize(conn, &inp, &out);
563   if (status) return status;
564
565   resp_hdr = RPCRT4_BuildAuthHeader(NDR_LOCAL_DATA_REPRESENTATION);
566   if (!resp_hdr)
567     return E_OUTOFMEMORY;
568
569   status = RPCRT4_SendAuth(conn, resp_hdr, NULL, 0, out.pvBuffer, out.cbBuffer);
570
571   HeapFree(GetProcessHeap(), 0, out.pvBuffer);
572   RPCRT4_FreeHeader(resp_hdr);
573
574   return status;
575 }
576
577 /***********************************************************************
578  *           RPCRT4_Send (internal)
579  * 
580  * Transmit a packet over connection in acceptable fragments.
581  */
582 RPC_STATUS RPCRT4_Send(RpcConnection *Connection, RpcPktHdr *Header,
583                        void *Buffer, unsigned int BufferLength)
584 {
585   RPC_STATUS r;
586   SecBuffer out;
587
588   if (!Connection->AuthInfo || SecIsValidHandle(&Connection->ctx))
589   {
590     return RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, NULL, 0);
591   }
592
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);
597
598   return r;
599 }
600
601 /***********************************************************************
602  *           RPCRT4_Receive (internal)
603  * 
604  * Receive a packet from connection and merge the fragments.
605  */
606 RPC_STATUS RPCRT4_Receive(RpcConnection *Connection, RpcPktHdr **Header,
607                           PRPC_MESSAGE pMsg)
608 {
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;
618
619   *Header = NULL;
620
621   TRACE("(%p, %p, %p)\n", Connection, Header, pMsg);
622
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;
629   }
630
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;
637   }
638
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;
644   }
645
646   *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
647   memcpy(*Header, &common_hdr, sizeof(common_hdr));
648
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;
655   }
656
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);
667   }
668
669   TRACE("buffer length = %u\n", pMsg->BufferLength);
670
671   status = I_RpcGetBuffer(pMsg);
672   if (status != RPC_S_OK) goto fail;
673
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;
681     }
682   }
683   buffer_length = 0;
684   while (TRUE)
685   {
686     unsigned int header_auth_len = RPC_AUTH_VERIFIER_LEN(&(*Header)->common);
687
688     /* verify header fields */
689
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;
696     }
697
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;
703     }
704
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;
709     }
710
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;
718     }
719
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;
727     }
728
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;
734       }
735
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;
747       }
748
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));
760     }
761
762     buffer_length += data_length;
763     if (!((*Header)->common.flags & RPC_FLG_LAST)) {
764       TRACE("next header\n");
765
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;
772       }
773
774       first_flag = 0;
775     } else {
776       break;
777     }
778   }
779   pMsg->BufferLength = buffer_length;
780
781   /* respond to authorization request */
782   if (common_hdr.ptype == PKT_BIND_ACK && auth_length > sizeof(RpcAuthVerifier))
783   {
784     status = RPCRT_AuthorizeConnection(Connection,
785                                        auth_data + sizeof(RpcAuthVerifier),
786                                        auth_length);
787     if (status)
788         goto fail;
789   }
790
791   /* success */
792   status = RPC_S_OK;
793
794 fail:
795   if (status != RPC_S_OK) {
796     RPCRT4_FreeHeader(*Header);
797     *Header = NULL;
798   }
799   HeapFree(GetProcessHeap(), 0, auth_data);
800   return status;
801 }
802
803 /***********************************************************************
804  *           I_RpcGetBuffer [RPCRT4.@]
805  *
806  * Allocates a buffer for use by I_RpcSend or I_RpcSendReceive and binds to the
807  * server interface.
808  *
809  * PARAMS
810  *  pMsg [I/O] RPC message information.
811  *
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.
817  *
818  * NOTES
819  *  The pMsg->BufferLength field determines the size of the buffer to allocate,
820  *  in bytes.
821  *
822  *  Use I_RpcFreeBuffer() to unbind from the server and free the message buffer.
823  *
824  * SEE ALSO
825  *  I_RpcFreeBuffer(), I_RpcSend(), I_RpcReceive(), I_RpcSendReceive().
826  */
827 RPC_STATUS WINAPI I_RpcGetBuffer(PRPC_MESSAGE pMsg)
828 {
829   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
830   /* FIXME: pfnAllocate? */
831   pMsg->Buffer = HeapAlloc(GetProcessHeap(), 0, pMsg->BufferLength);
832
833   TRACE("Buffer=%p\n", pMsg->Buffer);
834   /* FIXME: which errors to return? */
835   return pMsg->Buffer ? S_OK : E_OUTOFMEMORY;
836 }
837
838 /***********************************************************************
839  *           I_RpcReAllocateBuffer (internal)
840  */
841 static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg)
842 {
843   TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
844   pMsg->Buffer = HeapReAlloc(GetProcessHeap(), 0, pMsg->Buffer, pMsg->BufferLength);
845
846   TRACE("Buffer=%p\n", pMsg->Buffer);
847   return pMsg->Buffer ? RPC_S_OK : RPC_S_OUT_OF_RESOURCES;
848 }
849
850 /***********************************************************************
851  *           I_RpcFreeBuffer [RPCRT4.@]
852  *
853  * Frees a buffer allocated by I_RpcGetBuffer or I_RpcReceive and unbinds from
854  * the server interface.
855  *
856  * PARAMS
857  *  pMsg [I/O] RPC message information.
858  *
859  * RETURNS
860  *  RPC_S_OK.
861  *
862  * SEE ALSO
863  *  I_RpcGetBuffer(), I_RpcReceive().
864  */
865 RPC_STATUS WINAPI I_RpcFreeBuffer(PRPC_MESSAGE pMsg)
866 {
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;
872 }
873
874 /***********************************************************************
875  *           I_RpcSend [RPCRT4.@]
876  *
877  * Sends a message to the server.
878  *
879  * PARAMS
880  *  pMsg [I/O] RPC message information.
881  *
882  * RETURNS
883  *  Unknown.
884  *
885  * NOTES
886  *  The buffer must have been allocated with I_RpcGetBuffer().
887  *
888  * SEE ALSO
889  *  I_RpcGetBuffer(), I_RpcReceive(), I_RpcSendReceive().
890  */
891 RPC_STATUS WINAPI I_RpcSend(PRPC_MESSAGE pMsg)
892 {
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;
899
900   TRACE("(%p)\n", pMsg);
901   if (!bind) return RPC_S_INVALID_BINDING;
902
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; /* ? */
911
912     if (!bind->Endpoint || !bind->Endpoint[0])
913     {
914       TRACE("automatically resolving partially bound binding\n");
915       status = RpcEpResolveBinding(bind, cif);
916       if (status != RPC_S_OK) return status;
917     }
918
919     status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
920                                 &cif->InterfaceId);
921   }
922
923   if (status != RPC_S_OK) return status;
924
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);
932     }
933   } else {
934     hdr = RPCRT4_BuildRequestHeader(pMsg->DataRepresentation,
935                                     pMsg->BufferLength, pMsg->ProcNum,
936                                     &bind->ObjectUuid);
937     hdr->common.call_id = conn->NextCallId++;
938   }
939
940   status = RPCRT4_Send(conn, hdr, pMsg->Buffer, pMsg->BufferLength);
941
942   RPCRT4_FreeHeader(hdr);
943
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;
949   }
950   RPCRT4_CloseBinding(bind, conn);
951
952   return status;
953 }
954
955 /***********************************************************************
956  *           I_RpcReceive [RPCRT4.@]
957  */
958 RPC_STATUS WINAPI I_RpcReceive(PRPC_MESSAGE pMsg)
959 {
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;
966
967   TRACE("(%p)\n", pMsg);
968   if (!bind) return RPC_S_INVALID_BINDING;
969
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; /* ? */
982
983       if (!bind->Endpoint || !bind->Endpoint[0])
984       {
985         TRACE("automatically resolving partially bound binding\n");
986         status = RpcEpResolveBinding(bind, cif);
987         if (status != RPC_S_OK) return status;
988       }
989
990       status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
991                                   &cif->InterfaceId);
992     }
993     if (status != RPC_S_OK) return status;
994   }
995
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;
1000   }
1001
1002   status = RPC_S_PROTOCOL_ERROR;
1003
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;
1019   }
1020
1021   /* success */
1022   status = RPC_S_OK;
1023
1024 fail:
1025   RPCRT4_FreeHeader(hdr);
1026   RPCRT4_CloseBinding(bind, conn);
1027   return status;
1028 }
1029
1030 /***********************************************************************
1031  *           I_RpcSendReceive [RPCRT4.@]
1032  *
1033  * Sends a message to the server and receives the response.
1034  *
1035  * PARAMS
1036  *  pMsg [I/O] RPC message information.
1037  *
1038  * RETURNS
1039  *  Success: RPC_S_OK.
1040  *  Failure: Any error code.
1041  *
1042  * NOTES
1043  *  The buffer must have been allocated with I_RpcGetBuffer().
1044  *
1045  * SEE ALSO
1046  *  I_RpcGetBuffer(), I_RpcSend(), I_RpcReceive().
1047  */
1048 RPC_STATUS WINAPI I_RpcSendReceive(PRPC_MESSAGE pMsg)
1049 {
1050   RPC_STATUS status;
1051   RPC_MESSAGE original_message;
1052
1053   TRACE("(%p)\n", pMsg);
1054
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;
1063 }