rpc_message.c 43.4 KB
Newer Older
1 2 3 4
/*
 * RPC messages
 *
 * Copyright 2001-2002 Ove Kven, TransGaming Technologies
5
 * Copyright 2004 Filip Navara
6
 * Copyright 2006 CodeWeavers
7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 25 26 27 28 29
#include <stdio.h>
#include <string.h>

#include "windef.h"
#include "winbase.h"
#include "winerror.h"
30
#include "winuser.h"
31 32

#include "rpc.h"
33
#include "rpcndr.h"
34 35 36 37 38 39
#include "rpcdcep.h"

#include "wine/debug.h"

#include "rpc_binding.h"
#include "rpc_defs.h"
40
#include "rpc_message.h"
41
#include "ncastatus.h"
42

43
WINE_DEFAULT_DEBUG_CHANNEL(rpc);
44

45 46 47 48 49 50 51
/* note: the DCE/RPC spec says the alignment amount should be 4, but
 * MS/RPC servers seem to always use 16 */
#define AUTH_ALIGNMENT 16

/* gets the amount needed to round a value up to the specified alignment */
#define ROUND_UP_AMOUNT(value, alignment) \
    (((alignment) - (((value) % (alignment)))) % (alignment))
52
#define ROUND_UP(value, alignment) (((value) + ((alignment) - 1)) & ~((alignment)-1))
53

54 55 56 57 58 59
enum secure_packet_direction
{
  SECURE_PACKET_SEND,
  SECURE_PACKET_RECEIVE
};

60 61
static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg);

62
static DWORD RPCRT4_GetHeaderSize(const RpcPktHdr *Header)
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
{
  static const DWORD header_sizes[] = {
    sizeof(Header->request), 0, sizeof(Header->response),
    sizeof(Header->fault), 0, 0, 0, 0, 0, 0, 0, sizeof(Header->bind),
    sizeof(Header->bind_ack), sizeof(Header->bind_nack),
    0, 0, 0, 0, 0
  };
  ULONG ret = 0;
  
  if (Header->common.ptype < sizeof(header_sizes) / sizeof(header_sizes[0])) {
    ret = header_sizes[Header->common.ptype];
    if (ret == 0)
      FIXME("unhandled packet type\n");
    if (Header->common.flags & RPC_FLG_OBJECT_UUID)
      ret += sizeof(UUID);
  } else {
    TRACE("invalid packet type\n");
  }

  return ret;
}

85
static int packet_has_body(const RpcPktHdr *Header)
86 87 88 89 90 91
{
    return (Header->common.ptype == PKT_FAULT) ||
           (Header->common.ptype == PKT_REQUEST) ||
           (Header->common.ptype == PKT_RESPONSE);
}

92
static int packet_has_auth_verifier(const RpcPktHdr *Header)
93 94 95 96 97
{
    return !(Header->common.ptype == PKT_BIND_NACK) &&
           !(Header->common.ptype == PKT_SHUTDOWN);
}

98
static VOID RPCRT4_BuildCommonHeader(RpcPktHdr *Header, unsigned char PacketType,
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
                              unsigned long DataRepresentation)
{
  Header->common.rpc_ver = RPC_VER_MAJOR;
  Header->common.rpc_ver_minor = RPC_VER_MINOR;
  Header->common.ptype = PacketType;
  Header->common.drep[0] = LOBYTE(LOWORD(DataRepresentation));
  Header->common.drep[1] = HIBYTE(LOWORD(DataRepresentation));
  Header->common.drep[2] = LOBYTE(HIWORD(DataRepresentation));
  Header->common.drep[3] = HIBYTE(HIWORD(DataRepresentation));
  Header->common.auth_len = 0;
  Header->common.call_id = 1;
  Header->common.flags = 0;
  /* Flags and fragment length are computed in RPCRT4_Send. */
}                              

114
static RpcPktHdr *RPCRT4_BuildRequestHeader(unsigned long DataRepresentation,
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
                                     unsigned long BufferLength,
                                     unsigned short ProcNum,
                                     UUID *ObjectUuid)
{
  RpcPktHdr *header;
  BOOL has_object;
  RPC_STATUS status;

  has_object = (ObjectUuid != NULL && !UuidIsNil(ObjectUuid, &status));
  header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
                     sizeof(header->request) + (has_object ? sizeof(UUID) : 0));
  if (header == NULL) {
    return NULL;
  }

  RPCRT4_BuildCommonHeader(header, PKT_REQUEST, DataRepresentation);
  header->common.frag_len = sizeof(header->request);
  header->request.alloc_hint = BufferLength;
  header->request.context_id = 0;
  header->request.opnum = ProcNum;
  if (has_object) {
    header->common.flags |= RPC_FLG_OBJECT_UUID;
    header->common.frag_len += sizeof(UUID);
    memcpy(&header->request + 1, ObjectUuid, sizeof(UUID));
  }

  return header;
}

144
RpcPktHdr *RPCRT4_BuildResponseHeader(unsigned long DataRepresentation,
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
                                      unsigned long BufferLength)
{
  RpcPktHdr *header;

  header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->response));
  if (header == NULL) {
    return NULL;
  }

  RPCRT4_BuildCommonHeader(header, PKT_RESPONSE, DataRepresentation);
  header->common.frag_len = sizeof(header->response);
  header->response.alloc_hint = BufferLength;

  return header;
}

RpcPktHdr *RPCRT4_BuildFaultHeader(unsigned long DataRepresentation,
                                   RPC_STATUS Status)
{
  RpcPktHdr *header;

  header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->fault));
  if (header == NULL) {
    return NULL;
  }

  RPCRT4_BuildCommonHeader(header, PKT_FAULT, DataRepresentation);
  header->common.frag_len = sizeof(header->fault);
  header->fault.status = Status;

  return header;
}

RpcPktHdr *RPCRT4_BuildBindHeader(unsigned long DataRepresentation,
                                  unsigned short MaxTransmissionSize,
                                  unsigned short MaxReceiveSize,
181
                                  unsigned long  AssocGroupId,
182 183
                                  const RPC_SYNTAX_IDENTIFIER *AbstractId,
                                  const RPC_SYNTAX_IDENTIFIER *TransferId)
184 185 186 187 188 189 190 191 192 193 194 195
{
  RpcPktHdr *header;

  header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind));
  if (header == NULL) {
    return NULL;
  }

  RPCRT4_BuildCommonHeader(header, PKT_BIND, DataRepresentation);
  header->common.frag_len = sizeof(header->bind);
  header->bind.max_tsize = MaxTransmissionSize;
  header->bind.max_rsize = MaxReceiveSize;
196
  header->bind.assoc_gid = AssocGroupId;
197 198
  header->bind.num_elements = 1;
  header->bind.num_syntaxes = 1;
199 200
  header->bind.abstract = *AbstractId;
  header->bind.transfer = *TransferId;
201 202 203 204

  return header;
}

205
static RpcPktHdr *RPCRT4_BuildAuthHeader(unsigned long DataRepresentation)
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
{
  RpcPktHdr *header;

  header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
                     sizeof(header->common) + 12);
  if (header == NULL)
    return NULL;

  RPCRT4_BuildCommonHeader(header, PKT_AUTH3, DataRepresentation);
  header->common.frag_len = 0x14;
  header->common.auth_len = 0;

  return header;
}

