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