640631b1097a7c08de1956227129b0b86763eede
[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
18 #undef NUTAG_AUTO100
19
20 unsigned char flip[256];
21
22 int any_sip_interface = 0;
23
24 //pthread_mutex_t mutex_msg;
25 su_home_t       sip_home[1];
26
27 struct sip_inst {
28         char                    interface_name[64];
29         char                    local_peer[32];
30         char                    remote_peer[32];
31         su_root_t               *root;
32         nua_t                   *nua;
33 };
34
35 static int delete_event(struct lcr_work *work, void *instance, int index);
36 static int load_timer(struct lcr_timer *timer, void *instance, int index);
37
38 /*
39  * initialize SIP port
40  */
41 Psip::Psip(int type, char *portname, struct port_settings *settings, struct interface *interface) : Port(type, portname, settings, interface)
42 {
43         p_s_rtp_bridge = 0;
44         if (interface->rtp_bridge)
45                 p_s_rtp_bridge = 1;
46         p_s_sip_inst = interface->sip_inst;
47         memset(&p_s_delete, 0, sizeof(p_s_delete));
48         add_work(&p_s_delete, delete_event, this, 0);
49         p_s_handle = 0;
50         p_s_magic = 0;
51         memset(&p_s_rtp_fd, 0, sizeof(p_s_rtp_fd));
52         memset(&p_s_rtcp_fd, 0, sizeof(p_s_rtcp_fd));
53         memset(&p_s_rtp_sin_local, 0, sizeof(p_s_rtp_sin_local));
54         memset(&p_s_rtcp_sin_local, 0, sizeof(p_s_rtcp_sin_local));
55         memset(&p_s_rtp_sin_remote, 0, sizeof(p_s_rtp_sin_remote));
56         memset(&p_s_rtcp_sin_remote, 0, sizeof(p_s_rtcp_sin_remote));
57         p_s_rtp_ip_local = 0;
58         p_s_rtp_ip_remote = 0;
59         p_s_rtp_port_local = 0;
60         p_s_rtp_port_remote = 0;
61         p_s_b_sock = -1;
62         p_s_b_index = -1;
63         p_s_b_active = 0;
64         p_s_rxpos = 0;
65         p_s_rtp_tx_action = 0;
66
67         /* audio */
68         memset(&p_s_loadtimer, 0, sizeof(p_s_loadtimer));
69         add_timer(&p_s_loadtimer, load_timer, this, 0);
70         p_s_next_tv_sec = 0;
71
72         PDEBUG(DEBUG_SIP, "Created new Psip(%s).\n", portname);
73         if (!p_s_sip_inst)
74                 FATAL("No SIP instance for interface\n");
75 }
76
77
78 /*
79  * destructor
80  */
81 Psip::~Psip()
82 {
83         PDEBUG(DEBUG_SIP, "Destroyed SIP process(%s).\n", p_name);
84
85         del_timer(&p_s_loadtimer);
86         del_work(&p_s_delete);
87
88         rtp_close();
89 }
90
91 static const char *media_type2name(uint8_t media_type) {
92         switch (media_type) {
93         case MEDIA_TYPE_ULAW:
94                 return "PCMU";
95         case MEDIA_TYPE_ALAW:
96                 return "PCMA";
97         case MEDIA_TYPE_GSM:
98                 return "GSM";
99         case MEDIA_TYPE_GSM_HR:
100                 return "GSM-HR";
101         case MEDIA_TYPE_GSM_EFR:
102                 return "GSM-EFR";
103         case MEDIA_TYPE_AMR:
104                 return "AMR";
105         }
106
107         return "UKN";
108 }
109
110 static void sip_trace_header(class Psip *sip, const char *message, int direction)
111 {
112         /* init trace with given values */
113         start_trace(-1,
114                     NULL,
115                     sip?numberrize_callerinfo(sip->p_callerinfo.id, sip->p_callerinfo.ntype, options.national, options.international):NULL,
116                     sip?sip->p_dialinginfo.id:NULL,
117                     direction,
118                     CATEGORY_CH,
119                     sip?sip->p_serial:0,
120                     message);
121 }
122
123 /*
124  * RTP
125  */
126
127 /* according to RFC 3550 */
128 struct rtp_hdr {
129 #if __BYTE_ORDER == __LITTLE_ENDIAN
130         uint8_t  csrc_count:4,
131                   extension:1,
132                   padding:1,
133                   version:2;
134         uint8_t  payload_type:7,
135                   marker:1;
136 #elif __BYTE_ORDER == __BIG_ENDIAN
137         uint8_t  version:2,
138                   padding:1,
139                   extension:1,
140                   csrc_count:4;
141         uint8_t  marker:1,
142                   payload_type:7;
143 #endif
144         uint16_t sequence;
145         uint32_t timestamp;
146         uint32_t ssrc;
147 } __attribute__((packed));
148
149 struct rtp_x_hdr {
150         uint16_t by_profile;
151         uint16_t length;
152 } __attribute__((packed));
153
154 #define RTP_VERSION     2
155
156 #define PAYLOAD_TYPE_ULAW 0
157 #define PAYLOAD_TYPE_ALAW 8
158 #define PAYLOAD_TYPE_GSM 3
159
160 /* decode an rtp frame  */
161 static int rtp_decode(class Psip *psip, unsigned char *data, int len)
162 {
163         struct rtp_hdr *rtph = (struct rtp_hdr *)data;
164         struct rtp_x_hdr *rtpxh;
165         uint8_t *payload;
166         int payload_len;
167         int x_len;
168         unsigned char *from, *to;
169         int n;
170
171         if (len < 12) {
172                 PDEBUG(DEBUG_SIP, "received RTP frame too short (len = %d)\n", len);
173                 return -EINVAL;
174         }
175         if (rtph->version != RTP_VERSION) {
176                 PDEBUG(DEBUG_SIP, "received RTP version %d not supported.\n", rtph->version);
177                 return -EINVAL;
178         }
179         payload = data + sizeof(struct rtp_hdr) + (rtph->csrc_count << 2);
180         payload_len = len - sizeof(struct rtp_hdr) - (rtph->csrc_count << 2);
181         if (payload_len < 0) {
182                 PDEBUG(DEBUG_SIP, "received RTP frame too short (len = %d, "
183                         "csrc count = %d)\n", len, rtph->csrc_count);
184                 return -EINVAL;
185         }
186         if (rtph->extension) {
187                 if (payload_len < (int)sizeof(struct rtp_x_hdr)) {
188                         PDEBUG(DEBUG_SIP, "received RTP frame too short for "
189                                 "extension header\n");
190                         return -EINVAL;
191                 }
192                 rtpxh = (struct rtp_x_hdr *)payload;
193                 x_len = ntohs(rtpxh->length) * 4 + sizeof(struct rtp_x_hdr);
194                 payload += x_len;
195                 payload_len -= x_len;
196                 if (payload_len < 0) {
197                         PDEBUG(DEBUG_SIP, "received RTP frame too short, "
198                                 "extension header exceeds frame length\n");
199                         return -EINVAL;
200                 }
201         }
202         if (rtph->padding) {
203                 if (payload_len < 0) {
204                         PDEBUG(DEBUG_SIP, "received RTP frame too short for "
205                                 "padding length\n");
206                         return -EINVAL;
207                 }
208                 payload_len -= payload[payload_len - 1];
209                 if (payload_len < 0) {
210                         PDEBUG(DEBUG_SIP, "received RTP frame with padding "
211                                 "greater than payload\n");
212                         return -EINVAL;
213                 }
214         }
215
216         switch (rtph->payload_type) {
217 #if 0
218 we only support alaw and ulaw!
219         case RTP_PT_GSM_FULL:
220                 if (payload_len != 33) {
221                         PDEBUG(DEBUG_SIP, "received RTP full rate frame with "
222                                 "payload length != 33 (len = %d)\n",
223                                 payload_len);
224                         return -EINVAL;
225                 }
226                 break;
227         case RTP_PT_GSM_EFR:
228                 if (payload_len != 31) {
229                         PDEBUG(DEBUG_SIP, "received RTP full rate frame with "
230                                 "payload length != 31 (len = %d)\n",
231                                 payload_len);
232                         return -EINVAL;
233                 }
234                 break;
235         case RTP_PT_GSM_HALF:
236                 if (payload_len != 14) {
237                         PDEBUG(DEBUG_SIP, "received RTP half rate frame with "
238                                 "payload length != 14 (len = %d)\n",
239                                 payload_len);
240                         return -EINVAL;
241                 }
242                 break;
243 #endif
244         case PAYLOAD_TYPE_ALAW:
245                 if (options.law != 'a') {
246                         PDEBUG(DEBUG_SIP, "received Alaw, but we don't do Alaw\n");
247                         return -EINVAL;
248                 }
249                 break;
250         case PAYLOAD_TYPE_ULAW:
251                 if (options.law == 'a') {
252                         PDEBUG(DEBUG_SIP, "received Ulaw, but we don't do Ulaw\n");
253                         return -EINVAL;
254                 }
255                 break;
256         default:
257                 PDEBUG(DEBUG_SIP, "received RTP frame with unknown payload "
258                         "type %d\n", rtph->payload_type);
259                 return -EINVAL;
260         }
261
262         if (payload_len <= 0) {
263                 PDEBUG(DEBUG_SIP, "received RTP payload is too small: %d\n", payload_len);
264                 return 0;
265         }
266
267         /* record audio */
268         if (psip->p_record)
269                 psip->record(payload, payload_len, 0); // from down
270         if (psip->p_tap)
271                 psip->tap(payload, payload_len, 0); // from down
272
273         n = payload_len;
274         from = payload;
275         to = payload;
276         if (psip->p_echotest) {
277                 /* echo rtp data we just received */
278                 psip->rtp_send_frame(from, n, (options.law=='a')?PAYLOAD_TYPE_ALAW:PAYLOAD_TYPE_ULAW);
279                 return 0;
280         }
281         while(n--)
282                 *to++ = flip[*from++];
283         psip->bridge_tx(payload, payload_len);
284
285         return 0;
286 }
287
288 static int rtp_sock_callback(struct lcr_fd *fd, unsigned int what, void *instance, int index)
289 {
290         class Psip *psip = (class Psip *) instance;
291         int len;
292         unsigned char buffer[256];
293         int rc = 0;
294
295         if ((what & LCR_FD_READ)) {
296                 len = read(fd->fd, &buffer, sizeof(buffer));
297                 if (len <= 0) {
298                         PDEBUG(DEBUG_SIP, "read result=%d\n", len);
299 //                      psip->rtp_close();
300 //                      psip->rtp_shutdown();
301                         return len;
302                 }
303                 if (psip->p_s_rtp_is_connected)
304                         rc = rtp_decode(psip, buffer, len);
305         }
306
307         return rc;
308 }
309
310 static int rtcp_sock_callback(struct lcr_fd *fd, unsigned int what, void *instance, int index)
311 {
312 //      class Psip *psip = (class Psip *) instance;
313         int len;
314         unsigned char buffer[256];
315
316         if ((what & LCR_FD_READ)) {
317                 len = read(fd->fd, &buffer, sizeof(buffer));
318                 if (len <= 0) {
319                         PDEBUG(DEBUG_SIP, "read result=%d\n", len);
320 //                      psip->rtp_close();
321 //                      psip->rtp_shutdown();
322                         return len;
323                 }
324                 PDEBUG(DEBUG_SIP, "rtcp!\n");
325         }
326
327         return 0;
328 }
329
330 #define RTP_PORT_BASE   30000
331 #define RTP_PORT_MAX    39998
332 static unsigned short next_udp_port = RTP_PORT_BASE;
333
334 static int rtp_sub_socket_bind(int fd, struct sockaddr_in *sin_local, uint32_t ip, uint16_t port)
335 {
336         int rc;
337         socklen_t alen = sizeof(*sin_local);
338
339         sin_local->sin_family = AF_INET;
340         sin_local->sin_addr.s_addr = htonl(ip);
341         sin_local->sin_port = htons(port);
342
343         rc = bind(fd, (struct sockaddr *) sin_local, sizeof(*sin_local));
344         if (rc < 0)
345                 return rc;
346
347         /* retrieve the address we actually bound to, in case we
348          * passed INADDR_ANY as IP address */
349         return getsockname(fd, (struct sockaddr *) sin_local, &alen);
350 }
351
352 static int rtp_sub_socket_connect(int fd, struct sockaddr_in *sin_local, struct sockaddr_in *sin_remote, uint32_t ip, uint16_t port)
353 {
354         int rc;
355         socklen_t alen = sizeof(*sin_local);
356
357         sin_remote->sin_family = AF_INET;
358         sin_remote->sin_addr.s_addr = htonl(ip);
359         sin_remote->sin_port = htons(port);
360
361         rc = connect(fd, (struct sockaddr *) sin_remote, sizeof(*sin_remote));
362         if (rc < 0) {
363                 PERROR("failed to connect to ip %08x port %d rc=%d\n", ip, port, rc);
364                 return rc;
365         }
366
367         return getsockname(fd, (struct sockaddr *) sin_local, &alen);
368 }
369
370 int Psip::rtp_open(void)
371 {
372         int rc, rc2;
373         struct in_addr ia;
374         unsigned int ip;
375         unsigned short start_port;
376
377         /* create socket */
378         rc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
379         if (rc < 0) {
380                 rtp_close();
381                 return -EIO;
382         }
383         p_s_rtp_fd.fd = rc;
384         register_fd(&p_s_rtp_fd, LCR_FD_READ, rtp_sock_callback, this, 0);
385
386         rc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
387         if (rc < 0) {
388                 rtp_close();
389                 return -EIO;
390         }
391         p_s_rtcp_fd.fd = rc;
392         register_fd(&p_s_rtcp_fd, LCR_FD_READ, rtcp_sock_callback, this, 0);
393
394         /* bind socket */
395         ip = htonl(INADDR_ANY);
396         ia.s_addr = ip;
397         start_port = next_udp_port;
398         while (1) {
399                 rc = rtp_sub_socket_bind(p_s_rtp_fd.fd, &p_s_rtp_sin_local, ip, next_udp_port);
400                 if (rc != 0)
401                         goto try_next_port;
402
403                 rc = rtp_sub_socket_bind(p_s_rtcp_fd.fd, &p_s_rtcp_sin_local, ip, next_udp_port + 1);
404                 if (rc == 0) {
405                         p_s_rtp_port_local = next_udp_port;
406                         next_udp_port = (next_udp_port + 2 > RTP_PORT_MAX) ? RTP_PORT_BASE : next_udp_port + 2;
407                         break;
408                 }
409                 /* reopen rtp socket and try again with next udp port */
410                 unregister_fd(&p_s_rtp_fd);
411                 close(p_s_rtp_fd.fd);
412                 p_s_rtp_fd.fd = 0;
413                 rc2 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
414                 if (rc2 < 0) {
415                         rtp_close();
416                         return -EIO;
417                 }
418                 p_s_rtp_fd.fd = rc2;
419                 register_fd(&p_s_rtp_fd, LCR_FD_READ, rtp_sock_callback, this, 0);
420
421 try_next_port:
422                 next_udp_port = (next_udp_port + 2 > RTP_PORT_MAX) ? RTP_PORT_BASE : next_udp_port + 2;
423                 if (next_udp_port == start_port)
424                         break;
425                 /* we must use rc2, in order to preserve rc */
426         }
427         if (rc < 0) {
428                 PDEBUG(DEBUG_SIP, "failed to find port\n");
429                 rtp_close();
430                 return rc;
431         }
432         p_s_rtp_ip_local = ntohl(p_s_rtp_sin_local.sin_addr.s_addr);
433         PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
434         PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
435
436         return p_s_rtp_port_local;
437 }
438
439 int Psip::rtp_connect(void)
440 {
441         int rc;
442         struct in_addr ia;
443
444         ia.s_addr = htonl(p_s_rtp_ip_remote);
445         PDEBUG(DEBUG_SIP, "rtp_connect(ip=%s, port=%u)\n", inet_ntoa(ia), p_s_rtp_port_remote);
446
447         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);
448         if (rc < 0)
449                 return rc;
450
451         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);
452         if (rc < 0)
453                 return rc;
454
455         p_s_rtp_ip_local = ntohl(p_s_rtp_sin_local.sin_addr.s_addr);
456         PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
457         PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
458         p_s_rtp_is_connected = 1;
459
460         return 0;
461 }
462 void Psip::rtp_close(void)
463 {
464         if (p_s_rtp_fd.fd > 0) {
465                 unregister_fd(&p_s_rtp_fd);
466                 close(p_s_rtp_fd.fd);
467                 p_s_rtp_fd.fd = 0;
468         }
469         if (p_s_rtcp_fd.fd > 0) {
470                 unregister_fd(&p_s_rtcp_fd);
471                 close(p_s_rtcp_fd.fd);
472                 p_s_rtcp_fd.fd = 0;
473         }
474         if (p_s_rtp_is_connected) {
475                 PDEBUG(DEBUG_SIP, "rtp closed\n");
476                 p_s_rtp_is_connected = 0;
477         }
478 }
479
480 /* "to - from" */
481 void tv_difference(struct timeval *diff, const struct timeval *from,
482                           const struct timeval *__to)
483 {
484         struct timeval _to = *__to, *to = &_to;
485
486         if (to->tv_usec < from->tv_usec) {
487                 to->tv_sec -= 1;
488                 to->tv_usec += 1000000;
489         }
490
491         diff->tv_usec = to->tv_usec - from->tv_usec;
492         diff->tv_sec = to->tv_sec - from->tv_sec;
493 }
494
495 /* encode and send a rtp frame */
496 int Psip::rtp_send_frame(unsigned char *data, unsigned int len, uint8_t payload_type)
497 {
498         struct rtp_hdr *rtph;
499         int payload_len;
500         int duration; /* in samples */
501         unsigned char buffer[256];
502
503         /* record audio */
504         if (p_record)
505                 record(data, len, 1); // from up
506         if (p_tap)
507                 tap(data, len, 1); // from up
508
509         if (!p_s_rtp_is_connected) {
510                 /* drop silently */
511                 return 0;
512         }
513
514         if (!p_s_rtp_tx_action) {
515                 /* initialize sequences */
516                 p_s_rtp_tx_action = 1;
517                 p_s_rtp_tx_ssrc = rand();
518                 p_s_rtp_tx_sequence = random();
519                 p_s_rtp_tx_timestamp = random();
520                 memset(&p_s_rtp_tx_last_tv, 0, sizeof(p_s_rtp_tx_last_tv));
521         }
522
523         switch (payload_type) {
524 #if 0
525 we only support alaw and ulaw!
526         case RTP_PT_GSM_FULL:
527                 payload_len = 33;
528                 duration = 160;
529                 break;
530         case RTP_PT_GSM_EFR:
531                 payload_len = 31;
532                 duration = 160;
533                 break;
534         case RTP_PT_GSM_HALF:
535                 payload_len = 14;
536                 duration = 160;
537                 break;
538 #endif
539         case PAYLOAD_TYPE_ALAW:
540         case PAYLOAD_TYPE_ULAW:
541                 payload_len = len;
542                 duration = len;
543                 break;
544         default:
545                 PERROR("unsupported message type %d\n", payload_type);
546                 return -EINVAL;
547         }
548
549 #if 0
550         {
551                 struct timeval tv, tv_diff;
552                 long int usec_diff, frame_diff;
553
554                 gettimeofday(&tv, NULL);
555                 tv_difference(&tv_diff, &p_s_rtp_tx_last_tv, &tv);
556                 p_s_rtp_tx_last_tv = tv;
557
558                 usec_diff = tv_diff.tv_sec * 1000000 + tv_diff.tv_usec;
559                 frame_diff = (usec_diff / 20000);
560
561                 if (abs(frame_diff) > 1) {
562                         long int frame_diff_excess = frame_diff - 1;
563
564                         PDEBUG(DEBUG_SIP, "Correcting frame difference of %ld frames\n", frame_diff_excess);
565                         p_s_rtp_tx_sequence += frame_diff_excess;
566                         p_s_rtp_tx_timestamp += frame_diff_excess * duration;
567                 }
568         }
569 #endif
570
571         rtph = (struct rtp_hdr *) buffer;
572         rtph->version = RTP_VERSION;
573         rtph->padding = 0;
574         rtph->extension = 0;
575         rtph->csrc_count = 0;
576         rtph->marker = 0;
577         rtph->payload_type = payload_type;
578         rtph->sequence = htons(p_s_rtp_tx_sequence++);
579         rtph->timestamp = htonl(p_s_rtp_tx_timestamp);
580         p_s_rtp_tx_timestamp += duration;
581         rtph->ssrc = htonl(p_s_rtp_tx_ssrc);
582         memcpy(buffer + sizeof(struct rtp_hdr), data, payload_len);
583
584         if (p_s_rtp_fd.fd > 0) {
585                 len = write(p_s_rtp_fd.fd, &buffer, sizeof(struct rtp_hdr) + payload_len);
586                 if (len != sizeof(struct rtp_hdr) + payload_len) {
587                         PDEBUG(DEBUG_SIP, "write result=%d\n", len);
588 //                      rtp_close();
589 //                      rtp_shutdown();
590                         return -EIO;
591                 }
592         }
593
594         return 0;
595 }
596
597 /* receive from remote */
598 int Psip::bridge_rx(unsigned char *data, int len)
599 {
600         int ret;
601
602         /* don't bridge, if tones are provided */
603         if (p_tone_name[0])
604                 return -EBUSY;
605
606         if ((ret = Port::bridge_rx(data, len)))
607                 return ret;
608
609         /* write to rx buffer */
610         while(len--) {
611                 p_s_rxdata[p_s_rxpos++] = flip[*data++];
612                 if (p_s_rxpos == 160) {
613                         p_s_rxpos = 0;
614
615                         /* transmit data via rtp */
616                         rtp_send_frame(p_s_rxdata, 160, (options.law=='a')?PAYLOAD_TYPE_ALAW:PAYLOAD_TYPE_ULAW);
617                 }
618         }
619
620         return 0;
621 }
622
623 /* taken from freeswitch */
624 /* map sip responses to QSIG cause codes ala RFC4497 section 8.4.4 */
625 static int status2cause(int status)
626 {
627         switch (status) {
628         case 200:
629                 return 16; //SWITCH_CAUSE_NORMAL_CLEARING;
630         case 401:
631         case 402:
632         case 403:
633         case 407:
634         case 603:
635                 return 21; //SWITCH_CAUSE_CALL_REJECTED;
636         case 404:
637                 return 1; //SWITCH_CAUSE_UNALLOCATED_NUMBER;
638         case 485:
639         case 604:
640                 return 3; //SWITCH_CAUSE_NO_ROUTE_DESTINATION;
641         case 408:
642         case 504:
643                 return 102; //SWITCH_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
644         case 410:
645                 return 22; //SWITCH_CAUSE_NUMBER_CHANGED;
646         case 413:
647         case 414:
648         case 416:
649         case 420:
650         case 421:
651         case 423:
652         case 505:
653         case 513:
654                 return 127; //SWITCH_CAUSE_INTERWORKING;
655         case 480:
656                 return 180; //SWITCH_CAUSE_NO_USER_RESPONSE;
657         case 400:
658         case 481:
659         case 500:
660         case 503:
661                 return 41; //SWITCH_CAUSE_NORMAL_TEMPORARY_FAILURE;
662         case 486:
663         case 600:
664                 return 17; //SWITCH_CAUSE_USER_BUSY;
665         case 484:
666                 return 28; //SWITCH_CAUSE_INVALID_NUMBER_FORMAT;
667         case 488:
668         case 606:
669                 return 88; //SWITCH_CAUSE_INCOMPATIBLE_DESTINATION;
670         case 502:
671                 return 38; //SWITCH_CAUSE_NETWORK_OUT_OF_ORDER;
672         case 405:
673                 return 63; //SWITCH_CAUSE_SERVICE_UNAVAILABLE;
674         case 406:
675         case 415:
676         case 501:
677                 return 79; //SWITCH_CAUSE_SERVICE_NOT_IMPLEMENTED;
678         case 482:
679         case 483:
680                 return 25; //SWITCH_CAUSE_EXCHANGE_ROUTING_ERROR;
681         case 487:
682                 return 31; //??? SWITCH_CAUSE_ORIGINATOR_CANCEL;
683         default:
684                 return 31; //SWITCH_CAUSE_NORMAL_UNSPECIFIED;
685         }
686 }
687
688 static int cause2status(int cause, int location, const char **st)
689 {
690         int s;
691
692         switch (cause) {
693         case 1:
694                 s = 404; *st = sip_404_Not_found;
695                 break;
696         case 2:
697                 s = 404; *st = sip_404_Not_found;
698                 break;
699         case 3:
700                 s = 404; *st = sip_404_Not_found;
701                 break;
702         case 17:
703                 s = 486; *st = sip_486_Busy_here;
704                 break;
705         case 18:
706                 s = 408; *st = sip_408_Request_timeout;
707                 break;
708         case 19:
709                 s = 480; *st = sip_480_Temporarily_unavailable;
710                 break;
711         case 20:
712                 s = 480; *st = sip_480_Temporarily_unavailable;
713                 break;
714         case 21:
715                 if (location == LOCATION_USER) {
716                         s = 603; *st = sip_603_Decline;
717                 } else {
718                         s = 403; *st = sip_403_Forbidden;
719                 }
720                 break;
721         case 22:
722                 //s = 301; *st = sip_301_Moved_permanently;
723                 s = 410; *st = sip_410_Gone;
724                 break;
725         case 23:
726                 s = 410; *st = sip_410_Gone;
727                 break;
728         case 27:
729                 s = 502; *st = sip_502_Bad_gateway;
730                 break;
731         case 28:
732                 s = 484; *st = sip_484_Address_incomplete;
733                 break;
734         case 29:
735                 s = 501; *st = sip_501_Not_implemented;
736                 break;
737         case 31:
738                 s = 480; *st = sip_480_Temporarily_unavailable;
739                 break;
740         case 34:
741                 s = 503; *st = sip_503_Service_unavailable;
742                 break;
743         case 38:
744                 s = 503; *st = sip_503_Service_unavailable;
745                 break;
746         case 41:
747                 s = 503; *st = sip_503_Service_unavailable;
748                 break;
749         case 42:
750                 s = 503; *st = sip_503_Service_unavailable;
751                 break;
752         case 47:
753                 s = 503; *st = sip_503_Service_unavailable;
754                 break;
755         case 55:
756                 s = 403; *st = sip_403_Forbidden;
757                 break;
758         case 57:
759                 s = 403; *st = sip_403_Forbidden;
760                 break;
761         case 58:
762                 s = 503; *st = sip_503_Service_unavailable;
763                 break;
764         case 65:
765                 s = 488; *st = sip_488_Not_acceptable;
766                 break;
767         case 69:
768                 s = 501; *st = sip_501_Not_implemented;
769                 break;
770         case 70:
771                 s = 488; *st = sip_488_Not_acceptable;
772                 break;
773         case 79:
774                 s = 501; *st = sip_501_Not_implemented;
775                 break;
776         case 87:
777                 s = 403; *st = sip_403_Forbidden;
778                 break;
779         case 88:
780                 s = 503; *st = sip_503_Service_unavailable;
781                 break;
782         case 102:
783                 s = 504; *st = sip_504_Gateway_time_out;
784                 break;
785         default:
786                 s = 468; *st = sip_486_Busy_here;
787         }
788
789         return s;
790 }
791
792 /*
793  * endpoint sends messages to the SIP port
794  */
795
796 int Psip::message_connect(unsigned int epoint_id, int message_id, union parameter *param)
797 {
798         char sdp_str[256];
799         struct in_addr ia;
800         struct lcr_msg *message;
801         int media_type;
802         unsigned char payload_type;
803
804         if (param->connectinfo.rtpinfo.port) {
805                 PDEBUG(DEBUG_SIP, "RTP info given by remote, forward that\n");
806                 p_s_rtp_bridge = 1;
807                 media_type = param->connectinfo.rtpinfo.media_types[0];
808                 payload_type = param->connectinfo.rtpinfo.payload_types[0];
809                 p_s_rtp_ip_local = param->connectinfo.rtpinfo.ip;
810                 p_s_rtp_port_local = param->connectinfo.rtpinfo.port;
811                 PDEBUG(DEBUG_SIP, "payload type %d\n", payload_type);
812                 PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
813                 PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
814         } else {
815                 PDEBUG(DEBUG_SIP, "RTP info not given by remote, so we do our own RTP\n");
816                 media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
817                 payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
818                 /* open local RTP peer (if not bridging) */
819                 if (!p_s_rtp_is_connected && rtp_connect() < 0) {
820                         nua_cancel(p_s_handle, TAG_END());
821                         nua_handle_destroy(p_s_handle);
822                         p_s_handle = NULL;
823                         sip_trace_header(this, "CANCEL", DIRECTION_OUT);
824                         add_trace("reason", NULL, "failed to connect RTP/RTCP sockts");
825                         end_trace();
826                         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
827                         message->param.disconnectinfo.cause = 41;
828                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
829                         message_put(message);
830                         new_state(PORT_STATE_RELEASE);
831                         trigger_work(&p_s_delete);
832                         return 0;
833                 }
834         }
835
836         ia.s_addr = htonl(p_s_rtp_ip_local);
837
838         SPRINT(sdp_str,
839                 "v=0\n"
840                 "o=LCR-Sofia-SIP 0 0 IN IP4 %s\n"
841                 "s=SIP Call\n"
842                 "c=IN IP4 %s\n"
843                 "t=0 0\n"
844                 "m=audio %d RTP/AVP %d\n"
845                 "a=rtpmap:%d %s/8000\n"
846                 , inet_ntoa(ia), inet_ntoa(ia), p_s_rtp_port_local, payload_type, payload_type, media_type2name(media_type));
847         PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
848
849         nua_respond(p_s_handle, SIP_200_OK,
850                 NUTAG_MEDIA_ENABLE(0),
851                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
852                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
853         new_state(PORT_STATE_CONNECT);
854         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
855         add_trace("respond", "value", "200 OK");
856         add_trace("reason", NULL, "call connected");
857         add_trace("rtp", "ip", "%s", inet_ntoa(ia));
858         add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
859         add_trace("rtp", "payload", "%s:%d", media_type2name(media_type), payload_type);
860         end_trace();
861
862         return 0;
863 }
864
865 int Psip::message_release(unsigned int epoint_id, int message_id, union parameter *param)
866 {
867         struct lcr_msg *message;
868         char cause_str[128] = "";
869         int cause = param->disconnectinfo.cause;
870         int location = param->disconnectinfo.cause;
871         int status;
872         const char *status_text;
873
874         if (cause > 0 && cause <= 127) {
875                 SPRINT(cause_str, "Q.850;cause=%d;text=\"%s\"", cause, isdn_cause[cause].english);
876         }
877
878         switch (p_state) {
879         case PORT_STATE_OUT_SETUP:
880         case PORT_STATE_OUT_PROCEEDING:
881         case PORT_STATE_OUT_ALERTING:
882                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will cancel\n");
883                 sip_trace_header(this, "CANCEL", DIRECTION_OUT);
884                 if (cause_str[0])
885                         add_trace("cause", "value", "%d", cause);
886                 end_trace();
887                 nua_cancel(p_s_handle, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
888                 break;
889         case PORT_STATE_IN_SETUP:
890         case PORT_STATE_IN_PROCEEDING:
891         case PORT_STATE_IN_ALERTING:
892                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will respond\n");
893                 status = cause2status(cause, location, &status_text);
894                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
895                 if (cause_str[0])
896                         add_trace("cause", "value", "%d", cause);
897                 add_trace("respond", "value", "%d %s", status, status_text);
898                 end_trace();
899                 nua_respond(p_s_handle, status, status_text, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
900                 nua_handle_destroy(p_s_handle);
901                 p_s_handle = NULL;
902                 trigger_work(&p_s_delete);
903                 break;
904         default:
905                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will perform nua_bye\n");
906                 sip_trace_header(this, "BYE", DIRECTION_OUT);
907                 if (cause_str[0])
908                         add_trace("cause", "value", "%d", cause);
909                 end_trace();
910                 nua_bye(p_s_handle, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
911         }
912
913         if (message_id == MESSAGE_DISCONNECT) {
914                 while(p_epointlist) {
915                         message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
916                         message->param.disconnectinfo.cause = CAUSE_NORMAL;
917                         message->param.disconnectinfo.location = LOCATION_BEYOND;
918                         message_put(message);
919                         /* remove epoint */
920                         free_epointlist(p_epointlist);
921                 }
922         }
923
924         new_state(PORT_STATE_RELEASE);
925
926         return(0);
927 }
928
929 int Psip::message_setup(unsigned int epoint_id, int message_id, union parameter *param)
930 {
931         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
932         char from[128];
933         char to[128];
934         const char *local = inst->local_peer;
935         char local_ip[16];
936         const char *remote = inst->remote_peer;
937         char sdp_str[512], pt_str[32];
938         struct in_addr ia;
939         struct epoint_list *epointlist;
940         sip_cseq_t *cseq = NULL;
941         struct lcr_msg *message;
942         int lcr_media = { (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW };
943         unsigned char lcr_payload = { (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW };
944         int *media_types;
945         unsigned char *payload_types;
946         int payloads = 0;
947         int i;
948
949         PDEBUG(DEBUG_SIP, "Doing Setup (inst %p)\n", inst);
950
951         memcpy(&p_dialinginfo, &param->setup.dialinginfo, sizeof(p_dialinginfo));
952         memcpy(&p_callerinfo, &param->setup.callerinfo, sizeof(p_callerinfo));
953         memcpy(&p_redirinfo, &param->setup.redirinfo, sizeof(p_redirinfo));
954
955         if (param->setup.rtpinfo.port) {
956                 PDEBUG(DEBUG_SIP, "RTP info given by remote, forward that\n");
957                 p_s_rtp_bridge = 1;
958                 media_types = param->setup.rtpinfo.media_types;
959                 payload_types = param->setup.rtpinfo.payload_types;
960                 payloads = param->setup.rtpinfo.payloads;
961                 p_s_rtp_ip_local = param->setup.rtpinfo.ip;
962                 p_s_rtp_port_local = param->setup.rtpinfo.port;
963                 PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
964                 PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
965         } else {
966                 PDEBUG(DEBUG_SIP, "RTP info not given by remote, so we do our own RTP\n");
967                 p_s_rtp_bridge = 0;
968                 media_types = &lcr_media;
969                 payload_types = &lcr_payload;
970                 payloads = 1;
971
972                 /* open local RTP peer (if not bridging) */
973                 if (rtp_open() < 0) {
974                         PERROR("Failed to open RTP sockets\n");
975                         /* send release message to endpoit */
976                         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
977                         message->param.disconnectinfo.cause = 41;
978                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
979                         message_put(message);
980                         new_state(PORT_STATE_RELEASE);
981                         trigger_work(&p_s_delete);
982                         return 0;
983                 }
984         }
985
986         p_s_handle = nua_handle(inst->nua, NULL, TAG_END());
987         if (!p_s_handle) {
988                 PERROR("Failed to create handle\n");
989                 /* send release message to endpoit */
990                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
991                 message->param.disconnectinfo.cause = 41;
992                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
993                 message_put(message);
994                 new_state(PORT_STATE_RELEASE);
995                 trigger_work(&p_s_delete);
996                 return 0;
997         }
998         /* apply handle */
999         sip_trace_header(this, "NEW handle", DIRECTION_IN);
1000         add_trace("handle", "new", "0x%x", p_s_handle);
1001         end_trace();
1002
1003         if (!p_s_rtp_ip_local) {
1004                 char *p;
1005
1006                 /* extract IP from local peer */
1007                 SCPY(local_ip, local);
1008                 p = strchr(local_ip, ':');
1009                 if (p)
1010                         *p = '\0';
1011                 PDEBUG(DEBUG_SIP, "RTP local IP not known, so we use our local SIP ip %s\n", local_ip);
1012                 inet_pton(AF_INET, local_ip, &p_s_rtp_ip_local);
1013                 p_s_rtp_ip_local = ntohl(p_s_rtp_ip_local);
1014         }
1015         ia.s_addr = htonl(p_s_rtp_ip_local);
1016         SPRINT(sdp_str,
1017                 "v=0\n"
1018                 "o=LCR-Sofia-SIP 0 0 IN IP4 %s\n"
1019                 "s=SIP Call\n"
1020                 "c=IN IP4 %s\n"
1021                 "t=0 0\n"
1022                 "m=audio %d RTP/AVP"
1023                 , inet_ntoa(ia), inet_ntoa(ia), p_s_rtp_port_local);
1024         for (i = 0; i < payloads; i++) {
1025                 SPRINT(pt_str, " %d", payload_types[i]);
1026                 SCAT(sdp_str, pt_str);
1027         }
1028         SCAT(sdp_str, "\n");
1029         for (i = 0; i < payloads; i++) {
1030                 SPRINT(pt_str, "a=rtpmap:%d %s/8000\n", payload_types[i], media_type2name(media_types[i]));
1031                 SCAT(sdp_str, pt_str);
1032         }
1033         PDEBUG(DEBUG_SIP, "Using SDP for invite: %s\n", sdp_str);
1034
1035         SPRINT(from, "sip:%s@%s", param->setup.callerinfo.id, local);
1036         SPRINT(to, "sip:%s@%s", param->setup.dialinginfo.id, remote);
1037
1038         sip_trace_header(this, "INVITE", DIRECTION_OUT);
1039         add_trace("from", "uri", "%s", from);
1040         add_trace("to", "uri", "%s", to);
1041         add_trace("rtp", "ip", "%s", inet_ntoa(ia));
1042         add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
1043         for (i = 0; i < payloads; i++)
1044                 add_trace("rtp", "payload", "%s:%d", media_type2name(media_types[i]), payload_types[i]);
1045         end_trace();
1046
1047 //      cseq = sip_cseq_create(sip_home, 123, SIP_METHOD_INVITE);
1048
1049         nua_invite(p_s_handle,
1050                 TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1051                 TAG_IF(to[0], SIPTAG_TO_STR(to)),
1052                 TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1053                 NUTAG_MEDIA_ENABLE(0),
1054                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1055                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1056         new_state(PORT_STATE_OUT_SETUP);
1057
1058 #if 0
1059         PDEBUG(DEBUG_SIP, "do overlap\n");
1060         new_state(PORT_STATE_OUT_OVERLAP);
1061         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_OVERLAP);
1062         message_put(message);
1063 #else
1064         PDEBUG(DEBUG_SIP, "do proceeding\n");
1065         new_state(PORT_STATE_OUT_PROCEEDING);
1066         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_PROCEEDING);
1067         message_put(message);
1068 #endif
1069
1070         /* attach only if not already */
1071         epointlist = p_epointlist;
1072         while(epointlist) {
1073                 if (epointlist->epoint_id == epoint_id)
1074                         break;
1075                 epointlist = epointlist->next;
1076         }
1077         if (!epointlist)
1078                 epointlist_new(epoint_id);
1079
1080         return 0;
1081 }
1082         
1083 int Psip::message_notify(unsigned int epoint_id, int message_id, union parameter *param)
1084 {
1085 //      char sdp_str[256];
1086 //      struct in_addr ia;
1087
1088         switch (param->notifyinfo.notify) {
1089         case INFO_NOTIFY_REMOTE_HOLD:
1090 #if 0
1091                 SPRINT(sdp_str,
1092                         "v=0\n"
1093                         "o=LCR-Sofia-SIP 0 0 IN IP4 0.0.0.0\n"
1094                         "s=SIP Call\n"
1095                         "c=IN IP4 0.0.0.0\n"
1096                         "t=0 0\n"
1097                         );
1098                 PDEBUG(DEBUG_SIP, "Using SDP for hold: %s\n", sdp_str);
1099                 nua_info(p_s_handle,
1100 //                      TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1101 //                      TAG_IF(to[0], SIPTAG_TO_STR(to)),
1102 //                      TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1103                         NUTAG_MEDIA_ENABLE(0),
1104                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1105                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1106 #endif
1107                 break;
1108         case INFO_NOTIFY_REMOTE_RETRIEVAL:
1109 #if 0
1110                 ia.s_addr = htonl(p_s_rtp_ip_local);
1111                 SPRINT(sdp_str,
1112                         "v=0\n"
1113                         "o=LCR-Sofia-SIP 0 0 IN IP4 %s\n"
1114                         "s=SIP Call\n"
1115                         "c=IN IP4 %s\n"
1116                         "t=0 0\n"
1117                         "m=audio %d RTP/AVP %d\n"
1118                         "a=rtpmap:%d %s/8000\n"
1119                         , inet_ntoa(ia), inet_ntoa(ia), p_s_rtp_port_local, p_s_rtp_payload_type, p_s_rtp_payload_type, media_type2name(p_s_rtp_media_type));
1120                 PDEBUG(DEBUG_SIP, "Using SDP for rertieve: %s\n", sdp_str);
1121                 nua_info(p_s_handle,
1122 //                      TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1123 //                      TAG_IF(to[0], SIPTAG_TO_STR(to)),
1124 //                      TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1125                         NUTAG_MEDIA_ENABLE(0),
1126                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1127                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1128 #endif
1129                 break;
1130         }
1131
1132         return 0;
1133 }
1134
1135 int Psip::message_dtmf(unsigned int epoint_id, int message_id, union parameter *param)
1136 {
1137         char dtmf_str[64];
1138         
1139         /* prepare DTMF info payload */
1140         SPRINT(dtmf_str,
1141                 "Signal=%c\n"
1142                 "Duration=160\n"
1143                 , param->dtmf);
1144
1145         /* start invite to handle DTMF */
1146         nua_info(p_s_handle,
1147                 NUTAG_MEDIA_ENABLE(0),
1148                 SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
1149                 SIPTAG_PAYLOAD_STR(dtmf_str), TAG_END());
1150         
1151         return 0;
1152 }
1153
1154 /* NOTE: incomplete and not working */
1155 int Psip::message_information(unsigned int epoint_id, int message_id, union parameter *param)
1156 {
1157         char dtmf_str[64];
1158         
1159         /* prepare DTMF info payload */
1160         SPRINT(dtmf_str,
1161                 "Signal=%s\n"
1162                 "Duration=160\n"
1163                 , param->information.id);
1164
1165         /* start invite to handle DTMF */
1166         nua_info(p_s_handle,
1167                 NUTAG_MEDIA_ENABLE(0),
1168                 SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
1169                 SIPTAG_PAYLOAD_STR(dtmf_str), TAG_END());
1170         
1171         return 0;
1172 }
1173
1174 int Psip::message_epoint(unsigned int epoint_id, int message_id, union parameter *param)
1175 {
1176         if (Port::message_epoint(epoint_id, message_id, param))
1177                 return 1;
1178
1179         switch(message_id) {
1180                 case MESSAGE_ALERTING: /* call is ringing on LCR side */
1181                 if (p_state != PORT_STATE_IN_SETUP
1182                  && p_state != PORT_STATE_IN_PROCEEDING)
1183                         return 0;
1184                 nua_respond(p_s_handle, SIP_180_RINGING, TAG_END());
1185                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1186                 add_trace("respond", "value", "180 Ringing");
1187                 end_trace();
1188                 new_state(PORT_STATE_IN_ALERTING);
1189                 return 1;
1190
1191                 case MESSAGE_CONNECT: /* call is connected on LCR side */
1192                 if (p_state != PORT_STATE_IN_SETUP
1193                  && p_state != PORT_STATE_IN_PROCEEDING
1194                  && p_state != PORT_STATE_IN_ALERTING)
1195                         return 0;
1196                 message_connect(epoint_id, message_id, param);
1197                 return 1;
1198
1199                 case MESSAGE_DISCONNECT: /* call has been disconnected */
1200                 case MESSAGE_RELEASE: /* call has been released */
1201                 message_release(epoint_id, message_id, param);
1202                 return 1;
1203
1204                 case MESSAGE_SETUP: /* dial-out command received from epoint */
1205                 message_setup(epoint_id, message_id, param);
1206                 return 1;
1207
1208                 case MESSAGE_INFORMATION: /* overlap dialing */
1209                 if (p_state != PORT_STATE_OUT_OVERLAP)
1210                         return 0;
1211                 message_information(epoint_id, message_id, param);
1212                 return 1;
1213
1214                 case MESSAGE_DTMF: /* DTMF info to be transmitted via INFO transaction */
1215                 if (p_state == PORT_STATE_CONNECT)
1216                         message_dtmf(epoint_id, message_id, param);
1217                 case MESSAGE_NOTIFY: /* notification about remote hold/retrieve */
1218                 if (p_state == PORT_STATE_CONNECT)
1219                         message_notify(epoint_id, message_id, param);
1220                 return(1);
1221
1222                 default:
1223                 PDEBUG(DEBUG_SIP, "PORT(%s) SP port with (caller id %s) received an unsupported message: %d\n", p_name, p_callerinfo.id, message_id);
1224         }
1225
1226         return 0;
1227 }
1228
1229 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)
1230 {
1231         *payloads = 0;
1232
1233         if (!sip->sip_payload) {
1234                 PDEBUG(DEBUG_SIP, "no payload given\n");
1235                 return 0;
1236         }
1237
1238         sdp_parser_t *parser;
1239         sdp_session_t *sdp;
1240         sdp_media_t *m;
1241         sdp_attribute_t *attr;
1242         sdp_rtpmap_t *map;
1243         sdp_connection_t *conn;
1244
1245         PDEBUG(DEBUG_SIP, "payload given: %s\n", sip->sip_payload->pl_data);
1246
1247         parser = sdp_parse(NULL, sip->sip_payload->pl_data, (int) strlen(sip->sip_payload->pl_data), 0);
1248         if (!parser) {
1249                 return 400;
1250         }
1251         if (!(sdp = sdp_session(parser))) {
1252                 sdp_parser_free(parser);
1253                 return 400;
1254         }
1255         for (m = sdp->sdp_media; m; m = m->m_next) {
1256                 if (m->m_proto != sdp_proto_rtp)
1257                         continue;
1258                 if (m->m_type != sdp_media_audio)
1259                         continue;
1260                 PDEBUG(DEBUG_SIP, "RTP port:'%u'\n", m->m_port);
1261                 *port = m->m_port;
1262                 for (attr = m->m_attributes; attr; attr = attr->a_next) {
1263                         PDEBUG(DEBUG_SIP, "ATTR: name:'%s' value='%s'\n", attr->a_name, attr->a_value);
1264                 }
1265                 if (m->m_connections) {
1266                         conn = m->m_connections;
1267                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", conn->c_address);
1268                         inet_pton(AF_INET, conn->c_address, ip);
1269                         *ip = ntohl(p_s_rtp_ip_remote);
1270                 } else {
1271                         char *p = sip->sip_payload->pl_data;
1272                         char addr[16];
1273
1274                         PDEBUG(DEBUG_SIP, "sofia cannot find connection tag, so we try ourself\n");
1275                         p = strstr(p, "c=IN IP4 ");
1276                         if (!p) {
1277                                 PDEBUG(DEBUG_SIP, "missing c-tag with internet address\n");
1278                                 sdp_parser_free(parser);
1279                                 return 400;
1280                         }
1281                         SCPY(addr, p + 9);
1282                         if ((p = strchr(addr, '\n'))) *p = '\0';
1283                         if ((p = strchr(addr, '\r'))) *p = '\0';
1284                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", addr);
1285                         inet_pton(AF_INET, addr, ip);
1286                         *ip = ntohl(p_s_rtp_ip_remote);
1287                 }
1288                 for (map = m->m_rtpmaps; map; map = map->rm_next) {
1289                         int media_type = 0;
1290
1291                         PDEBUG(DEBUG_SIP, "RTPMAP: coding:'%s' rate='%d' pt='%d'\n", map->rm_encoding, map->rm_rate, map->rm_pt);
1292                         /* append to payload list, if there is space */
1293                         add_trace("rtp", "payload", "%s:%d", map->rm_encoding, map->rm_pt);
1294                         if (map->rm_pt == PAYLOAD_TYPE_ALAW)
1295                                 media_type = MEDIA_TYPE_ALAW;
1296                         else if (map->rm_pt == PAYLOAD_TYPE_ULAW)
1297                                 media_type = MEDIA_TYPE_ULAW;
1298                         else if (map->rm_pt == PAYLOAD_TYPE_GSM)
1299                                 media_type = MEDIA_TYPE_GSM;
1300                         else if (!strcmp(map->rm_encoding, "GSM-EFR"))
1301                                 media_type = MEDIA_TYPE_GSM_EFR;
1302                         else if (!strcmp(map->rm_encoding, "AMR"))
1303                                 media_type = MEDIA_TYPE_AMR;
1304                         else if (!strcmp(map->rm_encoding, "GSM-HR"))
1305                                 media_type = MEDIA_TYPE_GSM_HR;
1306                         if (media_type && *payloads <= max_payloads) {
1307                                 *payload_types++ = map->rm_pt;
1308                                 *media_types++ = media_type;
1309                                 (*payloads)++;
1310                         }
1311                 }
1312         }
1313
1314         sdp_parser_free(parser);
1315
1316         return 0;
1317 }
1318
1319 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 tagss[])
1320 {
1321         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1322         const char *from = "", *to = "", *name = "";
1323         char imsi[16] = "";
1324         int ret;
1325         class Endpoint *epoint;
1326         struct lcr_msg *message;
1327         struct interface *interface;
1328         int media_types[32];
1329         uint8_t payload_types[32];
1330         int payloads = 0;
1331         int media_type;
1332
1333         interface = getinterfacebyname(inst->interface_name);
1334         if (!interface) {
1335                 PERROR("Cannot find interface %s.\n", inst->interface_name);
1336                 return;
1337         }
1338
1339         if (sip->sip_from) {
1340                 if (sip->sip_from->a_url)
1341                         from = sip->sip_from->a_url->url_user;
1342                 if (sip->sip_from->a_display) {
1343                         name = sip->sip_from->a_display;
1344                         if (!strncmp(name, "\"IMSI", 5)) {
1345                                 strncpy(imsi, name + 5, 15);
1346                                 imsi[15] = '\0';
1347                                 name = "";
1348                         }
1349                 }
1350         }
1351         if (sip->sip_to) {
1352                 if (sip->sip_to->a_url)
1353                         to = sip->sip_to->a_url->url_user;
1354         }
1355         PDEBUG(DEBUG_SIP, "invite received (%s->%s)\n", from, to);
1356
1357         sip_trace_header(this, "Payload received", DIRECTION_NONE);
1358         ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
1359         if (!ret) {
1360                 /* if no RTP bridge, we must support LAW codec, otherwise we forward what we have */
1361                 if (!p_s_rtp_bridge) {
1362                         int i;
1363
1364                         /* check if supported payload type exists */
1365                         for (i = 0; i < payloads; i++) {
1366                                 if (media_types[i] == ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW))
1367                                         break;
1368                         }
1369                         if (i == payloads) {
1370                                 add_trace("error", NULL, "Expected LAW payload type (not bridged)");
1371                                 ret = 415;
1372                         }
1373                 }
1374         }
1375         end_trace();
1376         if (ret) {
1377                 if (ret == 400)
1378                         nua_respond(nh, SIP_400_BAD_REQUEST, TAG_END());
1379                 else
1380                         nua_respond(nh, SIP_415_UNSUPPORTED_MEDIA, TAG_END());
1381                 nua_handle_destroy(nh);
1382                 p_s_handle = NULL;
1383                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1384                 if (ret == 400)
1385                         add_trace("respond", "value", "415 Unsupported Media");
1386                 else
1387                         add_trace("respond", "value", "400 Bad Request");
1388                 add_trace("reason", NULL, "offered codec does not match");
1389                 end_trace();
1390                 new_state(PORT_STATE_RELEASE);
1391                 trigger_work(&p_s_delete);
1392                 return;
1393         }
1394
1395         /* open local RTP peer (if not bridging) */
1396         if (!p_s_rtp_bridge && rtp_open() < 0) {
1397                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1398                 nua_handle_destroy(nh);
1399                 p_s_handle = NULL;
1400                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1401                 add_trace("respond", "value", "500 Internal Server Error");
1402                 add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1403                 end_trace();
1404                 new_state(PORT_STATE_RELEASE);
1405                 trigger_work(&p_s_delete);
1406                 return;
1407         }
1408
1409         /* apply handle */
1410         sip_trace_header(this, "NEW handle", DIRECTION_IN);
1411         add_trace("handle", "new", "0x%x", nh);
1412         p_s_handle = nh;
1413         end_trace();
1414
1415         sip_trace_header(this, "INVITE", DIRECTION_IN);
1416         add_trace("rtp", "port", "%d", p_s_rtp_port_remote);
1417         /* caller information */
1418         if (!from[0]) {
1419                 p_callerinfo.present = INFO_PRESENT_NOTAVAIL;
1420                 p_callerinfo.ntype = INFO_NTYPE_NOTPRESENT;
1421                 add_trace("calling", "present", "unavailable");
1422         } else {
1423                 p_callerinfo.present = INFO_PRESENT_ALLOWED;
1424                 add_trace("calling", "present", "allowed");
1425                 p_callerinfo.screen = INFO_SCREEN_NETWORK;
1426                 p_callerinfo.ntype = INFO_NTYPE_UNKNOWN;
1427                 SCPY(p_callerinfo.id, from);
1428                 add_trace("calling", "number", "%s", from);
1429                 SCPY(p_callerinfo.name, name);
1430                 if (name[0])
1431                         add_trace("calling", "name", "%s", name);
1432                 SCPY(p_callerinfo.imsi, imsi);
1433                 if (imsi[0])
1434                         add_trace("calling", "imsi", "%s", imsi);
1435         }
1436         SCPY(p_callerinfo.interface, inst->interface_name);
1437         /* dialing information */
1438         if (to[0]) {
1439                 p_dialinginfo.ntype = INFO_NTYPE_UNKNOWN;
1440                 SCAT(p_dialinginfo.id, to);
1441                 add_trace("dialing", "number", "%s", to);
1442         }
1443         /* redir info */
1444         /* bearer capability */
1445         p_capainfo.bearer_capa = INFO_BC_SPEECH;
1446         p_capainfo.bearer_info1 = (options.law=='a')?3:2;
1447         p_capainfo.bearer_mode = INFO_BMODE_CIRCUIT;
1448         add_trace("bearer", "capa", "speech");
1449         add_trace("bearer", "mode", "circuit");
1450         /* if packet mode works some day, see dss1.cpp for conditions */
1451         p_capainfo.source_mode = B_MODE_TRANSPARENT;
1452
1453         end_trace();
1454
1455         /* create endpoint */
1456         if (p_epointlist)
1457                 FATAL("Incoming call but already got an endpoint.\n");
1458         if (!(epoint = new Endpoint(p_serial, 0)))
1459                 FATAL("No memory for Endpoint instance\n");
1460         epoint->ep_app = new_endpointapp(epoint, 0, interface->app); //incoming
1461         epointlist_new(epoint->ep_serial);
1462
1463 #ifdef NUTAG_AUTO100
1464         /* send trying (proceeding) */
1465         nua_respond(nh, SIP_100_TRYING, TAG_END());
1466         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1467         add_trace("respond", "value", "100 Trying");
1468         end_trace();
1469 #endif
1470
1471         new_state(PORT_STATE_IN_PROCEEDING);
1472
1473         /* send setup message to endpoit */
1474         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_SETUP);
1475         message->param.setup.port_type = p_type;
1476 //      message->param.setup.dtmf = 0;
1477         memcpy(&message->param.setup.dialinginfo, &p_dialinginfo, sizeof(struct dialing_info));
1478         memcpy(&message->param.setup.callerinfo, &p_callerinfo, sizeof(struct caller_info));
1479         memcpy(&message->param.setup.capainfo, &p_capainfo, sizeof(struct capa_info));
1480 //      SCPY((char *)message->param.setup.useruser.data, useruser.info);
1481 //      message->param.setup.useruser.len = strlen(mncc->useruser.info);
1482 //      message->param.setup.useruser.protocol = mncc->useruser.proto;
1483         if (p_s_rtp_bridge) {
1484                 int i;
1485
1486                 PDEBUG(DEBUG_SIP, "sending setup with RTP info\n");
1487                 message->param.setup.rtpinfo.ip = p_s_rtp_ip_remote;
1488                 message->param.setup.rtpinfo.port = p_s_rtp_port_remote;
1489                 /* add codecs to setup message */
1490                 for (i = 0; i < payloads; i++) {
1491                         message->param.setup.rtpinfo.media_types[i] = media_types[i];
1492                         message->param.setup.rtpinfo.payload_types[i] = payload_types[i];
1493                         if (i == sizeof(message->param.setup.rtpinfo.payload_types))
1494                                 break;
1495                 }
1496                 message->param.setup.rtpinfo.payloads = i;
1497         }
1498         message_put(message);
1499
1500         /* send progress, if tones are available and if we don't bridge */
1501         if (!p_s_rtp_bridge && interface->is_tones == IS_YES) {
1502                 char sdp_str[256];
1503                 struct in_addr ia;
1504                 unsigned char payload_type;
1505
1506                 PDEBUG(DEBUG_SIP, "Connecting audio, since we have tones available\n");
1507                 media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
1508                 payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
1509                 /* open local RTP peer (if not bridging) */
1510                 if (rtp_connect() < 0) {
1511                         nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1512                         nua_handle_destroy(nh);
1513                         p_s_handle = NULL;
1514                         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1515                         add_trace("respond", "value", "500 Internal Server Error");
1516                         add_trace("reason", NULL, "failed to connect RTP/RTCP sockts");
1517                         end_trace();
1518                         new_state(PORT_STATE_RELEASE);
1519                         trigger_work(&p_s_delete);
1520                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_RELEASE);
1521                         message->param.disconnectinfo.cause = 41;
1522                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1523                         message_put(message);
1524                         new_state(PORT_STATE_RELEASE);
1525                         trigger_work(&p_s_delete);
1526                         return;
1527                 }
1528
1529                 ia.s_addr = htonl(p_s_rtp_ip_local);
1530
1531                 SPRINT(sdp_str,
1532                         "v=0\n"
1533                         "o=LCR-Sofia-SIP 0 0 IN IP4 %s\n"
1534                         "s=SIP Call\n"
1535                         "c=IN IP4 %s\n"
1536                         "t=0 0\n"
1537                         "m=audio %d RTP/AVP %d\n"
1538                         "a=rtpmap:%d %s/8000\n"
1539                         , inet_ntoa(ia), inet_ntoa(ia), p_s_rtp_port_local, payload_type, payload_type, media_type2name(media_type));
1540                 PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
1541
1542                 nua_respond(p_s_handle, SIP_183_SESSION_PROGRESS,
1543                         NUTAG_MEDIA_ENABLE(0),
1544                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1545                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1546                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1547                 add_trace("respond", "value", "183 SESSION PROGRESS");
1548                 add_trace("reason", NULL, "audio available");
1549                 add_trace("rtp", "ip", "%s", inet_ntoa(ia));
1550                 add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
1551                 add_trace("rtp", "payload", "%s:%d", media_type2name(media_type), payload_type);
1552                 end_trace();
1553         }
1554 }
1555
1556 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 tagss[])
1557 {
1558         struct lcr_msg *message;
1559         int cause = 0;
1560
1561         PDEBUG(DEBUG_SIP, "bye received\n");
1562
1563         sip_trace_header(this, "BYE", DIRECTION_IN);
1564         if (sip->sip_reason && sip->sip_reason->re_protocol && !strcasecmp(sip->sip_reason->re_protocol, "Q.850") && sip->sip_reason->re_cause) {
1565                 cause = atoi(sip->sip_reason->re_cause);
1566                 add_trace("cause", "value", "%d", cause);
1567         }
1568         end_trace();
1569
1570 // let stack do bye automaticall, since it will not accept our response for some reason
1571 //      nua_respond(nh, SIP_200_OK, TAG_END());
1572         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1573         add_trace("respond", "value", "200 OK");
1574         end_trace();
1575 //      nua_handle_destroy(nh);
1576         p_s_handle = NULL;
1577
1578         rtp_close();
1579
1580         while(p_epointlist) {
1581                 /* send setup message to endpoit */
1582                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1583                 message->param.disconnectinfo.cause = cause ? : 16;
1584                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1585                 message_put(message);
1586                 /* remove epoint */
1587                 free_epointlist(p_epointlist);
1588         }
1589         new_state(PORT_STATE_RELEASE);
1590         trigger_work(&p_s_delete);
1591 }
1592
1593 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 tagss[])
1594 {
1595         struct lcr_msg *message;
1596
1597         PDEBUG(DEBUG_SIP, "cancel received\n");
1598
1599         sip_trace_header(this, "CANCEL", DIRECTION_IN);
1600         end_trace();
1601
1602         nua_handle_destroy(nh);
1603         p_s_handle = NULL;
1604
1605         rtp_close();
1606
1607         while(p_epointlist) {
1608                 /* send setup message to endpoit */
1609                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1610                 message->param.disconnectinfo.cause = 16;
1611                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1612                 message_put(message);
1613                 /* remove epoint */
1614                 free_epointlist(p_epointlist);
1615         }
1616         new_state(PORT_STATE_RELEASE);
1617         trigger_work(&p_s_delete);
1618 }
1619
1620 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 tagss[])
1621 {
1622         PDEBUG(DEBUG_SIP, "bye response received\n");
1623
1624         nua_handle_destroy(nh);
1625         p_s_handle = NULL;
1626
1627         rtp_close();
1628
1629         trigger_work(&p_s_delete);
1630 }
1631
1632 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 tagss[])
1633 {
1634         PDEBUG(DEBUG_SIP, "cancel response received\n");
1635
1636         nua_handle_destroy(nh);
1637         p_s_handle = NULL;
1638
1639         rtp_close();
1640
1641         trigger_work(&p_s_delete);
1642 }
1643
1644 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 tagss[])
1645 {
1646         struct lcr_msg *message;
1647         int cause = 0, location = 0;
1648         int media_types[32];
1649         uint8_t payload_types[32];
1650         int payloads = 0;
1651
1652         PDEBUG(DEBUG_SIP, "response to invite received (status = %d)\n", status);
1653
1654         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1655         add_trace("respond", "value", "%d", status);
1656         end_trace();
1657
1658         /* connect audio */
1659         if (status == 183 || (status >= 200 && status <= 299)) {
1660                 int ret;
1661
1662                 sip_trace_header(this, "Payload received", DIRECTION_NONE);
1663                 ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
1664                 if (!ret) {
1665                         if (payloads != 1)
1666                                 ret = 415;
1667                         else if (!p_s_rtp_bridge) {
1668                                 if (media_types[0] != ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW)) {
1669                                         add_trace("error", NULL, "Expected LAW payload type (not bridged)");
1670                                         ret = 415;
1671                                 }
1672                         }
1673                 }
1674                 end_trace();
1675                 if (ret) {
1676                         nua_cancel(nh, TAG_END());
1677                         sip_trace_header(this, "CANCEL", DIRECTION_OUT);
1678                         add_trace("reason", NULL, "accepted codec does not match");
1679                         end_trace();
1680                         cause = 88;
1681                         location = LOCATION_PRIVATE_LOCAL;
1682                         goto release_with_cause;
1683                 }
1684
1685                 /* connect to remote RTP (if not bridging) */
1686                 if (!p_s_rtp_bridge && rtp_connect() < 0) {
1687                         nua_cancel(nh, TAG_END());
1688                         sip_trace_header(this, "CANCEL", DIRECTION_OUT);
1689                         add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1690                         end_trace();
1691                         cause = 31;
1692                         location = LOCATION_PRIVATE_LOCAL;
1693                         goto release_with_cause;
1694                 }
1695         }
1696
1697         /* process 1xx */
1698         switch (status) {
1699         case 100:
1700 #if 0
1701                 PDEBUG(DEBUG_SIP, "do proceeding\n");
1702                 new_state(PORT_STATE_OUT_PROCEEDING);
1703                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROCEEDING);
1704                 message_put(message);
1705 #endif
1706                 return;
1707         case 180:
1708                 PDEBUG(DEBUG_SIP, "do alerting\n");
1709                 new_state(PORT_STATE_OUT_ALERTING);
1710                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_ALERTING);
1711                 message_put(message);
1712                 return;
1713         case 183:
1714                 PDEBUG(DEBUG_SIP, "do progress\n");
1715                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROGRESS);
1716                 message->param.progressinfo.progress = 8;
1717                 message->param.progressinfo.location = 10;
1718                 if (p_s_rtp_bridge) {
1719                         message->param.progressinfo.rtpinfo.ip = p_s_rtp_ip_remote;
1720                         message->param.progressinfo.rtpinfo.port = p_s_rtp_port_remote;
1721                         message->param.progressinfo.rtpinfo.media_types[0] = media_types[0];
1722                         message->param.progressinfo.rtpinfo.payload_types[0] = payload_types[0];
1723                         message->param.progressinfo.rtpinfo.payloads = 1;
1724                 }
1725                 message_put(message);
1726                 return;
1727         default:
1728                 if (status < 100 || status > 199)
1729                         break;
1730                 PDEBUG(DEBUG_SIP, "skipping 1xx message\n");
1731
1732                 return;
1733         }
1734
1735         /* process 2xx */
1736         if (status >= 200 && status <= 299) {
1737                 PDEBUG(DEBUG_SIP, "do connect\n");
1738                 nua_ack(nh, TAG_END());
1739                 new_state(PORT_STATE_CONNECT);
1740                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CONNECT);
1741                 if (p_s_rtp_bridge) {
1742                         message->param.connectinfo.rtpinfo.ip = p_s_rtp_ip_remote;
1743                         message->param.connectinfo.rtpinfo.port = p_s_rtp_port_remote;
1744                         message->param.connectinfo.rtpinfo.media_types[0] = media_types[0];
1745                         message->param.connectinfo.rtpinfo.payload_types[0] = payload_types[0];
1746                         message->param.connectinfo.rtpinfo.payloads = 1;
1747                 }
1748                 message_put(message);
1749                 return;
1750         }
1751         cause = status2cause(status);
1752         location = LOCATION_BEYOND;
1753
1754 release_with_cause:
1755         PDEBUG(DEBUG_SIP, "do release (cause %d)\n", cause);
1756
1757         while(p_epointlist) {
1758                 /* send setup message to endpoit */
1759                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1760                 message->param.disconnectinfo.cause = cause;
1761                 message->param.disconnectinfo.location = location;
1762                 message_put(message);
1763                 /* remove epoint */
1764                 free_epointlist(p_epointlist);
1765         }
1766
1767         new_state(PORT_STATE_RELEASE);
1768
1769         rtp_close();
1770
1771         trigger_work(&p_s_delete);
1772 }
1773
1774 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[])
1775 {
1776         struct sip_inst *inst = (struct sip_inst *) magic;
1777         class Port *port;
1778         class Psip *psip = NULL;
1779
1780         PDEBUG(DEBUG_SIP, "Event %d from stack received (handle=%p)\n", event, nh);
1781         if (!nh)
1782                 return;
1783
1784         /* create or find port instance */
1785         if (event == nua_i_invite)
1786         {
1787                 char name[64];
1788                 struct interface *interface = interface_first;
1789
1790                 /* create call instance */
1791                 SPRINT(name, "%s-%d-in", inst->interface_name, 0);
1792                 while (interface) {
1793                         if (!strcmp(interface->name, inst->interface_name))
1794                                 break;
1795                         interface = interface->next;
1796                 }
1797                 if (!interface) {
1798                         PERROR("Cannot find interface %s.\n", inst->interface_name);
1799                         return;
1800                 }
1801                 if (!(psip = new Psip(PORT_TYPE_SIP_IN, name, NULL, interface)))
1802                         FATAL("Cannot create Port instance.\n");
1803         } else {
1804                 port = port_first;
1805                 while(port) {
1806                         if ((port->p_type & PORT_CLASS_mISDN_MASK) == PORT_CLASS_SIP) {
1807                                 psip = (class Psip *)port;
1808                                 if (psip->p_s_handle == nh) {
1809                                         break;
1810                                 }
1811                         }
1812                         port = port->next;
1813                 }
1814         }
1815         if (!psip) {
1816                 PERROR("no SIP Port found for handel %p\n", nh);
1817                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1818                 nua_handle_destroy(nh);
1819                 return;
1820         }
1821
1822         switch (event) {
1823         case nua_r_set_params:
1824                 PDEBUG(DEBUG_SIP, "setparam response\n");
1825                 break;
1826         case nua_i_error:
1827                 PDEBUG(DEBUG_SIP, "error received\n");
1828                 break;
1829         case nua_i_state:
1830                 PDEBUG(DEBUG_SIP, "state change received\n");
1831                 break;
1832         case nua_i_register:
1833                 PDEBUG(DEBUG_SIP, "register received\n");
1834                 break;
1835         case nua_i_invite:
1836                 psip->i_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
1837                 break;
1838         case nua_i_ack:
1839                 PDEBUG(DEBUG_SIP, "ack received\n");
1840                 break;
1841         case nua_i_active:
1842                 PDEBUG(DEBUG_SIP, "active received\n");
1843                 break;
1844         case nua_i_bye:
1845                 psip->i_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
1846                 break;
1847         case nua_i_cancel:
1848                 psip->i_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
1849                 break;
1850         case nua_r_bye:
1851                 psip->r_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
1852                 break;
1853         case nua_r_cancel:
1854                 psip->r_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
1855                 break;
1856         case nua_r_invite:
1857                 psip->r_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
1858                 break;
1859         case nua_i_terminated:
1860                 PDEBUG(DEBUG_SIP, "terminated received\n");
1861                 break;
1862         default:
1863                 PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
1864         }
1865 }
1866
1867 /* received shutdown due to termination of RTP */
1868 void Psip::rtp_shutdown(void)
1869 {
1870         struct lcr_msg *message;
1871
1872         PDEBUG(DEBUG_SIP, "RTP stream terminated\n");
1873
1874         sip_trace_header(this, "RTP terminated", DIRECTION_IN);
1875         end_trace();
1876
1877         nua_handle_destroy(p_s_handle);
1878         p_s_handle = NULL;
1879
1880         while(p_epointlist) {
1881                 /* send setup message to endpoit */
1882                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1883                 message->param.disconnectinfo.cause = 16;
1884                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1885                 message_put(message);
1886                 /* remove epoint */
1887                 free_epointlist(p_epointlist);
1888         }
1889         new_state(PORT_STATE_RELEASE);
1890         trigger_work(&p_s_delete);
1891 }
1892
1893 int sip_init_inst(struct interface *interface)
1894 {
1895         struct sip_inst *inst = (struct sip_inst *) MALLOC(sizeof(*inst));
1896         char local[64];
1897
1898         interface->sip_inst = inst;
1899         SCPY(inst->interface_name, interface->name);
1900         SCPY(inst->local_peer, interface->sip_local_peer);
1901         SCPY(inst->remote_peer, interface->sip_remote_peer);
1902
1903         /* init root object */
1904         inst->root = su_root_create(inst);
1905         if (!inst->root) {
1906                 PERROR("Failed to create SIP root\n");
1907                 sip_exit_inst(interface);
1908                 return -EINVAL;
1909         }
1910
1911         SPRINT(local, "sip:%s",inst->local_peer);
1912         if (!strchr(inst->local_peer, ':'))
1913                 SCAT(local, ":5060");
1914         inst->nua = nua_create(inst->root, sip_callback, inst, NUTAG_URL(local), TAG_END());
1915         if (!inst->nua) {
1916                 PERROR("Failed to create SIP stack object\n");
1917                 sip_exit_inst(interface);
1918                 return -EINVAL;
1919         }
1920         nua_set_params(inst->nua,
1921                 SIPTAG_ALLOW_STR("INVITE,ACK,BYE,CANCEL,OPTIONS,NOTIFY,INFO"),
1922                 NUTAG_APPL_METHOD("INVITE"),
1923                 NUTAG_APPL_METHOD("ACK"),
1924 //              NUTAG_APPL_METHOD("BYE"), /* we must reply to BYE */
1925                 NUTAG_APPL_METHOD("CANCEL"),
1926                 NUTAG_APPL_METHOD("OPTIONS"),
1927                 NUTAG_APPL_METHOD("NOTIFY"),
1928                 NUTAG_APPL_METHOD("INFO"),
1929                 NUTAG_AUTOACK(0),
1930 #ifdef NUTAG_AUTO100
1931                 NUTAG_AUTO100(0),
1932 #endif
1933                 NUTAG_AUTOALERT(0),
1934                 NUTAG_AUTOANSWER(0),
1935                 TAG_NULL());
1936
1937         PDEBUG(DEBUG_SIP, "SIP interface created (inst=%p)\n", inst);
1938
1939         any_sip_interface = 1;
1940
1941         return 0;
1942 }
1943
1944 void sip_exit_inst(struct interface *interface)
1945 {
1946         struct sip_inst *inst = (struct sip_inst *) interface->sip_inst;
1947
1948         if (!inst)
1949                 return;
1950         if (inst->root)
1951                 su_root_destroy(inst->root);
1952         if (inst->nua) {
1953                 nua_destroy(inst->nua);
1954         }
1955         FREE(inst, sizeof(*inst));
1956         interface->sip_inst = NULL;
1957
1958         PDEBUG(DEBUG_SIP, "SIP interface removed\n");
1959
1960         /* check if there is any other SIP interface left */
1961         interface = interface_first;
1962         while (interface) {
1963                 if (interface->sip_inst)
1964                         break;
1965                 interface = interface->next;
1966         }
1967         if (!interface)
1968                 any_sip_interface = 0;
1969 }
1970
1971 extern su_log_t su_log_default[];
1972 extern su_log_t nua_log[];
1973 //extern su_log_t soa_log[];
1974
1975 int sip_init(void)
1976 {
1977         int i;
1978
1979         /* init SOFIA lib */
1980         su_init();
1981         su_home_init(sip_home);
1982
1983         if (options.deb & DEBUG_SIP) {
1984                 su_log_set_level(su_log_default, 9);
1985                 su_log_set_level(nua_log, 9);
1986                 //su_log_set_level(soa_log, 9);
1987         }
1988
1989         for (i = 0; i < 256; i++)
1990                 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);
1991
1992         PDEBUG(DEBUG_SIP, "SIP globals initialized\n");
1993
1994         return 0;
1995 }
1996
1997 void sip_exit(void)
1998 {
1999         su_home_deinit(sip_home);
2000         su_deinit();
2001
2002         PDEBUG(DEBUG_SIP, "SIP globals de-initialized\n");
2003 }
2004
2005 void sip_handle(void)
2006 {
2007         struct interface *interface = interface_first;
2008         struct sip_inst *inst;
2009
2010         while (interface) {
2011                 if (interface->sip_inst) {
2012                         inst = (struct sip_inst *) interface->sip_inst;
2013                         su_root_step(inst->root, 0);
2014                 }
2015                 interface = interface->next;
2016         }
2017 }
2018
2019 /* deletes when back in event loop */
2020 static int delete_event(struct lcr_work *work, void *instance, int index)
2021 {
2022         class Psip *psip = (class Psip *)instance;
2023
2024         delete psip;
2025
2026         return 0;
2027 }
2028
2029
2030 /*
2031  * generate audio, if no data is received from bridge
2032  */
2033
2034 void Psip::set_tone(const char *dir, const char *tone)
2035 {
2036         Port::set_tone(dir, tone);
2037
2038         update_load();
2039 }
2040
2041 void Psip::update_load(void)
2042 {
2043         /* don't trigger load event if event already active */
2044         if (p_s_loadtimer.active)
2045                 return;
2046
2047         /* don't start timer if ... */
2048         if (!p_tone_name[0])
2049                 return;
2050
2051         p_s_next_tv_sec = 0;
2052         schedule_timer(&p_s_loadtimer, 0, 0); /* no delay the first time */
2053 }
2054
2055 static int load_timer(struct lcr_timer *timer, void *instance, int index)
2056 {
2057         class Psip *psip = (class Psip *)instance;
2058
2059         /* stop timer if ... */
2060         if (!psip->p_tone_name[0])
2061                 return 0;
2062
2063         psip->load_tx();
2064
2065         return 0;
2066 }
2067
2068 #define SEND_SIP_LEN 160
2069
2070 void Psip::load_tx(void)
2071 {
2072         int diff;
2073         struct timeval current_time;
2074         int tosend = SEND_SIP_LEN, i;
2075         unsigned char buf[SEND_SIP_LEN], *p = buf;
2076
2077         /* get elapsed */
2078         gettimeofday(&current_time, NULL);
2079         if (!p_s_next_tv_sec) {
2080                 /* if timer expired the first time, set next expected timeout 160 samples in advance */
2081                 p_s_next_tv_sec = current_time.tv_sec;
2082                 p_s_next_tv_usec = current_time.tv_usec + SEND_SIP_LEN * 125;
2083                 if (p_s_next_tv_usec >= 1000000) {
2084                         p_s_next_tv_usec -= 1000000;
2085                         p_s_next_tv_sec++;
2086                 }
2087                 schedule_timer(&p_s_loadtimer, 0, SEND_SIP_LEN * 125);
2088         } else {
2089                 diff = 1000000 * (current_time.tv_sec - p_s_next_tv_sec)
2090                         + (current_time.tv_usec - p_s_next_tv_usec);
2091                 if (diff < -SEND_SIP_LEN * 125 || diff > SEND_SIP_LEN * 125) {
2092                         /* if clock drifts too much, set next timeout event to current timer + 160 */
2093                         diff = 0;
2094                         p_s_next_tv_sec = current_time.tv_sec;
2095                         p_s_next_tv_usec = current_time.tv_usec + SEND_SIP_LEN * 125;
2096                         if (p_s_next_tv_usec >= 1000000) {
2097                                 p_s_next_tv_usec -= 1000000;
2098                                 p_s_next_tv_sec++;
2099                         }
2100                 } else {
2101                         /* if diff is positive, it took too long, so next timeout will be earlier */
2102                         p_s_next_tv_usec += SEND_SIP_LEN * 125;
2103                         if (p_s_next_tv_usec >= 1000000) {
2104                                 p_s_next_tv_usec -= 1000000;
2105                                 p_s_next_tv_sec++;
2106                         }
2107                 }
2108                 schedule_timer(&p_s_loadtimer, 0, SEND_SIP_LEN * 125 - diff);
2109         }
2110
2111         /* copy tones */
2112         if (p_tone_name[0]) {
2113                 tosend -= read_audio(p, tosend);
2114         }
2115         if (tosend) {
2116                 PERROR("buffer is not completely filled\n");
2117                 return;
2118         }
2119
2120         p = buf;
2121         for (i = 0; i < SEND_SIP_LEN; i++) {
2122                 *p = flip[*p];
2123                 p++;
2124         }
2125         /* transmit data via rtp */
2126         rtp_send_frame(buf, SEND_SIP_LEN, (options.law=='a')?PAYLOAD_TYPE_ALAW:PAYLOAD_TYPE_ULAW);
2127 }
2128