221 222 223 224 225 226 227 228 229 230 231 232 233
RpcPktHdr *RPCRT4_BuildBindNackHeader(unsigned long DataRepresentation,
                                      unsigned char RpcVersion,
                                      unsigned char RpcVersionMinor)
{
  RpcPktHdr *header;

  header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(header->bind_nack));
  if (header == NULL) {
    return NULL;
  }

  RPCRT4_BuildCommonHeader(header, PKT_BIND_NACK, DataRepresentation);
  header->common.frag_len = sizeof(header->bind_nack);
234
  header->bind_nack.reject_reason = REJECT_REASON_NOT_SPECIFIED;
235 236 237 238 239 240 241 242 243 244
  header->bind_nack.protocols_count = 1;
  header->bind_nack.protocols[0].rpc_ver = RpcVersion;
  header->bind_nack.protocols[0].rpc_ver_minor = RpcVersionMinor;

  return header;
}

RpcPktHdr *RPCRT4_BuildBindAckHeader(unsigned long DataRepresentation,
                                     unsigned short MaxTransmissionSize,
                                     unsigned short MaxReceiveSize,
245
                                     unsigned long AssocGroupId,
246
                                     LPCSTR ServerAddress,
247 248
                                     unsigned long Result,
                                     unsigned long Reason,
249
                                     const RPC_SYNTAX_IDENTIFIER *TransferId)
250 251 252 253 254 255 256
{
  RpcPktHdr *header;
  unsigned long header_size;
  RpcAddressString *server_address;
  RpcResults *results;
  RPC_SYNTAX_IDENTIFIER *transfer_id;

257 258 259 260
  header_size = sizeof(header->bind_ack) +
                ROUND_UP(FIELD_OFFSET(RpcAddressString, string[strlen(ServerAddress) + 1]), 4) +
                sizeof(RpcResults) +
                sizeof(RPC_SYNTAX_IDENTIFIER);
261 262 263 264 265 266 267 268 269 270

  header = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, header_size);
  if (header == NULL) {
    return NULL;
  }

  RPCRT4_BuildCommonHeader(header, PKT_BIND_ACK, DataRepresentation);
  header->common.frag_len = header_size;
  header->bind_ack.max_tsize = MaxTransmissionSize;
  header->bind_ack.max_rsize = MaxReceiveSize;
271
  header->bind_ack.assoc_gid = AssocGroupId;
272 273 274
  server_address = (RpcAddressString*)(&header->bind_ack + 1);
  server_address->length = strlen(ServerAddress) + 1;
  strcpy(server_address->string, ServerAddress);
275 276
  /* results is 4-byte aligned */
  results = (RpcResults*)((ULONG_PTR)server_address + ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4));
277 278 279 280
  results->num_results = 1;
  results->results[0].result = Result;
  results->results[0].reason = Reason;
  transfer_id = (RPC_SYNTAX_IDENTIFIER*)(results + 1);
281
  *transfer_id = *TransferId;
282 283 284 285 286 287 288 289 290

  return header;
}

VOID RPCRT4_FreeHeader(RpcPktHdr *Header)
{
  HeapFree(GetProcessHeap(), 0, Header);
}

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
NCA_STATUS RPC2NCA_STATUS(RPC_STATUS status)
{
    switch (status)
    {
    case ERROR_INVALID_HANDLE:              return NCA_S_FAULT_CONTEXT_MISMATCH;
    case ERROR_OUTOFMEMORY:                 return NCA_S_FAULT_REMOTE_NO_MEMORY;
    case RPC_S_NOT_LISTENING:               return NCA_S_SERVER_TOO_BUSY;
    case RPC_S_UNKNOWN_IF:                  return NCA_S_UNK_IF;
    case RPC_S_SERVER_TOO_BUSY:             return NCA_S_SERVER_TOO_BUSY;
    case RPC_S_CALL_FAILED:                 return NCA_S_FAULT_UNSPEC;
    case RPC_S_CALL_FAILED_DNE:             return NCA_S_MANAGER_NOT_ENTERED;
    case RPC_S_PROTOCOL_ERROR:              return NCA_S_PROTO_ERROR;
    case RPC_S_UNSUPPORTED_TYPE:            return NCA_S_UNSUPPORTED_TYPE;
    case RPC_S_INVALID_TAG:                 return NCA_S_FAULT_INVALID_TAG;
    case RPC_S_INVALID_BOUND:               return NCA_S_FAULT_INVALID_BOUND;
    case RPC_S_PROCNUM_OUT_OF_RANGE:        return NCA_S_OP_RNG_ERROR;
    case RPC_X_SS_HANDLES_MISMATCH:         return NCA_S_FAULT_CONTEXT_MISMATCH;
308 309 310 311 312 313
    case RPC_S_CALL_CANCELLED:              return NCA_S_FAULT_CANCEL;
    case RPC_S_COMM_FAILURE:                return NCA_S_COMM_FAILURE;
    case RPC_X_WRONG_PIPE_ORDER:            return NCA_S_FAULT_PIPE_ORDER;
    case RPC_X_PIPE_CLOSED:                 return NCA_S_FAULT_PIPE_CLOSED;
    case RPC_X_PIPE_DISCIPLINE_ERROR:       return NCA_S_FAULT_PIPE_DISCIPLINE;
    case RPC_X_PIPE_EMPTY:                  return NCA_S_FAULT_PIPE_EMPTY;
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
    case STATUS_FLOAT_DIVIDE_BY_ZERO:       return NCA_S_FAULT_FP_DIV_ZERO;
    case STATUS_FLOAT_INVALID_OPERATION:    return NCA_S_FAULT_FP_ERROR;
    case STATUS_FLOAT_OVERFLOW:             return NCA_S_FAULT_FP_OVERFLOW;
    case STATUS_FLOAT_UNDERFLOW:            return NCA_S_FAULT_FP_UNDERFLOW;
    case STATUS_INTEGER_DIVIDE_BY_ZERO:     return NCA_S_FAULT_INT_DIV_BY_ZERO;
    case STATUS_INTEGER_OVERFLOW:           return NCA_S_FAULT_INT_OVERFLOW;
    default:                                return status;
    }
}

