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