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