RPC_STATUS NCA2RPC_STATUS(NCA_STATUS status)
{
    switch (status)
    {
    case NCA_S_COMM_FAILURE:            return RPC_S_COMM_FAILURE;
    case NCA_S_OP_RNG_ERROR:            return RPC_S_PROCNUM_OUT_OF_RANGE;
    case NCA_S_UNK_IF:                  return RPC_S_UNKNOWN_IF;
    case NCA_S_YOU_CRASHED:             return RPC_S_CALL_FAILED;
    case NCA_S_PROTO_ERROR:             return RPC_S_PROTOCOL_ERROR;
    case NCA_S_OUT_ARGS_TOO_BIG:        return ERROR_NOT_ENOUGH_SERVER_MEMORY;
    case NCA_S_SERVER_TOO_BUSY:         return RPC_S_SERVER_TOO_BUSY;
    case NCA_S_UNSUPPORTED_TYPE:        return RPC_S_UNSUPPORTED_TYPE;
    case NCA_S_FAULT_INT_DIV_BY_ZERO:   return RPC_S_ZERO_DIVIDE;
    case NCA_S_FAULT_ADDR_ERROR:        return RPC_S_ADDRESS_ERROR;
    case NCA_S_FAULT_FP_DIV_ZERO:       return RPC_S_FP_DIV_ZERO;
    case NCA_S_FAULT_FP_UNDERFLOW:      return RPC_S_FP_UNDERFLOW;
    case NCA_S_FAULT_FP_OVERFLOW:       return RPC_S_FP_OVERFLOW;
    case NCA_S_FAULT_INVALID_TAG:       return RPC_S_INVALID_TAG;
    case NCA_S_FAULT_INVALID_BOUND:     return RPC_S_INVALID_BOUND;
    case NCA_S_RPC_VERSION_MISMATCH:    return RPC_S_PROTOCOL_ERROR;
    case NCA_S_UNSPEC_REJECT:           return RPC_S_CALL_FAILED_DNE;
    case NCA_S_BAD_ACTID:               return RPC_S_CALL_FAILED_DNE;
    case NCA_S_WHO_ARE_YOU_FAILED:      return RPC_S_CALL_FAILED;
    case NCA_S_MANAGER_NOT_ENTERED:     return RPC_S_CALL_FAILED_DNE;
    case NCA_S_FAULT_CANCEL:            return RPC_S_CALL_CANCELLED;
    case NCA_S_FAULT_ILL_INST:          return RPC_S_ADDRESS_ERROR;
    case NCA_S_FAULT_FP_ERROR:          return RPC_S_FP_OVERFLOW;
    case NCA_S_FAULT_INT_OVERFLOW:      return RPC_S_ADDRESS_ERROR;
    case NCA_S_FAULT_UNSPEC:            return RPC_S_CALL_FAILED;
    case NCA_S_FAULT_PIPE_EMPTY:        return RPC_X_PIPE_EMPTY;
    case NCA_S_FAULT_PIPE_CLOSED:       return RPC_X_PIPE_CLOSED;
    case NCA_S_FAULT_PIPE_ORDER:        return RPC_X_WRONG_PIPE_ORDER;
    case NCA_S_FAULT_PIPE_DISCIPLINE:   return RPC_X_PIPE_DISCIPLINE_ERROR;
    case NCA_S_FAULT_PIPE_COMM_ERROR:   return RPC_S_COMM_FAILURE;
    case NCA_S_FAULT_PIPE_MEMORY:       return ERROR_OUTOFMEMORY;
    case NCA_S_FAULT_CONTEXT_MISMATCH:  return ERROR_INVALID_HANDLE;
    case NCA_S_FAULT_REMOTE_NO_MEMORY:  return ERROR_NOT_ENOUGH_SERVER_MEMORY;
    default:                            return status;
    }
}

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
static RPC_STATUS RPCRT4_SecurePacket(RpcConnection *Connection,
    enum secure_packet_direction dir,
    RpcPktHdr *hdr, unsigned int hdr_size,
    unsigned char *stub_data, unsigned int stub_data_size,
    RpcAuthVerifier *auth_hdr,
    unsigned char *auth_value, unsigned int auth_value_size)
{
    SecBufferDesc message;
    SecBuffer buffers[4];
    SECURITY_STATUS sec_status;

    message.ulVersion = SECBUFFER_VERSION;
    message.cBuffers = sizeof(buffers)/sizeof(buffers[0]);
    message.pBuffers = buffers;

    buffers[0].cbBuffer = hdr_size;
    buffers[0].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
    buffers[0].pvBuffer = hdr;
    buffers[1].cbBuffer = stub_data_size;
    buffers[1].BufferType = SECBUFFER_DATA;
    buffers[1].pvBuffer = stub_data;
    buffers[2].cbBuffer = sizeof(*auth_hdr);
    buffers[2].BufferType = SECBUFFER_DATA|SECBUFFER_READONLY_WITH_CHECKSUM;
    buffers[2].pvBuffer = auth_hdr;
    buffers[3].cbBuffer = auth_value_size;
    buffers[3].BufferType = SECBUFFER_TOKEN;
    buffers[3].pvBuffer = auth_value;

    if (dir == SECURE_PACKET_SEND)
    {
        if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
        {
            sec_status = EncryptMessage(&Connection->ctx, 0, &message, 0 /* FIXME */);
            if (sec_status != SEC_E_OK)
            {
                ERR("EncryptMessage failed with 0x%08x\n", sec_status);
                return RPC_S_SEC_PKG_ERROR;
            }
        }
        else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
        {
            sec_status = MakeSignature(&Connection->ctx, 0, &message, 0 /* FIXME */);
            if (sec_status != SEC_E_OK)
            {
                ERR("MakeSignature failed with 0x%08x\n", sec_status);
                return RPC_S_SEC_PKG_ERROR;
            }
        }
    }
    else if (dir == SECURE_PACKET_RECEIVE)
    {
        if ((auth_hdr->auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(hdr))
        {
            sec_status = DecryptMessage(&Connection->ctx, &message, 0 /* FIXME */, 0);
            if (sec_status != SEC_E_OK)
            {
421
                ERR("DecryptMessage failed with 0x%08x\n", sec_status);
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
                return RPC_S_SEC_PKG_ERROR;
            }
        }
        else if (auth_hdr->auth_level != RPC_C_AUTHN_LEVEL_NONE)
        {
            sec_status = VerifySignature(&Connection->ctx, &message, 0 /* FIXME */, NULL);
            if (sec_status != SEC_E_OK)
            {
                ERR("VerifySignature failed with 0x%08x\n", sec_status);
                return RPC_S_SEC_PKG_ERROR;
            }
        }
    }

    return RPC_S_OK;
}
         
439
/***********************************************************************
440
 *           RPCRT4_SendAuth (internal)
441
 * 
442
 * Transmit a packet with authorization data over connection in acceptable fragments.
443
 */
444 445
static RPC_STATUS RPCRT4_SendAuth(RpcConnection *Connection, RpcPktHdr *Header,
                                  void *Buffer, unsigned int BufferLength,
446
                                  const void *Auth, unsigned int AuthLength)
447 448
{
  PUCHAR buffer_pos;
449 450
  DWORD hdr_size;
  LONG count;
451
  unsigned char *pkt;
452 453
  LONG alen;
  RPC_STATUS status;
454

455 456
  RPCRT4_SetThreadCurrentConnection(Connection);

457 458 459
  buffer_pos = Buffer;
  /* The packet building functions save the packet header size, so we can use it. */
  hdr_size = Header->common.frag_len;
460 461 462
  if (AuthLength)
    Header->common.auth_len = AuthLength;
  else if (Connection->AuthInfo && packet_has_auth_verifier(Header))
463 464 465
  {
    if ((Connection->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY) && packet_has_body(Header))
      Header->common.auth_len = Connection->encryption_auth_len;
466 467
    else
      Header->common.auth_len = Connection->signature_auth_len;
468
  }
469 470
  else
    Header->common.auth_len = 0;
471 472
  Header->common.flags |= RPC_FLG_FIRST;
  Header->common.flags &= ~RPC_FLG_LAST;
473 474 475

  alen = RPC_AUTH_VERIFIER_LEN(&Header->common);

476
  while (!(Header->common.flags & RPC_FLG_LAST)) {
477
    unsigned char auth_pad_len = Header->common.auth_len ? ROUND_UP_AMOUNT(BufferLength, AUTH_ALIGNMENT) : 0;
478
    unsigned int pkt_size = BufferLength + hdr_size + alen + auth_pad_len;
479

480
    /* decide if we need to split the packet into fragments */
481 482 483
   if (pkt_size <= Connection->MaxTransmissionSize) {
     Header->common.flags |= RPC_FLG_LAST;
     Header->common.frag_len = pkt_size;
484
    } else {
485 486 487 488 489
      auth_pad_len = 0;
      /* make sure packet payload will be a multiple of 16 */
      Header->common.frag_len =
        ((Connection->MaxTransmissionSize - hdr_size - alen) & ~(AUTH_ALIGNMENT-1)) +
        hdr_size + alen;
490 491
    }

492 493 494
    pkt = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Header->common.frag_len);

    memcpy(pkt, Header, hdr_size);
495 496

    /* fragment consisted of header only and is the last one */
497 498 499
    if (hdr_size == Header->common.frag_len)
      goto write;

500
    memcpy(pkt + hdr_size, buffer_pos, Header->common.frag_len - hdr_size - auth_pad_len - alen);
501 502

    /* add the authorization info */
503
    if (Connection->AuthInfo && packet_has_auth_verifier(Header))
504
    {
505
      RpcAuthVerifier *auth_hdr = (RpcAuthVerifier *)&pkt[Header->common.frag_len - alen];
506

507 508 509 510
      auth_hdr->auth_type = Connection->AuthInfo->AuthnSvc;
      auth_hdr->auth_level = Connection->AuthInfo->AuthnLevel;
      auth_hdr->auth_pad_length = auth_pad_len;
      auth_hdr->auth_reserved = 0;
511
      /* a unique number... */
512 513
      auth_hdr->auth_context_id = (unsigned long)Connection;

514 515 516 517 518 519 520 521 522 523 524 525
      if (AuthLength)
        memcpy(auth_hdr + 1, Auth, AuthLength);
      else
      {
        status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_SEND,
            (RpcPktHdr *)pkt, hdr_size,
            pkt + hdr_size, Header->common.frag_len - hdr_size - alen,
            auth_hdr,
            (unsigned char *)(auth_hdr + 1), Header->common.auth_len);
        if (status != RPC_S_OK)
        {
          HeapFree(GetProcessHeap(), 0, pkt);
526
          RPCRT4_SetThreadCurrentConnection(NULL);
527 528 529
          return status;
        }
      }
530 531
    }

532 533 534
write:
    count = rpcrt4_conn_write(Connection, pkt, Header->common.frag_len);
    HeapFree(GetProcessHeap(), 0, pkt);
535
    if (count<0) {
536
      WARN("rpcrt4_conn_write failed (auth)\n");
537
      RPCRT4_SetThreadCurrentConnection(NULL);
538
      return RPC_S_CALL_FAILED;
539 540
    }

541 542
    buffer_pos += Header->common.frag_len - hdr_size - alen - auth_pad_len;
    BufferLength -= Header->common.frag_len - hdr_size - alen - auth_pad_len;
543 544 545
    Header->common.flags &= ~RPC_FLG_FIRST;
  }

