dom mar 16 23:37:23 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         if (strlen(get_header(req, "Record-Route")))
1658                 copy_header(resp, req, "Record-Route");
1659         if (!strstr(ot, "tag=")) {
1660                 /* Add the proper tag if we don't have it already.  If they have specified
1661                    their tag, use it.  Otherwise, use our own tag */
1662                 if (strlen(p->theirtag))
1663                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1664                 else if (p->tag)
1665                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1666                 else
1667                         strncpy(newto, ot, sizeof(newto) - 1);
1668                 ot = newto;
1669         }
1670         add_header(resp, "To", ot);
1671         copy_header(resp, req, "Call-ID");
1672         copy_header(resp, req, "CSeq");
1673         add_header(resp, "User-Agent", "Asterisk PBX");
1674         if (p->expirey) {
1675                 /* For registration responses, we also need expirey and
1676                    contact info */
1677                 char tmp[80];
1678                 char contact[256];
1679                 char *c;
1680                 if ((c=getsipuri(ot))) {
1681                         snprintf(contact, sizeof(contact), "<%s@%s>", c, inet_ntoa(p->ourip));
1682                         free(c);
1683                 } else {
1684                         snprintf(contact, sizeof(contact), "<%s>", inet_ntoa(p->ourip));
1685                 }
1686                 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1687                 add_header(resp, "Expires", tmp);
1688                 add_header(resp, "Contact", contact);
1689         } else {
1690                 char contact[256];
1691                 /* XXX This isn't exactly right and it's implemented
1692                        very stupidly *sigh* XXX */
1693                 char *c;
1694                 if ((c=getsipuri(ot))) {
1695                         snprintf(contact, sizeof(contact), "<%s@%s>", c, inet_ntoa(p->ourip));
1696                         free(c);
1697                 } else {
1698                         snprintf(contact, sizeof(contact), "<%s>", inet_ntoa(p->ourip));
1699                 }
1700                 add_header(resp, "Contact", contact);
1701         }
1702         return 0;
1703 }
1704
1705 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
1706 {
1707         struct sip_request *orig = &p->initreq;
1708         char stripped[80] ="";
1709         char tmp[80];
1710         char newto[256];
1711         char *c, *n;
1712         char *ot, *of;
1713
1714         memset(req, 0, sizeof(struct sip_request));
1715         
1716         if (inc)
1717                 p->ocseq++;
1718
1719         if (p->outgoing)
1720                 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1721         else
1722                 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1723         
1724         c = strchr(stripped, '<');
1725         if (c) 
1726                 c++;
1727         else
1728                 c = stripped;
1729         n = strchr(c, '>');
1730         if (n)
1731                 *n = '\0';
1732         
1733         init_req(req, msg, c);
1734
1735         snprintf(tmp, sizeof(tmp), "%d %s", p->ocseq, msg);
1736
1737         add_header(req, "Via", p->via);
1738
1739         ot = get_header(orig, "To");
1740         of = get_header(orig, "From");
1741
1742         if (!strstr(ot, "tag=")) {
1743                 /* Add the proper tag if we don't have it already.  If they have specified
1744                    their tag, use it.  Otherwise, use our own tag */
1745                 if (strlen(p->theirtag))
1746                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1747                 else
1748                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1749                 ot = newto;
1750         }
1751
1752         if (p->outgoing) {
1753                 add_header(req, "From", of);
1754                 add_header(req, "To", ot);
1755         } else {
1756                 add_header(req, "From", ot);
1757                 add_header(req, "To", of);
1758         }
1759         copy_header(req, orig, "Call-ID");
1760         add_header(req, "CSeq", tmp);
1761
1762         add_header(req, "User-Agent", "Asterisk PBX");
1763         return 0;
1764 }
1765
1766 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
1767 {
1768         struct sip_request resp;
1769         respprep(&resp, p, msg, req);
1770         add_header(&resp, "Content-Length", "0");
1771         add_blank_header(&resp);
1772         return send_response(p, &resp);
1773 }
1774
1775 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
1776 {
1777         struct sip_request resp;
1778         respprep(&resp, p, msg, req);
1779         add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
1780         add_header(&resp, "Accept", "application/sdp");
1781         add_header(&resp, "Content-Length", "0");
1782         add_blank_header(&resp);
1783         return send_response(p, &resp);
1784 }
1785
1786 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata)
1787 {
1788         struct sip_request resp;
1789         char tmp[256];
1790         snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
1791         respprep(&resp, p, msg, req);
1792         add_header(&resp, "Proxy-Authenticate", tmp);
1793         add_header(&resp, "Content-Length", "0");
1794         add_blank_header(&resp);
1795         return send_response(p, &resp);
1796 }
1797
1798 static int add_text(struct sip_request *req, char *text)
1799 {
1800         /* XXX Convert \n's to \r\n's XXX */
1801         int len = strlen(text);
1802         char clen[256];
1803         snprintf(clen, sizeof(clen), "%d", len);
1804         add_header(req, "Content-Type", "text/plain");
1805         add_header(req, "Content-Length", clen);
1806         add_line(req, text);
1807         return 0;
1808 }
1809
1810 static int add_digit(struct sip_request *req, char digit)
1811 {
1812         char tmp[256];
1813         int len;
1814         char clen[256];
1815         snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
1816         len = strlen(tmp);
1817         snprintf(clen, sizeof(clen), "%d", len);
1818         add_header(req, "Content-Type", "application/dtmf-relay");
1819         add_header(req, "Content-Length", clen);
1820         add_line(req, tmp);
1821         return 0;
1822 }
1823
1824 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
1825 {
1826         int len;
1827         int codec;
1828         int alreadysent = 0;
1829         char costr[80];
1830         struct sockaddr_in sin;
1831         struct sip_codec_pref *cur;
1832         char v[256];
1833         char s[256];
1834         char o[256];
1835         char c[256];
1836         char t[256];
1837         char m[256];
1838         char a[1024] = "";
1839         int x;
1840         struct sockaddr_in dest;
1841         /* XXX We break with the "recommendation" and send our IP, in order that our
1842                peer doesn't have to gethostbyname() us XXX */
1843         len = 0;
1844         if (!p->rtp) {
1845                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
1846                 return -1;
1847         }
1848         ast_rtp_get_us(p->rtp, &sin);
1849         if (rtp) {
1850                 ast_rtp_get_peer(rtp, &dest);
1851         } else {
1852                 dest.sin_addr = p->ourip;
1853                 dest.sin_port = sin.sin_port;
1854         }
1855         if (sipdebug)
1856                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
1857         snprintf(v, sizeof(v), "v=0\r\n");
1858         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
1859         snprintf(s, sizeof(s), "s=session\r\n");
1860         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
1861         snprintf(t, sizeof(t), "t=0 0\r\n");
1862         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
1863         /* Start by sending our preferred codecs */
1864         cur = prefs;
1865         while(cur) {
1866                 if (p->capability & cur->codec) {
1867                         if (sipdebug)
1868                                 ast_verbose("Answering with preferred capability %d\n", cur->codec);
1869                         codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
1870                         if (codec > -1) {
1871                                 snprintf(costr, sizeof(costr), " %d", codec);
1872                                 strcat(m, costr);
1873                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
1874                                 strcat(a, costr);
1875                         }
1876                 }
1877                 alreadysent |= cur->codec;
1878                 cur = cur->next;
1879         }
1880         /* Now send any other common codecs, and non-codec formats: */
1881         for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1882                 if ((p->capability & x) && !(alreadysent & x)) {
1883                         if (sipdebug)
1884                                 ast_verbose("Answering with capability %d\n", x);       
1885                         codec = ast_rtp_lookup_code(p->rtp, 1, x);
1886                         if (codec > -1) {
1887                         snprintf(costr, sizeof(costr), " %d", codec);
1888                                 strcat(m, costr);
1889                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
1890                                 strcat(a, costr);
1891                         }
1892                 }
1893         }
1894         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
1895                 if (p->nonCodecCapability & x) {
1896                         if (sipdebug)
1897                                 ast_verbose("Answering with non-codec capability %d\n", x);
1898                         codec = ast_rtp_lookup_code(p->rtp, 0, x);
1899                         if (codec > -1) {
1900                                 snprintf(costr, sizeof(costr), " %d", codec);
1901                                 strcat(m, costr);
1902                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
1903                                 strcat(a, costr);
1904                                 if (x == AST_RTP_DTMF) {
1905                                   /* Indicate we support DTMF...  Not sure about 16, but MSN supports it so dang it, we will too... */
1906                                   snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
1907                                            codec);
1908                                   strcat(a, costr);
1909                                 }
1910                         }
1911                 }
1912         }
1913         strcat(m, "\r\n");
1914         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
1915         snprintf(costr, sizeof(costr), "%d", len);
1916         add_header(resp, "Content-Type", "application/sdp");
1917         add_header(resp, "Content-Length", costr);
1918         add_line(resp, v);
1919         add_line(resp, o);
1920         add_line(resp, s);
1921         add_line(resp, c);
1922         add_line(resp, t);
1923         add_line(resp, m);
1924         add_line(resp, a);
1925         return 0;
1926 }
1927
1928 static void copy_request(struct sip_request *dst,struct sip_request *src)
1929 {
1930         long offset;
1931         int x;
1932         offset = ((void *)dst) - ((void *)src);
1933         /* First copy stuff */
1934         memcpy(dst, src, sizeof(*dst));
1935         /* Now fix pointer arithmetic */
1936         for (x=0;x<src->headers;x++)
1937                 dst->header[x] += offset;
1938         for (x=0;x<src->lines;x++)
1939                 dst->line[x] += offset;
1940 }
1941
1942 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req)
1943 {
1944         struct sip_request resp;
1945         respprep(&resp, p, msg, req);
1946         add_sdp(&resp, p, NULL);
1947         return send_response(p, &resp);
1948 }
1949
1950 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
1951 {
1952         struct sip_request resp;
1953         reqprep(&resp, p, "INVITE", 1);
1954         add_sdp(&resp, p, rtp);
1955         return send_response(p, &resp);
1956 }
1957
1958 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
1959 {
1960         char invite[256];
1961         char from[256];
1962         char to[256];
1963         char tmp[80];
1964         char cid[256];
1965         char *l = "asterisk", *n=NULL;
1966         if (p->owner && p->owner->callerid) {
1967                 strcpy(cid, p->owner->callerid);
1968                 ast_callerid_parse(cid, &n, &l);
1969                 if (l) 
1970                         ast_shrink_phone_number(l);
1971                 if (!l || !ast_isphonenumber(l))
1972                                 l = "asterisk";
1973         }
1974         if (!n)
1975                 n = l;
1976         snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%08x", n, l, inet_ntoa(p->ourip), p->tag);
1977         if (strlen(p->username)) {
1978                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1979                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1980                 } else {
1981                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
1982                 }
1983         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1984                 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1985         } else {
1986                 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
1987         }
1988         /* If there is a VXML URL append it to the SIP URL */
1989         if (vxml_url)
1990         {
1991                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
1992         }
1993         else
1994         {
1995                 snprintf(to, sizeof(to), "<%s>", invite );
1996         }
1997         memset(req, 0, sizeof(struct sip_request));
1998         init_req(req, cmd, invite);
1999         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2000
2001         add_header(req, "Via", p->via);
2002         add_header(req, "From", from);
2003         {
2004                 char contact2[256] ="", *c, contact[256];
2005                 /* XXX This isn't exactly right and it's implemented
2006                        very stupidly *sigh* XXX */
2007                 strncpy(contact2, from, sizeof(contact2)-1);
2008                 c = ditch_braces(contact2);
2009                 snprintf(contact, sizeof(contact), "<%s>", c);
2010                 add_header(req, "Contact", contact);
2011         }
2012         add_header(req, "To", to);
2013         add_header(req, "Call-ID", p->callid);
2014         add_header(req, "CSeq", tmp);
2015         add_header(req, "User-Agent", "Asterisk PBX");
2016 }
2017
2018 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
2019 {
2020         struct sip_request req;
2021         initreqprep(&req, p, cmd, vxml_url);
2022         if (auth)
2023                 add_header(&req, "Proxy-Authorization", auth);
2024         if (sdp) {
2025                 add_sdp(&req, p, NULL);
2026         } else {
2027                 add_header(&req, "Content-Length", "0");
2028                 add_blank_header(&req);
2029         }
2030         if (!p->initreq.headers) {
2031                 /* Use this as the basis */
2032                 copy_request(&p->initreq, &req);
2033                 parse(&p->initreq);
2034         }
2035         p->lastinvite = p->ocseq;
2036         return send_request(p, &req);
2037 }
2038
2039 static int transmit_notify(struct sip_pvt *p, int hasmsgs)
2040 {
2041         struct sip_request req;
2042         char tmp[256];
2043         char clen[20];
2044         initreqprep(&req, p, "NOTIFY", NULL);
2045         add_header(&req, "Event", "message-summary");
2046         add_header(&req, "Content-Type", "text/plain");
2047
2048         snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", hasmsgs ? "yes" : "no");
2049         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2050         add_header(&req, "Content-Length", clen);
2051         add_line(&req, tmp);
2052
2053         if (!p->initreq.headers) {
2054                 /* Use this as the basis */
2055                 copy_request(&p->initreq, &req);
2056                 parse(&p->initreq);
2057         }
2058
2059         p->lastinvite = p->ocseq;
2060         return send_request(p, &req);
2061 }
2062
2063 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2064
2065 static int sip_reregister(void *data) 
2066 {
2067         /* if we are here, we know that we need to reregister. */
2068         struct sip_registry *r=(struct sip_registry *)data;
2069         return sip_do_register(r);
2070         
2071 }
2072
2073
2074 static int sip_do_register(struct sip_registry *r)
2075 {
2076         int res;
2077         ast_pthread_mutex_lock(&r->lock);
2078         res=transmit_register(r, "REGISTER", NULL);
2079         ast_pthread_mutex_unlock(&r->lock);
2080         return res;
2081 }
2082
2083 static int sip_reg_timeout(void *data)
2084 {
2085         /* if we are here, our registration timed out, so we'll just do it over */
2086         struct sip_registry *r=data;
2087         int res;
2088         ast_pthread_mutex_lock(&r->lock);
2089         ast_log(LOG_NOTICE, "Registration timed out, trying again\n"); 
2090         r->regstate=REG_STATE_UNREGISTERED;
2091         /* cancel ourselves first!!! */
2092         /* ast_sched_del(sched,r->timeout); */
2093         res=transmit_register(r, "REGISTER", NULL);
2094         ast_pthread_mutex_unlock(&r->lock);
2095         return res;
2096 }
2097
2098 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2099 {
2100         struct sip_request req;
2101         char from[256];
2102         char to[256];
2103         char tmp[80];
2104         char via[80];
2105         char addr[80];
2106         struct sip_pvt *p;
2107         /* exit if we are already in process with this registrar ?*/
2108         if ( (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
2109                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2110                 return 0;
2111         }
2112
2113
2114         if (!(p=r->call)) {
2115                 if (!r->callid_valid) {
2116                   build_callid(r->callid, sizeof(r->callid), __ourip);
2117                   r->callid_valid=1;
2118                 }
2119                 p=sip_alloc( r->callid, &r->addr, 0);
2120                 p->outgoing = 1;
2121                 r->call=p;
2122                 p->registry=r;
2123                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2124                 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2125                 strncpy(p->username, r->username, sizeof(p->username)-1);
2126         }
2127
2128         /* set up a timeout */
2129         if (auth==NULL && !r->timeout)  {
2130                 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
2131                 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
2132         }
2133
2134         snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2135         snprintf(to, sizeof(to),     "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2136         
2137         snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
2138
2139         memset(&req, 0, sizeof(req));
2140         init_req(&req, cmd, addr);
2141
2142         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2143
2144         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
2145         add_header(&req, "Via", via);
2146         add_header(&req, "From", from);
2147         add_header(&req, "To", to);
2148         {
2149                 char contact[256];
2150                 snprintf(contact, sizeof(contact), "<sip:%s@%s:%d;transport=udp>", r->contact, inet_ntoa(p->ourip), ourport);
2151                 add_header(&req, "Contact", contact);
2152         }
2153         add_header(&req, "Call-ID", p->callid);
2154         add_header(&req, "CSeq", tmp);
2155         add_header(&req, "User-Agent", "Asterisk PBX");
2156         if (auth) 
2157                 add_header(&req, "Authorization", auth);
2158
2159         snprintf(tmp, sizeof(tmp), "%d", default_expirey);
2160         add_header(&req, "Expires", tmp);
2161         add_header(&req, "Event", "registration");
2162         copy_request(&p->initreq, &req);
2163         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2164         return send_request(p, &req);
2165 }
2166
2167 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2168 {
2169         struct sip_request req;
2170         reqprep(&req, p, "MESSAGE", 1);
2171         add_text(&req, text);
2172         return send_request(p, &req);
2173 }
2174
2175 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2176 {
2177         struct sip_request req;
2178         reqprep(&req, p, "INFO", 1);
2179         add_digit(&req, digit);
2180         return send_request(p, &req);
2181 }
2182
2183 static int transmit_request(struct sip_pvt *p, char *msg, int inc)
2184 {
2185         struct sip_request resp;
2186         reqprep(&resp, p, msg, inc);
2187         add_header(&resp, "Content-Length", "0");
2188         add_blank_header(&resp);
2189         return send_request(p, &resp);
2190 }
2191
2192 static int expire_register(void *data)
2193 {
2194         struct sip_peer *p = data;
2195         memset(&p->addr, 0, sizeof(p->addr));
2196         p->expire = -1;
2197         return 0;
2198 }
2199
2200 static int sip_poke_peer(struct sip_peer *peer);
2201
2202 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2203 {
2204         char contact[80]= ""; 
2205         char *expires = get_header(req, "Expires");
2206         int expirey = atoi(expires);
2207         char *c, *n, *pt;
2208         int port;
2209         struct hostent *hp;
2210         struct sockaddr_in oldsin;
2211         if (!strlen(expires)) {
2212                 expires = strstr(get_header(req, "Contact"), "expires=");
2213                 if (expires) 
2214                         if (sscanf(expires + 8, "%d;", &expirey) != 1)
2215                                 expirey = 0;
2216         }
2217         /* Look for brackets */
2218         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2219         c = contact;
2220         
2221         if ((n=strchr(c, '<'))) {
2222                 c = n + 1;
2223                 n = strchr(c, '>');
2224                 /* Lose the part after the > */
2225                 if (n) 
2226                         *n = '\0';
2227         }
2228         if (!strcasecmp(c, "*")) {
2229                 /* This means remove all registrations and return OK */
2230                 memset(&p->addr, 0, sizeof(p->addr));
2231                 if (p->expire > -1)
2232                         ast_sched_del(sched, p->expire);
2233                 p->expire = -1;
2234                 if (option_verbose > 2)
2235                         ast_verbose(VERBOSE_PREFIX_3 "Unegistered SIP '%s'\n", p->username);
2236                 return 0;
2237         }
2238         /* Make sure it's a SIP URL */
2239         if (strncasecmp(c, "sip:", 4)) {
2240                 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2241         } else
2242                 c += 4;
2243         /* Ditch q */
2244         n = strchr(c, ';');
2245         if (n) 
2246                 *n = '\0';
2247         /* Grab host */
2248         n = strchr(c, '@');
2249         if (!n) {
2250                 n = c;
2251                 c = NULL;
2252         } else {
2253                 *n = '\0';
2254                 n++;
2255         }
2256         pt = strchr(n, ':');
2257         if (pt) {
2258                 *pt = '\0';
2259                 pt++;
2260                 port = atoi(pt);
2261         } else
2262                 port = DEFAULT_SIP_PORT;
2263         memcpy(&oldsin, &p->addr, sizeof(oldsin));
2264         if (!p->nat) {
2265                 /* XXX This could block for a long time XXX */
2266                 hp = gethostbyname(n);
2267                 if (!hp)  {
2268                         ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2269                         return -1;
2270                 }
2271                 p->addr.sin_family = AF_INET;
2272                 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2273                 p->addr.sin_port = htons(port);
2274         } else {
2275                 /* Don't trust the contact field.  Just use what they came to us
2276                    with */
2277                 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2278         }
2279         if (c)
2280                 strncpy(p->username, c, sizeof(p->username) - 1);
2281         else
2282                 strcpy(p->username, "");
2283         if (p->expire > -1)
2284                 ast_sched_del(sched, p->expire);
2285         if ((expirey < 1) || (expirey > max_expirey))
2286                 expirey = max_expirey;
2287         p->expire = ast_sched_add(sched, (expirey + 10) * 1000, expire_register, p);
2288         pvt->expirey = expirey;
2289         if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
2290                 sip_poke_peer(p);
2291                 if (option_verbose > 2)
2292                         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);
2293         }
2294         return 0;
2295 }
2296
2297 static void md5_hash(char *output, char *input)
2298 {
2299                 struct MD5Context md5;
2300                 unsigned char digest[16];
2301                 char *ptr;
2302                 int x;
2303                 MD5Init(&md5);
2304                 MD5Update(&md5, input, strlen(input));
2305                 MD5Final(digest, &md5);
2306                 ptr = output;
2307                 for (x=0;x<16;x++)
2308                         ptr += sprintf(ptr, "%2.2x", digest[x]);
2309 }
2310
2311 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri)
2312 {
2313         int res = -1;
2314         /* Always OK if no secret */
2315         if (!strlen(secret))
2316                 return 0;
2317         if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2318                 snprintf(randdata, randlen, "%08x", rand());
2319                 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata);
2320                 res = 1;
2321         } else {
2322                 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2323                    an example in the spec of just what it is you're doing a hash on. */
2324                 char a1[256];
2325                 char a2[256];
2326                 char a1_hash[256];
2327                 char a2_hash[256];
2328                 char resp[256];
2329                 char resp_hash[256];
2330                 char tmp[256] = "";
2331                 char *c;
2332                 char *response ="";
2333                 char *resp_uri ="";
2334
2335                 /* Find their response among the mess that we'r sent for comparison */
2336                 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2337                 c = tmp;
2338
2339                 while(c) {
2340                         while (*c && (*c < 33)) c++;
2341                         if (!*c)
2342                                 break;
2343                         if (!strncasecmp(c, "response=", strlen("response="))) {
2344                                 c+= strlen("response=");
2345                                 if ((*c == '\"')) {
2346                                         response=++c;
2347                                         if((c = strchr(c,'\"')))
2348                                                 *c = '\0';
2349
2350                                 } else {
2351                                         response=c;
2352                                         if((c = strchr(c,',')))
2353                                                 *c = '\0';
2354                                 }
2355
2356                         } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2357                                 c+= strlen("uri=");
2358                                 if ((*c == '\"')) {
2359                                         resp_uri=++c;
2360                                         if((c = strchr(c,'\"')))
2361                                                 *c = '\0';
2362                                 } else {
2363                                         resp_uri=c;
2364                                         if((c = strchr(c,',')))
2365                                                 *c = '\0';
2366                                 }
2367
2368                         } else
2369                                 c = strchr(c, ',');
2370                         if (c)
2371                                 c++;
2372                 }
2373                 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2374                 if(strlen(resp_uri))
2375                         snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2376                 else
2377                         snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2378                 md5_hash(a1_hash, a1);
2379                 md5_hash(a2_hash, a2);
2380                 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2381                 md5_hash(resp_hash, resp);
2382
2383                 /* resp_hash now has the expected response, compare the two */
2384
2385                 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2386                         /* Auth is OK */
2387                         res = 0;
2388                 }
2389                 /* Assume success ;-) */
2390                 /* Eliminate random data */
2391                 strcpy(randdata, "");
2392         }
2393         return res;
2394 }
2395
2396 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2397 {
2398         int res = -1;
2399         struct sip_peer *peer;
2400         char tmp[256] = "";
2401         char *name, *c;
2402         char *t;
2403         /* Terminate URI */
2404         t = uri;
2405         while(*t && (*t > 32) && (*t != ';'))
2406                 t++;
2407         *t = '\0';
2408         
2409         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2410         c = ditch_braces(tmp);
2411         if (!strncmp(c, "sip:", 4)) {
2412                 name = c + 4;
2413         } else {
2414                 name = c;
2415                 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
2416         }
2417         c = strchr(name, '@');
2418         if (c) 
2419                 *c = '\0';
2420         ast_pthread_mutex_lock(&peerl.lock);
2421         peer = peerl.peers;
2422         while(peer) {
2423                 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2424                         p->nat = peer->nat;
2425                         transmit_response(p, "100 Trying", req);
2426                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri))) {
2427                                 if (parse_contact(p, peer, req)) {
2428                                         ast_log(LOG_WARNING, "Failed to parse contact info\n");
2429                                 } else {
2430                                         /* Say OK and ask subsystem to retransmit msg counter */
2431                                         transmit_response(p, "200 OK", req);
2432                                         peer->lastmsgssent = -1;
2433                                         res = 0;
2434                                 }
2435                         } 
2436                         break;
2437                 }       
2438                 peer = peer->next;
2439         }
2440         ast_pthread_mutex_unlock(&peerl.lock);
2441         if (res < 0)
2442                 transmit_response(p, "401 Unauthorized", &p->initreq);
2443         return res;
2444 }
2445
2446 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2447 {
2448         char tmp[256] = "", *c, *a;
2449         struct sip_request *req;
2450         
2451         req = oreq;
2452         if (!req)
2453                 req = &p->initreq;
2454         strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2455         c = ditch_braces(tmp);
2456         if (strncmp(c, "sip:", 4)) {
2457                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2458                 return -1;
2459         }
2460         c += 4;
2461         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2462                 *a = '\0';
2463         }
2464         if (sipdebug)
2465                 ast_verbose("Looking for %s in %s\n", c, p->context);
2466         if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2467                 if (!oreq)
2468                         strncpy(p->exten, c, sizeof(p->exten) - 1);
2469                 return 0;
2470         }
2471
2472         if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2473                 return 1;
2474         }
2475         
2476         return -1;
2477 }
2478
2479 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2480 {
2481         char tmp[256] = "", *c, *a;
2482         char tmp2[256] = "", *c2, *a2;
2483         char tmp3[256];
2484         char tmp4[256];
2485         char tmp5[256] = "";            /* CallID to replace */
2486         struct sip_request *req;
2487         struct sip_pvt *p2;
2488         
2489         req = oreq;
2490         if (!req)
2491                 req = &p->initreq;
2492         strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2493         strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
2494         strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
2495         strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
2496         
2497         c = ditch_braces(tmp);
2498         c2 = ditch_braces(tmp2);
2499         
2500                 
2501         if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
2502                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2503                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c2);
2504                 return -1;
2505         }
2506         c += 4;
2507         c2 += 4;
2508         if ((a = strchr(c, '?'))) {
2509                 /* Search for arguemnts */
2510                 *a = '\0';
2511                 a++;
2512                 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
2513                         strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
2514                         if ((a = strchr(tmp5, '%'))) {
2515                                 /* Yuck!  Pingtel converts the '@' to a %40, icky icky!  Convert
2516                                    back to an '@' */
2517                                 if ((a[1] == '4') && (a[2] == '0')) {
2518                                         *a = '@';
2519                                         memmove(a + 1, a+3, strlen(a + 3));
2520                                 }
2521                         }
2522                         if ((a = strchr(tmp5, '%'))) 
2523                                 *a = '\0';
2524                 }
2525         }
2526         
2527         if ((a = strchr(c, '@')))
2528                 *a = '\0';
2529         if ((a = strchr(c, ';'))) 
2530                 *a = '\0';
2531         
2532
2533         if ((a2 = strchr(c2, '@')))
2534                 *a2 = '\0';
2535
2536         if ((a2 = strchr(c2, ';'))) 
2537                 *a2 = '\0';
2538         
2539         
2540         if (sipdebug) {
2541                 ast_verbose("Looking for %s in %s\n", c, p->context);
2542                 ast_verbose("Looking for %s in %s\n", c2, p->context);
2543         }
2544         if (strlen(tmp5)) {     
2545                 /* This is a supervised transfer */
2546                 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
2547                 
2548                 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
2549                 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
2550                 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
2551                 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
2552                 p->refer_call = NULL;
2553                 ast_pthread_mutex_lock(&iflock);
2554                 /* Search interfaces and find the match */
2555                 p2 = iflist;
2556                 while(p2) {
2557                         if (!strcmp(p2->callid, tmp5)) {
2558                                 /* Go ahead and lock it before returning */
2559                                 ast_pthread_mutex_lock(&p2->lock);
2560                                 p->refer_call = p2;
2561                                 break;
2562                         }
2563                         p2 = p2->next;
2564                 }
2565                 ast_pthread_mutex_unlock(&iflock);
2566                 if (p->refer_call)
2567                         return 0;
2568                 else
2569                         ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
2570         } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2571                 /* This is an unsupervised transfer */
2572                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
2573                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
2574                 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
2575                 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
2576                 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
2577                 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
2578                 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
2579                 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
2580                 p->refer_call = NULL;
2581                 return 0;
2582         } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2583                 return 1;
2584         }
2585
2586         return -1;
2587 }
2588
2589
2590 static int check_via(struct sip_pvt *p, struct sip_request *req)
2591 {
2592         char via[256] = "";
2593         char *c, *pt;
2594         struct hostent *hp;
2595
2596         memset(via, 0, sizeof(via));
2597         strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
2598         c = strchr(via, ';');
2599         if (c) 
2600                 *c = '\0';
2601         c = strchr(via, ' ');
2602         if (c) {
2603                 *c = '\0';
2604                 c++;
2605                 while(*c && (*c < 33))
2606                         c++;
2607                 if (strcmp(via, "SIP/2.0/UDP")) {
2608                         ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
2609                         return -1;
2610                 }
2611                 pt = strchr(c, ':');
2612                 if (pt) {
2613                         *pt = '\0';
2614                         pt++;
2615                 }
2616                 hp = gethostbyname(c);
2617                 if (!hp) {
2618                         ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
2619                         return -1;
2620                 }
2621                 memset(&p->sa, 0, sizeof(p->sa));
2622                 p->sa.sin_family = AF_INET;
2623                 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2624                 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
2625                 if (sipdebug) {
2626                         if (p->nat)
2627                                 ast_verbose("Sending to %s : %d (NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2628                         else
2629                                 ast_verbose("Sending to %s : %d (non-NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2630                 }
2631         }
2632         return 0;
2633 }
2634
2635 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri)
2636 {
2637         struct sip_user *user;
2638         char *of, from[256] = "", *c;
2639         int res = 0;
2640         char *t;
2641         /* Terminate URI */
2642         t = uri;
2643         while(*t && (*t > 32) && (*t != ';'))
2644                 t++;
2645         *t = '\0';
2646         of = get_header(req, "From");
2647         strncpy(from, of, sizeof(from) - 1);
2648         of = ditch_braces(from);
2649         if (strncmp(of, "sip:", 4)) {
2650                 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2651         } else
2652                 of += 4;
2653         /* Get just the username part */
2654         if ((c = strchr(of, '@')))
2655                 *c = '\0';
2656         if ((c = strchr(of, ':')))
2657                 *c = '\0';
2658         strncpy(p->callerid, of, sizeof(p->callerid) - 1);
2659         if (!strlen(of))
2660                         return 0;
2661         ast_pthread_mutex_lock(&userl.lock);
2662         user = userl.users;
2663         while(user) {
2664                 if (!strcasecmp(user->name, of)) {
2665                         p->nat = user->nat;
2666                         if (p->rtp) {
2667                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", p->nat);
2668                                 ast_rtp_setnat(p->rtp, p->nat);
2669                         }
2670                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri))) {
2671                                 strncpy(p->context, user->context, sizeof(p->context) - 1);
2672                                 if (strlen(user->callerid) && strlen(p->callerid)) 
2673                                         strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
2674                                 strncpy(p->username, user->name, sizeof(p->username) - 1);
2675                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)  -1);
2676                                 p->canreinvite = user->canreinvite;
2677                                 p->amaflags = user->amaflags;
2678                                 if (user->dtmfmode)
2679                                         p->dtmfmode = user->dtmfmode;
2680                         }
2681                         break;
2682                 }
2683                 user = user->next;
2684         }
2685         ast_pthread_mutex_unlock(&userl.lock);
2686         return res;
2687 }
2688
2689 static int get_msg_text(char *buf, int len, struct sip_request *req)
2690 {
2691         int x;
2692         strcpy(buf, "");
2693         for (x=0;x<req->lines;x++) {
2694                 strncat(buf, req->line[x], len - strlen(buf) - 5);
2695                 strcat(buf, "\n");
2696         }
2697         return 0;
2698 }
2699
2700 static void receive_message(struct sip_pvt *p, struct sip_request *req)
2701 {
2702         char buf[1024];
2703         struct ast_frame f;
2704         if (get_msg_text(buf, sizeof(buf), req)) {
2705                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2706                 return;
2707         }
2708         if (p->owner) {
2709                 if (sipdebug)
2710                         ast_verbose("Message received: '%s'\n", buf);
2711                   memset(&f, 0, sizeof(f));
2712                   f.frametype = AST_FRAME_TEXT;
2713                   f.subclass = 0;
2714                   f.offset = 0;
2715                   f.data = buf;
2716                   f.datalen = strlen(buf);
2717                   ast_queue_frame(p->owner, &f, 1);
2718         }
2719 }
2720
2721 static int sip_show_users(int fd, int argc, char *argv[])
2722 {
2723 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
2724         struct sip_user *user;
2725         if (argc != 3) 
2726                 return RESULT_SHOWUSAGE;
2727         ast_pthread_mutex_lock(&userl.lock);
2728         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2729         for(user=userl.users;user;user=user->next) {
2730                 ast_cli(fd, FORMAT, user->name, user->secret, user->methods, 
2731                                 user->context,
2732                                 user->ha ? "Yes" : "No");
2733         }
2734         ast_pthread_mutex_unlock(&userl.lock);
2735         return RESULT_SUCCESS;
2736 #undef FORMAT
2737 }
2738
2739 static int sip_show_peers(int fd, int argc, char *argv[])
2740 {
2741 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s %-10s\n"
2742 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-8d %-10s\n"
2743         struct sip_peer *peer;
2744         char name[256] = "";
2745         if (argc != 3)
2746                 return RESULT_SHOWUSAGE;
2747         ast_pthread_mutex_lock(&peerl.lock);
2748         ast_cli(fd, FORMAT2, "Name/username", "Host", "   ", "Mask", "Port", "Status");
2749         for (peer = peerl.peers;peer;peer = peer->next) {
2750                 char nm[20] = "";
2751                 char status[20];
2752                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2753                 if (strlen(peer->username))
2754                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2755                 else
2756                         strncpy(name, peer->name, sizeof(name) - 1);
2757                 if (peer->maxms) {
2758                         if (peer->lastms < 0)
2759                                 strcpy(status, "UNREACHABLE");
2760                         else if (peer->lastms > peer->maxms) 
2761                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2762                         else if (peer->lastms) 
2763                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2764                         else 
2765                                 strcpy(status, "UNKNOWN");
2766                 } else 
2767                         strcpy(status, "Unmonitored");
2768                 ast_cli(fd, FORMAT, name, 
2769                                         peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2770                                         peer->dynamic ? "(D)" : "   ",
2771                                         nm,
2772                                         ntohs(peer->addr.sin_port), status);
2773         }
2774         ast_pthread_mutex_unlock(&peerl.lock);
2775         return RESULT_SUCCESS;
2776 #undef FORMAT
2777 #undef FORMAT2
2778 }
2779
2780 static char *regstate2str(int regstate)
2781 {
2782         switch(regstate) {
2783         case REG_STATE_UNREGISTERED:
2784                 return "Unregistered";
2785         case REG_STATE_REGSENT:
2786                 return "Request Sent";
2787         case REG_STATE_AUTHSENT:
2788                 return "Auth. Sent";
2789         case REG_STATE_REGISTERED:
2790                 return "Registered";
2791         case REG_STATE_REJECTED:
2792                 return "Rejected";
2793         case REG_STATE_TIMEOUT:
2794                 return "Timeout";
2795         case REG_STATE_NOAUTH:
2796                 return "No Authentication";
2797         default:
2798                 return "Unknown";
2799         }
2800 }
2801
2802 static int sip_show_registry(int fd, int argc, char *argv[])
2803 {
2804 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
2805 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
2806         struct sip_registry *reg;
2807         char host[80];
2808         char state[20];
2809         if (argc != 3)
2810                 return RESULT_SHOWUSAGE;
2811         ast_pthread_mutex_lock(&peerl.lock);
2812         ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
2813         for (reg = registrations;reg;reg = reg->next) {
2814                 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2815                 snprintf(state, sizeof(state), "%s", regstate2str(reg->regstate));
2816                 ast_cli(fd, FORMAT, host, 
2817                                         reg->username, state, reg->refresh, regstate2str(reg->regstate));
2818         }
2819         ast_pthread_mutex_unlock(&peerl.lock);
2820         return RESULT_SUCCESS;
2821 #undef FORMAT
2822 #undef FORMAT2
2823 }
2824
2825 static int sip_show_channels(int fd, int argc, char *argv[])
2826 {
2827 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %s\n"
2828 #define FORMAT  "%-15.15s  %-10.10s  %-11.11s  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %d\n"
2829         struct sip_pvt *cur;
2830         int numchans = 0;
2831         if (argc != 3)
2832                 return RESULT_SHOWUSAGE;
2833         ast_pthread_mutex_lock(&iflock);
2834         cur = iflist;
2835         ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2836         while (cur) {
2837                         ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr), 
2838                                                 strlen(cur->username) ? cur->username : "(None)", 
2839                                                 cur->callid, 
2840                                                 cur->ocseq, cur->icseq, 
2841                                                 0,
2842                                                 0,
2843                                                 cur->owner ? cur->owner->nativeformats : 0);
2844                 cur = cur->next;
2845                 numchans++;
2846         }
2847         ast_pthread_mutex_unlock(&iflock);
2848         ast_cli(fd, "%d active SIP channel(s)\n", numchans);
2849         return RESULT_SUCCESS;
2850 #undef FORMAT
2851 #undef FORMAT2
2852 }
2853
2854 static char *complete_sipch(char *line, char *word, int pos, int state)
2855 {
2856         int which=0;
2857         struct sip_pvt *cur;
2858         char *c = NULL;
2859         ast_pthread_mutex_lock(&iflock);
2860         cur = iflist;
2861         while(cur) {
2862                 if (!strncasecmp(word, cur->callid, strlen(word))) {
2863                         if (++which > state) {
2864                                 c = strdup(cur->callid);
2865                                 break;
2866                         }
2867                 }
2868                 cur = cur->next;
2869         }
2870         ast_pthread_mutex_unlock(&iflock);
2871         return c;
2872 }
2873
2874 static int sip_show_channel(int fd, int argc, char *argv[])
2875 {
2876         struct sip_pvt *cur;
2877         char tmp[256];
2878         if (argc != 4)
2879                 return RESULT_SHOWUSAGE;
2880         ast_pthread_mutex_lock(&iflock);
2881         cur = iflist;
2882         while(cur) {
2883                 if (!strcasecmp(cur->callid, argv[3])) {
2884                         ast_cli(fd, "Call-ID: %s\n", cur->callid);
2885                         ast_cli(fd, "Theoretical Address: %s:%d\n", inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
2886                         ast_cli(fd, "Received Address:    %s:%d\n", inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
2887                         ast_cli(fd, "NAT Support:         %s\n", cur->nat ? "Yes" : "No");
2888                         strcpy(tmp, "");
2889                         if (cur->dtmfmode & SIP_DTMF_RFC2833)
2890                                 strcat(tmp, "rfc2833 ");
2891                         if (cur->dtmfmode & SIP_DTMF_INFO)
2892                                 strcat(tmp, "info ");
2893                         if (cur->dtmfmode & SIP_DTMF_INBAND)
2894                                 strcat(tmp, "inband ");
2895                         ast_cli(fd, "DTMF Mode: %s\n", tmp);
2896                         break;
2897                 }
2898                 cur = cur->next;
2899         }
2900         ast_pthread_mutex_unlock(&iflock);
2901         if (!cur) 
2902                 ast_cli(fd, "No such SIP Call ID '%s'\n", argv[3]);
2903         return RESULT_SUCCESS;
2904 }
2905
2906 static void receive_info(struct sip_pvt *p, struct sip_request *req)
2907 {
2908         char buf[1024] = "";
2909         struct ast_frame f;
2910         char *c;
2911         /* Try getting the "signal=" part */
2912         if ((c = get_sdp(req, "Signal"))) {
2913                 strncpy(buf, c, sizeof(buf) - 1);
2914         } else if (get_msg_text(buf, sizeof(buf), req)) {
2915                 /* Normal INFO method */
2916                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2917                 return;
2918         }
2919         
2920         if (p->owner) {
2921                 if (strlen(buf)) {
2922                         if (sipdebug)
2923                                 ast_verbose("DTMF received: '%c'\n", buf[0]);
2924                         memset(&f, 0, sizeof(f));
2925                         f.frametype = AST_FRAME_DTMF;
2926                         f.subclass = buf[0];
2927                         f.offset = 0;
2928                         f.data = NULL;
2929                         f.datalen = 0;
2930                         ast_queue_frame(p->owner, &f, 1);
2931                 }
2932         }
2933 }
2934
2935 static int sip_do_debug(int fd, int argc, char *argv[])
2936 {
2937         if (argc != 2)
2938                 return RESULT_SHOWUSAGE;
2939         sipdebug = 1;
2940         ast_cli(fd, "SIP Debugging Enabled\n");
2941         return RESULT_SUCCESS;
2942 }
2943
2944 static int sip_no_debug(int fd, int argc, char *argv[])
2945 {
2946         if (argc != 3)
2947                 return RESULT_SHOWUSAGE;
2948         sipdebug = 0;
2949         ast_cli(fd, "SIP Debugging Disabled\n");
2950         return RESULT_SUCCESS;
2951 }
2952
2953 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len);
2954
2955 static int do_register_auth(struct sip_pvt *p, struct sip_request *req) {
2956         char digest[256];
2957         memset(digest,0,sizeof(digest));
2958         reply_digest(p,req, "WWW-Authenticate", "REGISTER", digest, sizeof(digest) );
2959         return transmit_register(p->registry,"REGISTER",digest); 
2960 }
2961
2962 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req) {
2963         char digest[256];
2964         memset(digest,0,sizeof(digest));
2965         reply_digest(p,req, "Proxy-Authenticate", "INVITE", digest, sizeof(digest) );
2966         return transmit_invite(p,"INVITE",1,digest, NULL); 
2967 }
2968
2969 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
2970
2971         char tmp[256] = "";
2972         char *realm = "";
2973         char *nonce = "";
2974         char *c;
2975         char a1[256];
2976         char a2[256];
2977         char a1_hash[256];
2978         char a2_hash[256];
2979         char resp[256];
2980         char resp_hash[256];
2981         char uri[256] = "";
2982
2983
2984         strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
2985         c = tmp;
2986         c+=strlen("Digest ");
2987         while (c) {
2988                 while (*c && (*c < 33)) c++;
2989                 if (!*c)
2990                         break;
2991                         if (!strncasecmp(c,"realm=", strlen("realm="))) {
2992                                 c+=strlen("realm=");
2993                                 if ((*c == '\"')) {
2994                                         realm=++c;
2995                                         if ((c = strchr(c,'\"')))
2996                                                 *c = '\0';
2997                                 } else {
2998                                         realm = c;
2999                                         if ((c = strchr(c,',')))
3000                                                 *c = '\0';
3001                                 }
3002
3003                         } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
3004                                 c+=strlen("nonce=");
3005                                 if ((*c == '\"')) {
3006                                         nonce=++c;
3007                                         if ((c = strchr(c,'\"')))
3008                                                 *c = '\0';
3009                                 } else {
3010                                         nonce = c;
3011                                         if ((c = strchr(c,',')))
3012                                                 *c = '\0';
3013                                 }
3014                         } else
3015                                 c = strchr(c,',');
3016                         if (c)
3017                                 c++;
3018                         }
3019
3020         /* Okay.  We've got the realm and nonce from the server.  Now lets build the MD5 digest. */
3021         snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
3022
3023         snprintf(a1,sizeof(a1),"%s:%s:%s",p->peername,realm,p->peersecret);
3024         snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
3025         md5_hash(a1_hash,a1);
3026         md5_hash(a2_hash,a2);
3027         snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,nonce,a2_hash);
3028         md5_hash(resp_hash,resp);
3029
3030         snprintf(digest,digest_len,"Digest username=\"%s\", realm=\"%s\", algorithm=\"MD5\", uri=\"%s\", nonce=\"%s\", response=\"%s\"",p->peername,realm,uri,nonce,resp_hash);
3031
3032         return 0;
3033 }
3034         
3035
3036         
3037         
3038
3039
3040 static char show_users_usage[] = 
3041 "Usage: sip show users\n"
3042 "       Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
3043
3044 static char show_channels_usage[] = 
3045 "Usage: sip show channels\n"
3046 "       Lists all currently active SIP channels.\n";
3047
3048 static char show_channel_usage[] = 
3049 "Usage: sip show channel <channel>\n"
3050 "       Provides detailed status on a given SIP channel.\n";
3051
3052 static char show_peers_usage[] = 
3053 "Usage: sip show peers\n"
3054 "       Lists all known SIP peers.\n";
3055
3056 static char show_reg_usage[] =
3057 "Usage: sip show registry\n"
3058 "       Lists all registration requests and status.\n";
3059
3060 static char debug_usage[] = 
3061 "Usage: sip debug\n"
3062 "       Enables dumping of SIP packets for debugging purposes\n";
3063
3064 static char no_debug_usage[] = 
3065 "Usage: sip no debug\n"
3066 "       Disables dumping of SIP packets for debugging purposes\n";
3067
3068 static struct ast_cli_entry  cli_show_users = 
3069         { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
3070 static struct ast_cli_entry  cli_show_channels =
3071         { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage};
3072 static struct ast_cli_entry  cli_show_channel =
3073         { { "sip", "show", "channel", NULL }, sip_show_channel, "Show detailed SIP channel info", show_channel_usage, complete_sipch  };
3074 static struct ast_cli_entry  cli_show_peers =
3075         { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
3076 static struct ast_cli_entry  cli_show_registry =
3077         { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
3078 static struct ast_cli_entry  cli_debug =
3079         { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
3080 static struct ast_cli_entry  cli_no_debug =
3081         { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
3082
3083
3084 static int sip_poke_peer_s(void *data)
3085 {
3086         struct sip_peer *peer = data;
3087         peer->pokeexpire = -1;
3088         sip_poke_peer(peer);
3089         return 0;
3090 }
3091
3092 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req)
3093 {
3094         char *to;
3095         char *msg, *c;
3096         struct ast_rtp *rtp;
3097         struct ast_channel *owner;
3098         struct sip_peer *peer;
3099         int pingtime;
3100         struct timeval tv;
3101         c = get_header(req, "Cseq");
3102         msg = strchr(c, ' ');
3103         if (!msg) msg = ""; else msg++;
3104 retrylock:
3105         ast_pthread_mutex_lock(&p->lock);
3106         /* Go ahead and lock the owner if it has one -- we may need it */
3107         if (p->owner && pthread_mutex_trylock(&p->owner->lock)) {
3108                 ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
3109                 ast_pthread_mutex_unlock(&p->lock);
3110                 /* Sleep infintismly short amount of time */
3111                 usleep(1);
3112                 goto retrylock;
3113         }
3114         owner = p->owner;
3115         if (p->peerpoke) {
3116                 /* We don't really care what the response is, just that it replied back. 
3117                    Well, as long as it's not a 100 response...  since we might
3118                    need to hang around for something more "difinitive" */
3119                 if (resp != 100) {
3120                         peer = p->peerpoke;
3121                         gettimeofday(&tv, NULL);
3122                         pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
3123                          &n