blob: a2f97997c41eec644d9ab8aa979d093f7337c26c [file] [log] [blame]
Benny Prijonofff245c2007-04-02 11:44:47 +00001/* $Id$ */
2/*
3 * Copyright (C) 2003-2007 Benny Prijono <benny@prijono.org>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19#include <pjsip.h>
20#include <pjlib-util.h>
21#include <pjlib.h>
22
23
24/* Options */
25static struct global_struct
26{
27 pj_caching_pool cp;
28 pjsip_endpoint *endpt;
29 int port;
30 pj_pool_t *pool;
31
32 pj_thread_t *thread;
33 pj_bool_t quit_flag;
34
35 pj_bool_t record_route;
36
37 unsigned name_cnt;
38 pjsip_host_port name[16];
39} global;
40
41
42
43static void app_perror(const char *msg, pj_status_t status)
44{
45 char errmsg[PJ_ERR_MSG_SIZE];
46
47 pj_strerror(status, errmsg, sizeof(errmsg));
48 PJ_LOG(1,(THIS_FILE, "%s: %s", msg, errmsg));
49}
50
51
52static void usage(void)
53{
54 puts("Options:\n"
55 "\n"
Benny Prijono230c2f92007-04-06 10:35:41 +000056 " -p, --port N Set local listener port to N\n"
57 " -R, --rr Perform record routing\n"
58 " -L, --log-level N Set log level to N (default: 4)\n"
59 " -h, --help Show this help screen\n"
Benny Prijonofff245c2007-04-02 11:44:47 +000060 );
61}
62
63
64static pj_status_t init_options(int argc, char *argv[])
65{
66 struct pj_getopt_option long_opt[] = {
67 { "port", 1, 0, 'p'},
68 { "rr", 0, 0, 'R'},
69 { "log-level", 1, 0, 'L'},
70 { "help", 0, 0, 'h'},
Benny Prijono230c2f92007-04-06 10:35:41 +000071 { NULL, 0, 0, 0}
Benny Prijonofff245c2007-04-02 11:44:47 +000072 };
73 int c;
74 int opt_ind;
75
76 pj_optind = 0;
Benny Prijono230c2f92007-04-06 10:35:41 +000077 while((c=pj_getopt_long(argc, argv, "p:L:Rh", long_opt, &opt_ind))!=-1) {
Benny Prijonofff245c2007-04-02 11:44:47 +000078 switch (c) {
79 case 'p':
80 global.port = atoi(pj_optarg);
Benny Prijono64ac31b2007-04-02 19:11:41 +000081 printf("Port is set to %d\n", global.port);
Benny Prijonofff245c2007-04-02 11:44:47 +000082 break;
83
84 case 'R':
85 global.record_route = PJ_TRUE;
86 printf("Using record route mode\n");
87 break;
88
89 case 'L':
90 pj_log_set_level(atoi(pj_optarg));
91 break;
92
93 case 'h':
94 usage();
95 return -1;
96
97 default:
98 puts("Unknown option. Run with --help for help.");
99 return -1;
100 }
101 }
102
103 return PJ_SUCCESS;
104}
105
106
107/*****************************************************************************
108 * This is a very simple PJSIP module, whose sole purpose is to display
109 * incoming and outgoing messages to log. This module will have priority
110 * higher than transport layer, which means:
111 *
112 * - incoming messages will come to this module first before reaching
113 * transaction layer.
114 *
115 * - outgoing messages will come to this module last, after the message
116 * has been 'printed' to contiguous buffer by transport layer and
117 * appropriate transport instance has been decided for this message.
118 *
119 */
120
121/* Notification on incoming messages */
122static pj_bool_t logging_on_rx_msg(pjsip_rx_data *rdata)
123{
124 PJ_LOG(5,(THIS_FILE, "RX %d bytes %s from %s %s:%d:\n"
125 "%.*s\n"
126 "--end msg--",
127 rdata->msg_info.len,
128 pjsip_rx_data_get_info(rdata),
129 rdata->tp_info.transport->type_name,
130 rdata->pkt_info.src_name,
131 rdata->pkt_info.src_port,
132 (int)rdata->msg_info.len,
133 rdata->msg_info.msg_buf));
134
135 /* Always return false, otherwise messages will not get processed! */
136 return PJ_FALSE;
137}
138
139/* Notification on outgoing messages */
140static pj_status_t logging_on_tx_msg(pjsip_tx_data *tdata)
141{
142
143 /* Important note:
144 * tp_info field is only valid after outgoing messages has passed
145 * transport layer. So don't try to access tp_info when the module
146 * has lower priority than transport layer.
147 */
148
149 PJ_LOG(5,(THIS_FILE, "TX %d bytes %s to %s %s:%d:\n"
150 "%.*s\n"
151 "--end msg--",
152 (tdata->buf.cur - tdata->buf.start),
153 pjsip_tx_data_get_info(tdata),
154 tdata->tp_info.transport->type_name,
155 tdata->tp_info.dst_name,
156 tdata->tp_info.dst_port,
157 (int)(tdata->buf.cur - tdata->buf.start),
158 tdata->buf.start));
159
160 /* Always return success, otherwise message will not get sent! */
161 return PJ_SUCCESS;
162}
163
164/* The module instance. */
165static pjsip_module mod_msg_logger =
166{
167 NULL, NULL, /* prev, next. */
168 { "mod-msg-logger", 14 }, /* Name. */
169 -1, /* Id */
170 PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */
171 NULL, /* load() */
172 NULL, /* start() */
173 NULL, /* stop() */
174 NULL, /* unload() */
175 &logging_on_rx_msg, /* on_rx_request() */
176 &logging_on_rx_msg, /* on_rx_response() */
177 &logging_on_tx_msg, /* on_tx_request. */
178 &logging_on_tx_msg, /* on_tx_response() */
179 NULL, /* on_tsx_state() */
180
181};
182
183
184static pj_status_t init_stack(void)
185{
186 pj_status_t status;
187
188 /* Must init PJLIB first: */
189 status = pj_init();
190 PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
191
192
193 /* Then init PJLIB-UTIL: */
194 status = pjlib_util_init();
195 PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
196
197
198 /* Must create a pool factory before we can allocate any memory. */
199 pj_caching_pool_init(&global.cp, &pj_pool_factory_default_policy, 0);
200
201 /* Create the endpoint: */
202 status = pjsip_endpt_create(&global.cp.factory, NULL, &global.endpt);
203 PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
204
205 /* Init transaction layer for stateful proxy only */
206#if STATEFUL
207 status = pjsip_tsx_layer_init_module(global.endpt);
208 PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
209#endif
210
211 /* Create listening transport */
212 {
213 pj_sockaddr_in addr;
214
215 addr.sin_family = PJ_AF_INET;
216 addr.sin_addr.s_addr = 0;
217 addr.sin_port = pj_htons((pj_uint16_t)global.port);
218
219 status = pjsip_udp_transport_start( global.endpt, &addr,
220 NULL, 1, NULL);
221 if (status != PJ_SUCCESS)
222 return status;
223 }
224
225 /* Create pool for the application */
226 global.pool = pj_pool_create(&global.cp.factory, "proxyapp",
227 4000, 4000, NULL);
228
229 /* Register the logger module */
230 pjsip_endpt_register_module(global.endpt, &mod_msg_logger);
231
232 return PJ_SUCCESS;
233}
234
235
236static pj_status_t init_proxy(void)
237{
238 pj_in_addr addr;
239 unsigned i;
240
241 /* List all names matching local endpoint.
242 * Note that PJLIB version 0.6 and newer has a function to
243 * enumerate local IP interface (pj_enum_ip_interface()), so
244 * by using it would be possible to list all IP interfaces in
245 * this host.
246 */
247
248 /* The first address is important since this would be the one
249 * to be added in Record-Route.
250 */
251 if (pj_gethostip(&addr) == PJ_SUCCESS) {
252 pj_strdup2(global.pool, &global.name[global.name_cnt].host,
253 pj_inet_ntoa(addr));
254 global.name[global.name_cnt].port = global.port;
255 global.name_cnt++;
256 }
257
258 global.name[global.name_cnt].host = pj_str("127.0.0.1");
259 global.name[global.name_cnt].port = global.port;
260 global.name_cnt++;
261
262 global.name[global.name_cnt].host = *pj_gethostname();
263 global.name[global.name_cnt].port = global.port;
264 global.name_cnt++;
265
266 global.name[global.name_cnt].host = pj_str("localhost");
267 global.name[global.name_cnt].port = global.port;
268 global.name_cnt++;
269
270 PJ_LOG(3,(THIS_FILE, "Proxy started, listening on port %d", global.port));
271 PJ_LOG(3,(THIS_FILE, "Local host aliases:"));
272 for (i=0; i<global.name_cnt; ++i) {
273 PJ_LOG(3,(THIS_FILE, " %.*s:%d",
274 (int)global.name[i].host.slen,
275 global.name[i].host.ptr,
276 global.name[i].port));
277 }
278
279 if (global.record_route) {
280 PJ_LOG(3,(THIS_FILE, "Using Record-Route mode"));
281 }
282
283 return PJ_SUCCESS;
284}
285
286
287#if PJ_HAS_THREADS
288static int worker_thread(void *p)
289{
290 pj_time_val delay = {0, 10};
291
292 PJ_UNUSED_ARG(p);
293
294 while (!global.quit_flag) {
295 pjsip_endpt_handle_events(global.endpt, &delay);
296 }
297
298 return 0;
299}
300#endif
301
302
303/* Utility to determine if URI is local to this host. */
304static pj_bool_t is_uri_local(const pjsip_sip_uri *uri)
305{
306 unsigned i;
307 for (i=0; i<global.name_cnt; ++i) {
308 if ((uri->port == global.name[i].port ||
309 (uri->port==0 && global.name[i].port==5060)) &&
310 pj_stricmp(&uri->host, &global.name[i].host)==0)
311 {
312 /* Match */
313 return PJ_TRUE;
314 }
315 }
316
317 /* Doesn't match */
318 return PJ_FALSE;
319}
320
321
322/* Proxy utility to verify incoming requests.
323 * Return non-zero if verification failed.
324 */
325static pj_status_t proxy_verify_request(pjsip_rx_data *rdata)
326{
327 const pj_str_t STR_PROXY_REQUIRE = {"Proxy-Require", 13};
328
329 /* RFC 3261 Section 16.3 Request Validation */
330
331 /* Before an element can proxy a request, it MUST verify the message's
332 * validity. A valid message must pass the following checks:
333 *
334 * 1. Reasonable Syntax
335 * 2. URI scheme
336 * 3. Max-Forwards
337 * 4. (Optional) Loop Detection
338 * 5. Proxy-Require
339 * 6. Proxy-Authorization
340 */
341
342 /* 1. Reasonable Syntax.
343 * This would have been checked by transport layer.
344 */
345
346 /* 2. URI scheme.
347 * We only want to support "sip:" URI scheme for this simple proxy.
348 */
349 if (!PJSIP_URI_SCHEME_IS_SIP(rdata->msg_info.msg->line.req.uri)) {
350 pjsip_endpt_respond_stateless(global.endpt, rdata,
351 PJSIP_SC_UNSUPPORTED_URI_SCHEME, NULL,
352 NULL, NULL);
353 return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_UNSUPPORTED_URI_SCHEME);
354 }
355
356 /* 3. Max-Forwards.
357 * Send error if Max-Forwards is 1 or lower.
358 */
359 if (rdata->msg_info.max_fwd && rdata->msg_info.max_fwd->ivalue <= 1) {
360 pjsip_endpt_respond_stateless(global.endpt, rdata,
361 PJSIP_SC_TOO_MANY_HOPS, NULL,
362 NULL, NULL);
363 return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_TOO_MANY_HOPS);
364 }
365
366 /* 4. (Optional) Loop Detection.
367 * Nah, we don't do that with this simple proxy.
368 */
369
370 /* 5. Proxy-Require */
371 if (pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &STR_PROXY_REQUIRE,
372 NULL) != NULL)
373 {
374 pjsip_endpt_respond_stateless(global.endpt, rdata,
375 PJSIP_SC_BAD_EXTENSION, NULL,
376 NULL, NULL);
377 return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_BAD_EXTENSION);
378 }
379
380 /* 6. Proxy-Authorization.
381 * Nah, we don't require any authorization with this sample.
382 */
383
384 return PJ_SUCCESS;
385}
386
387
388/* Process route information in the reqeust */
389static pj_status_t proxy_process_routing(pjsip_tx_data *tdata)
390{
391 pjsip_sip_uri *target;
392 pjsip_route_hdr *hroute;
393
394 /* RFC 3261 Section 16.4 Route Information Preprocessing */
395
396 target = (pjsip_sip_uri*) tdata->msg->line.req.uri;
397
398 /* The proxy MUST inspect the Request-URI of the request. If the
399 * Request-URI of the request contains a value this proxy previously
400 * placed into a Record-Route header field (see Section 16.6 item 4),
401 * the proxy MUST replace the Request-URI in the request with the last
402 * value from the Route header field, and remove that value from the
403 * Route header field. The proxy MUST then proceed as if it received
404 * this modified request.
405 */
406 /* Nah, we don't want to support this */
407
408 /* If the Request-URI contains a maddr parameter, the proxy MUST check
409 * to see if its value is in the set of addresses or domains the proxy
410 * is configured to be responsible for. If the Request-URI has a maddr
411 * parameter with a value the proxy is responsible for, and the request
412 * was received using the port and transport indicated (explicitly or by
413 * default) in the Request-URI, the proxy MUST strip the maddr and any
414 * non-default port or transport parameter and continue processing as if
415 * those values had not been present in the request.
416 */
417 if (target->maddr_param.slen != 0) {
418 pjsip_sip_uri maddr_uri;
419
420 maddr_uri.host = target->maddr_param;
421 maddr_uri.port = global.port;
422
423 if (is_uri_local(&maddr_uri)) {
424 target->maddr_param.slen = 0;
425 target->port = 0;
426 target->transport_param.slen = 0;
427 }
428 }
429
430 /* If the first value in the Route header field indicates this proxy,
431 * the proxy MUST remove that value from the request.
432 */
433 hroute = (pjsip_route_hdr*)
434 pjsip_msg_find_hdr(tdata->msg, PJSIP_H_ROUTE, NULL);
435 if (hroute && is_uri_local((pjsip_sip_uri*)hroute->name_addr.uri)) {
436 pj_list_erase(hroute);
437 }
438
439 return PJ_SUCCESS;
440}
441
442
443/* Postprocess the request before forwarding it */
444static void proxy_postprocess(pjsip_tx_data *tdata)
445{
446 /* Optionally record-route */
447 if (global.record_route) {
448 char uribuf[128];
449 pj_str_t uri;
450 const pj_str_t H_RR = { "Record-Route", 12 };
451 pjsip_generic_string_hdr *rr;
452
453 pj_ansi_snprintf(uribuf, sizeof(uribuf), "<sip:%.*s:%d;lr>",
454 (int)global.name[0].host.slen,
455 global.name[0].host.ptr,
456 global.name[0].port);
457 uri = pj_str(uribuf);
458 rr = pjsip_generic_string_hdr_create(tdata->pool,
459 &H_RR, &uri);
460 pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)rr);
461 }
462}
463
464
465/* Calculate new target for the request */
466static pj_status_t proxy_calculate_target(pjsip_rx_data *rdata,
467 pjsip_tx_data *tdata)
468{
469 pjsip_sip_uri *target;
470
471 /* RFC 3261 Section 16.5 Determining Request Targets */
472
473 target = (pjsip_sip_uri*) tdata->msg->line.req.uri;
474
475 /* If the Request-URI of the request contains an maddr parameter, the
476 * Request-URI MUST be placed into the target set as the only target
477 * URI, and the proxy MUST proceed to Section 16.6.
478 */
479 if (target->maddr_param.slen) {
480 proxy_postprocess(tdata);
481 return PJ_SUCCESS;
482 }
483
484
485 /* If the domain of the Request-URI indicates a domain this element is
486 * not responsible for, the Request-URI MUST be placed into the target
487 * set as the only target, and the element MUST proceed to the task of
488 * Request Forwarding (Section 16.6).
489 */
490 if (!is_uri_local(target)) {
491 proxy_postprocess(tdata);
492 return PJ_SUCCESS;
493 }
494
495 /* If the target set for the request has not been predetermined as
496 * described above, this implies that the element is responsible for the
497 * domain in the Request-URI, and the element MAY use whatever mechanism
498 * it desires to determine where to send the request.
499 */
500
501 /* We're not interested to receive request destined to us, so
502 * respond with 404/Not Found (only if request is not ACK!).
503 */
504 if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) {
505 pjsip_endpt_respond_stateless(global.endpt, rdata,
506 PJSIP_SC_NOT_FOUND, NULL,
507 NULL, NULL);
508 }
509
510 /* Delete the request since we're not forwarding it */
511 pjsip_tx_data_dec_ref(tdata);
512
513 return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_NOT_FOUND);
514}
515
516
517/* Destroy stack */
518static void destroy_stack(void)
519{
520 pjsip_endpt_destroy(global.endpt);
521 pj_pool_release(global.pool);
522 pj_caching_pool_destroy(&global.cp);
523
524 pj_shutdown();
525}
526