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