| 1 |
#ifndef H_WINSOCK /* -*- mode: c++ -*- */ |
| 2 |
/* |
| 3 |
* Copyright (C) 2009 TSUBAKIMOTO Hiroya <zorac@4000do.co.jp> |
| 4 |
* |
| 5 |
* This software comes with ABSOLUTELY NO WARRANTY; for details of |
| 6 |
* the license terms, see the LICENSE.txt file included with the program. |
| 7 |
*/ |
| 8 |
#define H_WINSOCK |
| 9 |
|
| 10 |
#include <exception> |
| 11 |
#include <string> |
| 12 |
#include <winsock2.h> |
| 13 |
#include <ws2tcpip.h> |
| 14 |
#define SECURITY_WIN32 |
| 15 |
#include <security.h> |
| 16 |
#include <schannel.h> |
| 17 |
|
| 18 |
using namespace std; |
| 19 |
|
| 20 |
// winsock - winsock handler |
| 21 |
class winsock { |
| 22 |
typedef int (WSAAPI *_get_t)(const char*, const char*, |
| 23 |
const struct addrinfo*, struct addrinfo**); |
| 24 |
typedef void (WSAAPI *_free_t)(struct addrinfo*); |
| 25 |
static _get_t _get; |
| 26 |
static _free_t _free; |
| 27 |
public: |
| 28 |
winsock(); |
| 29 |
~winsock() { WSACleanup(); } |
| 30 |
static struct addrinfo* getaddrinfo(const string& host, const string& port); |
| 31 |
static void freeaddrinfo(struct addrinfo* info) { _free(info); } |
| 32 |
public: |
| 33 |
// tls - transport layer security |
| 34 |
class tls { |
| 35 |
CredHandle _cred; |
| 36 |
CtxtHandle _ctx; |
| 37 |
SecPkgContext_StreamSizes _sizes; |
| 38 |
bool _avail; |
| 39 |
string _readq; |
| 40 |
string::size_type _rest; |
| 41 |
string _extra; |
| 42 |
struct buf { |
| 43 |
char* data; |
| 44 |
buf() : data(NULL) {} |
| 45 |
~buf() { delete [] data; } |
| 46 |
char* operator()(size_t n) |
| 47 |
{ delete [] data, data = NULL; return data = new char[n]; } |
| 48 |
} _buf; |
| 49 |
static string _emsg(SECURITY_STATUS ss); |
| 50 |
SECURITY_STATUS _ok(SECURITY_STATUS ss) const; |
| 51 |
SECURITY_STATUS _token(SecBufferDesc* inb = NULL); |
| 52 |
size_t _copyextra(size_t i, size_t size); |
| 53 |
public: |
| 54 |
tls(DWORD proto = SP_PROT_SSL3 | SP_PROT_TLS1); |
| 55 |
virtual ~tls(); |
| 56 |
void connect(); |
| 57 |
void shutdown(); |
| 58 |
size_t read(char* buf, size_t size); |
| 59 |
size_t write(const char* data, size_t size); |
| 60 |
protected: |
| 61 |
virtual size_t _recv(char* buf, size_t size) = 0; |
| 62 |
virtual size_t _send(const char* data, size_t size) = 0; |
| 63 |
}; |
| 64 |
|
| 65 |
// error - exception type |
| 66 |
class error : public exception { |
| 67 |
string _msg; |
| 68 |
public: |
| 69 |
error() : _msg(emsg()) {} |
| 70 |
error(const string& msg) : _msg(msg) {} |
| 71 |
~error() throw() {} |
| 72 |
const char* what() const throw() { return _msg.c_str(); } |
| 73 |
static string emsg(); |
| 74 |
}; |
| 75 |
}; |
| 76 |
|
| 77 |
#endif |