Browse code

- ser.cfg template preprocessed by m4

Jan Janak authored on 13/01/2004 19:42:56
Showing 2 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,29 @@
1
+#
2
+# $Id$
3
+#
4
+# (c) 2003 iptel.org
5
+#
6
+# Rules to process ser.cfg templates
7
+#
8
+
9
+define(`FROM_GW', `(_FROM_GW(1))')
10
+define(`_FROM_GW', `ifdef(`GW_IP_$1', `_FROM_GW(incr($1))(src_ip == GW_IP_$1)ifelse($1, 1, , ` || ')')')
11
+
12
+define(`TO_GW', `(@(_TO_GW(1))([;:].*)*)')
13
+define(`_TO_GW', `ifdef(`GW_IP_$1', `_TO_GW(incr($1))(patsubst(GW_IP_$1, `\.', `\\.'))ifelse($1, 1, , `|')')')
14
+
15
+define(`DIGEST_REALM', `SER_HOSTNAME')
16
+define(`SER_IP_REGEX', `patsubst(SER_IP, `\.', `\\.')')
17
+define(`SER_HOSTNAME_REGEX', `patsubst(SER_HOSTNAME, `\.', `\\.')')
18
+define(`SER_HOST_REGEX', `((SER_IP_REGEX)|(SER_HOSTNAME_REGEX))')
19
+
20
+define(`FROM_MYSELF', `(src_ip == SER_IP)')
21
+
22
+define(`ACC_FLAG', 1)
23
+define(`MISSED_FLAG', 3)
24
+define(`VM_FLAG', 4)
25
+define(`NAT_FLAG', 6)
26
+
27
+define(`PSTN', 3)
28
+define(`NAT', 1)
29
+define(`VOICEMAIL', 4)
0 30
new file mode 100644
... ...
@@ -0,0 +1,532 @@
1
+### m4 macros to make the configuration easier
2
+
3
+define(`SER_IP', `192.168.0.1')
4
+define(`SER_HOSTNAME', `foo.bar')
5
+
6
+define(`GW_IP_1', `192.168.0.2')
7
+define(`GW_IP_2', `192.168.0.3')
8
+
9
+### End of m4 macro section
10
+
11
+#
12
+# $Id$
13
+#
14
+# ser.cfg m4 template
15
+#
16
+
17
+#
18
+# Set the following in your CISCO PSTN gateway:
19
+# sip-ua
20
+#   nat symmetric role passive
21
+#   nat symmetric check-media-src
22
+#
23
+fork=yes
24
+port=5060
25
+log_stderror=no
26
+fifo="/tmp/ser_fifo"
27
+
28
+# uncomment to enter testing mode
29
+/*
30
+fork=no
31
+port=5064
32
+log_stderror=yes
33
+fifo="/tmp/ser_fifox"
34
+ */
35
+
36
+debug=3
37
+memlog=4  # memlog set high (>debug) -- no final time-consuming memory reports on exit
38
+mhomed=yes
39
+listen=SER_IP
40
+alias="SER_HOSTNAME"
41
+check_via=yes
42
+dns=yes
43
+rev_dns=no
44
+children=16
45
+
46
+# if changing fifo mode to a more restrictive value, put
47
+# decimal value in there, e.g. dec(rw|rw|rw)=dec(666)=438
48
+fifo_mode=0666
49
+
50
+loadmodule "/usr/local/lib/ser/modules/tm.so"
51
+loadmodule "/usr/local/lib/ser/modules/sl.so"
52
+loadmodule "/usr/local/lib/ser/modules/acc.so"
53
+loadmodule "/usr/local/lib/ser/modules/rr.so"
54
+loadmodule "/usr/local/lib/ser/modules/maxfwd.so"
55
+loadmodule "/usr/local/lib/ser/modules/mysql.so"
56
+loadmodule "/usr/local/lib/ser/modules/usrloc.so"
57
+loadmodule "/usr/local/lib/ser/modules/registrar.so"
58
+loadmodule "/usr/local/lib/ser/modules/auth.so"
59
+loadmodule "/usr/local/lib/ser/modules/auth_db.so"
60
+loadmodule "/usr/local/lib/ser/modules/textops.so"
61
+loadmodule "/usr/local/lib/ser/modules/uri.so"
62
+loadmodule "/usr/local/lib/ser/modules/group.so"
63
+loadmodule "/usr/local/lib/ser/modules/msilo.so"
64
+loadmodule "/usr/local/lib/ser/modules/nathelper.so"
65
+loadmodule "/usr/local/lib/ser/modules/enum.so"
66
+loadmodule "/usr/local/lib/ser/modules/domain.so"
67
+#loadmodule "/usr/local/lib/ser/modules/permissions.so"
68
+
69
+modparam("usrloc|acc|auth_db|group|msilo", "db_url", "sql://ser:heslo@localhost/ser")
70
+
71
+# -- usrloc params --
72
+/* 0 -- dont use mysql, 1 -- write_through, 2--write_back */
73
+modparam("usrloc", "db_mode", 2)
74
+modparam("usrloc", "timer_interval", 10)
75
+
76
+# -- auth params --
77
+modparam("auth_db", "calculate_ha1", yes)
78
+modparam("auth_db", "password_column", "password")
79
+#modparam("auth_db", "use_rpid", 1)
80
+modparam("auth", "nonce_expire", 300)
81
+modparam("auth", "rpid_prefix", "<sip:")
82
+modparam("auth", "rpid_suffix", "@GW_IP_3>;party=calling;id-type=subscriber;screen=yes;privacy=off")
83
+
84
+# -- rr params --
85
+# add value to ;lr param to make some broken UAs happy
86
+modparam("rr", "enable_full_lr", 1)
87
+
88
+# -- acc params --
89
+# report ACKs too for sake of completeness -- as we account PSTN
90
+# destinations which are RR, ACKs should show up
91
+modparam("acc", "report_ack", 1)
92
+modparam("acc", "log_level", 1)
93
+# if BYE fails (telephone is dead, record-routing broken, etc.), generate
94
+# a report nevertheless -- otherwise we would have no STOP event; => 1
95
+modparam("acc", "failed_transactions", 1)
96
+
97
+# that is the flag for which we will account -- don't forget to
98
+# set the same one :-)
99
+# Usage of flags is as follows:
100
+#   1 == should account(all to gateway),
101
+#   3 == should report on missed calls (transactions to iptel.org's users),
102
+#   4 == destination user wishes to use voicemail
103
+#   6 == nathelper
104
+#
105
+modparam("acc", "log_flag", ACC_FLAG)
106
+modparam("acc", "db_flag", ACC_FLAG)
107
+modparam("acc", "log_missed_flag", MISSED_FLAG)
108
+modparam("acc", "db_missed_flag", MISSED_FLAG)
109
+
110
+# report to syslog: From, i-uri, status, digest id, method
111
+modparam("acc", "log_fmt", "fisum")
112
+
113
+# -- tm params --
114
+modparam("tm", "fr_timer", 20)
115
+modparam("tm", "fr_inv_timer", 90)
116
+modparam("tm", "wt_timer", 20)
117
+
118
+# -- msilo params
119
+modparam("msilo", "registrar", "sip:registrar@SER_HOSTNAME")
120
+
121
+# -- enum params --
122
+modparam("enum", "domain_suffix", "e164.arpa.")
123
+
124
+# -- multi-domain
125
+modparam("domain", "db_mode", 1)
126
+
127
+# NAT features turned off -- smartnat available only in nat-capable release
128
+# We will you flag 6 to mark NATed contacts
129
+modparam("registrar", "nat_flag", NAT_FLAG)
130
+# Enable NAT pinging
131
+modparam("nathelper", "natping_interval", 15)
132
+# Ping only contacts that are known to be behind NAT
133
+modparam("nathelper", "ping_nated_only", 1)
134
+
135
+# ---------------------  request routing logic -------------------
136
+route {
137
+
138
+        if (!mf_process_maxfwd_header("10")) {
139
+                log("LOG: Too many hops\n");
140
+                sl_send_reply("483", "Alas Too Many Hops");
141
+                break;
142
+        };
143
+
144
+        if (msg:len >= max_len) {
145
+                sl_send_reply("513", "Message too large");
146
+                break;
147
+        };
148
+
149
+        # special handling for natted clients; first, nat test is
150
+        # executed: it looks for via!=received and RFC1918 addresses
151
+        # in Contact (may fail if line-folding used); also,
152
+        # the received test should, if complete, should check all
153
+        # vias for presence of received
154
+        if (nat_uac_test("3")) {
155
+                # allow RR-ed requests, as these may indicate that
156
+                # a NAT-enabled proxy takes care of it; unless it is
157
+                # a REGISTER
158
+
159
+                if (method == "REGISTER" || !search("^Record-Route:")) {
160
+                        log("LOG: Someone trying to register from private IP, rewriting\n");
161
+
162
+                        # This will work only for user agents that support symmetric
163
+                        # communication. We tested quite many of them and majority is
164
+                        # smart smart enough to be symmetric. In some phones, like
165
+                        # it takes a configuration option. With Cisco 7960, it is
166
+                        # called NAT_Enable=Yes, with kphone it is called
167
+                        # "symmetric media" and "symmetric signaling". (The latter
168
+                        # not part of public released yet.)
169
+
170
+                        fix_nated_contact(); # Rewrite contact with source IP of signalling
171
+                        if (method == "INVITE") {
172
+                                fix_nated_sdp("1");  # Add direction=active to SDP
173
+                        };
174
+                        force_rport();       # Add rport parameter to topmost Via
175
+                        setflag(NAT_FLAG); # Mark as NATed
176
+
177
+                        append_to_reply("P-NATed-Caller: Yes\r\n");
178
+                };
179
+        };
180
+
181
+
182
+        # anti-spam -- if somene claims to belong to our domain in From,
183
+        # challenge him (skip REGISTERs -- we will chalenge them later)
184
+        if (search("(From|F):.*@SER_HOST_REGEX")) {
185
+                # invites forwarded to other domains, like FWD may cause subsequent 
186
+                # request to come from there but have iptel in From -> verify
187
+                # only INVITEs (ignore FIFO/UAC's requests, i.e. src_ip==fox)
188
+                if ((method == "INVITE" || method == "SUBSCRIBE") && !(FROM_MYSELF || FROM_GW)) {
189
+                        if  (!(proxy_authorize("DIGEST_REALM", "subscriber"))) {
190
+                                proxy_challenge("DIGEST_REALM", "0");
191
+                                break;
192
+                        };
193
+
194
+                        # to maintain outside credibility of our proxy, we enforce
195
+                        # username in From to equal digest username; user with
196
+                        # "john.doe" id could advertise "bill.gates" in From otherwise;
197
+                        if (!check_from()) {
198
+                                log("LOG: From Cheating attempt in INVITE\n");
199
+                                sl_send_reply("403", "That is ugly -- use From=id next time (OB)");
200
+                                break;
201
+                        };
202
+
203
+                        # we better don't consume credentials -- some requests may be
204
+                        # spiraled through our server (sfo@iptel->7141@iptel) and the
205
+                        # subsequent iteration may challenge too, for example because of
206
+                        # iptel claim in From; UACs then give up because they
207
+                        # already submitted credentials for the given realm
208
+                        #consume_credentials();
209
+                }; # non-REGISTER from other domain
210
+        } else if ((method == "INVITE" || method == "SUBSCRIBE" || method=="REGISTER" ) && 
211
+                   !(uri == myself || uri =~ "TO_GW")) {
212
+                # and we serve our gateway too (we RR requests to it, so that
213
+                # its address may show up in subsequent requests after loose_route
214
+                sl_send_reply("403", "No relaying");
215
+                break;
216
+        };
217
+
218
+        # By default we record route everything except REGISTERs
219
+        if (!(method=="REGISTER")) record_route();
220
+
221
+        # if route forces us to forward to some explicit destination, do so
222
+        #
223
+        # loose_route returns true in case that a request included
224
+        # route header fields instructing SER where to relay a request;
225
+        # if that is the case, stop script processing and just forward there;
226
+        # one could alternatively ignore the return value and treat the
227
+        # request as if it was an outbound one; that would not work however
228
+        # with broken UAs which strip RR parameters from Route. (What happens
229
+        # is that with two RR /tcp2udp, spirals, etc./ and stripped parameters,
230
+        # SER a) rewrites r-uri with RR1 b) matches uri==myself against RR1
231
+        # c) applies mistakenly user-lookup to RR1 in r-uri
232
+
233
+        if (loose_route()) {
234
+                # check if someone has not introduced a pre-loaded INVITE -- if so,
235
+                # verify caller's privileges before accepting rr-ing
236
+                if ((method=="INVITE" || method=="ACK" || method=="CANCEL") && uri =~ "TO_GW") {
237
+                        route(PSTN); # Forward to PSTN gateway
238
+                } else {
239
+                        append_hf("P-hint: rr-enforced\r\n");
240
+                        # account all BYEs 
241
+                        if (method=="BYE") setflag(ACC_FLAG);
242
+                        route(NAT);  # Generic forward
243
+                };
244
+                break;
245
+        };
246
+
247
+        # -------  check for requests targeted out of our domain... -------
248
+        if (!(uri == myself || uri =~ "TO_GW")) {
249
+                # ... and we serve our gateway too (we RR requests to it, so that
250
+                # its address may show up in subsequent requests after
251
+                # rewriteFromRoute
252
+                append_hf("P-hint: OUTBOUND\r\n");
253
+                route(NAT);
254
+                break;
255
+        };
256
+
257
+
258
+        # ------- now, the request is for sure for our domain -----------
259
+        # registers always MUST be authenticated to
260
+        # avoid stealing incoming calls
261
+        if (method == "REGISTER") {
262
+                /*
263
+                if (!allow_register("register.allow", "register.deny")) {
264
+                        log(1, "LOG: alert: Forbidden IP in Contact\n");
265
+                        sl_send_reply("403", "Forbidden");
266
+                        break;
267
+                };
268
+                */
269
+
270
+                # prohibit attempts to grab someone else's To address 
271
+                # using  valid credentials; 
272
+                if (!www_authorize("DIGEST_REALM", "subscriber")) {
273
+                        # challenge if none or invalid credentials
274
+                        www_challenge("DIGEST_REALM", "0");
275
+                        break;
276
+                };
277
+
278
+                if (!check_to()) {
279
+                        log("LOG: To Cheating attempt\n");
280
+                        sl_send_reply("403", "That is ugly -- use To=id in REGISTERs");
281
+                        break;
282
+                };
283
+
284
+                # it is an authenticated request, update Contact database now
285
+                if (!save("location")) {
286
+                        sl_reply_error();
287
+                };
288
+
289
+                m_dump();
290
+                break;
291
+        };
292
+
293
+        # some UACs might be fooled by Contacts our UACs generate to make MSN
294
+        # happy (web-im, e.g.) -- tell its urneachable
295
+        if (uri =~ "sip:daemon@") {
296
+                sl_send_reply("410", "Daemon is gone");
297
+                break;
298
+        };
299
+
300
+        # aliases
301
+        # note: through a temporary error in provisioning interface, there
302
+        # are now aliases 905xx ... they take precedence overy any PSTN numbers
303
+        # as they are resolved first
304
+        lookup("aliases");
305
+
306
+        # check again, if it is still for our domain after aliases
307
+        if (!(uri == myself || uri =~ "TO_GW")) {
308
+                append_hf("P-hint: ALIASED-OUTBOUND\r\n");
309
+                route(NAT);
310
+                break;
311
+        };
312
+
313
+	# Remove leading + if it is a number begining with +
314
+	if (uri =~ "^[a-zA-Z]+:\+[0-9]+@") {
315
+		strip(1);
316
+		prefix("00");
317
+	};		
318
+
319
+	if (!does_uri_exist()) {
320
+		# Try numeric destinations through the gateway
321
+		if (uri =~ "^[a-zA-Z]+:[0-9]+@") {
322
+			route(PSTN);
323
+		} else {
324
+			sl_send_reply("604", "Does Not Exist Anywhere");
325
+		};
326
+		break;
327
+	};
328
+
329
+        # does the user wish redirection on no availability? (i.e., is he
330
+        # in the voicemail group?) -- determine it now and store it in
331
+        # flag 4, before we rewrite the flag using UsrLoc
332
+        if (is_user_in("Request-URI", "voicemail")) {
333
+                setflag(VM_FLAG);
334
+        };
335
+
336
+        # native SIP destinations are handled using our USRLOC DB
337
+        if (!lookup("location")) {
338
+                # handle user which was not found
339
+                route(VOICEMAIL);
340
+                break;
341
+        };
342
+
343
+        # check whether some inventive user has uploaded  gateway
344
+        # contacts to UsrLoc to bypass our authorization logic
345
+        if (uri =~ "TO_GW") {
346
+                log(1, "LOG: Weird! Gateway address in UsrLoc!\n");
347
+                route(PSTN);
348
+                break;
349
+        };
350
+
351
+        # if user is on-line and is in voicemail group, enable redirection
352
+        /* no voicemail currently activated
353
+        if (method == "INVITE" && isflagset(VM_FLAG)) {
354
+                t_on_failure("1");
355
+        };
356
+        */
357
+
358
+        # ... and also report on missed calls ... note that reporting
359
+        # on missed calls is mutually exclusive with silent C timer
360
+        setflag(MISSED_FLAG);
361
+
362
+        # we now know we may, we know where, let it go out now!
363
+        append_hf("P-hint: USRLOC\r\n");
364
+        route(NAT);
365
+}
366
+
367
+#
368
+# Forcing media relay if necesarry
369
+#
370
+route[NAT] {
371
+    if (uri=~"[@:](192\.168\.|10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.)" && !search("^Route:")) {
372
+            sl_send_reply("479", "We don't forward to private IP addresses");
373
+            break;
374
+    };
375
+    if (isflagset(NAT_FLAG)) {
376
+	    if (!is_present_hf("P-RTP-Proxy")) {
377
+            	force_rtp_proxy();
378
+		append_hf("P-RTP-Proxy: YES\r\n");
379
+	    };
380
+            append_hf("P-NATed-Calee: Yes\r\n");
381
+    };
382
+
383
+    # nat processing of replies; apply to all transactions (for example,
384
+    # re-INVITEs from public to private UA are hard to identify as
385
+    # natted at the moment of request processing); look at replies
386
+
387
+    t_on_reply("1");
388
+
389
+    if (!t_relay()) {
390
+            sl_reply_error();
391
+            break;
392
+    };
393
+}
394
+
395
+
396
+onreply_route[1] {
397
+        # natted transaction ?
398
+        if (isflagset(NAT_FLAG) && status =~ "(183)|2[0-9][0-9]") {
399
+                fix_nated_contact();
400
+                force_rtp_proxy();
401
+        # otherwise, is it a transaction behind a NAT and we did not
402
+        # know at time of request processing? (RFC1918 contacts)
403
+        } else if (nat_uac_test("1")) {
404
+                fix_nated_contact();
405
+        };
406
+
407
+        # keep Cisco gatweay sending keep-alives
408
+        if (isflagset(7) && status=~"2[0-9][0-9]") {
409
+                remove_hf("Session-Expires");
410
+                append_hf("Session-Expires: 60;refresher=UAC\r\n");
411
+                fix_nated_sdp("1");
412
+        };
413
+}
414
+
415
+
416
+#
417
+# logic for calls to the PSTN
418
+#
419
+route[PSTN] {
420
+
421
+        # discard non-PSTN methods
422
+        if (!(method == "INVITE" || method == "ACK" || method == "CANCEL" || method == "OPTIONS" || method == "BYE")) {
423
+                sl_send_reply("500", "only VoIP methods accepted for GW");
424
+                break;
425
+        };
426
+
427
+        # turn accounting on
428
+        setflag(ACC_FLAG);
429
+
430
+        # continue with requests to PSTN gateway ...
431
+
432
+        # no authentication needed if the destination is on our free-pstn
433
+        # list or if the caller is the digest-less gateway
434
+        #
435
+        # apply ACLs only to INVITEs -- we don't need to protect other
436
+        # requests, as they don't imply charges; also it could cause troubles
437
+        # when a call comes in via PSTN and goes to a party that can't
438
+        # authenticate (voicemail, other domain) -- BYEs would fail then
439
+        if (method == "INVITE") {
440
+		if (!is_user_in("Request-URI", "free-pstn")) {
441
+                	if (!proxy_authorize("DIGEST_REALM", "subscriber"))  {
442
+                        	proxy_challenge("DIGEST_REALM", "0");
443
+                        	break;
444
+                	};
445
+
446
+                	# let's check from=id ... avoids accounting confusion
447
+                	if (!check_from()) {
448
+                        	log("LOG: From Cheating attempt\n");
449
+                        	sl_send_reply("403", "That is ugly -- use From=id next time (gw)");
450
+                        	break;
451
+                	};
452
+		} else {
453
+			# Allow free-pstn destinations without any checks
454
+			route(5);
455
+			break;
456
+		};
457
+
458
+		if (uri =~ "^sip:00[1-9][0-9]+@") {
459
+			if (!is_user_in("credentials", "int")) {
460
+			    sl_send_reply("403", "International numbers not allowed");
461
+			    break;
462
+			};
463
+			route(5);
464
+		} else {
465
+			sl_send_reply("403", "Invalid Number");
466
+			break;
467
+		};
468
+        }; # authorized PSTN
469
+	break;
470
+}
471
+
472
+route[5] {
473
+	rewritehostport("GW_IP_1:5060");
474
+	consume_credentials();
475
+	append_hf("P-Hint: GATEWAY\r\n");
476
+
477
+	# Try alternative gateway on failure
478
+	t_on_failure("7");
479
+        # Our PSTN gateway is symmetric and can handle direction=active flag
480
+        # properly, therefore we don't have to use RTP proxy
481
+	t_relay();
482
+}
483
+
484
+
485
+
486
+failure_route[7] {
487
+	rewritehostport("GW_IP_2:5060");
488
+	append_branch();
489
+	t_relay();	
490
+}
491
+
492
+
493
+# ------------- handling of unavailable user ------------------
494
+route[VOICEMAIL] {
495
+        # message store
496
+        if (method == "MESSAGE") {
497
+                if (!t_newtran()) {
498
+                        sl_reply_error();
499
+                        break;
500
+                };
501
+
502
+                if (m_store("0")) {
503
+                        t_reply("202", "Accepted for Later Delivery");
504
+                        break;
505
+                };
506
+
507
+                t_reply("503", "Service Unavailable");
508
+                break;
509
+        };
510
+
511
+        # non-Voip -- just send "off-line"
512
+        if (!(method == "INVITE" || method == "ACK" || method == "CANCEL")) {
513
+                sl_send_reply("404", "Not Found");
514
+                break;
515
+        };
516
+
517
+        if (t_newtran()) {
518
+                if (method == "ACK") {
519
+                        log(1, "CAUTION: strange thing: ACK passed t_newtran\n");
520
+                        break;
521
+                };
522
+
523
+                t_reply("404", "Not Found");
524
+        };
525
+
526
+        # we account missed incoming calls; previous statteful processing
527
+        # guarantees that retransmissions are not accounted
528
+        if (method == "INVITE") {
529
+                acc_log_request("404 missed call\n");
530
+                acc_db_request("404 missed call", "missed_calls");
531
+        };
532
+}