/*
 *      base_io.cpp
 *
 *      Copyright 2009 Sebastian Wankerl <far_away@online.de>
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program 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 General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */


#include "base_io.hpp"

base_io::base_io (const std::string &u, const std::string &pw, const std::string &server, int port, bool s)  :  	user (u),
																													password (pw),
																													ssl(s)
{
    signal(SIGPIPE, SIG_IGN);

    st = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (st == -1)
        throw std::runtime_error ("socket () failed");

    service.sin_family = AF_INET;
    service.sin_port = htons (port);
    service.sin_family = AF_INET;

    hostent *host = gethostbyname (server.c_str ());
    if (host == 0)
        throw std::runtime_error ("Couldn't connect to the server");

    char **p = host->h_addr_list;
    do {
        if(*p == 0)
            throw std::runtime_error ("Couldn't connect to the server");;

        service.sin_addr.s_addr = *reinterpret_cast<unsigned long*>(*p);
        ++p;
        result = connect(st, reinterpret_cast<sockaddr*>(&service), sizeof(service));
    }
    while(result == -1);

	if(ssl) {
		const char *err;
		gnutls_global_init ();

		gnutls_certificate_allocate_credentials (&xcred);
		gnutls_certificate_set_x509_trust_file (xcred, "ca.pem", GNUTLS_X509_FMT_PEM);
	  	gnutls_init (&session, GNUTLS_CLIENT);

	  	int ret = gnutls_priority_set_direct (session, "PERFORMANCE", &err);
	  	if (ret < 0) {
			if (ret == GNUTLS_E_INVALID_REQUEST) {
		  		fprintf (stderr, "Syntax error at: %s\n", err);
			}
		  exit (1);
		}

	  	gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred);
		gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) st);

		ret = gnutls_handshake (session);
        if (ret < 0) {
            gnutls_perror(ret);
            throw std::runtime_error ("Handshake failed");
        }
	}
}

base_io::~base_io () {
	if(ssl) {
		gnutls_bye(session, GNUTLS_SHUT_RDWR);
		gnutls_deinit (session);
  		gnutls_certificate_free_credentials (xcred);
  		gnutls_global_deinit ();
	}
    result = close (st);
    if (result == 1)
        throw std::runtime_error ("close () failed");
}

void base_io::send_request (const std::string &m) {
    unsigned sent = 0;
    const char *msg = m.c_str ();
    const unsigned size = m.size ();
    do {
        result = ssl ? gnutls_record_send (session, msg, size - sent) : send (st, msg + sent, size - sent, 0); // either through ssl or standard socket
        if (result < 0)
            throw std::runtime_error ("send () failed");
        sent += result;
    } while (sent < size);
}

std::string base_io::split_headers () {
	std::string tags [] = {"From: ", "Subject: "};
	std::string raw_header, worked_headers;
	int step = 0;
	while (get_header(raw_header, step)) {
		for (int i = 0; i < 2; ++i) {

			int tag = raw_header.find(tags[i]);
			int len = tags[i].length();

			worked_headers += "<i>";
			worked_headers += raw_header.substr(tag, len);
			worked_headers += "</i>";
			worked_headers += raw_header.substr(tag + len, raw_header.find("\r\n", tag) - (tag + len) + 1);
			worked_headers += i == 1 ? "<tr><tr>" : "<tr>";
		}
		set_unred(step);
		++step;
	}
	return worked_headers;
}
