824aa7c8af5ee2a8a1a750c93799ae44e614f7b2
[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 char *getsipuri(char *header);
311
312 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
313 {
314         int res;
315         if (p->nat)
316             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
317         else
318             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
319         if (res != len) {
320                 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));
321         }
322         return res;
323 }
324
325 static int send_response(struct sip_pvt *p, struct sip_request *req)
326 {
327         int res;
328         if (sipdebug) {
329                 if (p->nat)
330                         ast_verbose("Transmitting (NAT):\n%s\n to %s:%d\n", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
331                 else
332                         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));
333         }
334         res = __sip_xmit(p, req->data, req->len);
335         if (res > 0)
336                 res = 0;
337         return res;
338 }
339
340 static int send_request(struct sip_pvt *p, struct sip_request *req)
341 {
342         int res;
343         if (sipdebug) {
344                 if (p->nat)
345                         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));
346                 else
347                         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));
348         }
349         res = __sip_xmit(p, req->data, req->len);
350         return res;
351 }
352
353 static char *ditch_braces(char *tmp)
354 {
355         char *c = tmp;
356         char *n;
357         c = tmp;
358         if ((n = strchr(tmp, '<')) ) {
359                 c = n + 1;
360                 while(*c && *c != '>') c++;
361                 if (*c != '>') {
362                         ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
363                 } else {
364                         *c = '\0';
365                 }
366                 return n+1;
367         }
368         return c;
369 }
370
371 static int sip_sendtext(struct ast_channel *ast, char *text)
372 {
373         struct sip_pvt *p = ast->pvt->pvt;
374         if (sipdebug) 
375                 ast_verbose("Sending text %s on %s\n", text, ast->name);
376         if (!p)
377                 return -1;
378         if (!text || !strlen(text))
379                 return 0;
380         if (sipdebug)
381                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
382         transmit_message_with_text(p, text);
383         return 0;       
384 }
385
386 static int create_addr(struct sip_pvt *r, char *peer)
387 {
388         struct hostent *hp;
389         struct sip_peer *p;
390         int found=0;
391         r->sa.sin_family = AF_INET;
392         ast_pthread_mutex_lock(&peerl.lock);
393         p = peerl.peers;
394         while(p) {
395                 if (!strcasecmp(p->name, peer)) {
396                         found++;
397                         r->capability = p->capability;
398                         r->nonCodecCapability = p->nonCodecCapability;
399                         r->nat = p->nat;
400                         if (r->rtp) {
401                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
402                                 ast_rtp_setnat(r->rtp, r->nat);
403                         }
404                         strncpy(r->peername, p->username, sizeof(r->peername)-1);
405                         strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
406                         strncpy(r->username, p->username, sizeof(r->username)-1);
407                         r->insecure = p->insecure;
408                         r->canreinvite = p->canreinvite;
409                         r->maxtime = p->maxms;
410                         if (p->dtmfmode) {
411                                 r->dtmfmode = p->dtmfmode;
412                                 if (r->dtmfmode & SIP_DTMF_RFC2833)
413                                         r->nonCodecCapability |= AST_RTP_DTMF;
414                                 else
415                                         r->nonCodecCapability &= ~AST_RTP_DTMF;
416                         }
417                         strncpy(r->context, p->context,sizeof(r->context)-1);
418                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
419                                 (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
420                                 if (p->addr.sin_addr.s_addr) {
421                                         r->sa.sin_addr = p->addr.sin_addr;
422                                         r->sa.sin_port = p->addr.sin_port;
423                                 } else {
424                                         r->sa.sin_addr = p->defaddr.sin_addr;
425                                         r->sa.sin_port = p->defaddr.sin_port;
426                                 }
427                                 memcpy(&r->recv, &r->sa, sizeof(r->recv));
428                                 break;
429                         }
430                 }
431                 p = p->next;
432         }
433         ast_pthread_mutex_unlock(&peerl.lock);
434         if (!p && !found) {
435                 hp = gethostbyname(peer);
436                 if (hp) {
437                         memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
438                         r->sa.sin_port = htons(DEFAULT_SIP_PORT);
439                         memcpy(&r->recv, &r->sa, sizeof(r->recv));
440                         return 0;
441                 } else {
442                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
443                         return -1;
444                 }
445         } else if (!p)
446                 return -1;
447         else
448                 return 0;
449 }
450
451 static int auto_congest(void *nothing)
452 {
453         struct sip_pvt *p = nothing;
454         ast_pthread_mutex_lock(&p->lock);
455         p->initid = -1;
456         if (p->owner) {
457                 if (!pthread_mutex_trylock(&p->owner->lock)) {
458                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
459                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
460                         ast_pthread_mutex_unlock(&p->owner->lock);
461                 }
462         }
463         ast_pthread_mutex_unlock(&p->lock);
464         return 0;
465 }
466
467 static void sip_prefs_free(void)
468 {
469         struct sip_codec_pref *cur, *next;
470         cur = prefs;
471         while(cur) {
472                 next = cur->next;
473                 free(cur);
474                 cur = next;
475         }
476         prefs = NULL;
477 }
478
479 static void sip_pref_remove(int format)
480 {
481         struct sip_codec_pref *cur, *prev=NULL;
482         cur = prefs;
483         while(cur) {
484                 if (cur->codec == format) {
485                         if (prev)
486                                 prev->next = cur->next;
487                         else
488                                 prefs = cur->next;
489                         free(cur);
490                         return;
491                 }
492                 prev = cur;
493                 cur = cur->next;
494         }
495 }
496
497 static int sip_pref_append(int format)
498 {
499         struct sip_codec_pref *cur, *tmp;
500         sip_pref_remove(format);
501         tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
502         if (!tmp)
503                 return -1;
504         memset(tmp, 0, sizeof(struct sip_codec_pref));
505         tmp->codec = format;
506         if (prefs) {
507                 cur = prefs;
508                 while(cur->next)
509                         cur = cur->next;
510                 cur->next = tmp;
511         } else
512                 prefs = tmp;
513         return 0;
514 }
515
516 static int sip_codec_choose(int formats)
517 {
518         struct sip_codec_pref *cur;
519         cur = prefs;
520         while(cur) {
521                 if (formats & cur->codec)
522                         return cur->codec;
523                 cur = cur->next;
524         }
525         return ast_best_codec(formats);
526 }
527
528 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
529 {
530         int res;
531         struct sip_pvt *p;
532         char *vxml_url = NULL;
533         struct varshead *headp;
534         struct ast_var_t *current;
535         
536         p = ast->pvt->pvt;
537         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
538                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
539                 return -1;
540         }
541
542         /* Check whether there is a VXML_URL variable */
543         headp=&ast->varshead;
544         AST_LIST_TRAVERSE(headp,current,entries) {
545                 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
546                 {
547                         vxml_url = ast_var_value(current);
548                         break;
549                 }
550         }
551         
552         res = 0;
553         p->outgoing = 1;
554         transmit_invite(p, "INVITE", 1, NULL, vxml_url);
555         if (p->maxtime) {
556                 /* Initialize auto-congest time */
557                 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
558         }
559         return res;
560 }
561
562 static void __sip_destroy(struct sip_pvt *p, int lockowner)
563 {
564         struct sip_pvt *cur, *prev = NULL;
565         if (p->rtp) {
566                 ast_rtp_destroy(p->rtp);
567         }
568         /* Unlink us from the owner if we have one */
569         if (p->owner) {
570                 if (lockowner)
571                         ast_pthread_mutex_lock(&p->owner->lock);
572                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
573                 p->owner->pvt->pvt = NULL;
574                 if (lockowner)
575                         ast_pthread_mutex_unlock(&p->owner->lock);
576         }
577         cur = iflist;
578         while(cur) {
579                 if (cur == p) {
580                         if (prev)
581                                 prev->next = cur->next;
582                         else
583                                 iflist = cur->next;
584                         break;
585                 }
586                 prev = cur;
587                 cur = cur->next;
588         }
589         if (!cur) {
590                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
591         } else {
592                 if (p->initid > -1)
593                         ast_sched_del(sched, p->initid);
594                 free(p);
595         }
596 }
597 static void sip_destroy(struct sip_pvt *p)
598 {
599         ast_pthread_mutex_lock(&iflock);
600         __sip_destroy(p, 1);
601         ast_pthread_mutex_unlock(&iflock);
602 }
603
604 /* Interface lookup code courtesy Tilghman of DrunkCoder.com.  Thanks! */
605
606 struct my_ifreq {
607     union
608       {
609         char ifrn_name[IFNAMSIZ];       /* Interface name, e.g. "en0".  */
610       } ifr_ifrn;
611
612     union
613       {
614         struct sockaddr_in ifru_addr;
615         char ifru_data[512];
616       } ifr_ifru;
617 };
618
619 struct in_addr *lookup_iface(char *iface) {
620         int mysock;
621         int res;
622         static struct  my_ifreq ifreq;
623         memset(&ifreq, 0, sizeof(ifreq));
624         strncpy(ifreq.ifr_ifrn.ifrn_name,iface,sizeof(ifreq.ifr_ifrn.ifrn_name) - 1);
625
626         mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
627         res = ioctl(mysock,SIOCGIFADDR,&ifreq);
628         
629         close(mysock);
630         if (res < 0) {
631                 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
632                 return &__ourip;
633         }
634         return( (struct in_addr *) &ifreq.ifr_ifru.ifru_addr.sin_addr );
635 }
636
637 static struct in_addr *myaddrfor(struct in_addr *them)
638 {
639         FILE *PROC;
640         struct in_addr *temp = NULL;
641         unsigned int remote_ip;
642         char line[256];
643         remote_ip = them->s_addr;
644         
645         PROC = fopen("/proc/net/route","r");
646         if (!PROC) {
647                 /* If /proc/net/route doesn't exist, fall back to the old method */
648                 return &__ourip;
649         }
650         /* First line contains headers */
651         fgets(line,sizeof(line),PROC);
652
653         while (!feof(PROC)) {
654                 char iface[8];
655                 unsigned int dest, gateway, mask;
656                 int i,aoffset;
657                 char *fields[40];
658
659                 fgets(line,sizeof(line),PROC);
660
661                 aoffset = 0;
662                 for (i=0;i<sizeof(line);i++) {
663                         char *boffset;
664
665                         fields[aoffset++] = line + i;
666                         boffset = strchr(line + i,'\t');
667                         if (boffset == NULL) {
668                                 /* Exit loop */
669                                 break;
670                         } else {
671                                 *boffset = '\0';
672                                 i = boffset - line;
673                         }
674                 }
675
676                 sscanf(fields[0],"%s",iface);
677                 sscanf(fields[1],"%x",&dest);
678                 sscanf(fields[2],"%x",&gateway);
679                 sscanf(fields[7],"%x",&mask);
680 #if 0
681                 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
682 #endif          
683                 if (((remote_ip & mask) ^ dest) == 0) {
684                         if (sipdebug)
685                                 ast_verbose("Interface is %s\n",iface);
686                         temp = lookup_iface(iface);
687                         if (sipdebug)
688                                 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
689                         break;
690                 }
691         }
692         fclose(PROC);
693         if (!temp) {
694                 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s.  Using default\n", inet_ntoa(*them));
695                 temp = &__ourip;
696         }
697         return temp;
698 }
699
700
701 static int sip_hangup(struct ast_channel *ast)
702 {
703         struct sip_pvt *p = ast->pvt->pvt;
704         int needcancel = 0;
705         if (option_debug)
706                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
707         if (!ast->pvt->pvt) {
708                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
709                 return 0;
710         }
711         ast_pthread_mutex_lock(&p->lock);
712         /* Determine how to disconnect */
713         if (p->owner != ast) {
714                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
715                 ast_pthread_mutex_unlock(&p->lock);
716                 return 0;
717         }
718         if (!ast || (ast->_state != AST_STATE_UP))
719                 needcancel = 1;
720         /* Disconnect */
721         p = ast->pvt->pvt;
722         if (p->vad) {
723             ast_dsp_free(p->vad);
724         }
725         p->owner = NULL;
726         ast->pvt->pvt = NULL;
727
728         p->needdestroy = 1;
729         /* Start the process if it's not already started */
730         if (!p->alreadygone && strlen(p->initreq.data)) {
731                 if (needcancel) {
732                         transmit_request(p, "CANCEL", 0);
733                 } else {
734                         /* Send a hangup */
735                         transmit_request(p, "BYE", 1);
736                 }
737         }
738         ast_pthread_mutex_unlock(&p->lock);
739         return 0;
740 }
741
742 static int sip_answer(struct ast_channel *ast)
743 {
744         int res = 0,fmt;
745         char *codec;
746         struct sip_pvt *p = ast->pvt->pvt;
747
748         
749         if (ast->_state != AST_STATE_UP) {
750         
751         
752         
753                 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
754                 if (codec) {
755                         ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
756                         fmt=ast_getformatbyname(codec);
757                         if (fmt) {
758                                 p->capability=fmt;
759                         } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
760                 }
761
762                 ast_setstate(ast, AST_STATE_UP);
763                 if (option_debug)
764                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
765                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq);
766         }
767         return res;
768 }
769
770 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
771 {
772         struct sip_pvt *p = ast->pvt->pvt;
773         int res = 0;
774         if (frame->frametype != AST_FRAME_VOICE) {
775                 if (frame->frametype == AST_FRAME_IMAGE)
776                         return 0;
777                 else {
778                         ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
779                         return 0;
780                 }
781         } else {
782                 if (!(frame->subclass & ast->nativeformats)) {
783                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
784                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
785                         return -1;
786                 }
787         }
788         if (p) {
789                 ast_pthread_mutex_lock(&p->lock);
790                 if (p->rtp) {
791                         if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
792                                 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq);
793                                 p->progress = 1;
794                         }
795                         res =  ast_rtp_write(p->rtp, frame);
796                 }
797                 ast_pthread_mutex_unlock(&p->lock);
798         }
799         return res;
800 }
801
802 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
803 {
804         struct sip_pvt *p = newchan->pvt->pvt;
805         ast_pthread_mutex_lock(&p->lock);
806         if (p->owner != oldchan) {
807                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
808                 ast_pthread_mutex_unlock(&p->lock);
809                 return -1;
810         }
811         p->owner = newchan;
812         ast_pthread_mutex_unlock(&p->lock);
813         return 0;
814 }
815
816 static int sip_senddigit(struct ast_channel *ast, char digit)
817 {
818         struct sip_pvt *p = ast->pvt->pvt;
819         if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
820                 transmit_info_with_digit(p, digit);
821         }
822         if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
823                 ast_rtp_senddigit(p->rtp, digit);
824         }
825         /* If in-band DTMF is desired, send that */
826         if (p->dtmfmode & SIP_DTMF_INBAND)
827                 return -1;
828         return 0;
829 }
830
831 static int sip_indicate(struct ast_channel *ast, int condition)
832 {
833         struct sip_pvt *p = ast->pvt->pvt;
834         switch(condition) {
835         case AST_CONTROL_RINGING:
836                 if (ast->_state == AST_STATE_RING) {
837                         transmit_response(p, "180 Ringing", &p->initreq);
838                         break;
839                 }
840                 return -1;
841         case AST_CONTROL_BUSY:
842                 if (ast->_state != AST_STATE_UP) {
843                         transmit_response(p, "600 Busy everywhere", &p->initreq);
844                         p->alreadygone = 1;
845                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
846                         break;
847                 }
848                 return -1;
849         case AST_CONTROL_CONGESTION:
850                 if (ast->_state != AST_STATE_UP) {
851                         transmit_response(p, "486 Busy here", &p->initreq);
852                         p->alreadygone = 1;
853                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
854                         break;
855                 }
856                 return -1;
857         case -1:
858                 return -1;
859         default:
860                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
861                 return -1;
862         }
863         return 0;
864 }
865
866
867 #if 0
868 static int sip_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
869 {
870         struct sip_pvt *p0, *p1;
871         struct ast_frame *f;
872         struct ast_channel *who, *cs[3];
873         int to;
874
875         /* if need DTMF, cant native bridge */
876         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
877                 return -2;
878         ast_pthread_mutex_lock(&c0->lock);
879         ast_pthread_mutex_lock(&c1->lock);
880         p0 = c0->pvt->pvt;
881         p1 = c1->pvt->pvt;
882         ast_log(LOG_DEBUG, "Reinvite? %s: %s, %s: %s\n", c0->name, p0->canreinvite ? "yes" : "no", c1->name, p1->canreinvite ? "yes" : "no");
883         if (!p0->canreinvite || !p1->canreinvite) {
884                 /* Not gonna support reinvite */
885                 ast_pthread_mutex_unlock(&c0->lock);
886                 ast_pthread_mutex_unlock(&c1->lock);
887                 return -2;
888         }
889         transmit_reinvite_with_sdp(p0, p1->rtp);
890         transmit_reinvite_with_sdp(p1, p0->rtp);
891         ast_pthread_mutex_unlock(&c0->lock);
892         ast_pthread_mutex_unlock(&c1->lock);
893         cs[0] = c0;
894         cs[1] = c1;
895         cs[2] = NULL;
896         for (;;) {
897                 if ((c0->pvt->pvt != p0)  ||
898                         (c1->pvt->pvt != p1) ||
899                         (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
900                                 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
901                                 if (c0->pvt->pvt == p0)
902                                         transmit_reinvite_with_sdp(p0, NULL);
903                                 if (c1->pvt->pvt == p1)
904                                         transmit_reinvite_with_sdp(p1, NULL);
905                                 /* Tell it to try again later */
906                                 return -3;
907                 }
908                 to = -1;
909                 who = ast_waitfor_n(cs, 2, &to);
910                 if (!who) {
911                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
912                         continue;
913                 }
914                 f = ast_read(who);
915                 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
916                                    (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
917                                ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
918                         *fo = f;
919                         *rc = who;
920                         ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
921                         if (c0->pvt->pvt == p0 && !c0->_softhangup)
922                                 transmit_reinvite_with_sdp(p0, NULL);
923                         if (c1->pvt->pvt == p1 && !c1->_softhangup)
924                                 transmit_reinvite_with_sdp(p1, NULL);
925                         /* That's all we needed */
926                         return 0;
927                 } else 
928                         ast_frfree(f);
929                 /* Swap priority not that it's a big deal at this point */
930                 cs[2] = cs[0];
931                 cs[0] = cs[1];
932                 cs[1] = cs[2];
933                 
934         }
935         return -1;
936 }
937 #endif
938
939 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
940 {
941         struct ast_channel *tmp;
942         int fmt;
943         tmp = ast_channel_alloc(1);
944         if (tmp) {
945                 /* Select our native format based on codec preference until we receive
946                    something from another device to the contrary. */
947                 if (i->capability)
948                         tmp->nativeformats = sip_codec_choose(i->capability);
949                 else 
950                         tmp->nativeformats = sip_codec_choose(capability);
951                 fmt = ast_best_codec(tmp->nativeformats);
952                 if (title)
953                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
954                 else
955                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
956                 tmp->type = type;
957                 if (i->dtmfmode & SIP_DTMF_INBAND) {
958                     i->vad = ast_dsp_new();
959                     ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
960                 }
961                 tmp->fds[0] = ast_rtp_fd(i->rtp);
962                 ast_setstate(tmp, state);
963                 if (state == AST_STATE_RING)
964                         tmp->rings = 1;
965                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
966                 tmp->writeformat = fmt;
967                 tmp->pvt->rawwriteformat = fmt;
968                 tmp->readformat = fmt;
969                 tmp->pvt->rawreadformat = fmt;
970                 tmp->pvt->pvt = i;
971                 tmp->pvt->send_text = sip_sendtext;
972                 tmp->pvt->call = sip_call;
973                 tmp->pvt->hangup = sip_hangup;
974                 tmp->pvt->answer = sip_answer;
975                 tmp->pvt->read = sip_read;
976                 tmp->pvt->write = sip_write;
977                 tmp->pvt->indicate = sip_indicate;
978                 tmp->pvt->fixup = sip_fixup;
979                 tmp->pvt->send_digit = sip_senddigit;
980                 tmp->pvt->bridge = ast_rtp_bridge;
981                 if (strlen(i->language))
982                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
983                 i->owner = tmp;
984                 ast_pthread_mutex_lock(&usecnt_lock);
985                 usecnt++;
986                 ast_pthread_mutex_unlock(&usecnt_lock);
987                 ast_update_use_count();
988                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
989                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
990                 if (strlen(i->callerid))
991                         tmp->callerid = strdup(i->callerid);
992                 tmp->priority = 1;
993                 if (state != AST_STATE_DOWN) {
994                         if (ast_pbx_start(tmp)) {
995                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
996                                 ast_hangup(tmp);
997                                 tmp = NULL;
998                         }
999                 }
1000         } else
1001                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1002         return tmp;
1003 }
1004
1005 static struct cfalias {
1006         char *fullname;
1007         char *shortname;
1008 } aliases[] = {
1009         { "Content-Type", "c" },
1010         { "Content-Encoding", "e" },
1011         { "From", "f" },
1012         { "Call-ID", "i" },
1013         { "Contact", "m" },
1014         { "Content-Length", "l" },
1015         { "Subject", "s" },
1016         { "To", "t" },
1017         { "Via", "v" },
1018 };
1019
1020 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1021   if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1022     char* r = line + nameLen + 1;
1023     while (*r && (*r < 33)) ++r;
1024     return r;
1025   }
1026
1027   return "";
1028 }
1029
1030 static char *get_sdp(struct sip_request *req, char *name) {
1031   int x;
1032   int len = strlen(name);
1033   char *r;
1034
1035   for (x=0; x<req->lines; x++) {
1036     r = get_sdp_by_line(req->line[x], name, len);
1037     if (r[0] != '\0') return r;
1038   }
1039   return "";
1040 }
1041
1042 static void sdpLineNum_iterator_init(int* iterator) {
1043   *iterator = 0;
1044 }
1045
1046 static char* get_sdp_iterate(int* iterator,
1047                              struct sip_request *req, char *name) {
1048   int len = strlen(name);
1049   char *r;
1050   while (*iterator < req->lines) {
1051     r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1052     if (r[0] != '\0') return r;
1053   }
1054   return "";
1055 }
1056
1057 static char *__get_header(struct sip_request *req, char *name, int *start)
1058 {
1059         int x;
1060         int len = strlen(name);
1061         char *r;
1062         for (x=*start;x<req->headers;x++) {
1063                 if (!strncasecmp(req->header[x], name, len) && 
1064                                 (req->header[x][len] == ':')) {
1065                                         r = req->header[x] + len + 1;
1066                                         while(*r && (*r < 33))
1067                                                         r++;
1068                                         *start = x+1;
1069                                         return r;
1070                 }
1071         }
1072         /* Try aliases */
1073         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
1074                 if (!strcasecmp(aliases[x].fullname, name))
1075                         return __get_header(req, aliases[x].shortname, start);
1076
1077         /* Don't return NULL, so get_header is always a valid pointer */
1078         return "";
1079 }
1080
1081 static char *get_header(struct sip_request *req, char *name)
1082 {
1083         int start = 0;
1084         return __get_header(req, name, &start);
1085 }
1086
1087 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1088 {
1089         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
1090         struct ast_frame *f;
1091         static struct ast_frame null_frame = { AST_FRAME_NULL, };
1092         f = ast_rtp_read(p->rtp);
1093         /* Don't send RFC2833 if we're not supposed to */
1094         if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1095                 return &null_frame;
1096         if (p->owner) {
1097                 /* We already hold the channel lock */
1098                 if (f->frametype == AST_FRAME_VOICE) {
1099                         if (f->subclass != p->owner->nativeformats) {
1100                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1101                                 p->owner->nativeformats = f->subclass;
1102                                 ast_set_read_format(p->owner, p->owner->readformat);
1103                                 ast_set_write_format(p->owner, p->owner->writeformat);
1104                         }
1105             if (p->dtmfmode & SIP_DTMF_INBAND) {
1106                    f = ast_dsp_process(p->owner,p->vad,f,0);
1107             }
1108                 }
1109         }
1110         return f;
1111 }
1112
1113 static struct ast_frame *sip_read(struct ast_channel *ast)
1114 {
1115         struct ast_frame *fr;
1116         struct sip_pvt *p = ast->pvt->pvt;
1117         ast_pthread_mutex_lock(&p->lock);
1118         fr = sip_rtp_read(p);
1119         ast_pthread_mutex_unlock(&p->lock);
1120         return fr;
1121 }
1122
1123 static void build_callid(char *callid, int len, struct in_addr ourip)
1124 {
1125         int res;
1126         int val;
1127         int x;
1128         for (x=0;x<4;x++) {
1129                 val = rand();
1130                 res = snprintf(callid, len, "%08x", val);
1131                 len -= res;
1132                 callid += res;
1133         }
1134         /* It's not important that we really use our right IP here... */
1135         snprintf(callid, len, "@%s", inet_ntoa(ourip));
1136 }
1137
1138 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1139 {
1140         struct sip_pvt *p;
1141
1142         p = malloc(sizeof(struct sip_pvt));
1143         if (!p)
1144                 return NULL;
1145         /* Keep track of stuff */
1146         memset(p, 0, sizeof(struct sip_pvt));
1147         p->initid = -1;
1148         p->rtp = ast_rtp_new(NULL, NULL);
1149         p->branch = rand();     
1150         p->tag = rand();
1151         /* Start with 101 instead of 1 */
1152         p->ocseq = 101;
1153         if (!p->rtp) {
1154                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1155                 free(p);
1156                 return NULL;
1157         }
1158         ast_rtp_settos(p->rtp, tos);
1159         if (useglobalnat && sin) {
1160                 /* Setup NAT structure according to global settings if we have an address */
1161                 p->nat = globalnat;
1162                 memcpy(&p->recv, sin, sizeof(p->recv));
1163                 ast_rtp_setnat(p->rtp, p->nat);
1164         }
1165         ast_pthread_mutex_init(&p->lock);
1166 #if 0
1167         ast_rtp_set_data(p->rtp, p);
1168         ast_rtp_set_callback(p->rtp, rtpready);
1169 #endif  
1170         if (sin) {
1171                 memcpy(&p->sa, sin, sizeof(p->sa));
1172                 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
1173         } else {
1174                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1175         }
1176         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1177         if (!callid)
1178                 build_callid(p->callid, sizeof(p->callid), p->ourip);
1179         else
1180                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1181         /* Assume reinvite OK */
1182         p->canreinvite = 1;
1183         p->dtmfmode = globaldtmfmode;
1184         if (p->dtmfmode & SIP_DTMF_RFC2833)
1185                 p->nonCodecCapability |= AST_RTP_DTMF;
1186         /* Add to list */
1187         ast_pthread_mutex_lock(&iflock);
1188         p->next = iflist;
1189         iflist = p;
1190         ast_pthread_mutex_unlock(&iflock);
1191         if (option_debug)
1192                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1193         return p;
1194 }
1195
1196 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1197 {
1198         struct sip_pvt *p;
1199         char *callid;
1200         callid = get_header(req, "Call-ID");
1201         if (!strlen(callid)) {
1202                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1203                 return NULL;
1204         }
1205         ast_pthread_mutex_lock(&iflock);
1206         p = iflist;
1207         while(p) {
1208                 if (!strcmp(p->callid, callid)) {
1209                         /* Found the call */
1210 #if 0
1211                         if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1212                             (p->sa.sin_port != sin->sin_port))) {
1213                                         char orig[80];
1214                                         char new[80];
1215                                         snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1216                                         snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1217                                         ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1218                                         ast_pthread_mutex_unlock(&iflock);
1219                                         return NULL;
1220                         }
1221 #endif
1222                         ast_pthread_mutex_unlock(&iflock);
1223                         return p;
1224                 }
1225                 p = p->next;
1226         }
1227         ast_pthread_mutex_unlock(&iflock);
1228         return sip_alloc(callid, sin, 1);
1229 }
1230
1231 static int sip_register(char *value, int lineno)
1232 {
1233         struct sip_registry *reg;
1234         char copy[256] = "";
1235         char *username, *hostname, *secret;
1236         char *porta;
1237         char *contact;
1238         char *stringp=NULL;
1239         
1240         struct hostent *hp;
1241         if (!value)
1242                 return -1;
1243         strncpy(copy, value, sizeof(copy)-1);
1244         stringp=copy;
1245         username = stringp;
1246         hostname = strrchr(stringp, '@');
1247         if (hostname) {
1248                 *hostname = '\0';
1249                 hostname++;
1250         }
1251         if (!hostname) {
1252                 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1253                 return -1;
1254         }
1255         stringp=username;
1256         username = strsep(&stringp, ":");
1257         secret = strsep(&stringp, ":");
1258         stringp = hostname;
1259         hostname = strsep(&stringp, "/");
1260         contact = strsep(&stringp, "/");
1261         if (!contact || !strlen(contact))
1262                 contact = "s";
1263         stringp=hostname;
1264         hostname = strsep(&stringp, ":");
1265         porta = strsep(&stringp, ":");
1266         
1267         if (porta && !atoi(porta)) {
1268                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1269                 return -1;
1270         }
1271         hp = gethostbyname(hostname);
1272         if (!hp) {
1273                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1274                 return -1;
1275         }
1276         reg = malloc(sizeof(struct sip_registry));
1277         if (reg) {
1278                 memset(reg, 0, sizeof(struct sip_registry));
1279                 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1280                 strncpy(reg->username, username, sizeof(reg->username)-1);
1281                 if (secret)
1282                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1283                 reg->expire = -1;
1284                 reg->refresh = default_expirey;
1285                 reg->addr.sin_family = AF_INET;
1286                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
1287                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1288                 reg->next = registrations;
1289                 reg->callid_valid = 0;
1290                 registrations = reg;
1291         } else {
1292                 ast_log(LOG_ERROR, "Out of memory\n");
1293                 return -1;
1294         }
1295         return 0;
1296 }
1297
1298 static void parse(struct sip_request *req)
1299 {
1300         /* Divide fields by NULL's */
1301         char *c;
1302         int f = 0;
1303         c = req->data;
1304
1305         /* First header starts immediately */
1306         req->header[f] = c;
1307         while(*c) {
1308                 if (*c == '\n') {
1309                         /* We've got a new header */
1310                         *c = 0;
1311
1312 #if 0
1313                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1314 #endif                  
1315                         if (!strlen(req->header[f])) {
1316                                 /* Line by itself means we're now in content */
1317                                 c++;
1318                                 break;
1319                         }
1320                         if (f >= SIP_MAX_HEADERS - 1) {
1321                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1322                         } else
1323                                 f++;
1324                         req->header[f] = c + 1;
1325                 } else if (*c == '\r') {
1326                         /* Ignore but eliminate \r's */
1327                         *c = 0;
1328                 }
1329                 c++;
1330         }
1331         /* Check for last header */
1332         if (strlen(req->header[f])) 
1333                 f++;
1334         req->headers = f;
1335         /* Now we process any mime content */
1336         f = 0;
1337         req->line[f] = c;
1338         while(*c) {
1339                 if (*c == '\n') {
1340                         /* We've got a new line */
1341                         *c = 0;
1342 #if 0
1343                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1344 #endif                  
1345                         if (f >= SIP_MAX_LINES - 1) {
1346                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1347                         } else
1348                                 f++;
1349                         req->line[f] = c + 1;
1350                 } else if (*c == '\r') {
1351                         /* Ignore and eliminate \r's */
1352                         *c = 0;
1353                 }
1354                 c++;
1355         }
1356         /* Check for last line */
1357         if (strlen(req->line[f])) 
1358                 f++;
1359         req->lines = f;
1360         if (sipdebug)
1361                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1362         if (*c) 
1363                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1364 }
1365
1366 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1367 {
1368         char *m;
1369         char *c;
1370         char *a;
1371         char host[258];
1372         int len = -1;
1373         int portno;
1374         int peercapability, peerNonCodecCapability;
1375         struct sockaddr_in sin;
1376         char *codecs;
1377         struct hostent *hp;
1378         int codec;
1379         int iterator;
1380
1381         /* Get codec and RTP info from SDP */
1382         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1383                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1384                 return -1;
1385         }
1386         m = get_sdp(req, "m");
1387         c = get_sdp(req, "c");
1388         if (!strlen(m) || !strlen(c)) {
1389                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1390                 return -1;
1391         }
1392         if (sscanf(c, "IN IP4 %256s", host) != 1) {
1393                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1394                 return -1;
1395         }
1396         /* XXX This could block for a long time, and block the main thread! XXX */
1397         hp = gethostbyname(host);
1398         if (!hp) {
1399                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1400                 return -1;
1401         }
1402         if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1403                 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
1404                 return -1;
1405         }
1406         sin.sin_family = AF_INET;
1407         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1408         sin.sin_port = htons(portno);
1409         if (p->rtp)
1410                 ast_rtp_set_peer(p->rtp, &sin);
1411 #if 0
1412         printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1413 #endif  
1414         // Scan through the RTP payload types specified in a "m=" line:
1415         ast_rtp_pt_clear(p->rtp);
1416         codecs = m + len;
1417         while(strlen(codecs)) {
1418                 if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
1419                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1420                         return -1;
1421                 }
1422                 ast_rtp_set_m_type(p->rtp, codec);
1423                 codecs += len;
1424         }
1425
1426         // Next, scan through each "a=rtpmap:" line, noting each
1427         // specified RTP payload type (with corresponding MIME subtype):
1428         sdpLineNum_iterator_init(&iterator);
1429         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1430           char* mimeSubtype = strdup(a); // ensures we have enough space
1431           if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1432           // Note: should really look at the 'freq' and '#chans' params too
1433           ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1434           free(mimeSubtype);
1435         }
1436
1437         // Now gather all of the codecs that were asked for:
1438         ast_rtp_get_current_formats(p->rtp,
1439                                 &peercapability, &peerNonCodecCapability);
1440         p->capability = capability & peercapability;
1441         p->nonCodecCapability = nonCodecCapability & peerNonCodecCapability;
1442         if (sipdebug) {
1443                 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1444                             capability, peercapability, p->capability);
1445                 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1446                             nonCodecCapability, peerNonCodecCapability,
1447                             p->nonCodecCapability);
1448         }
1449         if (!p->capability) {
1450                 ast_log(LOG_WARNING, "No compatible codecs!\n");
1451                 return -1;
1452         }
1453         if (p->owner) {
1454                 if (!(p->owner->nativeformats & p->capability)) {
1455                         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);
1456                         p->owner->nativeformats = sip_codec_choose(p->capability);
1457                         ast_set_read_format(p->owner, p->owner->readformat);
1458                         ast_set_write_format(p->owner, p->owner->writeformat);
1459                 }
1460                 if (p->owner->bridge) {
1461                         /* Turn on/off music on hold if we are holding/unholding */
1462                         if (sin.sin_addr.s_addr) {
1463                                 ast_moh_stop(p->owner->bridge);
1464                         } else {
1465                                 ast_moh_start(p->owner->bridge, NULL);
1466                         }
1467                 }
1468         }
1469         return 0;
1470         
1471 }
1472
1473 static int add_header(struct sip_request *req, char *var, char *value)
1474 {
1475         if (req->len >= sizeof(req->data) - 4) {
1476                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1477                 return -1;
1478         }
1479         if (req->lines) {
1480                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1481                 return -1;
1482         }
1483         req->header[req->headers] = req->data + req->len;
1484         snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1485         req->len += strlen(req->header[req->headers]);
1486         if (req->headers < SIP_MAX_HEADERS)
1487                 req->headers++;
1488         else {
1489                 ast_log(LOG_WARNING, "Out of header space\n");
1490                 return -1;
1491         }
1492         return 0;       
1493 }
1494
1495 static int add_blank_header(struct sip_request *req)
1496 {
1497         if (req->len >= sizeof(req->data) - 4) {
1498                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1499                 return -1;
1500         }
1501         if (req->lines) {
1502                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1503                 return -1;
1504         }
1505         req->header[req->headers] = req->data + req->len;
1506         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1507         req->len += strlen(req->header[req->headers]);
1508         if (req->headers < SIP_MAX_HEADERS)
1509                 req->headers++;
1510         else {
1511                 ast_log(LOG_WARNING, "Out of header space\n");
1512                 return -1;
1513         }
1514         return 0;       
1515 }
1516
1517 static int add_line(struct sip_request *req, char *line)
1518 {
1519         if (req->len >= sizeof(req->data) - 4) {
1520                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1521                 return -1;
1522         }
1523         if (!req->lines) {
1524                 /* Add extra empty return */
1525                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1526                 req->len += strlen(req->data + req->len);
1527         }
1528         req->line[req->lines] = req->data + req->len;
1529         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1530         req->len += strlen(req->line[req->lines]);
1531         if (req->lines < SIP_MAX_LINES)
1532                 req->lines++;
1533         else {
1534                 ast_log(LOG_WARNING, "Out of line space\n");
1535                 return -1;
1536         }
1537         return 0;       
1538 }
1539
1540 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1541 {
1542         char *tmp;
1543         tmp = get_header(orig, field);
1544         if (strlen(tmp)) {
1545                 /* Add what we're responding to */
1546                 return add_header(req, field, tmp);
1547         }
1548         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1549         return -1;
1550 }
1551
1552 #if 0
1553 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1554 {
1555         char *tmp;
1556         int start = 0;
1557         int copied = 0;
1558         for (;;) {
1559                 tmp = __get_header(orig, field, &start);
1560                 if (strlen(tmp)) {
1561                         /* Add what we're responding to */
1562                         add_header(req, field, tmp);
1563                         copied++;
1564                 } else
1565                         break;
1566         }
1567         if (!copied) {
1568                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1569                 return -1;
1570         }
1571         return 0;
1572 }
1573 #endif
1574 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1575 {
1576         char *tmp;
1577         int start = 0;
1578         int copied = 0;
1579         char new[256];
1580         for (;;) {
1581                 tmp = __get_header(orig, field, &start);
1582                 if (strlen(tmp)) {
1583                         if (!copied && p->nat) {
1584                                 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1585                                         snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1586                                 else
1587                                         snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1588                                 add_header(req, field, new);
1589                         } else {
1590                                 /* Add what we're responding to */
1591                                 add_header(req, field, tmp);
1592                         }
1593                         copied++;
1594                 } else
1595                         break;
1596         }
1597         if (!copied) {
1598                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1599                 return -1;
1600         }
1601         return 0;
1602 }
1603
1604 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1605 {
1606         /* Initialize a response */
1607         if (req->headers || req->len) {
1608                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1609                 return -1;
1610         }
1611         req->header[req->headers] = req->data + req->len;
1612         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1613         req->len += strlen(req->header[req->headers]);
1614         if (req->headers < SIP_MAX_HEADERS)
1615                 req->headers++;
1616         else
1617                 ast_log(LOG_WARNING, "Out of header space\n");
1618         return 0;
1619 }
1620
1621 static int init_req(struct sip_request *req, char *resp, char *recip)
1622 {
1623         /* Initialize a response */
1624         if (req->headers || req->len) {
1625                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1626                 return -1;
1627         }
1628         req->header[req->headers] = req->data + req->len;
1629         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1630         req->len += strlen(req->header[req->headers]);
1631         if (req->headers < SIP_MAX_HEADERS)
1632                 req->headers++;
1633         else
1634                 ast_log(LOG_WARNING, "Out of header space\n");
1635         return 0;
1636 }
1637
1638 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1639 {
1640         char newto[256] = "", *ot;
1641         memset(resp, 0, sizeof(*resp));
1642         init_resp(resp, msg, req);
1643         copy_via_headers(p, resp, req, "Via");
1644         copy_header(resp, req, "From");
1645         ot = get_header(req, "To");
1646         if (strlen(get_header(req, "Record-Route")))
1647                 copy_header(resp, req, "Record-Route");
1648         if (!strstr(ot, "tag=")) {
1649                 /* Add the proper tag if we don't have it already.  If they have specified
1650                    their tag, use it.  Otherwise, use our own tag */
1651                 if (strlen(p->theirtag))
1652                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1653                 else if (p->tag)
1654                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1655                 else
1656                         strncpy(newto, ot, sizeof(newto) - 1);
1657                 ot = newto;
1658         }
1659         add_header(resp, "To", ot);
1660         copy_header(resp, req, "Call-ID");
1661         copy_header(resp, req, "CSeq");
1662         add_header(resp, "User-Agent", "Asterisk PBX");
1663         if (p->expirey) {
1664                 /* For registration responses, we also need expirey and
1665                    contact info */
1666                 char tmp[80];
1667                 char contact[256];
1668                 char *c;
1669                 if ((c=getsipuri(ot))) {
1670                         snprintf(contact, sizeof(contact), "<%s@%s>", c, inet_ntoa(p->ourip));
1671                         free(c);
1672                 } else {
1673                         snprintf(contact, sizeof(contact), "<%s>", inet_ntoa(p->ourip));
1674                 }
1675                 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1676                 add_header(resp, "Expires", tmp);
1677                 add_header(resp, "Contact", contact);
1678         } else {
1679                 char contact[256];
1680                 /* XXX This isn't exactly right and it's implemented
1681                        very stupidly *sigh* XXX */
1682                 char *c;
1683                 if ((c=getsipuri(ot))) {
1684                         snprintf(contact, sizeof(contact), "<%s@%s>", c, inet_ntoa(p->ourip));
1685                         free(c);
1686                 } else {
1687                         snprintf(contact, sizeof(contact), "<%s>", inet_ntoa(p->ourip));
1688                 }
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         struct sip_peer *peer;
2628         char *of, from[256] = "", *c;
2629         int res = 0;
2630         char *t;
2631         /* Terminate URI */
2632         t = uri;
2633         while(*t && (*t > 32) && (*t != ';'))
2634                 t++;
2635         *t = '\0';
2636         of = get_header(req, "From");
2637         strncpy(from, of, sizeof(from) - 1);
2638         of = ditch_braces(from);
2639         if (strncmp(of, "sip:", 4)) {
2640                 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2641         } else
2642                 of += 4;
2643         /* Get just the username part */
2644         if ((c = strchr(of, '@')))
2645                 *c = '\0';
2646         if ((c = strchr(of, ':')))
2647                 *c = '\0';
2648         strncpy(p->callerid, of, sizeof(p->callerid) - 1);
2649         if (!strlen(of))
2650                         return 0;
2651         ast_pthread_mutex_lock(&userl.lock);
2652         user = userl.users;
2653         while(user) {
2654                 if (!strcasecmp(user->name, of)) {
2655                         p->nat = user->nat;
2656                         if (p->rtp) {
2657                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
2658                                 ast_rtp_setnat(p->rtp, p->nat);
2659                         }
2660                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri))) {
2661                                 strncpy(p->context, user->context, sizeof(p->context) - 1);
2662                                 if (strlen(user->callerid) && strlen(p->callerid)) 
2663                                         strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
2664                                 strncpy(p->username, user->name, sizeof(p->username) - 1);
2665                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)  -1);
2666                                 p->canreinvite = user->canreinvite;
2667                                 p->amaflags = user->amaflags;
2668                                 if (user->dtmfmode) {
2669                                         p->dtmfmode = user->dtmfmode;
2670                                         if (p->dtmfmode & SIP_DTMF_RFC2833)
2671                                                 p->nonCodecCapability |= AST_RTP_DTMF;
2672                                         else
2673                                                 p->nonCodecCapability &= ~AST_RTP_DTMF;
2674                                 }
2675                         }
2676                         break;
2677                 }
2678                 user = user->next;
2679         }
2680         ast_pthread_mutex_unlock(&userl.lock);
2681         if (!user) {
2682         /* If we didn't find a user match, check for peers */
2683                 ast_pthread_mutex_lock(&peerl.lock);
2684                 peer = peerl.peers;
2685                 while(peer) {
2686                         if (!memcmp(&peer->addr, &p->recv, sizeof(peer->addr))) {
2687                                 /* Take the peer */
2688                                 p->nat = peer->nat;
2689                                 if (p->rtp) {
2690                                         ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
2691                                         ast_rtp_setnat(p->rtp, p->nat);
2692                                 }
2693                                 p->canreinvite = peer->canreinvite;
2694                                 strncpy(p->username, peer->name, sizeof(p->username) - 1);
2695                                 if (peer->dtmfmode) {
2696                                         p->dtmfmode = peer->dtmfmode;
2697                                         if (p->dtmfmode & SIP_DTMF_RFC2833)
2698                                                 p->nonCodecCapability |= AST_RTP_DTMF;
2699                                         else
2700                                                 p->nonCodecCapability &= ~AST_RTP_DTMF;
2701                                 }
2702                                 break;
2703                         }
2704                         peer = peer->next;
2705                 }
2706                 ast_pthread_mutex_unlock(&peerl.lock);
2707         }
2708         return res;
2709 }
2710
2711 static int get_msg_text(char *buf, int len, struct sip_request *req)
2712 {
2713         int x;
2714         strcpy(buf, "");
2715         for (x=0;x<req->lines;x++) {
2716                 strncat(buf, req->line[x], len - strlen(buf) - 5);
2717                 strcat(buf, "\n");
2718         }
2719         return 0;
2720 }
2721
2722 static void receive_message(struct sip_pvt *p, struct sip_request *req)
2723 {
2724         char buf[1024];
2725         struct ast_frame f;
2726         if (get_msg_text(buf, sizeof(buf), req)) {
2727                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2728                 return;
2729         }
2730         if (p->owner) {
2731                 if (sipdebug)
2732                         ast_verbose("Message received: '%s'\n", buf);
2733                   memset(&f, 0, sizeof(f));
2734                   f.frametype = AST_FRAME_TEXT;
2735                   f.subclass = 0;
2736                   f.offset = 0;
2737                   f.data = buf;
2738                   f.datalen = strlen(buf);
2739                   ast_queue_frame(p->owner, &f, 1);
2740         }
2741 }
2742
2743 static int sip_show_users(int fd, int argc, char *argv[])
2744 {
2745 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
2746         struct sip_user *user;
2747         if (argc != 3) 
2748                 return RESULT_SHOWUSAGE;
2749         ast_pthread_mutex_lock(&userl.lock);
2750         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2751         for(user=userl.users;user;user=user->next) {
2752                 ast_cli(fd, FORMAT, user->name, user->secret, user->methods, 
2753                                 user->context,
2754                                 user->ha ? "Yes" : "No");
2755         }
2756         ast_pthread_mutex_unlock(&userl.lock);
2757         return RESULT_SUCCESS;
2758 #undef FORMAT
2759 }
2760
2761 static int sip_show_peers(int fd, int argc, char *argv[])
2762 {
2763 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s %-10s\n"
2764 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-8d %-10s\n"
2765         struct sip_peer *peer;
2766         char name[256] = "";
2767         if (argc != 3)
2768                 return RESULT_SHOWUSAGE;
2769         ast_pthread_mutex_lock(&peerl.lock);
2770         ast_cli(fd, FORMAT2, "Name/username", "Host", "   ", "Mask", "Port", "Status");
2771         for (peer = peerl.peers;peer;peer = peer->next) {
2772                 char nm[20] = "";
2773                 char status[20];
2774                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2775                 if (strlen(peer->username))
2776                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2777                 else
2778                         strncpy(name, peer->name, sizeof(name) - 1);
2779                 if (peer->maxms) {
2780                         if (peer->lastms < 0)
2781                                 strcpy(status, "UNREACHABLE");
2782                         else if (peer->lastms > peer->maxms) 
2783                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2784                         else if (peer->lastms) 
2785                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2786                         else 
2787                                 strcpy(status, "UNKNOWN");
2788                 } else 
2789                         strcpy(status, "Unmonitored");
2790                 ast_cli(fd, FORMAT, name, 
2791                                         peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2792                                         peer->dynamic ? "(D)" : "   ",
2793                                         nm,
2794                                         ntohs(peer->addr.sin_port), status);
2795         }
2796         ast_pthread_mutex_unlock(&peerl.lock);
2797         return RESULT_SUCCESS;
2798 #undef FORMAT
2799 #undef FORMAT2
2800 }
2801
2802 static char *regstate2str(int regstate)
2803 {
2804         switch(regstate) {
2805         case REG_STATE_UNREGISTERED:
2806                 return "Unregistered";
2807         case REG_STATE_REGSENT:
2808                 return "Request Sent";
2809         case REG_STATE_AUTHSENT:
2810                 return "Auth. Sent";
2811         case REG_STATE_REGISTERED:
2812                 return "Registered";
2813         case REG_STATE_REJECTED:
2814                 return "Rejected";
2815         case REG_STATE_TIMEOUT:
2816                 return "Timeout";
2817         case REG_STATE_NOAUTH:
2818                 return "No Authentication";
2819         default:
2820                 return "Unknown";
2821         }
2822 }
2823
2824 static int sip_show_registry(int fd, int argc, char *argv[])
2825 {
2826 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
2827 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
2828         struct sip_registry *reg;
2829         char host[80];
2830         char state[20];
2831         if (argc != 3)
2832                 return RESULT_SHOWUSAGE;
2833         ast_pthread_mutex_lock(&peerl.lock);
2834         ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
2835         for (reg = registrations;reg;reg = reg->next) {
2836                 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2837                 snprintf(state, sizeof(state), "%s", regstate2str(reg->regstate));
2838                 ast_cli(fd, FORMAT, host, 
2839                                         reg->username, state, reg->refresh, regstate2str(reg->regstate));
2840         }
2841         ast_pthread_mutex_unlock(&peerl.lock);
2842         return RESULT_SUCCESS;
2843 #undef FORMAT
2844 #undef FORMAT2
2845 }
2846
2847 static int sip_show_channels(int fd, int argc, char *argv[])
2848 {
2849 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %s\n"
2850 #define FORMAT  "%-15.15s  %-10.10s  %-11.11s  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %d\n"
2851         struct sip_pvt *cur;
2852         int numchans = 0;
2853         if (argc != 3)
2854                 return RESULT_SHOWUSAGE;
2855         ast_pthread_mutex_lock(&iflock);
2856         cur = iflist;
2857         ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2858         while (cur) {
2859                         ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr), 
2860                                                 strlen(cur->username) ? cur->username : "(None)", 
2861                                                 cur->callid, 
2862                                                 cur->ocseq, cur->icseq, 
2863                                                 0,
2864                                                 0,
2865                                                 cur->owner ? cur->owner->nativeformats : 0);
2866                 cur = cur->next;
2867                 numchans++;
2868         }
2869         ast_pthread_mutex_unlock(&iflock);
2870         ast_cli(fd, "%d active SIP channel(s)\n", numchans);
2871         return RESULT_SUCCESS;
2872 #undef FORMAT
2873 #undef FORMAT2
2874 }
2875
2876 static char *complete_sipch(char *line, char *word, int pos, int state)
2877 {
2878         int which=0;
2879         struct sip_pvt *cur;
2880         char *c = NULL;
2881         ast_pthread_mutex_lock(&iflock);
2882         cur = iflist;
2883         while(cur) {
2884                 if (!strncasecmp(word, cur->callid, strlen(word))) {
2885                         if (++which > state) {
2886                                 c = strdup(cur->callid);
2887                                 break;
2888                         }
2889                 }
2890                 cur = cur->next;
2891         }
2892         ast_pthread_mutex_unlock(&iflock);
2893         return c;
2894 }
2895
2896 static int sip_show_channel(int fd, int argc, char *argv[])
2897 {
2898         struct sip_pvt *cur;
2899         char tmp[256];
2900         if (argc != 4)
2901                 return RESULT_SHOWUSAGE;
2902         ast_pthread_mutex_lock(&iflock);
2903         cur = iflist;
2904         while(cur) {
2905                 if (!strcasecmp(cur->callid, argv[3])) {
2906                         ast_cli(fd, "Call-ID: %s\n", cur->callid);
2907                         ast_cli(fd, "Theoretical Address: %s:%d\n", inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
2908                         ast_cli(fd, "Received Address:    %s:%d\n", inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
2909                         ast_cli(fd, "NAT Support:         %s\n", cur->nat ? "Yes" : "No");
2910                         strcpy(tmp, "");
2911                         if (cur->dtmfmode & SIP_DTMF_RFC2833)
2912                                 strcat(tmp, "rfc2833 ");
2913                         if (cur->dtmfmode & SIP_DTMF_INFO)
2914                                 strcat(tmp, "info ");
2915                         if (cur->dtmfmode & SIP_DTMF_INBAND)
2916                                 strcat(tmp, "inband ");
2917                         ast_cli(fd, "DTMF Mode: %s\n", tmp);
2918                         break;
2919                 }
2920                 cur = cur->next;
2921         }
2922         ast_pthread_mutex_unlock(&iflock);
2923         if (!cur) 
2924                 ast_cli(fd, "No such SIP Call ID '%s'\n", argv[3]);
2925         return RESULT_SUCCESS;
2926 }
2927
2928 static void receive_info(struct sip_pvt *p, struct sip_request *req)
2929 {
2930         char buf[1024] = "";
2931         struct ast_frame f;
2932         char *c;
2933         /* Try getting the "signal=" part */
2934         if ((c = get_sdp(req, "Signal"))) {
2935                 strncpy(buf, c, sizeof(buf) - 1);
2936         } else if (get_msg_text(buf, sizeof(buf), req)) {
2937                 /* Normal INFO method */
2938                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2939                 return;
2940         }
2941         
2942         if (p->owner) {
2943                 if (strlen(buf)) {
2944                         if (sipdebug)
2945                                 ast_verbose("DTMF received: '%c'\n", buf[0]);
2946                         memset(&f, 0, sizeof(f));
2947                         f.frametype = AST_FRAME_DTMF;
2948                         f.subclass = buf[0];
2949                         f.offset = 0;
2950                         f.data = NULL;
2951                         f.datalen = 0;
2952                         ast_queue_frame(p->owner, &f, 1);
2953                 }
2954         }
2955 }
2956
2957 static int sip_do_debug(int fd, int argc, char *argv[])
2958 {
2959         if (argc != 2)
2960                 return RESULT_SHOWUSAGE;
2961         sipdebug = 1;
2962         ast_cli(fd, "SIP Debugging Enabled\n");
2963         return RESULT_SUCCESS;
2964 }
2965
2966 static int sip_no_debug(int fd, int argc, char *argv[])
2967 {
2968         if (argc != 3)
2969                 return RESULT_SHOWUSAGE;
2970         sipdebug = 0;
2971         ast_cli(fd, "SIP Debugging Disabled\n");
2972         return RESULT_SUCCESS;
2973 }
2974
2975 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len);
2976
2977 static int do_register_auth(struct sip_pvt *p, struct sip_request *req) {
2978         char digest[256];
2979         memset(digest,0,sizeof(digest));
2980         reply_digest(p,req, "WWW-Authenticate", "REGISTER", digest, sizeof(digest) );
2981         return transmit_register(p->registry,"REGISTER",digest); 
2982 }
2983
2984 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req) {
2985         char digest[256];
2986         memset(digest,0,sizeof(digest));
2987         reply_digest(p,req, "Proxy-Authenticate", "INVITE", digest, sizeof(digest) );
2988         return transmit_invite(p,"INVITE",1,digest, NULL); 
2989 }
2990
2991 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
2992
2993         char tmp[256] = "";
2994         char *realm = "";
2995         char *nonce = "";
2996         char *c;
2997         char a1[256];
2998         char a2[256];
2999         char a1_hash[256];
3000         char a2_hash[256];
3001         char resp[256];
3002         char resp_hash[256];
3003         char uri[256] = "";
3004
3005
3006         strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
3007         c = tmp;
3008         c+=strlen("Digest ");
3009         while (c) {
3010                 while (*c && (*c < 33)) c++;
3011                 if (!*c)
3012                         break;
3013                         if (!strncasecmp(c,"realm=", strlen("realm="))) {
3014                                 c+=strlen("realm=");
3015                                 if ((*c == '\"')) {
3016                                         realm=++c;
3017                                         if ((c = strchr(c,'\"')))
3018                                                 *c = '\0';
3019                                 } else {
3020                                         realm = c;
3021                                         if ((c = strchr(c,',')))
3022                                                 *c = '\0';
3023                                 }
3024
3025                         } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
3026                                 c+=strlen("nonce=");
3027                                 if ((*c == '\"')) {
3028                                         nonce=++c;
3029                                         if ((c = strchr(c,'\"')))
3030                                                 *c = '\0';
3031                                 } else {
3032                                         nonce = c;
3033                                         if ((c = strchr(c,',')))
3034                                                 *c = '\0';
3035                                 }
3036                         } else
3037                                 c = strchr(c,',');
3038                         if (c)
3039                                 c++;
3040                         }
3041
3042         /* Okay.  We've got the realm and nonce from the server.  Now lets build the MD5 digest. */
3043         snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
3044
3045         snprintf(a1,sizeof(a1),"%s:%s:%s",p->peername,realm,p->peersecret);
3046         snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
3047         md5_hash(a1_hash,a1);
3048         md5_hash(a2_hash,a2);
3049         snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,nonce,a2_hash);
3050         md5_hash(resp_hash,resp);
3051
3052         snprintf(digest,digest_len,"Digest username=\"%s\", realm=\"%s\", algorithm=\"MD5\", uri=\"%s\", nonce=\"%s\", response=\"%s\"",p->peername,realm,uri,nonce,resp_hash);
3053
3054         return 0;
3055 }
3056         
3057
3058         
3059         
3060
3061
3062 static char show_users_usage[] = 
3063 "Usage: sip show users\n"
3064 "       Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
3065
3066 static char show_channels_usage[] = 
3067 "Usage: sip show channels\n"
3068 "       Lists all currently active SIP channels.\n";
3069
3070 static char show_channel_usage[] = 
3071 "Usage: sip show channel <channel>\n"
3072 "       Provides detailed status on a given SIP channel.\n";
3073
3074 static char show_peers_usage[] = 
3075 "Usage: sip show peers\n"
3076 "       Lists all known SIP peers.\n";
3077
3078 static char show_reg_usage[] =
3079 "Usage: sip show registry\n"
3080 "       Lists all registration requests and status.\n";
3081
3082 static char debug_usage[] = 
3083 "Usage: sip debug\n"
3084 "       Enables dumping of SIP packets for debugging purposes\n";
3085
3086 static char no_debug_usage[] = 
3087 "Usage: sip no debug\n"
3088 "       Disables dumping of SIP packets for debugging purposes\n";
3089
3090 static struct ast_cli_entry  cli_show_users = 
3091         { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
3092 static struct ast_cli_entry  cli_show_channels =
3093         { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage};
3094 static struct ast_cli_entry  cli_show_channel =
3095         { { "sip", "show", "channel", NULL }, sip_show_channel, "Show detailed SIP channel info", show_channel_usage, complete_sipch  };
3096 static struct ast_cli_entry  cli_show_peers =
3097         { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
3098 static struct ast_cli_entry  cli_show_registry =
3099         { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
3100 static struct ast_cli_entry  cli_debug =
3101         { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
3102 static struct ast_cli_entry  cli_no_debug =
3103         { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
3104
3105
3106 static int sip_poke_peer_s(void *data)
3107 {
3108         struct sip_peer *peer = data;
3109         peer->pokeexpire = -1;
3110         sip_poke_peer(peer);
3111         return 0;
3112 }
3113
3114 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req)
3115 {
3116         char *to;
3117         char *msg, *c;
3118         struct ast_rtp *rtp;
3119         struct ast_channel *owner;
3120         struct sip_peer *peer;
3121         int pingtime;
3122         struct timeval tv;
3123         c = get_header(req, "Cseq");
3124         msg = strchr(c, ' ');
3125         if (!msg) msg = ""; else msg++;
3126 retrylock:
3127         ast_pthread_mutex_lock(&p->lock);
3128         /* Go ahead and lock the owner if it has one -- we may need it */
3129         if (p->owner && pthread_mutex_trylock(&p->owner->lock)) {
3130                 ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
3131                 ast_pthread_mutex_unlock(&p->lock);
3132                 /* Sleep infintismly short amount of time */
3133                 usleep(1);
3134                 goto retrylock;
3135         }
3136         owner = p->owner;
3137         if (p->peerpoke) {
3138                 /* We don't really care what the response is, just that it replied back. 
3139                    Well, as long as it's not a 100 response...  since we might
3140                    need to hang around for something more "difinitive" */
3141                 if (resp != 100) {
3142                         peer = p->peerpoke;
3143                         gettimeofday(&tv, NULL);
3144                         pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
3145                                                 (tv.tv_usec - peer->ps.tv_usec) / 1000;
3146                         if (pingtime < 1)
3147                                 pingtime = 1;
3148                         if ((peer->lastms < 0)  || (peer->lastms > peer->maxms)) {
3149                                 if (pingtime <= peer->maxms)
3150                                 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE!\n", peer->name);
3151                         } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
3152                                 if (pingtime > peer->maxms)
3153                                         ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED!\n", peer->name);
3154                         }
3155                         peer->lastms = pingtime;
3156                         peer->call = NULL;
3157                         if (peer->pokeexpire > -1)
3158                                 ast_sched_del(sched, peer->pokeexpire);
3159                         if (!strcasecmp(msg, "INVITE"))
3160                                 transmit_request(p, "ACK", 0);
3161                         sip_destroy(p);
3162                         p = NULL;
3163                         /* Try again eventually */
3164                         if ((peer->lastms < 0)  || (peer->lastms > peer->maxms))
3165                                 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
3166                         else
3167                                 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
3168                 }
3169         } else if (p->outgoing) {
3170                 if (p->initid > -1) {
3171                         /* Don't auto congest anymore since we've gotten something useful back */
3172                         ast_sched_del(sched, p->initid);
3173                         p->initid = -1;
3174                 }
3175                 /* Get their tag if we haven't already */
3176                 if (!strlen(p->theirtag)) {
3177                         to = get_header(req, "To");
3178                         to = strstr(to, "tag=");
3179                         if (to) {
3180                                 to += 4;
3181                                 strncpy(p->theirtag, to, sizeof(p->theirtag) - 1);
3182                                 to = strchr(p->theirtag, ';');
3183                                 if (to)
3184                                         *to = '\0';
3185                         }
3186                 }
3187                 
3188                 switch(resp) {
3189                 case 100:
3190                         break;
3191                 case 183:       /* We don't really need this since we pass in-band audio anyway */
3192                         /* Not important */
3193                         if (strlen(get_header(req, "Content-Type")))
3194                                 process_sdp(p, req);
3195                         break;
3196                 case 180:
3197                         if (p->owner) {
3198                                 ast_queue_control(p->owner, AST_CONTROL_RINGING, 0);
3199                                 if (p->owner->_state != AST_STATE_UP)
3200                                         ast_setstate(p->owner, AST_STATE_RINGING);
3201                         }
3202                         break;
3203                 case 200:
3204                         if (strlen(get_header(req, "Content-Type")))
3205                                 process_sdp(p, req);
3206                         if (p->owner) {
3207                                 if (p->owner->_state != AST_STATE_UP) {
3208                                         ast_setstate(p->owner, AST_STATE_UP);
3209                                         ast_queue_control(p->owner, AST_CONTROL_ANSWER, 0);
3210                                 }
3211                         }
3212                         if (!strcasecmp(msg, "INVITE"))
3213                                 transmit_request(p, "ACK", 0);
3214                         else if (!strcasecmp(msg, "REGISTER"))
3215                         {
3216                                 /* char *exp; */
3217                                 int expires;
3218                                 struct sip_registry *r;
3219                                 r=p->registry;
3220                                 r->regstate=REG_STATE_REGISTERED;
3221                                 ast_log(LOG_NOTICE, "Registration successful\n");
3222                                 ast_log(LOG_NOTICE, "Cancelling timeout %d\n", r->timeout);
3223                                 if (r->timeout) 
3224                                         ast_sched_del(sched, r->timeout);
3225                                 r->timeout=0;
3226                                 /* set us up for re-registering */
3227                                 /* figure out how long we got registered for */
3228                                 if (r->expire != -1)
3229                                         ast_sched_del(sched, r->expire);
3230                                 expires=atoi(get_header(req, "expires"));
3231                                 if (!expires) expires=default_expirey;
3232                                         r->expire=ast_sched_add(sched, (expires-2)*1000, sip_reregister, r); 
3233
3234                         }
3235                         break;
3236                 case 401: /* Not authorized on REGISTER */
3237                         /* XXX: Do I need to ACK the 401? 
3238                         transmit_request(p, "ACK", 0);
3239                         */
3240                         do_register_auth(p, req);
3241                         break;
3242                 case 407:
3243                         /* First we ACK */
3244                         transmit_request(p, "ACK", 0);
3245                         /* Then we AUTH */
3246                         do_proxy_auth(p, req);
3247                         /* This is just a hack to kill the channel while testing */
3248                         /* 
3249                         p->alreadygone = 1;
3250                         if (p->rtp) {
3251                                 rtp = p->rtp;
3252                                 p->rtp = NULL;
3253                                 ast_rtp_destroy(rtp);
3254                         }
3255                         if (p->owner)
3256                                 ast_queue_hangup(p->owner,0);
3257                         transmit_request(p,"ACK",0);
3258                         sip_destroy(p);
3259                         p = NULL;
3260                         */
3261                         break;
3262                 default:
3263                         if ((resp >= 400) && (resp < 700)) {
3264                                 if (option_verbose > 2) 
3265                                         ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, inet_ntoa(p->sa.sin_addr));
3266                                 p->alreadygone = 1;
3267                                 if (p->rtp) {
3268                                         rtp = p->rtp;
3269                                         p->rtp = NULL;
3270                                         /* Immediately stop RTP */
3271                                         ast_rtp_destroy(rtp);
3272                                 }
3273                                 /* XXX Locking issues?? XXX */
3274                                 switch(resp) {
3275                                 case 486: /* Busy here */
3276                                 case 600: /* Busy everywhere */
3277                                         if (p->owner)
3278                                                 ast_queue_control(p->owner, AST_CONTROL_BUSY, 0);
3279                                         break;
3280                                 case 480: /* Temporarily Unavailable */
3281                                 case 404: /* Not Found */
3282                                 case 410: /* Gone */
3283                                 case 500: /* Server error */
3284                                 case 501: /* Not Implemented */
3285                                         if (owner)
3286                                                 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
3287                                         break;
3288                                 default:
3289                                         /* Send hangup */       
3290                                         if (owner)
3291                                                 ast_queue_hangup(p->owner, 0);
3292                                         break;
3293                                 }
3294                                 transmit_request(p, "ACK", 0);
3295                                 __sip_destroy(p, 0);
3296                                 p = NULL;
3297                         } else
3298                                 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));
3299                 }
3300         } else {
3301                 if (sipdebug)
3302                         ast_verbose("Message is %s\n", msg);
3303                 switch(resp) {
3304                 case 200:
3305                         if (!strcasecmp(msg, "INVITE") || !strcasecmp(msg, "REGISTER") )
3306                                 transmit_request(p, "ACK", 0);
3307                         break;
3308                 }
3309         }
3310         if (owner)
3311                 ast_pthread_mutex_unlock(&owner->lock);
3312         if (p)
3313                 ast_pthread_mutex_unlock(&p->lock);
3314 }
3315
3316 static int determine_firstline_parts( struct sip_request *req ) {
3317
3318   char *e, *cmd;
3319   int len;
3320   
3321   cmd= req->header[0];
3322   while(*cmd && (*cmd < 33)) {
3323     cmd++;
3324   }
3325   if (!*cmd) {
3326     return -1;
3327   }
3328   e= cmd;
3329   while(*e && (*e > 32)) {
3330     e++;
3331   }
3332   /* Get the command */
3333   if (*e) {
3334     *e = '\0';
3335     e++;
3336   }
3337   req->rlPart1= cmd;
3338   while( *e && ( *e < 33 ) ) {
3339     e++; 
3340   }
3341   if( !*e ) {
3342     return -1;
3343   }
3344     
3345   if ( !strcasecmp(cmd, "SIP/2.0") ) {
3346     /* We have a response */
3347     req->rlPart2= e;
3348     len= strlen( req->rlPart2 );
3349     if( len < 2 ) { return -1; }
3350     e+= len - 1;
3351     while( *e && *e<33 ) {
3352       e--; 
3353     }
3354     *(++e)= '\0';
3355   } else {
3356     /* We have a request */
3357     if( *e == '<' ) { 
3358       e++;
3359       if( !*e ) { return -1; }  
3360     }
3361     req->rlPart2= e;
3362     if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
3363       return -1;
3364     }
3365     while( isspace( *(--e) ) ) {}
3366     if( *e == '>' ) {
3367       *e= '\0';
3368     } else {
3369       *(++e)= '\0';
3370     }
3371   }
3372   return 1;
3373 }
3374
3375 static int attempt_transfer(struct sip_pvt *p1, struct sip_pvt *p2)
3376 {
3377         if (!p1->owner || !p2->owner) {
3378                 ast_log(LOG_WARNING, "Transfer attempted without dual ownership?\n");
3379                 return -1;
3380         }
3381         if (p1->owner->bridge) {
3382                 if (p2->owner->bridge)
3383                         ast_moh_stop(p2->owner->bridge);
3384                 ast_moh_stop(p1->owner->bridge);
3385                 ast_moh_stop(p1->owner);
3386                 ast_moh_stop(p2->owner);
3387                 if (ast_channel_masquerade(p2->owner, p1->owner->bridge)) {
3388                         ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p2->owner->name, p1->owner->bridge->name);
3389                         return -1;
3390                 }
3391         } else if (p2->owner->bridge) {
3392                 ast_moh_stop(p2->owner->bridge);
3393                 ast_moh_stop(p2->owner);
3394                 ast_moh_stop(p1->owner);
3395                 if (ast_channel_masquerade(p1->owner, p2->owner->bridge)) {
3396                         ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p1->owner->name, p2->owner->bridge->name);
3397                         return -1;
3398                 }
3399         } else {
3400                 ast_log(LOG_NOTICE, "Transfer attempted with no bridged calls to transfer\n");
3401                 return -1;
3402         }
3403         return 0;
3404 }
3405
3406 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin)
3407 {
3408         struct sip_request resp;
3409         char *cmd;
3410         char *cseq;
3411         char *e;
3412         struct ast_channel *c=NULL;
3413         int seqno;
3414         int len;
3415         int ignore=0;
3416         int respid;
3417         int res;
3418         /* Clear out potential response */
3419         memset(&resp, 0, sizeof(resp));
3420         /* Get Method and Cseq */
3421         cseq = get_header(req, "Cseq");
3422         cmd = req->header[0];
3423         /* Must have Cseq */
3424         if (!strlen(cmd) || !strlen(cseq))
3425                         return -1;
3426         if (sscanf(cseq, "%i%n", &seqno, &len) != 1) {
3427                 ast_log(LOG_DEBUG, "No seqno in '%s'\n", cmd);
3428                 return -1;
3429         }
3430         /* Get the command */
3431         cseq += len;
3432
3433   /* Determine the request URI for sip, sips or tel URIs */
3434         if( determine_firstline_parts( req ) < 0 ) {
3435           return -1; 
3436         }
3437         cmd= req->rlPart1;
3438         e= req->rlPart2;
3439         
3440         if (strcasecmp(cmd, "SIP/2.0")) {
3441                 /* Request coming in */                 
3442                 if (p->icseq && (p->icseq < seqno)) {
3443                         ast_log(LOG_DEBUG, "Ignoring out of order packet %d (expecting %d)\n", seqno, p->icseq);
3444                         return -1;
3445                 } else if (p->icseq && (p->icseq != seqno)) {
3446                         /* ignore means "don't do anything with it" but still have to 
3447                            respond appropriately  */
3448                         ignore=1;
3449                 }
3450         } else {
3451                 /* Response to our request -- Do some sanity checks */  
3452                 if (!p->initreq.headers) {
3453                         ast_log(LOG_DEBUG, "That's odd...  Got a response on a call we dont know about.\n");
3454                         sip_destroy(p);
3455                         return 0;
3456                 } else if (p->ocseq && (p->ocseq < seqno)) {
3457                         ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
3458                         return -1;
3459                 } else if (p->ocseq && (p->ocseq != seqno)) {
3460                         /* ignore means "don't do anything with it" but still have to 
3461                            respond appropriately  */
3462                         ignore=1;
3463                 }
3464         }
3465         
3466         if (strcmp(cmd, "SIP/2.0") && (seqno >= p->icseq))
3467                 /* Next should follow monotonically increasing */
3468                 p->icseq = seqno + 1;
3469
3470         /* Initialize the context if it hasn't been already */
3471         if (!strcasecmp(cmd, "OPTIONS")) {
3472                 if (!strlen(p->context))
3473                         strncpy(p->context, context, sizeof(p->context) - 1);
3474                 res = get_destination(p, req);
3475                 if (res < 0)
3476                         transmit_response_with_allow(p, "404 Not Found", req);
3477                 else if (res > 0)
3478                         transmit_response_with_allow(p, "484 Address Incomplete", req);
3479                 else 
3480                         transmit_response_with_allow(p, "200 OK", req);
3481         } else if (!strcasecmp(cmd, "INVITE")) {
3482                 if (p->outgoing && p->owner && (p->owner->_state != AST_STATE_UP)) {
3483                         /* This is a call to ourself.  Send ourselves an error code and stop
3484                            processing immediately, as SIP really has no good mechanism for
3485                            being able to call yourself */
3486                         transmit_response(p, "482 Loop Detected", req);
3487                         /* We do NOT destroy p here, so that our response will be accepted */
3488                         return 0;
3489                 }
3490                 /* Process the SDP portion */
3491                 if (!ignore) {
3492                         /* Use this as the basis */
3493                         if (sipdebug)
3494                                 ast_verbose("Using latest request as basis request\n");
3495                         /* This call is no longer outgoing if it ever was */
3496                         p->outgoing = 0;
3497                         copy_request(&p->initreq, req);
3498                         check_via(p, req);
3499                         if (strlen(get_header(req, "Content-Type"))) {
3500                                 if (process_sdp(p, req))
3501                                         return -1;
3502                         } else {
3503                                 p->capability = capability;
3504                                 ast_log(LOG_DEBUG, "Hm....  No sdp for the moemnt\n");
3505                         }
3506                 } else if (sipdebug)
3507                         ast_verbose("Ignoring this request\n");
3508                 if (!p->lastinvite) {
3509                         /* Handle authentication if this is our first invite */
3510                         res = check_user(p, req, cmd, e);
3511                         if (res) {
3512                                 if (res < 0) {
3513                                         ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
3514                                         sip_destroy(p);
3515                                 }
3516                                 return 0;
3517                         }
3518                         /* Initialize the context if it hasn't been already */
3519                         if (!strlen(p->context))
3520                                 strncpy(p->context, context, sizeof(p->context) - 1);
3521                         if ((res = get_destination(p, NULL))) {
3522                                 if (res < 0)
3523                                         transmit_response(p, "404 Not Found", req);
3524                                 else