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