385c483892ecb1e510e7cb92879937a3fbfed067
[asterisk/asterisk.git] / channels / chan_sip.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Implementation of Session Initiation Protocol
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <ctype.h>
16 #include <pthread.h>
17 #include <string.h>
18 #include <asterisk/lock.h>
19 #include <asterisk/channel.h>
20 #include <asterisk/channel_pvt.h>
21 #include <asterisk/config.h>
22 #include <asterisk/logger.h>
23 #include <asterisk/module.h>
24 #include <asterisk/pbx.h>
25 #include <asterisk/options.h>
26 #include <asterisk/lock.h>
27 #include <asterisk/sched.h>
28 #include <asterisk/io.h>
29 #include <asterisk/rtp.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/callerid.h>
32 #include <asterisk/cli.h>
33 #include <asterisk/md5.h>
34 #include <asterisk/app.h>
35 #include <asterisk/musiconhold.h>
36 #include <asterisk/dsp.h>
37 #include <sys/socket.h>
38 #include <sys/ioctl.h>
39 #include <net/if.h>
40 #include <errno.h>
41 #include <unistd.h>
42 #include <stdlib.h>
43 #include <fcntl.h>
44 #include <netdb.h>
45 #include <arpa/inet.h>
46 #include <sys/signal.h>
47 #include <netinet/ip.h>
48
49 /* #define VOCAL_DATA_HACK */
50
51 #define SIPDUMPER
52 #define DEFAULT_DEFAULT_EXPIREY 120
53 #define DEFAULT_MAX_EXPIREY     3600
54
55 #define SIP_DTMF_RFC2833        (1 << 0)
56 #define SIP_DTMF_INBAND         (1 << 1)
57 #define SIP_DTMF_INFO           (1 << 2)
58
59 static int max_expirey = DEFAULT_MAX_EXPIREY;
60 static int default_expirey = DEFAULT_DEFAULT_EXPIREY;
61
62 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
63
64 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
65 #define DEFAULT_FREQ_OK         60 * 1000               /* How often to check for the host to be up */
66 #define DEFAULT_FREQ_NOTOK      10 * 1000               /* How often to check, if the host is down... */
67
68 static char *desc = "Session Initiation Protocol (SIP)";
69 static char *type = "sip";
70 static char *tdesc = "Session Initiation Protocol (SIP)";
71 static char *config = "sip.conf";
72
73 #define DEFAULT_SIP_PORT        5060    /* From RFC 2543 */
74 #define SIP_MAX_PACKET  1500            /* Also from RFC 2543, should sub headers tho */
75
76 static char context[AST_MAX_EXTENSION] = "default";
77
78 static char language[MAX_LANGUAGE] = "";
79
80 static int usecnt =0;
81 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
82
83 /* Protect the interface list (of sip_pvt's) */
84 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
85
86 /* Protect the monitoring thread, so only one process can kill or start it, and not
87    when it's doing something critical. */
88 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
89
90 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
91
92 /* This is the thread for the monitor which checks for input on the channels
93    which are not currently in use.  */
94 static pthread_t monitor_thread = 0;
95
96 static int restart_monitor(void);
97
98 /* Codecs that we support by default: */
99 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM;
100 static int nonCodecCapability = AST_RTP_DTMF;
101
102 static char ourhost[256];
103 static struct in_addr __ourip;
104 static int ourport;
105
106 static int sipdebug = 0;
107
108 static int tos = 0;
109
110 static int globaldtmfmode = SIP_DTMF_RFC2833;
111
112 /* Expire slowly */
113 static int expirey = 900;
114
115 static struct sched_context *sched;
116 static struct io_context *io;
117 /* The private structures of the  sip channels are linked for
118    selecting outgoing channels */
119    
120 #define SIP_MAX_HEADERS         64
121 #define SIP_MAX_LINES           64
122
123 static struct sip_codec_pref {
124         int codec;
125         struct sip_codec_pref *next;
126 } *prefs;
127
128 struct sip_request {
129   char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
130   char *rlPart2; /* The Request URI or Response Status */
131         int len;
132         int headers;                                    /* SIP Headers */
133         char *header[SIP_MAX_HEADERS];
134         int lines;                                              /* SDP Content */
135         char *line[SIP_MAX_LINES];
136         char data[SIP_MAX_PACKET];
137 };
138
139 static struct sip_pvt {
140         pthread_mutex_t lock;                           /* Channel private lock */
141         char callid[80];                                        /* Global CallID */
142         char randdata[80];      /* Random data */
143         unsigned int ocseq;                                     /* Current outgoing seqno */
144         unsigned int icseq;                                     /* Current incoming seqno */
145         int lastinvite;                                         /* Last Cseq of invite */
146         int alreadygone;                                        /* Whether or not we've already been destroyed by or peer */
147         int needdestroy;                                        /* if we need to be destroyed */
148         int capability;                                         /* Special capability */
149         int nonCodecCapability;
150         int outgoing;                                           /* Outgoing or incoming call? */
151         int insecure;                                           /* Don't check source port/ip */
152         int expirey;                                            /* How long we take to expire */
153         int branch;                                                     /* One random number */
154         int canreinvite;                                        /* Do we support reinvite */
155         int progress;                                           /* Have sent 183 message progress */
156         int tag;                                                        /* Another random number */
157         int nat;                                                        /* Whether to try to support NAT */
158         struct sockaddr_in sa;                          /* Our peer */
159         struct sockaddr_in recv;                        /* Received as */
160         struct in_addr ourip;                           /* Our IP */
161         struct ast_channel *owner;                      /* Who owns us */
162         char exten[AST_MAX_EXTENSION];          /* Extention where to start */
163         char refer_to[AST_MAX_EXTENSION];       /* Place to store REFER-TO extension */
164         char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
165         char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
166         struct sip_pvt *refer_call;                     /* Call we are referring */
167         char record_route[256];
168         char record_route_info[256];
169         char remote_party_id[256];
170         char context[AST_MAX_EXTENSION];
171         char language[MAX_LANGUAGE];
172         char theirtag[256];                             /* Their tag */
173         char username[81];
174         char peername[81];
175         char peersecret[81];
176         char callerid[256];                                     /* Caller*ID */
177         char via[256];
178         char accountcode[256];                          /* Account code */
179         int amaflags;                                           /* AMA Flags */
180         struct sip_request initreq;                     /* Initial request */
181         
182         int maxtime;                                            /* Max time for first response */
183         int initid;                                                     /* Auto-congest ID if appropriate */
184
185         int dtmfmode;
186         struct ast_dsp *vad;
187         
188         struct sip_peer *peerpoke;                      /* If this calls is to poke a peer, which one */
189         struct sip_registry *registry;                  /* If this is a REGISTER call, to which registry */
190         struct ast_rtp *rtp;                            /* RTP Session */
191         struct sip_pvt *next;
192 } *iflist = NULL;
193
194 static struct sip_pkt {
195         int retrans;
196         struct sip_pvt *owner;
197         int packetlen;
198         char data[SIP_MAX_PACKET];
199         struct sip_pkt *next;
200 } *packets = NULL;      
201
202 struct sip_user {
203         /* Users who can access various contexts */
204         char name[80];
205         char secret[80];
206         char context[80];
207         char callerid[80];
208         char methods[80];
209         char accountcode[80];
210         int nat;
211         int hascallerid;
212         int amaflags;
213         int insecure;
214         int canreinvite;
215         int dtmfmode;
216         struct ast_ha *ha;
217         struct sip_user *next;
218 };
219
220 struct sip_peer {
221         char name[80];
222         char secret[80];
223         char context[80];               /* JK02: peers need context too to allow parking etc */
224         char methods[80];
225         char username[80];
226         char mailbox[AST_MAX_EXTENSION];
227         int lastmsgssent;
228         time_t  lastmsgcheck;
229         int dynamic;
230         int expire;
231         int expirey;
232         int capability;
233         int nonCodecCapability;
234         int insecure;
235         int nat;
236         int canreinvite;
237         int dtmfmode;
238         struct sockaddr_in addr;
239         struct in_addr mask;
240
241         /* Qualification */
242         struct sip_pvt *call;           /* Call pointer */
243         int pokeexpire;                         /* When to expire poke */
244         int lastms;                                     /* How long last response took (in ms), or -1 for no response */
245         int maxms;                                      /* Max ms we will accept for the host to be up, 0 to not monitor */
246         struct timeval ps;                      /* Ping send time */
247         
248         struct sockaddr_in defaddr;
249         struct ast_ha *ha;
250         int delme;
251         int lastmsg;
252         struct sip_peer *next;
253 };
254
255 static struct ast_user_list {
256         struct sip_user *users;
257         pthread_mutex_t lock;
258 } userl = { NULL, AST_MUTEX_INITIALIZER };
259
260 static struct ast_peer_list {
261         struct sip_peer *peers;
262         pthread_mutex_t lock;
263 } peerl = { NULL, AST_MUTEX_INITIALIZER };
264
265
266 #define REG_STATE_UNREGISTERED 0
267 #define REG_STATE_REGSENT          1
268 #define REG_STATE_AUTHSENT         2
269 #define REG_STATE_REGISTERED   3
270 #define REG_STATE_REJECTED         4
271 #define REG_STATE_TIMEOUT          5
272 #define REG_STATE_NOAUTH           6
273
274 struct sip_registry {
275         pthread_mutex_t lock;                           /* Channel private lock */
276         struct sockaddr_in addr;                /* Who we connect to for registration purposes */
277         char username[80];
278         char secret[80];                        /* Password or key name in []'s */
279         char contact[80];                       /* Contact extension */
280         char random[80];
281         int expire;                                     /* Sched ID of expiration */
282         int timeout;                                    /* sched id of sip_reg_timeout */
283         int refresh;                                    /* How often to refresh */
284         struct sip_pvt *call;                           /* create a sip_pvt structure for each outbound "registration call" in progress */
285         int regstate;
286         int callid_valid;               /* 0 means we haven't chosen callid for this registry yet. */
287         char callid[80];                /* Global CallID for this registry */
288         struct sockaddr_in us;                  /* Who the server thinks we are */
289         struct sip_registry *next;
290 };
291
292 static int sip_do_register(struct sip_registry *r);
293 struct sip_registry *registrations;
294
295 static int sipsock  = -1;
296 static int globalnat = 0;
297
298 static struct sockaddr_in bindaddr;
299
300 static struct ast_frame  *sip_read(struct ast_channel *ast);
301 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
302 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req);
303 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand);
304 static int transmit_request(struct sip_pvt *p, char *msg, int inc);
305 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url);
306 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp);
307 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
308 static int transmit_message_with_text(struct sip_pvt *p, char *text);
309 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
310
311 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
312 {
313         int res;
314         if (p->nat)
315             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
316         else
317             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
318         if (res != len) {
319                 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, inet_ntoa(p->sa.sin_addr), res, strerror(errno));
320         }
321         return res;
322 }
323
324 static int send_response(struct sip_pvt *p, struct sip_request *req)
325 {
326         int res;
327         if (sipdebug) {
328                 if (p->nat)
329                         ast_verbose("Transmitting (NAT):\n%s\n to %s:%d\n", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
330                 else
331                         ast_verbose("Transmitting (no NAT):\n%s\n to %s:%d\n", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
332         }
333         res = __sip_xmit(p, req->data, req->len);
334         if (res > 0)
335                 res = 0;
336         return res;
337 }
338
339 static int send_request(struct sip_pvt *p, struct sip_request *req)
340 {
341         int res;
342         if (sipdebug) {
343                 if (p->nat)
344                         ast_verbose("XXX Need to handle Retransmitting XXX:\n%s (NAT) to %s:%d\n", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
345                 else
346                         ast_verbose("XXX Need to handle Retransmitting XXX:\n%s (no NAT) to %s:%d\n", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
347         }
348         res = __sip_xmit(p, req->data, req->len);
349         return res;
350 }
351
352 static char *ditch_braces(char *tmp)
353 {
354         char *c = tmp;
355         char *n;
356         c = tmp;
357         if ((n = strchr(tmp, '<')) ) {
358                 c = n + 1;
359                 while(*c && *c != '>') c++;
360                 if (*c != '>') {
361                         ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
362                 } else {
363                         *c = '\0';
364                 }
365                 return n+1;
366         }
367         return c;
368 }
369
370 static int sip_sendtext(struct ast_channel *ast, char *text)
371 {
372         struct sip_pvt *p = ast->pvt->pvt;
373         if (sipdebug) 
374                 ast_verbose("Sending text %s on %s\n", text, ast->name);
375         if (!p)
376                 return -1;
377         if (!text || !strlen(text))
378                 return 0;
379         if (sipdebug)
380                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
381         transmit_message_with_text(p, text);
382         return 0;       
383 }
384
385 static int create_addr(struct sip_pvt *r, char *peer)
386 {
387         struct hostent *hp;
388         struct sip_peer *p;
389         int found=0;
390         r->sa.sin_family = AF_INET;
391         ast_pthread_mutex_lock(&peerl.lock);
392         p = peerl.peers;
393         while(p) {
394                 if (!strcasecmp(p->name, peer)) {
395                         found++;
396                         r->capability = p->capability;
397                         r->nonCodecCapability = p->nonCodecCapability;
398                         r->nat = p->nat;
399                         if (r->rtp) {
400                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
401                                 ast_rtp_setnat(r->rtp, r->nat);
402                         }
403                         strncpy(r->peername, p->username, sizeof(r->peername)-1);
404                         strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
405                         strncpy(r->username, p->username, sizeof(r->username)-1);
406                         r->insecure = p->insecure;
407                         r->canreinvite = p->canreinvite;
408                         r->maxtime = p->maxms;
409                         if (p->dtmfmode)
410                                 r->dtmfmode = p->dtmfmode;
411                         strncpy(r->context, p->context,sizeof(r->context)-1);
412                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
413                                 (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
414                                 if (p->addr.sin_addr.s_addr) {
415                                         r->sa.sin_addr = p->addr.sin_addr;
416                                         r->sa.sin_port = p->addr.sin_port;
417                                 } else {
418                                         r->sa.sin_addr = p->defaddr.sin_addr;
419                                         r->sa.sin_port = p->defaddr.sin_port;
420                                 }
421                                 memcpy(&r->recv, &r->sa, sizeof(r->recv));
422                                 break;
423                         }
424                 }
425                 p = p->next;
426         }
427         ast_pthread_mutex_unlock(&peerl.lock);
428         if (!p && !found) {
429                 hp = gethostbyname(peer);
430                 if (hp) {
431                         memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
432                         r->sa.sin_port = htons(DEFAULT_SIP_PORT);
433                         memcpy(&r->recv, &r->sa, sizeof(r->recv));
434                         return 0;
435                 } else {
436                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
437                         return -1;
438                 }
439         } else if (!p)
440                 return -1;
441         else
442                 return 0;
443 }
444
445 static int auto_congest(void *nothing)
446 {
447         struct sip_pvt *p = nothing;
448         ast_pthread_mutex_lock(&p->lock);
449         p->initid = -1;
450         if (p->owner) {
451                 if (!pthread_mutex_trylock(&p->owner->lock)) {
452                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
453                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
454                         ast_pthread_mutex_unlock(&p->owner->lock);
455                 }
456         }
457         ast_pthread_mutex_unlock(&p->lock);
458         return 0;
459 }
460
461 static void sip_prefs_free(void)
462 {
463         struct sip_codec_pref *cur, *next;
464         cur = prefs;
465         while(cur) {
466                 next = cur->next;
467                 free(cur);
468                 cur = next;
469         }
470         prefs = NULL;
471 }
472
473 static void sip_pref_remove(int format)
474 {
475         struct sip_codec_pref *cur, *prev;
476         cur = prefs;
477         while(cur) {
478                 if (cur->codec == format) {
479                         if (prev)
480                                 prev->next = cur->next;
481                         else
482                                 prefs = cur->next;
483                         free(cur);
484                         return;
485                 }
486                 prev = cur;
487                 cur = cur->next;
488         }
489 }
490
491 static int sip_pref_append(int format)
492 {
493         struct sip_codec_pref *cur, *tmp;
494         sip_pref_remove(format);
495         tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
496         if (!tmp)
497                 return -1;
498         memset(tmp, 0, sizeof(struct sip_codec_pref));
499         tmp->codec = format;
500         if (prefs) {
501                 cur = prefs;
502                 while(cur->next)
503                         cur = cur->next;
504                 cur->next = tmp;
505         } else
506                 prefs = tmp;
507         return 0;
508 }
509
510 static int sip_codec_choose(int formats)
511 {
512         struct sip_codec_pref *cur;
513         cur = prefs;
514         while(cur) {
515                 if (formats & cur->codec)
516                         return cur->codec;
517                 cur = cur->next;
518         }
519         return ast_best_codec(formats);
520 }
521
522 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
523 {
524         int res;
525         struct sip_pvt *p;
526         char *vxml_url = NULL;
527         struct varshead *headp;
528         struct ast_var_t *current;
529         
530         p = ast->pvt->pvt;
531         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
532                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
533                 return -1;
534         }
535
536         /* Check whether there is a VXML_URL variable */
537         headp=&ast->varshead;
538         AST_LIST_TRAVERSE(headp,current,entries) {
539                 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
540                 {
541                         vxml_url = ast_var_value(current);
542                         break;
543                 }
544         }
545         
546         res = 0;
547         p->outgoing = 1;
548         transmit_invite(p, "INVITE", 1, NULL, vxml_url);
549         if (p->maxtime) {
550                 /* Initialize auto-congest time */
551                 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
552         }
553         return res;
554 }
555
556 static void __sip_destroy(struct sip_pvt *p, int lockowner)
557 {
558         struct sip_pvt *cur, *prev = NULL;
559         if (p->rtp) {
560                 ast_rtp_destroy(p->rtp);
561         }
562         /* Unlink us from the owner if we have one */
563         if (p->owner) {
564                 if (lockowner)
565                         ast_pthread_mutex_lock(&p->owner->lock);
566                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
567                 p->owner->pvt->pvt = NULL;
568                 if (lockowner)
569                         ast_pthread_mutex_unlock(&p->owner->lock);
570         }
571         cur = iflist;
572         while(cur) {
573                 if (cur == p) {
574                         if (prev)
575                                 prev->next = cur->next;
576                         else
577                                 iflist = cur->next;
578                         break;
579                 }
580                 prev = cur;
581                 cur = cur->next;
582         }
583         if (!cur) {
584                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
585         } else {
586                 if (p->initid > -1)
587                         ast_sched_del(sched, p->initid);
588                 free(p);
589         }
590 }
591 static void sip_destroy(struct sip_pvt *p)
592 {
593         ast_pthread_mutex_lock(&iflock);
594         __sip_destroy(p, 1);
595         ast_pthread_mutex_unlock(&iflock);
596 }
597
598 /* Interface lookup code courtesy Tilghman of DrunkCoder.com.  Thanks! */
599
600 struct my_ifreq {
601     union
602       {
603         char ifrn_name[IFNAMSIZ];       /* Interface name, e.g. "en0".  */
604       } ifr_ifrn;
605
606     union
607       {
608         struct sockaddr_in ifru_addr;
609         char ifru_data[512];
610       } ifr_ifru;
611 };
612
613 struct in_addr *lookup_iface(char *iface) {
614         int mysock;
615         int res;
616         static struct  my_ifreq ifreq;
617         memset(&ifreq, 0, sizeof(ifreq));
618         strncpy(ifreq.ifr_ifrn.ifrn_name,iface,sizeof(ifreq.ifr_ifrn.ifrn_name) - 1);
619
620         mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
621         res = ioctl(mysock,SIOCGIFADDR,&ifreq);
622         
623         close(mysock);
624         if (res < 0) {
625                 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
626                 return &__ourip;
627         }
628         return( (struct in_addr *) &ifreq.ifr_ifru.ifru_addr.sin_addr );
629 }
630
631 static struct in_addr *myaddrfor(struct in_addr *them)
632 {
633         FILE *PROC;
634         struct in_addr *temp = NULL;
635         unsigned int remote_ip;
636         char line[256];
637         remote_ip = them->s_addr;
638         
639         PROC = fopen("/proc/net/route","r");
640         if (!PROC) {
641                 /* If /proc/net/route doesn't exist, fall back to the old method */
642                 return &__ourip;
643         }
644         /* First line contains headers */
645         fgets(line,sizeof(line),PROC);
646
647         while (!feof(PROC)) {
648                 char iface[8];
649                 unsigned int dest, gateway, mask;
650                 int i,aoffset;
651                 char *fields[40];
652
653                 fgets(line,sizeof(line),PROC);
654
655                 aoffset = 0;
656                 for (i=0;i<sizeof(line);i++) {
657                         char *boffset;
658
659                         fields[aoffset++] = line + i;
660                         boffset = strchr(line + i,'\t');
661                         if (boffset == NULL) {
662                                 /* Exit loop */
663                                 break;
664                         } else {
665                                 *boffset = '\0';
666                                 i = boffset - line;
667                         }
668                 }
669
670                 sscanf(fields[0],"%s",iface);
671                 sscanf(fields[1],"%x",&dest);
672                 sscanf(fields[2],"%x",&gateway);
673                 sscanf(fields[7],"%x",&mask);
674 #if 0
675                 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
676 #endif          
677                 if (((remote_ip & mask) ^ dest) == 0) {
678                         if (sipdebug)
679                                 ast_verbose("Interface is %s\n",iface);
680                         temp = lookup_iface(iface);
681                         if (sipdebug)
682                                 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
683                         break;
684                 }
685         }
686         fclose(PROC);
687         if (!temp) {
688                 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s.  Using default\n", inet_ntoa(*them));
689                 temp = &__ourip;
690         }
691         return temp;
692 }
693
694
695 static int sip_hangup(struct ast_channel *ast)
696 {
697         struct sip_pvt *p = ast->pvt->pvt;
698         int needcancel = 0;
699         if (option_debug)
700                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
701         if (!ast->pvt->pvt) {
702                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
703                 return 0;
704         }
705         ast_pthread_mutex_lock(&p->lock);
706         /* Determine how to disconnect */
707         if (p->owner != ast) {
708                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
709                 ast_pthread_mutex_unlock(&p->lock);
710                 return 0;
711         }
712         if (!ast || (ast->_state != AST_STATE_UP))
713                 needcancel = 1;
714         /* Disconnect */
715         p = ast->pvt->pvt;
716         if (p->vad) {
717             ast_dsp_free(p->vad);
718         }
719         p->owner = NULL;
720         ast->pvt->pvt = NULL;
721
722         p->needdestroy = 1;
723 #if 0
724         /* Invert sense of outgoing */
725         p->outgoing = 1 - p->outgoing;
726 #endif  
727         /* Start the process if it's not already started */
728         if (!p->alreadygone && strlen(p->initreq.data)) {
729                 if (needcancel) {
730                         transmit_request(p, "CANCEL", 0);
731                 } else {
732                         /* Send a hangup */
733                         transmit_request(p, "BYE", 1);
734                 }
735         }
736 #if 0
737         /* Restore sense of outgoing */
738         p->outgoing = 1 - p->outgoing;
739 #endif  
740         ast_pthread_mutex_unlock(&p->lock);
741         return 0;
742 }
743
744 static int sip_answer(struct ast_channel *ast)
745 {
746         int res = 0,fmt,capability;
747         char *codec;
748         struct sip_pvt *p = ast->pvt->pvt;
749         struct sip_codec_pref *oldpref=NULL;
750
751         
752         if (ast->_state != AST_STATE_UP) {
753         
754         
755         
756                 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
757                 if (codec) {
758                         ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
759                         fmt=ast_getformatbyname(codec);
760                         if (fmt) {
761                                 oldpref=prefs;
762                                 prefs=NULL;
763                                 sip_pref_append(fmt);
764                                 capability=p->capability;
765                                 p->capability=fmt;
766                         } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
767                 }
768
769                 ast_setstate(ast, AST_STATE_UP);
770                 if (option_debug)
771                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
772                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq);
773                 sip_prefs_free();
774                 if (oldpref) {
775                         prefs=oldpref;
776                         p->capability=capability;
777                 }
778         }
779         return res;
780 }
781
782 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
783 {
784         struct sip_pvt *p = ast->pvt->pvt;
785         int res = 0;
786         if (frame->frametype != AST_FRAME_VOICE) {
787                 if (frame->frametype == AST_FRAME_IMAGE)
788                         return 0;
789                 else {
790                         ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
791                         return 0;
792                 }
793         } else {
794                 if (!(frame->subclass & ast->nativeformats)) {
795                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
796                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
797                         return -1;
798                 }
799         }
800         if (p) {
801                 ast_pthread_mutex_lock(&p->lock);
802                 if (p->rtp) {
803                         if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
804                                 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq);
805                                 p->progress = 1;
806                         }
807                         res =  ast_rtp_write(p->rtp, frame);
808                 }
809                 ast_pthread_mutex_unlock(&p->lock);
810         }
811         return res;
812 }
813
814 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
815 {
816         struct sip_pvt *p = newchan->pvt->pvt;
817         ast_pthread_mutex_lock(&p->lock);
818         if (p->owner != oldchan) {
819                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
820                 ast_pthread_mutex_unlock(&p->lock);
821                 return -1;
822         }
823         p->owner = newchan;
824         ast_pthread_mutex_unlock(&p->lock);
825         return 0;
826 }
827
828 static int sip_senddigit(struct ast_channel *ast, char digit)
829 {
830         struct sip_pvt *p = ast->pvt->pvt;
831         if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
832                 transmit_info_with_digit(p, digit);
833         }
834         if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
835                 ast_rtp_senddigit(p->rtp, digit);
836         }
837         /* If in-band DTMF is desired, send that */
838         if (p->dtmfmode & SIP_DTMF_INBAND)
839                 return -1;
840         return 0;
841 }
842
843 static int sip_indicate(struct ast_channel *ast, int condition)
844 {
845         struct sip_pvt *p = ast->pvt->pvt;
846         switch(condition) {
847         case AST_CONTROL_RINGING:
848                 if (ast->_state == AST_STATE_RING) {
849                         transmit_response(p, "180 Ringing", &p->initreq);
850                         break;
851                 }
852                 return -1;
853         case AST_CONTROL_BUSY:
854                 if (ast->_state != AST_STATE_UP) {
855                         transmit_response(p, "600 Busy everywhere", &p->initreq);
856                         p->alreadygone = 1;
857                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
858                         break;
859                 }
860                 return -1;
861         case AST_CONTROL_CONGESTION:
862                 if (ast->_state != AST_STATE_UP) {
863                         transmit_response(p, "486 Busy here", &p->initreq);
864                         p->alreadygone = 1;
865                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
866                         break;
867                 }
868                 return -1;
869         case -1:
870                 return -1;
871         default:
872                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
873                 return -1;
874         }
875         return 0;
876 }
877
878
879 #if 0
880 static int sip_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
881 {
882         struct sip_pvt *p0, *p1;
883         struct ast_frame *f;
884         struct ast_channel *who, *cs[3];
885         int to;
886
887         /* if need DTMF, cant native bridge */
888         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
889                 return -2;
890         ast_pthread_mutex_lock(&c0->lock);
891         ast_pthread_mutex_lock(&c1->lock);
892         p0 = c0->pvt->pvt;
893         p1 = c1->pvt->pvt;
894         ast_log(LOG_DEBUG, "Reinvite? %s: %s, %s: %s\n", c0->name, p0->canreinvite ? "yes" : "no", c1->name, p1->canreinvite ? "yes" : "no");
895         if (!p0->canreinvite || !p1->canreinvite) {
896                 /* Not gonna support reinvite */
897                 ast_pthread_mutex_unlock(&c0->lock);
898                 ast_pthread_mutex_unlock(&c1->lock);
899                 return -2;
900         }
901         transmit_reinvite_with_sdp(p0, p1->rtp);
902         transmit_reinvite_with_sdp(p1, p0->rtp);
903         ast_pthread_mutex_unlock(&c0->lock);
904         ast_pthread_mutex_unlock(&c1->lock);
905         cs[0] = c0;
906         cs[1] = c1;
907         cs[2] = NULL;
908         for (;;) {
909                 if ((c0->pvt->pvt != p0)  ||
910                         (c1->pvt->pvt != p1) ||
911                         (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
912                                 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
913                                 if (c0->pvt->pvt == p0)
914                                         transmit_reinvite_with_sdp(p0, NULL);
915                                 if (c1->pvt->pvt == p1)
916                                         transmit_reinvite_with_sdp(p1, NULL);
917                                 /* Tell it to try again later */
918                                 return -3;
919                 }
920                 to = -1;
921                 who = ast_waitfor_n(cs, 2, &to);
922                 if (!who) {
923                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
924                         continue;
925                 }
926                 f = ast_read(who);
927                 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
928                                    (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
929                                ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
930                         *fo = f;
931                         *rc = who;
932                         ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
933                         if (c0->pvt->pvt == p0 && !c0->_softhangup)
934                                 transmit_reinvite_with_sdp(p0, NULL);
935                         if (c1->pvt->pvt == p1 && !c1->_softhangup)
936                                 transmit_reinvite_with_sdp(p1, NULL);
937                         /* That's all we needed */
938                         return 0;
939                 } else 
940                         ast_frfree(f);
941                 /* Swap priority not that it's a big deal at this point */
942                 cs[2] = cs[0];
943                 cs[0] = cs[1];
944                 cs[1] = cs[2];
945                 
946         }
947         return -1;
948 }
949 #endif
950
951 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
952 {
953         struct ast_channel *tmp;
954         int fmt;
955         tmp = ast_channel_alloc(1);
956         if (tmp) {
957                 /* Select our native format based on codec preference until we receive
958                    something from another device to the contrary. */
959                 if (i->capability)
960                         tmp->nativeformats = sip_codec_choose(i->capability);
961                 else 
962                         tmp->nativeformats = sip_codec_choose(capability);
963                 fmt = ast_best_codec(tmp->nativeformats);
964                 if (title)
965                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
966                 else
967                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
968                 tmp->type = type;
969                 if (i->dtmfmode & SIP_DTMF_INBAND) {
970                     i->vad = ast_dsp_new();
971                     ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
972                 }
973                 tmp->fds[0] = ast_rtp_fd(i->rtp);
974                 ast_setstate(tmp, state);
975                 if (state == AST_STATE_RING)
976                         tmp->rings = 1;
977                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
978                 tmp->writeformat = fmt;
979                 tmp->pvt->rawwriteformat = fmt;
980                 tmp->readformat = fmt;
981                 tmp->pvt->rawreadformat = fmt;
982                 tmp->pvt->pvt = i;
983                 tmp->pvt->send_text = sip_sendtext;
984                 tmp->pvt->call = sip_call;
985                 tmp->pvt->hangup = sip_hangup;
986                 tmp->pvt->answer = sip_answer;
987                 tmp->pvt->read = sip_read;
988                 tmp->pvt->write = sip_write;
989                 tmp->pvt->indicate = sip_indicate;
990                 tmp->pvt->fixup = sip_fixup;
991                 tmp->pvt->send_digit = sip_senddigit;
992                 tmp->pvt->bridge = ast_rtp_bridge;
993                 if (strlen(i->language))
994                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
995                 i->owner = tmp;
996                 ast_pthread_mutex_lock(&usecnt_lock);
997                 usecnt++;
998                 ast_pthread_mutex_unlock(&usecnt_lock);
999                 ast_update_use_count();
1000                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1001                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1002                 if (strlen(i->callerid))
1003                         tmp->callerid = strdup(i->callerid);
1004                 tmp->priority = 1;
1005                 if (state != AST_STATE_DOWN) {
1006                         if (ast_pbx_start(tmp)) {
1007                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1008                                 ast_hangup(tmp);
1009                                 tmp = NULL;
1010                         }
1011                 }
1012         } else
1013                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1014         return tmp;
1015 }
1016
1017 static struct cfalias {
1018         char *fullname;
1019         char *shortname;
1020 } aliases[] = {
1021         { "Content-Type", "c" },
1022         { "Content-Encoding", "e" },
1023         { "From", "f" },
1024         { "Call-ID", "i" },
1025         { "Contact", "m" },
1026         { "Content-Length", "l" },
1027         { "Subject", "s" },
1028         { "To", "t" },
1029         { "Via", "v" },
1030 };
1031
1032 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1033   if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1034     char* r = line + nameLen + 1;
1035     while (*r && (*r < 33)) ++r;
1036     return r;
1037   }
1038
1039   return "";
1040 }
1041
1042 static char *get_sdp(struct sip_request *req, char *name) {
1043   int x;
1044   int len = strlen(name);
1045   char *r;
1046
1047   for (x=0; x<req->lines; x++) {
1048     r = get_sdp_by_line(req->line[x], name, len);
1049     if (r[0] != '\0') return r;
1050   }
1051   return "";
1052 }
1053
1054 static void sdpLineNum_iterator_init(int* iterator) {
1055   *iterator = 0;
1056 }
1057
1058 static char* get_sdp_iterate(int* iterator,
1059                              struct sip_request *req, char *name) {
1060   int len = strlen(name);
1061   char *r;
1062   while (*iterator < req->lines) {
1063     r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1064     if (r[0] != '\0') return r;
1065   }
1066   return "";
1067 }
1068
1069 static char *__get_header(struct sip_request *req, char *name, int *start)
1070 {
1071         int x;
1072         int len = strlen(name);
1073         char *r;
1074         for (x=*start;x<req->headers;x++) {
1075                 if (!strncasecmp(req->header[x], name, len) && 
1076                                 (req->header[x][len] == ':')) {
1077                                         r = req->header[x] + len + 1;
1078                                         while(*r && (*r < 33))
1079                                                         r++;
1080                                         *start = x+1;
1081                                         return r;
1082                 }
1083         }
1084         /* Try aliases */
1085         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
1086                 if (!strcasecmp(aliases[x].fullname, name))
1087                         return __get_header(req, aliases[x].shortname, start);
1088
1089         /* Don't return NULL, so get_header is always a valid pointer */
1090         return "";
1091 }
1092
1093 static char *get_header(struct sip_request *req, char *name)
1094 {
1095         int start = 0;
1096         return __get_header(req, name, &start);
1097 }
1098
1099 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1100 {
1101         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
1102         struct ast_frame *f;
1103         static struct ast_frame null_frame = { AST_FRAME_NULL, };
1104         f = ast_rtp_read(p->rtp);
1105         /* Don't send RFC2833 if we're not supposed to */
1106         if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1107                 return &null_frame;
1108         if (p->owner) {
1109                 /* We already hold the channel lock */
1110                 if (f->frametype == AST_FRAME_VOICE) {
1111                         if (f->subclass != p->owner->nativeformats) {
1112                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1113                                 p->owner->nativeformats = f->subclass;
1114                                 ast_set_read_format(p->owner, p->owner->readformat);
1115                                 ast_set_write_format(p->owner, p->owner->writeformat);
1116                         }
1117             if (p->dtmfmode & SIP_DTMF_INBAND) {
1118                    f = ast_dsp_process(p->owner,p->vad,f,0);
1119             }
1120                 }
1121         }
1122         return f;
1123 }
1124
1125 static struct ast_frame *sip_read(struct ast_channel *ast)
1126 {
1127         struct ast_frame *fr;
1128         struct sip_pvt *p = ast->pvt->pvt;
1129         ast_pthread_mutex_lock(&p->lock);
1130         fr = sip_rtp_read(p);
1131         ast_pthread_mutex_unlock(&p->lock);
1132         return fr;
1133 }
1134
1135 static void build_callid(char *callid, int len, struct in_addr ourip)
1136 {
1137         int res;
1138         int val;
1139         int x;
1140         for (x=0;x<4;x++) {
1141                 val = rand();
1142                 res = snprintf(callid, len, "%08x", val);
1143                 len -= res;
1144                 callid += res;
1145         }
1146         /* It's not important that we really use our right IP here... */
1147         snprintf(callid, len, "@%s", inet_ntoa(ourip));
1148 }
1149
1150 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1151 {
1152         struct sip_pvt *p;
1153
1154         p = malloc(sizeof(struct sip_pvt));
1155         if (!p)
1156                 return NULL;
1157         /* Keep track of stuff */
1158         memset(p, 0, sizeof(struct sip_pvt));
1159         p->initid = -1;
1160         p->rtp = ast_rtp_new(NULL, NULL);
1161         p->branch = rand();     
1162         p->tag = rand();
1163         /* Start with 101 instead of 1 */
1164         p->ocseq = 101;
1165         if (!p->rtp) {
1166                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1167                 free(p);
1168                 return NULL;
1169         }
1170         ast_rtp_settos(p->rtp, tos);
1171         if (useglobalnat && sin) {
1172                 /* Setup NAT structure according to global settings if we have an address */
1173                 p->nat = globalnat;
1174                 memcpy(&p->recv, sin, sizeof(p->recv));
1175                 ast_rtp_setnat(p->rtp, p->nat);
1176         }
1177         ast_pthread_mutex_init(&p->lock);
1178 #if 0
1179         ast_rtp_set_data(p->rtp, p);
1180         ast_rtp_set_callback(p->rtp, rtpready);
1181 #endif  
1182         if (sin) {
1183                 memcpy(&p->sa, sin, sizeof(p->sa));
1184                 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
1185         } else {
1186                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1187         }
1188         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1189         if (!callid)
1190                 build_callid(p->callid, sizeof(p->callid), p->ourip);
1191         else
1192                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1193         /* Assume reinvite OK */
1194         p->canreinvite = 1;
1195         p->dtmfmode = globaldtmfmode;
1196         /* Add to list */
1197         ast_pthread_mutex_lock(&iflock);
1198         p->next = iflist;
1199         iflist = p;
1200         ast_pthread_mutex_unlock(&iflock);
1201         if (option_debug)
1202                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1203         return p;
1204 }
1205
1206 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1207 {
1208         struct sip_pvt *p;
1209         char *callid;
1210         callid = get_header(req, "Call-ID");
1211         if (!strlen(callid)) {
1212                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1213                 return NULL;
1214         }
1215         ast_pthread_mutex_lock(&iflock);
1216         p = iflist;
1217         while(p) {
1218                 if (!strcmp(p->callid, callid)) {
1219                         /* Found the call */
1220 #if 0
1221                         if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1222                             (p->sa.sin_port != sin->sin_port))) {
1223                                         char orig[80];
1224                                         char new[80];
1225                                         snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1226                                         snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1227                                         ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1228                                         ast_pthread_mutex_unlock(&iflock);
1229                                         return NULL;
1230                         }
1231 #endif
1232                         ast_pthread_mutex_unlock(&iflock);
1233                         return p;
1234                 }
1235                 p = p->next;
1236         }
1237         ast_pthread_mutex_unlock(&iflock);
1238         return sip_alloc(callid, sin, 1);
1239 }
1240
1241 static int sip_register(char *value, int lineno)
1242 {
1243         struct sip_registry *reg;
1244         char copy[256] = "";
1245         char *username, *hostname, *secret;
1246         char *porta;
1247         char *contact;
1248         char *stringp=NULL;
1249         
1250         struct hostent *hp;
1251         if (!value)
1252                 return -1;
1253         strncpy(copy, value, sizeof(copy)-1);
1254         stringp=copy;
1255         username = stringp;
1256         hostname = strrchr(stringp, '@');
1257         if (hostname) {
1258                 *hostname = '\0';
1259                 hostname++;
1260         }
1261         if (!hostname) {
1262                 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1263                 return -1;
1264         }
1265         stringp=username;
1266         username = strsep(&stringp, ":");
1267         secret = strsep(&stringp, ":");
1268         stringp = hostname;
1269         hostname = strsep(&stringp, "/");
1270         contact = strsep(&stringp, "/");
1271         if (!contact || !strlen(contact))
1272                 contact = "s";
1273         stringp=hostname;
1274         hostname = strsep(&stringp, ":");
1275         porta = strsep(&stringp, ":");
1276         
1277         if (porta && !atoi(porta)) {
1278                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1279                 return -1;
1280         }
1281         hp = gethostbyname(hostname);
1282         if (!hp) {
1283                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1284                 return -1;
1285         }
1286         reg = malloc(sizeof(struct sip_registry));
1287         if (reg) {
1288                 memset(reg, 0, sizeof(struct sip_registry));
1289                 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1290                 strncpy(reg->username, username, sizeof(reg->username)-1);
1291                 if (secret)
1292                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1293                 reg->expire = -1;
1294                 reg->refresh = default_expirey;
1295                 reg->addr.sin_family = AF_INET;
1296                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
1297                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1298                 reg->next = registrations;
1299                 reg->callid_valid = 0;
1300                 registrations = reg;
1301         } else {
1302                 ast_log(LOG_ERROR, "Out of memory\n");
1303                 return -1;
1304         }
1305         return 0;
1306 }
1307
1308 static void parse(struct sip_request *req)
1309 {
1310         /* Divide fields by NULL's */
1311         char *c;
1312         int f = 0;
1313         c = req->data;
1314
1315         /* First header starts immediately */
1316         req->header[f] = c;
1317         while(*c) {
1318                 if (*c == '\n') {
1319                         /* We've got a new header */
1320                         *c = 0;
1321
1322 #if 0
1323                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1324 #endif                  
1325                         if (!strlen(req->header[f])) {
1326                                 /* Line by itself means we're now in content */
1327                                 c++;
1328                                 break;
1329                         }
1330                         if (f >= SIP_MAX_HEADERS - 1) {
1331                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1332                         } else
1333                                 f++;
1334                         req->header[f] = c + 1;
1335                 } else if (*c == '\r') {
1336                         /* Ignore but eliminate \r's */
1337                         *c = 0;
1338                 }
1339                 c++;
1340         }
1341         /* Check for last header */
1342         if (strlen(req->header[f])) 
1343                 f++;
1344         req->headers = f;
1345         /* Now we process any mime content */
1346         f = 0;
1347         req->line[f] = c;
1348         while(*c) {
1349                 if (*c == '\n') {
1350                         /* We've got a new line */
1351                         *c = 0;
1352 #if 0
1353                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1354 #endif                  
1355                         if (f >= SIP_MAX_LINES - 1) {
1356                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1357                         } else
1358                                 f++;
1359                         req->line[f] = c + 1;
1360                 } else if (*c == '\r') {
1361                         /* Ignore and eliminate \r's */
1362                         *c = 0;
1363                 }
1364                 c++;
1365         }
1366         /* Check for last line */
1367         if (strlen(req->line[f])) 
1368                 f++;
1369         req->lines = f;
1370         if (sipdebug)
1371                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1372         if (*c) 
1373                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1374 }
1375
1376 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1377 {
1378         char *m;
1379         char *c;
1380         char *a;
1381         char host[258];
1382         int len = -1;
1383         int portno;
1384         int peercapability, peerNonCodecCapability;
1385         struct sockaddr_in sin;
1386         char *codecs;
1387         struct hostent *hp;
1388         int codec;
1389         int iterator;
1390
1391         /* Get codec and RTP info from SDP */
1392         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1393                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1394                 return -1;
1395         }
1396         m = get_sdp(req, "m");
1397         c = get_sdp(req, "c");
1398         if (!strlen(m) || !strlen(c)) {
1399                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1400                 return -1;
1401         }
1402         if (sscanf(c, "IN IP4 %256s", host) != 1) {
1403                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1404                 return -1;
1405         }
1406         /* XXX This could block for a long time, and block the main thread! XXX */
1407         hp = gethostbyname(host);
1408         if (!hp) {
1409                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1410                 return -1;
1411         }
1412         if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1413                 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
1414                 return -1;
1415         }
1416         sin.sin_family = AF_INET;
1417         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1418         sin.sin_port = htons(portno);
1419         if (p->rtp)
1420                 ast_rtp_set_peer(p->rtp, &sin);
1421 #if 0
1422         printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1423 #endif  
1424         // Scan through the RTP payload types specified in a "m=" line:
1425         ast_rtp_pt_clear(p->rtp);
1426         codecs = m + len;
1427         while(strlen(codecs)) {
1428                 if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
1429                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1430                         return -1;
1431                 }
1432                 ast_rtp_set_m_type(p->rtp, codec);
1433                 codecs += len;
1434         }
1435
1436         // Next, scan through each "a=rtpmap:" line, noting each
1437         // specified RTP payload type (with corresponding MIME subtype):
1438         sdpLineNum_iterator_init(&iterator);
1439         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1440           char* mimeSubtype = strdup(a); // ensures we have enough space
1441           if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1442           // Note: should really look at the 'freq' and '#chans' params too
1443           ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1444           free(mimeSubtype);
1445         }
1446
1447         // Now gather all of the codecs that were asked for:
1448         ast_rtp_get_current_formats(p->rtp,
1449                                 &peercapability, &peerNonCodecCapability);
1450         p->capability = capability & peercapability;
1451         p->nonCodecCapability = nonCodecCapability & peerNonCodecCapability;
1452         if (sipdebug) {
1453                 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1454                             capability, peercapability, p->capability);
1455                 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1456                             nonCodecCapability, peerNonCodecCapability,
1457                             p->nonCodecCapability);
1458         }
1459         if (!p->capability) {
1460                 ast_log(LOG_WARNING, "No compatible codecs!\n");
1461                 return -1;
1462         }
1463         if (p->owner) {
1464                 if (!(p->owner->nativeformats & p->capability)) {
1465                         ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %d and not %d\n", p->capability, p->owner->nativeformats);
1466                         p->owner->nativeformats = sip_codec_choose(p->capability);
1467                         ast_set_read_format(p->owner, p->owner->readformat);
1468                         ast_set_write_format(p->owner, p->owner->writeformat);
1469                 }
1470                 if (p->owner->bridge) {
1471                         /* Turn on/off music on hold if we are holding/unholding */
1472                         if (sin.sin_addr.s_addr) {
1473                                 ast_moh_stop(p->owner->bridge);
1474                         } else {
1475                                 ast_moh_start(p->owner->bridge, NULL);
1476                         }
1477                 }
1478         }
1479         return 0;
1480         
1481 }
1482
1483 static int add_header(struct sip_request *req, char *var, char *value)
1484 {
1485         if (req->len >= sizeof(req->data) - 4) {
1486                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1487                 return -1;
1488         }
1489         if (req->lines) {
1490                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1491                 return -1;
1492         }
1493         req->header[req->headers] = req->data + req->len;
1494         snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1495         req->len += strlen(req->header[req->headers]);
1496         if (req->headers < SIP_MAX_HEADERS)
1497                 req->headers++;
1498         else {
1499                 ast_log(LOG_WARNING, "Out of header space\n");
1500                 return -1;
1501         }
1502         return 0;       
1503 }
1504
1505 static int add_blank_header(struct sip_request *req)
1506 {
1507         if (req->len >= sizeof(req->data) - 4) {
1508                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1509                 return -1;
1510         }
1511         if (req->lines) {
1512                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1513                 return -1;
1514         }
1515         req->header[req->headers] = req->data + req->len;
1516         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1517         req->len += strlen(req->header[req->headers]);
1518         if (req->headers < SIP_MAX_HEADERS)
1519                 req->headers++;
1520         else {
1521                 ast_log(LOG_WARNING, "Out of header space\n");
1522                 return -1;
1523         }
1524         return 0;       
1525 }
1526
1527 static int add_line(struct sip_request *req, char *line)
1528 {
1529         if (req->len >= sizeof(req->data) - 4) {
1530                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1531                 return -1;
1532         }
1533         if (!req->lines) {
1534                 /* Add extra empty return */
1535                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1536                 req->len += strlen(req->data + req->len);
1537         }
1538         req->line[req->lines] = req->data + req->len;
1539         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1540         req->len += strlen(req->line[req->lines]);
1541         if (req->lines < SIP_MAX_LINES)
1542                 req->lines++;
1543         else {
1544                 ast_log(LOG_WARNING, "Out of line space\n");
1545                 return -1;
1546         }
1547         return 0;       
1548 }
1549
1550 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1551 {
1552         char *tmp;
1553         tmp = get_header(orig, field);
1554         if (strlen(tmp)) {
1555                 /* Add what we're responding to */
1556                 return add_header(req, field, tmp);
1557         }
1558         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1559         return -1;
1560 }
1561
1562 #if 0
1563 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1564 {
1565         char *tmp;
1566         int start = 0;
1567         int copied = 0;
1568         for (;;) {
1569                 tmp = __get_header(orig, field, &start);
1570                 if (strlen(tmp)) {
1571                         /* Add what we're responding to */
1572                         add_header(req, field, tmp);
1573                         copied++;
1574                 } else
1575                         break;
1576         }
1577         if (!copied) {
1578                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1579                 return -1;
1580         }
1581         return 0;
1582 }
1583 #endif
1584 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1585 {
1586         char *tmp;
1587         int start = 0;
1588         int copied = 0;
1589         char new[256];
1590         for (;;) {
1591                 tmp = __get_header(orig, field, &start);
1592                 if (strlen(tmp)) {
1593                         if (!copied && p->nat) {
1594                                 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1595                                         snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1596                                 else
1597                                         snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1598                                 add_header(req, field, new);
1599                         } else {
1600                                 /* Add what we're responding to */
1601                                 add_header(req, field, tmp);
1602                         }
1603                         copied++;
1604                 } else
1605                         break;
1606         }
1607         if (!copied) {
1608                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1609                 return -1;
1610         }
1611         return 0;
1612 }
1613
1614 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1615 {
1616         /* Initialize a response */
1617         if (req->headers || req->len) {
1618                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1619                 return -1;
1620         }
1621         req->header[req->headers] = req->data + req->len;
1622         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1623         req->len += strlen(req->header[req->headers]);
1624         if (req->headers < SIP_MAX_HEADERS)
1625                 req->headers++;
1626         else
1627                 ast_log(LOG_WARNING, "Out of header space\n");
1628         return 0;
1629 }
1630
1631 static int init_req(struct sip_request *req, char *resp, char *recip)
1632 {
1633         /* Initialize a response */
1634         if (req->headers || req->len) {
1635                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1636                 return -1;
1637         }
1638         req->header[req->headers] = req->data + req->len;
1639         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1640         req->len += strlen(req->header[req->headers]);
1641         if (req->headers < SIP_MAX_HEADERS)
1642                 req->headers++;
1643         else
1644                 ast_log(LOG_WARNING, "Out of header space\n");
1645         return 0;
1646 }
1647
1648 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1649 {
1650         char newto[256] = "", *ot;
1651         memset(resp, 0, sizeof(*resp));
1652         init_resp(resp, msg, req);
1653         copy_via_headers(p, resp, req, "Via");
1654         copy_header(resp, req, "From");
1655         ot = get_header(req, "To");
1656         if (!strstr(ot, "tag=")) {
1657                 /* Add the proper tag if we don't have it already.  If they have specified
1658                    their tag, use it.  Otherwise, use our own tag */
1659                 if (strlen(p->theirtag))
1660                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1661                 else if (p->tag)
1662                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1663                 else
1664                         strncpy(newto, ot, sizeof(newto) - 1);
1665                 ot = newto;
1666         }
1667         add_header(resp, "To", ot);
1668         copy_header(resp, req, "Call-ID");
1669         copy_header(resp, req, "CSeq");
1670         add_header(resp, "User-Agent", "Asterisk PBX");
1671         if (p->expirey) {
1672                 /* For registration responses, we also need expirey and
1673                    contact info */
1674                 char tmp[80];
1675                 char contact2[256] = "", *c, contact[256];
1676                 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1677                 strncpy(contact2, get_header(req, "Contact"), sizeof(contact2)-1);
1678                 c = ditch_braces(contact2);
1679                 snprintf(contact, sizeof(contact), "<%s>", c);
1680                 add_header(resp, "Expires", tmp);
1681                 add_header(resp, "Contact", contact);
1682         } else {
1683                 char contact2[256] = "", *c, contact[256];
1684                 /* XXX This isn't exactly right and it's implemented
1685                        very stupidly *sigh* XXX */
1686                 strncpy(contact2, get_header(req, "To"), sizeof(contact2)-1);
1687                 c = ditch_braces(contact2);
1688                 snprintf(contact, sizeof(contact), "<%s>", c);
1689                 add_header(resp, "Contact", contact);
1690         }
1691         return 0;
1692 }
1693
1694 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
1695 {
1696         struct sip_request *orig = &p->initreq;
1697         char stripped[80] ="";
1698         char tmp[80];
1699         char newto[256];
1700         char *c, *n;
1701         char *ot, *of;
1702
1703         memset(req, 0, sizeof(struct sip_request));
1704         
1705         if (inc)
1706                 p->ocseq++;
1707
1708         if (p->outgoing)
1709                 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1710         else
1711                 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1712         
1713         c = strchr(stripped, '<');
1714         if (c) 
1715                 c++;
1716         else
1717                 c = stripped;
1718         n = strchr(c, '>');
1719         if (n)
1720                 *n = '\0';
1721         
1722         init_req(req, msg, c);
1723
1724         snprintf(tmp, sizeof(tmp), "%d %s", p->ocseq, msg);
1725
1726         add_header(req, "Via", p->via);
1727
1728         ot = get_header(orig, "To");
1729         of = get_header(orig, "From");
1730
1731         if (!strstr(ot, "tag=")) {
1732                 /* Add the proper tag if we don't have it already.  If they have specified
1733                    their tag, use it.  Otherwise, use our own tag */
1734                 if (strlen(p->theirtag))
1735                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1736                 else
1737                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1738                 ot = newto;
1739         }
1740
1741         if (p->outgoing) {
1742                 add_header(req, "From", of);
1743                 add_header(req, "To", ot);
1744         } else {
1745                 add_header(req, "From", ot);
1746                 add_header(req, "To", of);
1747         }
1748         copy_header(req, orig, "Call-ID");
1749         add_header(req, "CSeq", tmp);
1750
1751         add_header(req, "User-Agent", "Asterisk PBX");
1752         return 0;
1753 }
1754
1755 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
1756 {
1757         struct sip_request resp;
1758         respprep(&resp, p, msg, req);
1759         add_header(&resp, "Content-Length", "0");
1760         add_blank_header(&resp);
1761         return send_response(p, &resp);
1762 }
1763
1764 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
1765 {
1766         struct sip_request resp;
1767         respprep(&resp, p, msg, req);
1768         add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
1769         add_header(&resp, "Accept", "application/sdp");
1770         add_header(&resp, "Content-Length", "0");
1771         add_blank_header(&resp);
1772         return send_response(p, &resp);
1773 }
1774
1775 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata)
1776 {
1777         struct sip_request resp;
1778         char tmp[256];
1779         snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
1780         respprep(&resp, p, msg, req);
1781         add_header(&resp, "Proxy-Authenticate", tmp);
1782         add_header(&resp, "Content-Length", "0");
1783         add_blank_header(&resp);
1784         return send_response(p, &resp);
1785 }
1786
1787 static int add_text(struct sip_request *req, char *text)
1788 {
1789         /* XXX Convert \n's to \r\n's XXX */
1790         int len = strlen(text);
1791         char clen[256];
1792         snprintf(clen, sizeof(clen), "%d", len);
1793         add_header(req, "Content-Type", "text/plain");
1794         add_header(req, "Content-Length", clen);
1795         add_line(req, text);
1796         return 0;
1797 }
1798
1799 static int add_digit(struct sip_request *req, char digit)
1800 {
1801         char tmp[256];
1802         int len;
1803         char clen[256];
1804         snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
1805         len = strlen(tmp);
1806         snprintf(clen, sizeof(clen), "%d", len);
1807         add_header(req, "Content-Type", "application/dtmf-relay");
1808         add_header(req, "Content-Length", clen);
1809         add_line(req, tmp);
1810         return 0;
1811 }
1812
1813 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
1814 {
1815         int len;
1816         int codec;
1817         int alreadysent = 0;
1818         char costr[80];
1819         struct sockaddr_in sin;
1820         struct sip_codec_pref *cur;
1821         char v[256];
1822         char s[256];
1823         char o[256];
1824         char c[256];
1825         char t[256];
1826         char m[256];
1827         char a[1024] = "";
1828         int x;
1829         struct sockaddr_in dest;
1830         /* XXX We break with the "recommendation" and send our IP, in order that our
1831                peer doesn't have to gethostbyname() us XXX */
1832         len = 0;
1833         if (!p->rtp) {
1834                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
1835                 return -1;
1836         }
1837         ast_rtp_get_us(p->rtp, &sin);
1838         if (rtp) {
1839                 ast_rtp_get_peer(rtp, &dest);
1840         } else {
1841                 dest.sin_addr = p->ourip;
1842                 dest.sin_port = sin.sin_port;
1843         }
1844         if (sipdebug)
1845                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
1846         snprintf(v, sizeof(v), "v=0\r\n");
1847         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
1848         snprintf(s, sizeof(s), "s=session\r\n");
1849         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
1850         snprintf(t, sizeof(t), "t=0 0\r\n");
1851         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
1852         /* Start by sending our preferred codecs */
1853         cur = prefs;
1854         while(cur) {
1855                 if (p->capability & cur->codec) {
1856                         if (sipdebug)
1857                                 ast_verbose("Answering with preferred capability %d\n", cur->codec);
1858                         codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
1859                         if (codec > -1) {
1860                                 snprintf(costr, sizeof(costr), " %d", codec);
1861                                 strcat(m, costr);
1862                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
1863                                 strcat(a, costr);
1864                         }
1865                 }
1866                 alreadysent |= cur->codec;
1867                 cur = cur->next;
1868         }
1869         /* Now send any other common codecs, and non-codec formats: */
1870         for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1871                 if ((p->capability & x) && !(alreadysent & x)) {
1872                         if (sipdebug)
1873                                 ast_verbose("Answering with capability %d\n", x);       
1874                         codec = ast_rtp_lookup_code(p->rtp, 1, x);
1875                         if (codec > -1) {
1876                         snprintf(costr, sizeof(costr), " %d", codec);
1877                                 strcat(m, costr);
1878                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
1879                                 strcat(a, costr);
1880                         }
1881                 }
1882         }
1883         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
1884                 if (p->nonCodecCapability & x) {
1885                         if (sipdebug)
1886                                 ast_verbose("Answering with non-codec capability %d\n", x);
1887                         codec = ast_rtp_lookup_code(p->rtp, 0, x);
1888                         if (codec > -1) {
1889                                 snprintf(costr, sizeof(costr), " %d", codec);
1890                                 strcat(m, costr);
1891                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
1892                                 strcat(a, costr);
1893                                 if (x == AST_RTP_DTMF) {
1894                                   /* Indicate we support DTMF...  Not sure about 16, but MSN supports it so dang it, we will too... */
1895                                   snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
1896                                            codec);
1897                                   strcat(a, costr);
1898                                 }
1899                         }
1900                 }
1901         }
1902         strcat(m, "\r\n");
1903         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
1904         snprintf(costr, sizeof(costr), "%d", len);
1905         add_header(resp, "Content-Type", "application/sdp");
1906         add_header(resp, "Content-Length", costr);
1907         add_line(resp, v);
1908         add_line(resp, o);
1909         add_line(resp, s);
1910         add_line(resp, c);
1911         add_line(resp, t);
1912         add_line(resp, m);
1913         add_line(resp, a);
1914         return 0;
1915 }
1916
1917 static void copy_request(struct sip_request *dst,struct sip_request *src)
1918 {
1919         long offset;
1920         int x;
1921         offset = ((void *)dst) - ((void *)src);
1922         /* First copy stuff */
1923         memcpy(dst, src, sizeof(*dst));
1924         /* Now fix pointer arithmetic */
1925         for (x=0;x<src->headers;x++)
1926                 dst->header[x] += offset;
1927         for (x=0;x<src->lines;x++)
1928                 dst->line[x] += offset;
1929 }
1930
1931 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req)
1932 {
1933         struct sip_request resp;
1934         respprep(&resp, p, msg, req);
1935         add_sdp(&resp, p, NULL);
1936         return send_response(p, &resp);
1937 }
1938
1939 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
1940 {
1941         struct sip_request resp;
1942         reqprep(&resp, p, "INVITE", 1);
1943         add_sdp(&resp, p, rtp);
1944         return send_response(p, &resp);
1945 }
1946
1947 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
1948 {
1949         char invite[256];
1950         char from[256];
1951         char to[256];
1952         char tmp[80];
1953         char cid[256];
1954         char *l = "asterisk", *n=NULL;
1955         if (p->owner && p->owner->callerid) {
1956                 strcpy(cid, p->owner->callerid);
1957                 ast_callerid_parse(cid, &n, &l);
1958                 if (l) 
1959                         ast_shrink_phone_number(l);
1960                 if (!l || !ast_isphonenumber(l))
1961                                 l = "asterisk";
1962         }
1963         if (!n)
1964                 n = l;
1965         snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%08x", n, l, inet_ntoa(p->ourip), p->tag);
1966         if (strlen(p->username)) {
1967                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1968                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1969                 } else {
1970                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
1971                 }
1972         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1973                 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1974         } else {
1975                 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
1976         }
1977         /* If there is a VXML URL append it to the SIP URL */
1978         if (vxml_url)
1979         {
1980                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
1981         }
1982         else
1983         {
1984                 snprintf(to, sizeof(to), "<%s>", invite );
1985         }
1986         memset(req, 0, sizeof(struct sip_request));
1987         init_req(req, cmd, invite);
1988         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
1989
1990         add_header(req, "Via", p->via);
1991         add_header(req, "From", from);
1992         {
1993                 char contact2[256] ="", *c, contact[256];
1994                 /* XXX This isn't exactly right and it's implemented
1995                        very stupidly *sigh* XXX */
1996                 strncpy(contact2, from, sizeof(contact2)-1);
1997                 c = ditch_braces(contact2);
1998                 snprintf(contact, sizeof(contact), "<%s>", c);
1999                 add_header(req, "Contact", contact);
2000         }
2001         add_header(req, "To", to);
2002         add_header(req, "Call-ID", p->callid);
2003         add_header(req, "CSeq", tmp);
2004         add_header(req, "User-Agent", "Asterisk PBX");
2005 }
2006
2007 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
2008 {
2009         struct sip_request req;
2010         initreqprep(&req, p, cmd, vxml_url);
2011         if (auth)
2012                 add_header(&req, "Proxy-Authorization", auth);
2013         if (sdp) {
2014                 add_sdp(&req, p, NULL);
2015         } else {
2016                 add_header(&req, "Content-Length", "0");
2017                 add_blank_header(&req);
2018         }
2019         if (!p->initreq.headers) {
2020                 /* Use this as the basis */
2021                 copy_request(&p->initreq, &req);
2022                 parse(&p->initreq);
2023         }
2024         p->lastinvite = p->ocseq;
2025         return send_request(p, &req);
2026 }
2027
2028 static int transmit_notify(struct sip_pvt *p, int hasmsgs)
2029 {
2030         struct sip_request req;
2031         char tmp[256];
2032         char clen[20];
2033         initreqprep(&req, p, "NOTIFY", NULL);
2034         add_header(&req, "Event", "message-summary");
2035         add_header(&req, "Content-Type", "text/plain");
2036
2037         snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", hasmsgs ? "yes" : "no");
2038         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2039         add_header(&req, "Content-Length", clen);
2040         add_line(&req, tmp);
2041
2042         if (!p->initreq.headers) {
2043                 /* Use this as the basis */
2044                 copy_request(&p->initreq, &req);
2045                 parse(&p->initreq);
2046         }
2047
2048         p->lastinvite = p->ocseq;
2049         return send_request(p, &req);
2050 }
2051
2052 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2053
2054 static int sip_reregister(void *data) 
2055 {
2056         /* if we are here, we know that we need to reregister. */
2057         struct sip_registry *r=(struct sip_registry *)data;
2058         return sip_do_register(r);
2059         
2060 }
2061
2062
2063 static int sip_do_register(struct sip_registry *r)
2064 {
2065         int res;
2066         ast_pthread_mutex_lock(&r->lock);
2067         res=transmit_register(r, "REGISTER", NULL);
2068         ast_pthread_mutex_unlock(&r->lock);
2069         return res;
2070 }
2071
2072 static int sip_reg_timeout(void *data)
2073 {
2074         /* if we are here, our registration timed out, so we'll just do it over */
2075         struct sip_registry *r=data;
2076         int res;
2077         ast_pthread_mutex_lock(&r->lock);
2078         ast_log(LOG_NOTICE, "Registration timed out, trying again\n"); 
2079         r->regstate=REG_STATE_UNREGISTERED;
2080         /* cancel ourselves first!!! */
2081         /* ast_sched_del(sched,r->timeout); */
2082         res=transmit_register(r, "REGISTER", NULL);
2083         ast_pthread_mutex_unlock(&r->lock);
2084         return res;
2085 }
2086
2087 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2088 {
2089         struct sip_request req;
2090         char from[256];
2091         char to[256];
2092         char tmp[80];
2093         char via[80];
2094         char addr[80];
2095         struct sip_pvt *p;
2096         /* exit if we are already in process with this registrar ?*/
2097         if ( (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
2098                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2099                 return 0;
2100         }
2101
2102
2103         if (!(p=r->call)) {
2104                 if (!r->callid_valid) {
2105                   build_callid(r->callid, sizeof(r->callid), __ourip);
2106                   r->callid_valid=1;
2107                 }
2108                 p=sip_alloc( r->callid, &r->addr, 0);
2109                 p->outgoing = 1;
2110                 r->call=p;
2111                 p->registry=r;
2112                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2113                 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2114                 strncpy(p->username, r->username, sizeof(p->username)-1);
2115         }
2116
2117         /* set up a timeout */
2118         if (auth==NULL && !r->timeout)  {
2119                 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
2120                 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
2121         }
2122
2123         snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2124         snprintf(to, sizeof(to),     "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2125         
2126         snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
2127
2128         memset(&req, 0, sizeof(req));
2129         init_req(&req, cmd, addr);
2130
2131         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2132
2133         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
2134         add_header(&req, "Via", via);
2135         add_header(&req, "From", from);
2136         add_header(&req, "To", to);
2137         {
2138                 char contact[256];
2139                 snprintf(contact, sizeof(contact), "<sip:%s@%s:%d;transport=udp>", r->contact, inet_ntoa(p->ourip), ourport);
2140                 add_header(&req, "Contact", contact);
2141         }
2142         add_header(&req, "Call-ID", p->callid);
2143         add_header(&req, "CSeq", tmp);
2144         add_header(&req, "User-Agent", "Asterisk PBX");
2145         if (auth) 
2146                 add_header(&req, "Authorization", auth);
2147
2148         snprintf(tmp, sizeof(tmp), "%d", default_expirey);
2149         add_header(&req, "Expires", tmp);
2150         add_header(&req, "Event", "registration");
2151         copy_request(&p->initreq, &req);
2152         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2153         return send_request(p, &req);
2154 }
2155
2156 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2157 {
2158         struct sip_request req;
2159         reqprep(&req, p, "MESSAGE", 1);
2160         add_text(&req, text);
2161         return send_request(p, &req);
2162 }
2163
2164 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2165 {
2166         struct sip_request req;
2167         reqprep(&req, p, "INFO", 1);
2168         add_digit(&req, digit);
2169         return send_request(p, &req);
2170 }
2171
2172 static int transmit_request(struct sip_pvt *p, char *msg, int inc)
2173 {
2174         struct sip_request resp;
2175         reqprep(&resp, p, msg, inc);
2176         add_header(&resp, "Content-Length", "0");
2177         add_blank_header(&resp);
2178         return send_request(p, &resp);
2179 }
2180
2181 static int expire_register(void *data)
2182 {
2183         struct sip_peer *p = data;
2184         memset(&p->addr, 0, sizeof(p->addr));
2185         p->expire = -1;
2186         return 0;
2187 }
2188
2189 static int sip_poke_peer(struct sip_peer *peer);
2190
2191 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2192 {
2193         char contact[80]= ""; 
2194         char *expires = get_header(req, "Expires");
2195         int expirey = atoi(expires);
2196         char *c, *n, *pt;
2197         int port;
2198         struct hostent *hp;
2199         struct sockaddr_in oldsin;
2200         if (!strlen(expires)) {
2201                 expires = strstr(get_header(req, "Contact"), "expires=");
2202                 if (expires) 
2203                         if (sscanf(expires + 8, "%d;", &expirey) != 1)
2204                                 expirey = 0;
2205         }
2206         /* Look for brackets */
2207         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2208         c = contact;
2209         
2210         if ((n=strchr(c, '<'))) {
2211                 c = n + 1;
2212                 n = strchr(c, '>');
2213                 /* Lose the part after the > */
2214                 if (n) 
2215                         *n = '\0';
2216         }
2217         if (!strcasecmp(c, "*")) {
2218                 /* This means remove all registrations and return OK */
2219                 memset(&p->addr, 0, sizeof(p->addr));
2220                 if (p->expire > -1)
2221                         ast_sched_del(sched, p->expire);
2222                 p->expire = -1;
2223                 if (option_verbose > 2)
2224                         ast_verbose(VERBOSE_PREFIX_3 "Unegistered SIP '%s'\n", p->username);
2225                 return 0;
2226         }
2227         /* Make sure it's a SIP URL */
2228         if (strncasecmp(c, "sip:", 4)) {
2229                 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2230         } else
2231                 c += 4;
2232         /* Ditch q */
2233         n = strchr(c, ';');
2234         if (n) 
2235                 *n = '\0';
2236         /* Grab host */
2237         n = strchr(c, '@');
2238         if (!n) {
2239                 n = c;
2240                 c = NULL;
2241         } else {
2242                 *n = '\0';
2243                 n++;
2244         }
2245         pt = strchr(n, ':');
2246         if (pt) {
2247                 *pt = '\0';
2248                 pt++;
2249                 port = atoi(pt);
2250         } else
2251                 port = DEFAULT_SIP_PORT;
2252         memcpy(&oldsin, &p->addr, sizeof(oldsin));
2253         if (!p->nat) {
2254                 /* XXX This could block for a long time XXX */
2255                 hp = gethostbyname(n);
2256                 if (!hp)  {
2257                         ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2258                         return -1;
2259                 }
2260                 p->addr.sin_family = AF_INET;
2261                 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2262                 p->addr.sin_port = htons(port);
2263         } else {
2264                 /* Don't trust the contact field.  Just use what they came to us
2265                    with */
2266                 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2267         }
2268         if (c)
2269                 strncpy(p->username, c, sizeof(p->username) - 1);
2270         else
2271                 strcpy(p->username, "");
2272         if (p->expire > -1)
2273                 ast_sched_del(sched, p->expire);
2274         if ((expirey < 1) || (expirey > max_expirey))
2275                 expirey = max_expirey;
2276         p->expire = ast_sched_add(sched, (expirey + 10) * 1000, expire_register, p);
2277         pvt->expirey = expirey;
2278         if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
2279                 sip_poke_peer(p);
2280                 if (option_verbose > 2)
2281                         ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", p->username, inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port), expirey);
2282         }
2283         return 0;
2284 }
2285
2286 static void md5_hash(char *output, char *input)
2287 {
2288                 struct MD5Context md5;
2289                 unsigned char digest[16];
2290                 char *ptr;
2291                 int x;
2292                 MD5Init(&md5);
2293                 MD5Update(&md5, input, strlen(input));
2294                 MD5Final(digest, &md5);
2295                 ptr = output;
2296                 for (x=0;x<16;x++)
2297                         ptr += sprintf(ptr, "%2.2x", digest[x]);
2298 }
2299
2300 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri)
2301 {
2302         int res = -1;
2303         /* Always OK if no secret */
2304         if (!strlen(secret))
2305                 return 0;
2306         if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2307                 snprintf(randdata, randlen, "%08x", rand());
2308                 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata);
2309                 res = 1;
2310         } else {
2311                 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2312                    an example in the spec of just what it is you're doing a hash on. */
2313                 char a1[256];
2314                 char a2[256];
2315                 char a1_hash[256];
2316                 char a2_hash[256];
2317                 char resp[256];
2318                 char resp_hash[256];
2319                 char tmp[256] = "";
2320                 char *c;
2321                 char *response ="";
2322                 char *resp_uri ="";
2323
2324                 /* Find their response among the mess that we'r sent for comparison */
2325                 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2326                 c = tmp;
2327
2328                 while(c) {
2329                         while (*c && (*c < 33)) c++;
2330                         if (!*c)
2331                                 break;
2332                         if (!strncasecmp(c, "response=", strlen("response="))) {
2333                                 c+= strlen("response=");
2334                                 if ((*c == '\"')) {
2335                                         response=++c;
2336                                         if((c = strchr(c,'\"')))
2337                                                 *c = '\0';
2338
2339                                 } else {
2340                                         response=c;
2341                                         if((c = strchr(c,',')))
2342                                                 *c = '\0';
2343                                 }
2344
2345                         } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2346                                 c+= strlen("uri=");
2347                                 if ((*c == '\"')) {
2348                                         resp_uri=++c;
2349                                         if((c = strchr(c,'\"')))
2350                                                 *c = '\0';
2351                                 } else {
2352                                         resp_uri=c;
2353                                         if((c = strchr(c,',')))
2354                                                 *c = '\0';
2355                                 }
2356
2357                         } else
2358                                 c = strchr(c, ',');
2359                         if (c)
2360                                 c++;
2361                 }
2362                 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2363                 if(strlen(resp_uri))
2364                         snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2365                 else
2366                         snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2367                 md5_hash(a1_hash, a1);
2368                 md5_hash(a2_hash, a2);
2369                 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2370                 md5_hash(resp_hash, resp);
2371
2372                 /* resp_hash now has the expected response, compare the two */
2373
2374                 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2375                         /* Auth is OK */
2376                         res = 0;
2377                 }
2378                 /* Assume success ;-) */
2379                 /* Eliminate random data */
2380                 strcpy(randdata, "");
2381         }
2382         return res;
2383 }
2384
2385 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2386 {
2387         int res = -1;
2388         struct sip_peer *peer;
2389         char tmp[256] = "";
2390         char *name, *c;
2391         char *t;
2392         /* Terminate URI */
2393         t = uri;
2394         while(*t && (*t > 32) && (*t != ';'))
2395                 t++;
2396         *t = '\0';
2397         
2398         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2399         c = ditch_braces(tmp);
2400         if (!strncmp(c, "sip:", 4)) {
2401                 name = c + 4;
2402         } else {
2403                 name = c;
2404                 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
2405         }
2406         c = strchr(name, '@');
2407         if (c) 
2408                 *c = '\0';
2409         ast_pthread_mutex_lock(&peerl.lock);
2410         peer = peerl.peers;
2411         while(peer) {
2412                 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2413                         p->nat = peer->nat;
2414                         transmit_response(p, "100 Trying", req);
2415                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri))) {
2416                                 if (parse_contact(p, peer, req)) {
2417                                         ast_log(LOG_WARNING, "Failed to parse contact info\n");
2418                                 } else {
2419                                         /* Say OK and ask subsystem to retransmit msg counter */
2420                                         transmit_response(p, "200 OK", req);
2421                                         peer->lastmsgssent = -1;
2422                                         res = 0;
2423                                 }
2424                         } 
2425                         break;
2426                 }       
2427                 peer = peer->next;
2428         }
2429         ast_pthread_mutex_unlock(&peerl.lock);
2430         if (res < 0)
2431                 transmit_response(p, "401 Unauthorized", &p->initreq);
2432         return res;
2433 }
2434
2435 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2436 {
2437         char tmp[256] = "", *c, *a;
2438         struct sip_request *req;
2439         
2440         req = oreq;
2441         if (!req)
2442                 req = &p->initreq;
2443         strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2444         c = ditch_braces(tmp);
2445         if (strncmp(c, "sip:", 4)) {
2446                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2447                 return -1;
2448         }
2449         c += 4;
2450         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2451                 *a = '\0';
2452         }
2453         if (sipdebug)
2454                 ast_verbose("Looking for %s in %s\n", c, p->context);
2455         if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2456                 if (!oreq)
2457                         strncpy(p->exten, c, sizeof(p->exten) - 1);
2458                 return 0;
2459         }
2460
2461         if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2462                 return 1;
2463         }
2464         
2465         return -1;
2466 }
2467
2468 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2469 {
2470         char tmp[256] = "", *c, *a;
2471         char tmp2[256] = "", *c2, *a2;
2472         char tmp3[256];
2473         char tmp4[256];
2474         char tmp5[256] = "";            /* CallID to replace */
2475         struct sip_request *req;
2476         struct sip_pvt *p2;
2477         
2478         req = oreq;
2479         if (!req)
2480                 req = &p->initreq;
2481         strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2482         strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
2483         strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
2484         strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
2485         
2486         c = ditch_braces(tmp);
2487         c2 = ditch_braces(tmp2);
2488         
2489                 
2490         if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
2491                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2492                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c2);
2493                 return -1;
2494         }
2495         c += 4;
2496         c2 += 4;
2497         if ((a = strchr(c, '?'))) {
2498                 /* Search for arguemnts */
2499                 *a = '\0';
2500                 a++;
2501                 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
2502                         strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
2503                         if ((a = strchr(tmp5, '%'))) {
2504                                 /* Yuck!  Pingtel converts the '@' to a %40, icky icky!  Convert
2505                                    back to an '@' */
2506                                 if ((a[1] == '4') && (a[2] == '0')) {
2507                                         *a = '@';
2508                                         memmove(a + 1, a+3, strlen(a + 3));
2509                                 }
2510                         }
2511                         if ((a = strchr(tmp5, '%'))) 
2512                                 *a = '\0';
2513                 }
2514         }
2515         
2516         if ((a = strchr(c, '@')))
2517                 *a = '\0';
2518         if ((a = strchr(c, ';'))) 
2519                 *a = '\0';
2520         
2521
2522         if ((a2 = strchr(c2, '@')))
2523                 *a2 = '\0';
2524
2525         if ((a2 = strchr(c2, ';'))) 
2526                 *a2 = '\0';
2527         
2528         
2529         if (sipdebug) {
2530                 ast_verbose("Looking for %s in %s\n", c, p->context);
2531                 ast_verbose("Looking for %s in %s\n", c2, p->context);
2532         }
2533         if (strlen(tmp5)) {     
2534                 /* This is a supervised transfer */
2535                 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
2536                 
2537                 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
2538                 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
2539                 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
2540                 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
2541                 p->refer_call = NULL;
2542                 ast_pthread_mutex_lock(&iflock);
2543                 /* Search interfaces and find the match */
2544                 p2 = iflist;
2545                 while(p2) {
2546                         if (!strcmp(p2->callid, tmp5)) {
2547                                 /* Go ahead and lock it before returning */
2548                                 ast_pthread_mutex_lock(&p2->lock);
2549                                 p->refer_call = p2;
2550                                 break;
2551                         }
2552                         p2 = p2->next;
2553                 }
2554                 ast_pthread_mutex_unlock(&iflock);
2555                 if (p->refer_call)
2556                         return 0;
2557                 else
2558                         ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
2559         } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2560                 /* This is an unsupervised transfer */
2561                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
2562                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
2563                 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
2564                 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
2565                 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
2566                 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
2567                 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
2568                 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
2569                 p->refer_call = NULL;
2570                 return 0;
2571         } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2572                 return 1;
2573         }
2574
2575         return -1;
2576 }
2577
2578
2579 static int check_via(struct sip_pvt *p, struct sip_request *req)
2580 {
2581         char via[256] = "";
2582         char *c, *pt;
2583         struct hostent *hp;
2584
2585         memset(via, 0, sizeof(via));
2586         strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
2587         c = strchr(via, ';');
2588         if (c) 
2589                 *c = '\0';
2590         c = strchr(via, ' ');
2591         if (c) {
2592                 *c = '\0';
2593                 c++;
2594                 while(*c && (*c < 33))
2595                         c++;
2596                 if (strcmp(via, "SIP/2.0/UDP")) {
2597                         ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
2598                         return -1;
2599                 }
2600                 pt = strchr(c, ':');
2601                 if (pt) {
2602                         *pt = '\0';
2603                         pt++;
2604                 }
2605                 hp = gethostbyname(c);
2606                 if (!hp) {
2607                         ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
2608                         return -1;
2609                 }
2610                 memset(&p->sa, 0, sizeof(p->sa));
2611                 p->sa.sin_family = AF_INET;
2612                 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2613                 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
2614                 if (sipdebug) {
2615                         if (p->nat)
2616                                 ast_verbose("Sending to %s : %d (NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2617                         else
2618                                 ast_verbose("Sending to %s : %d (non-NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2619                 }
2620         }
2621         return 0;
2622 }
2623
2624 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri)
2625 {
2626         struct sip_user *user;
2627         char *of, from[256] = "", *c;
2628         int res = 0;
2629         char *t;
2630         /* Terminate URI */
2631         t = uri;
2632         while(*t && (*t > 32) && (*t != ';'))
2633                 t++;
2634         *t = '\0';
2635         of = get_header(req, "From");
2636         strncpy(from, of, sizeof(from) - 1);
2637         of = ditch_braces(from);
2638         if (strncmp(of, "sip:", 4)) {
2639                 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2640         } else
2641                 of += 4;
2642         /* Get just the username part */
2643         if ((c = strchr(of, '@')))
2644                 *c = '\0';
2645         if ((c = strchr(of, ':')))
2646                 *c = '\0';
2647         strncpy(p->callerid, of, sizeof(p->callerid) - 1);
2648         if (!strlen(of))
2649                         return 0;
2650         ast_pthread_mutex_lock(&userl.lock);
2651         user = userl.users;
2652         while(user) {
2653                 if (!strcasecmp(user->name, of)) {
2654                         p->nat = user->nat;
2655                         if (p->rtp) {
2656                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
2657                                 ast_rtp_setnat(p->rtp, p->nat);
2658                         }
2659                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri))) {
2660                                 strncpy(p->context, user->context, sizeof(p->context) - 1);
2661                                 if (strlen(user->callerid) && strlen(p->callerid)) 
2662                                         strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
2663                                 strncpy(p->username, user->name, sizeof(p->username) - 1);
2664                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)  -1);
2665                                 p->canreinvite = user->canreinvite;
2666                                 p->amaflags = user->amaflags;
2667                                 if (user->dtmfmode)
2668                                         p->dtmfmode = user->dtmfmode;
2669                         }
2670                         break;
2671                 }
2672                 user = user->next;
2673         }
2674         ast_pthread_mutex_unlock(&userl.lock);
2675         return res;
2676 }
2677
2678 static int get_msg_text(char *buf, int len, struct sip_request *req)
2679 {
2680         int x;
2681         strcpy(buf, "");
2682         for (x=0;x<req->lines;x++) {
2683                 strncat(buf, req->line[x], len - strlen(buf) - 5);
2684                 strcat(buf, "\n");
2685         }
2686         return 0;
2687 }
2688
2689 static void receive_message(struct sip_pvt *p, struct sip_request *req)
2690 {
2691         char buf[1024];
2692         struct ast_frame f;
2693         if (get_msg_text(buf, sizeof(buf), req)) {
2694                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2695                 return;
2696         }
2697         if (p->owner) {
2698                 if (sipdebug)
2699                         ast_verbose("Message received: '%s'\n", buf);
2700                   memset(&f, 0, sizeof(f));
2701                   f.frametype = AST_FRAME_TEXT;
2702                   f.subclass = 0;
2703                   f.offset = 0;
2704                   f.data = buf;
2705                   f.datalen = strlen(buf);
2706                   ast_queue_frame(p->owner, &f, 1);
2707         }
2708 }
2709
2710 static int sip_show_users(int fd, int argc, char *argv[])
2711 {
2712 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
2713         struct sip_user *user;
2714         if (argc != 3) 
2715                 return RESULT_SHOWUSAGE;
2716         ast_pthread_mutex_lock(&userl.lock);
2717         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2718         for(user=userl.users;user;user=user->next) {
2719                 ast_cli(fd, FORMAT, user->name, user->secret, user->methods, 
2720                                 user->context,
2721                                 user->ha ? "Yes" : "No");
2722         }
2723         ast_pthread_mutex_unlock(&userl.lock);
2724         return RESULT_SUCCESS;
2725 #undef FORMAT
2726 }
2727
2728 static int sip_show_peers(int fd, int argc, char *argv[])
2729 {
2730 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s %-10s\n"
2731 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-8d %-10s\n"
2732         struct sip_peer *peer;
2733         char name[256] = "";
2734         if (argc != 3)
2735                 return RESULT_SHOWUSAGE;
2736         ast_pthread_mutex_lock(&peerl.lock);
2737         ast_cli(fd, FORMAT2, "Name/username", "Host", "   ", "Mask", "Port", "Status");
2738         for (peer = peerl.peers;peer;peer = peer->next) {
2739                 char nm[20] = "";
2740                 char status[20];
2741                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2742                 if (strlen(peer->username))
2743                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2744                 else
2745                         strncpy(name, peer->name, sizeof(name) - 1);
2746                 if (peer->maxms) {
2747                         if (peer->lastms < 0)
2748                                 strcpy(status, "UNREACHABLE");
2749                         else if (peer->lastms > peer->maxms) 
2750                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2751                         else if (peer->lastms) 
2752                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2753                         else 
2754                                 strcpy(status, "UNKNOWN");
2755                 } else 
2756                         strcpy(status, "Unmonitored");
2757                 ast_cli(fd, FORMAT, name, 
2758                                         peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2759                                         peer->dynamic ? "(D)" : "   ",
2760                                         nm,
2761                                         ntohs(peer->addr.sin_port), status);
2762         }
2763         ast_pthread_mutex_unlock(&peerl.lock);
2764         return RESULT_SUCCESS;
2765 #undef FORMAT
2766 #undef FORMAT2
2767 }
2768
2769 static char *regstate2str(int regstate)
2770 {
2771         switch(regstate) {
2772         case REG_STATE_UNREGISTERED:
2773                 return "Unregistered";
2774         case REG_STATE_REGSENT:
2775                 return "Request Sent";
2776         case REG_STATE_AUTHSENT:
2777                 return "Auth. Sent";
2778         case REG_STATE_REGISTERED:
2779                 return "Registered";
2780         case REG_STATE_REJECTED:
2781                 return "Rejected";
2782         case REG_STATE_TIMEOUT:
2783                 return "Timeout";
2784         case REG_STATE_NOAUTH:
2785                 return "No Authentication";
2786         default:
2787                 return "Unknown";
2788         }
2789 }
2790
2791 static int sip_show_registry(int fd, int argc, char *argv[])
2792 {
2793 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
2794 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
2795         struct sip_registry *reg;
2796         char host[80];
2797         char state[20];
2798         if (argc != 3)
2799                 return RESULT_SHOWUSAGE;
2800         ast_pthread_mutex_lock(&peerl.lock);
2801         ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
2802         for (reg = registrations;reg;reg = reg->next) {
2803                 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2804                 snprintf(state, sizeof(state), "%s", regstate2str(reg->regstate));
2805                 ast_cli(fd, FORMAT, host, 
2806                                         reg->username, state, reg->refresh, regstate2str(reg->regstate));
2807         }
2808         ast_pthread_mutex_unlock(&peerl.lock);
2809         return RESULT_SUCCESS;
2810 #undef FORMAT
2811 #undef FORMAT2
2812 }
2813
2814 static int sip_show_channels(int fd, int argc, char *argv[])
2815 {
2816 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %s\n"
2817 #define FORMAT  "%-15.15s  %-10.10s  %-11.11s  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %d\n"
2818         struct sip_pvt *cur;
2819         int numchans = 0;
2820         if (argc != 3)
2821                 return RESULT_SHOWUSAGE;
2822         ast_pthread_mutex_lock(&iflock);
2823         cur = iflist;
2824         ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2825         while (cur) {
2826                         ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr), 
2827                                                 strlen(cur->username) ? cur->username : "(None)", 
2828                                                 cur->callid, 
2829                                                 cur->ocseq, cur->icseq, 
2830                                                 0,
2831                                                 0,
2832                                                 cur->owner ? cur->owner->nativeformats : 0);
2833                 cur = cur->next;
2834                 numchans++;
2835         }
2836         ast_pthread_mutex_unlock(&iflock);
2837         ast_cli(fd, "%d active SIP channel(s)\n", numchans);
2838         return RESULT_SUCCESS;
2839 #undef FORMAT
2840 #undef FORMAT2
2841 }
2842
2843 static char *complete_sipch(char *line, char *word, int pos, int state)
2844 {
2845         int which=0;
2846         struct sip_pvt *cur;
2847         char *c = NULL;
2848         ast_pthread_mutex_lock(&iflock);
2849         cur = iflist;
2850         while(cur) {
2851                 if (!strncasecmp(word, cur->callid, strlen(word))) {
2852                         if (++which > state) {
2853                                 c = strdup(cur->callid);
2854                                 break;
2855                         }
2856                 }
2857                 cur = cur->next;
2858         }
2859         ast_pthread_mutex_unlock(&iflock);
2860         return c;
2861 }
2862
2863 static int sip_show_channel(int fd, int argc, char *argv[])
2864 {
2865         struct sip_pvt *cur;
2866         char tmp[256];
2867         if (argc != 4)
2868                 return RESULT_SHOWUSAGE;
2869         ast_pthread_mutex_lock(&iflock);
2870         cur = iflist;
2871         while(cur) {
2872                 if (!strcasecmp(cur->callid, argv[3])) {
2873                         ast_cli(fd, "Call-ID: %s\n", cur->callid);
2874                         ast_cli(fd, "Theoretical Address: %s:%d\n", inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
2875                         ast_cli(fd, "Received Address:    %s:%d\n", inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
2876                         ast_cli(fd, "NAT Support:         %s\n", cur->nat ? "Yes" : "No");
2877                         strcpy(tmp, "");
2878                         if (cur->dtmfmode & SIP_DTMF_RFC2833)
2879                                 strcat(tmp, "rfc2833 ");
2880                         if (cur->dtmfmode & SIP_DTMF_INFO)
2881                                 strcat(tmp, "info ");
2882                         if (cur->dtmfmode & SIP_DTMF_INBAND)
2883                                 strcat(tmp, "inband ");
2884                         ast_cli(fd, "DTMF Mode: %s\n", tmp);
2885                         break;
2886                 }
2887                 cur = cur->next;
2888         }
2889         ast_pthread_mutex_unlock(&iflock);
2890         if (!cur) 
2891                 ast_cli(fd, "No such SIP Call ID '%s'\n", argv[3]);
2892         return RESULT_SUCCESS;
2893 }
2894
2895 static void receive_info(struct sip_pvt *p, struct sip_request *req)
2896 {
2897         char buf[1024] = "";
2898         struct ast_frame f;
2899         char *c;
2900         /* Try getting the "signal=" part */
2901         if ((c = get_sdp(req, "Signal"))) {
2902                 strncpy(buf, c, sizeof(buf) - 1);
2903         } else if (get_msg_text(buf, sizeof(buf), req)) {
2904                 /* Normal INFO method */
2905                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2906                 return;
2907         }
2908         
2909         if (p->owner) {
2910                 if (strlen(buf)) {
2911                         if (sipdebug)
2912                                 ast_verbose("DTMF received: '%c'\n", buf[0]);
2913                         memset(&f, 0, sizeof(f));
2914                         f.frametype = AST_FRAME_DTMF;
2915                         f.subclass = buf[0];
2916                         f.offset = 0;
2917                         f.data = NULL;
2918                         f.datalen = 0;
2919                         ast_queue_frame(p->owner, &f, 1);
2920                 }
2921         }
2922 }
2923
2924 static int sip_do_debug(int fd, int argc, char *argv[])
2925 {
2926         if (argc != 2)
2927                 return RESULT_SHOWUSAGE;
2928         sipdebug = 1;
2929         ast_cli(fd, "SIP Debugging Enabled\n");
2930         return RESULT_SUCCESS;
2931 }
2932
2933 static int sip_no_debug(int fd, int argc, char *argv[])
2934 {
2935         if (argc != 3)
2936                 return RESULT_SHOWUSAGE;
2937         sipdebug = 0;
2938         ast_cli(fd, "SIP Debugging Disabled\n");
2939         return RESULT_SUCCESS;
2940 }
2941
2942 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len);
2943
2944 static int do_register_auth(struct sip_pvt *p, struct sip_request *req) {
2945         char digest[256];
2946         memset(digest,0,sizeof(digest));
2947         reply_digest(p,req, "WWW-Authenticate", "REGISTER", digest, sizeof(digest) );
2948         return transmit_register(p->registry,"REGISTER",digest); 
2949 }
2950
2951 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req) {
2952         char digest[256];
2953         memset(digest,0,sizeof(digest));
2954         reply_digest(p,req, "Proxy-Authenticate", "INVITE", digest, sizeof(digest) );
2955         return transmit_invite(p,"INVITE",1,digest, NULL); 
2956 }
2957
2958 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
2959
2960         char tmp[256] = "";
2961         char *realm = "";
2962         char *nonce = "";
2963         char *c;
2964         char a1[256];
2965         char a2[256];
2966         char a1_hash[256];
2967         char a2_hash[256];
2968         char resp[256];
2969         char resp_hash[256];
2970         char uri[256] = "";
2971
2972
2973         strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
2974         c = tmp;
2975         c+=strlen("Digest ");
2976         while (c) {
2977                 while (*c && (*c < 33)) c++;
2978                 if (!*c)
2979                         break;
2980                         if (!strncasecmp(c,"realm=", strlen("realm="))) {
2981                                 c+=strlen("realm=");
2982                                 if ((*c == '\"')) {
2983                                         realm=++c;
2984                                         if ((c = strchr(c,'\"')))
2985                                                 *c = '\0';
2986                                 } else {
2987                                         realm = c;
2988                                         if ((c = strchr(c,',')))
2989                                                 *c = '\0';
2990                                 }
2991
2992                         } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
2993                                 c+=strlen("nonce=");
2994                                 if ((*c == '\"')) {
2995                                         nonce=++c;
2996                                         if ((c = strchr(c,'\"')))
2997                                                 *c = '\0';
2998                                 } else {
2999                                         nonce = c;
3000                                         if ((c = strchr(c,',')))
3001                                                 *c = '\0';
3002                                 }
3003                         } else
3004                                 c = strchr(c,',');
3005                         if (c)
3006                                 c++;
3007                         }
3008
3009         /* Okay.  We've got the realm and nonce from the server.  Now lets build the MD5 digest. */
3010         snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
3011
3012         snprintf(a1,sizeof(a1),"%s:%s:%s",p->peername,realm,p->peersecret);
3013         snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
3014         md5_hash(a1_hash,a1);
3015         md5_hash(a2_hash,a2);
3016         snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,nonce,a2_hash);
3017         md5_hash(resp_hash,resp);
3018
3019         snprintf(digest,digest_len,"Digest username=\"%s\", realm=\"%s\", algorithm=\"MD5\", uri=\"%s\", nonce=\"%s\", response=\"%s\"",p->peername,realm,uri,nonce,resp_hash);
3020
3021         return 0;
3022 }
3023         
3024
3025         
3026         
3027
3028
3029 static char show_users_usage[] = 
3030 "Usage: sip show users\n"
3031 "       Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
3032
3033 static char show_channels_usage[] = 
3034 "Usage: sip show channels\n"
3035 "       Lists all currently active SIP channels.\n";
3036
3037 static char show_channel_usage[] = 
3038 "Usage: sip show channel <channel>\n"
3039 "       Provides detailed status on a given SIP channel.\n";
3040
3041 static char show_peers_usage[] = 
3042 "Usage: sip show peers\n"
3043 "       Lists all known SIP peers.\n";
3044
3045 static char show_reg_usage[] =
3046 "Usage: sip show registry\n"
3047 "       Lists all registration requests and status.\n";
3048
3049 static char debug_usage[] = 
3050 "Usage: sip debug\n"
3051 "       Enables dumping of SIP packets for debugging purposes\n";
3052
3053 static char no_debug_usage[] = 
3054 "Usage: sip no debug\n"
3055 "       Disables dumping of SIP packets for debugging purposes\n";
3056
3057 static struct ast_cli_entry  cli_show_users = 
3058         { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
3059 static struct ast_cli_entry  cli_show_channels =
3060         { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage};
3061 static struct ast_cli_entry  cli_show_channel =
3062         { { "sip", "show", "channel", NULL }, sip_show_channel, "Show detailed SIP channel info", show_channel_usage, complete_sipch  };
3063 static struct ast_cli_entry  cli_show_peers =
3064         { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
3065 static struct ast_cli_entry  cli_show_registry =
3066         { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
3067 static struct ast_cli_entry  cli_debug =
3068         { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
3069 static struct ast_cli_entry  cli_no_debug =
3070         { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
3071
3072
3073 static int sip_poke_peer_s(void *data)
3074 {
3075         struct sip_peer *peer = data;
3076         peer->pokeexpire = -1;
3077         sip_poke_peer(peer);
3078         return 0;
3079 }
3080
3081 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req)
3082 {
3083         char *to;
3084         char *msg, *c;
3085         struct ast_rtp *rtp;
3086         struct ast_channel *owner;
3087         struct sip_peer *peer;
3088         int pingtime;
3089         struct timeval tv;
3090         c = get_header(req, "Cseq");
3091         msg = strchr(c, ' ');
3092         if (!msg) msg = ""; else msg++;
3093 retrylock:
3094         ast_pthread_mutex_lock(&p->lock);
3095         /* Go ahead and lock the owner if it has one -- we may need it */
3096         if (p->owner && pthread_mutex_trylock(&p->owner->lock)) {
3097                 ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
3098                 ast_pthread_mutex_unlock(&p->lock);
3099                 /* Sleep infintismly short amount of time */
3100                 usleep(1);
3101                 goto retrylock;
3102         }
3103         owner = p->owner;
3104         if (p->peerpoke) {
3105                 /* We don't really care what the response is, just that it replied back. 
3106                    Well, as long as it's not a 100 response...  since we might
3107                    need to hang around for something more "difinitive" */
3108                 if (resp != 100) {
3109                         peer = p->peerpoke;
3110                         gettimeofday(&tv, NULL);
3111                         pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
3112                                                 (tv.tv_usec - peer->ps.tv_usec) / 1000;
3113                         if (pingtime < 1)
3114                                 pingtime = 1;
3115                         if ((peer->lastms < 0)  || (peer->lastms > peer->maxms)) {
3116                                 if (pingtime <= peer->maxms)
3117                                 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE!\n", peer->name);
3118                         } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
3119                                 if (pingtime > peer->maxms)
3120                                         ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED!\n", peer->name);
3121                         }
3122                         peer->lastms = pingtime;
3123                         peer->call = NULL;
3124                         if (peer->pokeexpire > -1)
3125                                 ast_sched_del(sched, peer->pokeexpire);
3126                         if (!strcasecmp(msg, "INVITE"))
3127                                 transmit_request(p, "ACK", 0);
3128                         sip_destroy(p);
3129                         p = NULL;
3130                         /* Try again eventually */
3131                         if ((peer->lastms < 0)  || (peer->lastms > peer->maxms))
3132                                 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
3133                         else
3134                                 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
3135                 }
3136         } else if (p->outgoing) {
3137                 if (p->initid > -1) {
3138                         /* Don't auto congest anymore since we've gotten something useful back */
3139                         ast_sched_del(sched, p->initid);
3140                         p->initid = -1;
3141                 }
3142                 /* Get their tag if we haven't already */
3143                 if (!strlen(p->theirtag)) {
3144                         to = get_header(req, "To");
3145                         to = strstr(to, "tag=");
3146                         if (to) {
3147                                 to += 4;
3148                                 strncpy(p->theirtag, to, sizeof(p->theirtag) - 1);
3149                                 to = strchr(p->theirtag, ';');
3150                                 if (to)
3151                                         *to = '\0';
3152                         }
3153                 }
3154                 
3155                 switch(resp) {
3156                 case 100:
3157                         break;
3158                 case 183:       /* We don't really need this since we pass in-band audio anyway */
3159                         /* Not important */
3160                         if (strlen(get_header(req, "Content-Type")))
3161                                 process_sdp(p, req);
3162                         break;
3163                 case 180:
3164                         if (p->owner) {
3165                                 ast_queue_control(p->owner, AST_CONTROL_RINGING, 0);
3166                                 if (p->owner->_state != AST_STATE_UP)
3167                                         ast_setstate(p->owner, AST_STATE_RINGING);
3168                         }
3169                         break;
3170                 case 200:
3171                         if (strlen(get_header(req, "Content-Type")))
3172                                 process_sdp(p, req);
3173                         if (p->owner) {
3174                                 if (p->owner->_state != AST_STATE_UP) {
3175                                         ast_setstate(p->owner, AST_STATE_UP);
3176                                         ast_queue_control(p->owner, AST_CONTROL_ANSWER, 0);
3177                                 }
3178                         }
3179                         if (!strcasecmp(msg, "INVITE"))
3180                                 transmit_request(p, "ACK", 0);
3181                         else if (!strcasecmp(msg, "REGISTER"))
3182                         {
3183                                 /* char *exp; */
3184                                 int expires;
3185                                 struct sip_registry *r;
3186                                 r=p->registry;
3187                                 r->regstate=REG_STATE_REGISTERED;
3188                                 ast_log(LOG_NOTICE, "Registration successful\n");
3189                                 ast_log(LOG_NOTICE, "Cancelling timeout %d\n", r->timeout);
3190                                 if (r->timeout) 
3191                                         ast_sched_del(sched, r->timeout);
3192                                 r->timeout=0;
3193                                 /* set us up for re-registering */
3194                                 /* figure out how long we got registered for */
3195                                 if (r->expire != -1)
3196                                         ast_sched_del(sched, r->expire);
3197                                 expires=atoi(get_header(req, "expires"));
3198                                 if (!expires) expires=default_expirey;
3199                                         r->expire=ast_sched_add(sched, (expires-2)*1000, sip_reregister, r); 
3200
3201                         }
3202                         break;
3203                 case 401: /* Not authorized on REGISTER */
3204                         /* XXX: Do I need to ACK the 401? 
3205                         transmit_request(p, "ACK", 0);
3206                         */
3207                         do_register_auth(p, req);
3208                         break;
3209                 case 407:
3210                         /* First we ACK */
3211                         transmit_request(p, "ACK", 0);
3212                         /* Then we AUTH */
3213                         do_proxy_auth(p, req);
3214                         /* This is just a hack to kill the channel while testing */
3215                         /* 
3216                         p->alreadygone = 1;
3217                         if (p->rtp) {
3218                                 rtp = p->rtp;
3219                                 p->rtp = NULL;
3220                                 ast_rtp_destroy(rtp);
3221                         }
3222                         if (p->owner)
3223                                 ast_queue_hangup(p->owner,0);
3224                         transmit_request(p,"ACK",0);
3225                         sip_destroy(p);
3226                         p = NULL;
3227                         */
3228                         break;
3229                 default:
3230                         if ((resp >= 400) && (resp < 700)) {
3231                                 if (option_verbose > 2) 
3232                                         ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, inet_ntoa(p->sa.sin_addr));
3233                                 p->alreadygone = 1;
3234                                 if (p->rtp) {
3235                                         rtp = p->rtp;
3236                                         p->rtp = NULL;
3237                                         /* Immediately stop RTP */
3238                                         ast_rtp_destroy(rtp);
3239                                 }
3240                                 /* XXX Locking issues?? XXX */
3241                                 switch(resp) {
3242                                 case 486: /* Busy here */
3243                                 case 600: /* Busy everywhere */
3244                                         if (p->owner)
3245                                                 ast_queue_control(p->owner, AST_CONTROL_BUSY, 0);
3246                                         break;
3247                                 case 480: /* Temporarily Unavailable */
3248                                 case 404: /* Not Found */
3249                                 case 410: /* Gone */
3250                                 case 500: /* Server error */
3251                                 case 501: /* Not Implemented */
3252                                         if (owner)
3253                                                 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
3254                                         break;
3255                                 default:
3256                                         /* Send hangup */       
3257                                         if (owner)
3258                                                 ast_queue_hangup(p->owner, 0);
3259                                         break;
3260                                 }
3261                                 transmit_request(p, "ACK", 0);
3262                                 __sip_destroy(p, 0);
3263                                 p = NULL;
3264                         } else
3265                                 ast_log(LOG_NOTICE, "Dunno anything about a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : inet_ntoa(p->sa.sin_addr));
3266                 }
3267         } else {
3268                 if (sipdebug)
3269                         ast_verbose("Message is %s\n", msg);
3270                 switch(resp) {
3271                 case 200:
3272                         if (!strcasecmp(msg, "INVITE") || !strcasecmp(msg, "REGISTER") )
3273                                 transmit_request(p, "ACK", 0);
3274                         break;
3275                 }
3276         }
3277         if (owner)
3278                 ast_pthread_mutex_unlock(&owner->lock);
3279         if (p)
3280                 ast_pthread_mutex_unlock(&p->lock);
3281 }
3282
3283 static int determine_firstline_parts( struct sip_request *req ) {
3284
3285   char *e, *cmd;
3286   int len;
3287   
3288   cmd= req->header[0];
3289   while(*cmd && (*cmd < 33)) {
3290     cmd++;
3291   }
3292   if (!*cmd) {
3293     return -1;
3294   }
3295   e= cmd;
3296   while(*e && (*e > 32)) {
3297     e++;
3298   }
3299   /* Get the command */
3300   if (*e) {
3301     *e = '\0';
3302     e++;
3303   }
3304   req->rlPart1= cmd;
3305   while( *e && ( *e < 33 ) ) {
3306     e++; 
3307   }
3308   if( !*e ) {
3309     return -1;
3310   }
3311     
3312   if ( !strcasecmp(cmd, "SIP/2.0") ) {
3313     /* We have a response */
3314     req->rlPart2= e;
3315     len= strlen( req->rlPart2 );
3316     if( len < 2 ) { return -1; }
3317     e+= len - 1;
3318     while( *e && *e<33 ) {
3319       e--; 
3320     }
3321     *(++e)= '\0';
3322   } else {
3323     /* We have a request */
3324     if( *e == '<' ) { 
3325       e++;
3326       if( !*e ) { return -1; }  
3327     }
3328     req->rlPart2= e;
3329     if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
3330       return -1;
3331     }
3332     while( isspace( *(--e) ) ) {}
3333     if( *e == '>' ) {
3334       *e= '\0';
3335     } else {
3336       *(++e)= '\0';
3337     }
3338   }
3339   return 1;
3340 }
3341
3342 static int attempt_transfer(struct sip_pvt *p1, struct sip_pvt *p2)
3343 {
3344         if (!p1->owner || !p2->owner) {
3345                 ast_log(LOG_WARNING, "Transfer attempted without dual ownership?\n");
3346                 return -1;
3347         }
3348         if (p1->owner->bridge) {
3349                 if (p2->owner->bridge)
3350                         ast_moh_stop(p2->owner->bridge);
3351                 ast_moh_stop(p1->owner->bridge);
3352                 ast_moh_stop(p1->owner);
3353                 ast_moh_stop(p2->owner);
3354                 if (ast_channel_masquerade(p2->owner, p1->owner->bridge)) {
3355                         ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p2->owner->name, p1->owner->bridge->name);
3356                         return -1;
3357                 }
3358         } else if (p2->owner->bridge) {
3359                 ast_moh_stop(p2->owner->bridge);
3360                 ast_moh_stop(p2->owner);
3361                 ast_moh_stop(p1->owner);
3362                 if (ast_channel_masquerade(p1->owner, p2->owner->bridge)) {
3363                         ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p1->owner->name, p2->owner->bridge->name);
3364                         return -1;
3365                 }
3366         } else {
3367                 ast_log(LOG_NOTICE, "Transfer attempted with no bridged calls to transfer\n");
3368                 return -1;
3369         }
3370         return 0;
3371 }
3372
3373 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin)
3374 {
3375         struct sip_request resp;
3376         char *cmd;
3377         char *cseq;
3378         char *e;
3379         struct ast_channel *c=NULL;
3380         int seqno;
3381         int len;
3382         int ignore=0;
3383         int respid;
3384         int res;
3385         /* Clear out potential response */
3386         memset(&resp, 0, sizeof(resp));
3387         /* Get Method and Cseq */
3388         cseq = get_header(req, "Cseq");
3389         cmd = req->header[0];
3390         /* Must have Cseq */
3391         if (!strlen(cmd) || !strlen(cseq))
3392                         return -1;
3393         if (sscanf(cseq, "%i%n", &seqno, &len) != 1) {
3394                 ast_log(LOG_DEBUG, "No seqno in '%s'\n", cmd);
3395                 return -1;
3396         }
3397         /* Get the command */
3398         cseq += len;
3399
3400   /* Determine the request URI for sip, sips or tel URIs */
3401         if( determine_firstline_parts( req ) < 0 ) {
3402           return -1; 
3403         }
3404         cmd= req->rlPart1;
3405         e= req->rlPart2;
3406         
3407         if (strcasecmp(cmd, "SIP/2.0")) {
3408                 /* Request coming in */                 
3409                 if (p->icseq && (p->icseq < seqno)) {
3410                         ast_log(LOG_DEBUG, "Ignoring out of order packet %d (expecting %d)\n", seqno, p->icseq);
3411                         return -1;
3412                 } else if (p->icseq && (p->icseq != seqno)) {
3413                         /* ignore means "don't do anything with it" but still have to 
3414                            respond appropriately  */
3415                         ignore=1;
3416                 }
3417         } else {
3418                 /* Response to our request -- Do some sanity checks */  
3419                 if (!p->initreq.headers) {
3420                         ast_log(LOG_DEBUG, "That's odd...  Got a response on a call we dont know about.\n");
3421                         sip_destroy(p);
3422                         return 0;
3423                 } else if (p->ocseq && (p->ocseq < seqno)) {
3424                         ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
3425                         return -1;
3426                 } else if (p->ocseq && (p->ocseq != seqno)) {
3427                         /* ignore means "don't do anything with it" but still have to 
3428                            respond appropriately  */
3429                         ignore=1;
3430                 }
3431         }
3432         
3433         if (strcmp(cmd, "SIP/2.0"))
3434                 /* Next should follow monotonically increasing */
3435                 p->icseq = seqno + 1;
3436
3437         /* Initialize the context if it hasn't been already */
3438         if (!strcasecmp(cmd, "OPTIONS")) {
3439                 if (!strlen(p->context))
3440                         strncpy(p->context, context, sizeof(p->context) - 1);
3441                 res = get_destination(p, req);
3442                 if (res < 0)
3443                         transmit_response_with_allow(p, "404 Not Found", req);
3444                 else if (res > 0)
3445                         transmit_response_with_allow(p, "484 Address Incomplete", req);
3446                 else 
3447                         transmit_response_with_allow(p, "200 OK", req);
3448         } else if (!strcasecmp(cmd, "INVITE")) {
3449                 if (p->outgoing && p->owner && (p->owner->_state != AST_STATE_UP)) {
3450                         /* This is a call to ourself.  Send ourselves an error code and stop
3451                            processing immediately, as SIP really has no good mechanism for
3452                            being able to call yourself */
3453                         transmit_response(p, "482 Loop Detected", req);
3454                         /* We do NOT destroy p here, so that our response will be accepted */
3455                         return 0;
3456                 }
3457                 /* Process the SDP portion */
3458                 if (!ignore) {
3459                         /* Use this as the basis */
3460                         if (sipdebug)
3461                                 ast_verbose("Using latest request as basis request\n");
3462                         /* This call is no longer outgoing if it ever was */
3463                         p->outgoing = 0;
3464                         copy_request(&p->initreq, req);
3465                         check_via(p, req);
3466                         if (strlen(get_header(req, "Content-Type"))) {
3467                                 if (process_sdp(p, req))
3468                                         return -1;
3469                         } else {
3470                                 p->capability = capability;
3471                                 ast_log(LOG_DEBUG, "Hm....  No sdp for the moemnt\n");
3472                         }
3473                 } else if (sipdebug)
3474                         ast_verbose("Ignoring this request\n");
3475                 if (!p->lastinvite) {
3476                         /* Handle authentication if this is our first invite */
3477                         res = check_user(p, req, cmd, e);
3478                         if (res) {
3479                                 if (res < 0) {
3480                                         ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
3481                                         sip_destroy(p);
3482                                 }
3483                                 return 0;
3484                         }
3485                         /* Initialize the context if it hasn't been already */
3486                         if (!strlen(p->context))
3487                                 strncpy(p->context, context, sizeof(p->context) - 1);
3488                         if ((res = get_destination(p, NULL))) {
3489                                 if (res < 0)
3490                                         transmit_response(p, "404 Not Found", req);
3491                                 else
3492                                         transmit_response(p, "484 Address Incomplete", req);
3493                                 sip_destroy(p);
3494                                 p = NULL;
3495                                 c = NULL;
3496                         } else {
3497                                 /* If no extension was specified, use the s one */
3498                                 if (!strlen(p->exten))
3499                                         strncpy(p->exten, "s", sizeof(p->exten) - 1);
3500                                 /* Initialize tag */    
3501                                 p->tag = rand();
3502                                 /* First invitation */
3503                                 c = sip_new(p, AST_STATE_DOWN, strlen(p->username) ? p->username : NULL);
3504                         }
3505                         
3506                 } else 
3507                         c = p->owner;
3508                 if (!ignore && p)
3509                         p->lastinvite = seqno;
3510                 if (c) {
3511                         switch(c->_state) {
3512                         case AST_STATE_DOWN:
3513                                 transmit_response(p, "100 Trying", req);
3514                                 ast_setstate(c, AST_STATE_RING);
3515                                 if (ast_pbx_start(c)) {
3516                                         ast_log(LOG_WARNING, "Failed to start PBX :(\n");
3517                                         ast_hangup(c);
3518                                         transmit_response(p, "503 Unavailable", req);
3519                                         sip_destroy(p);
3520                                 }
3521                                 break;
3522                         case AST_STATE_RING:
3523                                 transmit_response(p, "100 Trying", req);
3524                                 break;
3525                         case AST_STATE_RINGING:
3526                                 transmit_response(p, "180 Ringing", req);