b5d96359b75c632ce091512637350eccd69f0e75
[lcr.git] / sip.cpp
1 /*****************************************************************************\
2 **                                                                           **
3 ** Linux Call Router                                                         **
4 **                                                                           **
5 **---------------------------------------------------------------------------**
6 ** Copyright: Andreas Eversberg                                              **
7 **                                                                           **
8 ** SIP port                                                                  **
9 **                                                                           **
10 \*****************************************************************************/ 
11
12 #include "main.h"
13 #include <sofia-sip/sip_status.h>
14 #include <sofia-sip/su_log.h>
15 #include <sofia-sip/sdp.h>
16 #include <sofia-sip/sip_header.h>
17 #include <sofia-sip/stun.h>
18 #include <sofia-sip/stun_tag.h>
19
20 #ifndef SOFIA_SIP_GCC_4_8_PATCH_APLLIED
21 #warning ********************************************************
22 #warning Please apply the sofia-sip-gcc-4.8.patch !
23 #warning If this issue is already fixed, just remove this check.
24 #warning ********************************************************
25 #error
26 #endif
27
28 #undef NUTAG_AUTO100
29
30 unsigned char flip[256];
31
32 int any_sip_interface = 0;
33
34 //pthread_mutex_t mutex_msg;
35 su_home_t       sip_home[1];
36
37 #define REGISTER_STATE_UNREGISTERED     1
38 #define REGISTER_STATE_REGISTERING      2
39 #define REGISTER_STATE_REGISTERED       3
40 #define REGISTER_STATE_FAILED           4
41
42 #define STUN_RETRY_TIMER                10, 0
43 #define REGISTER_RETRY_TIMER            10, 0
44
45 #define STUN_STATE_UNRESOLVED           1
46 #define STUN_STATE_RESOLVING            2
47 #define STUN_STATE_RESOLVED             3
48 #define STUN_STATE_FAILED               4
49
50 #define RTP_PORT_BASE   30000
51 #define RTP_PORT_MAX    39998
52
53 struct sip_inst {
54         char                    interface_name[64];
55         char                    local_peer[128];
56         char                    remote_peer[128];
57         char                    asserted_id[128];
58         int                     allow_register;
59         int                     register_state;
60         char                    register_user[128];
61         char                    register_host[128];
62         nua_handle_t            *register_handle;
63         struct lcr_timer        register_retry_timer;
64         struct lcr_timer        register_option_timer;
65         int                     register_interval;
66         int                     options_interval;
67         char                    auth_user[128];
68         char                    auth_password[128];
69         su_root_t               *root;
70         nua_t                   *nua;
71
72         char                    public_ip[128];
73         int                     stun_state;
74         char                    stun_server[128];
75         stun_handle_t           *stun_handle;
76         su_socket_t             stun_socket;
77         struct lcr_timer        stun_retry_timer;
78         int                     stun_interval;
79
80         unsigned short          rtp_port_from;
81         unsigned short          rtp_port_to;
82         unsigned short          next_rtp_port;
83
84 };
85
86 static int delete_event(struct lcr_work *work, void *instance, int index);
87 static int invite_option_timer(struct lcr_timer *timer, void *instance, int index);
88 static int load_timer(struct lcr_timer *timer, void *instance, int index);
89
90 /*
91  * initialize SIP port
92  */
93 Psip::Psip(int type, char *portname, struct port_settings *settings, struct interface *interface) : Port(type, portname, settings, interface)
94 {
95         p_s_rtp_bridge = 0;
96         if (interface->rtp_bridge)
97                 p_s_rtp_bridge = 1;
98         p_s_sip_inst = interface->sip_inst;
99         memset(&p_s_delete, 0, sizeof(p_s_delete));
100         add_work(&p_s_delete, delete_event, this, 0);
101         p_s_handle = 0;
102         p_s_magic = 0;
103         memset(&p_s_rtp_fd, 0, sizeof(p_s_rtp_fd));
104         memset(&p_s_rtcp_fd, 0, sizeof(p_s_rtcp_fd));
105         memset(&p_s_rtp_sin_local, 0, sizeof(p_s_rtp_sin_local));
106         memset(&p_s_rtcp_sin_local, 0, sizeof(p_s_rtcp_sin_local));
107         memset(&p_s_rtp_sin_remote, 0, sizeof(p_s_rtp_sin_remote));
108         memset(&p_s_rtcp_sin_remote, 0, sizeof(p_s_rtcp_sin_remote));
109         p_s_rtp_ip_local = 0;
110         p_s_rtp_ip_remote = 0;
111         p_s_rtp_port_local = 0;
112         p_s_rtp_port_remote = 0;
113         p_s_b_sock = -1;
114         p_s_b_index = -1;
115         p_s_b_active = 0;
116         p_s_rxpos = 0;
117         p_s_rtp_tx_action = 0;
118         p_s_rtp_is_connected = 0;
119
120         /* create option timer */
121         memset(&p_s_invite_option_timer, 0, sizeof(p_s_invite_option_timer));
122         add_timer(&p_s_invite_option_timer, invite_option_timer, this, 0);
123         p_s_invite_direction = 0;
124
125         /* audio */
126         memset(&p_s_load_timer, 0, sizeof(p_s_load_timer));
127         add_timer(&p_s_load_timer, load_timer, this, 0);
128         p_s_next_tv_sec = 0;
129
130         PDEBUG(DEBUG_SIP, "Created new Psip(%s).\n", portname);
131         if (!p_s_sip_inst)
132                 FATAL("No SIP instance for interface\n");
133 }
134
135
136 /*
137  * destructor
138  */
139 Psip::~Psip()
140 {
141         PDEBUG(DEBUG_SIP, "Destroyed SIP process(%s).\n", p_name);
142
143         del_timer(&p_s_invite_option_timer);
144         del_timer(&p_s_load_timer);
145         del_work(&p_s_delete);
146
147         rtp_close();
148 }
149
150 static const char *media_type2name(uint8_t media_type) {
151         switch (media_type) {
152         case MEDIA_TYPE_ULAW:
153                 return "PCMU";
154         case MEDIA_TYPE_ALAW:
155                 return "PCMA";
156         case MEDIA_TYPE_GSM:
157                 return "GSM";
158         case MEDIA_TYPE_GSM_HR:
159                 return "GSM-HR";
160         case MEDIA_TYPE_GSM_EFR:
161                 return "GSM-EFR";
162         case MEDIA_TYPE_AMR:
163                 return "AMR";
164         }
165
166         return "UKN";
167 }
168
169 static void sip_trace_header(class Psip *sip, const char *interface_name, const char *message, int direction)
170 {
171         struct interface *interface = NULL;
172
173         if (interface_name)
174                 interface = getinterfacebyname(interface_name);
175
176         /* init trace with given values */
177         start_trace(-1,
178                     interface,
179                     sip?numberrize_callerinfo(sip->p_callerinfo.id, sip->p_callerinfo.ntype, options.national, options.international):NULL,
180                     sip?sip->p_dialinginfo.id:NULL,
181                     direction,
182                     CATEGORY_CH,
183                     sip?sip->p_serial:0,
184                     message);
185 }
186
187 /*
188  * RTP
189  */
190
191 /* according to RFC 3550 */
192 struct rtp_hdr {
193 #if __BYTE_ORDER == __LITTLE_ENDIAN
194         uint8_t  csrc_count:4,
195                   extension:1,
196                   padding:1,
197                   version:2;
198         uint8_t  payload_type:7,
199                   marker:1;
200 #elif __BYTE_ORDER == __BIG_ENDIAN
201         uint8_t  version:2,
202                   padding:1,
203                   extension:1,
204                   csrc_count:4;
205         uint8_t  marker:1,
206                   payload_type:7;
207 #endif
208         uint16_t sequence;
209         uint32_t timestamp;
210         uint32_t ssrc;
211 } __attribute__((packed));
212
213 struct rtp_x_hdr {
214         uint16_t by_profile;
215         uint16_t length;
216 } __attribute__((packed));
217
218 #define RTP_VERSION     2
219
220 #define PAYLOAD_TYPE_ULAW 0
221 #define PAYLOAD_TYPE_ALAW 8
222 #define PAYLOAD_TYPE_GSM 3
223
224 /* decode an rtp frame  */
225 static int rtp_decode(class Psip *psip, unsigned char *data, int len)
226 {
227         struct rtp_hdr *rtph = (struct rtp_hdr *)data;
228         struct rtp_x_hdr *rtpxh;
229         uint8_t *payload;
230         int payload_len;
231         int x_len;
232         unsigned char *from, *to;
233         int n;
234
235         if (len < 12) {
236                 PDEBUG(DEBUG_SIP, "received RTP frame too short (len = %d)\n", len);
237                 return -EINVAL;
238         }
239         if (rtph->version != RTP_VERSION) {
240                 PDEBUG(DEBUG_SIP, "received RTP version %d not supported.\n", rtph->version);
241                 return -EINVAL;
242         }
243         payload = data + sizeof(struct rtp_hdr) + (rtph->csrc_count << 2);
244         payload_len = len - sizeof(struct rtp_hdr) - (rtph->csrc_count << 2);
245         if (payload_len < 0) {
246                 PDEBUG(DEBUG_SIP, "received RTP frame too short (len = %d, "
247                         "csrc count = %d)\n", len, rtph->csrc_count);
248                 return -EINVAL;
249         }
250         if (rtph->extension) {
251                 if (payload_len < (int)sizeof(struct rtp_x_hdr)) {
252                         PDEBUG(DEBUG_SIP, "received RTP frame too short for "
253                                 "extension header\n");
254                         return -EINVAL;
255                 }
256                 rtpxh = (struct rtp_x_hdr *)payload;
257                 x_len = ntohs(rtpxh->length) * 4 + sizeof(struct rtp_x_hdr);
258                 payload += x_len;
259                 payload_len -= x_len;
260                 if (payload_len < 0) {
261                         PDEBUG(DEBUG_SIP, "received RTP frame too short, "
262                                 "extension header exceeds frame length\n");
263                         return -EINVAL;
264                 }
265         }
266         if (rtph->padding) {
267                 if (payload_len < 0) {
268                         PDEBUG(DEBUG_SIP, "received RTP frame too short for "
269                                 "padding length\n");
270                         return -EINVAL;
271                 }
272                 payload_len -= payload[payload_len - 1];
273                 if (payload_len < 0) {
274                         PDEBUG(DEBUG_SIP, "received RTP frame with padding "
275                                 "greater than payload\n");
276                         return -EINVAL;
277                 }
278         }
279
280         switch (rtph->payload_type) {
281 #if 0
282 we only support alaw and ulaw!
283         case RTP_PT_GSM_FULL:
284                 if (payload_len != 33) {
285                         PDEBUG(DEBUG_SIP, "received RTP full rate frame with "
286                                 "payload length != 33 (len = %d)\n",
287                                 payload_len);
288                         return -EINVAL;
289                 }
290                 break;
291         case RTP_PT_GSM_EFR:
292                 if (payload_len != 31) {
293                         PDEBUG(DEBUG_SIP, "received RTP full rate frame with "
294                                 "payload length != 31 (len = %d)\n",
295                                 payload_len);
296                         return -EINVAL;
297                 }
298                 break;
299         case RTP_PT_GSM_HALF:
300                 if (payload_len != 14) {
301                         PDEBUG(DEBUG_SIP, "received RTP half rate frame with "
302                                 "payload length != 14 (len = %d)\n",
303                                 payload_len);
304                         return -EINVAL;
305                 }
306                 break;
307 #endif
308         case PAYLOAD_TYPE_ALAW:
309                 if (options.law != 'a') {
310                         PDEBUG(DEBUG_SIP, "received Alaw, but we don't do Alaw\n");
311                         return -EINVAL;
312                 }
313                 break;
314         case PAYLOAD_TYPE_ULAW:
315                 if (options.law == 'a') {
316                         PDEBUG(DEBUG_SIP, "received Ulaw, but we don't do Ulaw\n");
317                         return -EINVAL;
318                 }
319                 break;
320         default:
321                 PDEBUG(DEBUG_SIP, "received RTP frame with unknown payload "
322                         "type %d\n", rtph->payload_type);
323                 return -EINVAL;
324         }
325
326         if (payload_len <= 0) {
327                 PDEBUG(DEBUG_SIP, "received RTP payload is too small: %d\n", payload_len);
328                 return 0;
329         }
330
331         /* record audio */
332         if (psip->p_record)
333                 psip->record(payload, payload_len, 0); // from down
334         if (psip->p_tap)
335                 psip->tap(payload, payload_len, 0); // from down
336
337         n = payload_len;
338         from = payload;
339         to = payload;
340         if (psip->p_echotest) {
341                 /* echo rtp data we just received */
342                 psip->rtp_send_frame(from, n, (options.law=='a')?PAYLOAD_TYPE_ALAW:PAYLOAD_TYPE_ULAW);
343                 return 0;
344         }
345         while(n--)
346                 *to++ = flip[*from++];
347         if (psip->p_dov_rx)
348                 psip->dov_rx(payload, payload_len);
349         psip->bridge_tx(payload, payload_len);
350
351         return 0;
352 }
353
354 static int rtp_sock_callback(struct lcr_fd *fd, unsigned int what, void *instance, int index)
355 {
356         class Psip *psip = (class Psip *) instance;
357         int len;
358         unsigned char buffer[256];
359         int rc = 0;
360
361         if ((what & LCR_FD_READ)) {
362                 len = read(fd->fd, &buffer, sizeof(buffer));
363                 if (len <= 0) {
364                         PDEBUG(DEBUG_SIP, "read result=%d\n", len);
365 //                      psip->rtp_close();
366 //                      psip->rtp_shutdown();
367                         return len;
368                 }
369                 if (psip->p_s_rtp_is_connected)
370                         rc = rtp_decode(psip, buffer, len);
371         }
372
373         return rc;
374 }
375
376 static int rtcp_sock_callback(struct lcr_fd *fd, unsigned int what, void *instance, int index)
377 {
378 //      class Psip *psip = (class Psip *) instance;
379         int len;
380         unsigned char buffer[256];
381
382         if ((what & LCR_FD_READ)) {
383                 len = read(fd->fd, &buffer, sizeof(buffer));
384                 if (len <= 0) {
385                         PDEBUG(DEBUG_SIP, "read result=%d\n", len);
386 //                      psip->rtp_close();
387 //                      psip->rtp_shutdown();
388                         return len;
389                 }
390                 PDEBUG(DEBUG_SIP, "rtcp!\n");
391         }
392
393         return 0;
394 }
395
396 static int rtp_sub_socket_bind(int fd, struct sockaddr_in *sin_local, uint32_t ip, uint16_t port)
397 {
398         int rc;
399         socklen_t alen = sizeof(*sin_local);
400
401         sin_local->sin_family = AF_INET;
402         sin_local->sin_addr.s_addr = htonl(ip);
403         sin_local->sin_port = htons(port);
404
405         rc = bind(fd, (struct sockaddr *) sin_local, sizeof(*sin_local));
406         if (rc < 0)
407                 return rc;
408
409         /* retrieve the address we actually bound to, in case we
410          * passed INADDR_ANY as IP address */
411         return getsockname(fd, (struct sockaddr *) sin_local, &alen);
412 }
413
414 static int rtp_sub_socket_connect(int fd, struct sockaddr_in *sin_local, struct sockaddr_in *sin_remote, uint32_t ip, uint16_t port)
415 {
416         int rc;
417         socklen_t alen = sizeof(*sin_local);
418
419         sin_remote->sin_family = AF_INET;
420         sin_remote->sin_addr.s_addr = htonl(ip);
421         sin_remote->sin_port = htons(port);
422
423         rc = connect(fd, (struct sockaddr *) sin_remote, sizeof(*sin_remote));
424         if (rc < 0) {
425                 PERROR("failed to connect to ip %08x port %d rc=%d\n", ip, port, rc);
426                 return rc;
427         }
428
429         return getsockname(fd, (struct sockaddr *) sin_local, &alen);
430 }
431
432 int Psip::rtp_open(void)
433 {
434         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
435         int rc, rc2;
436 //      struct in_addr ia;
437         unsigned int ip;
438         unsigned short start_port;
439
440         PDEBUG(DEBUG_SIP, "rtp_open\n");
441
442         /* create socket */
443         rc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
444         if (rc < 0) {
445                 rtp_close();
446                 return -EIO;
447         }
448         p_s_rtp_fd.fd = rc;
449         register_fd(&p_s_rtp_fd, LCR_FD_READ, rtp_sock_callback, this, 0);
450
451         rc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
452         if (rc < 0) {
453                 rtp_close();
454                 return -EIO;
455         }
456         p_s_rtcp_fd.fd = rc;
457         register_fd(&p_s_rtcp_fd, LCR_FD_READ, rtcp_sock_callback, this, 0);
458
459         /* bind socket */
460         ip = htonl(INADDR_ANY);
461         start_port = inst->next_rtp_port;
462         while (1) {
463                 rc = rtp_sub_socket_bind(p_s_rtp_fd.fd, &p_s_rtp_sin_local, ip, inst->next_rtp_port);
464                 if (rc != 0)
465                         goto try_next_port;
466
467                 rc = rtp_sub_socket_bind(p_s_rtcp_fd.fd, &p_s_rtcp_sin_local, ip, inst->next_rtp_port + 1);
468                 if (rc == 0) {
469                         p_s_rtp_port_local = inst->next_rtp_port;
470                         inst->next_rtp_port = (inst->next_rtp_port + 2 > inst->rtp_port_to) ? inst->rtp_port_from : inst->next_rtp_port + 2;
471                         break;
472                 }
473                 /* reopen rtp socket and try again with next udp port */
474                 unregister_fd(&p_s_rtp_fd);
475                 close(p_s_rtp_fd.fd);
476                 p_s_rtp_fd.fd = 0;
477                 rc2 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
478                 if (rc2 < 0) {
479                         rtp_close();
480                         return -EIO;
481                 }
482                 p_s_rtp_fd.fd = rc2;
483                 register_fd(&p_s_rtp_fd, LCR_FD_READ, rtp_sock_callback, this, 0);
484
485 try_next_port:
486                 inst->next_rtp_port = (inst->next_rtp_port + 2 > inst->rtp_port_to) ? inst->rtp_port_from : inst->next_rtp_port + 2;
487                 if (inst->next_rtp_port == start_port)
488                         break;
489                 /* we must use rc2, in order to preserve rc */
490         }
491         if (rc < 0) {
492                 PDEBUG(DEBUG_SIP, "failed to find port\n");
493                 rtp_close();
494                 return rc;
495         }
496         p_s_rtp_ip_local = ntohl(p_s_rtp_sin_local.sin_addr.s_addr);
497         PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
498         PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
499
500         return p_s_rtp_port_local;
501 }
502
503 int Psip::rtp_connect(void)
504 {
505         int rc;
506         struct in_addr ia;
507
508         ia.s_addr = htonl(p_s_rtp_ip_remote);
509         if (p_s_rtp_is_connected)
510                 PDEBUG(DEBUG_SIP, "reconnecting existing RTP connection to new/same destination\n");
511         PDEBUG(DEBUG_SIP, "rtp_connect(ip=%s, port=%u)\n", inet_ntoa(ia), p_s_rtp_port_remote);
512
513         rc = rtp_sub_socket_connect(p_s_rtp_fd.fd, &p_s_rtp_sin_local, &p_s_rtp_sin_remote, p_s_rtp_ip_remote, p_s_rtp_port_remote);
514         if (rc < 0)
515                 return rc;
516
517         rc = rtp_sub_socket_connect(p_s_rtcp_fd.fd, &p_s_rtcp_sin_local, &p_s_rtcp_sin_remote, p_s_rtp_ip_remote, p_s_rtp_port_remote + 1);
518         if (rc < 0)
519                 return rc;
520
521         p_s_rtp_ip_local = ntohl(p_s_rtp_sin_local.sin_addr.s_addr);
522         PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
523         PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
524         p_s_rtp_is_connected = 1;
525
526         return 0;
527 }
528 void Psip::rtp_close(void)
529 {
530         if (p_s_rtp_fd.fd > 0) {
531                 unregister_fd(&p_s_rtp_fd);
532                 close(p_s_rtp_fd.fd);
533                 p_s_rtp_fd.fd = 0;
534         }
535         if (p_s_rtcp_fd.fd > 0) {
536                 unregister_fd(&p_s_rtcp_fd);
537                 close(p_s_rtcp_fd.fd);
538                 p_s_rtcp_fd.fd = 0;
539         }
540         if (p_s_rtp_is_connected) {
541                 PDEBUG(DEBUG_SIP, "rtp closed\n");
542                 p_s_rtp_is_connected = 0;
543         }
544 }
545
546 /* "to - from" */
547 void tv_difference(struct timeval *diff, const struct timeval *from,
548                           const struct timeval *__to)
549 {
550         struct timeval _to = *__to, *to = &_to;
551
552         if (to->tv_usec < from->tv_usec) {
553                 to->tv_sec -= 1;
554                 to->tv_usec += 1000000;
555         }
556
557         diff->tv_usec = to->tv_usec - from->tv_usec;
558         diff->tv_sec = to->tv_sec - from->tv_sec;
559 }
560
561 /* encode and send a rtp frame */
562 int Psip::rtp_send_frame(unsigned char *data, unsigned int len, uint8_t payload_type)
563 {
564         struct rtp_hdr *rtph;
565         int payload_len;
566         int duration; /* in samples */
567         unsigned char buffer[256];
568
569         /* record audio */
570         if (p_record)
571                 record(data, len, 1); // from up
572         if (p_tap)
573                 tap(data, len, 1); // from up
574
575         if (!p_s_rtp_is_connected) {
576                 /* drop silently */
577                 return 0;
578         }
579
580         if (!p_s_rtp_tx_action) {
581                 /* initialize sequences */
582                 p_s_rtp_tx_action = 1;
583                 p_s_rtp_tx_ssrc = rand();
584                 p_s_rtp_tx_sequence = random();
585                 p_s_rtp_tx_timestamp = random();
586                 memset(&p_s_rtp_tx_last_tv, 0, sizeof(p_s_rtp_tx_last_tv));
587         }
588
589         switch (payload_type) {
590 #if 0
591 we only support alaw and ulaw!
592         case RTP_PT_GSM_FULL:
593                 payload_len = 33;
594                 duration = 160;
595                 break;
596         case RTP_PT_GSM_EFR:
597                 payload_len = 31;
598                 duration = 160;
599                 break;
600         case RTP_PT_GSM_HALF:
601                 payload_len = 14;
602                 duration = 160;
603                 break;
604 #endif
605         case PAYLOAD_TYPE_ALAW:
606         case PAYLOAD_TYPE_ULAW:
607                 payload_len = len;
608                 duration = len;
609                 break;
610         default:
611                 PERROR("unsupported message type %d\n", payload_type);
612                 return -EINVAL;
613         }
614
615 #if 0
616         {
617                 struct timeval tv, tv_diff;
618                 long int usec_diff, frame_diff;
619
620                 gettimeofday(&tv, NULL);
621                 tv_difference(&tv_diff, &p_s_rtp_tx_last_tv, &tv);
622                 p_s_rtp_tx_last_tv = tv;
623
624                 usec_diff = tv_diff.tv_sec * 1000000 + tv_diff.tv_usec;
625                 frame_diff = (usec_diff / 20000);
626
627                 if (abs(frame_diff) > 1) {
628                         long int frame_diff_excess = frame_diff - 1;
629
630                         PDEBUG(DEBUG_SIP, "Correcting frame difference of %ld frames\n", frame_diff_excess);
631                         p_s_rtp_tx_sequence += frame_diff_excess;
632                         p_s_rtp_tx_timestamp += frame_diff_excess * duration;
633                 }
634         }
635 #endif
636
637         rtph = (struct rtp_hdr *) buffer;
638         rtph->version = RTP_VERSION;
639         rtph->padding = 0;
640         rtph->extension = 0;
641         rtph->csrc_count = 0;
642         rtph->marker = 0;
643         rtph->payload_type = payload_type;
644         rtph->sequence = htons(p_s_rtp_tx_sequence++);
645         rtph->timestamp = htonl(p_s_rtp_tx_timestamp);
646         p_s_rtp_tx_timestamp += duration;
647         rtph->ssrc = htonl(p_s_rtp_tx_ssrc);
648         memcpy(buffer + sizeof(struct rtp_hdr), data, payload_len);
649
650         if (p_s_rtp_fd.fd > 0) {
651                 len = write(p_s_rtp_fd.fd, &buffer, sizeof(struct rtp_hdr) + payload_len);
652                 if (len != sizeof(struct rtp_hdr) + payload_len) {
653                         PDEBUG(DEBUG_SIP, "write result=%d\n", len);
654 //                      rtp_close();
655 //                      rtp_shutdown();
656                         return -EIO;
657                 }
658         }
659
660         return 0;
661 }
662
663 /* receive from remote */
664 int Psip::bridge_rx(unsigned char *data, int len)
665 {
666         int ret;
667
668         /* don't bridge, if tones are provided */
669         if (p_tone_name[0] || p_dov_tx)
670                 return -EBUSY;
671
672         if (p_dov_tx)
673                 return -EBUSY;
674
675         if ((ret = Port::bridge_rx(data, len)))
676                 return ret;
677
678         /* write to rx buffer */
679         while(len--) {
680                 p_s_rxdata[p_s_rxpos++] = flip[*data++];
681                 if (p_s_rxpos == 160) {
682                         p_s_rxpos = 0;
683
684                         /* transmit data via rtp */
685                         rtp_send_frame(p_s_rxdata, 160, (options.law=='a')?PAYLOAD_TYPE_ALAW:PAYLOAD_TYPE_ULAW);
686                 }
687         }
688
689         return 0;
690 }
691
692 /* taken from freeswitch */
693 /* map sip responses to QSIG cause codes ala RFC4497 section 8.4.4 */
694 static int status2cause(int status)
695 {
696         switch (status) {
697         case 200:
698                 return 16; //SWITCH_CAUSE_NORMAL_CLEARING;
699         case 401:
700         case 402:
701         case 403:
702         case 407:
703         case 603:
704                 return 21; //SWITCH_CAUSE_CALL_REJECTED;
705         case 404:
706                 return 1; //SWITCH_CAUSE_UNALLOCATED_NUMBER;
707         case 485:
708         case 604:
709                 return 3; //SWITCH_CAUSE_NO_ROUTE_DESTINATION;
710         case 408:
711         case 504:
712                 return 102; //SWITCH_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
713         case 410:
714                 return 22; //SWITCH_CAUSE_NUMBER_CHANGED;
715         case 413:
716         case 414:
717         case 416:
718         case 420:
719         case 421:
720         case 423:
721         case 505:
722         case 513:
723                 return 127; //SWITCH_CAUSE_INTERWORKING;
724         case 480:
725                 return 180; //SWITCH_CAUSE_NO_USER_RESPONSE;
726         case 400:
727         case 481:
728         case 500:
729         case 503:
730                 return 41; //SWITCH_CAUSE_NORMAL_TEMPORARY_FAILURE;
731         case 486:
732         case 600:
733                 return 17; //SWITCH_CAUSE_USER_BUSY;
734         case 484:
735                 return 28; //SWITCH_CAUSE_INVALID_NUMBER_FORMAT;
736         case 488:
737         case 606:
738                 return 88; //SWITCH_CAUSE_INCOMPATIBLE_DESTINATION;
739         case 502:
740                 return 38; //SWITCH_CAUSE_NETWORK_OUT_OF_ORDER;
741         case 405:
742                 return 63; //SWITCH_CAUSE_SERVICE_UNAVAILABLE;
743         case 406:
744         case 415:
745         case 501:
746                 return 79; //SWITCH_CAUSE_SERVICE_NOT_IMPLEMENTED;
747         case 482:
748         case 483:
749                 return 25; //SWITCH_CAUSE_EXCHANGE_ROUTING_ERROR;
750         case 487:
751                 return 31; //??? SWITCH_CAUSE_ORIGINATOR_CANCEL;
752         default:
753                 return 31; //SWITCH_CAUSE_NORMAL_UNSPECIFIED;
754         }
755 }
756
757 static int cause2status(int cause, int location, const char **st)
758 {
759         int s;
760
761         switch (cause) {
762         case 1:
763                 s = 404; *st = sip_404_Not_found;
764                 break;
765         case 2:
766                 s = 404; *st = sip_404_Not_found;
767                 break;
768         case 3:
769                 s = 404; *st = sip_404_Not_found;
770                 break;
771         case 17:
772                 s = 486; *st = sip_486_Busy_here;
773                 break;
774         case 18:
775                 s = 408; *st = sip_408_Request_timeout;
776                 break;
777         case 19:
778                 s = 480; *st = sip_480_Temporarily_unavailable;
779                 break;
780         case 20:
781                 s = 480; *st = sip_480_Temporarily_unavailable;
782                 break;
783         case 21:
784                 if (location == LOCATION_USER) {
785                         s = 603; *st = sip_603_Decline;
786                 } else {
787                         s = 403; *st = sip_403_Forbidden;
788                 }
789                 break;
790         case 22:
791                 //s = 301; *st = sip_301_Moved_permanently;
792                 s = 410; *st = sip_410_Gone;
793                 break;
794         case 23:
795                 s = 410; *st = sip_410_Gone;
796                 break;
797         case 26:
798                 s = 404; *st = sip_404_Not_found;
799                 break;
800         case 27:
801                 s = 502; *st = sip_502_Bad_gateway;
802                 break;
803         case 28:
804                 s = 484; *st = sip_484_Address_incomplete;
805                 break;
806         case 29:
807                 s = 501; *st = sip_501_Not_implemented;
808                 break;
809         case 31:
810                 s = 480; *st = sip_480_Temporarily_unavailable;
811                 break;
812         case 34:
813                 s = 503; *st = sip_503_Service_unavailable;
814                 break;
815         case 38:
816                 s = 503; *st = sip_503_Service_unavailable;
817                 break;
818         case 41:
819                 s = 503; *st = sip_503_Service_unavailable;
820                 break;
821         case 42:
822                 s = 503; *st = sip_503_Service_unavailable;
823                 break;
824         case 47:
825                 s = 503; *st = sip_503_Service_unavailable;
826                 break;
827         case 55:
828                 s = 403; *st = sip_403_Forbidden;
829                 break;
830         case 57:
831                 s = 403; *st = sip_403_Forbidden;
832                 break;
833         case 58:
834                 s = 503; *st = sip_503_Service_unavailable;
835                 break;
836         case 65:
837                 s = 488; *st = sip_488_Not_acceptable;
838                 break;
839         case 69:
840                 s = 501; *st = sip_501_Not_implemented;
841                 break;
842         case 70:
843                 s = 488; *st = sip_488_Not_acceptable;
844                 break;
845         case 79:
846                 s = 501; *st = sip_501_Not_implemented;
847                 break;
848         case 87:
849                 s = 403; *st = sip_403_Forbidden;
850                 break;
851         case 88:
852                 s = 503; *st = sip_503_Service_unavailable;
853                 break;
854         case 102:
855                 s = 504; *st = sip_504_Gateway_time_out;
856                 break;
857         case 111:
858                 s = 500; *st = sip_500_Internal_server_error;
859                 break;
860         case 127:
861                 s = 500; *st = sip_500_Internal_server_error;
862                 break;
863         default:
864                 s = 468; *st = sip_486_Busy_here;
865         }
866
867         return s;
868 }
869
870 /* use STUN ip, or return the ip without change */
871 unsigned int Psip::get_local_ip(unsigned int ip)
872 {
873         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
874
875         if (inst->public_ip[0]) {
876                 PDEBUG(DEBUG_SIP, "RTP local IP is replaced by STUN ip %s\n", inst->public_ip);
877                 inet_pton(AF_INET, inst->public_ip, &ip);
878                 return htonl(ip);
879         }
880         return ip;
881 }
882
883 /*
884  * endpoint sends messages to the SIP port
885  */
886
887 int Psip::message_connect(unsigned int epoint_id, int message_id, union parameter *param)
888 {
889         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
890         const char *sdp_str = NULL;
891         struct lcr_msg *message;
892         struct interface *interface;
893         int media_type;
894         unsigned char payload_type;
895
896         interface = getinterfacebyname(inst->interface_name);
897         if (!interface) {
898                 PERROR("Cannot find interface %s.\n", inst->interface_name);
899                 return 0;
900         }
901
902         if (param->connectinfo.rtpinfo.port) {
903                 PDEBUG(DEBUG_SIP, "RTP info given by remote, forward that\n");
904                 p_s_rtp_bridge = 1;
905                 media_type = param->connectinfo.rtpinfo.media_types[0];
906                 payload_type = param->connectinfo.rtpinfo.payload_types[0];
907                 p_s_rtp_ip_local = param->connectinfo.rtpinfo.ip;
908                 p_s_rtp_port_local = param->connectinfo.rtpinfo.port;
909                 PDEBUG(DEBUG_SIP, "payload type %d\n", payload_type);
910                 PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
911                 PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
912         } else {
913                 PDEBUG(DEBUG_SIP, "RTP info not given by remote, so we do our own RTP\n");
914                 media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
915                 payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
916                 /* open local RTP peer (if not bridging) */
917                 if (rtp_connect() < 0) {
918                         nua_cancel(p_s_handle, TAG_END());
919                         nua_handle_destroy(p_s_handle);
920                         p_s_handle = NULL;
921                         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
922                         add_trace("reason", NULL, "failed to connect RTP/RTCP sockts");
923                         end_trace();
924                         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
925                         message->param.disconnectinfo.cause = 41;
926                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
927                         message_put(message);
928                         new_state(PORT_STATE_RELEASE);
929                         trigger_work(&p_s_delete);
930                         return 0;
931                 }
932         }
933
934         sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, 1, &payload_type, &media_type);
935         PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
936
937         /* NOTE:
938          * If this response causes corrupt messages, like SDP body inside or
939          * before header, check if the sofia-sip-gcc-4.8.patch was applied.
940          * If it is still corrupted, try to disable optimization when compiling
941          * sofia-sip.
942          */
943         nua_respond(p_s_handle, SIP_200_OK,
944                 NUTAG_MEDIA_ENABLE(0),
945                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
946                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
947
948         new_state(PORT_STATE_CONNECT);
949         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
950         add_trace("respond", "value", "200 OK");
951         add_trace("reason", NULL, "call connected");
952         struct in_addr ia;
953         memset(&ia, 0, sizeof(ia));
954         ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
955         add_trace("rtp", "ip", "%s", inet_ntoa(ia));
956         add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
957         add_trace("rtp", "payload", "%s:%d", media_type2name(media_type), payload_type);
958         end_trace();
959
960         return 0;
961 }
962
963 int Psip::message_release(unsigned int epoint_id, int message_id, union parameter *param)
964 {
965         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
966         struct lcr_msg *message;
967         char cause_str[128] = "";
968         int cause = param->disconnectinfo.cause;
969         int location = param->disconnectinfo.cause;
970         int status;
971         const char *status_text;
972
973         if (cause > 0 && cause <= 127) {
974                 SPRINT(cause_str, "Q.850;cause=%d;text=\"%s\"", cause, isdn_cause[cause].english);
975         }
976
977         switch (p_state) {
978         case PORT_STATE_OUT_SETUP:
979         case PORT_STATE_OUT_PROCEEDING:
980         case PORT_STATE_OUT_ALERTING:
981                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will cancel\n");
982                 sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
983                 if (cause_str[0])
984                         add_trace("cause", "value", "%d", cause);
985                 end_trace();
986                 nua_cancel(p_s_handle, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
987                 break;
988         case PORT_STATE_IN_SETUP:
989         case PORT_STATE_IN_PROCEEDING:
990         case PORT_STATE_IN_ALERTING:
991                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will respond\n");
992                 status = cause2status(cause, location, &status_text);
993                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
994                 if (cause_str[0])
995                         add_trace("cause", "value", "%d", cause);
996                 add_trace("respond", "value", "%d %s", status, status_text);
997                 end_trace();
998                 nua_respond(p_s_handle, status, status_text, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
999                 nua_handle_destroy(p_s_handle);
1000                 p_s_handle = NULL;
1001                 trigger_work(&p_s_delete);
1002                 break;
1003         default:
1004                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will perform nua_bye\n");
1005                 sip_trace_header(this, inst->interface_name, "BYE", DIRECTION_OUT);
1006                 if (cause_str[0])
1007                         add_trace("cause", "value", "%d", cause);
1008                 end_trace();
1009                 nua_bye(p_s_handle, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
1010         }
1011
1012         if (message_id == MESSAGE_DISCONNECT) {
1013                 while(p_epointlist) {
1014                         message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1015                         message->param.disconnectinfo.cause = CAUSE_NORMAL;
1016                         message->param.disconnectinfo.location = LOCATION_BEYOND;
1017                         message_put(message);
1018                         /* remove epoint */
1019                         free_epointlist(p_epointlist);
1020                 }
1021         }
1022
1023         new_state(PORT_STATE_RELEASE);
1024
1025         return(0);
1026 }
1027
1028 int Psip::message_setup(unsigned int epoint_id, int message_id, union parameter *param)
1029 {
1030         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1031         char from[128] = "";
1032         char asserted_id[128] = "", asserted_msg[256] = "";
1033         char to[128] = "";
1034         char contact[128] = "";
1035         const char *local = inst->local_peer;
1036         char local_ip[16];
1037         const char *remote = inst->remote_peer;
1038         const char *sdp_str = NULL;
1039         struct epoint_list *epointlist;
1040         sip_cseq_t *cseq = NULL;
1041         struct lcr_msg *message;
1042         int lcr_media = { (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW };
1043         unsigned char lcr_payload = { (options.law=='a') ? (unsigned char )PAYLOAD_TYPE_ALAW : (unsigned char )PAYLOAD_TYPE_ULAW };
1044         int *media_types;
1045         unsigned char *payload_types;
1046         int payloads = 0;
1047         int i;
1048
1049         if (!remote[0]) {
1050                 sip_trace_header(this, inst->interface_name, "INVITE", DIRECTION_OUT);
1051                 add_trace("failed", "reason", "No remote peer set or no peer has registered to us.");
1052                 end_trace();
1053                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1054                 message->param.disconnectinfo.cause = 27;
1055                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1056                 message_put(message);
1057                 new_state(PORT_STATE_RELEASE);
1058                 trigger_work(&p_s_delete);
1059                 return 0;
1060         }
1061         
1062         PDEBUG(DEBUG_SIP, "Doing Setup (inst %p)\n", inst);
1063
1064         memcpy(&p_dialinginfo, &param->setup.dialinginfo, sizeof(p_dialinginfo));
1065         memcpy(&p_callerinfo, &param->setup.callerinfo, sizeof(p_callerinfo));
1066 //      memcpy(&p_redirinfo, &param->setup.redirinfo, sizeof(p_redirinfo));
1067         do_screen(1, p_callerinfo.id, sizeof(p_callerinfo.id), &p_callerinfo.ntype, &p_callerinfo.present, inst->interface_name);
1068 //      do_screen(1, p_redirinfo.id, sizeof(p_redirinfo.id), &p_redirinfo.ntype, &p_redirinfo.present, inst->interface_name);
1069
1070         if (param->setup.rtpinfo.port) {
1071                 PDEBUG(DEBUG_SIP, "RTP info given by remote, forward that\n");
1072                 p_s_rtp_bridge = 1;
1073                 media_types = param->setup.rtpinfo.media_types;
1074                 payload_types = param->setup.rtpinfo.payload_types;
1075                 payloads = param->setup.rtpinfo.payloads;
1076                 p_s_rtp_ip_local = param->setup.rtpinfo.ip;
1077                 p_s_rtp_port_local = param->setup.rtpinfo.port;
1078                 PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
1079                 PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
1080         } else {
1081                 PDEBUG(DEBUG_SIP, "RTP info not given by remote, so we do our own RTP\n");
1082                 p_s_rtp_bridge = 0;
1083                 media_types = &lcr_media;
1084                 payload_types = &lcr_payload;
1085                 payloads = 1;
1086
1087                 /* open local RTP peer (if not bridging) */
1088                 if (rtp_open() < 0) {
1089                         PERROR("Failed to open RTP sockets\n");
1090                         /* send release message to endpoit */
1091                         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1092                         message->param.disconnectinfo.cause = 41;
1093                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1094                         message_put(message);
1095                         new_state(PORT_STATE_RELEASE);
1096                         trigger_work(&p_s_delete);
1097                         return 0;
1098                 }
1099                 if (!p_s_rtp_ip_local) {
1100                         char *p;
1101
1102                         /* extract IP from local peer */
1103                         SCPY(local_ip, local);
1104                         p = strchr(local_ip, ':');
1105                         if (p)
1106                                 *p = '\0';
1107                         PDEBUG(DEBUG_SIP, "RTP local IP not known, so we use our local SIP ip %s\n", local_ip);
1108                         inet_pton(AF_INET, local_ip, &p_s_rtp_ip_local);
1109                         p_s_rtp_ip_local = ntohl(p_s_rtp_ip_local);
1110                 }
1111         }
1112
1113         p_s_handle = nua_handle(inst->nua, NULL, TAG_END());
1114         if (!p_s_handle) {
1115                 PERROR("Failed to create handle\n");
1116                 /* send release message to endpoit */
1117                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1118                 message->param.disconnectinfo.cause = 41;
1119                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1120                 message_put(message);
1121                 new_state(PORT_STATE_RELEASE);
1122                 trigger_work(&p_s_delete);
1123                 return 0;
1124         }
1125         /* apply handle to trace */
1126 //      sip_trace_header(this, inst->interface_name, "NEW handle", DIRECTION_IN);
1127 //      add_trace("handle", "new", "0x%x", p_s_handle);
1128 //      end_trace();
1129
1130         sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, payloads, payload_types, media_types);
1131         PDEBUG(DEBUG_SIP, "Using SDP for invite: %s\n", sdp_str);
1132
1133         SPRINT(from, "sip:%s@%s", p_callerinfo.id, remote);
1134         SPRINT(to, "sip:%s@%s", p_dialinginfo.id, remote);
1135         if (inst->asserted_id[0]) {
1136                 SPRINT(asserted_id, "sip:%s@%s", inst->asserted_id, remote);
1137                 SPRINT(asserted_msg, "P-Asserted-Identity: <%s>", asserted_id);
1138         }
1139         if (inst->public_ip[0]) {
1140                 char *p;
1141                 SPRINT(contact, "sip:%s@%s", p_callerinfo.id, inst->public_ip);
1142                 p = strchr(inst->local_peer, ':');
1143                 if (p)
1144                         SCAT(contact, p);
1145         }
1146
1147         sip_trace_header(this, inst->interface_name, "INVITE", DIRECTION_OUT);
1148         add_trace("from", "uri", "%s", from);
1149         add_trace("to", "uri", "%s", to);
1150         if (asserted_id[0])
1151                 add_trace("assert-id", "uri", "%s", asserted_id);
1152         struct in_addr ia;
1153         memset(&ia, 0, sizeof(ia));
1154         ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
1155         add_trace("rtp", "ip", "%s", inet_ntoa(ia));
1156         add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
1157         for (i = 0; i < payloads; i++)
1158                 add_trace("rtp", "payload", "%s:%d", media_type2name(media_types[i]), payload_types[i]);
1159         end_trace();
1160
1161 //      cseq = sip_cseq_create(sip_home, 123, SIP_METHOD_INVITE);
1162
1163         nua_invite(p_s_handle,
1164                 TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1165                 TAG_IF(to[0], SIPTAG_TO_STR(to)),
1166                 TAG_IF(asserted_msg[0], SIPTAG_HEADER_STR(asserted_msg)),
1167                 TAG_IF(contact[0], SIPTAG_CONTACT_STR(contact)),
1168                 TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1169                 NUTAG_MEDIA_ENABLE(0),
1170                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1171                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1172         new_state(PORT_STATE_OUT_SETUP);
1173
1174         p_s_invite_direction = DIRECTION_OUT;
1175
1176 #if 0
1177         PDEBUG(DEBUG_SIP, "do overlap\n");
1178         new_state(PORT_STATE_OUT_OVERLAP);
1179         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_OVERLAP);
1180         message_put(message);
1181 #else
1182         PDEBUG(DEBUG_SIP, "do proceeding\n");
1183         new_state(PORT_STATE_OUT_PROCEEDING);
1184         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_PROCEEDING);
1185         message_put(message);
1186 #endif
1187
1188         /* attach only if not already */
1189         epointlist = p_epointlist;
1190         while(epointlist) {
1191                 if (epointlist->epoint_id == epoint_id)
1192                         break;
1193                 epointlist = epointlist->next;
1194         }
1195         if (!epointlist)
1196                 epointlist_new(epoint_id);
1197
1198         return 0;
1199 }
1200         
1201 int Psip::message_notify(unsigned int epoint_id, int message_id, union parameter *param)
1202 {
1203 //      char 
1204 //      struct in_addr ia;
1205
1206         switch (param->notifyinfo.notify) {
1207         case INFO_NOTIFY_REMOTE_HOLD:
1208 #if 0
1209                 sdp_str = generate_sdp(0, 0, 0, NULL, NULL);
1210                 SPRINT(sdp_str,
1211                         "v=0\r\n"
1212                         "o=LCR-Sofia-SIP 0 0 IN IP4 0.0.0.0\r\n"
1213                         "s=SIP Call\r\n"
1214                         "c=IN IP4 0.0.0.0\r\n"
1215                         "t=0 0\r\n"
1216                         );
1217                 PDEBUG(DEBUG_SIP, "Using SDP for hold: %s\n", sdp_str);
1218                 nua_info(p_s_handle,
1219 //                      TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1220 //                      TAG_IF(to[0], SIPTAG_TO_STR(to)),
1221 //                      TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1222                         NUTAG_MEDIA_ENABLE(0),
1223                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1224                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1225 #endif
1226                 break;
1227         case INFO_NOTIFY_REMOTE_RETRIEVAL:
1228 #if 0
1229                 sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, 1, &payload_type, &media_type);
1230                 PDEBUG(DEBUG_SIP, "Using SDP for rertieve: %s\n", sdp_str);
1231                 nua_info(p_s_handle,
1232 //                      TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1233 //                      TAG_IF(to[0], SIPTAG_TO_STR(to)),
1234 //                      TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1235                         NUTAG_MEDIA_ENABLE(0),
1236                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1237                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1238 #endif
1239                 break;
1240         }
1241
1242         return 0;
1243 }
1244
1245 int Psip::message_dtmf(unsigned int epoint_id, int message_id, union parameter *param)
1246 {
1247         char dtmf_str[64];
1248         
1249         /* prepare DTMF info payload */
1250         SPRINT(dtmf_str,
1251                 "Signal=%c\n"
1252                 "Duration=160\n"
1253                 , param->dtmf);
1254
1255         /* start invite to handle DTMF */
1256         nua_info(p_s_handle,
1257                 NUTAG_MEDIA_ENABLE(0),
1258                 SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
1259                 SIPTAG_PAYLOAD_STR(dtmf_str), TAG_END());
1260         
1261         return 0;
1262 }
1263
1264 /* NOTE: incomplete and not working */
1265 int Psip::message_information(unsigned int epoint_id, int message_id, union parameter *param)
1266 {
1267         char dtmf_str[64];
1268         
1269         /* prepare DTMF info payload */
1270         SPRINT(dtmf_str,
1271                 "Signal=%s\n"
1272                 "Duration=160\n"
1273                 , param->information.id);
1274
1275         /* start invite to handle DTMF */
1276         nua_info(p_s_handle,
1277                 NUTAG_MEDIA_ENABLE(0),
1278                 SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
1279                 SIPTAG_PAYLOAD_STR(dtmf_str), TAG_END());
1280         
1281         return 0;
1282 }
1283
1284 int Psip::message_epoint(unsigned int epoint_id, int message_id, union parameter *param)
1285 {
1286         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1287
1288         if (Port::message_epoint(epoint_id, message_id, param))
1289                 return 1;
1290
1291         switch(message_id) {
1292                 case MESSAGE_ALERTING: /* call is ringing on LCR side */
1293                 if (p_state != PORT_STATE_IN_SETUP
1294                  && p_state != PORT_STATE_IN_PROCEEDING)
1295                         return 0;
1296                 nua_respond(p_s_handle, SIP_180_RINGING, TAG_END());
1297                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1298                 add_trace("respond", "value", "180 Ringing");
1299                 end_trace();
1300                 new_state(PORT_STATE_IN_ALERTING);
1301                 return 1;
1302
1303                 case MESSAGE_CONNECT: /* call is connected on LCR side */
1304                 if (p_state != PORT_STATE_IN_SETUP
1305                  && p_state != PORT_STATE_IN_PROCEEDING
1306                  && p_state != PORT_STATE_IN_ALERTING)
1307                         return 0;
1308                 message_connect(epoint_id, message_id, param);
1309                 return 1;
1310
1311                 case MESSAGE_DISCONNECT: /* call has been disconnected */
1312                 case MESSAGE_RELEASE: /* call has been released */
1313                 message_release(epoint_id, message_id, param);
1314                 return 1;
1315
1316                 case MESSAGE_SETUP: /* dial-out command received from epoint */
1317                 message_setup(epoint_id, message_id, param);
1318                 return 1;
1319
1320                 case MESSAGE_INFORMATION: /* overlap dialing */
1321                 if (p_state != PORT_STATE_OUT_OVERLAP)
1322                         return 0;
1323                 message_information(epoint_id, message_id, param);
1324                 return 1;
1325
1326                 case MESSAGE_DTMF: /* DTMF info to be transmitted via INFO transaction */
1327                 if (p_state == PORT_STATE_CONNECT)
1328                         message_dtmf(epoint_id, message_id, param);
1329                 case MESSAGE_NOTIFY: /* notification about remote hold/retrieve */
1330                 if (p_state == PORT_STATE_CONNECT)
1331                         message_notify(epoint_id, message_id, param);
1332                 return(1);
1333
1334                 default:
1335                 PDEBUG(DEBUG_SIP, "PORT(%s) SIP port with (caller id %s) received an unsupported message: %d\n", p_name, p_callerinfo.id, message_id);
1336         }
1337
1338         return 0;
1339 }
1340
1341 int Psip::parse_sdp(sip_t const *sip, unsigned int *ip, unsigned short *port, uint8_t *payload_types, int *media_types, int *payloads, int max_payloads)
1342 {
1343         *payloads = 0;
1344
1345         if (!sip->sip_payload) {
1346                 PDEBUG(DEBUG_SIP, "no payload given\n");
1347                 return 0;
1348         }
1349
1350         sdp_parser_t *parser;
1351         sdp_session_t *sdp;
1352         sdp_media_t *m;
1353         sdp_attribute_t *attr;
1354         sdp_rtpmap_t *map;
1355         sdp_connection_t *conn;
1356
1357         PDEBUG(DEBUG_SIP, "payload given: %s\n", sip->sip_payload->pl_data);
1358
1359         parser = sdp_parse(NULL, sip->sip_payload->pl_data, (int) strlen(sip->sip_payload->pl_data), 0);
1360         if (!parser) {
1361                 return 400;
1362         }
1363         if (!(sdp = sdp_session(parser))) {
1364                 sdp_parser_free(parser);
1365                 return 400;
1366         }
1367         for (m = sdp->sdp_media; m; m = m->m_next) {
1368                 if (m->m_proto != sdp_proto_rtp)
1369                         continue;
1370                 if (m->m_type != sdp_media_audio)
1371                         continue;
1372                 PDEBUG(DEBUG_SIP, "RTP port:'%u'\n", m->m_port);
1373                 *port = m->m_port;
1374                 for (attr = m->m_attributes; attr; attr = attr->a_next) {
1375                         PDEBUG(DEBUG_SIP, "ATTR: name:'%s' value='%s'\n", attr->a_name, attr->a_value);
1376                 }
1377                 if (m->m_connections) {
1378                         conn = m->m_connections;
1379                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", conn->c_address);
1380                         inet_pton(AF_INET, conn->c_address, ip);
1381                         *ip = ntohl(p_s_rtp_ip_remote);
1382                 } else {
1383                         char *p = sip->sip_payload->pl_data;
1384                         char addr[16];
1385
1386                         PDEBUG(DEBUG_SIP, "sofia cannot find connection tag, so we try ourself\n");
1387                         p = strstr(p, "c=IN IP4 ");
1388                         if (!p) {
1389                                 PDEBUG(DEBUG_SIP, "missing c-tag with internet address\n");
1390                                 sdp_parser_free(parser);
1391                                 return 400;
1392                         }
1393                         SCPY(addr, p + 9);
1394                         if ((p = strchr(addr, '\n'))) *p = '\0';
1395                         if ((p = strchr(addr, '\r'))) *p = '\0';
1396                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", addr);
1397                         inet_pton(AF_INET, addr, ip);
1398                         *ip = ntohl(p_s_rtp_ip_remote);
1399                 }
1400                 for (map = m->m_rtpmaps; map; map = map->rm_next) {
1401                         int media_type = 0;
1402
1403                         PDEBUG(DEBUG_SIP, "RTPMAP: coding:'%s' rate='%d' pt='%d'\n", map->rm_encoding, map->rm_rate, map->rm_pt);
1404                         /* append to payload list, if there is space */
1405                         add_trace("rtp", "payload", "%s:%d", map->rm_encoding, map->rm_pt);
1406                         if (map->rm_pt == PAYLOAD_TYPE_ALAW)
1407                                 media_type = MEDIA_TYPE_ALAW;
1408                         else if (map->rm_pt == PAYLOAD_TYPE_ULAW)
1409                                 media_type = MEDIA_TYPE_ULAW;
1410                         else if (map->rm_pt == PAYLOAD_TYPE_GSM)
1411                                 media_type = MEDIA_TYPE_GSM;
1412                         else if (!strcmp(map->rm_encoding, "GSM-EFR"))
1413                                 media_type = MEDIA_TYPE_GSM_EFR;
1414                         else if (!strcmp(map->rm_encoding, "AMR"))
1415                                 media_type = MEDIA_TYPE_AMR;
1416                         else if (!strcmp(map->rm_encoding, "GSM-HR"))
1417                                 media_type = MEDIA_TYPE_GSM_HR;
1418                         if (media_type && *payloads <= max_payloads) {
1419                                 *payload_types++ = map->rm_pt;
1420                                 *media_types++ = media_type;
1421                                 (*payloads)++;
1422                         }
1423                 }
1424         }
1425
1426         sdp_parser_free(parser);
1427
1428         return 0;
1429 }
1430
1431 const char *Psip::generate_sdp(unsigned int rtp_ip_local, unsigned short rtp_port_local, int payloads, unsigned char *payload_types, int *media_types)
1432 {
1433         struct in_addr ia;
1434         static char sdp_str[256], sub_str[128];
1435         int i;
1436
1437         memset(&ia, 0, sizeof(ia));
1438         ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
1439         SPRINT(sdp_str,
1440                 "v=0\r\n"
1441                 "o=LCR-Sofia-SIP 0 0 IN IP4 %s\r\n"
1442                 "s=SIP Call\r\n"
1443                 "c=IN IP4 %s\r\n"
1444                 "t=0 0\r\n", inet_ntoa(ia), inet_ntoa(ia));
1445         if (payloads) {
1446                 SPRINT(sub_str, "m=audio %d RTP/AVP", p_s_rtp_port_local);
1447                 SCAT(sdp_str, sub_str);
1448                 for (i = 0; i < payloads; i++) {
1449                         SPRINT(sub_str, " %d", payload_types[i]);
1450                         SCAT(sdp_str, sub_str);
1451                 }
1452                 SCAT(sdp_str, "\r\n");
1453                 for (i = 0; i < payloads; i++) {
1454                         SPRINT(sub_str, "a=rtpmap:%d %s/8000\r\n", payload_types[i], media_type2name(media_types[i]));
1455                         SCAT(sdp_str, sub_str);
1456                 }
1457         }
1458
1459         return sdp_str;
1460 }
1461
1462 static int challenge(struct sip_inst *inst, class Psip *psip, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1463 {
1464         sip_www_authenticate_t const *authenticate = NULL;
1465         char const *realm = NULL;
1466         char const *scheme = NULL;
1467         int i;
1468         char *cur;
1469         char authentication[256] = "";
1470         PDEBUG(DEBUG_SIP, "challenge order received\n");
1471
1472         if (!inst->auth_user[0]) {
1473                 PDEBUG(DEBUG_SIP, "No credentials available\n");
1474                 sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1475                 add_trace("error", NULL, "There are no credentials given for interface");
1476                 end_trace();
1477                 return -1;
1478         }
1479
1480         if (sip->sip_www_authenticate) {
1481                 authenticate = sip->sip_www_authenticate;
1482         } else if (sip->sip_proxy_authenticate) {
1483                 authenticate = sip->sip_proxy_authenticate;
1484         } else {
1485                 PDEBUG(DEBUG_SIP, "No authentication header found\n");
1486                 sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1487                 add_trace("error", NULL, "Authentication method unknwon");
1488                 end_trace();
1489                 return -1;
1490         }
1491
1492         scheme = (char const *) authenticate->au_scheme;
1493         if (authenticate->au_params) {
1494                 for (i = 0; (cur = (char *) authenticate->au_params[i]); i++) {
1495                         if ((realm = strstr(cur, "realm="))) {
1496                                 realm += 6;
1497                                 break;
1498                         }
1499                 }
1500         }
1501
1502         if (!scheme || !realm) {
1503                 PDEBUG(DEBUG_SIP, "No scheme or no realm in authentication header found\n");
1504                 sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1505                 add_trace("error", NULL, "Authentication header has no realm or scheme");
1506                 end_trace();
1507                 return -1;
1508         }
1509
1510         SPRINT(authentication, "%s:%s:%s:%s", scheme, realm, inst->auth_user, inst->auth_password);
1511         PDEBUG(DEBUG_SIP, "auth: '%s'\n", authentication);
1512
1513         sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1514         add_trace("scheme", NULL, "%s", scheme);
1515         add_trace("realm", NULL, "%s", realm);
1516         add_trace("user", NULL, "%s", inst->auth_user);
1517         add_trace("pass", NULL, "%s", inst->auth_password);
1518         end_trace();
1519
1520         nua_authenticate(nh, /*SIPTAG_EXPIRES_STR("3600"),*/ NUTAG_AUTH(authentication), TAG_END());
1521
1522         return 0;
1523 }
1524
1525 static void i_options(struct sip_inst *inst, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1526 {
1527         #define NUTAG_WITH_THIS_MSG(msg) nutag_with, tag_ptr_v(msg)
1528         nua_saved_event_t saved[1];
1529         nua_save_event(nua, saved);
1530         nua_event_data_t const *data = nua_event_data(saved);
1531
1532         sip_trace_header(NULL, inst->interface_name, "OPTIONS", DIRECTION_IN);
1533         end_trace();
1534
1535         sip_trace_header(NULL, inst->interface_name, "RESPOND", DIRECTION_OUT);
1536         add_trace("respond", "value", "200 OK");
1537         end_trace();
1538
1539         nua_respond(nh, SIP_200_OK, NUTAG_WITH_THIS_MSG(data->e_msg), TAG_END());
1540         nua_handle_destroy(nh);
1541         inst->register_handle = NULL;
1542 }
1543
1544 static void i_register(struct sip_inst *inst, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1545 {
1546         #define NUTAG_WITH_THIS_MSG(msg) nutag_with, tag_ptr_v(msg)
1547         nua_saved_event_t saved[1];
1548         sip_contact_t const *contact = NULL;
1549         contact = sip->sip_contact;
1550         nua_save_event(nua, saved);
1551         nua_event_data_t const *data = nua_event_data(saved);
1552
1553         if (!inst->allow_register) {
1554                 sip_trace_header(NULL, inst->interface_name, "REGISTER", DIRECTION_IN);
1555                 add_trace("error", NULL, "forbidden, because we don't accept registration");
1556                 end_trace();
1557                 nua_respond(nh, SIP_403_FORBIDDEN, NUTAG_WITH_THIS_MSG(data->e_msg), TAG_END());
1558                 nua_handle_destroy(nh);
1559                 inst->register_handle = NULL;
1560                 return;
1561         }
1562
1563         if (contact->m_url->url_host)
1564                 SCPY(inst->remote_peer, contact->m_url->url_host);
1565         if (contact->m_url->url_port && contact->m_url->url_port[0]) {
1566                 SCAT(inst->remote_peer, ":");
1567                 SCAT(inst->remote_peer, contact->m_url->url_port);
1568         }
1569
1570         sip_trace_header(NULL, inst->interface_name, "REGISTER", DIRECTION_IN);
1571         add_trace("contact", "uri", "%s", inst->remote_peer);
1572         end_trace();
1573
1574         sip_trace_header(NULL, inst->interface_name, "RESPOND", DIRECTION_OUT);
1575         add_trace("respond", "value", "200 OK");
1576         add_trace("reason", NULL, "peer registered");
1577         end_trace();
1578
1579         nua_respond(nh, SIP_200_OK, SIPTAG_CONTACT(sip->sip_contact), NUTAG_WITH_THIS_MSG(data->e_msg), TAG_END());
1580         nua_handle_destroy(nh);
1581         inst->register_handle = NULL;
1582 }
1583
1584 static void r_register(struct sip_inst *inst, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1585 {
1586         int rc;
1587
1588         sip_trace_header(NULL, inst->interface_name, "STATUS", DIRECTION_IN);
1589         add_trace("value", NULL, "%d", status);
1590         add_trace("phrase", NULL, "%s", phrase);
1591         end_trace();
1592
1593         switch (status) {
1594         case 200:
1595                 status_200:
1596                 /* if not registered, become registered and start register interval timer */
1597                 if (inst->register_state != REGISTER_STATE_REGISTERED) {
1598                         if (inst->register_interval)
1599                                 schedule_timer(&inst->register_retry_timer, inst->register_interval, 0);
1600                         inst->register_state = REGISTER_STATE_REGISTERED;
1601                 }
1602                 /* start option timer */
1603                 if (inst->options_interval)
1604                         PDEBUG(DEBUG_SIP, "register ok, scheduling option timer with %d seconds\n", inst->options_interval);
1605                         schedule_timer(&inst->register_option_timer, inst->options_interval, 0);
1606                 break;
1607         case 401:
1608         case 407:
1609                 PDEBUG(DEBUG_SIP, "Register challenge received\n");
1610                 rc = challenge(inst, NULL, status, phrase, nua, magic, nh, hmagic, sip, tags);
1611                 if (rc < 0)
1612                         goto status_400;
1613                 break;
1614         default:
1615                 if (status >= 200 && status <= 299)
1616                         goto status_200;
1617                 if (status < 400)
1618                         break;
1619                 status_400:
1620                 PDEBUG(DEBUG_SIP, "Register failed, starting register timer\n");
1621                 inst->register_state = REGISTER_STATE_FAILED;
1622                 nua_handle_destroy(nh);
1623                 inst->register_handle = NULL;
1624                 /* stop option timer */
1625                 unsched_timer(&inst->register_option_timer);
1626                 /* if failed, start register interval timer with REGISTER_RETRY_TIMER */
1627                 schedule_timer(&inst->register_retry_timer, REGISTER_RETRY_TIMER);
1628         }
1629 }
1630
1631 void Psip::i_invite(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1632 {
1633         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1634         const char *from = "", *to = "", *name = "";
1635         char imsi[16] = "";
1636         int ret;
1637         class Endpoint *epoint;
1638         struct lcr_msg *message;
1639         struct interface *interface;
1640         const char *sdp_str = NULL;
1641         int media_types[32];
1642         uint8_t payload_types[32];
1643         int payloads = 0;
1644         unsigned char payload_type;
1645         int media_type;
1646
1647         interface = getinterfacebyname(inst->interface_name);
1648         if (!interface) {
1649                 PERROR("Cannot find interface %s.\n", inst->interface_name);
1650                 return;
1651         }
1652
1653         if (sip->sip_from) {
1654                 if (sip->sip_from->a_url)
1655                         from = sip->sip_from->a_url->url_user;
1656                 if (sip->sip_from->a_display) {
1657                         name = sip->sip_from->a_display;
1658                         if (!strncmp(name, "\"IMSI", 5)) {
1659                                 strncpy(imsi, name + 5, 15);
1660                                 imsi[15] = '\0';
1661                                 name = "";
1662                         }
1663                 }
1664         }
1665         if (sip->sip_to) {
1666                 if (sip->sip_to->a_url)
1667                         to = sip->sip_to->a_url->url_user;
1668         }
1669         PDEBUG(DEBUG_SIP, "invite received (%s->%s)\n", from, to);
1670
1671         sip_trace_header(this, inst->interface_name, "Payload received", DIRECTION_NONE);
1672         ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
1673         if (!ret) {
1674                 /* if no RTP bridge, we must support LAW codec, otherwise we forward what we have */
1675                 if (!p_s_rtp_bridge) {
1676                         int i;
1677
1678                         /* check if supported payload type exists */
1679                         for (i = 0; i < payloads; i++) {
1680                                 if (media_types[i] == ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW))
1681                                         break;
1682                         }
1683                         if (i == payloads) {
1684                                 add_trace("error", NULL, "Expected LAW payload type (not bridged)");
1685                                 ret = 415;
1686                         }
1687                 }
1688         }
1689         end_trace();
1690         if (ret) {
1691                 if (ret == 400)
1692                         nua_respond(nh, SIP_400_BAD_REQUEST, TAG_END());
1693                 else
1694                         nua_respond(nh, SIP_415_UNSUPPORTED_MEDIA, TAG_END());
1695                 nua_handle_destroy(nh);
1696                 p_s_handle = NULL;
1697                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1698                 if (ret == 400)
1699                         add_trace("respond", "value", "415 Unsupported Media");
1700                 else
1701                         add_trace("respond", "value", "400 Bad Request");
1702                 add_trace("reason", NULL, "offered codec does not match");
1703                 end_trace();
1704                 if (p_state != PORT_STATE_IDLE) {
1705                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_RELEASE);
1706                         message->param.disconnectinfo.cause = 41;
1707                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1708                         message_put(message);
1709                 }
1710                 new_state(PORT_STATE_RELEASE);
1711                 trigger_work(&p_s_delete);
1712                 return;
1713         }
1714
1715         /* handle re-invite */
1716         if (p_state != PORT_STATE_IDLE) {
1717                 sip_trace_header(this, inst->interface_name, "RE-INVITE", DIRECTION_IN);
1718                 end_trace();
1719                 if (p_s_rtp_bridge) {
1720                         PDEBUG(DEBUG_SIP, "RE-INVITE not implemented for RTP forwarding\n");
1721                         nua_respond(nh, SIP_501_NOT_IMPLEMENTED, TAG_END());
1722                         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1723                         add_trace("respond", "value", "501 NOT IMPLEMENTED");
1724                         add_trace("reason", NULL, "RE-INVITE not implemented for RTP forwarding");
1725                         end_trace();
1726                 } else {
1727                         PDEBUG(DEBUG_SIP, "RTP info given by remote, forward that\n");
1728                         media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
1729                         payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
1730                         if (rtp_connect() < 0) {
1731                                 goto rtp_failed;
1732                         }
1733                         sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, 1, &payload_type, &media_type);
1734                         PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
1735                         nua_respond(p_s_handle, SIP_200_OK,
1736                                 NUTAG_MEDIA_ENABLE(0),
1737                                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1738                                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1739                 }
1740                 return;
1741         }
1742
1743         /* open local RTP peer (if not bridging) */
1744         if (!p_s_rtp_bridge && rtp_open() < 0) {
1745                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1746                 nua_handle_destroy(nh);
1747                 p_s_handle = NULL;
1748                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1749                 add_trace("respond", "value", "500 Internal Server Error");
1750                 add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1751                 end_trace();
1752                 new_state(PORT_STATE_RELEASE);
1753                 trigger_work(&p_s_delete);
1754                 return;
1755         }
1756
1757         /* apply handle */
1758 //      sip_trace_header(this, inst->interface_name, "NEW handle", DIRECTION_IN);
1759 //      add_trace("handle", "new", "0x%x", nh);
1760 //      end_trace();
1761 //
1762         p_s_handle = nh;
1763
1764         sip_trace_header(this, inst->interface_name, "INVITE", DIRECTION_IN);
1765         add_trace("rtp", "port", "%d", p_s_rtp_port_remote);
1766         /* caller information */
1767         if (!from[0]) {
1768                 p_callerinfo.present = INFO_PRESENT_NOTAVAIL;
1769                 p_callerinfo.ntype = INFO_NTYPE_NOTPRESENT;
1770                 add_trace("calling", "present", "unavailable");
1771         } else {
1772                 p_callerinfo.present = INFO_PRESENT_ALLOWED;
1773                 add_trace("calling", "present", "allowed");
1774                 p_callerinfo.screen = INFO_SCREEN_NETWORK;
1775                 p_callerinfo.ntype = INFO_NTYPE_UNKNOWN;
1776                 SCPY(p_callerinfo.id, from);
1777                 add_trace("calling", "number", "%s", from);
1778                 SCPY(p_callerinfo.name, name);
1779                 if (name[0])
1780                         add_trace("calling", "name", "%s", name);
1781                 SCPY(p_callerinfo.imsi, imsi);
1782                 if (imsi[0])
1783                         add_trace("calling", "imsi", "%s", imsi);
1784         }
1785         SCPY(p_callerinfo.interface, inst->interface_name);
1786         /* dialing information */
1787         if (to[0]) {
1788                 p_dialinginfo.ntype = INFO_NTYPE_UNKNOWN;
1789                 SCAT(p_dialinginfo.id, to);
1790                 add_trace("dialing", "number", "%s", to);
1791         }
1792         /* redir info */
1793         /* bearer capability */
1794         p_capainfo.bearer_capa = INFO_BC_SPEECH;
1795         p_capainfo.bearer_info1 = (options.law=='a')?3:2;
1796         p_capainfo.bearer_mode = INFO_BMODE_CIRCUIT;
1797         add_trace("bearer", "capa", "speech");
1798         add_trace("bearer", "mode", "circuit");
1799         /* if packet mode works some day, see dss1.cpp for conditions */
1800         p_capainfo.source_mode = B_MODE_TRANSPARENT;
1801
1802         end_trace();
1803
1804         /* create endpoint */
1805         if (p_epointlist)
1806                 FATAL("Incoming call but already got an endpoint.\n");
1807         if (!(epoint = new Endpoint(p_serial, 0)))
1808                 FATAL("No memory for Endpoint instance\n");
1809         epoint->ep_app = new_endpointapp(epoint, 0, interface->app); //incoming
1810         epointlist_new(epoint->ep_serial);
1811
1812 #ifdef NUTAG_AUTO100
1813         /* send trying (proceeding) */
1814         nua_respond(nh, SIP_100_TRYING, TAG_END());
1815         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1816         add_trace("respond", "value", "100 Trying");
1817         end_trace();
1818 #endif
1819
1820         new_state(PORT_STATE_IN_PROCEEDING);
1821
1822         /* send setup message to endpoit */
1823         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_SETUP);
1824         message->param.setup.port_type = p_type;
1825 //      message->param.setup.dtmf = 0;
1826         memcpy(&message->param.setup.dialinginfo, &p_dialinginfo, sizeof(struct dialing_info));
1827         memcpy(&message->param.setup.callerinfo, &p_callerinfo, sizeof(struct caller_info));
1828         memcpy(&message->param.setup.capainfo, &p_capainfo, sizeof(struct capa_info));
1829 //      SCPY((char *)message->param.setup.useruser.data, useruser.info);
1830 //      message->param.setup.useruser.len = strlen(mncc->useruser.info);
1831 //      message->param.setup.useruser.protocol = mncc->useruser.proto;
1832         if (p_s_rtp_bridge) {
1833                 int i;
1834
1835                 PDEBUG(DEBUG_SIP, "sending setup with RTP info\n");
1836                 message->param.setup.rtpinfo.ip = p_s_rtp_ip_remote;
1837                 message->param.setup.rtpinfo.port = p_s_rtp_port_remote;
1838                 /* add codecs to setup message */
1839                 for (i = 0; i < payloads; i++) {
1840                         message->param.setup.rtpinfo.media_types[i] = media_types[i];
1841                         message->param.setup.rtpinfo.payload_types[i] = payload_types[i];
1842                         if (i == sizeof(message->param.setup.rtpinfo.payload_types))
1843                                 break;
1844                 }
1845                 message->param.setup.rtpinfo.payloads = i;
1846         }
1847         message_put(message);
1848
1849         /* start option timer */
1850         if (inst->options_interval) {
1851                 PDEBUG(DEBUG_SIP, "Invite received, scheduling option timer with %d seconds\n", inst->options_interval);
1852                 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
1853         }
1854
1855         p_s_invite_direction = DIRECTION_IN;
1856
1857         /* send progress, if tones are available and if we don't bridge */
1858         if (!p_s_rtp_bridge && interface->is_tones == IS_YES) {
1859                 PDEBUG(DEBUG_SIP, "Connecting audio, since we have tones available\n");
1860                 media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
1861                 payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
1862                 /* open local RTP peer (if not bridging) */
1863                 if (rtp_connect() < 0) {
1864 rtp_failed:
1865                         nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1866                         nua_handle_destroy(nh);
1867                         p_s_handle = NULL;
1868                         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1869                         add_trace("respond", "value", "500 Internal Server Error");
1870                         add_trace("reason", NULL, "failed to connect RTP/RTCP sockts");
1871                         end_trace();
1872                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_RELEASE);
1873                         message->param.disconnectinfo.cause = 41;
1874                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1875                         message_put(message);
1876                         new_state(PORT_STATE_RELEASE);
1877                         trigger_work(&p_s_delete);
1878                         return;
1879                 }
1880
1881                 sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, 1, &payload_type, &media_type);
1882                 PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
1883
1884                 nua_respond(p_s_handle, SIP_183_SESSION_PROGRESS,
1885                         NUTAG_MEDIA_ENABLE(0),
1886                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1887                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1888                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1889                 add_trace("respond", "value", "183 SESSION PROGRESS");
1890                 add_trace("reason", NULL, "audio available");
1891                 struct in_addr ia;
1892                 memset(&ia, 0, sizeof(ia));
1893                 ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
1894                 add_trace("rtp", "ip", "%s", inet_ntoa(ia));
1895                 add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
1896                 add_trace("rtp", "payload", "%s:%d", media_type2name(media_type), payload_type);
1897                 end_trace();
1898         }
1899 }
1900
1901 void Psip::i_options(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1902 {
1903         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1904
1905         PDEBUG(DEBUG_SIP, "options received\n");
1906
1907         sip_trace_header(this, inst->interface_name, "OPTIONS", DIRECTION_IN);
1908         end_trace();
1909
1910         nua_respond(nh, SIP_200_OK, TAG_END());
1911 }
1912
1913 void Psip::i_bye(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1914 {
1915         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1916         struct lcr_msg *message;
1917         int cause = 0;
1918
1919         PDEBUG(DEBUG_SIP, "bye received\n");
1920
1921         sip_trace_header(this, inst->interface_name, "BYE", DIRECTION_IN);
1922         if (sip->sip_reason && sip->sip_reason->re_protocol && !strcasecmp(sip->sip_reason->re_protocol, "Q.850") && sip->sip_reason->re_cause) {
1923                 cause = atoi(sip->sip_reason->re_cause);
1924                 add_trace("cause", "value", "%d", cause);
1925         }
1926         end_trace();
1927
1928 // let stack do bye automaticall, since it will not accept our response for some reason
1929 //      nua_respond(nh, SIP_200_OK, TAG_END());
1930         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1931         add_trace("respond", "value", "200 OK");
1932         end_trace();
1933 //      nua_handle_destroy(nh);
1934         p_s_handle = NULL;
1935
1936         rtp_close();
1937
1938         while(p_epointlist) {
1939                 /* send setup message to endpoit */
1940                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1941                 message->param.disconnectinfo.cause = cause ? : 16;
1942                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1943                 message_put(message);
1944                 /* remove epoint */
1945                 free_epointlist(p_epointlist);
1946         }
1947         new_state(PORT_STATE_RELEASE);
1948         trigger_work(&p_s_delete);
1949 }
1950
1951 void Psip::i_cancel(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1952 {
1953         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1954         struct lcr_msg *message;
1955
1956         PDEBUG(DEBUG_SIP, "cancel received\n");
1957
1958         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_IN);
1959         end_trace();
1960
1961         nua_handle_destroy(nh);
1962         p_s_handle = NULL;
1963
1964         rtp_close();
1965
1966         while(p_epointlist) {
1967                 /* send setup message to endpoit */
1968                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1969                 message->param.disconnectinfo.cause = 16;
1970                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1971                 message_put(message);
1972                 /* remove epoint */
1973                 free_epointlist(p_epointlist);
1974         }
1975         new_state(PORT_STATE_RELEASE);
1976         trigger_work(&p_s_delete);
1977 }
1978
1979 void Psip::r_bye(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1980 {
1981         PDEBUG(DEBUG_SIP, "bye response received\n");
1982
1983         nua_handle_destroy(nh);
1984         p_s_handle = NULL;
1985
1986         rtp_close();
1987
1988         trigger_work(&p_s_delete);
1989 }
1990
1991 void Psip::r_cancel(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1992 {
1993         PDEBUG(DEBUG_SIP, "cancel response received\n");
1994
1995         nua_handle_destroy(nh);
1996         p_s_handle = NULL;
1997
1998         rtp_close();
1999
2000         trigger_work(&p_s_delete);
2001 }
2002
2003 void Psip::r_invite(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2004 {
2005         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2006         struct lcr_msg *message;
2007         int cause = 0, location = 0;
2008         int media_types[32];
2009         uint8_t payload_types[32];
2010         int payloads = 0;
2011
2012         PDEBUG(DEBUG_SIP, "response to invite received (status = %d)\n", status);
2013
2014         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2015         add_trace("respond", "value", "%d", status);
2016         end_trace();
2017
2018         /* connect audio */
2019         if (status == 183 || (status >= 200 && status <= 299)) {
2020                 int ret;
2021
2022                 sip_trace_header(this, inst->interface_name, "Payload received", DIRECTION_NONE);
2023                 ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
2024                 if (!ret) {
2025                         if (payloads != 1)
2026                                 ret = 415;
2027                         else if (!p_s_rtp_bridge) {
2028                                 if (media_types[0] != ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW)) {
2029                                         add_trace("error", NULL, "Expected LAW payload type (not bridged)");
2030                                         ret = 415;
2031                                 }
2032                         }
2033                 }
2034                 end_trace();
2035                 if (ret) {
2036                         nua_cancel(nh, TAG_END());
2037                         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
2038                         add_trace("reason", NULL, "accepted codec does not match");
2039                         end_trace();
2040                         cause = 88;
2041                         location = LOCATION_PRIVATE_LOCAL;
2042                         goto release_with_cause;
2043                 }
2044
2045                 /* connect to remote RTP (if not bridging) */
2046                 if (!p_s_rtp_bridge && rtp_connect() < 0) {
2047                         nua_cancel(nh, TAG_END());
2048                         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
2049                         add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
2050                         end_trace();
2051                         cause = 31;
2052                         location = LOCATION_PRIVATE_LOCAL;
2053                         goto release_with_cause;
2054                 }
2055         }
2056
2057         /* start option timer */
2058         if (inst->options_interval) {
2059                 PDEBUG(DEBUG_SIP, "Invite response, scheduling option timer with %d seconds\n", inst->options_interval);
2060                 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
2061         }
2062
2063         switch (status) {
2064         case 100:
2065 #if 0
2066                 PDEBUG(DEBUG_SIP, "do proceeding\n");
2067                 new_state(PORT_STATE_OUT_PROCEEDING);
2068                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROCEEDING);
2069                 message_put(message);
2070 #endif
2071                 return;
2072         case 180:
2073                 PDEBUG(DEBUG_SIP, "do alerting\n");
2074                 new_state(PORT_STATE_OUT_ALERTING);
2075                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_ALERTING);
2076                 message_put(message);
2077                 return;
2078         case 183:
2079                 PDEBUG(DEBUG_SIP, "do progress\n");
2080                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROGRESS);
2081                 message->param.progressinfo.progress = 8;
2082                 message->param.progressinfo.location = 10;
2083                 if (p_s_rtp_bridge) {
2084                         message->param.progressinfo.rtpinfo.ip = p_s_rtp_ip_remote;
2085                         message->param.progressinfo.rtpinfo.port = p_s_rtp_port_remote;
2086                         message->param.progressinfo.rtpinfo.media_types[0] = media_types[0];
2087                         message->param.progressinfo.rtpinfo.payload_types[0] = payload_types[0];
2088                         message->param.progressinfo.rtpinfo.payloads = 1;
2089                 }
2090                 message_put(message);
2091                 return;
2092         case 200:
2093                 status_200:
2094                 PDEBUG(DEBUG_SIP, "do connect\n");
2095                 nua_ack(nh, TAG_END());
2096                 new_state(PORT_STATE_CONNECT);
2097                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CONNECT);
2098                 if (p_s_rtp_bridge) {
2099                         message->param.connectinfo.rtpinfo.ip = p_s_rtp_ip_remote;
2100                         message->param.connectinfo.rtpinfo.port = p_s_rtp_port_remote;
2101                         message->param.connectinfo.rtpinfo.media_types[0] = media_types[0];
2102                         message->param.connectinfo.rtpinfo.payload_types[0] = payload_types[0];
2103                         message->param.connectinfo.rtpinfo.payloads = 1;
2104                 }
2105                 message_put(message);
2106                 return;
2107         default:
2108                 if (status >= 200 && status <= 299)
2109                         goto status_200;
2110                 if (status < 100 || status > 199)
2111                         break;
2112                 PDEBUG(DEBUG_SIP, "skipping 1xx message\n");
2113
2114                 return;
2115         }
2116
2117         cause = status2cause(status);
2118         location = LOCATION_BEYOND;
2119
2120 release_with_cause:
2121         PDEBUG(DEBUG_SIP, "do release (cause %d)\n", cause);
2122
2123         while(p_epointlist) {
2124                 /* send setup message to endpoit */
2125                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2126                 message->param.disconnectinfo.cause = cause;
2127                 message->param.disconnectinfo.location = location;
2128                 message_put(message);
2129                 /* remove epoint */
2130                 free_epointlist(p_epointlist);
2131         }
2132
2133         new_state(PORT_STATE_RELEASE);
2134
2135         rtp_close();
2136
2137         trigger_work(&p_s_delete);
2138 }
2139
2140 void Psip::r_options(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2141 {
2142         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2143         int cause = 0, location = 0;
2144         struct lcr_msg *message;
2145
2146         PDEBUG(DEBUG_SIP, "options result %d received\n", status);
2147
2148         if (status >= 200 && status <= 299) {
2149                 PDEBUG(DEBUG_SIP, "options ok, scheduling option timer with %d seconds\n", inst->options_interval);
2150                 /* restart option timer */
2151                 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
2152                 return;
2153         }
2154
2155         nua_handle_destroy(nh);
2156         p_s_handle = NULL;
2157
2158         rtp_close();
2159
2160         cause = status2cause(status);
2161         location = LOCATION_BEYOND;
2162
2163         while(p_epointlist) {
2164                 /* send setup message to endpoit */
2165                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2166                 message->param.disconnectinfo.cause = cause;
2167                 message->param.disconnectinfo.location = location;
2168                 message_put(message);
2169                 /* remove epoint */
2170                 free_epointlist(p_epointlist);
2171         }
2172         new_state(PORT_STATE_RELEASE);
2173         trigger_work(&p_s_delete);
2174 }
2175
2176 void Psip::i_state(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2177 {
2178         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2179
2180         PDEBUG(DEBUG_SIP, "state change received\n");
2181         sip_trace_header(this, inst->interface_name, "STATUS", DIRECTION_OUT);
2182         add_trace("value", NULL, "%d", status);
2183         add_trace("phrase", NULL, "%s", phrase);
2184         end_trace();
2185 }
2186
2187 static void sip_callback(nua_event_t event, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2188 {
2189         struct sip_inst *inst = (struct sip_inst *) magic;
2190         class Port *port;
2191         class Psip *psip = NULL;
2192         int rc;
2193
2194         PDEBUG(DEBUG_SIP, "Event %d from SIP stack received (handle=%p)\n", event, nh);
2195         if (!nh)
2196                 return;
2197
2198         /* hunt for existing handles */
2199         port = port_first;
2200         while(port) {
2201                 if ((port->p_type & PORT_CLASS_mISDN_MASK) == PORT_CLASS_SIP) {
2202                         psip = (class Psip *)port;
2203                         if (psip->p_s_handle == nh) {
2204                                 PDEBUG(DEBUG_SIP, "Event found for port %s\n", psip->p_name);
2205                                 break;
2206                         }
2207                 }
2208                 port = port->next;
2209         }
2210         if (!port)
2211                 psip = NULL;
2212
2213         /* new handle */
2214         switch (event) {
2215         case nua_i_options:
2216                 if (!inst->register_handle) {
2217                         PDEBUG(DEBUG_SIP, "New options instance\n");
2218                         inst->register_handle = nh;
2219                 }
2220                 break;
2221         case nua_i_register:
2222                 if (!inst->register_handle) {
2223                         PDEBUG(DEBUG_SIP, "New register instance\n");
2224                         inst->register_handle = nh;
2225                 }
2226                 break;
2227         case nua_i_invite:
2228                 if (!psip) {
2229                         char name[64];
2230                         struct interface *interface = interface_first;
2231
2232                         PDEBUG(DEBUG_SIP, "New psip instance\n");
2233
2234                         /* create call instance */
2235                         SPRINT(name, "%s-%d-in", inst->interface_name, 0);
2236                         while (interface) {
2237                                 if (!strcmp(interface->name, inst->interface_name))
2238                                         break;
2239                                 interface = interface->next;
2240                         }
2241                         if (!interface)
2242                                 FATAL("Cannot find interface %s.\n", inst->interface_name);
2243                         if (!(psip = new Psip(PORT_TYPE_SIP_IN, name, NULL, interface)))
2244                                 FATAL("Cannot create Port instance.\n");
2245                 }
2246                 break;
2247         default:
2248                 if (!psip && !inst->register_handle) {
2249                         PDEBUG(DEBUG_SIP, "Destroying unknown instance\n");
2250                         nua_handle_destroy(nh);
2251                         return;
2252                 }
2253         }
2254
2255         /* handle register process */
2256         if (inst->register_handle == nh) {
2257                 switch (event) {
2258                 case nua_i_options:
2259                         i_options(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2260                         break;
2261                 case nua_i_register:
2262                         i_register(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2263                         break;
2264                 case nua_r_register:
2265                         r_register(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2266                         break;
2267                 default:
2268                         PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
2269                 }
2270                 return;
2271         }
2272
2273         /* handle port process */
2274         if (!psip) {
2275                 PERROR("no SIP Port found for handel %p\n", nh);
2276                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
2277                 nua_handle_destroy(nh);
2278                 return;
2279         }
2280
2281         switch (status) {
2282         case 401:
2283         case 407:
2284                 rc = challenge(inst, psip, status, phrase, nua, magic, nh, hmagic, sip, tags);
2285                 if (rc >= 0)
2286                         return;
2287         }
2288
2289         switch (event) {
2290         case nua_r_set_params:
2291                 PDEBUG(DEBUG_SIP, "setparam response\n");
2292                 break;
2293         case nua_r_options:
2294                 psip->r_options(status, phrase, nua, magic, nh, hmagic, sip, tags);
2295                 break;
2296         case nua_i_error:
2297                 PDEBUG(DEBUG_SIP, "error received\n");
2298                 break;
2299         case nua_i_state:
2300                 psip->i_state(status, phrase, nua, magic, nh, hmagic, sip, tags);
2301                 break;
2302         case nua_i_invite:
2303                 psip->i_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
2304                 break;
2305         case nua_i_ack:
2306                 PDEBUG(DEBUG_SIP, "ack received\n");
2307                 break;
2308         case nua_i_active:
2309                 PDEBUG(DEBUG_SIP, "active received\n");
2310                 break;
2311         case nua_i_options:
2312                 psip->i_options(status, phrase, nua, magic, nh, hmagic, sip, tags);
2313                 break;
2314         case nua_i_bye:
2315                 psip->i_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
2316                 break;
2317         case nua_i_cancel:
2318                 psip->i_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
2319                 break;
2320         case nua_r_bye:
2321                 psip->r_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
2322                 break;
2323         case nua_r_cancel:
2324                 psip->r_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
2325                 break;
2326         case nua_r_invite:
2327                 psip->r_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
2328                 break;
2329         case nua_i_terminated:
2330                 PDEBUG(DEBUG_SIP, "terminated received\n");
2331                 break;
2332         default:
2333                 PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
2334         }
2335 }
2336
2337 static void stun_bind_cb(stun_discovery_magic_t *magic, stun_handle_t *sh, stun_discovery_t *sd, stun_action_t action, stun_state_t event)
2338 {
2339         struct sip_inst *inst = (struct sip_inst *) magic;
2340         su_sockaddr_t sa;
2341         socklen_t addrlen;
2342
2343         PDEBUG(DEBUG_SIP, "Event %d from STUN stack received\n", event);
2344
2345         switch (event) {
2346         case stun_discovery_done:
2347                 addrlen = sizeof(sa);
2348                 memset(&sa, 0, addrlen);
2349                 if (stun_discovery_get_address(sd, &sa, &addrlen) < 0) {
2350                         PDEBUG(DEBUG_SIP, "stun_discovery_get_address failed\n");
2351                         goto failed;
2352                 }
2353                 su_inet_ntop(sa.su_family, SU_ADDR(&sa), inst->public_ip, sizeof(inst->public_ip));
2354                 inst->stun_state = STUN_STATE_RESOLVED;
2355                 /* start timer for next stun request with inst->stun_interval */
2356                 schedule_timer(&inst->stun_retry_timer, inst->stun_interval, 0);
2357                 sip_trace_header(NULL, inst->interface_name, "STUN resolved", DIRECTION_OUT);
2358                 add_trace("ip", "addr", "%s", inst->public_ip);
2359                 end_trace();
2360                 break;
2361         default:
2362 failed:
2363                 PDEBUG(DEBUG_SIP, "STUN failed, starting timer\n");
2364                 inst->stun_state = STUN_STATE_FAILED;
2365                 /* start timer for next stun request (after failing) with STUN_RETRY_TIMER */
2366                 schedule_timer(&inst->stun_retry_timer, STUN_RETRY_TIMER);
2367                 sip_trace_header(NULL, inst->interface_name, "STUN failed", DIRECTION_OUT);
2368                 end_trace();
2369         }
2370 }
2371
2372 /* received shutdown due to termination of RTP */
2373 void Psip::rtp_shutdown(void)
2374 {
2375         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2376         struct lcr_msg *message;
2377
2378         PDEBUG(DEBUG_SIP, "RTP stream terminated\n");
2379
2380         sip_trace_header(this, inst->interface_name, "RTP terminated", DIRECTION_IN);
2381         end_trace();
2382
2383         nua_handle_destroy(p_s_handle);
2384         p_s_handle = NULL;
2385
2386         while(p_epointlist) {
2387                 /* send setup message to endpoit */
2388                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2389                 message->param.disconnectinfo.cause = 16;
2390                 message->param.disconnectinfo.location = LOCATION_BEYOND;
2391                 message_put(message);
2392                 /* remove epoint */
2393                 free_epointlist(p_epointlist);
2394         }
2395         new_state(PORT_STATE_RELEASE);
2396         trigger_work(&p_s_delete);
2397 }
2398
2399 static int invite_option_timer(struct lcr_timer *timer, void *instance, int index)
2400 {
2401         class Psip *psip = (class Psip *)instance;
2402         struct sip_inst *inst = (struct sip_inst *) psip->p_s_sip_inst;
2403
2404         sip_trace_header(psip, inst->interface_name, "OPTIONS", psip->p_s_invite_direction);
2405         end_trace();
2406
2407         nua_options(psip->p_s_handle,
2408                 TAG_END());
2409
2410         return 0;
2411 }
2412
2413 static int stun_retry_timer(struct lcr_timer *timer, void *instance, int index)
2414 {
2415         struct sip_inst *inst = (struct sip_inst *)instance;
2416
2417         PDEBUG(DEBUG_SIP, "timeout, restart stun lookup\n");
2418         inst->stun_state = STUN_STATE_UNRESOLVED;
2419
2420         return 0;
2421 }
2422
2423 static int register_retry_timer(struct lcr_timer *timer, void *instance, int index)
2424 {
2425         struct sip_inst *inst = (struct sip_inst *)instance;
2426
2427         PDEBUG(DEBUG_SIP, "timeout, restart register\n");
2428         /* if we have a handle, destroy it and becom unregistered, so registration is
2429          * triggered next */
2430         if (inst->register_handle) {
2431                 /* stop option timer */
2432                 unsched_timer(&inst->register_option_timer);
2433                 nua_handle_destroy(inst->register_handle);
2434                 inst->register_handle = NULL;
2435         }
2436         inst->register_state = REGISTER_STATE_UNREGISTERED;
2437
2438         return 0;
2439 }
2440
2441 static int register_option_timer(struct lcr_timer *timer, void *instance, int index)
2442 {
2443         struct sip_inst *inst = (struct sip_inst *)instance;
2444         sip_trace_header(NULL, inst->interface_name, "OPTIONS", DIRECTION_OUT);
2445         end_trace();
2446
2447         nua_options(inst->register_handle,
2448                 TAG_END());
2449
2450         return 0;
2451 }
2452
2453 int sip_init_inst(struct interface *interface)
2454 {
2455         struct sip_inst *inst = (struct sip_inst *) MALLOC(sizeof(*inst));
2456         char local[256];
2457
2458         interface->sip_inst = inst;
2459         SCPY(inst->interface_name, interface->name);
2460         SCPY(inst->local_peer, interface->sip_local_peer);
2461         SCPY(inst->remote_peer, interface->sip_remote_peer);
2462         if (!inst->remote_peer[0])
2463                 inst->allow_register = 1;
2464         SCPY(inst->asserted_id, interface->sip_asserted_id);
2465         if (interface->sip_register) {
2466                 inst->register_state = REGISTER_STATE_UNREGISTERED;
2467                 SCPY(inst->register_user, interface->sip_register_user);
2468                 SCPY(inst->register_host, interface->sip_register_host);
2469         }
2470         SCPY(inst->auth_user, interface->sip_auth_user);
2471         SCPY(inst->auth_password, interface->sip_auth_password);
2472         inst->register_interval = interface->sip_register_interval;
2473         inst->options_interval = interface->sip_options_interval;
2474
2475         inst->rtp_port_from = interface->rtp_port_from;
2476         inst->rtp_port_to = interface->rtp_port_to;
2477         if (!inst->rtp_port_from || !inst->rtp_port_to) {
2478                 inst->rtp_port_from = RTP_PORT_BASE;
2479                 inst->rtp_port_to = RTP_PORT_MAX;
2480         }
2481         inst->next_rtp_port = inst->rtp_port_from;
2482
2483         /* create timers */
2484         memset(&inst->stun_retry_timer, 0, sizeof(inst->stun_retry_timer));
2485         add_timer(&inst->stun_retry_timer, stun_retry_timer, inst, 0);
2486         memset(&inst->register_retry_timer, 0, sizeof(inst->register_retry_timer));
2487         add_timer(&inst->register_retry_timer, register_retry_timer, inst, 0);
2488         memset(&inst->register_option_timer, 0, sizeof(inst->register_option_timer));
2489         add_timer(&inst->register_option_timer, register_option_timer, inst, 0);
2490
2491         /* init root object */
2492         inst->root = su_root_create(inst);
2493         if (!inst->root) {
2494                 PERROR("Failed to create SIP root\n");
2495                 sip_exit_inst(interface);
2496                 return -EINVAL;
2497         }
2498
2499         SPRINT(local, "sip:%s",inst->local_peer);
2500         if (!strchr(inst->local_peer, ':'))
2501                 SCAT(local, ":5060");
2502         inst->nua = nua_create(inst->root, sip_callback, inst, NUTAG_URL(local), TAG_END());
2503         if (!inst->nua) {
2504                 PERROR("Failed to create SIP stack object\n");
2505                 sip_exit_inst(interface);
2506                 return -EINVAL;
2507         }
2508         nua_set_params(inst->nua,
2509                 SIPTAG_ALLOW_STR("REGISTER,INVITE,ACK,BYE,CANCEL,OPTIONS,NOTIFY,INFO"),
2510                 NUTAG_APPL_METHOD("REGISTER"),
2511                 NUTAG_APPL_METHOD("INVITE"),
2512                 NUTAG_APPL_METHOD("ACK"),
2513 //              NUTAG_APPL_METHOD("BYE"), /* we must reply to BYE */
2514                 NUTAG_APPL_METHOD("CANCEL"),
2515                 NUTAG_APPL_METHOD("OPTIONS"),
2516                 NUTAG_APPL_METHOD("NOTIFY"),
2517                 NUTAG_APPL_METHOD("INFO"),
2518                 NUTAG_AUTOACK(0),
2519 #ifdef NUTAG_AUTO100
2520                 NUTAG_AUTO100(0),
2521 #endif
2522                 NUTAG_AUTOALERT(0),
2523                 NUTAG_AUTOANSWER(0),
2524                 TAG_NULL());
2525
2526         SCPY(inst->public_ip, interface->sip_public_ip);
2527         if (interface->sip_stun_server[0]) {
2528                 SCPY(inst->stun_server, interface->sip_stun_server);
2529                 inst->stun_interval = interface->sip_stun_interval;
2530                 inst->stun_handle = stun_handle_init(inst->root,
2531                         STUNTAG_SERVER(inst->stun_server),
2532                         TAG_NULL());
2533                 if (!inst->stun_handle) {
2534                         PERROR("Failed to create STUN handle\n");
2535                         sip_exit_inst(interface);
2536                         return -EINVAL;
2537                 }
2538                 inst->stun_socket = su_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
2539                 if (inst->stun_socket < 0) {
2540                         PERROR("Failed to create STUN socket\n");
2541                         sip_exit_inst(interface);
2542                         return -EINVAL;
2543                 }
2544                 inst->stun_state = STUN_STATE_UNRESOLVED;
2545         }
2546
2547         PDEBUG(DEBUG_SIP, "SIP interface created (inst=%p)\n", inst);
2548
2549         any_sip_interface = 1;
2550
2551         return 0;
2552 }
2553
2554 void sip_exit_inst(struct interface *interface)
2555 {
2556         struct sip_inst *inst = (struct sip_inst *) interface->sip_inst;
2557
2558         if (!inst)
2559                 return;
2560         del_timer(&inst->stun_retry_timer);
2561         del_timer(&inst->register_retry_timer);
2562         del_timer(&inst->register_option_timer);
2563         if (inst->stun_socket)
2564                 su_close(inst->stun_socket);
2565         if (inst->stun_handle)
2566                 stun_handle_destroy(inst->stun_handle);
2567         if (inst->register_handle)
2568                 nua_handle_destroy(inst->register_handle);
2569         if (inst->root)
2570                 su_root_destroy(inst->root);
2571         if (inst->nua)
2572                 nua_destroy(inst->nua);
2573         FREE(inst, sizeof(*inst));
2574         interface->sip_inst = NULL;
2575
2576         PDEBUG(DEBUG_SIP, "SIP interface removed\n");
2577
2578         /* check if there is any other SIP interface left */
2579         interface = interface_first;
2580         while (interface) {
2581                 if (interface->sip_inst)
2582                         break;
2583                 interface = interface->next;
2584         }
2585         if (!interface)
2586                 any_sip_interface = 0;
2587 }
2588
2589 extern su_log_t su_log_default[];
2590 extern su_log_t nua_log[];
2591
2592 int sip_init(void)
2593 {
2594         int i;
2595
2596         /* init SOFIA lib */
2597         su_init();
2598         su_home_init(sip_home);
2599
2600         if (options.deb & DEBUG_SIP) {
2601                 su_log_set_level(su_log_default, 9);
2602                 su_log_set_level(nua_log, 9);
2603                 //su_log_set_level(soa_log, 9);
2604         }
2605
2606         for (i = 0; i < 256; i++)
2607                 flip[i] = ((i & 1) << 7) + ((i & 2) << 5) + ((i & 4) << 3) + ((i & 8) << 1) + ((i & 16) >> 1) + ((i & 32) >> 3) + ((i & 64) >> 5) + ((i & 128) >> 7);
2608
2609         PDEBUG(DEBUG_SIP, "SIP globals initialized\n");
2610
2611         return 0;
2612 }
2613
2614 void sip_exit(void)
2615 {
2616         su_home_deinit(sip_home);
2617         su_deinit();
2618
2619         PDEBUG(DEBUG_SIP, "SIP globals de-initialized\n");
2620 }
2621
2622 static void sip_handle_stun(struct sip_inst *inst)
2623 {
2624         int rc;
2625
2626         switch (inst->stun_state) {
2627         case STUN_STATE_UNRESOLVED:
2628                 PDEBUG(DEBUG_SIP, "Trying to to get local IP from stun server\n");
2629                 rc = stun_bind(inst->stun_handle, stun_bind_cb, (stun_discovery_magic_t *)inst,
2630                         STUNTAG_SOCKET(inst->stun_socket),
2631                         STUNTAG_REGISTER_EVENTS(1),
2632                         TAG_NULL());
2633                 if (rc < 0) {
2634                         PERROR("Failed to call stun_bind()\n");
2635                         inst->stun_state = STUN_STATE_FAILED;
2636                         break;
2637                 }
2638                 inst->stun_state = STUN_STATE_RESOLVING;
2639                 sip_trace_header(NULL, inst->interface_name, "STUN resolving", DIRECTION_OUT);
2640                 add_trace("server", "addr", "%s", inst->stun_server);
2641                 end_trace();
2642                 break;
2643         }
2644 }
2645
2646 static void sip_handle_register(struct sip_inst *inst)
2647 {
2648         char from[128] = "";
2649         char to[128] = "";
2650         char contact[128] = "";
2651
2652         switch (inst->register_state) {
2653         case REGISTER_STATE_UNREGISTERED:
2654                 /* wait for resoved stun */
2655                 if (inst->stun_handle && inst->stun_state != STUN_STATE_RESOLVED)
2656                         return;
2657
2658                 PDEBUG(DEBUG_SIP, "Registering to peer\n");
2659                 inst->register_handle = nua_handle(inst->nua, NULL, TAG_END());
2660                 if (!inst->register_handle) {
2661                         PERROR("Failed to create handle\n");
2662                         inst->register_state = REGISTER_STATE_FAILED;
2663                         break;
2664                 }
2665                 /* apply handle to trace */
2666 //              sip_trace_header(NULL, inst->interface_name, "NEW handle", DIRECTION_NONE);
2667 //              add_trace("handle", "new", "0x%x", inst->register_handle);
2668 //              end_trace();
2669
2670                 SPRINT(from, "sip:%s@%s", inst->register_user, inst->register_host);
2671                 SPRINT(to, "sip:%s@%s", inst->register_user, inst->register_host);
2672                 if (inst->public_ip[0]) {
2673                         char *p;
2674                         SPRINT(contact, "sip:%s@%s", inst->register_user, inst->public_ip);
2675                         p = strchr(inst->local_peer, ':');
2676                         if (p)
2677                                 SCAT(contact, p);
2678                 }
2679
2680                 sip_trace_header(NULL, inst->interface_name, "REGISTER", DIRECTION_OUT);
2681                 add_trace("from", "uri", "%s", from);
2682                 add_trace("to", "uri", "%s", to);
2683                 end_trace();
2684
2685                 nua_register(inst->register_handle,
2686                         TAG_IF(from[0], SIPTAG_FROM_STR(from)),
2687                         TAG_IF(to[0], SIPTAG_TO_STR(to)),
2688                         TAG_IF(contact[0], SIPTAG_CONTACT_STR(contact)),
2689                         TAG_END());
2690
2691                 inst->register_state = REGISTER_STATE_REGISTERING;
2692
2693                 break;
2694         }
2695         
2696 }
2697
2698 void sip_handle(void)
2699 {
2700         struct interface *interface = interface_first;
2701         struct sip_inst *inst;
2702
2703         while (interface) {
2704                 if (interface->sip_inst) {
2705                         inst = (struct sip_inst *) interface->sip_inst;
2706                         su_root_step(inst->root, 0);
2707                         sip_handle_stun(inst);
2708                         sip_handle_register(inst);
2709                 }
2710                 interface = interface->next;
2711         }
2712 }
2713
2714 /* deletes when back in event loop */
2715 static int delete_event(struct lcr_work *work, void *instance, int index)
2716 {
2717         class Psip *psip = (class Psip *)instance;
2718
2719         delete psip;
2720
2721         return 0;
2722 }
2723
2724
2725 /*
2726  * generate audio, if no data is received from bridge
2727  */
2728
2729 void Psip::set_tone(const char *dir, const char *tone)
2730 {
2731         Port::set_tone(dir, tone);
2732
2733         update_load();
2734 }
2735
2736 void Psip::update_load(void)
2737 {
2738         /* don't trigger load event if event already active */
2739         if (p_s_load_timer.active)
2740                 return;
2741
2742         /* don't start timer if ... */
2743         if (!p_tone_name[0] && !p_dov_tx)
2744                 return;
2745
2746         p_s_next_tv_sec = 0;
2747         schedule_timer(&p_s_load_timer, 0, 0); /* no delay the first time */
2748 }
2749
2750 static int load_timer(struct lcr_timer *timer, void *instance, int index)
2751 {
2752         class Psip *psip = (class Psip *)instance;
2753
2754         /* stop timer if ... */
2755         if (!psip->p_tone_name[0] && !psip->p_dov_tx)
2756                 return 0;
2757
2758         psip->load_tx();
2759
2760         return 0;
2761 }
2762
2763 #define SEND_SIP_LEN 160
2764
2765 void Psip::load_tx(void)
2766 {
2767         int diff;
2768         struct timeval current_time;
2769         int tosend = SEND_SIP_LEN, i;
2770         unsigned char buf[SEND_SIP_LEN], *p = buf;
2771
2772         /* get elapsed */
2773         gettimeofday(&current_time, NULL);
2774         if (!p_s_next_tv_sec) {
2775                 /* if timer expired the first time, set next expected timeout 160 samples in advance */
2776                 p_s_next_tv_sec = current_time.tv_sec;
2777                 p_s_next_tv_usec = current_time.tv_usec + SEND_SIP_LEN * 125;
2778                 if (p_s_next_tv_usec >= 1000000) {
2779                         p_s_next_tv_usec -= 1000000;
2780                         p_s_next_tv_sec++;
2781                 }
2782                 schedule_timer(&p_s_load_timer, 0, SEND_SIP_LEN * 125);
2783         } else {
2784                 diff = 1000000 * (current_time.tv_sec - p_s_next_tv_sec)
2785                         + (current_time.tv_usec - p_s_next_tv_usec);
2786                 if (diff < -SEND_SIP_LEN * 125 || diff > SEND_SIP_LEN * 125) {
2787                         /* if clock drifts too much, set next timeout event to current timer + 160 */
2788                         diff = 0;
2789                         p_s_next_tv_sec = current_time.tv_sec;
2790                         p_s_next_tv_usec = current_time.tv_usec + SEND_SIP_LEN * 125;
2791                         if (p_s_next_tv_usec >= 1000000) {
2792                                 p_s_next_tv_usec -= 1000000;
2793                                 p_s_next_tv_sec++;
2794                         }
2795                 } else {
2796                         /* if diff is positive, it took too long, so next timeout will be earlier */
2797                         p_s_next_tv_usec += SEND_SIP_LEN * 125;
2798                         if (p_s_next_tv_usec >= 1000000) {
2799                                 p_s_next_tv_usec -= 1000000;
2800                                 p_s_next_tv_sec++;
2801                         }
2802                 }
2803                 schedule_timer(&p_s_load_timer, 0, SEND_SIP_LEN * 125 - diff);
2804         }
2805
2806         /* copy tones */
2807         if (p_tone_name[0]) {
2808                 tosend -= read_audio(p, tosend);
2809         } else
2810         if (p_dov_tx) {
2811                 tosend -= dov_tx(p, tosend);
2812         }
2813         if (tosend) {
2814                 PERROR("buffer is not completely filled\n");
2815                 return;
2816         }
2817
2818         p = buf;
2819         for (i = 0; i < SEND_SIP_LEN; i++) {
2820                 *p = flip[*p];
2821                 p++;
2822         }
2823         /* transmit data via rtp */
2824         rtp_send_frame(buf, SEND_SIP_LEN, (options.law=='a')?PAYLOAD_TYPE_ALAW:PAYLOAD_TYPE_ULAW);
2825 }
2826