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