546
  RPCRT4_SetThreadCurrentConnection(NULL);
547 548 549
  return RPC_S_OK;
}

550
/***********************************************************************
551 552 553
 *           RPCRT4_ClientAuthorize (internal)
 *
 * Authorize a client connection. A NULL in param signifies a new connection.
554
 */
555 556
static RPC_STATUS RPCRT4_ClientAuthorize(RpcConnection *conn, SecBuffer *in,
                                         SecBuffer *out)
557 558 559
{
  SECURITY_STATUS r;
  SecBufferDesc out_desc;
560
  SecBufferDesc inp_desc;
561 562
  SecPkgContext_Sizes secctx_sizes;
  BOOL continue_needed;
563 564 565 566 567 568 569
  ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
                      ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;

  if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY)
    context_req |= ISC_REQ_INTEGRITY;
  else if (conn->AuthInfo->AuthnLevel == RPC_C_AUTHN_LEVEL_PKT_PRIVACY)
    context_req |= ISC_REQ_CONFIDENTIALITY | ISC_REQ_INTEGRITY;
570 571

  out->BufferType = SECBUFFER_TOKEN;
572
  out->cbBuffer = conn->AuthInfo->cbMaxToken;
573
  out->pvBuffer = HeapAlloc(GetProcessHeap(), 0, out->cbBuffer);
574
  if (!out->pvBuffer) return ERROR_OUTOFMEMORY;
575 576 577 578 579

  out_desc.ulVersion = 0;
  out_desc.cBuffers = 1;
  out_desc.pBuffers = out;

580 581 582 583
  inp_desc.cBuffers = 1;
  inp_desc.pBuffers = in;
  inp_desc.ulVersion = 0;

584 585 586 587
  r = InitializeSecurityContextW(&conn->AuthInfo->cred, in ? &conn->ctx : NULL,
        in ? NULL : conn->AuthInfo->server_principal_name, context_req, 0,
        SECURITY_NETWORK_DREP, in ? &inp_desc : NULL, 0, &conn->ctx,
        &out_desc, &conn->attr, &conn->exp);
588 589 590
  if (FAILED(r))
  {
      WARN("InitializeSecurityContext failed with error 0x%08x\n", r);
591
      goto failed;
592
  }
593

594
  TRACE("r = 0x%08x, attr = 0x%08x\n", r, conn->attr);
595 596
  continue_needed = ((r == SEC_I_CONTINUE_NEEDED) ||
                     (r == SEC_I_COMPLETE_AND_CONTINUE));
597 598 599 600 601 602 603 604

  if ((r == SEC_I_COMPLETE_NEEDED) || (r == SEC_I_COMPLETE_AND_CONTINUE))
  {
      TRACE("complete needed\n");
      r = CompleteAuthToken(&conn->ctx, &out_desc);
      if (FAILED(r))
      {
          WARN("CompleteAuthToken failed with error 0x%08x\n", r);
605
          goto failed;
606 607 608 609
      }
  }

  TRACE("cbBuffer = %ld\n", out->cbBuffer);
610

611 612 613 614 615 616 617 618 619 620 621 622
  if (!continue_needed)
  {
      r = QueryContextAttributesA(&conn->ctx, SECPKG_ATTR_SIZES, &secctx_sizes);
      if (FAILED(r))
      {
          WARN("QueryContextAttributes failed with error 0x%08x\n", r);
          goto failed;
      }
      conn->signature_auth_len = secctx_sizes.cbMaxSignature;
      conn->encryption_auth_len = secctx_sizes.cbSecurityTrailer;
  }

623
  return RPC_S_OK;
624 625 626 627 628

failed:
  HeapFree(GetProcessHeap(), 0, out->pvBuffer);
  out->pvBuffer = NULL;
  return ERROR_ACCESS_DENIED; /* FIXME: is this correct? */
