HTTPmsg_PT.cc 47.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 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 144 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 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 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 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 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 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 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 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 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
/******************************************************************************
* Copyright (c) 2000-2019 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html
*
* Contributors:
*   Eduard Czimbalmos - initial implementation and initial documentation
*   Istvan Ovary
*   Peter Dimitrov
*   Balasko Jeno
*   Gabor Szalai
******************************************************************************/
//
//  File:               HTTPmsg_PT.cc
//  Description:        HTTP test port implementation
//  Rev:                R9B
//  Prodnr:             CNL 113 469


#include "HTTPmsg_PT.hh"

#include <ctype.h>
#include <arpa/inet.h>

#ifdef AS_USE_SSL
#include <openssl/ssl.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#endif

static bool report_lf=true;

namespace HTTPmsg__PortType {

HTTPmsg__PT::HTTPmsg__PT(const char *par_port_name)
	: HTTPmsg__PT_BASE(par_port_name)
{
    parameter_set(use_connection_ASPs_name(), "yes");
    parameter_set(server_backlog_name(), "1024");
    use_notification_ASPs = false;
    set_ttcn_buffer_usercontrol(true);
    set_handle_half_close(true);
    adding_client_connection = false;
    adding_ssl_connection = false;
    server_use_ssl = false;
#ifdef AS_USE_SSL
    
    set_ssl_use_ssl(true);
#endif
    use_send_failed = false;
    last_msg = NULL;
}

HTTPmsg__PT::~HTTPmsg__PT()
{

}

void HTTPmsg__PT::set_parameter(const char *parameter_name,
	const char *parameter_value)
{
    log_debug("entering HTTPmsg__PT::set_parameter(%s, %s)", parameter_name, parameter_value);
    if(strcasecmp(parameter_name, use_notification_ASPs_name()) == 0) {
        if (strcasecmp(parameter_value,"yes")==0) use_notification_ASPs = true;
        else if (strcasecmp(parameter_value,"no")==0) use_notification_ASPs = false;
        else log_error("Parameter value '%s' not recognized for parameter '%s'", parameter_value, use_notification_ASPs_name());
    } else if(strcasecmp(parameter_name, "report_failed_message") == 0){
        if (strcasecmp(parameter_value,"yes")==0) use_send_failed = true;
        else if (strcasecmp(parameter_value,"no")==0) use_send_failed = false;
        else log_error("Parameter value '%s' not recognized for parameter '%s'", parameter_value, "report_failed_message");
    }
    else if((strcasecmp(parameter_name, use_connection_ASPs_name()) == 0) || !parameter_set(parameter_name ,parameter_value)) {
        log_warning("HTTPmsg__PT::set_parameter(): Unsupported Test Port parameter: %s", parameter_name);
    }
    log_debug("leaving HTTPmsg__PT::set_parameter(%s, %s)", parameter_name, parameter_value);
}

void HTTPmsg__PT::Handle_Fd_Event(int fd,
    boolean is_readable, boolean is_writable, boolean is_error)
{
    log_debug("-------------- entering HTTPmsg__PT::Handle_Fd_Event() - event received on a connection");
    Handle_Socket_Event(fd, is_readable, is_writable, is_error);
    log_debug("leaving HTTPmsg__PT::Handle_Fd_Event()");
}

void HTTPmsg__PT::Handle_Timeout(double time_since_last_call)
{
    log_debug("entering HTTPmsg__PT::Handle_Timeout()");
    Handle_Timeout_Event(time_since_last_call);
    log_debug("leaving HTTPmsg__PT::Handle_Timeout()");
}

void HTTPmsg__PT::user_map(const char *system_port)
{
    log_debug("entering HTTPmsg__PT::user_map(%s)",system_port);
    if(TTCN_Logger::log_this_event(TTCN_DEBUG)) {
        if(!get_socket_debugging())
            log_warning("%s: to switch on HTTP test port debugging, set the '*.%s.http_debugging := \"yes\" in the port's parameters.", get_name(), get_name());
    }
    map_user();
    log_debug("leaving HTTPmsg__PT::user_map()");
}

void HTTPmsg__PT::user_unmap(const char *system_port)
{
  log_debug("entering HTTPmsg__PT::user_unmap(%s)",system_port);

  unmap_user();

  log_debug("leaving HTTPmsg__PT::user_unmap()");
}

void HTTPmsg__PT::user_start()
{
}

void HTTPmsg__PT::user_stop()
{
}

void HTTPmsg__PT::outgoing_send(const HTTPmsg__Types::Close& send_par)
{
    log_debug("entering HTTPmsg__PT::outgoing_send(Close)");

    if(send_par.client__id().ispresent())
        remove_client((int)send_par.client__id()());
    else
        remove_all_clients();

    log_debug("leaving HTTPmsg__PT::outgoing_send(Close)");
}

void HTTPmsg__PT::outgoing_send(const HTTPmsg__Types::Connect& send_par)
{
    log_debug("entering HTTPmsg__PT::outgoing_send(Connect)");

    adding_ssl_connection = send_par.use__ssl();
    adding_client_connection = true;

#ifndef AS_USE_SSL
    if(adding_ssl_connection)
    {
        log_error("%s: HTTP test port is not compiled to support SSL connections. Please check the User's Guide for instructions on compiling the HTTP test port with SSL support.", get_name());
    }
#endif

   int client_id = open_client_connection(send_par.hostname(),int2str((INTEGER)send_par.portnumber()),NULL,NULL);

    adding_ssl_connection = false;
    adding_client_connection = false;

    log_debug("leaving HTTPmsg__PT::outgoing_send(Connect),client_id: %d", client_id);
}

void HTTPmsg__PT::outgoing_send(const HTTPmsg__Types::Listen& send_par)
{
    log_debug("entering HTTPmsg__PT::outgoing_send(Listen)");

    server_use_ssl = send_par.use__ssl();

    if(server_use_ssl)
        {
    #ifndef AS_USE_SSL
            log_error("%s: HTTP test port is not compiled to support SSL connections. Please check the User's Guide for instructions on compiling the HTTP test port with SSL support.", get_name());
    #endif
        }

    if(send_par.local__hostname().ispresent())
		{

       	open_listen_port(send_par.local__hostname()(),int2str((INTEGER)send_par.portnumber()));

		}
    else
    {
        log_debug("using IN_ADDR_ANY as local host name");
        open_listen_port(NULL,int2str((INTEGER)send_par.portnumber()));

    }

    log_debug("leaving HTTPmsg__PT::outgoing_send(Listen)");

}

void HTTPmsg__PT::outgoing_send(const HTTPmsg__Types::Half__close& send_par)
{
    log_debug("entering HTTPmsg__PT::outgoing_send(Half_close)");

    if(send_par.client__id().ispresent())
        send_shutdown((int)send_par.client__id()());
    else
        send_shutdown();

    log_debug("leaving HTTPmsg__PT::outgoing_send(Half_close)");

}

void HTTPmsg__PT::outgoing_send(const HTTPmsg__Types::Shutdown& /*send_par*/)
{
    log_debug("entering HTTPmsg__PT::outgoing_send(Shutdown)");

    close_listen_port();

    log_debug("leaving HTTPmsg__PT::outgoing_send(Shutdown)");
}

void HTTPmsg__PT::outgoing_send(const HTTPmsg__Types::HTTPMessage& send_par)
{
    log_debug("entering HTTPmsg__PT::outgoing_send(HTTPMessage)");

    TTCN_Buffer snd_buf;
    int client_id = -1;
    last_msg = &send_par;
    
    switch(send_par.get_selection())
    {
        case HTTPmsg__Types::HTTPMessage::ALT_request:
        {
            if(send_par.request().client__id().ispresent())
                client_id = send_par.request().client__id()();
            break;
        }
        case HTTPmsg__Types::HTTPMessage::ALT_request__binary:
        {
            if(send_par.request__binary().client__id().ispresent())
                client_id = send_par.request__binary().client__id()();
            break;
        }
        case HTTPmsg__Types::HTTPMessage::ALT_response:
        {
            if(send_par.response().client__id().ispresent())
                client_id = send_par.response().client__id()();
            break;
        }
        case HTTPmsg__Types::HTTPMessage::ALT_response__binary:
        {
            if(send_par.response__binary().client__id().ispresent())
                client_id = send_par.response__binary().client__id()();
            break;
        }
        case HTTPmsg__Types::HTTPMessage::ALT_erronous__msg:
        {
            if(send_par.erronous__msg().client__id().ispresent())
                client_id = send_par.erronous__msg().client__id()();
            break;
        }
        default:
            TTCN_error("Unknown HTTP_Message type to encode and send!");
    }

    f_HTTP_encodeCommon(send_par, snd_buf);

    if(client_id >= 0)
        send_outgoing(snd_buf.get_data(), snd_buf.get_len(), client_id);
    else
        send_outgoing(snd_buf.get_data(), snd_buf.get_len());
    
    last_msg = NULL;
    log_debug("leaving HTTPmsg__PT::outgoing_send(HTTPMessage)");
}

void HTTPmsg__PT::report_unsent(int client_id, int /*msg_length*/, int /*sent_length*/, const unsigned char* /*msg*/, const char* /*error_text*/)
{
  if(use_send_failed  && last_msg){
    HTTPmsg__Types::Send__failed asp;
    asp.msg()=*last_msg;
    asp.already__half__closed()= (get_peer(client_id,true)->tcp_state) == CLOSE_WAIT ;
    
    incoming_message(asp);
  }
}


void HTTPmsg__PT::client_connection_opened(int client_id)
{
    log_debug("entering HTTPmsg__PT::client_connection_opened(%d)", client_id);

    if(use_notification_ASPs)
    {
        HTTPmsg__Types::Connect__result asp;
        asp.client__id() = client_id;
        incoming_message(asp);
    }
    else if(client_id < 0)
        log_error("Cannot connect to server");

    log_debug("leaving HTTPmsg__PT::client_connection_opened()");
}

void HTTPmsg__PT::listen_port_opened(int port_number)
{
  log_debug("entering HTTPmsg__PT::listen_port_opened(%d)", port_number);

  if(use_notification_ASPs)
  {
    HTTPmsg__Types::Listen__result asp;
    asp.portnumber() = port_number;
    incoming_message(asp);
  }
  else if(port_number < 0)
    log_error("Cannot listen at port");

  log_debug("leaving HTTPmsg__PT::listen_port_opened()");
}

void HTTPmsg__PT::message_incoming(const unsigned char* /*msg*/, int /*messageLength*/, int client_id)
{
    log_debug("entering HTTPmsg__PT::message_incoming()");

    TTCN_Buffer* buf_p = get_buffer(client_id);

    while(buf_p->get_read_len() > 0)
    {
        log_debug("HTTPmsg__PT::message_incoming(): decoding next message, len: %d", (int)buf_p->get_read_len());
        if(!HTTP_decode(buf_p, client_id))
            break;
    }

    log_debug("leaving HTTPmsg__PT::message_incoming()");
}

void HTTPmsg__PT::peer_half_closed(int client_id)
{
    log_debug("entering HTTPmsg__PT::peer_half_closed(client_id: %d)", client_id);

    TTCN_Buffer* buf_p = get_buffer(client_id);
    buf_p->rewind();
    while(buf_p->get_read_len() > 0)
    {
        log_debug("HTTPmsg__PT::remove_client(): decoding next message, len: %d", (int)buf_p->get_read_len());
        if(!HTTP_decode(buf_p, client_id,true))
            break;
    }

    HTTPmsg__Types::Half__close asp;
    asp.client__id() = client_id;
    incoming_message(asp);

    log_debug("leaving HTTPmsg__PT::peer_half_closed(client_id: %d)", client_id);
}

void HTTPmsg__PT::peer_disconnected(int client_id)
{
    log_debug("entering HTTPmsg__PT::peer_disconnected(client_id: %d)", client_id);

    if(use_notification_ASPs)
    {
        HTTPmsg__Types::Close asp;
        asp.client__id() = client_id;
        incoming_message(asp);
    }
    else Abstract_Socket::peer_disconnected(client_id);

    log_debug("leaving HTTPmsg__PT::peer_disconnected(client_id: %d)", client_id);
}

//void HTTPmsg__PT::peer_connected(int client_id, sockaddr_in& addr)

void HTTPmsg__PT::peer_connected(int client_id, const char * host, const int port)
{
    log_debug("entering HTTPmsg__PT::peer_connected(%d)", client_id);

    if(use_notification_ASPs)
    {
        HTTPmsg__Types::Client__connected asp;
        asp.hostname() = host;
        asp.portnumber() = port;
        asp.client__id() = client_id;

        incoming_message(asp);
    }
    else Abstract_Socket::peer_connected(client_id, host, port);

    log_debug("leaving HTTPmsg__PT::peer_connected()");
}

bool HTTPmsg__PT::add_user_data(int client_id)
{
    log_debug("entering HTTPmsg__PT::add_user_data(client_id: %d, use_ssl: %s)",
        client_id, (adding_client_connection && adding_ssl_connection) || (server_use_ssl && !adding_ssl_connection) ? "yes" : "no");

    set_server_mode(!adding_client_connection);

    if((adding_client_connection && !adding_ssl_connection) || (!adding_client_connection && !server_use_ssl))
    {
        log_debug("leaving HTTPmsg__PT::add_user_data() with returning Abstract_Socket::add_user_data()");
        return Abstract_Socket::add_user_data(client_id);
    }
    else
    {
#ifdef AS_USE_SSL
        log_debug("leaving HTTPmsg__PT::add_user_data() with returning SSL_Socket::add_user_data()");
        return SSL_Socket::add_user_data(client_id);
#else
        log_error("%s: HTTP test port is not compiled to support SSL connections. Please check the User's Guide for instructions on compiling the HTTP test port with SSL support.", get_name());
#endif
    }

    // Programming error in HTTPmsg__PT::add_user_data()
    return false;
}

bool HTTPmsg__PT::remove_user_data(int client_id)
{
    log_debug("entering HTTPmsg__PT::remove_user_data(client_id: %d", client_id);

#ifdef AS_USE_SSL
    if(get_user_data(client_id))
    {
        // INFO: it is assumed that only SSL_Socket assigns user data to each peer
        log_debug("leaving HTTPmsg__PT::remove_user_data() with returning SSL_Socket::remove_user_data()");
        return SSL_Socket::remove_user_data(client_id);
    }
#endif

    log_debug("leaving HTTPmsg__PT::remove_user_data() with returning Abstract_Socket::remove_user_data()");
    return Abstract_Socket::remove_user_data(client_id);
}

int HTTPmsg__PT::receive_message_on_fd(int client_id)
{
    log_debug("entering HTTPmsg__PT::receive_message_on_fd(client_id: %d)", client_id);

#ifdef AS_USE_SSL
    if(get_user_data(client_id))
    {
        // INFO: it is assumed that only SSL_Socket assigns user data to each peer
        log_debug("leaving HTTPmsg__PT::receive_message_on_fd() with returning SSL_Socket::receive_message_on_fd()");
        return SSL_Socket::receive_message_on_fd(client_id);
    }
#endif

    log_debug("leaving HTTPmsg__PT::receive_message_on_fd() with returning Abstract_Socket::receive_message_on_fd()");
    return Abstract_Socket::receive_message_on_fd(client_id);
}

void HTTPmsg__PT::remove_client(int client_id)
{
    log_debug("entering HTTPmsg__PT::remove_client(client_id: %d)", client_id);

    TTCN_Buffer* buf_p = get_buffer(client_id);

    while(buf_p->get_read_len() > 0)
    {
        log_debug("HTTPmsg__PT::remove_client(): decoding next message, len: %d", (int)buf_p->get_read_len());
        if(!HTTP_decode(buf_p, client_id,true))
            break;
    }

#ifdef AS_USE_SSL
    if(get_user_data(client_id))
    {
        // INFO: it is assumed that only SSL_Socket assigns user data to each peer
        log_debug("leaving HTTPmsg__PT::remove_client() with returning SSL_Socket::remove_client()");
        return SSL_Socket::remove_client(client_id);
    }
#endif

    log_debug("leaving HTTPmsg__PT::remove_client() with returning Abstract_Socket::remove_client()");
    return Abstract_Socket::remove_client(client_id);
}

int HTTPmsg__PT::send_message_on_fd(int client_id, const unsigned char * message_buffer, int length_of_message)
{
    log_debug("entering HTTPmsg__PT::send_message_on_fd(client_id: %d)", client_id);

#ifdef AS_USE_SSL
    if(get_user_data(client_id))
    {
        // INFO: it is assumed that only SSL_Socket assigns user data to each peer
        log_debug("leaving HTTPmsg__PT::send_message_on_fd() with returning SSL_Socket::send_message_on_fd()");
        return SSL_Socket::send_message_on_fd(client_id, message_buffer, length_of_message);
    }
#endif

    log_debug("leaving HTTPmsg__PT::send_message_on_fd() with returning Abstract_Socket::send_message_on_fd()");
    return Abstract_Socket::send_message_on_fd(client_id, message_buffer, length_of_message);
}

int HTTPmsg__PT::send_message_on_nonblocking_fd(int client_id, const unsigned char * message_buffer, int length_of_message)
{
    log_debug("entering HTTPmsg__PT::(client_id: %d)", client_id);

#ifdef AS_USE_SSL
    if(get_user_data(client_id))
    {
        // INFO: it is assumed that only SSL_Socket assigns user data to each peer
        log_debug("leaving HTTPmsg__PT::send_message_on_nonblocking_fd() with returning SSL_Socket::send_message_on_nonblocking_fd()");
        return SSL_Socket::send_message_on_nonblocking_fd(client_id, message_buffer, length_of_message);
    }
#endif

    log_debug("leaving HTTPmsg__PT::send_message_on_nonblocking_fd() with returning Abstract_Socket::send_message_on_nonblocking_fd()");
    return Abstract_Socket::send_message_on_nonblocking_fd(client_id, message_buffer, length_of_message);
}

// HTTP specific functions

// replaced by f_HTTP_encodeCommon:
// void HTTPmsg__PT::HTTP_encode(const HTTPmsg__Types::HTTPMessage& msg, TTCN_Buffer& buf)
// {
//   f_HTTP_encodeCommon( msg, buf);
// }

//Encodes msg type of "HTTPMessage" into buffer
void f_HTTP_encodeCommon(const HTTPmsg__Types::HTTPMessage& msg, TTCN_Buffer& buf)
{
    buf.clear();
    if( msg.get_selection() == HTTPmsg__Types::HTTPMessage::ALT_erronous__msg )
        buf.put_cs(msg.erronous__msg().msg());
    else
    {
        const HTTPmsg__Types::HeaderLines* header = NULL;
        const HTTPmsg__Types::HTTPRequest* request = NULL;
        const HTTPmsg__Types::HTTPResponse* response = NULL;
        const HTTPmsg__Types::HTTPRequest__binary__body* request_binary = NULL;
        const HTTPmsg__Types::HTTPResponse__binary__body* response_binary = NULL;
        const CHARSTRING* body = NULL;
        const OCTETSTRING* body_binary = NULL;

        if(msg.get_selection() == HTTPmsg__Types::HTTPMessage::ALT_request)
        {
            request = &msg.request();
            header = &request->header();
            body = &request->body();
            buf.put_cs(request->method());
            buf.put_c(' ');
            buf.put_cs(request->uri());
            buf.put_cs(" HTTP/");
            buf.put_cs(int2str(request->version__major()));
            buf.put_c('.');
            buf.put_cs(int2str(request->version__minor()));
            buf.put_cs("\r\n");
        }
        else if(msg.get_selection() == HTTPmsg__Types::HTTPMessage::ALT_response)
        {
            response = &msg.response();
            header = &response->header();
            body = &response->body();
            buf.put_cs("HTTP/");
            buf.put_cs(int2str(response->version__major()));
            buf.put_c('.');
            buf.put_cs(int2str(response->version__minor()));
            buf.put_c(' ');
            buf.put_cs(int2str(response->statuscode()));
            buf.put_c(' ');
            buf.put_cs(response->statustext());
            buf.put_cs("\r\n");
        }
        else if(msg.get_selection() == HTTPmsg__Types::HTTPMessage::ALT_request__binary)
        {
            request_binary = &msg.request__binary();
            header = &request_binary->header();
            body_binary = &request_binary->body();
            buf.put_cs(request_binary->method());
            buf.put_c(' ');
            buf.put_cs(request_binary->uri());
            buf.put_cs(" HTTP/");
            buf.put_cs(int2str(request_binary->version__major()));
            buf.put_c('.');
            buf.put_cs(int2str(request_binary->version__minor()));
            buf.put_cs("\r\n");
        }
        else if(msg.get_selection() == HTTPmsg__Types::HTTPMessage::ALT_response__binary)
        {
            response_binary = &msg.response__binary();
            header = &response_binary->header();
            body_binary = &response_binary->body();
            buf.put_cs("HTTP/");
            buf.put_cs(int2str(response_binary->version__major()));
            buf.put_c('.');
            buf.put_cs(int2str(response_binary->version__minor()));
            buf.put_c(' ');
            buf.put_cs(int2str(response_binary->statuscode()));
            buf.put_c(' ');
            buf.put_cs(response_binary->statustext());
            buf.put_cs("\r\n");
        }

        for( int i = 0; i < header->size_of(); i++ )
        {
            buf.put_cs((*header)[i].header__name());
            buf.put_cs(": ");
            buf.put_cs((*header)[i].header__value());
            buf.put_cs("\r\n");
        }

        buf.put_cs("\r\n");

        if(body && body->lengthof() > 0)
        {
            buf.put_cs(*body);
        }
        else if(body_binary && body_binary->lengthof() > 0)
        {
            buf.put_os(*body_binary);
        }
    }
}

bool HTTPmsg__PT::HTTP_decode(TTCN_Buffer* buffer, const int client_id, const bool connection_closed)
{

  //HTTPmsg__Types::HTTPMessage * msg = new HTTPmsg__Types::HTTPMessage();

  HTTPmsg__Types::HTTPMessage msg;

  if(f_HTTP_decodeCommon(buffer, msg, connection_closed, get_socket_debugging(), test_port_type, test_port_name ))
  {
    TTCN_Logger::log(TTCN_DEBUG,"HTTPmsg__PT::HTTP_decode, before calling incoming_message");
    f_setClientId(msg,client_id);
    incoming_message(msg);
    TTCN_Logger::log(TTCN_DEBUG,"HTTPmsg__PT::HTTP_decode, after calling incoming_message");
    return true;
  }
  return false;
}

void f_setClientId( HTTPmsg__Types::HTTPMessage& msg, const int client_id)
{
  switch(msg.get_selection())
  {
    case HTTPmsg__Types::HTTPMessage::ALT_request:
    {
      msg.request().client__id()=client_id;
      break;
    }
    case HTTPmsg__Types::HTTPMessage::ALT_request__binary:
    {
      msg.request__binary().client__id()=client_id;
      break;
    }
    case HTTPmsg__Types::HTTPMessage::ALT_response:
    {
      msg.response().client__id()=client_id;
      break;
    }
    case HTTPmsg__Types::HTTPMessage::ALT_response__binary:
    {
      msg.response__binary().client__id()=client_id;
      break;
    }
    case HTTPmsg__Types::HTTPMessage::ALT_erronous__msg:  //is this case redundant code(?)
    {
      msg.erronous__msg().client__id()=OMIT_VALUE;
      break;
    }
    default:
      break;
  }//switch
  return;
}//f_setClientId

//
// returns with true if the buffer is not empty and it contain valid message
// Postcondition: if buffer contains valid message, msg will contain the first decoded HTTP message, the decoded part will be removed from the buffer
bool f_HTTP_decodeCommon( TTCN_Buffer* buffer, HTTPmsg__Types::HTTPMessage& msg, const bool connection_closed,
    const bool socket_debugging, const char *test_port_type, const char *test_port_name)
{

    TTCN_Logger::log(TTCN_DEBUG, "starting f_HTTP_decodeCommon ");
    if(buffer->get_read_len() <= 0)
        return FALSE;

    buffer->rewind();

    Decoding_Params decoding_params;
    decoding_params.non_persistent_connection = FALSE;
    decoding_params.chunked_body = FALSE;
    decoding_params.content_length = -1;
    decoding_params.error = FALSE;
    decoding_params.isMessage = TRUE;

    if (TTCN_Logger::log_this_event(TTCN_DEBUG))
    {
        if( test_port_name!= NULL)
          TTCN_Logger::log(TTCN_DEBUG, "%s DECODER: <%s>\n", test_port_name,
            (const char*)CHARSTRING(buffer->get_read_len(), (const char*)buffer->get_read_data()));
        else
          TTCN_Logger::log(TTCN_DEBUG, "DECODER: <%s>\n",
            (const char*)CHARSTRING(buffer->get_read_len(), (const char*)buffer->get_read_data()));
    }

    CHARSTRING first;
    bool isResponse;

    // Decoding the first line

    switch(get_line(buffer, first, false))
    {
    case TRUE: // The first line is available
        {
            //HTTPmsg__Types::HTTPMessage msg;
            HTTPmsg__Types::HeaderLines header = NULL_VALUE;
            OCTETSTRING body=OCTETSTRING(0, (const unsigned char*)"");
            const char *cc_first = (const char *)first;
            //fprintf(stderr, "first: %s\n", cc_first);
            int version__major, version__minor, statusCode;

            char* method_name;
            const char* pos = strchr(cc_first, ' ');
            if(pos == NULL)
            {
                TTCN_Logger::log(TTCN_DEBUG, "could not find space in the first line of response: <%s>", cc_first);
                decoding_params.isMessage = FALSE;
                decoding_params.error = TRUE;
                break;
            }
            method_name = (char*)Malloc(pos - cc_first + 1);
            strncpy(method_name, cc_first, pos - cc_first);
            method_name[pos - cc_first] = '\0';

            char* stext = (char*)Malloc(strlen(cc_first));
            stext[0] = '\0';
	    
            TTCN_Logger::log(TTCN_DEBUG, "method_name: <%s>", method_name);
            if(strncasecmp(method_name, "HTTP/", 5) == 0)
            {
                // The first line contains a response like HTTP/1.1 200 OK
                isResponse = true;

                if(sscanf(cc_first, "HTTP/%d.%d %d %[^\r]", &version__major, &version__minor,
                          &statusCode, stext) < 3)
                {
                    decoding_params.isMessage = FALSE;
                    decoding_params.error = TRUE;
            Free(method_name);
            Free(stext);
                    break;
                }
                if (version__minor == 0)
                    decoding_params.non_persistent_connection = TRUE;
            }
            else
            {
                isResponse = false;
                // The first line contains a request
                // like "POST / HTTP/1.0"
                if(sscanf(pos + 1, "%s HTTP/%d.%d",
                          stext, &version__major, &version__minor ) != 3)
                {
                    decoding_params.isMessage = FALSE;
                    decoding_params.error = TRUE;
            Free(method_name);
            Free(stext);
                    break;
                }
            }

            // Additional header lines
            TTCN_Logger::log(TTCN_DEBUG, "Decoding the headers");
            HTTP_decode_header(buffer, header, decoding_params, socket_debugging, isResponse, test_port_type, test_port_name);
            TTCN_Logger::log(TTCN_DEBUG, "Headers decoded. %s headers.", decoding_params.isMessage ? "Valid" : "Invalid");

            if(isResponse && decoding_params.content_length==-1){
              if( (statusCode>99 && statusCode <200) || statusCode==204 || statusCode==304 ) decoding_params.content_length=0;
            }

            if(decoding_params.isMessage)
                HTTP_decode_body(buffer, body, decoding_params, connection_closed, socket_debugging, test_port_type, test_port_name);

            if(decoding_params.isMessage)
            {
                TTCN_Logger::log(TTCN_DEBUG, "Message successfully decoded");
                bool foundBinaryCharacter = false;

                int len = body.lengthof();
                const unsigned char* ptr = (const unsigned char*)body;
                for(int i = 0; i < len && !foundBinaryCharacter; i++)
                {
                    if(!isascii(ptr[i]))
                        foundBinaryCharacter = true;
                }
                if(foundBinaryCharacter)
                    TTCN_Logger::log(TTCN_DEBUG, "Binary data found");
                if(isResponse)
                {
                  if(foundBinaryCharacter)
                  {
                    HTTPmsg__Types::HTTPResponse__binary__body& response_binary = msg.response__binary();
                    response_binary.client__id() = OMIT_VALUE;
                    response_binary.version__major() = version__major;
                    response_binary.version__minor() = version__minor;
                    response_binary.statuscode() = statusCode;
                    if(strlen(stext) > 0)
                        response_binary.statustext() = CHARSTRING(stext);
                    else
                        response_binary.statustext() = "";
                    response_binary.header() = header;
                    response_binary.body() = body;
                  }
                  else
                  {
                    HTTPmsg__Types::HTTPResponse& response = msg.response();
                    response.client__id() = OMIT_VALUE;
                    response.version__major() = version__major;
                    response.version__minor() = version__minor;
                    response.statuscode() = statusCode;
                    if(strlen(stext) > 0)
                        response.statustext() = CHARSTRING(stext);
                    else
                        response.statustext() = "";
                    response.header() = header;
                    response.body() = oct2char(body);
                  }
                }
                else
                {
                  if(foundBinaryCharacter)
                  {
                    HTTPmsg__Types::HTTPRequest__binary__body& request_binary = msg.request__binary();
                    request_binary.client__id() = OMIT_VALUE;
                    request_binary.method() = CHARSTRING(method_name);
                    request_binary.uri() = CHARSTRING(stext);
                    request_binary.version__major() = version__major;
                    request_binary.version__minor() = version__minor;
                    request_binary.header() = header;
                    request_binary.body() = body;
                  }
                  else
                  {
                    HTTPmsg__Types::HTTPRequest& request = msg.request();
                    request.client__id() = OMIT_VALUE;
                    request.method() = CHARSTRING(method_name);
                    request.uri() = CHARSTRING(stext);
                    request.version__major() = version__major;
                    request.version__minor() = version__minor;
                    request.header() = header;
                    request.body() = oct2char(body);
                  }
                }
                //incoming_message(msg); <- outer function calls if necessary
            }
            Free(method_name);
            Free(stext);
        }
        break;
    case BUFFER_CRLF:
    case BUFFER_FAIL:
        decoding_params.error = TRUE;
    case FALSE:
        decoding_params.isMessage = FALSE;
    }

    if(decoding_params.error)
    {

        if(buffer->get_read_len() > 0)
          msg.erronous__msg().msg() = CHARSTRING(buffer->get_read_len(), (const char*)buffer->get_read_data());
        else
          msg.erronous__msg().msg() = "The previous message is erronous.";
        msg.erronous__msg().client__id() = OMIT_VALUE;
        //incoming_message(msg);
        buffer->clear();
        decoding_params.isMessage = TRUE;
    }

    if(decoding_params.isMessage)
    {
        buffer->cut();
    }

    return decoding_params.isMessage;
}

void HTTP_decode_header(TTCN_Buffer* buffer, HTTPmsg__Types::HeaderLines& headers, Decoding_Params& decoding_params,
    const bool socket_debugging, const bool resp, const char *test_port_type, const char *test_port_name)
{
    CHARSTRING cstr;
    const char* separator;
    char* header_name = NULL;
    bool length_received = false;

    for(int i = 0; ; i++)
    {
        switch(get_line(buffer, cstr, true))
        {
        case TRUE:
            {
                char h[cstr.lengthof() + 1];
                strcpy(h, (const char*)cstr);
                separator = strchr(h, ':');
                if(separator)
                {
                    header_name = (char*)Realloc(header_name, separator - h + 1);
                    strncpy(header_name, h, separator - h);
                    header_name[separator - h] = '\0';
                    separator++;
                    while(*separator && isspace(separator[0]))
                        separator++;
                    char* end = h + strlen(h);
                    while(isspace((end - 1)[0]))
                    {
                        end--;
                        *end = '\0';
                    }
                    headers[i] = HTTPmsg__Types::HeaderLine(header_name, separator);
                    HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name, "+Header line: <%s: %s>", header_name, separator);

                    if(!strcasecmp(header_name, "Content-Length"))
                        { sscanf(separator, "%d", &decoding_params.content_length); length_received=true;}
                    else if(!strcasecmp(header_name, "Connection") && !strcasecmp(separator, "close"))
                        decoding_params.non_persistent_connection = TRUE;
                    else if(!strcasecmp(header_name, "Connection") && !strcasecmp(separator, "keep-alive"))
                        decoding_params.non_persistent_connection = FALSE;
                    else if(!strcasecmp(header_name, "Transfer-Encoding") && !strcasecmp(separator, "chunked"))
                        decoding_params.chunked_body = TRUE;

                }
                continue;
            }
        case BUFFER_FAIL:
            HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name, "BUFFER_FAIL in HTTP_decode_header!");
            HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name, "whole bufer now: <%s>", (const char*)buffer->get_data());
            log_to_hexa(buffer);
            decoding_params.error = TRUE;
        case FALSE:
            decoding_params.isMessage = FALSE;
        case BUFFER_CRLF:
            break;
        }
        break;
    }
    if(decoding_params.isMessage && !resp && !length_received && !decoding_params.chunked_body) decoding_params.content_length=0;
    Free(header_name);
}

