source: trunk/library/net.c @ 1271

Revision 1271, 8.5 KB checked in by paul, 10 days ago (diff)
  • Updated to support NetBSD
Line 
1/*
2 *  TCP networking functions
3 *
4 *  Copyright (C) 2006-2010, Brainspark B.V.
5 *
6 *  This file is part of PolarSSL (http://www.polarssl.org)
7 *  Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
8 *
9 *  All rights reserved.
10 *
11 *  This program is free software; you can redistribute it and/or modify
12 *  it under the terms of the GNU General Public License as published by
13 *  the Free Software Foundation; either version 2 of the License, or
14 *  (at your option) any later version.
15 *
16 *  This program is distributed in the hope that it will be useful,
17 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
18 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 *  GNU General Public License for more details.
20 *
21 *  You should have received a copy of the GNU General Public License along
22 *  with this program; if not, write to the Free Software Foundation, Inc.,
23 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 */
25
26#include "polarssl/config.h"
27
28#if defined(POLARSSL_NET_C)
29
30#include "polarssl/net.h"
31
32#if defined(_WIN32) || defined(_WIN32_WCE)
33
34#include <winsock2.h>
35#include <windows.h>
36
37#if defined(_WIN32_WCE)
38#pragma comment( lib, "ws2.lib" )
39#else
40#pragma comment( lib, "ws2_32.lib" )
41#endif
42
43#define read(fd,buf,len)        recv(fd,(char*)buf,(int) len,0)
44#define write(fd,buf,len)       send(fd,(char*)buf,(int) len,0)
45#define close(fd)               closesocket(fd)
46
47static int wsa_init_done = 0;
48
49#else
50
51#include <sys/types.h>
52#include <sys/socket.h>
53#include <netinet/in.h>
54#include <arpa/inet.h>
55#include <sys/time.h>
56#include <unistd.h>
57#include <signal.h>
58#include <fcntl.h>
59#include <netdb.h>
60#include <errno.h>
61
62#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
63#include <sys/endian.h>
64#elif defined(__APPLE__)
65#include <machine/endian.h>
66#elif defined(sun)
67#include <sys/isa_defs.h>
68#else
69#include <endian.h>
70#endif
71
72#endif
73
74#include <stdlib.h>
75#include <stdio.h>
76#include <time.h>
77
78/*
79 * htons() is not always available.
80 * By default go for LITTLE_ENDIAN variant. Otherwise hope for _BYTE_ORDER and __BIG_ENDIAN
81 * to help determine endianess.
82 */
83#if defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && __BYTE_ORDER == __BIG_ENDIAN
84#define POLARSSL_HTONS(n) (n)
85#else
86#define POLARSSL_HTONS(n) (((((unsigned short)(n) & 0xFF)) << 8) | (((unsigned short)(n) & 0xFF00) >> 8))
87#endif
88
89unsigned short net_htons(unsigned short n);
90#define net_htons(n) POLARSSL_HTONS(n)
91
92/*
93 * Initiate a TCP connection with host:port
94 */
95int net_connect( int *fd, const char *host, int port )
96{
97    struct sockaddr_in server_addr;
98    struct hostent *server_host;
99
100#if defined(_WIN32) || defined(_WIN32_WCE)
101    WSADATA wsaData;
102
103    if( wsa_init_done == 0 )
104    {
105        if( WSAStartup( MAKEWORD(2,0), &wsaData ) == SOCKET_ERROR )
106            return( POLARSSL_ERR_NET_SOCKET_FAILED );
107
108        wsa_init_done = 1;
109    }
110#else
111    signal( SIGPIPE, SIG_IGN );
112#endif
113
114    if( ( server_host = gethostbyname( host ) ) == NULL )
115        return( POLARSSL_ERR_NET_UNKNOWN_HOST );
116
117    if( ( *fd = socket( AF_INET, SOCK_STREAM, IPPROTO_IP ) ) < 0 )
118        return( POLARSSL_ERR_NET_SOCKET_FAILED );
119
120    memcpy( (void *) &server_addr.sin_addr,
121            (void *) server_host->h_addr,
122                     server_host->h_length );
123
124    server_addr.sin_family = AF_INET;
125    server_addr.sin_port   = net_htons( port );
126
127    if( connect( *fd, (struct sockaddr *) &server_addr,
128                 sizeof( server_addr ) ) < 0 )
129    {
130        close( *fd );
131        return( POLARSSL_ERR_NET_CONNECT_FAILED );
132    }
133
134    return( 0 );
135}
136
137/*
138 * Create a listening socket on bind_ip:port
139 */
140int net_bind( int *fd, const char *bind_ip, int port )
141{
142    int n, c[4];
143    struct sockaddr_in server_addr;
144
145#if defined(_WIN32) || defined(_WIN32_WCE)
146    WSADATA wsaData;
147
148    if( wsa_init_done == 0 )
149    {
150        if( WSAStartup( MAKEWORD(2,0), &wsaData ) == SOCKET_ERROR )
151            return( POLARSSL_ERR_NET_SOCKET_FAILED );
152
153        wsa_init_done = 1;
154    }
155#else
156    signal( SIGPIPE, SIG_IGN );
157#endif
158
159    if( ( *fd = socket( AF_INET, SOCK_STREAM, IPPROTO_IP ) ) < 0 )
160        return( POLARSSL_ERR_NET_SOCKET_FAILED );
161
162    n = 1;
163    setsockopt( *fd, SOL_SOCKET, SO_REUSEADDR,
164                (const char *) &n, sizeof( n ) );
165
166    server_addr.sin_addr.s_addr = INADDR_ANY;
167    server_addr.sin_family      = AF_INET;
168    server_addr.sin_port        = net_htons( port );
169
170    if( bind_ip != NULL )
171    {
172        memset( c, 0, sizeof( c ) );
173        sscanf( bind_ip, "%d.%d.%d.%d", &c[0], &c[1], &c[2], &c[3] );
174
175        for( n = 0; n < 4; n++ )
176            if( c[n] < 0 || c[n] > 255 )
177                break;
178
179        if( n == 4 )
180            server_addr.sin_addr.s_addr =
181                ( (unsigned long) c[0] << 24 ) |
182                ( (unsigned long) c[1] << 16 ) |
183                ( (unsigned long) c[2] <<  8 ) |
184                ( (unsigned long) c[3]       );
185    }
186
187    if( bind( *fd, (struct sockaddr *) &server_addr,
188              sizeof( server_addr ) ) < 0 )
189    {
190        close( *fd );
191        return( POLARSSL_ERR_NET_BIND_FAILED );
192    }
193
194    if( listen( *fd, POLARSSL_NET_LISTEN_BACKLOG ) != 0 )
195    {
196        close( *fd );
197        return( POLARSSL_ERR_NET_LISTEN_FAILED );
198    }
199
200    return( 0 );
201}
202
203/*
204 * Check if the current operation is blocking
205 */
206static int net_is_blocking( void )
207{
208#if defined(_WIN32) || defined(_WIN32_WCE)
209    return( WSAGetLastError() == WSAEWOULDBLOCK );
210#else
211    switch( errno )
212    {
213#if defined EAGAIN
214        case EAGAIN:
215#endif
216#if defined EWOULDBLOCK && EWOULDBLOCK != EAGAIN
217        case EWOULDBLOCK:
218#endif
219            return( 1 );
220    }
221    return( 0 );
222#endif
223}
224
225/*
226 * Accept a connection from a remote client
227 */
228int net_accept( int bind_fd, int *client_fd, void *client_ip )
229{
230    struct sockaddr_in client_addr;
231
232#if defined(__socklen_t_defined) || defined(_SOCKLEN_T) ||  \
233    defined(_SOCKLEN_T_DECLARED)
234    socklen_t n = (socklen_t) sizeof( client_addr );
235#else
236    int n = (int) sizeof( client_addr );
237#endif
238
239    *client_fd = accept( bind_fd, (struct sockaddr *)
240                         &client_addr, &n );
241
242    if( *client_fd < 0 )
243    {
244        if( net_is_blocking() != 0 )
245            return( POLARSSL_ERR_NET_WANT_READ );
246
247        return( POLARSSL_ERR_NET_ACCEPT_FAILED );
248    }
249
250    if( client_ip != NULL )
251        memcpy( client_ip, &client_addr.sin_addr.s_addr,
252                    sizeof( client_addr.sin_addr.s_addr ) );
253
254    return( 0 );
255}
256
257/*
258 * Set the socket blocking or non-blocking
259 */
260int net_set_block( int fd )
261{
262#if defined(_WIN32) || defined(_WIN32_WCE)
263    u_long n = 0;
264    return( ioctlsocket( fd, FIONBIO, &n ) );
265#else
266    return( fcntl( fd, F_SETFL, fcntl( fd, F_GETFL ) & ~O_NONBLOCK ) );
267#endif
268}
269
270int net_set_nonblock( int fd )
271{
272#if defined(_WIN32) || defined(_WIN32_WCE)
273    u_long n = 1;
274    return( ioctlsocket( fd, FIONBIO, &n ) );
275#else
276    return( fcntl( fd, F_SETFL, fcntl( fd, F_GETFL ) | O_NONBLOCK ) );
277#endif
278}
279
280/*
281 * Portable usleep helper
282 */
283void net_usleep( unsigned long usec )
284{
285    struct timeval tv;
286    tv.tv_sec  = 0;
287    tv.tv_usec = usec;
288    select( 0, NULL, NULL, NULL, &tv );
289}
290
291/*
292 * Read at most 'len' characters
293 */
294int net_recv( void *ctx, unsigned char *buf, size_t len )
295{ 
296    int ret = read( *((int *) ctx), buf, len );
297
298    if( ret < 0 )
299    {
300        if( net_is_blocking() != 0 )
301            return( POLARSSL_ERR_NET_WANT_READ );
302
303#if defined(_WIN32) || defined(_WIN32_WCE)
304        if( WSAGetLastError() == WSAECONNRESET )
305            return( POLARSSL_ERR_NET_CONN_RESET );
306#else
307        if( errno == EPIPE || errno == ECONNRESET )
308            return( POLARSSL_ERR_NET_CONN_RESET );
309
310        if( errno == EINTR )
311            return( POLARSSL_ERR_NET_WANT_READ );
312#endif
313
314        return( POLARSSL_ERR_NET_RECV_FAILED );
315    }
316
317    return( ret );
318}
319
320/*
321 * Write at most 'len' characters
322 */
323int net_send( void *ctx, const unsigned char *buf, size_t len )
324{
325    int ret = write( *((int *) ctx), buf, len );
326
327    if( ret < 0 )
328    {
329        if( net_is_blocking() != 0 )
330            return( POLARSSL_ERR_NET_WANT_WRITE );
331
332#if defined(_WIN32) || defined(_WIN32_WCE)
333        if( WSAGetLastError() == WSAECONNRESET )
334            return( POLARSSL_ERR_NET_CONN_RESET );
335#else
336        if( errno == EPIPE || errno == ECONNRESET )
337            return( POLARSSL_ERR_NET_CONN_RESET );
338
339        if( errno == EINTR )
340            return( POLARSSL_ERR_NET_WANT_WRITE );
341#endif
342
343        return( POLARSSL_ERR_NET_SEND_FAILED );
344    }
345
346    return( ret );
347}
348
349/*
350 * Gracefully close the connection
351 */
352void net_close( int fd )
353{
354    shutdown( fd, 2 );
355    close( fd );
356}
357
358#endif
Note: See TracBrowser for help on using the repository browser.

What are you looking for?