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