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