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