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