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