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