629 630 631 632 633 634 635 636 637 638 639 640
}

/***********************************************************************
 *           RPCRT4_AuthorizeBinding (internal)
 */
static RPC_STATUS RPCRT_AuthorizeConnection(RpcConnection* conn,
                                            BYTE *challenge, ULONG count)
{
  SecBuffer inp, out;
  RpcPktHdr *resp_hdr;
  RPC_STATUS status;

641
  TRACE("challenge %s, %d bytes\n", challenge, count);
642 643 644 645 646

  inp.BufferType = SECBUFFER_TOKEN;
  inp.pvBuffer = challenge;
  inp.cbBuffer = count;

647 648
  status = RPCRT4_ClientAuthorize(conn, &inp, &out);
  if (status) return status;
649 650 651 652 653 654 655

  resp_hdr = RPCRT4_BuildAuthHeader(NDR_LOCAL_DATA_REPRESENTATION);
  if (!resp_hdr)
    return E_OUTOFMEMORY;

  status = RPCRT4_SendAuth(conn, resp_hdr, NULL, 0, out.pvBuffer, out.cbBuffer);

656
  HeapFree(GetProcessHeap(), 0, out.pvBuffer);
657 658 659 660 661
  RPCRT4_FreeHeader(resp_hdr);

  return status;
}

662 663 664 665 666 667 668 669
/***********************************************************************
 *           RPCRT4_Send (internal)
 * 
 * Transmit a packet over connection in acceptable fragments.
 */
RPC_STATUS RPCRT4_Send(RpcConnection *Connection, RpcPktHdr *Header,
                       void *Buffer, unsigned int BufferLength)
{
670 671 672
  RPC_STATUS r;
  SecBuffer out;

673
  if (!Connection->AuthInfo || SecIsValidHandle(&Connection->ctx))
674 675 676 677 678
  {
    return RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, NULL, 0);
  }

  /* tack on a negotiate packet */
679 680 681 682 683 684
  r = RPCRT4_ClientAuthorize(Connection, NULL, &out);
  if (r == RPC_S_OK)
  {
    r = RPCRT4_SendAuth(Connection, Header, Buffer, BufferLength, out.pvBuffer, out.cbBuffer);
    HeapFree(GetProcessHeap(), 0, out.pvBuffer);
  }
685 686

  return r;
687 688
}

689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
/* validates version and frag_len fields */
RPC_STATUS RPCRT4_ValidateCommonHeader(const RpcPktCommonHdr *hdr)
{
  DWORD hdr_length;

  /* verify if the header really makes sense */
  if (hdr->rpc_ver != RPC_VER_MAJOR ||
      hdr->rpc_ver_minor != RPC_VER_MINOR)
  {
    WARN("unhandled packet version\n");
    return RPC_S_PROTOCOL_ERROR;
  }

  hdr_length = RPCRT4_GetHeaderSize((const RpcPktHdr*)hdr);
  if (hdr_length == 0)
  {
    WARN("header length == 0\n");
    return RPC_S_PROTOCOL_ERROR;
  }

  if (hdr->frag_len < hdr_length)
  {
    WARN("bad frag length %d\n", hdr->frag_len);
    return RPC_S_PROTOCOL_ERROR;
  }

  return RPC_S_OK;
}

718
/***********************************************************************
719
 *           RPCRT4_receive_fragment (internal)
720
 * 
721
 * Receive a fragment from a connection.
722
 */
723
RPC_STATUS RPCRT4_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
724 725
{
  RPC_STATUS status;
726 727
  DWORD hdr_length;
  LONG dwRead;
728 729 730
  RpcPktCommonHdr common_hdr;

  *Header = NULL;
731
  *Payload = NULL;
732

733
  TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
734

735
  /* read packet common header */
736
  dwRead = rpcrt4_conn_read(Connection, &common_hdr, sizeof(common_hdr));
737
  if (dwRead != sizeof(common_hdr)) {
738
    WARN("Short read of header, %d bytes\n", dwRead);
739
    status = RPC_S_CALL_FAILED;
740 741 742
    goto fail;
  }

743 744
  status = RPCRT4_ValidateCommonHeader(&common_hdr);
  if (status != RPC_S_OK) goto fail;
745 746 747

  hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
  if (hdr_length == 0) {
748
    WARN("header length == 0\n");
749 750 751 752 753 754 755 756
    status = RPC_S_PROTOCOL_ERROR;
    goto fail;
  }

  *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
  memcpy(*Header, &common_hdr, sizeof(common_hdr));

  /* read the rest of packet header */
757
  dwRead = rpcrt4_conn_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
758
  if (dwRead != hdr_length - sizeof(common_hdr)) {
759
    WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
760
    status = RPC_S_CALL_FAILED;
761 762 763
    goto fail;
  }

764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
  if (common_hdr.frag_len - hdr_length)
  {
    *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
    if (!*Payload)
    {
      status = RPC_S_OUT_OF_RESOURCES;
      goto fail;
    }

    dwRead = rpcrt4_conn_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
    if (dwRead != common_hdr.frag_len - hdr_length)
    {
      WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
      status = RPC_S_CALL_FAILED;
      goto fail;
    }
  }
  else
    *Payload = NULL;

  /* success */
  status = RPC_S_OK;

fail:
  if (status != RPC_S_OK) {
    RPCRT4_FreeHeader(*Header);
    *Header = NULL;
    HeapFree(GetProcessHeap(), 0, *Payload);
    *Payload = NULL;
  }
  return status;
}

/***********************************************************************
 *           RPCRT4_Receive (internal)
 *
 * Receive a packet from connection and merge the fragments.
 */
