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