2 * Copyright (C) 2010 Martin Willi
3 * Copyright (C) 2010 revosec AG
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 #include "tls_socket.h"
22 typedef struct private_tls_socket_t private_tls_socket_t
;
23 typedef struct private_tls_application_t private_tls_application_t
;
25 struct private_tls_application_t
{
28 * Implements tls_application layer.
30 tls_application_t application
;
33 * Chunk of data to send
38 * Chunk of data received
44 * Private data of an tls_socket_t object.
46 struct private_tls_socket_t
{
49 * Public tls_socket_t interface.
54 * TLS application implementation
56 private_tls_application_t app
;
64 * Underlying OS socket
69 METHOD(tls_application_t
, process
, status_t
,
70 private_tls_application_t
*this, bio_reader_t
*reader
)
74 if (!reader
->read_data(reader
, reader
->remaining(reader
), &data
))
78 this->in
= chunk_cat("mc", this->in
, data
);
82 METHOD(tls_application_t
, build
, status_t
,
83 private_tls_application_t
*this, bio_writer_t
*writer
)
87 writer
->write_data(writer
, this->out
);
88 this->out
= chunk_empty
;
95 * TLS data exchange loop
97 static bool exchange(private_tls_socket_t
*this, bool wr
)
103 for (round
= 0; TRUE
; round
++)
108 switch (this->tls
->build(this->tls
, buf
, &len
, NULL
))
112 len
= write(this->fd
, buf
, len
);
127 if (this->app
.out
.len
== 0)
128 { /* all data written */
134 if (this->app
.in
.len
)
135 { /* some data received */
139 { /* did some handshaking, return empty chunk to not block */
143 len
= read(this->fd
, buf
, sizeof(buf
));
148 if (this->tls
->process(this->tls
, buf
, len
) != NEED_MORE
)
155 METHOD(tls_socket_t
, read_
, bool,
156 private_tls_socket_t
*this, chunk_t
*buf
)
158 if (exchange(this, FALSE
))
161 this->app
.in
= chunk_empty
;
167 METHOD(tls_socket_t
, write_
, bool,
168 private_tls_socket_t
*this, chunk_t buf
)
171 if (exchange(this, TRUE
))
178 METHOD(tls_socket_t
, get_fd
, int,
179 private_tls_socket_t
*this)
184 METHOD(tls_socket_t
, destroy
, void,
185 private_tls_socket_t
*this)
187 this->tls
->destroy(this->tls
);
188 free(this->app
.in
.ptr
);
195 tls_socket_t
*tls_socket_create(bool is_server
, identification_t
*server
,
196 identification_t
*peer
, int fd
, tls_cache_t
*cache
)
198 private_tls_socket_t
*this;
211 .destroy
= (void*)nop
,
217 this->tls
= tls_create(is_server
, server
, peer
, TLS_PURPOSE_GENERIC
,
218 &this->app
.application
, cache
);
225 return &this->public;