RPC_STATUS RPCRT4_Receive(RpcConnection *Connection, RpcPktHdr **Header,
                          PRPC_MESSAGE pMsg)
{
  RPC_STATUS status;
  DWORD hdr_length;
  unsigned short first_flag;
  unsigned long data_length;
  unsigned long buffer_length;
  unsigned long auth_length;
  unsigned char *auth_data = NULL;
812
  RpcPktHdr *CurrentHeader = NULL;
813 814 815
  void *payload = NULL;

  *Header = NULL;
816
  pMsg->Buffer = NULL;
817 818 819 820 821 822 823 824 825 826

  TRACE("(%p, %p, %p)\n", Connection, Header, pMsg);

  RPCRT4_SetThreadCurrentConnection(Connection);

  status = RPCRT4_receive_fragment(Connection, Header, &payload);
  if (status != RPC_S_OK) goto fail;

  hdr_length = RPCRT4_GetHeaderSize(*Header);

827
  /* read packet body */
828
  switch ((*Header)->common.ptype) {
829 830 831 832 833 834 835
  case PKT_RESPONSE:
    pMsg->BufferLength = (*Header)->response.alloc_hint;
    break;
  case PKT_REQUEST:
    pMsg->BufferLength = (*Header)->request.alloc_hint;
    break;
  default:
836
    pMsg->BufferLength = (*Header)->common.frag_len - hdr_length - RPC_AUTH_VERIFIER_LEN(&(*Header)->common);
837
  }
838 839 840

  TRACE("buffer length = %u\n", pMsg->BufferLength);

841 842 843 844 845 846
  pMsg->Buffer = I_RpcAllocate(pMsg->BufferLength);
  if (!pMsg->Buffer)
  {
    status = ERROR_OUTOFMEMORY;
    goto fail;
  }
847 848

  first_flag = RPC_FLG_FIRST;
849
  auth_length = (*Header)->common.auth_len;
850
  if (auth_length) {
851
    auth_data = HeapAlloc(GetProcessHeap(), 0, RPC_AUTH_VERIFIER_LEN(&(*Header)->common));
852
    if (!auth_data) {
853
      status = RPC_S_OUT_OF_RESOURCES;
854 855 856
      goto fail;
    }
  }
857
  CurrentHeader = *Header;
858
  buffer_length = 0;
859
  while (TRUE)
860
  {
861
    unsigned int header_auth_len = RPC_AUTH_VERIFIER_LEN(&CurrentHeader->common);
862 863 864

    /* verify header fields */

865 866
    if ((CurrentHeader->common.frag_len < hdr_length) ||
        (CurrentHeader->common.frag_len - hdr_length < header_auth_len)) {
867
      WARN("frag_len %d too small for hdr_length %d and auth_len %d\n",
868
        CurrentHeader->common.frag_len, hdr_length, CurrentHeader->common.auth_len);
869 870 871 872
      status = RPC_S_PROTOCOL_ERROR;
      goto fail;
    }

873
    if (CurrentHeader->common.auth_len != auth_length) {
874
      WARN("auth_len header field changed from %ld to %d\n",
875
        auth_length, CurrentHeader->common.auth_len);
876 877 878 879
      status = RPC_S_PROTOCOL_ERROR;
      goto fail;
    }

880
    if ((CurrentHeader->common.flags & RPC_FLG_FIRST) != first_flag) {
881
      TRACE("invalid packet flags\n");
882 883 884 885
      status = RPC_S_PROTOCOL_ERROR;
      goto fail;
    }

886
    data_length = CurrentHeader->common.frag_len - hdr_length - header_auth_len;
887 888 889 890 891 892 893 894
    if (data_length + buffer_length > pMsg->BufferLength) {
      TRACE("allocation hint exceeded, new buffer length = %ld\n",
        data_length + buffer_length);
      pMsg->BufferLength = data_length + buffer_length;
      status = I_RpcReAllocateBuffer(pMsg);
      if (status != RPC_S_OK) goto fail;
    }

895
    memcpy((unsigned char *)pMsg->Buffer + buffer_length, payload, data_length);
896

897
    if (header_auth_len) {
898 899
      if (header_auth_len < sizeof(RpcAuthVerifier) ||
          header_auth_len > RPC_AUTH_VERIFIER_LEN(&(*Header)->common)) {
900 901 902 903 904
        WARN("bad auth verifier length %d\n", header_auth_len);
        status = RPC_S_PROTOCOL_ERROR;
        goto fail;
      }

905 906 907 908 909
      /* FIXME: we should accumulate authentication data for the bind,
       * bind_ack, alter_context and alter_context_response if necessary.
       * however, the details of how this is done is very sketchy in the
       * DCE/RPC spec. for all other packet types that have authentication
       * verifier data then it is just duplicated in all the fragments */
910
      memcpy(auth_data, (unsigned char *)payload + data_length, header_auth_len);
911 912 913

      /* these packets are handled specially, not by the generic SecurePacket
       * function */
914 915 916
      if (((*Header)->common.ptype != PKT_BIND) &&
          ((*Header)->common.ptype != PKT_BIND_ACK) &&
          ((*Header)->common.ptype != PKT_AUTH3))
917
      {
918
        status = RPCRT4_SecurePacket(Connection, SECURE_PACKET_RECEIVE,
919
            CurrentHeader, hdr_length,
920 921
            (unsigned char *)pMsg->Buffer + buffer_length, data_length,
            (RpcAuthVerifier *)auth_data,
922
            auth_data + sizeof(RpcAuthVerifier),
923
            header_auth_len - sizeof(RpcAuthVerifier));
924 925
        if (status != RPC_S_OK) goto fail;
      }
926 927
    }

928
    buffer_length += data_length;
929
    if (!(CurrentHeader->common.flags & RPC_FLG_LAST)) {
930 931
      TRACE("next header\n");

932 933 934 935
      if (*Header != CurrentHeader)
      {
          RPCRT4_FreeHeader(CurrentHeader);
          CurrentHeader = NULL;
936
      }
937 938 939 940 941
      HeapFree(GetProcessHeap(), 0, payload);
      payload = NULL;

      status = RPCRT4_receive_fragment(Connection, &CurrentHeader, &payload);
      if (status != RPC_S_OK) goto fail;
942 943

      first_flag = 0;
944 945
    } else {
      break;
946 947
    }
  }
948
  pMsg->BufferLength = buffer_length;
949

950
  /* respond to authorization request */
951
  if ((*Header)->common.ptype == PKT_BIND_ACK && auth_length > sizeof(RpcAuthVerifier))
952
  {
953 954 955
    status = RPCRT_AuthorizeConnection(Connection,
                                       auth_data + sizeof(RpcAuthVerifier),
                                       auth_length);
956 957
    if (status)
        goto fail;
958 959
  }

960 961 962 963
  /* success */
  status = RPC_S_OK;

fail:
964
  RPCRT4_SetThreadCurrentConnection(NULL);
965 966
  if (CurrentHeader != *Header)
    RPCRT4_FreeHeader(CurrentHeader);
967
  if (status != RPC_S_OK) {
968 969
    I_RpcFree(pMsg->Buffer);
    pMsg->Buffer = NULL;
970 971 972
    RPCRT4_FreeHeader(*Header);
    *Header = NULL;
  }
973
  HeapFree(GetProcessHeap(), 0, auth_data);
974
  HeapFree(GetProcessHeap(), 0, payload);
975 976 977
  return status;
}

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
/***********************************************************************
 *           I_RpcNegotiateTransferSyntax [RPCRT4.@]
 *
 * Negotiates the transfer syntax used by a client connection by connecting
 * to the server.
 *
 * PARAMS
 *  pMsg   [I] RPC Message structure.
 *  pAsync [I] Asynchronous state to set.
 *
 * RETURNS
 *  Success: RPC_S_OK.
 *  Failure: Any error code.
 */
RPC_STATUS WINAPI I_RpcNegotiateTransferSyntax(PRPC_MESSAGE pMsg)
{
  RpcBinding* bind = (RpcBinding*)pMsg->Handle;
  RpcConnection* conn;
  RPC_STATUS status = RPC_S_OK;

  TRACE("(%p)\n", pMsg);

  if (!bind || bind->server)
    return RPC_S_INVALID_BINDING;

  /* if we already have a connection, we don't need to negotiate again */
  if (!pMsg->ReservedForRuntime)
  {
    RPC_CLIENT_INTERFACE *cif = pMsg->RpcInterfaceInformation;
    if (!cif) return RPC_S_INTERFACE_NOT_FOUND;

    if (!bind->Endpoint || !bind->Endpoint[0])
    {
      TRACE("automatically resolving partially bound binding\n");
      status = RpcEpResolveBinding(bind, cif);
      if (status != RPC_S_OK) return status;
    }

    status = RPCRT4_OpenBinding(bind, &conn, &cif->TransferSyntax,
                                &cif->InterfaceId);

    if (status == RPC_S_OK)
1020
    {
1021
      pMsg->ReservedForRuntime = conn;
1022 1023
      RPCRT4_AddRefBinding(bind);
    }
1024 1025 1026 1027 1028
  }

  return status;
}

