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