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