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