557e83b6a7de5bbba3c58f5c5ecdee36fbb5accd
[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         int alreadysent = 0;
1636         char costr[80];
1637         struct sockaddr_in sin;
1638         struct sip_codec_pref *cur;
1639         char v[256];
1640         char s[256];
1641         char o[256];
1642         char c[256];
1643         char t[256];
1644         char m[256];
1645         char a[1024] = "";
1646         int x;
1647         struct sockaddr_in dest;
1648         /* XXX We break with the "recommendation" and send our IP, in order that our
1649                peer doesn't have to gethostbyname() us XXX */
1650         len = 0;
1651         if (!p->rtp) {
1652                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
1653                 return -1;
1654         }
1655         ast_rtp_get_us(p->rtp, &sin);
1656         if (rtp) {
1657                 ast_rtp_get_peer(rtp, &dest);
1658         } else {
1659                 dest.sin_addr = p->ourip;
1660                 dest.sin_port = sin.sin_port;
1661         }
1662         if (sipdebug)
1663                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
1664         snprintf(v, sizeof(v), "v=0\r\n");
1665         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
1666         snprintf(s, sizeof(s), "s=session\r\n");
1667         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
1668         snprintf(t, sizeof(t), "t=0 0\r\n");
1669         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
1670         /* Start by sending our preferred codecs */
1671         cur = prefs;
1672         while(cur) {
1673                 if (p->capability & cur->codec) {
1674                         if (sipdebug)
1675                                 ast_verbose("Answering with preferred capability %d\n", cur->codec);
1676                         if ((codec = ast2rtp(cur->codec)) > -1) {
1677                                 snprintf(costr, sizeof(costr), " %d", codec);
1678                                 strcat(m, costr);
1679                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast2rtpn(x));
1680                                 strcat(a, costr);
1681                         }
1682                 }
1683                 alreadysent |= cur->codec;
1684                 cur = cur->next;
1685         }
1686         /* Now send anything else in no particular order */
1687         for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1688                 if ((p->capability & x) && !(alreadysent & x)) {
1689                         if (sipdebug)
1690                                 ast_verbose("Answering with capability %d\n", x);
1691                         if ((codec = ast2rtp(x)) > -1) {
1692                                 snprintf(costr, sizeof(costr), " %d", codec);
1693                                 strcat(m, costr);
1694                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast2rtpn(x));
1695                                 strcat(a, costr);
1696                         }
1697                 }
1698         }
1699         strcat(m, " 101\r\n");
1700         strcat(a, "a=rtpmap:101 telephone-event/8000\r\n");
1701         /* Indicate we support DTMF only...  Not sure about 16, but MSN supports it so dang it, we will too... */
1702         strcat(a, "a=fmtp:101 0-16\r\n");
1703         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
1704         snprintf(costr, sizeof(costr), "%d", len);
1705         add_header(resp, "Content-Type", "application/sdp");
1706         add_header(resp, "Content-Length", costr);
1707         add_line(resp, v);
1708         add_line(resp, o);
1709         add_line(resp, s);
1710         add_line(resp, c);
1711         add_line(resp, t);
1712         add_line(resp, m);
1713         add_line(resp, a);
1714         return 0;
1715 }
1716
1717 static void copy_request(struct sip_request *dst,struct sip_request *src)
1718 {
1719         long offset;
1720         int x;
1721         offset = ((void *)dst) - ((void *)src);
1722         /* First copy stuff */
1723         memcpy(dst, src, sizeof(*dst));
1724         /* Now fix pointer arithmetic */
1725         for (x=0;x<src->headers;x++)
1726                 dst->header[x] += offset;
1727         for (x=0;x<src->lines;x++)
1728                 dst->line[x] += offset;
1729 }
1730
1731 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req)
1732 {
1733         struct sip_request resp;
1734         respprep(&resp, p, msg, req);
1735         add_sdp(&resp, p, NULL);
1736         return send_response(p, &resp);
1737 }
1738
1739 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
1740 {
1741         struct sip_request resp;
1742         reqprep(&resp, p, "INVITE", 1);
1743         add_sdp(&resp, p, rtp);
1744         return send_response(p, &resp);
1745 }
1746
1747 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
1748 {
1749         char invite[256];
1750         char from[256];
1751         char to[256];
1752         char tmp[80];
1753         char cid[256];
1754         char *l = "asterisk", *n=NULL;
1755         if (p->owner && p->owner->callerid) {
1756                 strcpy(cid, p->owner->callerid);
1757                 ast_callerid_parse(cid, &n, &l);
1758                 if (l) 
1759                         ast_shrink_phone_number(l);
1760                 if (!l || !ast_isphonenumber(l))
1761                                 l = "asterisk";
1762         }
1763         if (!n)
1764                 n = "asterisk";
1765         snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%08x", n, l, inet_ntoa(p->ourip), p->tag);
1766         if (strlen(p->username)) {
1767                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1768                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1769                 } else {
1770                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
1771                 }
1772         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1773                 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1774         } else {
1775                 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
1776         }
1777         /* If there is a VXML URL append it to the SIP URL */
1778         if (vxml_url)
1779         {
1780                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
1781         }
1782         else
1783         {
1784                 snprintf(to, sizeof(to), "<%s>", invite );
1785         }
1786         memset(req, 0, sizeof(struct sip_request));
1787         init_req(req, cmd, invite);
1788         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
1789
1790         add_header(req, "Via", p->via);
1791         add_header(req, "From", from);
1792         {
1793                 char contact2[256] ="", *c, contact[256];
1794                 /* XXX This isn't exactly right and it's implemented
1795                        very stupidly *sigh* XXX */
1796                 strncpy(contact2, from, sizeof(contact2)-1);
1797                 c = ditch_braces(contact2);
1798                 snprintf(contact, sizeof(contact), "<%s>", c);
1799                 add_header(req, "Contact", contact);
1800         }
1801         add_header(req, "To", to);
1802         add_header(req, "Call-ID", p->callid);
1803         add_header(req, "CSeq", tmp);
1804         add_header(req, "User-Agent", "Asterisk PBX");
1805 }
1806
1807 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
1808 {
1809         struct sip_request req;
1810         initreqprep(&req, p, cmd, vxml_url);
1811         if (auth)
1812                 add_header(&req, "Proxy-Authorization", auth);
1813         if (sdp) {
1814                 add_sdp(&req, p, NULL);
1815         } else {
1816                 add_header(&req, "Content-Length", "0");
1817                 add_blank_header(&req);
1818         }
1819         if (!p->initreq.headers) {
1820                 /* Use this as the basis */
1821                 copy_request(&p->initreq, &req);
1822                 parse(&p->initreq);
1823         }
1824         p->lastinvite = p->ocseq;
1825         return send_request(p, &req);
1826 }
1827
1828 static int transmit_notify(struct sip_pvt *p, int hasmsgs)
1829 {
1830         struct sip_request req;
1831         char tmp[256];
1832         char clen[20];
1833         initreqprep(&req, p, "NOTIFY", NULL);
1834         add_header(&req, "Event", "message-summary");
1835         add_header(&req, "Content-Type", "text/plain");
1836
1837         snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", hasmsgs ? "yes" : "no");
1838         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
1839         add_header(&req, "Content-Length", clen);
1840         add_line(&req, tmp);
1841
1842         if (!p->initreq.headers) {
1843                 /* Use this as the basis */
1844                 copy_request(&p->initreq, &req);
1845                 parse(&p->initreq);
1846         }
1847
1848         p->lastinvite = p->ocseq;
1849         return send_request(p, &req);
1850 }
1851
1852 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
1853
1854 static int sip_reregister(void *data) 
1855 {
1856         /* if we are here, we know that we need to reregister. */
1857         struct sip_registry *r=(struct sip_registry *)data;
1858         return sip_do_register(r);
1859         
1860 }
1861
1862
1863 static int sip_do_register(struct sip_registry *r)
1864 {
1865         int res;
1866         ast_pthread_mutex_lock(&r->lock);
1867         res=transmit_register(r, "REGISTER", NULL);
1868         ast_pthread_mutex_unlock(&r->lock);
1869         return res;
1870 }
1871
1872 static int sip_reg_timeout(void *data)
1873 {
1874         /* if we are here, our registration timed out, so we'll just do it over */
1875         struct sip_registry *r=data;
1876         int res;
1877         ast_pthread_mutex_lock(&r->lock);
1878         ast_log(LOG_NOTICE, "Registration timed out, trying again\n"); 
1879         r->regstate=REG_STATE_UNREGISTERED;
1880         /* cancel ourselves first!!! */
1881         /* ast_sched_del(sched,r->timeout); */
1882         res=transmit_register(r, "REGISTER", NULL);
1883         ast_pthread_mutex_unlock(&r->lock);
1884         return res;
1885 }
1886
1887 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
1888 {
1889         struct sip_request req;
1890         char from[256];
1891         char to[256];
1892         char tmp[80];
1893         char via[80];
1894         char addr[80];
1895         struct sip_pvt *p;
1896         /* exit if we are already in process with this registrar ?*/
1897         if ( (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
1898                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
1899                 return 0;
1900         }
1901
1902
1903         if (!(p=r->call)) {
1904                 if (!r->callid_valid) {
1905                   build_callid(r->callid, sizeof(r->callid), __ourip);
1906                   r->callid_valid=1;
1907                 }
1908                 p=sip_alloc( r->callid, &r->addr );
1909                 p->outgoing = 1;
1910                 r->call=p;
1911                 p->registry=r;
1912                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
1913                 strncpy(p->peername, r->username, sizeof(p->peername)-1);
1914                 strncpy(p->username, r->username, sizeof(p->username)-1);
1915         }
1916
1917         /* set up a timeout */
1918         if (auth==NULL && !r->timeout)  {
1919                 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
1920                 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
1921         }
1922
1923         snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
1924         snprintf(to, sizeof(to),     "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
1925         
1926         snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
1927
1928         memset(&req, 0, sizeof(req));
1929         init_req(&req, cmd, addr);
1930
1931         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
1932
1933         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1934         add_header(&req, "Via", via);
1935         add_header(&req, "From", from);
1936         add_header(&req, "To", to);
1937         {
1938                 char contact[256];
1939                 snprintf(contact, sizeof(contact), "<sip:%s@%s:%d;transport=udp>", r->contact, inet_ntoa(p->ourip), ourport);
1940                 add_header(&req, "Contact", contact);
1941         }
1942         add_header(&req, "Call-ID", p->callid);
1943         add_header(&req, "CSeq", tmp);
1944         add_header(&req, "User-Agent", "Asterisk PBX");
1945         if (auth) 
1946                 add_header(&req, "Authorization", auth);
1947
1948         snprintf(tmp, sizeof(tmp), "%d", default_expirey);
1949         add_header(&req, "Expires", tmp);
1950         add_header(&req, "Event", "registration");
1951         copy_request(&p->initreq, &req);
1952         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
1953         return send_request(p, &req);
1954 }
1955
1956 static int transmit_message_with_text(struct sip_pvt *p, char *text)
1957 {
1958         struct sip_request req;
1959         reqprep(&req, p, "MESSAGE", 1);
1960         add_text(&req, text);
1961         return send_request(p, &req);
1962 }
1963
1964 static int transmit_request(struct sip_pvt *p, char *msg, int inc)
1965 {
1966         struct sip_request resp;
1967         reqprep(&resp, p, msg, inc);
1968         add_header(&resp, "Content-Length", "0");
1969         add_blank_header(&resp);
1970         return send_request(p, &resp);
1971 }
1972
1973 static int expire_register(void *data)
1974 {
1975         struct sip_peer *p = data;
1976         memset(&p->addr, 0, sizeof(p->addr));
1977         p->expire = -1;
1978         return 0;
1979 }
1980
1981 static int sip_poke_peer(struct sip_peer *peer);
1982
1983 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
1984 {
1985         char contact[80]= ""; 
1986         char *expires = get_header(req, "Expires");
1987         int expirey = atoi(expires);
1988         char *c, *n, *pt;
1989         int port;
1990         struct hostent *hp;
1991         struct sockaddr_in oldsin;
1992         if (!strlen(expires)) {
1993                 expires = strstr(get_header(req, "Contact"), "expires=");
1994                 if (expires) 
1995                         if (sscanf(expires + 8, "%d;", &expirey) != 1)
1996                                 expirey = 0;
1997         }
1998         /* Look for brackets */
1999         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2000         c = contact;
2001         
2002         if ((n=strchr(c, '<'))) {
2003                 c = n + 1;
2004                 n = strchr(c, '>');
2005                 /* Lose the part after the > */
2006                 if (n) 
2007                         *n = '\0';
2008         }
2009         /* Make sure it's a SIP URL */
2010         if (strncasecmp(c, "sip:", 4)) {
2011                 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contcact\n", c);
2012                 return -1;
2013         }
2014         c += 4;
2015         /* Ditch q */
2016         n = strchr(c, ';');
2017         if (n) 
2018                 *n = '\0';
2019         /* Grab host */
2020         n = strchr(c, '@');
2021         if (!n) {
2022                 n = c;
2023                 c = NULL;
2024         } else {
2025                 *n = '\0';
2026                 n++;
2027         }
2028         pt = strchr(n, ':');
2029         if (pt) {
2030                 *pt = '\0';
2031                 pt++;
2032                 port = atoi(pt);
2033         } else
2034                 port = DEFAULT_SIP_PORT;
2035         /* XXX This could block for a long time XXX */
2036         hp = gethostbyname(n);
2037         if (!hp)  {
2038                 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2039                 return -1;
2040         }
2041         memcpy(&oldsin, &p->addr, sizeof(oldsin));
2042         p->addr.sin_family = AF_INET;
2043         memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2044         p->addr.sin_port = htons(port);
2045         if (c)
2046                 strncpy(p->username, c, sizeof(p->username) - 1);
2047         else
2048                 strcpy(p->username, "");
2049         if (p->expire > -1)
2050                 ast_sched_del(sched, p->expire);
2051         if ((expirey < 1) || (expirey > max_expirey))
2052                 expirey = max_expirey;
2053         p->expire = ast_sched_add(sched, expirey * 1000, expire_register, p);
2054         pvt->expirey = expirey;
2055         if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
2056                 sip_poke_peer(p);
2057                 if (option_verbose > 2)
2058                         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);
2059         }
2060         return 0;
2061 }
2062
2063 static void md5_hash(char *output, char *input)
2064 {
2065                 struct MD5Context md5;
2066                 unsigned char digest[16];
2067                 char *ptr;
2068                 int x;
2069                 MD5Init(&md5);
2070                 MD5Update(&md5, input, strlen(input));
2071                 MD5Final(digest, &md5);
2072                 ptr = output;
2073                 for (x=0;x<16;x++)
2074                         ptr += sprintf(ptr, "%2.2x", digest[x]);
2075 }
2076
2077 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri)
2078 {
2079         int res = -1;
2080         /* Always OK if no secret */
2081         if (!strlen(secret))
2082                 return 0;
2083         if (!strlen(randdata)) {
2084                 snprintf(randdata, randlen, "%08x", rand());
2085                 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata);
2086                 res = 1;
2087         } else {
2088                 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2089                    an example in the spec of just what it is you're doing a hash on. */
2090                 char a1[256];
2091                 char a2[256];
2092                 char a1_hash[256];
2093                 char a2_hash[256];
2094                 char resp[256];
2095                 char resp_hash[256];
2096                 char tmp[256] = "";
2097                 char *c;
2098                 char *response ="";
2099                 char *resp_uri ="";
2100
2101                 /* Find their response among the mess that we'r sent for comparison */
2102                 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2103                 c = tmp;
2104
2105                 while(c) {
2106                         while (*c && (*c < 33)) c++;
2107                         if (!*c)
2108                                 break;
2109                         if (!strncasecmp(c, "response=", strlen("response="))) {
2110                                 c+= strlen("response=");
2111                                 if ((*c == '\"')) {
2112                                         response=++c;
2113                                         if((c = strchr(c,'\"')))
2114                                                 *c = '\0';
2115
2116                                 } else {
2117                                         response=c;
2118                                         if((c = strchr(c,',')))
2119                                                 *c = '\0';
2120                                 }
2121
2122                         } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2123                                 c+= strlen("uri=");
2124                                 if ((*c == '\"')) {
2125                                         resp_uri=++c;
2126                                         if((c = strchr(c,'\"')))
2127                                                 *c = '\0';
2128                                 } else {
2129                                         resp_uri=c;
2130                                         if((c = strchr(c,',')))
2131                                                 *c = '\0';
2132                                 }
2133
2134                         } else
2135                                 c = strchr(c, ',');
2136                         if (c)
2137                                 c++;
2138                 }
2139                 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2140                 if(strlen(resp_uri))
2141                         snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2142                 else
2143                         snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2144                 md5_hash(a1_hash, a1);
2145                 md5_hash(a2_hash, a2);
2146                 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2147                 md5_hash(resp_hash, resp);
2148
2149                 /* resp_hash now has the expected response, compare the two */
2150
2151                 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2152                         /* Auth is OK */
2153                         res = 0;
2154                 }
2155                 /* Assume success ;-) */
2156                 /* Eliminate random data */
2157                 strcpy(randdata, "");
2158         }
2159         return res;
2160 }
2161
2162 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2163 {
2164         int res = -1;
2165         struct sip_peer *peer;
2166         char tmp[256] = "";
2167         char *name, *c;
2168         char *t;
2169         /* Terminate URI */
2170         t = uri;
2171         while(*t && (*t > 32) && (*t != ';'))
2172                 t++;
2173         *t = '\0';
2174         
2175         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2176         c = ditch_braces(tmp);
2177         if (strncmp(c, "sip:", 4)) {
2178                 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s\n", tmp, inet_ntoa(sin->sin_addr));
2179                 return -1;
2180         }
2181         name = c + 4;
2182         c = strchr(name, '@');
2183         if (c) 
2184                 *c = '\0';
2185         ast_pthread_mutex_lock(&peerl.lock);
2186         peer = peerl.peers;
2187         while(peer) {
2188                 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2189                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri))) {
2190                                 if (parse_contact(p, peer, req)) {
2191                                         ast_log(LOG_WARNING, "Failed to parse contact info\n");
2192                                 } else {
2193                                         /* Say OK and ask subsystem to retransmit msg counter */
2194                                         transmit_response(p, "200 OK", req);
2195                                         peer->lastmsgssent = -1;
2196                                         res = 0;
2197                                 }
2198                         } 
2199                         break;
2200                 }       
2201                 peer = peer->next;
2202         }
2203         ast_pthread_mutex_unlock(&peerl.lock);
2204         if (res < 0)
2205                 transmit_response(p, "401 Unauthorized", &p->initreq);
2206         return res;
2207 }
2208
2209 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2210 {
2211         char tmp[256] = "", *c, *a;
2212         struct sip_request *req;
2213         
2214         req = oreq;
2215         if (!req)
2216                 req = &p->initreq;
2217         strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2218         c = ditch_braces(tmp);
2219         if (strncmp(c, "sip:", 4)) {
2220                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2221                 return -1;
2222         }
2223         c += 4;
2224         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2225                 *a = '\0';
2226         }
2227         if (sipdebug)
2228                 ast_verbose("Looking for %s in %s\n", c, p->context);
2229         if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2230                 if (!oreq)
2231                         strncpy(p->exten, c, sizeof(p->exten) - 1);
2232                 return 0;
2233         }
2234
2235         if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2236                 return 1;
2237         }
2238         
2239         return -1;
2240 }
2241
2242 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2243 {
2244         char tmp[256] = "", *c, *a;
2245         char tmp2[256] = "", *c2, *a2;
2246         char tmp3[256];
2247         char tmp4[256];
2248         char tmp5[256] = "";            /* CallID to replace */
2249         struct sip_request *req;
2250         struct sip_pvt *p2;
2251         
2252         req = oreq;
2253         if (!req)
2254                 req = &p->initreq;
2255         strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2256         strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
2257         strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
2258         strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
2259         
2260         c = ditch_braces(tmp);
2261         c2 = ditch_braces(tmp2);
2262         
2263                 
2264         if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
2265                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2266                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c2);
2267                 return -1;
2268         }
2269         c += 4;
2270         c2 += 4;
2271         if ((a = strchr(c, '?'))) {
2272                 /* Search for arguemnts */
2273                 *a = '\0';
2274                 a++;
2275                 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
2276                         strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
2277                         if ((a = strchr(tmp5, '%'))) {
2278                                 /* Yuck!  Pingtel converts the '@' to a %40, icky icky!  Convert
2279                                    back to an '@' */
2280                                 if ((a[1] == '4') && (a[2] == '0')) {
2281                                         *a = '@';
2282                                         memmove(a + 1, a+3, strlen(a + 3));
2283                                 }
2284                         }
2285                         if ((a = strchr(tmp5, '%'))) 
2286                                 *a = '\0';
2287                 }
2288         }
2289         
2290         if ((a = strchr(c, '@')))
2291                 *a = '\0';
2292         if ((a = strchr(c, ';'))) 
2293                 *a = '\0';
2294         
2295
2296         if ((a2 = strchr(c2, '@')))
2297                 *a2 = '\0';
2298
2299         if ((a2 = strchr(c2, ';'))) 
2300                 *a2 = '\0';
2301         
2302         
2303         if (sipdebug)
2304                 ast_verbose("Looking for %s in %s\n", c, p->context);
2305                 ast_verbose("Looking for %s in %s\n", c2, p->context);
2306                 
2307         if (strlen(tmp5)) {     
2308                 /* This is a supervised transfer */
2309                 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
2310                 
2311                 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
2312                 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
2313                 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
2314                 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
2315                 p->refer_call = NULL;
2316                 ast_pthread_mutex_lock(&iflock);
2317                 /* Search interfaces and find the match */
2318                 p2 = iflist;
2319                 while(p2) {
2320                         if (!strcmp(p2->callid, tmp5)) {
2321                                 /* Go ahead and lock it before returning */
2322                                 ast_pthread_mutex_lock(&p2->lock);
2323                                 p->refer_call = p2;
2324                                 break;
2325                         }
2326                         p2 = p2->next;
2327                 }
2328                 ast_pthread_mutex_unlock(&iflock);
2329                 if (p->refer_call)
2330                         return 0;
2331                 else
2332                         ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
2333         } else if (ast_exists_extension(NULL, p->context, c, 1, NULL) && ast_exists_extension(NULL, p->context, c2, 1, NULL)) {
2334                 /* This is an unsupervised transfer */
2335                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
2336                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
2337                 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
2338                 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
2339                 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
2340                 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
2341                 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
2342                 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
2343                 p->refer_call = NULL;
2344                 return 0;
2345         } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2346                 return 1;
2347         }
2348
2349         return -1;
2350 }
2351
2352
2353 static int check_via(struct sip_pvt *p, struct sip_request *req)
2354 {
2355         char via[256] = "";
2356         char *c, *pt;
2357         struct hostent *hp;
2358
2359         memset(via, 0, sizeof(via));
2360         strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
2361         c = strchr(via, ';');
2362         if (c) 
2363                 *c = '\0';
2364         c = strchr(via, ' ');
2365         if (c) {
2366                 *c = '\0';
2367                 c++;
2368                 while(*c && (*c < 33))
2369                         c++;
2370                 if (strcmp(via, "SIP/2.0/UDP")) {
2371                         ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
2372                         return -1;
2373                 }
2374                 pt = strchr(c, ':');
2375                 if (pt) {
2376                         *pt = '\0';
2377                         pt++;
2378                 }
2379                 hp = gethostbyname(c);
2380                 if (!hp) {
2381                         ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
2382                         return -1;
2383                 }
2384                 memset(&p->sa, 0, sizeof(p->sa));
2385                 p->sa.sin_family = AF_INET;
2386                 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
2387                 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2388                 if (sipdebug)
2389                         ast_verbose("Sending to %s : %d\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2390         }
2391         return 0;
2392 }
2393
2394 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri)
2395 {
2396         struct sip_user *user;
2397         char *of, from[256] = "", *c;
2398         int res = 0;
2399         char *t;
2400         /* Terminate URI */
2401         t = uri;
2402         while(*t && (*t > 32) && (*t != ';'))
2403                 t++;
2404         *t = '\0';
2405         of = get_header(req, "From");
2406         strncpy(from, of, sizeof(from) - 1);
2407         of = ditch_braces(from);
2408         if (strncmp(of, "sip:", 4))
2409                 return 0;
2410         else
2411                 of += 4;
2412         /* Get just the username part */
2413         if ((c = strchr(of, '@')))
2414                 *c = '\0';
2415         if ((c = strchr(of, ':')))
2416                 *c = '\0';
2417         strncpy(p->callerid, of, sizeof(p->callerid) - 1);
2418         if (!strlen(of))
2419                         return 0;
2420         ast_pthread_mutex_lock(&userl.lock);
2421         user = userl.users;
2422         while(user) {
2423                 if (!strcasecmp(user->name, of)) {
2424                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri))) {
2425                                 strncpy(p->context, user->context, sizeof(p->context) - 1);
2426                                 if (strlen(user->callerid) && strlen(p->callerid)) 
2427                                         strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
2428                                 strncpy(p->username, user->name, sizeof(p->username) - 1);
2429                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)  -1);
2430                                 p->canreinvite = user->canreinvite;
2431                                 p->amaflags = user->amaflags;
2432                         }
2433                         break;
2434                 }
2435                 user = user->next;
2436         }
2437         ast_pthread_mutex_unlock(&userl.lock);
2438         return res;
2439 }
2440
2441 static int get_msg_text(char *buf, int len, struct sip_request *req)
2442 {
2443         int x;
2444         strcpy(buf, "");
2445         for (x=0;x<req->lines;x++) {
2446                 strncat(buf, req->line[x], len - strlen(buf) - 5);
2447                 strcat(buf, "\n");
2448         }
2449         return 0;
2450 }
2451
2452 static void receive_message(struct sip_pvt *p, struct sip_request *req)
2453 {
2454         char buf[1024];
2455         struct ast_frame f;
2456         if (get_msg_text(buf, sizeof(buf), req)) {
2457                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2458                 return;
2459         }
2460         if (p->owner) {
2461                 if (sipdebug)
2462                         ast_verbose("Message received: '%s'\n", buf);
2463                 memset(&f, 0, sizeof(f));
2464                 f.frametype = AST_FRAME_TEXT;
2465                 f.subclass = 0;
2466                 f.offset = 0;
2467                 f.data = buf;
2468                 f.datalen = strlen(buf);
2469                 ast_queue_frame(p->owner, &f, 1);
2470         }
2471 }
2472
2473 static int sip_show_users(int fd, int argc, char *argv[])
2474 {
2475 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
2476         struct sip_user *user;
2477         if (argc != 3) 
2478                 return RESULT_SHOWUSAGE;
2479         ast_pthread_mutex_lock(&userl.lock);
2480         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2481         for(user=userl.users;user;user=user->next) {
2482                 ast_cli(fd, FORMAT, user->name, user->secret, user->methods, 
2483                                 user->context,
2484                                 user->ha ? "Yes" : "No");
2485         }
2486         ast_pthread_mutex_unlock(&userl.lock);
2487         return RESULT_SUCCESS;
2488 #undef FORMAT
2489 }
2490
2491 static int sip_show_peers(int fd, int argc, char *argv[])
2492 {
2493 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s %-10s\n"
2494 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-8d %-10s\n"
2495         struct sip_peer *peer;
2496         char name[256] = "";
2497         if (argc != 3)
2498                 return RESULT_SHOWUSAGE;
2499         ast_pthread_mutex_lock(&peerl.lock);
2500         ast_cli(fd, FORMAT2, "Name/username", "Host", "   ", "Mask", "Port", "Status");
2501         for (peer = peerl.peers;peer;peer = peer->next) {
2502                 char nm[20] = "";
2503                 char status[20];
2504                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2505                 if (strlen(peer->username))
2506                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2507                 else
2508                         strncpy(name, peer->name, sizeof(name) - 1);
2509                 if (peer->maxms) {
2510                         if (peer->lastms < 0)
2511                                 strcpy(status, "UNREACHABLE");
2512                         else if (peer->lastms > peer->maxms) 
2513                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2514                         else if (peer->lastms) 
2515                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2516                         else 
2517                                 strcpy(status, "UNKNOWN");
2518                 } else 
2519                         strcpy(status, "Unmonitored");
2520                 ast_cli(fd, FORMAT, name, 
2521                                         peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2522                                         peer->dynamic ? "(D)" : "   ",
2523                                         nm,
2524                                         ntohs(peer->addr.sin_port), status);
2525         }
2526         ast_pthread_mutex_unlock(&peerl.lock);
2527         return RESULT_SUCCESS;
2528 #undef FORMAT
2529 #undef FORMAT2
2530 }
2531
2532 static char *regstate2str(int regstate)
2533 {
2534         switch(regstate) {
2535         case REG_STATE_UNREGISTERED:
2536                 return "Unregistered";
2537         case REG_STATE_REGSENT:
2538                 return "Request Sent";
2539         case REG_STATE_AUTHSENT:
2540                 return "Auth. Sent";
2541         case REG_STATE_REGISTERED:
2542                 return "Registered";
2543         case REG_STATE_REJECTED:
2544                 return "Rejected";
2545         case REG_STATE_TIMEOUT:
2546                 return "Timeout";
2547         case REG_STATE_NOAUTH:
2548                 return "No Authentication";
2549         default:
2550                 return "Unknown";
2551         }
2552 }
2553
2554 static int sip_show_registry(int fd, int argc, char *argv[])
2555 {
2556 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
2557 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
2558         struct sip_registry *reg;
2559         char host[80];
2560         char state[20];
2561         if (argc != 3)
2562                 return RESULT_SHOWUSAGE;
2563         ast_pthread_mutex_lock(&peerl.lock);
2564         ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
2565         for (reg = registrations;reg;reg = reg->next) {
2566                 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2567                 snprintf(state, sizeof(state), "%s", regstate2str(reg->regstate));
2568                 ast_cli(fd, FORMAT, host, 
2569                                         reg->username, state, reg->refresh, regstate2str(reg->regstate));
2570         }
2571         ast_pthread_mutex_unlock(&peerl.lock);
2572         return RESULT_SUCCESS;
2573 #undef FORMAT
2574 #undef FORMAT2
2575 }
2576
2577 static int sip_show_channels(int fd, int argc, char *argv[])
2578 {
2579 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %s\n"
2580 #define FORMAT  "%-15.15s  %-10.10s  %-11.11s  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %d\n"
2581         struct sip_pvt *cur;
2582         int numchans = 0;
2583         if (argc != 3)
2584                 return RESULT_SHOWUSAGE;
2585         ast_pthread_mutex_lock(&iflock);
2586         cur = iflist;
2587         ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2588         while (cur) {
2589                         ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr), 
2590                                                 strlen(cur->username) ? cur->username : "(None)", 
2591                                                 cur->callid, 
2592                                                 cur->ocseq, cur->icseq, 
2593                                                 0,
2594                                                 0,
2595                                                 cur->owner ? cur->owner->nativeformats : 0);
2596                 cur = cur->next;
2597                 numchans++;
2598         }
2599         ast_pthread_mutex_unlock(&iflock);
2600         ast_cli(fd, "%d active SIP channel(s)\n", numchans);
2601         return RESULT_SUCCESS;
2602 #undef FORMAT
2603 #undef FORMAT2
2604 }
2605
2606 static void receive_info(struct sip_pvt *p, struct sip_request *req)
2607 {
2608         char buf[1024] = "";
2609         struct ast_frame f;
2610         char *c;
2611         /* Try getting the "signal=" part */
2612         if ((c = get_sdp(req, "Signal"))) {
2613                 strncpy(buf, c, sizeof(buf) - 1);
2614         } else if (get_msg_text(buf, sizeof(buf), req)) {
2615                 /* Normal INFO method */
2616                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2617                 return;
2618         }
2619         
2620         if (p->owner) {
2621                 if (strlen(buf)) {
2622                         if (sipdebug)
2623                                 ast_verbose("DTMF received: '%c'\n", buf[0]);
2624                         memset(&f, 0, sizeof(f));
2625                         f.frametype = AST_FRAME_DTMF;
2626                         f.subclass = buf[0];
2627                         f.offset = 0;
2628                         f.data = NULL;
2629                         f.datalen = 0;
2630                         ast_queue_frame(p->owner, &f, 1);
2631                 }
2632         }
2633 }
2634
2635 static int sip_do_debug(int fd, int argc, char *argv[])
2636 {
2637         if (argc != 2)
2638                 return RESULT_SHOWUSAGE;
2639         sipdebug = 1;
2640         ast_cli(fd, "SIP Debugging Enabled\n");
2641         return RESULT_SUCCESS;
2642 }
2643
2644 static int sip_no_debug(int fd, int argc, char *argv[])
2645 {
2646         if (argc != 3)
2647                 return RESULT_SHOWUSAGE;
2648         sipdebug = 0;
2649         ast_cli(fd, "SIP Debugging Disabled\n");
2650         return RESULT_SUCCESS;
2651 }
2652
2653 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len);
2654
2655 static int do_register_auth(struct sip_pvt *p, struct sip_request *req) {
2656         char digest[256];
2657         memset(digest,0,sizeof(digest));
2658         reply_digest(p,req, "WWW-Authenticate", "REGISTER", (char *)&digest, sizeof(digest) );
2659         return transmit_register(p->registry,"REGISTER",(char *)&digest); 
2660 }
2661
2662 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req) {
2663         char digest[256];
2664         memset(digest,0,sizeof(digest));
2665         reply_digest(p,req, "Proxy-Authenticate", "INVITE", (char *)&digest, sizeof(digest) );
2666         return transmit_invite(p,"INVITE",1,(char *)&digest, NULL); 
2667 }
2668
2669 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
2670
2671         char tmp[256] = "";
2672         char *realm = "";
2673         char *nonce = "";
2674         char *c;
2675         char a1[256];
2676         char a2[256];
2677         char a1_hash[256];
2678         char a2_hash[256];
2679         char resp[256];
2680         char resp_hash[256];
2681         char uri[256] = "";
2682
2683
2684         strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
2685         c = tmp;
2686         c+=strlen("Digest ");
2687         while (c) {
2688                 while (*c && (*c < 33)) c++;
2689                 if (!*c)
2690                         break;
2691                         if (!strncasecmp(c,"realm=", strlen("realm="))) {
2692                                 c+=strlen("realm=");
2693                                 if ((*c == '\"')) {
2694                                         realm=++c;
2695                                         if ((c = strchr(c,'\"')))
2696                                                 *c = '\0';
2697                                 } else {
2698                                         realm = c;
2699                                         if ((c = strchr(c,',')))
2700                                                 *c = '\0';
2701                                 }
2702
2703                         } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
2704                                 c+=strlen("nonce=");
2705                                 if ((*c == '\"')) {
2706                                         nonce=++c;
2707                                         if ((c = strchr(c,'\"')))
2708                                                 *c = '\0';
2709                                 } else {
2710                                         nonce = c;
2711                                         if ((c = strchr(c,',')))
2712                                                 *c = '\0';
2713                                 }
2714                         } else
2715                                 c = strchr(c,',');
2716                         if (c)
2717                                 c++;
2718                         }
2719
2720         /* Okay.  We've got the realm and nonce from the server.  Now lets build the MD5 digest. */
2721         snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
2722
2723         snprintf(a1,sizeof(a1),"%s:%s:%s",p->peername,realm,p->peersecret);
2724         snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
2725         md5_hash(a1_hash,a1);
2726         md5_hash(a2_hash,a2);
2727         snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,nonce,a2_hash);
2728         md5_hash(resp_hash,resp);
2729
2730         snprintf(digest,digest_len,"Digest username=\"%s\", realm=\"%s\", algorithm=\"MD5\", uri=\"%s\", nonce=\"%s\", response=\"%s\"",p->peername,realm,uri,nonce,resp_hash);
2731
2732         return 0;
2733 }
2734         
2735
2736         
2737         
2738
2739
2740 static char show_users_usage[] = 
2741 "Usage: sip show users\n"
2742 "       Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
2743
2744 static char show_channels_usage[] = 
2745 "Usage: sip show channels\n"
2746 "       Lists all currently active SIP channels.\n";
2747
2748 static char show_peers_usage[] = 
2749 "Usage: sip show peers\n"
2750 "       Lists all known SIP peers.\n";
2751
2752 static char show_reg_usage[] =
2753 "Usage: sip show registry\n"
2754 "       Lists all registration requests and status.\n";
2755
2756 static char debug_usage[] = 
2757 "Usage: sip debug\n"
2758 "       Enables dumping of SIP packets for debugging purposes\n";
2759
2760 static char no_debug_usage[] = 
2761 "Usage: sip no debug\n"
2762 "       Disables dumping of SIP packets for debugging purposes\n";
2763
2764 static struct ast_cli_entry  cli_show_users = 
2765         { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
2766 static struct ast_cli_entry  cli_show_channels =
2767         { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage };
2768 static struct ast_cli_entry  cli_show_peers =
2769         { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
2770 static struct ast_cli_entry  cli_show_registry =
2771         { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
2772 static struct ast_cli_entry  cli_debug =
2773         { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
2774 static struct ast_cli_entry  cli_no_debug =
2775         { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
2776
2777
2778 static int sip_poke_peer_s(void *data)
2779 {
2780         struct sip_peer *peer = data;
2781         peer->pokeexpire = -1;
2782         sip_poke_peer(peer);
2783         return 0;
2784 }
2785
2786 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req)
2787 {
2788         char *to;
2789         char *msg, *c;
2790         struct ast_rtp *rtp;
2791         struct ast_channel *owner;
2792         struct sip_peer *peer;
2793         int pingtime;
2794         struct timeval tv;
2795         c = get_header(req, "Cseq");
2796         msg = strchr(c, ' ');
2797         if (!msg) msg = ""; else msg++;
2798 retrylock:
2799         ast_pthread_mutex_lock(&p->lock);
2800         /* Go ahead and lock the owner if it has one -- we may need it */
2801         if (p->owner && pthread_mutex_trylock(&p->owner->lock)) {
2802                 ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
2803                 ast_pthread_mutex_unlock(&p->lock);
2804                 /* Sleep infintismly short amount of time */
2805                 usleep(1);
2806                 goto retrylock;
2807         }
2808         owner = p->owner;
2809         if (p->peerpoke) {
2810                 /* We don't really care what the response is, just that it replied back. 
2811                    Well, as long as it's not a 100 response...  since we might
2812                    need to hang around for something more "difinitive" */
2813                 if (resp != 100) {
2814                         peer = p->peerpoke;
2815                         gettimeofday(&tv, NULL);
2816                         pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
2817                                                 (tv.tv_usec - peer->ps.tv_usec) / 1000;
2818                         if (pingtime < 1)
2819                                 pingtime = 1;
2820                         if ((peer->lastms < 0)  || (peer->lastms > peer->maxms)) {
2821                                 if (pingtime <= peer->maxms)
2822                                 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE!\n", peer->name);
2823                         } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
2824                                 if (pingtime > peer->maxms)
2825                                         ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED!\n", peer->name);
2826                         }
2827                         peer->lastms = pingtime;
2828                         peer->call = NULL;
2829                         if (peer->pokeexpire > -1)
2830                                 ast_sched_del(sched, peer->pokeexpire);
2831                         if (!strcasecmp(msg, "INVITE"))
2832                                 transmit_request(p, "ACK", 0);
2833                         sip_destroy(p);
2834                         p = NULL;
2835                         /* Try again eventually */
2836                         if ((peer->lastms < 0)  || (peer->lastms > peer->maxms))
2837                                 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
2838                         else
2839                                 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
2840                 }
2841         } else if (p->outgoing) {
2842                 if (p->initid > -1) {
2843                         /* Don't auto congest anymore since we've gotten something useful back */
2844                         ast_sched_del(sched, p->initid);
2845                         p->initid = -1;
2846                 }
2847                 /* Get their tag if we haven't already */
2848                 if (!strlen(p->theirtag)) {
2849                         to = get_header(req, "To");
2850                         to = strstr(to, "tag=");
2851                         if (to) {
2852                                 to += 4;
2853                                 strncpy(p->theirtag, to, sizeof(p->theirtag) - 1);
2854                                 to = strchr(p->theirtag, ';');
2855                                 if (to)
2856                                         *to = '\0';
2857                         }
2858                 }
2859                 
2860                 switch(resp) {
2861                 case 100:
2862                         break;
2863                 case 183:       /* We don't really need this since we pass in-band audio anyway */
2864                         /* Not important */
2865                         if (strlen(get_header(req, "Content-Type")))
2866                                 process_sdp(p, req);
2867                         break;
2868                 case 180:
2869                         if (p->owner) {
2870                                 ast_queue_control(p->owner, AST_CONTROL_RINGING, 0);
2871                                 if (p->owner->_state != AST_STATE_UP)
2872                                         ast_setstate(p->owner, AST_STATE_RINGING);
2873                         }
2874                         break;
2875                 case 200:
2876                         if (strlen(get_header(req, "Content-Type")))
2877                                 process_sdp(p, req);
2878                         if (p->owner) {
2879                                 if (p->owner->_state != AST_STATE_UP) {
2880                                         ast_setstate(p->owner, AST_STATE_UP);
2881                                         ast_queue_control(p->owner, AST_CONTROL_ANSWER, 0);
2882                                 }
2883                         }
2884                         if (!strcasecmp(msg, "INVITE"))
2885                                 transmit_request(p, "ACK", 0);
2886                         else if (!strcasecmp(msg, "REGISTER"))
2887                         {
2888                                 /* char *exp; */
2889                                 int expires;
2890                                 struct sip_registry *r;
2891                                 transmit_request(p, "ACK", 0);
2892                                 r=p->registry;
2893                                 r->regstate=REG_STATE_REGISTERED;
2894                                 ast_log(LOG_NOTICE, "Registration successful\n");
2895                                 ast_log(LOG_NOTICE, "Cancelling timeout %d\n", r->timeout);
2896                                 if (r->timeout) 
2897                                         ast_sched_del(sched, r->timeout);
2898                                 r->timeout=0;
2899                                 /* set us up for re-registering */
2900                                 /* figure out how long we got registered for */
2901                                 if (r->expire != -1)
2902                                         ast_sched_del(sched, r->expire);
2903                                 expires=atoi(get_header(req, "expires"));
2904                                 if (!expires) expires=default_expirey;
2905                                         r->expire=ast_sched_add(sched, (expires-2)*1000, sip_reregister, r); 
2906
2907                         }
2908                         break;
2909                 case 401: /* Not authorized on REGISTER */
2910                         /* XXX: Do I need to ACK the 401? 
2911                         transmit_request(p, "ACK", 0);
2912                         */
2913                         do_register_auth(p, req);
2914                         break;
2915                 case 407:
2916                         /* First we ACK */
2917                         transmit_request(p, "ACK", 0);
2918                         /* Then we AUTH */
2919                         do_proxy_auth(p, req);
2920                         /* This is just a hack to kill the channel while testing */
2921                         /* 
2922                         p->alreadygone = 1;
2923                         if (p->rtp) {
2924                                 rtp = p->rtp;
2925                                 p->rtp = NULL;
2926                                 ast_rtp_destroy(rtp);
2927                         }
2928                         if (p->owner)
2929                                 ast_queue_hangup(p->owner,0);
2930                         transmit_request(p,"ACK",0);
2931                         sip_destroy(p);
2932                         p = NULL;
2933                         */
2934                         break;
2935                 default:
2936                         if ((resp >= 400) && (resp < 700)) {
2937                                 if (option_verbose > 2) 
2938                                         ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, inet_ntoa(p->sa.sin_addr));
2939                                 p->alreadygone = 1;
2940                                 if (p->rtp) {
2941                                         rtp = p->rtp;
2942                                         p->rtp = NULL;
2943                                         /* Immediately stop RTP */
2944                                         ast_rtp_destroy(rtp);
2945                                 }
2946                                 /* XXX Locking issues?? XXX */
2947                                 switch(resp) {
2948                                 case 486: /* Busy here */
2949                                 case 600: /* Busy everywhere */
2950                                         if (p->owner)
2951                                                 ast_queue_control(p->owner, AST_CONTROL_BUSY, 0);
2952                                         break;
2953                                 case 480: /* Temporarily Unavailable */
2954                                 case 404: /* Not Found */
2955                                 case 410: /* Gone */
2956                                 case 500: /* Server error */
2957                                 case 501: /* Not Implemented */
2958                                         if (owner)
2959                                                 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
2960                                         break;
2961                                 default:
2962                                         /* Send hangup */       
2963                                         if (owner)
2964                                                 ast_queue_hangup(p->owner, 0);
2965                                         break;
2966                                 }
2967                                 transmit_request(p, "ACK", 0);
2968                                 __sip_destroy(p, 0);
2969                                 p = NULL;
2970                         } else
2971                                 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));
2972                 }
2973         } else {
2974                 if (sipdebug)
2975                         ast_verbose("Message is %s\n", msg);
2976                 switch(resp) {
2977                 case 200:
2978                         if (!strcasecmp(msg, "INVITE") || !strcasecmp(msg, "REGISTER") )
2979                                 transmit_request(p, "ACK", 0);
2980                         break;
2981                 }
2982         }
2983         if (owner)
2984                 ast_pthread_mutex_unlock(&owner->lock);
2985         if (p)
2986                 ast_pthread_mutex_unlock(&p->lock);
2987 }
2988
2989 static int determine_firstline_parts( struct sip_request *req ) {
2990
2991   char *e, *cmd;
2992   int len;
2993   
2994   cmd= req->header[0];
2995   while(*cmd && (*cmd < 33)) {
2996     cmd++;
2997   }
2998   if (!*cmd) {
2999     return -1;
3000   }
3001   e= cmd;
3002   while(*e && (*e > 32)) {
3003     e++;
3004   }
3005   /* Get the command */
3006   if (*e) {
3007     *e = '\0';
3008     e++;
3009   }
3010   req->rlPart1= cmd;
3011   while( *e && ( *e < 33 ) ) {
3012     e++; 
3013   }
3014   if( !*e ) {
3015     return -1;
3016   }
3017     
3018   if ( !strcasecmp(cmd, "SIP/2.0") ) {
3019     /* We have a response */
3020     req->rlPart2= e;
3021     len= strlen( req->rlPart2 );
3022     if( len < 2 ) { return -1; }
3023     e+= len - 1;
3024     while( *e && *e<33 ) {
3025       e--; 
3026     }
3027     *(++e)= '\0';
3028   } else {
3029     /* We have a request */
3030     if( *e == '<' ) { 
3031       e++;
3032       if( !*e ) { return -1; }  
3033     }
3034     req->rlPart2= e;
3035     if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
3036       return -1;
3037     }
3038     while( isspace( *(--e) ) ) {}
3039     if( *e == '>' ) {
3040       *e= '\0';
3041     } else {
3042       *(++e)= '\0';
3043     }
3044   }
3045   return 1;
3046 }
3047
3048 static int attempt_transfer(struct sip_pvt *p1, struct sip_pvt *p2)
3049 {
3050         if (!p1->owner || !p2->owner) {
3051                 ast_log(LOG_WARNING, "Transfer attempted without dual ownership?\n");
3052                 return -1;
3053         }
3054         if (p1->owner->bridge) {
3055                 if (p2->owner->bridge)
3056                         ast_moh_stop(p2->owner->bridge);
3057                 ast_moh_stop(p1->owner->bridge);
3058                 ast_moh_stop(p1->owner);
3059                 ast_moh_stop(p2->owner);
3060                 if (ast_channel_masquerade(p2->owner, p1->owner->bridge)) {
3061                         ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p2->owner->name, p1->owner->bridge->name);
3062                         return -1;
3063                 }
3064         } else if (p2->owner->bridge) {
3065                 ast_moh_stop(p2->owner->bridge);
3066                 ast_moh_stop(p2->owner);
3067                 ast_moh_stop(p1->owner);
3068                 if (ast_channel_masquerade(p1->owner, p2->owner->bridge)) {
3069                         ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p1->owner->name, p2->owner->bridge->name);
3070                         return -1;
3071                 }
3072         } else {
3073                 ast_log(LOG_NOTICE, "Transfer attempted with no bridged calls to transfer\n");
3074                 return -1;
3075         }
3076         return 0;
3077 }
3078
3079 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin)
3080 {
3081         struct sip_request resp;
3082         char *cmd;
3083         char *cseq;
3084         char *e;
3085         struct ast_channel *c=NULL;
3086         int seqno;
3087         int len;
3088         int ignore=0;
3089         int respid;
3090         int res;
3091         /* Clear out potential response */
3092         memset(&resp, 0, sizeof(resp));
3093         /* Get Method and Cseq */
3094         cseq = get_header(req, "Cseq");
3095         cmd = req->header[0];
3096         /* Must have Cseq */
3097         if (!strlen(cmd) || !strlen(cseq))
3098                         return -1;
3099         if (sscanf(cseq, "%i%n", &seqno, &len) != 1) {
3100                 ast_log(LOG_DEBUG, "No seqno in '%s'\n", cmd);
3101                 return -1;
3102         }
3103         /* Get the command */
3104         cseq += len;
3105
3106   /* Determine the request URI for sip, sips or tel URIs */
3107         if( determine_firstline_parts( req ) < 0 ) {
3108           return -1; 
3109         }
3110         cmd= req->rlPart1;
3111         e= req->rlPart2;
3112         
3113         if (strcasecmp(cmd, "SIP/2.0")) {
3114                 /* Request coming in */                 
3115                 if (p->icseq && (p->icseq < seqno)) {
3116                         ast_log(LOG_DEBUG, "Ignoring out of order packet %d (expecting %d)\n", seqno, p->icseq);
3117                         return -1;
3118                 } else if (p->icseq && (p->icseq != seqno)) {
3119                         /* ignore means "don't do anything with it" but still have to 
3120                            respond appropriately  */
3121                         ignore=1;
3122                 }
3123         } else {
3124                 /* Response to our request -- Do some sanity checks */  
3125                 if (!p->initreq.headers) {
3126                         ast_log(LOG_DEBUG, "That's odd...  Got a response on a call we dont know about.\n");
3127                         sip_destroy(p);
3128                         return 0;
3129                 } else if (p->ocseq && (p->ocseq < seqno)) {
3130                         ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
3131                         return -1;
3132                 } else if (p->ocseq && (p->ocseq != seqno)) {
3133                         /* ignore means "don't do anything with it" but still have to 
3134                            respond appropriately  */
3135                         ignore=1;
3136                 }
3137         }
3138         
3139         if (strcmp(cmd, "SIP/2.0"))
3140                 /* Next should follow monotonically increasing */
3141                 p->icseq = seqno + 1;
3142
3143         /* Initialize the context if it hasn't been already */
3144         if (!strcasecmp(cmd, "OPTIONS")) {
3145                 if (!strlen(p->context))
3146                         strncpy(p->context, context, sizeof(p->context) - 1);
3147                 res = get_destination(p, req);
3148                 if (res < 0)
3149                         transmit_response_with_allow(p, "404 Not Found", req);
3150                 else if (res > 0)
3151                         transmit_response_with_allow(p, "484 Address Incomplete", req);
3152                 else 
3153                         transmit_response_with_allow(p, "200 OK", req);
3154         } else if (!strcasecmp(cmd, "INVITE")) {
3155                 if (p->outgoing && p->owner && (p->owner->_state != AST_STATE_UP)) {
3156                         /* This is a call to ourself.  Send ourselves an error code and stop
3157                            processing immediately, as SIP really has no good mechanism for
3158                            being able to call yourself */
3159                         transmit_response(p, "482 Loop Detected", req);
3160                         /* We do NOT destroy p here, so that our response will be accepted */
3161                         return 0;
3162                 }
3163                 /* Process the SDP portion */
3164                 if (!ignore) {
3165                         /* Use this as the basis */
3166                         if (sipdebug)
3167                                 ast_verbose("Using latest request as basis request\n");
3168                         copy_request(&p->initreq, req);
3169                         check_via(p, req);
3170                         if (strlen(get_header(req, "Content-Type"))) {
3171                                 if (process_sdp(p, req))
3172                                         return -1;
3173                         } else {
3174                                 p->capability = capability;
3175                                 ast_log(LOG_DEBUG, "Hm....  No sdp for the moemnt\n");
3176                         }
3177                 } else if (sipdebug)
3178                         ast_verbose("Ignoring this request\n");
3179                 if (!p->lastinvite) {
3180                         /* Handle authentication if this is our first invite */
3181                         res = check_user(p, req, cmd, e);
3182                         if (res) {
3183                                 if (res < 0) {
3184                                         ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
3185                                         sip_destroy(p);
3186                                 }
3187                                 return 0;
3188                         }
3189                         /* Initialize the context if it hasn't been already */
3190                         if (!strlen(p->context))
3191                                 strncpy(p->context, context, sizeof(p->context) - 1);
3192                         if ((res = get_destination(p, NULL))) {
3193                                 if (res < 0)
3194                                         transmit_response(p, "404 Not Found", req);
3195                                 else
3196                                         transmit_response(p, "484 Address Incomplete", req);
3197                                 sip_destroy(p);
3198                                 p = NULL;
3199                                 c = NULL;
3200                         } else {
3201                                 /* If no extension was specified, use the s one */
3202                                 if (!strlen(p->exten))
3203                                         strncpy(p->exten, "s", sizeof(p->exten) - 1);
3204                                 /* Initialize tag */    
3205                                 p->tag = rand();
3206                                 /* First invitation */
3207                                 c = sip_new(p, AST_STATE_DOWN, strlen(p->username) ? p->username : NULL);
3208                         }
3209                         
3210                 } else 
3211                         c = p->owner;
3212                 if (!ignore && p)
3213                         p->lastinvite = seqno;
3214                 if (c) {
3215                         switch(c->_state) {
3216                         case AST_STATE_DOWN:
3217                                 transmit_response(p, "100 Trying", req);
3218                                 ast_setstate(c, AST_STATE_RING);
3219                                 if (ast_pbx_start(c)) {
3220                                         ast_log(LOG_WARNING, "Failed to start PBX :(\n");
3221                                         ast_hangup(c);
3222                                         transmit_response(p, "503 Unavailable", req);
3223                                         sip_destroy(p);
3224                                 }
3225                                 break;
3226                         case AST_STATE_RING:
3227                                 transmit_response(p, "100 Trying", req);
3228                                 break;
3229                         case AST_STATE_RINGING:
3230                                 transmit_response(p, "180 Ringing", req);
3231                                 break;
3232                         case AST_STATE_UP:
3233                                 transmit_response_with_sdp(p, "200 OK", req);
3234                                 break;
3235                         default:
3236                                 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
3237                                 transmit_response(p, "100 Trying", req);
3238                         }
3239                 } else {
3240                         if (p) {
3241                                 ast_log(LOG_NOTICE, "Unable to create/find channel\n");
3242                                 transmit_response(p, "503 Unavailable", req);
3243                                 sip_destroy(p);
3244                         }
3245                 }
3246         } else if (!strcasecmp(cmd, "REFER")) {
3247                 struct ast_channel *transfer_to;
3248                 ast_log(LOG_DEBUG, "We found a REFER!\n");
3249                 if (!strlen(p->context))
3250                         strncpy(p->context, context, sizeof(p->context) - 1);
3251                 res = get_refer_info(p, req);
3252                 if (res < 0)
3253                         transmit_response_with_allow(p, "404 Not Found", req);
3254                 else if (res > 0)
3255                         transmit_response_with_allow(p, "484 Address Incomplete", req);
3256                 else {
3257                         transmit_response(p, "202 Accepted", req);
3258                         if (p->refer_call) {
3259                                 ast_log(LOG_DEBUG,"202 Accepted (supervised)\n");
3260                                 attempt_transfer(p, p->refer_call);
3261                                 ast_pthread_mutex_unlock(&p->refer_call->lock);
3262                                 p->refer_call = NULL;
3263                         } else {
3264                                 ast_log(LOG_DEBUG,"202 Accepted (blind)\n");
3265                                 c = p->owner;
3266                                 if (c) {
3267                                         transfer_to = c->bridge;
3268                                         if (transfer_to)
3269                                                 ast_async_goto(transfer_to,"", p->refer_to,1, 1);
3270                                 }
3271                         }
3272                 }
3273         } else if (!strcasecmp(cmd, "CANCEL") || !strcasecmp(cmd, "BYE")) {
3274                 copy_request(&p->initreq, req);
3275                 p->alreadygone = 1;
3276                 if (p->rtp) {
3277                         /* Immediately stop RTP */
3278                         ast_rtp_destroy(p->rtp);
3279                         p->rtp = NULL;
3280                 }
3281                 if (p->owner)
3282                         ast_queue_hangup(p->owner, 1);
3283                 transmit_response(p, "200 OK", req);
3284         } else if (!strcasecmp(cmd, "MESSAGE")) {
3285                 if (sipdebug)
3286                         ast_verbose("Receiving message!\n");
3287                 receive_message(p, req);
3288                 transmit_response(p, "200 OK", req);
3289         } else if (!strcasecmp(cmd, "INFO")) {
3290                 if (sipdebug)
3291                         ast_verbose("Receiving DTMF!\n");
3292                 receive_info(p, req);
3293                 transmit_response(p, "200 OK", req);
3294         } else if (!strcasecmp(cmd, "REGISTER")) {
3295                 /* Use this as the basis */
3296                 if (sipdebug)
3297                         ast_verbose("Using latest request as basis request\n");
3298                 copy_request(&p->initreq, req);
3299                 check_via(p, req);
3300                 transmit_response(p, "100 Trying", req);
3301                 if ((res = register_verify(p, sin, req, e)) < 0) 
3302                         ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s'\n", get_header(req, "To"), inet_ntoa(sin->sin_addr));
3303                 if (res < 1) {
3304                         sip_destroy(p);
3305                 }
3306         } else if (!strcasecmp(cmd, "ACK")) {
3307                 /* Uhm, I haven't figured out the point of the ACK yet.  Are we
3308                    supposed to retransmit responses until we get an ack? 
3309                    Make sure this is on a valid call */
3310                 if (strlen(get_header(req, "Content-Type"))) {
3311                         if (process_sdp(p, req))
3312                                 return -1;
3313                 } 
3314                 if (!p->lastinvite && !strlen(p->randdata))
3315                         sip_destroy(p);
3316         } else if (!strcasecmp(cmd, "SIP/2.0")) {
3317                 while(*e && (*e < 33)) e++;
3318                 if (sscanf(e, "%i %n", &respid, &len) != 1) {
3319                         ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
3320                 } else {
3321                         handle_response(p, respid, e + len, req);
3322                 }
3323         } else {
3324                 transmit_response_with_allow(p, "405 Method Not Allowed", req);
3325                 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
3326                         cmd, inet_ntoa(p->sa.sin_addr));
3327         }
3328         return 0;
3329 }
3330
3331 static int sipsock_read(int *id, int fd, short events, void *ignore)
3332 {
3333         struct sip_request req;
3334         struct sockaddr_in sin;
3335         struct sip_pvt *p;
3336         int res;
3337         int len;
3338         len = sizeof(sin);
3339         memset(&req, 0, sizeof(req));
3340         res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
3341         if (res < 0) {
3342                 if (errno != ECONNREFUSED)
3343                         ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
3344                 return 1;
3345         }
3346         req.data[res] = '\0';
3347         req.len = res;
3348         if (sipdebug)
3349                 ast_verbose("Sip read: \n%s\n", req.data);
3350         parse(&req);
3351         if (req.headers < 2) {
3352                 /* Must have at least two headers */
3353                 return 1;
3354         }
3355         /* Process request, with netlock held */
3356         ast_pthread_mutex_lock(&netlock);
3357         p = find_call(&req, &sin);
3358         if (p) {
3359                 handle_request(p, &req, &sin);
3360         }
3361         ast_pthread_mutex_unlock(&netlock);
3362         return 1;
3363 }
3364
3365 static int sip_send_mwi_to_peer(struct sip_peer *peer)
3366 {
3367         /* Called with peerl lock, but releases it */
3368         struct sip_pvt *p;
3369         int hasmsgs;
3370         char name[256] = "";
3371         /* Check for messages */
3372         hasmsgs = ast_app_has_voicemail(peer->mailbox);
3373         
3374         time(&peer->lastmsgcheck);
3375         
3376         /* Return now if it's the same thing we told them last time */
3377         if (hasmsgs == peer->lastmsgssent) {
3378                 ast_pthread_mutex_unlock(&peerl.lock);
3379                 return 0;
3380         }
3381         
3382         p = sip_alloc(NULL, NULL);
3383         if (!p) {
3384                 ast_log(LOG_WARNING, "Unable to build sip pvt data for MWI\n");
3385                 ast_pthread_mutex_unlock(&peerl.lock);
3386                 return -1;
3387         }
3388         strncpy(name, peer->name, sizeof(name) - 1);
3389         peer->lastmsgssent = hasmsgs;
3390         ast_pthread_mutex_unlock(&peerl.lock);
3391         if (create_addr(p, peer->name)) {
3392                 /* Maybe they're not registered, etc. */
3393                 sip_destroy(p);
3394                 return 0;
3395         }
3396         /* Recalculate our side, and recalculate Call ID */
3397         memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
3398         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
3399         build_callid(p->callid, sizeof(p->callid), p->ourip);
3400         /* Send MWI */
3401         transmit_notify(p, hasmsgs);
3402         /* Destroy channel */
3403         sip_destroy(p);
3404         return 0;
3405 }
3406
3407 static void *do_monitor(void *data)
3408 {
3409         int res;
3410         struct sip_pkt *p;
3411         struct sip_pvt *sip;
3412         struct sip_peer *peer;
3413         time_t t;
3414         /* Add an I/O event to our UDP socket */
3415         if (sipsock > -1) 
3416                 ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
3417         
3418         /* This thread monitors all the frame relay interfaces which are not yet in use
3419            (and thus do not have a separate thread) indefinitely */
3420         /* From here on out, we die whenever asked */
3421         for(;;) {
3422                 /* Check for interfaces needing to be killed */
3423                 ast_pthread_mutex_lock(&iflock);
3424 restartsearch:          
3425                 sip = iflist;
3426                 while(sip) {
3427                         if (sip->needdestroy) {
3428                                 __sip_destroy(sip, 1);
3429                                 goto restartsearch;
3430                         }
3431                         sip = sip->next;
3432                 }
3433                 ast_pthread_mutex_unlock(&iflock);
3434                 /* Don't let anybody kill us right away.  Nobody should lock the interface list
3435                    and wait for the monitor list, but the other way around is okay. */
3436                 ast_pthread_mutex_lock(&monlock);
3437                 /* Lock the network interface */
3438                 ast_pthread_mutex_lock(&netlock);
3439                 p = packets;
3440                 while(p) {
3441                         /* Handle any retransmissions */
3442                         p = p->next;
3443                 }
3444                 /* Okay, now that we know what to do, release the network lock */
3445                 ast_pthread_mutex_unlock(&netlock);
3446                 /* And from now on, we're okay to be killed, so release the monitor lock as well */
3447                 ast_pthread_mutex_unlock(&monlock);
3448                 pthread_testcancel();
3449                 /* Wait for sched or io */
3450                 res = ast_sched_wait(sched);
3451                 if ((res < 0) || (res > 1000))
3452                         res = 1000;
3453                 res = ast_io_wait(io, res);
3454                 ast_pthread_mutex_lock(&monlock);
3455                 if (res >= 0) 
3456                         ast_sched_runq(sched);
3457                 ast_pthread_mutex_lock(&peerl.lock);
3458                 peer = peerl.peers;
3459                 time(&t);
3460                 while(peer) {
3461                         if (strlen(peer->mailbox) && (t - peer->lastmsgcheck > 10)) {
3462                                 sip_send_mwi_to_peer(peer);
3463                                 break;
3464                         }
3465                         peer = peer->next;
3466                 }
3467                 /* Remember, sip_send_mwi_to_peer releases the lock if we've called it */
3468                 if (!peer)
3469                         ast_pthread_mutex_unlock(&peerl.lock);
3470                 ast_pthread_mutex_unlock(&monlock);
3471         }
3472         /* Never reached */
3473         return NULL;
3474         
3475 }
3476
3477 static int restart_monitor(void)
3478 {
3479         /* If we're supposed to be stopped -- stay stopped */
3480         if (monitor_thread == -2)
3481                 return 0;
3482         if (ast_pthread_mutex_lock(&monlock)) {
3483                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
3484                 return -1;
3485         }
3486         if (monitor_thread == pthread_self()) {
3487                 ast_pthread_mutex_unlock(&monlock);
3488                 ast_log(LOG_WARNING, "Cannot kill myself\n");
3489                 return -1;
3490         }
3491         if (monitor_thread) {
3492                 /* Wake up the thread */
3493                 pthread_kill(monitor_thread, SIGURG);
3494         } else {
3495                 /* Start a new monitor */
3496                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
3497                         ast_pthread_mutex_unlock(&monlock);
3498                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
3499                         return -1;
3500                 }
3501         }
3502         ast_pthread_mutex_unlock(&monlock);
3503         return 0;
3504 }
3505
3506 static int sip_poke_noanswer(void *data)
3507 {
3508         struct sip_peer *peer = data;
3509         peer->pokeexpire = -1;
3510         if (peer->lastms > -1)
3511                 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!\n", peer->name);
3512         if (peer->call)
3513                 sip_destroy(peer->call);
3514         peer->call = NULL;
3515         peer->lastms = -1;
3516         /* Try again quickly */
3517         peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
3518         return 0;
3519 }
3520
3521 static int sip_poke_peer(struct sip_peer *peer)
3522 {
3523         struct sip_pvt *p;
3524         if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
3525       &n