1029 1030
/***********************************************************************
 *           I_RpcGetBuffer [RPCRT4.@]
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
 *
 * Allocates a buffer for use by I_RpcSend or I_RpcSendReceive and binds to the
 * server interface.
 *
 * PARAMS
 *  pMsg [I/O] RPC message information.
 *
 * RETURNS
 *  Success: RPC_S_OK.
 *  Failure: RPC_S_INVALID_BINDING if pMsg->Handle is invalid.
 *           RPC_S_SERVER_UNAVAILABLE if unable to connect to server.
 *           ERROR_OUTOFMEMORY if buffer allocation failed.
 *
 * NOTES
 *  The pMsg->BufferLength field determines the size of the buffer to allocate,
 *  in bytes.
 *
 *  Use I_RpcFreeBuffer() to unbind from the server and free the message buffer.
 *
 * SEE ALSO
 *  I_RpcFreeBuffer(), I_RpcSend(), I_RpcReceive(), I_RpcSendReceive().
1052 1053 1054
 */
RPC_STATUS WINAPI I_RpcGetBuffer(PRPC_MESSAGE pMsg)
{
1055 1056 1057
  RPC_STATUS status;
  RpcBinding* bind = (RpcBinding*)pMsg->Handle;

1058
  TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
1059

1060 1061 1062 1063
  if (!bind)
    return RPC_S_INVALID_BINDING;

  pMsg->Buffer = I_RpcAllocate(pMsg->BufferLength);
1064
  TRACE("Buffer=%p\n", pMsg->Buffer);
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078

  if (!pMsg->Buffer)
    return ERROR_OUTOFMEMORY;

  if (!bind->server)
  {
    status = I_RpcNegotiateTransferSyntax(pMsg);
    if (status != RPC_S_OK)
      I_RpcFree(pMsg->Buffer);
  }
  else
    status = RPC_S_OK;

  return status;
1079 1080
}

1081 1082 1083 1084 1085 1086 1087 1088 1089
/***********************************************************************
 *           I_RpcReAllocateBuffer (internal)
 */
static RPC_STATUS I_RpcReAllocateBuffer(PRPC_MESSAGE pMsg)
{
  TRACE("(%p): BufferLength=%d\n", pMsg, pMsg->BufferLength);
  pMsg->Buffer = HeapReAlloc(GetProcessHeap(), 0, pMsg->Buffer, pMsg->BufferLength);

  TRACE("Buffer=%p\n", pMsg->Buffer);
1090
  return pMsg->Buffer ? RPC_S_OK : ERROR_OUTOFMEMORY;
1091 1092
}

1093 1094
/***********************************************************************
 *           I_RpcFreeBuffer [RPCRT4.@]
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
 *
 * Frees a buffer allocated by I_RpcGetBuffer or I_RpcReceive and unbinds from
 * the server interface.
 *
 * PARAMS
 *  pMsg [I/O] RPC message information.
 *
 * RETURNS
 *  RPC_S_OK.
 *
 * SEE ALSO
 *  I_RpcGetBuffer(), I_RpcReceive().
1107 1108 1109
 */
RPC_STATUS WINAPI I_RpcFreeBuffer(PRPC_MESSAGE pMsg)
{
1110 1111
  RpcBinding* bind = (RpcBinding*)pMsg->Handle;

1112
  TRACE("(%p) Buffer=%p\n", pMsg, pMsg->Buffer);
1113 1114 1115 1116 1117 1118 1119

  if (!bind) return RPC_S_INVALID_BINDING;

  if (pMsg->ReservedForRuntime)
  {
    RpcConnection *conn = pMsg->ReservedForRuntime;
    RPCRT4_CloseBinding(bind, conn);
1120
    RPCRT4_ReleaseBinding(bind);
1121 1122 1123
    pMsg->ReservedForRuntime = NULL;
  }
  I_RpcFree(pMsg->Buffer);
1124
  return RPC_S_OK;
1125 1126
}

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
static void CALLBACK async_apc_notifier_proc(ULONG_PTR ulParam)
{
    RPC_ASYNC_STATE *state = (RPC_ASYNC_STATE *)ulParam;
    state->u.APC.NotificationRoutine(state, NULL, state->Event);
}

static DWORD WINAPI async_notifier_proc(LPVOID p)
{
    RpcConnection *conn = p;
    RPC_ASYNC_STATE *state = conn->async_state;

1138
    if (state && conn->ops->wait_for_incoming_data(conn) != -1)
1139 1140 1141 1142 1143
    {
        state->Event = RpcCallComplete;
        switch (state->NotificationType)
        {
        case RpcNotificationTypeEvent:
1144
            TRACE("RpcNotificationTypeEvent %p\n", state->u.hEvent);
1145 1146 1147
            SetEvent(state->u.hEvent);
            break;
        case RpcNotificationTypeApc:
1148
            TRACE("RpcNotificationTypeApc %p\n", state->u.APC.hThread);
1149 1150 1151
            QueueUserAPC(async_apc_notifier_proc, state->u.APC.hThread, (ULONG_PTR)state);
            break;
        case RpcNotificationTypeIoc:
1152 1153 1154
            TRACE("RpcNotificationTypeIoc %p, 0x%x, 0x%lx, %p\n",
                state->u.IOC.hIOPort, state->u.IOC.dwNumberOfBytesTransferred,
                state->u.IOC.dwCompletionKey, state->u.IOC.lpOverlapped);
1155 1156 1157 1158 1159 1160
            PostQueuedCompletionStatus(state->u.IOC.hIOPort,
                state->u.IOC.dwNumberOfBytesTransferred,
                state->u.IOC.dwCompletionKey,
                state->u.IOC.lpOverlapped);
            break;
        case RpcNotificationTypeHwnd:
1161 1162
            TRACE("RpcNotificationTypeHwnd %p 0x%x\n", state->u.HWND.hWnd,
                state->u.HWND.Msg);
1163 1164 1165
            PostMessageW(state->u.HWND.hWnd, state->u.HWND.Msg, 0, 0);
            break;
        case RpcNotificationTypeCallback:
1166
            TRACE("RpcNotificationTypeCallback %p\n", state->u.NotificationRoutine);
1167 1168 1169
            state->u.NotificationRoutine(state, NULL, state->Event);
            break;
        case RpcNotificationTypeNone:
1170 1171
            TRACE("RpcNotificationTypeNone\n");
            break;
1172
        default:
1173
            FIXME("unknown NotificationType: %d/0x%x\n", state->NotificationType, state->NotificationType);
1174 1175 1176 1177 1178 1179 1180
            break;
        }
    }

    return 0;
}

