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