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