1181 1182
/***********************************************************************
 *           I_RpcSend [RPCRT4.@]
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
 *
 * Sends a message to the server.
 *
 * PARAMS
 *  pMsg [I/O] RPC message information.
 *
 * RETURNS
 *  Unknown.
 *
 * NOTES
 *  The buffer must have been allocated with I_RpcGetBuffer().
 *
 * SEE ALSO
 *  I_RpcGetBuffer(), I_RpcReceive(), I_RpcSendReceive().
1197 1198 1199 1200
 */
RPC_STATUS WINAPI I_RpcSend(PRPC_MESSAGE pMsg)
{
  RpcBinding* bind = (RpcBinding*)pMsg->Handle;
1201
  RpcConnection* conn;
1202
  RPC_STATUS status;
1203
  RpcPktHdr *hdr;
1204 1205

  TRACE("(%p)\n", pMsg);
1206
  if (!bind || bind->server || !pMsg->ReservedForRuntime) return RPC_S_INVALID_BINDING;
1207

1208
  conn = pMsg->ReservedForRuntime;
1209

1210
  hdr = RPCRT4_BuildRequestHeader(pMsg->DataRepresentation,
1211 1212
                                  pMsg->BufferLength,
                                  pMsg->ProcNum & ~RPC_FLAGS_VALID_BIT,
1213 1214 1215 1216
                                  &bind->ObjectUuid);
  if (!hdr)
    return ERROR_OUTOFMEMORY;
  hdr->common.call_id = conn->NextCallId++;
1217

1218 1219 1220 1221
  status = RPCRT4_Send(conn, hdr, pMsg->Buffer, pMsg->BufferLength);

  RPCRT4_FreeHeader(hdr);

1222 1223 1224 1225 1226 1227
  if (status == RPC_S_OK && pMsg->RpcFlags & RPC_BUFFER_ASYNC)
  {
    if (!QueueUserWorkItem(async_notifier_proc, conn, WT_EXECUTEDEFAULT | WT_EXECUTELONGFUNCTION))
        status = RPC_S_OUT_OF_RESOURCES;
  }

1228
  return status;
1229 1230
}

1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
/* is this status something that the server can't recover from? */
static inline BOOL is_hard_error(RPC_STATUS status)
{
    switch (status)
    {
    case 0: /* user-defined fault */
    case ERROR_ACCESS_DENIED:
    case ERROR_INVALID_PARAMETER:
    case RPC_S_PROTOCOL_ERROR:
    case RPC_S_CALL_FAILED:
    case RPC_S_CALL_FAILED_DNE:
1242
    case RPC_S_SEC_PKG_ERROR:
1243 1244 1245 1246 1247 1248
        return TRUE;
    default:
        return FALSE;
    }
}

1249 1250 1251 1252 1253 1254 1255
/***********************************************************************
 *           I_RpcReceive [RPCRT4.@]
 */
RPC_STATUS WINAPI I_RpcReceive(PRPC_MESSAGE pMsg)
{
  RpcBinding* bind = (RpcBinding*)pMsg->Handle;
  RPC_STATUS status;
1256
  RpcPktHdr *hdr = NULL;
1257
  RpcConnection *conn;
1258 1259

  TRACE("(%p)\n", pMsg);
1260
  if (!bind || bind->server || !pMsg->ReservedForRuntime) return RPC_S_INVALID_BINDING;
1261

1262
  conn = pMsg->ReservedForRuntime;
1263 1264 1265 1266 1267
  status = RPCRT4_Receive(conn, &hdr, pMsg);
  if (status != RPC_S_OK) {
    WARN("receive failed with error %lx\n", status);
    goto fail;
  }
1268

1269 1270
  switch (hdr->common.ptype) {
  case PKT_RESPONSE:
1271
    break;
1272
  case PKT_FAULT:
1273
    ERR ("we got fault packet with status 0x%lx\n", hdr->fault.status);
1274
    status = NCA2RPC_STATUS(hdr->fault.status);
1275 1276 1277
    if (is_hard_error(status))
        goto fail;
    break;
1278
  default:
1279
    WARN("bad packet type %d\n", hdr->common.ptype);
1280
    status = RPC_S_PROTOCOL_ERROR;
1281
    goto fail;
1282
  }
1283 1284

  /* success */
1285 1286
  RPCRT4_FreeHeader(hdr);
  return status;
1287

1288
fail:
1289
  RPCRT4_FreeHeader(hdr);
1290
  RPCRT4_DestroyConnection(conn);
1291
  pMsg->ReservedForRuntime = NULL;
1292
  return status;
1293 1294 1295 1296
}

/***********************************************************************
 *           I_RpcSendReceive [RPCRT4.@]
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
 *
 * Sends a message to the server and receives the response.
 *
 * PARAMS
 *  pMsg [I/O] RPC message information.
 *
 * RETURNS
 *  Success: RPC_S_OK.
 *  Failure: Any error code.
 *
 * NOTES
 *  The buffer must have been allocated with I_RpcGetBuffer().
 *
 * SEE ALSO
 *  I_RpcGetBuffer(), I_RpcSend(), I_RpcReceive().
1312 1313 1314 1315
 */
RPC_STATUS WINAPI I_RpcSendReceive(PRPC_MESSAGE pMsg)
{
  RPC_STATUS status;
1316
  void *original_buffer;
1317 1318

  TRACE("(%p)\n", pMsg);
1319

1320
  original_buffer = pMsg->Buffer;
1321 1322 1323
  status = I_RpcSend(pMsg);
  if (status == RPC_S_OK)
    status = I_RpcReceive(pMsg);
1324 1325
  /* free the buffer replaced by a new buffer in I_RpcReceive */
  if (status == RPC_S_OK)
1326
    I_RpcFree(original_buffer);
1327 1328
  return status;
}
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345

/***********************************************************************
 *           I_RpcAsyncSetHandle [RPCRT4.@]
 *
 * Sets the asynchronous state of the handle contained in the RPC message
 * structure.
 *
 * PARAMS
 *  pMsg   [I] RPC Message structure.
 *  pAsync [I] Asynchronous state to set.
 *
 * RETURNS
 *  Success: RPC_S_OK.
 *  Failure: Any error code.
 */
RPC_STATUS WINAPI I_RpcAsyncSetHandle(PRPC_MESSAGE pMsg, PRPC_ASYNC_STATE pAsync)
{
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
    RpcBinding* bind = (RpcBinding*)pMsg->Handle;
    RpcConnection *conn;

    TRACE("(%p, %p)\n", pMsg, pAsync);

    if (!bind || bind->server || !pMsg->ReservedForRuntime) return RPC_S_INVALID_BINDING;

    conn = pMsg->ReservedForRuntime;
    conn->async_state = pAsync;

    return RPC_S_OK;
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
}

/***********************************************************************
 *           I_RpcAsyncAbortCall [RPCRT4.@]
 *
 * Aborts an asynchronous call.
 *
 * PARAMS
 *  pAsync        [I] Asynchronous state.
 *  ExceptionCode [I] Exception code.
 *
 * RETURNS
 *  Success: RPC_S_OK.
 *  Failure: Any error code.
 */
RPC_STATUS WINAPI I_RpcAsyncAbortCall(PRPC_ASYNC_STATE pAsync, ULONG ExceptionCode)
{
    FIXME("(%p, %d): stub\n", pAsync, ExceptionCode);
    return RPC_S_INVALID_ASYNC_HANDLE;
}