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