-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSipServer.cpp_old
More file actions
306 lines (256 loc) · 8.93 KB
/
SipServer.cpp_old
File metadata and controls
306 lines (256 loc) · 8.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/****************************************************************************
* Copyright (C) 2009 by Joshua weaver *
* joshuaweaver@gmail.com *
* *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are *
* met: *
* * Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* * Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in *
* the documentation and/or other materials provided with the *
* distribution. *
* * Neither the name of the <ORGANIZATION> nor the names of its *
* contributors may be used to endorse or promote products derived *
* from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT *
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
***************************************************************************/
#include "SipServer.hpp"
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <boost/regex.hpp>
#include <cctype> //for to(upper|lower) transform
#include <sstream>
#include <fcntl.h> //O_NONBLOCK and friends
//DEBUGGING
#include <iostream>
using namespace std;
namespace Sip
{
//
//Utility functions
//
/**
* Generated a randoms string.
* @warning Not cryptographically secure, should not be used for crypto
* @param length The length of the string
* @return A string of random, printable characters
*/
string RandomString( int length )
{
ostringstream output;
for ( int i = 0; i < length; ++i )
{
char nextChar = ( rand() % 26 ) + 97;
output << nextChar;
}
return output.str();
}
SipServer::SipServer( int UDPPort ) throw( SipServerException )
: m_udpPort ( UDPPort )
{
bzero( &m_serverAddr, sizeof( m_serverAddr ) );
m_sock = socket( AF_INET, SOCK_DGRAM, 0 );
if ( m_sock == -1 )
throw SipServerException( string( "Could not create socket: " ) + strerror( errno ), "" );
int on = 1;
if ( setsockopt ( m_sock, SOL_SOCKET, SO_REUSEADDR, ( const char* ) &on, sizeof ( on ) ) == -1 )
{
close( m_sock );
throw SipServerException( string( "Could not set SO_REUSEADDR on socket: " ) + strerror( errno ) , "");
}
// Set non-blocking
long arg = 0 ;
if ( ( arg = fcntl ( m_sock, F_GETFL, NULL ) ) < 0 )
throw SipServerException( "Could not get socket opts: " + string(strerror ( errno )), "" );
arg |= O_NONBLOCK;
if ( fcntl ( m_sock, F_SETFL, arg ) < 0 )
throw SipServerException( "Could not set socket non-blocking: " + string(strerror ( errno )), "" );
sockaddr& serverAddrCast = ( sockaddr& ) m_serverAddr;
m_serverAddr.sin_family = AF_INET;
m_serverAddr.sin_port= htons( m_udpPort );
m_serverAddr.sin_addr.s_addr = INADDR_ANY;
int bindResult = bind( m_sock, &serverAddrCast, sizeof( m_serverAddr ) );
if ( bindResult == -1 )
{
ostringstream errorBuilder;
errorBuilder << "Could not bind to UDP port " << m_udpPort << ", error: " << strerror( errno );
close( m_sock );
throw SipServerException( errorBuilder.str() , "");
}
}
string SipServer::Accept( auto_ptr<SipMessage>& sipMessage )
{
//SELECT() crap
fd_set myset;
struct timeval tv;
int selectResult;
tv.tv_sec = 3; //Wait 3 seconds for a datagram
tv.tv_usec = 0;
FD_ZERO ( &myset );
FD_SET ( m_sock, &myset );
// END SELECT() crap
selectResult = select ( m_sock + 1, &myset, NULL, NULL, &tv );
if ( selectResult < 0 )
{
throw SipServerException( string( "Socket error waiting for SIP data : " ) + strerror( errno ), "" );
}
else if ( selectResult == 0 )
{
throw SipServerTimeout( "SipServer::Accept() timeout" );
}
else //We have waiting data, we're good to go
{
return SipUtility::GetMessage( sipMessage, m_sock );
}
return string( "" );
}
void SipServer::Respond( SipResponse& response ) const
{
SipUtility::Respond( response );
}
void SipServer::Request( SipRequest& request ) const
{
SipUtility::Request( request );
}
int SipServer::UDPPort() const throw()
{
return m_udpPort;
}
//
// SipUtility
//
string SipUtility::GetMessage( auto_ptr<SipMessage>& sipMessage, int sock )
{
char buffer[ BUFFERSIZE ];
sockaddr_in clientAddr;
bzero( &clientAddr, sizeof( clientAddr ) );
sockaddr& clientAddrCast = ( sockaddr& ) clientAddr;
int size = sizeof ( clientAddr );
int received = recvfrom ( sock , buffer , BUFFERSIZE , 0, &clientAddrCast, ( socklen_t * ) &size );
//cerr << "received: " << received << endl;
if(received < 0) //signal? errno will tell us
throw SipServerException(string("No request found. ") + strerror(errno), "");
string data( buffer, received );
ParseMessage( sipMessage, data );
return string( inet_ntoa(clientAddr.sin_addr) );
}
void SipUtility::Respond( SipResponse& response )
{
ostringstream message;
string datagram;
try
{
if ( response.HasHeader( "via" ) == false )
throw SipServerException( "No Via tag in response - response malformed.", response.rawMessage );
URI recipient = Via( response.GetHeaderValues( "via" )[0] );
//cout << "<<Response OUT to " << recipient.URIAsString() << ":\n" << datagram << endl << endl;
DecrementForwards( response );
SendSipMessage( response.ToString(), recipient );
}
catch ( ViaException& e )
{
throw SipServerException( e.what(), response.rawMessage );
}
catch ( SipHeaderValueException& e )
{
throw SipServerException( e.what(), response.rawMessage );
}
}
void SipUtility::Request( SipRequest& request )
{
ostringstream message;
//cout << "<<Request OUT to " << recipient.URIAsString() << ":\n" << datagram << endl << endl;
DecrementForwards( request );
SendSipMessage( request.ToString(), request.RequestURI() );
}
void SipUtility::SendSipMessage( const string& rawMessage, const URI& recipient )
{
if ( !recipient.HasHost() )
throw SipServerException( "No host to send message to", rawMessage );
string host = recipient.Host();
int port = 5060;
if ( recipient.Protocol() != "sip" )
throw SipServerException( string( "Unsupported protocol: " ) + recipient.Protocol() , rawMessage );
if ( recipient.HasPort() )
port = recipient.Port();
ostringstream portAsStream;
portAsStream << port;
//TODO: Support 'transport' tag, not just UDP
struct addrinfo hints;
struct addrinfo * result;
struct addrinfo * res;
int error, sock;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; // Allow only IPv4... shortsighted?
hints.ai_socktype = SOCK_DGRAM; // Datagram socket
hints.ai_flags = AI_PASSIVE; // For wildcard IP address
hints.ai_protocol = 0; // Any protocol
error = getaddrinfo( host.c_str(), portAsStream.str().c_str(), &hints, &result);
if ( error != 0 )
throw SipServerException( string( "Could not resolve host: " ) + host, rawMessage );
try
{
for (res = result; res != NULL; res = res->ai_next)
{
sock = socket( res->ai_family , res->ai_socktype, res->ai_protocol );
if ( sock == -1 )
continue;
int sent = sendto ( sock , rawMessage.c_str() , rawMessage.length() , 0, res->ai_addr, res->ai_addrlen ) ;
close( sock );
if ( sent == -1 )
{ //Uh-oh, we didn't send...
ostringstream errorDescription;
switch( errno )
{
case EMSGSIZE:
throw SipServerException( "Could not send SIP message: too big", rawMessage );
break;
default:
errorDescription << "Could not send SIP message: " << strerror( errno ) << '[' << errno << ']';
throw SipServerException( errorDescription.str(), rawMessage );
}
}
}
}
catch ( SipServerException& e )
{
freeaddrinfo( result );
throw;
}
//Cleanup
freeaddrinfo( result );
}
void SipUtility::DecrementForwards( SipMessage& mesg )
{
if ( !mesg.HasHeader( "max-forwards" ) )
return;
int forwards = atoi( mesg.GetHeaderValues( "max-forwards" )[0].Value().c_str() );
forwards--;
if ( forwards < 0)
throw SipServerException( "Cannot forward, Max-Forwards < 0", mesg.GetOriginalRawMessage() );
else
{
stringstream newForwardsValue;
newForwardsValue << forwards;
mesg.ModifyHeader( "max-forwards" )[0].SetValue( newForwardsValue.str() );
}
}
} //namespace Sip