21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

13.8 Guarding Against Creating Too Many<br />

Network Sockets<br />

<strong>Problem</strong><br />

You need to limit the number of network sockets that your program can create.<br />

Solution<br />

Limiting the number of sockets that can be created in an application is a good way to<br />

mitigate potential denial of service attacks by preventing an attacker from creating<br />

too many open sockets for your program to be able to handle. Imposing a limit on<br />

sockets is a simple matter of maintaining a count of the number of sockets that have<br />

been created so far. To do this, you will need to appropriately wrap three socket<br />

functions. The first two functions that need to be wrapped, socket( ) and accept( ),<br />

are used to obtain new socket descriptors, and they should be modified to increment<br />

the number of sockets when they’re successful. The third function, close( )<br />

(closesocket( ) on Windows), is used to dispose of an existing socket descriptor, and<br />

it should be modified to decrement the number of sockets when it’s successful.<br />

Discussion<br />

To limit the number of sockets that can be created, the first step is to call spc_<br />

socketpool_init( ) to initialize the socket pool code. On Unix, this does nothing, but<br />

it is required on Windows to initialize two synchronization objects. Once the socket<br />

pool code is initialized, the next step is to call spc_socketpool_setlimit( ) with the<br />

maximum number of sockets to allow. In our implementation, any limit less than or<br />

equal to zero disables limiting sockets but causes them still to be counted. We have<br />

written the code to be thread-safe and to allow the wrapped functions to block when<br />

no sockets are available. If the limit is adjusted to allow more sockets when the old<br />

limit has already been reached, we cause all threads waiting for sockets to be awakened<br />

by signaling a condition object using pthread_cond_broadcast( ) on Unix or<br />

PulseEvent( ) on Windows.<br />

#include <br />

#include <br />

#ifndef WIN32<br />

#include <br />

#include <br />

#else<br />

#include <br />

#include <br />

#endif<br />

#ifndef WIN32<br />

724 | Chapter 13: Other Topics<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!