void HTTP_decode_body(TTCN_Buffer* buffer, OCTETSTRING& body, Decoding_Params& decoding_params, const bool connection_closed,
    const bool socket_debugging, const char *test_port_type, const char *test_port_name)
{
    if(buffer->get_read_len() > 0)
        HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name,  "Decoding body, buffer length: %d", buffer->get_read_len());

    if (decoding_params.chunked_body)
    {
        HTTP_decode_chunked_body(buffer, body, decoding_params, socket_debugging, test_port_type, test_port_name);
        HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name,  "--------- After chunked body decoding:");
        HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name,  "--------- non_persistent_connection: %s",  decoding_params.non_persistent_connection ? "yes" : "no");
        HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name,  "--------- chunked_body: %s",  decoding_params.chunked_body ? "yes" : "no");
        HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name,  "--------- content_length: %d",  decoding_params.content_length);
        HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name,  "--------- error: %s",  decoding_params.error ? "yes" : "no");
        HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name,  "--------- isMessage: %s",  decoding_params.isMessage ? "yes" : "no");

    }
    else if(decoding_params.content_length >= 0)
    {
        HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name,  "lengthof body: %d, content_length given: %d", buffer->get_read_len(), decoding_params.content_length);
        if(buffer->get_read_len() >= (unsigned)decoding_params.content_length)
        {
            body = OCTETSTRING(decoding_params.content_length, buffer->get_read_data());
            buffer->set_pos(buffer->get_pos() + decoding_params.content_length);
        }
        else
        {
            decoding_params.isMessage = FALSE;
            HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name,  "The decoder's body length %d is less than the Content_length in the message header %d; The HTTP port is waiting for additional data.", buffer->get_read_len(), decoding_params.content_length);
            buffer->set_pos(buffer->get_pos() + buffer->get_read_len());
        }
    }
    else if(connection_closed)
    {
       /* if(buffer->get_read_len() >= 0)*/ // Always true
        {
            body = OCTETSTRING(buffer->get_read_len(), buffer->get_read_data());
            buffer->set_pos(buffer->get_pos() + buffer->get_read_len());
        }
    } else {
            decoding_params.isMessage = FALSE;
            HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name,  "The HTTP port is waiting for additional data.");
            buffer->set_pos(buffer->get_pos() + buffer->get_read_len());
    }
}

void HTTP_decode_chunked_body(TTCN_Buffer* buffer, OCTETSTRING& body, Decoding_Params& decoding_params,
    const bool socket_debugging, const char *test_port_type, const char *test_port_name)
{
    OCTETSTRING chunk;
    CHARSTRING line;
    unsigned int chunk_size = 1;

    while(chunk_size > 0)
    {
        switch(get_line(buffer, line, false))
        {
            case TRUE:
                HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name,  "line: <%s>", (const char*)line);
                if(sscanf((const char *)line, "%x", &chunk_size) != 1)
                {
                    HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name,  "No chunksize found");
                    body = body + OCTETSTRING(line.lengthof(), (const unsigned char*)(const char*)line);
                    chunk_size = 0;
                    decoding_params.error = TRUE;
                }
                else
                {
                    if(chunk_size == 0)
                    {
                        HTTPmsg__Types::log_debug(socket_debugging, test_port_type, test_port_name, "chunk_size 0 -> closing chunk");