40c5572d40af5be5f9f098c8df500f9a624cdab1
[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 unsigned char flip[256];
19
20 //pthread_mutex_t mutex_msg;
21 su_home_t       sip_home[1];
22
23 struct sip_inst {
24         struct interface        *interface;
25         su_root_t               *root;
26         nua_t                   *nua;
27 };
28
29 static int delete_event(struct lcr_work *work, void *instance, int index);
30
31 /*
32  * initialize SIP port
33  */
34 Psip::Psip(int type, struct mISDNport *mISDNport, char *portname, struct port_settings *settings, int channel, int exclusive, int mode, struct interface *interface) : PmISDN(type, mISDNport, portname, settings, channel, exclusive, mode)
35 {
36         p_m_s_sip_inst = interface->sip_inst;
37         memset(&p_m_s_delete, 0, sizeof(p_m_s_delete));
38         add_work(&p_m_s_delete, delete_event, this, 0);
39         p_m_s_handle = 0;
40         p_m_s_magic = 0;
41         memset(&p_m_s_rtp_fd, 0, sizeof(p_m_s_rtp_fd));
42         memset(&p_m_s_rtcp_fd, 0, sizeof(p_m_s_rtcp_fd));
43         memset(&p_m_s_rtp_sin_local, 0, sizeof(p_m_s_rtp_sin_local));
44         memset(&p_m_s_rtcp_sin_local, 0, sizeof(p_m_s_rtcp_sin_local));
45         memset(&p_m_s_rtp_sin_remote, 0, sizeof(p_m_s_rtp_sin_remote));
46         memset(&p_m_s_rtcp_sin_remote, 0, sizeof(p_m_s_rtcp_sin_remote));
47         p_m_s_rtp_ip_local = 0;
48         p_m_s_rtp_ip_remote = 0;
49         p_m_s_rtp_port_local = 0;
50         p_m_s_rtp_port_remote = 0;
51         p_m_s_b_sock = -1;
52         p_m_s_b_index = -1;
53         p_m_s_b_active = 0;
54         p_m_s_rxpos = 0;
55         p_m_s_rtp_tx_action = 0;
56
57         PDEBUG(DEBUG_SIP, "Created new Psip(%s).\n", portname);
58 }
59
60
61 /*
62  * destructor
63  */
64 Psip::~Psip()
65 {
66         PDEBUG(DEBUG_SIP, "Destroyed SIP process(%s).\n", p_name);
67
68         del_work(&p_m_s_delete);
69
70         /* close audio transfer socket */
71         if (p_m_s_b_sock > -1)
72                 bchannel_close();
73
74         rtp_close();
75 }
76
77
78 static void sip_trace_header(class Psip *sip, const char *message, int direction)
79 {
80         /* init trace with given values */
81         start_trace(-1,
82                     NULL,
83                     sip?numberrize_callerinfo(sip->p_callerinfo.id, sip->p_callerinfo.ntype, options.national, options.international):NULL,
84                     sip?sip->p_dialinginfo.id:NULL,
85                     direction,
86                     CATEGORY_CH,
87                     sip?sip->p_serial:0,
88                     message);
89 }
90
91 /*
92  * RTP
93  */
94
95 /* according to RFC 3550 */
96 struct rtp_hdr {
97 #if __BYTE_ORDER == __LITTLE_ENDIAN
98         uint8_t  csrc_count:4,
99                   extension:1,
100                   padding:1,
101                   version:2;
102         uint8_t  payload_type:7,
103                   marker:1;
104 #elif __BYTE_ORDER == __BIG_ENDIAN
105         uint8_t  version:2,
106                   padding:1,
107                   extension:1,
108                   csrc_count:4;
109         uint8_t  marker:1,
110                   payload_type:7;
111 #endif
112         uint16_t sequence;
113         uint32_t timestamp;
114         uint32_t ssrc;
115 } __attribute__((packed));
116
117 struct rtp_x_hdr {
118         uint16_t by_profile;
119         uint16_t length;
120 } __attribute__((packed));
121
122 #define RTP_VERSION     2
123
124 #define RTP_PT_ULAW 0
125 #define RTP_PT_ALAW 8
126 #define RTP_PT_GSM_FULL 3
127 #define RTP_PT_GSM_HALF 96
128 #define RTP_PT_GSM_EFR 97
129 #define RTP_PT_AMR 98
130
131 /* decode an rtp frame  */
132 static int rtp_decode(class Psip *psip, unsigned char *data, int len)
133 {
134         struct rtp_hdr *rtph = (struct rtp_hdr *)data;
135         struct rtp_x_hdr *rtpxh;
136         uint8_t *payload;
137         int payload_len;
138         int x_len;
139
140         if (len < 12) {
141                 PDEBUG(DEBUG_SIP, "received RTP frame too short (len = %d)\n", len);
142                 return -EINVAL;
143         }
144         if (rtph->version != RTP_VERSION) {
145                 PDEBUG(DEBUG_SIP, "received RTP version %d not supported.\n", rtph->version);
146                 return -EINVAL;
147         }
148         payload = data + sizeof(struct rtp_hdr) + (rtph->csrc_count << 2);
149         payload_len = len - sizeof(struct rtp_hdr) - (rtph->csrc_count << 2);
150         if (payload_len < 0) {
151                 PDEBUG(DEBUG_SIP, "received RTP frame too short (len = %d, "
152                         "csrc count = %d)\n", len, rtph->csrc_count);
153                 return -EINVAL;
154         }
155         if (rtph->extension) {
156                 if (payload_len < (int)sizeof(struct rtp_x_hdr)) {
157                         PDEBUG(DEBUG_SIP, "received RTP frame too short for "
158                                 "extension header\n");
159                         return -EINVAL;
160                 }
161                 rtpxh = (struct rtp_x_hdr *)payload;
162                 x_len = ntohs(rtpxh->length) * 4 + sizeof(struct rtp_x_hdr);
163                 payload += x_len;
164                 payload_len -= x_len;
165                 if (payload_len < 0) {
166                         PDEBUG(DEBUG_SIP, "received RTP frame too short, "
167                                 "extension header exceeds frame length\n");
168                         return -EINVAL;
169                 }
170         }
171         if (rtph->padding) {
172                 if (payload_len < 0) {
173                         PDEBUG(DEBUG_SIP, "received RTP frame too short for "
174                                 "padding length\n");
175                         return -EINVAL;
176                 }
177                 payload_len -= payload[payload_len - 1];
178                 if (payload_len < 0) {
179                         PDEBUG(DEBUG_SIP, "received RTP frame with padding "
180                                 "greater than payload\n");
181                         return -EINVAL;
182                 }
183         }
184
185         switch (rtph->payload_type) {
186         case RTP_PT_GSM_FULL:
187                 if (payload_len != 33) {
188                         PDEBUG(DEBUG_SIP, "received RTP full rate frame with "
189                                 "payload length != 33 (len = %d)\n",
190                                 payload_len);
191                         return -EINVAL;
192                 }
193                 break;
194         case RTP_PT_GSM_EFR:
195                 if (payload_len != 31) {
196                         PDEBUG(DEBUG_SIP, "received RTP full rate frame with "
197                                 "payload length != 31 (len = %d)\n",
198                                 payload_len);
199                         return -EINVAL;
200                 }
201                 break;
202         case RTP_PT_ALAW:
203                 if (options.law != 'a') {
204                         PDEBUG(DEBUG_SIP, "received Alaw, but we don't do Alaw\n");
205                         return -EINVAL;
206                 }
207                 break;
208         case RTP_PT_ULAW:
209                 if (options.law == 'a') {
210                         PDEBUG(DEBUG_SIP, "received Ulaw, but we don't do Ulaw\n");
211                         return -EINVAL;
212                 }
213                 break;
214         default:
215                 PDEBUG(DEBUG_SIP, "received RTP frame with unknown payload "
216                         "type %d\n", rtph->payload_type);
217                 return -EINVAL;
218         }
219
220         if (payload_len <= 0) {
221                 PDEBUG(DEBUG_SIP, "received RTP payload is too small: %d\n", payload_len);
222                 return 0;
223         }
224
225         psip->bchannel_send(PH_DATA_REQ, 0, payload, payload_len);
226
227         return 0;
228 }
229
230 static int rtp_sock_callback(struct lcr_fd *fd, unsigned int what, void *instance, int index)
231 {
232         class Psip *psip = (class Psip *) instance;
233         int len;
234         unsigned char buffer[256];
235         int rc = 0;
236
237         if ((what & LCR_FD_READ)) {
238                 len = read(fd->fd, &buffer, sizeof(buffer));
239                 if (len <= 0) {
240                         PDEBUG(DEBUG_SIP, "read result=%d\n", len);
241 //                      psip->rtp_close();
242 //                      psip->rtp_shutdown();
243                         return len;
244                 }
245                 rc = rtp_decode(psip, buffer, len);
246         }
247
248         return rc;
249 }
250
251 static int rtcp_sock_callback(struct lcr_fd *fd, unsigned int what, void *instance, int index)
252 {
253 //      class Psip *psip = (class Psip *) instance;
254         int len;
255         unsigned char buffer[256];
256
257         if ((what & LCR_FD_READ)) {
258                 len = read(fd->fd, &buffer, sizeof(buffer));
259                 if (len <= 0) {
260                         PDEBUG(DEBUG_SIP, "read result=%d\n", len);
261 //                      psip->rtp_close();
262 //                      psip->rtp_shutdown();
263                         return len;
264                 }
265                 PDEBUG(DEBUG_SIP, "rtcp!");
266         }
267
268         return 0;
269 }
270
271 #define RTP_PORT_BASE   30000
272 static unsigned int next_udp_port = RTP_PORT_BASE;
273
274 static int rtp_sub_socket_bind(int fd, struct sockaddr_in *sin_local, uint32_t ip, uint16_t port)
275 {
276         int rc;
277         socklen_t alen = sizeof(*sin_local);
278
279         sin_local->sin_family = AF_INET;
280         sin_local->sin_addr.s_addr = htonl(ip);
281         sin_local->sin_port = htons(port);
282
283         rc = bind(fd, (struct sockaddr *) sin_local, sizeof(*sin_local));
284         if (rc < 0)
285                 return rc;
286
287         /* retrieve the address we actually bound to, in case we
288          * passed INADDR_ANY as IP address */
289         return getsockname(fd, (struct sockaddr *) sin_local, &alen);
290 }
291
292 static int rtp_sub_socket_connect(int fd, struct sockaddr_in *sin_local, struct sockaddr_in *sin_remote, uint32_t ip, uint16_t port)
293 {
294         int rc;
295         socklen_t alen = sizeof(*sin_local);
296
297         sin_remote->sin_family = AF_INET;
298         sin_remote->sin_addr.s_addr = htonl(ip);
299         sin_remote->sin_port = htons(port);
300
301         rc = connect(fd, (struct sockaddr *) sin_remote, sizeof(*sin_remote));
302         if (rc < 0) {
303                 PERROR("failed to connect to ip %08x port %d rc=%d\n", ip, port, rc);
304                 return rc;
305         }
306
307         return getsockname(fd, (struct sockaddr *) sin_local, &alen);
308 }
309
310 int Psip::rtp_open(void)
311 {
312         int rc;
313         struct in_addr ia;
314         unsigned int ip;
315
316         /* create socket */
317         rc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
318         if (!rc) {
319                 rtp_close();
320                 return -EIO;
321         }
322         p_m_s_rtp_fd.fd = rc;
323         register_fd(&p_m_s_rtp_fd, LCR_FD_READ, rtp_sock_callback, this, 0);
324
325         rc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
326         if (!rc) {
327                 rtp_close();
328                 return -EIO;
329         }
330         p_m_s_rtcp_fd.fd = rc;
331         register_fd(&p_m_s_rtcp_fd, LCR_FD_READ, rtcp_sock_callback, this, 0);
332
333         /* bind socket */
334         ip = htonl(INADDR_ANY);
335         ia.s_addr = ip;
336         for (next_udp_port = next_udp_port % 0xffff;
337              next_udp_port < 0xffff; next_udp_port += 2) {
338                 rc = rtp_sub_socket_bind(p_m_s_rtp_fd.fd, &p_m_s_rtp_sin_local, ip, next_udp_port);
339                 if (rc != 0)
340                         continue;
341
342                 rc = rtp_sub_socket_bind(p_m_s_rtcp_fd.fd, &p_m_s_rtcp_sin_local, ip, next_udp_port+1);
343                 if (rc == 0)
344                         break;
345         }
346         if (rc < 0) {
347                 PDEBUG(DEBUG_SIP, "failed to find port\n");
348                 rtp_close();
349                 return rc;
350         }
351         p_m_s_rtp_port_local = next_udp_port;
352         p_m_s_rtp_ip_local = ntohl(p_m_s_rtp_sin_local.sin_addr.s_addr);
353         PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_m_s_rtp_ip_local, p_m_s_rtp_port_local);
354         PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_m_s_rtp_ip_remote, p_m_s_rtp_port_remote);
355
356         return p_m_s_rtp_port_local;
357 }
358
359 int Psip::rtp_connect(void)
360 {
361         int rc;
362         struct in_addr ia;
363
364         ia.s_addr = htonl(p_m_s_rtp_ip_remote);
365         PDEBUG(DEBUG_SIP, "rtp_connect(ip=%s, port=%u)\n", inet_ntoa(ia), p_m_s_rtp_port_remote);
366
367         rc = rtp_sub_socket_connect(p_m_s_rtp_fd.fd, &p_m_s_rtp_sin_local, &p_m_s_rtp_sin_remote, p_m_s_rtp_ip_remote, p_m_s_rtp_port_remote);
368         if (rc < 0)
369                 return rc;
370
371         rc = rtp_sub_socket_connect(p_m_s_rtcp_fd.fd, &p_m_s_rtcp_sin_local, &p_m_s_rtcp_sin_remote, p_m_s_rtp_ip_remote, p_m_s_rtp_port_remote + 1);
372         if (rc < 0)
373                 return rc;
374
375         p_m_s_rtp_ip_local = ntohl(p_m_s_rtp_sin_local.sin_addr.s_addr);
376         PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_m_s_rtp_ip_local, p_m_s_rtp_port_local);
377         PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_m_s_rtp_ip_remote, p_m_s_rtp_port_remote);
378         p_m_s_rtp_is_connected = 1;
379
380         return 0;
381 }
382 void Psip::rtp_close(void)
383 {
384         if (p_m_s_rtp_fd.fd > 0) {
385                 unregister_fd(&p_m_s_rtp_fd);
386                 close(p_m_s_rtp_fd.fd);
387                 p_m_s_rtp_fd.fd = 0;
388         }
389         if (p_m_s_rtcp_fd.fd > 0) {
390                 unregister_fd(&p_m_s_rtcp_fd);
391                 close(p_m_s_rtcp_fd.fd);
392                 p_m_s_rtcp_fd.fd = 0;
393         }
394         if (p_m_s_rtp_is_connected) {
395                 PDEBUG(DEBUG_SIP, "rtp closed\n");
396                 p_m_s_rtp_is_connected = 0;
397         }
398 }
399
400 /* "to - from" */
401 void tv_difference(struct timeval *diff, const struct timeval *from,
402                           const struct timeval *__to)
403 {
404         struct timeval _to = *__to, *to = &_to;
405
406         if (to->tv_usec < from->tv_usec) {
407                 to->tv_sec -= 1;
408                 to->tv_usec += 1000000;
409         }
410
411         diff->tv_usec = to->tv_usec - from->tv_usec;
412         diff->tv_sec = to->tv_sec - from->tv_sec;
413 }
414
415 /* encode and send a rtp frame */
416 int Psip::rtp_send_frame(unsigned char *data, unsigned int len, int payload_type)
417 {
418         struct rtp_hdr *rtph;
419         int payload_len;
420         int duration; /* in samples */
421         unsigned char buffer[256];
422
423         if (!p_m_s_rtp_is_connected) {
424                 /* drop silently */
425                 return 0;
426         }
427
428         if (!p_m_s_rtp_tx_action) {
429                 /* initialize sequences */
430                 p_m_s_rtp_tx_action = 1;
431                 p_m_s_rtp_tx_ssrc = rand();
432                 p_m_s_rtp_tx_sequence = random();
433                 p_m_s_rtp_tx_timestamp = random();
434                 memset(&p_m_s_rtp_tx_last_tv, 0, sizeof(p_m_s_rtp_tx_last_tv));
435         }
436
437         switch (payload_type) {
438         case RTP_PT_GSM_FULL:
439                 payload_len = 33;
440                 duration = 160;
441                 break;
442         case RTP_PT_GSM_EFR:
443                 payload_len = 31;
444                 duration = 160;
445                 break;
446         case RTP_PT_ALAW:
447         case RTP_PT_ULAW:
448                 payload_len = len;
449                 duration = len;
450                 break;
451         default:
452                 PERROR("unsupported message type %d\n", payload_type);
453                 return -EINVAL;
454         }
455
456 #if 0
457         {
458                 struct timeval tv, tv_diff;
459                 long int usec_diff, frame_diff;
460
461                 gettimeofday(&tv, NULL);
462                 tv_difference(&tv_diff, &p_m_s_rtp_tx_last_tv, &tv);
463                 p_m_s_rtp_tx_last_tv = tv;
464
465                 usec_diff = tv_diff.tv_sec * 1000000 + tv_diff.tv_usec;
466                 frame_diff = (usec_diff / 20000);
467
468                 if (abs(frame_diff) > 1) {
469                         long int frame_diff_excess = frame_diff - 1;
470
471                         PDEBUG(DEBUG_SIP, "Correcting frame difference of %ld frames\n", frame_diff_excess);
472                         p_m_s_rtp_tx_sequence += frame_diff_excess;
473                         p_m_s_rtp_tx_timestamp += frame_diff_excess * duration;
474                 }
475         }
476 #endif
477
478         rtph = (struct rtp_hdr *) buffer;
479         rtph->version = RTP_VERSION;
480         rtph->padding = 0;
481         rtph->extension = 0;
482         rtph->csrc_count = 0;
483         rtph->marker = 0;
484         rtph->payload_type = payload_type;
485         rtph->sequence = htons(p_m_s_rtp_tx_sequence++);
486         rtph->timestamp = htonl(p_m_s_rtp_tx_timestamp);
487         p_m_s_rtp_tx_timestamp += duration;
488         rtph->ssrc = htonl(p_m_s_rtp_tx_ssrc);
489         memcpy(buffer + sizeof(struct rtp_hdr), data, payload_len);
490
491         if (p_m_s_rtp_fd.fd > 0) {
492                 len = write(p_m_s_rtp_fd.fd, &buffer, sizeof(struct rtp_hdr) + payload_len);
493                 if (len != sizeof(struct rtp_hdr) + payload_len) {
494                         PDEBUG(DEBUG_SIP, "write result=%d\n", len);
495 //                      rtp_close();
496 //                      rtp_shutdown();
497                         return -EIO;
498                 }
499         }
500
501         return 0;
502 }
503
504 /*
505  * bchannel handling
506  */
507
508 /* select free bchannel from loopback interface */
509 int Psip::hunt_bchannel(void)
510 {
511         return loop_hunt_bchannel(this, p_m_mISDNport);
512 }
513
514 /* close SIP side bchannel */
515 void Psip::bchannel_close(void)
516 {
517         if (p_m_s_b_sock > -1) {
518                 unregister_fd(&p_m_s_b_fd);
519                 close(p_m_s_b_sock);
520         }
521         p_m_s_b_sock = -1;
522         p_m_s_b_index = -1;
523         p_m_s_b_active = 0;
524 }
525
526 static int b_handler(struct lcr_fd *fd, unsigned int what, void *instance, int index);
527
528 /* open external side bchannel */
529 int Psip::bchannel_open(int index)
530 {
531         int ret;
532         struct sockaddr_mISDN addr;
533         struct mISDNhead act;
534
535         if (p_m_s_b_sock > -1) {
536                 PERROR("Socket already created for index %d\n", index);
537                 return(-EIO);
538         }
539
540         /* open socket */
541         ret = p_m_s_b_sock = socket(PF_ISDN, SOCK_DGRAM, ISDN_P_B_RAW);
542         if (ret < 0) {
543                 PERROR("Failed to open bchannel-socket for index %d\n", index);
544                 bchannel_close();
545                 return(ret);
546         }
547         memset(&p_m_s_b_fd, 0, sizeof(p_m_s_b_fd));
548         p_m_s_b_fd.fd = p_m_s_b_sock;
549         register_fd(&p_m_s_b_fd, LCR_FD_READ, b_handler, this, 0);
550
551
552         /* bind socket to bchannel */
553         addr.family = AF_ISDN;
554         addr.dev = mISDNloop.port;
555         addr.channel = index+1+(index>15);
556         ret = bind(p_m_s_b_sock, (struct sockaddr *)&addr, sizeof(addr));
557         if (ret < 0) {
558                 PERROR("Failed to bind bchannel-socket for index %d\n", index);
559                 bchannel_close();
560                 return(ret);
561         }
562         /* activate bchannel */
563         PDEBUG(DEBUG_SIP, "Activating SIP side channel index %i.\n", index);
564         act.prim = PH_ACTIVATE_REQ; 
565         act.id = 0;
566         ret = sendto(p_m_s_b_sock, &act, MISDN_HEADER_LEN, 0, NULL, 0);
567         if (ret < 0) {
568                 PERROR("Failed to activate index %d\n", index);
569                 bchannel_close();
570                 return(ret);
571         }
572
573         p_m_s_b_index = index;
574
575         return(0);
576 }
577
578 /* receive from bchannel */
579 void Psip::bchannel_receive(struct mISDNhead *hh, unsigned char *data, int len)
580 {
581         /* write to rx buffer */
582         while(len--) {
583                 p_m_s_rxdata[p_m_s_rxpos++] = flip[*data++];
584                 if (p_m_s_rxpos == 160) {
585                         p_m_s_rxpos = 0;
586
587                         /* transmit data via rtp */
588                         rtp_send_frame(p_m_s_rxdata, 160, (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW);
589                 }
590         }
591 }
592
593 /* transmit to bchannel */
594 void Psip::bchannel_send(unsigned int prim, unsigned int id, unsigned char *data, int len)
595 {
596         unsigned char buf[MISDN_HEADER_LEN+len];
597         struct mISDNhead *hh = (struct mISDNhead *)buf;
598         unsigned char *to = buf + MISDN_HEADER_LEN;
599         int n = len;
600         int ret;
601
602         if (!p_m_s_b_active)
603                 return;
604
605         /* make and send frame */
606         hh->prim = prim;
607         hh->id = 0;
608         while(n--)
609                 *to++ = flip[*data++];
610         ret = sendto(p_m_s_b_sock, buf, MISDN_HEADER_LEN+len, 0, NULL, 0);
611         if (ret <= 0)
612                 PERROR("Failed to send to socket index %d\n", p_m_s_b_index);
613 }
614
615 /* handle socket input */
616 static int b_handler(struct lcr_fd *fd, unsigned int what, void *instance, int index)
617 {
618         class Psip *psip = (class Psip *)instance;
619         int ret;
620         unsigned char buffer[2048+MISDN_HEADER_LEN];
621         struct mISDNhead *hh = (struct mISDNhead *)buffer;
622
623         /* handle message from bchannel */
624         if (psip->p_m_s_b_sock > -1) {
625                 ret = recv(psip->p_m_s_b_sock, buffer, sizeof(buffer), 0);
626                 if (ret >= (int)MISDN_HEADER_LEN) {
627                         switch(hh->prim) {
628                                 /* we don't care about confirms, we use rx data to sync tx */
629                                 case PH_DATA_CNF:
630                                 break;
631                                 /* we receive audio data, we respond to it AND we send tones */
632                                 case PH_DATA_IND:
633                                 psip->bchannel_receive(hh, buffer+MISDN_HEADER_LEN, ret-MISDN_HEADER_LEN);
634                                 break;
635                                 case PH_ACTIVATE_IND:
636                                 psip->p_m_s_b_active = 1;
637                                 break;
638                                 case PH_DEACTIVATE_IND:
639                                 psip->p_m_s_b_active = 0;
640                                 break;
641                         }
642                 } else {
643                         if (ret < 0 && errno != EWOULDBLOCK)
644                                 PERROR("Read from GSM port, index %d failed with return code %d\n", ret);
645                 }
646         }
647
648         return 0;
649 }
650
651 /* taken from freeswitch */
652 /* map sip responses to QSIG cause codes ala RFC4497 section 8.4.4 */
653 static int status2cause(int status)
654 {
655         switch (status) {
656         case 200:
657                 return 16; //SWITCH_CAUSE_NORMAL_CLEARING;
658         case 401:
659         case 402:
660         case 403:
661         case 407:
662         case 603:
663                 return 21; //SWITCH_CAUSE_CALL_REJECTED;
664         case 404:
665                 return 1; //SWITCH_CAUSE_UNALLOCATED_NUMBER;
666         case 485:
667         case 604:
668                 return 3; //SWITCH_CAUSE_NO_ROUTE_DESTINATION;
669         case 408:
670         case 504:
671                 return 102; //SWITCH_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
672         case 410:
673                 return 22; //SWITCH_CAUSE_NUMBER_CHANGED;
674         case 413:
675         case 414:
676         case 416:
677         case 420:
678         case 421:
679         case 423:
680         case 505:
681         case 513:
682                 return 127; //SWITCH_CAUSE_INTERWORKING;
683         case 480:
684                 return 180; //SWITCH_CAUSE_NO_USER_RESPONSE;
685         case 400:
686         case 481:
687         case 500:
688         case 503:
689                 return 41; //SWITCH_CAUSE_NORMAL_TEMPORARY_FAILURE;
690         case 486:
691         case 600:
692                 return 17; //SWITCH_CAUSE_USER_BUSY;
693         case 484:
694                 return 28; //SWITCH_CAUSE_INVALID_NUMBER_FORMAT;
695         case 488:
696         case 606:
697                 return 88; //SWITCH_CAUSE_INCOMPATIBLE_DESTINATION;
698         case 502:
699                 return 38; //SWITCH_CAUSE_NETWORK_OUT_OF_ORDER;
700         case 405:
701                 return 63; //SWITCH_CAUSE_SERVICE_UNAVAILABLE;
702         case 406:
703         case 415:
704         case 501:
705                 return 79; //SWITCH_CAUSE_SERVICE_NOT_IMPLEMENTED;
706         case 482:
707         case 483:
708                 return 25; //SWITCH_CAUSE_EXCHANGE_ROUTING_ERROR;
709         case 487:
710                 return 31; //??? SWITCH_CAUSE_ORIGINATOR_CANCEL;
711         default:
712                 return 31; //SWITCH_CAUSE_NORMAL_UNSPECIFIED;
713         }
714 }
715
716 static int cause2status(int cause, int location, const char **st)
717 {
718         int s;
719
720         switch (cause) {
721         case 1:
722                 s = 404; *st = sip_404_Not_found;
723                 break;
724         case 2:
725                 s = 404; *st = sip_404_Not_found;
726                 break;
727         case 3:
728                 s = 404; *st = sip_404_Not_found;
729                 break;
730         case 17:
731                 s = 486; *st = sip_486_Busy_here;
732                 break;
733         case 18:
734                 s = 408; *st = sip_408_Request_timeout;
735                 break;
736         case 19:
737                 s = 480; *st = sip_480_Temporarily_unavailable;
738                 break;
739         case 20:
740                 s = 480; *st = sip_480_Temporarily_unavailable;
741                 break;
742         case 21:
743                 if (location == LOCATION_USER) {
744                         s = 603; *st = sip_603_Decline;
745                 } else {
746                         s = 403; *st = sip_403_Forbidden;
747                 }
748                 break;
749         case 22:
750                 //s = 301; *st = sip_301_Moved_permanently;
751                 s = 410; *st = sip_410_Gone;
752                 break;
753         case 23:
754                 s = 410; *st = sip_410_Gone;
755                 break;
756         case 27:
757                 s = 502; *st = sip_502_Bad_gateway;
758                 break;
759         case 28:
760                 s = 484; *st = sip_484_Address_incomplete;
761                 break;
762         case 29:
763                 s = 501; *st = sip_501_Not_implemented;
764                 break;
765         case 31:
766                 s = 480; *st = sip_480_Temporarily_unavailable;
767                 break;
768         case 34:
769                 s = 503; *st = sip_503_Service_unavailable;
770                 break;
771         case 38:
772                 s = 503; *st = sip_503_Service_unavailable;
773                 break;
774         case 41:
775                 s = 503; *st = sip_503_Service_unavailable;
776                 break;
777         case 42:
778                 s = 503; *st = sip_503_Service_unavailable;
779                 break;
780         case 47:
781                 s = 503; *st = sip_503_Service_unavailable;
782                 break;
783         case 55:
784                 s = 403; *st = sip_403_Forbidden;
785                 break;
786         case 57:
787                 s = 403; *st = sip_403_Forbidden;
788                 break;
789         case 58:
790                 s = 503; *st = sip_503_Service_unavailable;
791                 break;
792         case 65:
793                 s = 488; *st = sip_488_Not_acceptable;
794                 break;
795         case 69:
796                 s = 501; *st = sip_501_Not_implemented;
797                 break;
798         case 70:
799                 s = 488; *st = sip_488_Not_acceptable;
800                 break;
801         case 79:
802                 s = 501; *st = sip_501_Not_implemented;
803                 break;
804         case 87:
805                 s = 403; *st = sip_403_Forbidden;
806                 break;
807         case 88:
808                 s = 503; *st = sip_503_Service_unavailable;
809                 break;
810         case 102:
811                 s = 504; *st = sip_504_Gateway_time_out;
812                 break;
813         default:
814                 s = 468; *st = sip_486_Busy_here;
815         }
816
817         return s;
818 }
819
820 /*
821  * endpoint sends messages to the SIP port
822  */
823
824 int Psip::message_connect(unsigned int epoint_id, int message_id, union parameter *param)
825 {
826         char sdp_str[256];
827         struct in_addr ia;
828         struct lcr_msg *message;
829
830         if (rtp_connect() < 0) {
831                 nua_cancel(p_m_s_handle, TAG_END());
832                 nua_handle_destroy(p_m_s_handle);
833                 p_m_s_handle = NULL;
834                 sip_trace_header(this, "CANCEL", DIRECTION_OUT);
835                 add_trace("reason", NULL, "failed to connect RTP/RTCP sockts");
836                 end_trace();
837                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
838                 message->param.disconnectinfo.cause = 41;
839                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
840                 message_put(message);
841                 new_state(PORT_STATE_RELEASE);
842                 trigger_work(&p_m_s_delete);
843                 return 0;
844         }
845         ia.s_addr = htonl(p_m_s_rtp_ip_local);
846
847         SPRINT(sdp_str,
848                 "v=0\n"
849                 "o=LCR-Sofia-SIP 0 0 IN IP4 %s\n"
850                 "s=SIP Call\n"
851                 "c=IN IP4 %s\n"
852                 "t=0 0\n"
853                 "m=audio %d RTP/AVP %d\n"
854                 "a=rtpmap:%d %s/8000\n"
855                 , inet_ntoa(ia), inet_ntoa(ia), p_m_s_rtp_port_local, (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW, (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW, (options.law=='a')?"PCMA":"PCMU");
856         PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
857
858         nua_respond(p_m_s_handle, SIP_200_OK,
859                 NUTAG_MEDIA_ENABLE(0),
860                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
861                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
862         new_state(PORT_STATE_CONNECT);
863         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
864         add_trace("respond", "value", "200 OK");
865         add_trace("reason", NULL, "call connected");
866         end_trace();
867
868         return 0;
869 }
870
871 int Psip::message_release(unsigned int epoint_id, int message_id, union parameter *param)
872 {
873         struct lcr_msg *message;
874         char cause_str[128] = "";
875         int cause = param->disconnectinfo.cause;
876         int location = param->disconnectinfo.cause;
877         int status;
878         const char *status_text;
879
880         if (cause > 0 && cause <= 127) {
881                 SPRINT(cause_str, "Q.850;cause=%d;text=\"%s\"", cause, isdn_cause[cause].english);
882         }
883
884         switch (p_state) {
885         case PORT_STATE_OUT_SETUP:
886         case PORT_STATE_OUT_PROCEEDING:
887         case PORT_STATE_OUT_ALERTING:
888                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will cancel\n");
889                 sip_trace_header(this, "CANCEL", DIRECTION_OUT);
890                 if (cause_str[0])
891                         add_trace("cause", "value", "%d", cause);
892                 end_trace();
893                 nua_cancel(p_m_s_handle, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
894                 break;
895         case PORT_STATE_IN_SETUP:
896         case PORT_STATE_IN_PROCEEDING:
897         case PORT_STATE_IN_ALERTING:
898                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will respond\n");
899                 status = cause2status(cause, location, &status_text);
900                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
901                 if (cause_str[0])
902                         add_trace("cause", "value", "%d", cause);
903                 add_trace("respond", "value", "%d %s", status, status_text);
904                 end_trace();
905                 nua_respond(p_m_s_handle, status, status_text, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
906                 nua_handle_destroy(p_m_s_handle);
907                 p_m_s_handle = NULL;
908                 trigger_work(&p_m_s_delete);
909                 break;
910         default:
911                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will perform nua_bye\n");
912                 sip_trace_header(this, "BYE", DIRECTION_OUT);
913                 if (cause_str[0])
914                         add_trace("cause", "value", "%d", cause);
915                 end_trace();
916                 nua_bye(p_m_s_handle, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
917         }
918
919         if (message_id == MESSAGE_DISCONNECT) {
920                 while(p_epointlist) {
921                         message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
922                         message->param.disconnectinfo.cause = CAUSE_NORMAL;
923                         message->param.disconnectinfo.location = LOCATION_BEYOND;
924                         message_put(message);
925                         /* remove epoint */
926                         free_epointlist(p_epointlist);
927                 }
928         }
929
930         new_state(PORT_STATE_RELEASE);
931
932         return(0);
933 }
934
935 int Psip::message_setup(unsigned int epoint_id, int message_id, union parameter *param)
936 {
937         struct sip_inst *inst = (struct sip_inst *) p_m_s_sip_inst;
938         char from[128];
939         char to[128];
940         const char *local = inst->interface->sip_local_ip;
941         const char *remote = inst->interface->sip_remote_ip;
942         char sdp_str[256];
943         struct in_addr ia;
944         struct epoint_list *epointlist;
945         sip_cseq_t *cseq = NULL;
946         int ret;
947         int channel;
948
949         PDEBUG(DEBUG_SIP, "Doing Setup (inst %p)\n", inst);
950
951         /* release if port is blocked */
952         if (p_m_mISDNport->ifport->block) {
953                 struct lcr_msg *message;
954
955                 sip_trace_header(this, "INVITE", DIRECTION_OUT);
956                 add_trace("failure", NULL, "Port blocked.");
957                 end_trace();
958                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
959                 message->param.disconnectinfo.cause = 27; // temp. unavail.
960                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
961                 message_put(message);
962                 new_state(PORT_STATE_RELEASE);
963                 trigger_work(&p_m_s_delete);
964                 return 0;
965         }
966
967         /* hunt channel */
968         ret = channel = hunt_bchannel();
969         if (ret < 0)
970                 goto no_channel;
971         /* open channel */
972         ret = seize_bchannel(channel, 1);
973         if (ret < 0) {
974                 struct lcr_msg *message;
975
976                 no_channel:
977                 sip_trace_header(this, "INVITE", DIRECTION_OUT);
978                 add_trace("failure", NULL, "No internal audio channel available.");
979                 end_trace();
980                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
981                 message->param.disconnectinfo.cause = 34;
982                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
983                 message_put(message);
984                 new_state(PORT_STATE_RELEASE);
985                 trigger_work(&p_m_s_delete);
986                 return 0;
987         }
988         bchannel_event(p_m_mISDNport, p_m_b_index, B_EVENT_USE);
989         if (bchannel_open(p_m_b_index))
990                 goto no_channel;
991
992         memcpy(&p_dialinginfo, &param->setup.dialinginfo, sizeof(p_dialinginfo));
993         memcpy(&p_callerinfo, &param->setup.callerinfo, sizeof(p_callerinfo));
994         memcpy(&p_redirinfo, &param->setup.redirinfo, sizeof(p_redirinfo));
995
996         /* connect to remote RTP */
997         if (rtp_open() < 0) {
998                 struct lcr_msg *message;
999
1000                 PERROR("Failed to open RTP sockets\n");
1001                 /* send release message to endpoit */
1002                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1003                 message->param.disconnectinfo.cause = 41;
1004                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1005                 message_put(message);
1006                 new_state(PORT_STATE_RELEASE);
1007                 trigger_work(&p_m_s_delete);
1008                 return 0;
1009         }
1010         SPRINT(from, "sip:%s@%s", param->setup.callerinfo.id, local);
1011         SPRINT(to, "sip:%s@%s", param->setup.dialinginfo.id, remote);
1012
1013         sip_trace_header(this, "INVITE", DIRECTION_OUT);
1014         add_trace("from", "uri", "%s", from);
1015         add_trace("to", "uri", "%s", to);
1016         add_trace("rtp", "port", "%d,%d", p_m_s_rtp_port_local, p_m_s_rtp_port_local + 1);
1017         end_trace();
1018
1019         p_m_s_handle = nua_handle(inst->nua, NULL, TAG_END());
1020         if (!p_m_s_handle) {
1021                 struct lcr_msg *message;
1022
1023                 PERROR("Failed to create handle\n");
1024                 /* send release message to endpoit */
1025                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1026                 message->param.disconnectinfo.cause = 41;
1027                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1028                 message_put(message);
1029                 new_state(PORT_STATE_RELEASE);
1030                 trigger_work(&p_m_s_delete);
1031                 return 0;
1032         }
1033         /* apply handle */
1034         sip_trace_header(this, "NEW handle", DIRECTION_IN);
1035         add_trace("handle", "new", "0x%x", p_m_s_handle);
1036         end_trace();
1037
1038         inet_pton(AF_INET, local, &p_m_s_rtp_ip_local);
1039         p_m_s_rtp_ip_local = ntohl(p_m_s_rtp_ip_local);
1040         ia.s_addr = htonl(p_m_s_rtp_ip_local);
1041         SPRINT(sdp_str,
1042                 "v=0\n"
1043                 "o=LCR-Sofia-SIP 0 0 IN IP4 %s\n"
1044                 "s=SIP Call\n"
1045                 "c=IN IP4 %s\n"
1046                 "t=0 0\n"
1047                 "m=audio %d RTP/AVP %d\n"
1048                 "a=rtpmap:%d %s/8000\n"
1049                 , inet_ntoa(ia), inet_ntoa(ia), p_m_s_rtp_port_local, (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW, (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW, (options.law=='a')?"PCMA":"PCMU");
1050         PDEBUG(DEBUG_SIP, "Using SDP for invite: %s\n", sdp_str);
1051
1052 //      cseq = sip_cseq_create(sip_home, 123, SIP_METHOD_INVITE);
1053
1054         nua_invite(p_m_s_handle,
1055                 TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1056                 TAG_IF(to[0], SIPTAG_TO_STR(to)),
1057                 TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1058                 NUTAG_MEDIA_ENABLE(0),
1059                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1060                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1061         new_state(PORT_STATE_OUT_SETUP);
1062
1063         /* attach only if not already */
1064         epointlist = p_epointlist;
1065         while(epointlist) {
1066                 if (epointlist->epoint_id == epoint_id)
1067                         break;
1068                 epointlist = epointlist->next;
1069         }
1070         if (!epointlist)
1071                 epointlist_new(epoint_id);
1072
1073         return 0;
1074 }
1075         
1076 int Psip::message_epoint(unsigned int epoint_id, int message_id, union parameter *param)
1077 {
1078         class Endpoint *epoint;
1079
1080         if (PmISDN::message_epoint(epoint_id, message_id, param))
1081                 return 1;
1082
1083         epoint = find_epoint_id(epoint_id);
1084         if (!epoint) {
1085                 PDEBUG(DEBUG_SIP, "PORT(%s) no endpoint object found where the message is from.\n", p_name);
1086                 return 0;
1087         }
1088
1089         switch(message_id) {
1090                 case MESSAGE_ALERTING: /* call is ringing on LCR side */
1091                 if (p_state != PORT_STATE_IN_SETUP
1092                  && p_state != PORT_STATE_IN_PROCEEDING)
1093                         return 0;
1094                 nua_respond(p_m_s_handle, SIP_180_RINGING, TAG_END());
1095                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1096                 add_trace("respond", "value", "180 Ringing");
1097                 end_trace();
1098                 new_state(PORT_STATE_IN_ALERTING);
1099                 return 1;
1100
1101                 case MESSAGE_CONNECT: /* call is connected on LCR side */
1102                 if (p_state != PORT_STATE_IN_SETUP
1103                  && p_state != PORT_STATE_IN_PROCEEDING
1104                  && p_state != PORT_STATE_IN_ALERTING)
1105                         return 0;
1106                 message_connect(epoint_id, message_id, param);
1107                 return 1;
1108
1109                 case MESSAGE_DISCONNECT: /* call has been disconnected */
1110                 case MESSAGE_RELEASE: /* call has been released */
1111                 message_release(epoint_id, message_id, param);
1112                 return 1;
1113
1114                 case MESSAGE_SETUP: /* dial-out command received from epoint */
1115                 message_setup(epoint_id, message_id, param);
1116                 return 1;
1117
1118                 default:
1119                 PDEBUG(DEBUG_SIP, "PORT(%s) SP port with (caller id %s) received an unsupported message: %d\n", p_name, p_callerinfo.id, message_id);
1120         }
1121
1122         return 0;
1123 }
1124
1125 int Psip::parse_sdp(sip_t const *sip, unsigned int *ip, unsigned short *port)
1126 {
1127         int codec_supported = 0;
1128
1129         if (!sip->sip_payload) {
1130                 PDEBUG(DEBUG_SIP, "no payload given\n");
1131                 return 0;
1132         }
1133
1134         sdp_parser_t *parser;
1135         sdp_session_t *sdp;
1136         sdp_media_t *m;
1137         sdp_attribute_t *attr;
1138         sdp_rtpmap_t *map;
1139         sdp_connection_t *conn;
1140
1141         PDEBUG(DEBUG_SIP, "payload given: %s\n", sip->sip_payload->pl_data);
1142
1143         parser = sdp_parse(NULL, sip->sip_payload->pl_data, (int) strlen(sip->sip_payload->pl_data), 0);
1144         if (!parser) {
1145                 return 400;
1146         }
1147         if (!(sdp = sdp_session(parser))) {
1148                 sdp_parser_free(parser);
1149                 return 400;
1150         }
1151         for (m = sdp->sdp_media; m; m = m->m_next) {
1152                 if (m->m_proto != sdp_proto_rtp)
1153                         continue;
1154                 if (m->m_type != sdp_media_audio)
1155                         continue;
1156                 PDEBUG(DEBUG_SIP, "RTP port:'%u'\n", m->m_port);
1157                 *port = m->m_port;
1158                 for (attr = m->m_attributes; attr; attr = attr->a_next) {
1159                         PDEBUG(DEBUG_SIP, "ATTR: name:'%s' value='%s'\n", attr->a_name, attr->a_value);
1160                 }
1161                 if (m->m_connections) {
1162                         conn = m->m_connections;
1163                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", conn->c_address);
1164                         inet_pton(AF_INET, conn->c_address, ip);
1165                         *ip = ntohl(p_m_s_rtp_ip_remote);
1166                 } else {
1167                         char *p = sip->sip_payload->pl_data;
1168                         char addr[16];
1169
1170                         PDEBUG(DEBUG_SIP, "sofia cannot find connection tag, so we try ourself\n");
1171                         p = strstr(p, "c=IN IP4 ");
1172                         if (!p) {
1173                                 PDEBUG(DEBUG_SIP, "missing c-tag with internet address\n");
1174                                 sdp_parser_free(parser);
1175                                 return 400;
1176                         }
1177                         SCPY(addr, p + 9);
1178                         if ((p = strchr(addr, '\n'))) *p = '\0';
1179                         if ((p = strchr(addr, '\r'))) *p = '\0';
1180                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", addr);
1181                         inet_pton(AF_INET, addr, ip);
1182                         *ip = ntohl(p_m_s_rtp_ip_remote);
1183                 }
1184                 for (map = m->m_rtpmaps; map; map = map->rm_next) {
1185                         PDEBUG(DEBUG_SIP, "RTPMAP: coding:'%s' rate='%d'\n", map->rm_encoding, map->rm_rate);
1186                         if (!strcmp(map->rm_encoding, (options.law=='a')?"PCMA":"PCMU") && map->rm_rate == 8000) {
1187                                 PDEBUG(DEBUG_SIP, "supported codec found\n");
1188                                 codec_supported = 1;
1189                                 goto done_codec;
1190                         }
1191                 }
1192         }
1193         done_codec:
1194
1195         sdp_parser_free(parser);
1196
1197         if (!codec_supported)
1198                 return 415;
1199
1200         return 0;
1201 }
1202
1203 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[])
1204 {
1205         const char *from = "", *to = "";
1206         int ret;
1207         class Endpoint *epoint;
1208         struct lcr_msg *message;
1209         int channel;
1210
1211         if (sip->sip_from && sip->sip_from->a_url)
1212                 from = sip->sip_from->a_url->url_user;
1213         if (sip->sip_to && sip->sip_to->a_url)
1214                 to = sip->sip_to->a_url->url_user;
1215         PDEBUG(DEBUG_SIP, "invite received (%s->%s)\n", from, to);
1216
1217         ret = parse_sdp(sip, &p_m_s_rtp_ip_remote, &p_m_s_rtp_port_remote);
1218         if (ret) {
1219                 if (ret == 400)
1220                         nua_respond(nh, SIP_400_BAD_REQUEST, TAG_END());
1221                 else
1222                         nua_respond(nh, SIP_415_UNSUPPORTED_MEDIA, TAG_END());
1223                 nua_handle_destroy(nh);
1224                 p_m_s_handle = NULL;
1225                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1226                 if (ret == 400)
1227                         add_trace("respond", "value", "415 Unsupported Media");
1228                 else
1229                         add_trace("respond", "value", "400 Bad Request");
1230                 add_trace("reason", NULL, "offered codec does not match");
1231                 end_trace();
1232                 new_state(PORT_STATE_RELEASE);
1233                 trigger_work(&p_m_s_delete);
1234                 return;
1235         }
1236
1237         /* connect to remote RTP */
1238         if (rtp_open() < 0) {
1239                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1240                 nua_handle_destroy(nh);
1241                 p_m_s_handle = NULL;
1242                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1243                 add_trace("respond", "value", "500 Internal Server Error");
1244                 add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1245                 end_trace();
1246                 new_state(PORT_STATE_RELEASE);
1247                 trigger_work(&p_m_s_delete);
1248                 return;
1249         }
1250
1251         /* apply handle */
1252         sip_trace_header(this, "NEW handle", DIRECTION_IN);
1253         add_trace("handle", "new", "0x%x", nh);
1254         p_m_s_handle = nh;
1255         end_trace();
1256
1257         /* if blocked, release call */
1258         if (p_m_mISDNport->ifport->block) {
1259                 nua_respond(nh, SIP_503_SERVICE_UNAVAILABLE, TAG_END());
1260                 nua_handle_destroy(nh);
1261                 p_m_s_handle = NULL;
1262                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1263                 add_trace("respond", "value", "503 Service Unavailable");
1264                 add_trace("reason", NULL, "port is blocked");
1265                 end_trace();
1266                 new_state(PORT_STATE_RELEASE);
1267                 trigger_work(&p_m_s_delete);
1268                 return;
1269         }
1270         sip_trace_header(this, "INVITE", DIRECTION_IN);
1271         add_trace("RTP", "port", "%d", p_m_s_rtp_port_remote);
1272         /* caller information */
1273         if (!from[0]) {
1274                 p_callerinfo.present = INFO_PRESENT_NOTAVAIL;
1275                 p_callerinfo.ntype = INFO_NTYPE_NOTPRESENT;
1276                 add_trace("calling", "present", "unavailable");
1277         } else {
1278                 p_callerinfo.present = INFO_PRESENT_ALLOWED;
1279                 add_trace("calling", "present", "allowed");
1280                 p_callerinfo.screen = INFO_SCREEN_NETWORK;
1281                 p_callerinfo.ntype = INFO_NTYPE_UNKNOWN;
1282                 SCPY(p_callerinfo.id, from);
1283                 add_trace("calling", "number", "%s", from);
1284         }
1285         p_callerinfo.isdn_port = p_m_portnum;
1286         SCPY(p_callerinfo.interface, p_m_mISDNport->ifport->interface->name);
1287         /* dialing information */
1288         if (to[0]) {
1289                 p_dialinginfo.ntype = INFO_NTYPE_UNKNOWN;
1290                 SCAT(p_dialinginfo.id, to);
1291                 add_trace("dialing", "number", "%s", to);
1292         }
1293         /* redir info */
1294         /* bearer capability */
1295         p_capainfo.bearer_capa = INFO_BC_SPEECH;
1296         p_capainfo.bearer_info1 = (options.law=='a')?3:2;
1297         p_capainfo.bearer_mode = INFO_BMODE_CIRCUIT;
1298         add_trace("bearer", "capa", "speech");
1299         add_trace("bearer", "mode", "circuit");
1300         /* if packet mode works some day, see dss1.cpp for conditions */
1301         p_capainfo.source_mode = B_MODE_TRANSPARENT;
1302
1303         end_trace();
1304
1305         /* hunt channel */
1306         ret = channel = hunt_bchannel();
1307         if (ret < 0)
1308                 goto no_channel;
1309
1310         /* open channel */
1311         ret = seize_bchannel(channel, 1);
1312         if (ret < 0) {
1313                 no_channel:
1314                 nua_respond(nh, SIP_480_TEMPORARILY_UNAVAILABLE, TAG_END());
1315                 nua_handle_destroy(nh);
1316                 p_m_s_handle = NULL;
1317                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1318                 add_trace("respond", "value", "480 Temporarily Unavailable");
1319                 add_trace("reason", NULL, "no channel");
1320                 end_trace();
1321                 new_state(PORT_STATE_RELEASE);
1322                 trigger_work(&p_m_s_delete);
1323                 return;
1324         }
1325         bchannel_event(p_m_mISDNport, p_m_b_index, B_EVENT_USE);
1326         if (bchannel_open(p_m_b_index))
1327                 goto no_channel;
1328
1329         /* create endpoint */
1330         if (p_epointlist)
1331                 FATAL("Incoming call but already got an endpoint.\n");
1332         if (!(epoint = new Endpoint(p_serial, 0)))
1333                 FATAL("No memory for Endpoint instance\n");
1334         if (!(epoint->ep_app = new DEFAULT_ENDPOINT_APP(epoint, 0))) //incoming
1335                 FATAL("No memory for Endpoint Application instance\n");
1336         epointlist_new(epoint->ep_serial);
1337
1338         /* send trying (proceeding) */
1339         nua_respond(nh, SIP_100_TRYING, TAG_END());
1340         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1341         add_trace("respond", "value", "100 Trying");
1342         end_trace();
1343
1344         new_state(PORT_STATE_IN_PROCEEDING);
1345
1346         /* send setup message to endpoit */
1347         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_SETUP);
1348         message->param.setup.isdn_port = p_m_portnum;
1349         message->param.setup.port_type = p_type;
1350 //      message->param.setup.dtmf = 0;
1351         memcpy(&message->param.setup.dialinginfo, &p_dialinginfo, sizeof(struct dialing_info));
1352         memcpy(&message->param.setup.callerinfo, &p_callerinfo, sizeof(struct caller_info));
1353         memcpy(&message->param.setup.capainfo, &p_capainfo, sizeof(struct capa_info));
1354 //      SCPY((char *)message->param.setup.useruser.data, useruser.info);
1355 //      message->param.setup.useruser.len = strlen(mncc->useruser.info);
1356 //      message->param.setup.useruser.protocol = mncc->useruser.proto;
1357         message_put(message);
1358 }
1359
1360 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[])
1361 {
1362         struct lcr_msg *message;
1363         int cause = 0;
1364
1365         PDEBUG(DEBUG_SIP, "bye received\n");
1366
1367         sip_trace_header(this, "BYE", DIRECTION_IN);
1368         if (sip->sip_reason && sip->sip_reason->re_protocol && !strcasecmp(sip->sip_reason->re_protocol, "Q.850") && sip->sip_reason->re_cause) {
1369                 cause = atoi(sip->sip_reason->re_cause);
1370                 add_trace("cause", "value", "%d", cause);
1371         }
1372         end_trace();
1373
1374 // let stack do bye automaticall, since it will not accept our response for some reason
1375 //      nua_respond(nh, SIP_200_OK, TAG_END());
1376         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1377         add_trace("respond", "value", "200 OK");
1378         end_trace();
1379 //      nua_handle_destroy(nh);
1380         p_m_s_handle = NULL;
1381
1382         rtp_close();
1383
1384         while(p_epointlist) {
1385                 /* send setup message to endpoit */
1386                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1387                 message->param.disconnectinfo.cause = cause ? : 16;
1388                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1389                 message_put(message);
1390                 /* remove epoint */
1391                 free_epointlist(p_epointlist);
1392         }
1393         new_state(PORT_STATE_RELEASE);
1394         trigger_work(&p_m_s_delete);
1395 }
1396
1397 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[])
1398 {
1399         struct lcr_msg *message;
1400
1401         PDEBUG(DEBUG_SIP, "cancel received\n");
1402
1403         sip_trace_header(this, "CANCEL", DIRECTION_IN);
1404         end_trace();
1405
1406         nua_handle_destroy(nh);
1407         p_m_s_handle = NULL;
1408
1409         rtp_close();
1410
1411         while(p_epointlist) {
1412                 /* send setup message to endpoit */
1413                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1414                 message->param.disconnectinfo.cause = 16;
1415                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1416                 message_put(message);
1417                 /* remove epoint */
1418                 free_epointlist(p_epointlist);
1419         }
1420         new_state(PORT_STATE_RELEASE);
1421         trigger_work(&p_m_s_delete);
1422 }
1423
1424 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[])
1425 {
1426         PDEBUG(DEBUG_SIP, "bye response received\n");
1427
1428         nua_handle_destroy(nh);
1429         p_m_s_handle = NULL;
1430
1431         rtp_close();
1432
1433         trigger_work(&p_m_s_delete);
1434 }
1435
1436 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[])
1437 {
1438         PDEBUG(DEBUG_SIP, "cancel response received\n");
1439
1440         nua_handle_destroy(nh);
1441         p_m_s_handle = NULL;
1442
1443         rtp_close();
1444
1445         trigger_work(&p_m_s_delete);
1446 }
1447
1448 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[])
1449 {
1450         struct lcr_msg *message;
1451         int cause = 0, location = 0;
1452
1453         PDEBUG(DEBUG_SIP, "response to invite received (status = %d)\n", status);
1454
1455         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1456         add_trace("respond", "value", "%d", status);
1457         end_trace();
1458
1459         /* process 1xx */
1460         switch (status) {
1461         case 100:
1462                 PDEBUG(DEBUG_SIP, "do proceeding\n");
1463                 new_state(PORT_STATE_OUT_PROCEEDING);
1464                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROCEEDING);
1465                 message_put(message);
1466                 return;
1467         case 180:
1468                 PDEBUG(DEBUG_SIP, "do alerting\n");
1469                 new_state(PORT_STATE_OUT_ALERTING);
1470                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_ALERTING);
1471                 message_put(message);
1472                 return;
1473         default:
1474                 if (status < 100 || status > 199)
1475                         break;
1476                 PDEBUG(DEBUG_SIP, "skipping 1xx message\n");
1477
1478                 return;
1479         }
1480
1481         /* process 2xx */
1482         if (status >= 200 && status <= 299) {
1483                 int ret;
1484
1485                 ret = parse_sdp(sip, &p_m_s_rtp_ip_remote, &p_m_s_rtp_port_remote);
1486                 if (ret) {
1487                         if (ret == 400)
1488                                 nua_cancel(nh, TAG_END());
1489                         else
1490                                 nua_cancel(nh, TAG_END());
1491                         sip_trace_header(this, "CANCEL", DIRECTION_OUT);
1492                         add_trace("reason", NULL, "offered codec does not match");
1493                         end_trace();
1494                         cause = 88;
1495                         location = LOCATION_PRIVATE_LOCAL;
1496                         goto release_with_cause;
1497                 }
1498
1499                 /* connect to remote RTP */
1500                 if (rtp_connect() < 0) {
1501                         nua_cancel(nh, TAG_END());
1502                         sip_trace_header(this, "CANCEL", DIRECTION_OUT);
1503                         add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1504                         end_trace();
1505                         cause = 31;
1506                         location = LOCATION_PRIVATE_LOCAL;
1507                         goto release_with_cause;
1508                 }
1509
1510                 PDEBUG(DEBUG_SIP, "do connect\n");
1511                 nua_ack(nh, TAG_END());
1512                 new_state(PORT_STATE_CONNECT);
1513                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CONNECT);
1514                 message_put(message);
1515
1516                 return;
1517         }
1518
1519         cause = status2cause(status);
1520         location = LOCATION_BEYOND;
1521
1522 release_with_cause:
1523         PDEBUG(DEBUG_SIP, "do release (cause %d)\n", cause);
1524
1525         while(p_epointlist) {
1526                 /* send setup message to endpoit */
1527                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1528                 message->param.disconnectinfo.cause = cause;
1529                 message->param.disconnectinfo.location = location;
1530                 message_put(message);
1531                 /* remove epoint */
1532                 free_epointlist(p_epointlist);
1533         }
1534
1535         new_state(PORT_STATE_RELEASE);
1536
1537         rtp_close();
1538
1539         trigger_work(&p_m_s_delete);
1540 }
1541
1542 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[])
1543 {
1544         struct sip_inst *inst = (struct sip_inst *) magic;
1545         class Port *port;
1546         class Psip *psip = NULL;
1547
1548         PDEBUG(DEBUG_SIP, "Event %d from stack received (handle=%p)\n", event, nh);
1549         if (!nh)
1550                 return;
1551
1552         /* create or find port instance */
1553         if (event == nua_i_invite)
1554         {
1555                 char name[64];
1556                 /* create call instance */
1557                 SPRINT(name, "%s-%d-in", inst->interface->name, 0);
1558                 if (!(psip = new Psip(PORT_TYPE_SIP_IN, (inst->interface->ifport) ? inst->interface->ifport->mISDNport : NULL, name, NULL, 0, 0, B_MODE_TRANSPARENT, inst->interface)))
1559                         FATAL("Cannot create Port instance.\n");
1560         } else {
1561                 port = port_first;
1562                 while(port) {
1563                         if ((port->p_type & PORT_CLASS_mISDN_MASK) == PORT_CLASS_SIP) {
1564                                 psip = (class Psip *)port;
1565                                 if (psip->p_m_s_handle == nh) {
1566                                         break;
1567                                 }
1568                         }
1569                         port = port->next;
1570                 }
1571         }
1572         if (!psip) {
1573                 PERROR("no SIP Port found for handel %p\n", nh);
1574                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1575                 nua_handle_destroy(nh);
1576                 return;
1577         }
1578
1579         switch (event) {
1580         case nua_r_set_params:
1581                 PDEBUG(DEBUG_SIP, "setparam response\n");
1582                 break;
1583         case nua_i_error:
1584                 PDEBUG(DEBUG_SIP, "error received\n");
1585                 break;
1586         case nua_i_state:
1587                 PDEBUG(DEBUG_SIP, "state change received\n");
1588                 break;
1589         case nua_i_register:
1590                 PDEBUG(DEBUG_SIP, "register received\n");
1591                 break;
1592         case nua_i_invite:
1593                 psip->i_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
1594                 break;
1595         case nua_i_ack:
1596                 PDEBUG(DEBUG_SIP, "ack received\n");
1597                 break;
1598         case nua_i_active:
1599                 PDEBUG(DEBUG_SIP, "active received\n");
1600                 break;
1601         case nua_i_bye:
1602                 psip->i_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
1603                 break;
1604         case nua_i_cancel:
1605                 psip->i_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
1606                 break;
1607         case nua_r_bye:
1608                 psip->r_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
1609                 break;
1610         case nua_r_cancel:
1611                 psip->r_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
1612                 break;
1613         case nua_r_invite:
1614                 psip->r_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
1615                 break;
1616         case nua_i_terminated:
1617                 PDEBUG(DEBUG_SIP, "terminated received\n");
1618                 break;
1619         default:
1620                 PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
1621         }
1622 }
1623
1624 /* received shutdown due to termination of RTP */
1625 void Psip::rtp_shutdown(void)
1626 {
1627         struct lcr_msg *message;
1628
1629         PDEBUG(DEBUG_SIP, "RTP stream terminated\n");
1630
1631         sip_trace_header(this, "RTP terminated", DIRECTION_IN);
1632         end_trace();
1633
1634         nua_handle_destroy(p_m_s_handle);
1635         p_m_s_handle = NULL;
1636
1637         while(p_epointlist) {
1638                 /* send setup message to endpoit */
1639                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1640                 message->param.disconnectinfo.cause = 16;
1641                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1642                 message_put(message);
1643                 /* remove epoint */
1644                 free_epointlist(p_epointlist);
1645         }
1646         new_state(PORT_STATE_RELEASE);
1647         trigger_work(&p_m_s_delete);
1648 }
1649
1650 int sip_init_inst(struct interface *interface)
1651 {
1652         struct sip_inst *inst = (struct sip_inst *) MALLOC(sizeof(*inst));
1653
1654         interface->sip_inst = inst;
1655         inst->interface = interface;
1656
1657         /* init root object */
1658         inst->root = su_root_create(inst);
1659         if (!inst->root) {
1660                 PERROR("Failed to create SIP root\n");
1661                 sip_exit_inst(interface);
1662                 return -EINVAL;
1663         }
1664
1665         inst->nua = nua_create(inst->root, sip_callback, inst, TAG_NULL());
1666         if (!inst->nua) {
1667                 PERROR("Failed to create SIP stack object\n");
1668                 sip_exit_inst(interface);
1669                 return -EINVAL;
1670         }
1671         nua_set_params(inst->nua,
1672                 SIPTAG_ALLOW_STR("INVITE,ACK,BYE,CANCEL,OPTIONS,NOTIFY,INFO"),
1673                 NUTAG_APPL_METHOD("INVITE"),
1674                 NUTAG_APPL_METHOD("ACK"),
1675 //              NUTAG_APPL_METHOD("BYE"), /* we must reply to BYE */
1676                 NUTAG_APPL_METHOD("CANCEL"),
1677                 NUTAG_APPL_METHOD("OPTIONS"),
1678                 NUTAG_APPL_METHOD("NOTIFY"),
1679                 NUTAG_APPL_METHOD("INFO"),
1680                 NUTAG_AUTOACK(0),
1681                 NUTAG_AUTO100(0),
1682                 NUTAG_AUTOALERT(0),
1683                 NUTAG_AUTOANSWER(0),
1684                 TAG_NULL());
1685
1686         PDEBUG(DEBUG_SIP, "SIP interface created (inst=%p)\n", inst);
1687
1688         return 0;
1689 }
1690
1691 void sip_exit_inst(struct interface *interface)
1692 {
1693         struct sip_inst *inst = (struct sip_inst *) interface->sip_inst;
1694
1695         if (!inst)
1696                 return;
1697         if (inst->root)
1698                 su_root_destroy(inst->root);
1699         if (inst->nua) {
1700                 nua_destroy(inst->nua);
1701         }
1702         FREE(inst, sizeof(*inst));
1703         interface->sip_inst = NULL;
1704
1705         PDEBUG(DEBUG_SIP, "SIP interface removed\n");
1706 }
1707
1708 extern su_log_t su_log_default[];
1709 extern su_log_t nua_log[];
1710 //extern su_log_t soa_log[];
1711
1712 int sip_init(void)
1713 {
1714         int i;
1715
1716         /* init SOFIA lib */
1717         su_init();
1718         su_home_init(sip_home);
1719
1720         if (options.deb & DEBUG_SIP) {
1721                 su_log_set_level(su_log_default, 9);
1722                 su_log_set_level(nua_log, 9);
1723                 //su_log_set_level(soa_log, 9);
1724         }
1725
1726         for (i = 0; i < 256; i++)
1727                 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);
1728
1729         PDEBUG(DEBUG_SIP, "SIP globals initialized\n");
1730
1731         return 0;
1732 }
1733
1734 void sip_exit(void)
1735 {
1736         su_home_deinit(sip_home);
1737         su_deinit();
1738
1739         PDEBUG(DEBUG_SIP, "SIP globals de-initialized\n");
1740 }
1741
1742 void sip_handle(void)
1743 {
1744         struct interface *interface = interface_first;
1745         struct sip_inst *inst;
1746
1747         while (interface) {
1748                 if (interface->sip_inst) {
1749                         inst = (struct sip_inst *) interface->sip_inst;
1750                         su_root_step(inst->root, 0);
1751                 }
1752                 interface = interface->next;
1753         }
1754 }
1755
1756 /* deletes when back in event loop */
1757 static int delete_event(struct lcr_work *work, void *instance, int index)
1758 {
1759         class Psip *psip = (class Psip *)instance;
1760
1761         delete psip;
1762
1763         return 0;
1764 }
1765